inventory_id; } } $core = WPIMLend_Repo::get_core_items( $ids ); foreach ( $loans as $loan ) { foreach ( isset( $lines[ $loan->loan_id ] ) ? $lines[ $loan->loan_id ] : [] as $l ) { $c = isset( $core[ $l->inventory_id ] ) ? $core[ $l->inventory_id ] : NULL; $unit = $l->unit_id ? WPIMLend_Repo::get_unit( $l->unit_id ) : NULL; fputcsv( $out, array_map( [ __CLASS__, 'cell' ], [ $loan->loan_id, $loan->borrower_name, $loan->borrower_email, $loan->borrower_group, $c ? $c->inventory_number : '', $c ? $c->inventory_name : '(deleted)', $unit ? $unit->code : '', $l->quantity, (int) $l->quantity - (int) $l->returned_quantity, get_date_from_gmt( $loan->out_at, 'Y-m-d H:i' ), $loan->due_date, $loan->status, ] ) ); } } $offset += 500; } while ( count( $loans ) === 500 ); fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- closes the php://output stream opened above } /** * @param array|null $file An entry from $_FILES. * * @return array [ 'ok' => bool, 'message' => string ] */ public static function import_borrowers( $file ) { if ( empty( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) { return [ 'ok' => FALSE, 'message' => __( 'Choose a CSV file.', 'borrowdesk' ) ]; } $check = wp_check_filetype( $file['name'], [ 'csv' => 'text/csv', 'txt' => 'text/plain' ] ); if ( ! $check['ext'] ) { return [ 'ok' => FALSE, 'message' => __( 'That is not a CSV file.', 'borrowdesk' ) ]; } $handle = fopen( $file['tmp_name'], 'r' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- fgetcsv() over the uploaded temp file; WP_Filesystem has no CSV line reader if ( ! $handle ) { return [ 'ok' => FALSE, 'message' => __( 'The file could not be read.', 'borrowdesk' ) ]; } $added = 0; $skipped = 0; $row_no = 0; while ( ( $row = fgetcsv( $handle ) ) !== FALSE ) { $row_no ++; $row = array_map( 'trim', $row ); if ( 1 === $row_no && isset( $row[0] ) && 'name' === strtolower( preg_replace( '/^\xEF\xBB\xBF/', '', $row[0] ) ) ) { continue; // header } $name = sanitize_text_field( $row[0] ?? '' ); if ( '' === $name ) { $skipped ++; continue; } $email = sanitize_email( $row[1] ?? '' ); if ( $email && WPIMLend_Repo::find_borrower_by_email( $email ) ) { $skipped ++; continue; } $id = WPIMLend_Repo::save_borrower( [ 'name' => $name, 'email' => $email, 'phone' => sanitize_text_field( $row[2] ?? '' ), 'borrower_group' => sanitize_text_field( $row[3] ?? '' ), 'notes' => sanitize_textarea_field( $row[4] ?? '' ), 'user_id' => 0, ] ); $id ? $added ++ : $skipped ++; } fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- closes the uploaded temp file opened above return [ 'ok' => TRUE, /* translators: 1: added, 2: skipped */ 'message' => sprintf( __( 'Imported %1$d borrowers, skipped %2$d.', 'borrowdesk' ), $added, $skipped ), ]; } }