| @@ -57,20 +57,31 @@ | ||
| 57 | 57 | } |
| 58 | 58 | |
| 59 | 59 | $fileContent = str_replace( [ "\r\n", "\r" ], "\n", $fileContent ); |
| 60 | 60 | |
| 61 | + // Parse through a stream so fgetcsv() correctly assembles records whose | |
| 62 | + // quoted fields span multiple lines (e.g. multi-line doc content). A plain | |
| 63 | + // explode( "\n" ) + str_getcsv() per line splits such records apart, producing | |
| 64 | + // rows whose column count no longer matches the headers — which makes the | |
| 65 | + // array_combine() calls below fatal (500 error on Sample Docs import). | |
| 66 | + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- in-memory stream, no filesystem access; required for multi-line CSV records. | |
| 61 | 67 | $handle = fopen( 'php://temp', 'r+' ); |
| 62 | - fwrite( $handle, $fileContent ); | |
| 63 | - rewind( $handle ); | |
| 64 | - | |
| 65 | 68 | if ( $handle !== false ) { |
| 66 | - while ( ( $row = fgetcsv( $handle, 1000, ',' ) ) !== false ) { | |
| 69 | + fwrite( $handle, $fileContent ); | |
| 70 | + rewind( $handle ); | |
| 71 | + while ( ( $row = fgetcsv( $handle, 0, ',' ) ) !== false ) { | |
| 67 | 72 | $csv_data[] = $row; |
| 68 | 73 | } |
| 74 | + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- closing in-memory stream; WP_Filesystem does not apply. | |
| 69 | 75 | fclose( $handle ); |
| 70 | 76 | } |
| 71 | 77 | |
| 72 | 78 | $headers = array_shift( $csv_data ); |
| 79 | + | |
| 80 | + // Bail out cleanly on an empty/malformed file instead of fataling below. | |
| 81 | + if ( ! is_array( $headers ) || empty( $headers ) ) { | |
| 82 | + return $data; | |
| 83 | + } | |
| 73 | 84 | |
| 74 | 85 | // Process specific headers for 'Docs Title' |
| 75 | 86 | if ( $headers[0] == 'Docs Title' ) { |
| 76 | 87 | $replacementMap = [ 'Docs Slug' => 'post_name' ]; |