$def ) { $cols[ $key ] = $def['label']; } foreach ( Nodebook_Props::defs( 'contact' ) as $key => $def ) { $cols[ $key ] = $def['label']; } $cols['email_status'] = __( 'Email consent', 'nodebook' ); $cols['segments'] = __( 'Static segments', 'nodebook' ); $cols['custom_fields'] = __( 'Custom fields (JSON)', 'nodebook' ); $cols['id'] = 'ID'; return $cols; } public static function company_columns() { $cols = array(); foreach ( Nodebook_Fields::company() as $key => $def ) { $cols[ $key ] = $def['label']; } foreach ( Nodebook_Props::defs( 'company' ) as $key => $def ) { $cols[ $key ] = $def['label']; } $cols['contacts'] = __( 'Contacts', 'nodebook' ); $cols['id'] = 'ID'; return $cols; } /** Neutralise spreadsheet formula injection. */ public static function cell( $v ) { $v = (string) $v; if ( '' !== $v && in_array( $v[0], array( '=', '+', '-', '@', "\t", "\r" ), true ) && ! is_numeric( $v ) ) { $v = "'" . $v; } return $v; } private static function start( $filename ) { nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $filename ) . '"' ); $out = fopen( 'php://output', 'w' ); fwrite( $out, "\xEF\xBB\xBF" ); // UTF-8 BOM so Excel reads accents correctly. return $out; } /** * @param array $args segment, status, search, ids. */ public static function export_contacts( array $args ) { $cols = self::contact_columns(); $out = self::start( 'nodebook-contacts-' . gmdate( 'Y-m-d' ) . '.csv' ); fputcsv( $out, array_values( $cols ) ); $page = 1; do { $r = Nodebook_Contacts::query( array_merge( $args, array( 'per_page' => 500, 'page' => $page, 'orderby' => 'created_at', 'order' => 'ASC' ) ) ); $vals = Nodebook_Props::values_for( 'contact', wp_list_pluck( $r['rows'], 'id' ) ); foreach ( $r['rows'] as $c ) { $line = array(); foreach ( array_keys( $cols ) as $key ) { if ( Nodebook_Props::is_key( $key ) ) { $line[] = $vals[ (int) $c['id'] ][ $key ] ?? ''; } elseif ( 'custom_fields' === $key ) { $line[] = $c['meta'] ? wp_json_encode( $c['meta'], JSON_UNESCAPED_UNICODE ) : ''; } elseif ( 'segments' === $key ) { $line[] = implode( '; ', wp_list_pluck( Nodebook_Segments::for_contact( $c['id'] ), 'name' ) ); } else { $line[] = isset( $c[ $key ] ) ? $c[ $key ] : ''; } } fputcsv( $out, array_map( array( __CLASS__, 'cell' ), $line ) ); } ++$page; } while ( count( $r['rows'] ) === 500 ); fclose( $out ); exit; } public static function export_companies( array $args ) { $cols = self::company_columns(); $out = self::start( 'nodebook-companies-' . gmdate( 'Y-m-d' ) . '.csv' ); fputcsv( $out, array_values( $cols ) ); $page = 1; do { $r = Nodebook_Companies::query( array_merge( $args, array( 'per_page' => 500, 'page' => $page ) ) ); $vals = Nodebook_Props::values_for( 'company', wp_list_pluck( $r['rows'], 'id' ) ); foreach ( $r['rows'] as $co ) { $line = array(); foreach ( array_keys( $cols ) as $key ) { $line[] = Nodebook_Props::is_key( $key ) ? ( $vals[ (int) $co['id'] ][ $key ] ?? '' ) : ( isset( $co[ $key ] ) ? $co[ $key ] : '' ); } fputcsv( $out, array_map( array( __CLASS__, 'cell' ), $line ) ); } ++$page; } while ( count( $r['rows'] ) === 500 ); fclose( $out ); exit; } /** Deals (open, won and lost) with their contact, company and deal fields. */ public static function export_deals( array $args ) { $defs = Nodebook_Props::defs( 'deal' ); $team = Nodebook_Team::users(); $out = self::start( 'nodebook-deals-' . gmdate( 'Y-m-d' ) . '.csv' ); fputcsv( $out, array_merge( array( 'id', 'title', 'stage', 'outcome', 'lost_reason', 'value', 'currency', 'expected_close', 'contact_email', 'contact_name', 'company', 'owner', 'source', 'created_at_utc', 'closed_at_utc', 'notes' ), wp_list_pluck( $defs, 'label' ) ) ); $rows = Nodebook_Deals::query( array( 'outcome' => 'all', 'order' => 'created', 'limit' => 100000, ) ); foreach ( array_chunk( $rows, 500 ) as $chunk ) { $vals = Nodebook_Props::values_for( 'deal', wp_list_pluck( $chunk, 'id' ) ); foreach ( $chunk as $d ) { $line = array( $d['id'], $d['title'], '' === $d['outcome'] ? Nodebook_Deals::stage_name( $d ) : '', '' === $d['outcome'] ? 'open' : $d['outcome'], $d['lost_reason'], $d['value'], $d['currency'], (string) $d['expected_close'], (string) $d['email'], $d['contact_id'] ? trim( $d['first_name'] . ' ' . $d['last_name'] ) : '', (string) $d['company'], $d['owner_id'] ? ( $team[ (int) $d['owner_id'] ] ?? '' ) : '', $d['source'], $d['created_at'], (string) $d['closed_at'], (string) $d['notes'], ); foreach ( array_keys( $defs ) as $k ) { $line[] = $vals[ (int) $d['id'] ][ $k ] ?? ''; } fputcsv( $out, array_map( array( __CLASS__, 'cell' ), $line ) ); } } fclose( $out ); exit; } public static function export_activities( array $args ) { global $wpdb; $out = self::start( 'nodebook-activities-' . gmdate( 'Y-m-d' ) . '.csv' ); fputcsv( $out, array( 'contact_email', 'contact_id', 'type', 'title', 'url', 'created_at_utc', 'data' ) ); $last = 0; do { list( $restricted, $me, $unassigned ) = Nodebook_Team::scope_args(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- streaming export from plugin tables. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT a.*, c.email FROM %i a INNER JOIN %i c ON c.id = a.contact_id WHERE a.id > %d AND ( %d = 0 OR c.owner_id = %d OR ( %d = 1 AND c.owner_id = 0 ) ) ORDER BY a.id ASC LIMIT 1000', Nodebook_Activities::table(), Nodebook_Contacts::table(), $last, $restricted, $me, $unassigned ), ARRAY_A ); foreach ( $rows as $a ) { $last = (int) $a['id']; fputcsv( $out, array_map( array( __CLASS__, 'cell' ), array( $a['email'], $a['contact_id'], $a['type'], $a['title'], $a['url'], $a['created_at'], $a['data'] ) ) ); } } while ( count( $rows ) === 1000 ); fclose( $out ); exit; } /* ------------------------------------------------------------------ * * Import * ------------------------------------------------------------------ */ private static function dir() { $up = wp_upload_dir(); $dir = trailingslashit( $up['basedir'] ) . 'nodebook-imports'; if ( ! is_dir( $dir ) ) { wp_mkdir_p( $dir ); } if ( ! file_exists( $dir . '/index.php' ) ) { file_put_contents( $dir . '/index.php', " false, 'mimes' => array( 'csv' => 'text/csv', 'txt' => 'text/plain', ), 'unique_filename_callback' => static function () use ( $token ) { return $token . '.csv'; }, ) ); remove_filter( 'upload_dir', $to_dir ); if ( empty( $moved['file'] ) || ! empty( $moved['error'] ) ) { return new WP_Error( 'move', __( 'The file could not be stored. Please upload a .csv file.', 'nodebook' ) ); } $dest = $moved['file']; $fh = fopen( $dest, 'r' ); if ( ! $fh ) { return new WP_Error( 'read', __( 'The file could not be read.', 'nodebook' ) ); } $first = (string) fgets( $fh ); $first = preg_replace( '/^\xEF\xBB\xBF/', '', $first ); $delim = self::delimiter( $first ); rewind( $fh ); $bom = fread( $fh, 3 ); if ( "\xEF\xBB\xBF" !== $bom ) { rewind( $fh ); } $headers = fgetcsv( $fh, 0, $delim ); $offset = ftell( $fh ); fclose( $fh ); if ( ! $headers || count( array_filter( $headers, 'strlen' ) ) === 0 ) { wp_delete_file( $dest ); return new WP_Error( 'empty', __( 'The file has no header row.', 'nodebook' ) ); } $headers = array_map( static function ( $h ) { return mb_substr( sanitize_text_field( (string) $h ), 0, 190 ); }, $headers ); self::save_job( $token, array( 'user' => get_current_user_id(), 'entity' => 'companies' === $entity ? 'companies' : 'contacts', 'file' => $dest, 'name' => sanitize_file_name( (string) $file['name'] ), 'delim' => $delim, 'headers' => $headers, 'offset' => $offset, 'start' => $offset, 'size' => filesize( $dest ), 'map' => array(), 'options' => array(), 'stats' => array( 'created' => 0, 'updated' => 0, 'skipped' => 0, 'rows' => 0, ), ) ); return $token; } public static function delimiter( $line ) { $best = ','; $max = 0; foreach ( array( ',', ';', "\t", '|' ) as $d ) { $n = substr_count( $line, $d ); if ( $n > $max ) { $max = $n; $best = $d; } } return $best; } /** * Suggest a target field for each CSV header. */ public static function guess_map( array $headers, $entity ) { $targets = 'companies' === $entity ? Nodebook_Fields::company() : Nodebook_Fields::contact(); $map = array(); foreach ( $headers as $i => $h ) { $norm = strtolower( trim( preg_replace( '/[^a-z0-9]+/i', '_', $h ), '_' ) ); $hit = ''; foreach ( $targets as $key => $def ) { if ( ! empty( $def['readonly'] ) && 'created_at' !== $key ) { continue; } if ( $norm === $key || strtolower( $def['label'] ) === strtolower( trim( $h ) ) ) { $hit = $key; break; } } if ( ! $hit && 'contacts' === $entity && preg_match( '/^(email_?(status|consent)|e_?mail_consent|subscription(_status)?|subscribed|subscriber_status|newsletter|marketing(_consent|_status)?|accepts_marketing|opt_?in|email_marketing)$/', $norm ) ) { $hit = 'email_status'; } if ( ! $hit && 'contacts' === $entity ) { $g = Nodebook_Fields::guess( $h ); $hit = in_array( $g, array( '', 'skip', 'message' ), true ) ? '' : $g; if ( 'name' === $hit ) { $hit = 'full_name'; } if ( 'segments' === $norm || 'static_segments' === $norm ) { $hit = 'segments'; } if ( 'custom_fields_json' === $norm ) { $hit = 'custom_fields'; } } if ( ! $hit && 'companies' === $entity && preg_match( '/company|organi[sz]ation|bedrijf|empresa/i', $h ) ) { $hit = 'name'; } if ( 'id' === $norm ) { $hit = ''; } if ( ! $hit || '__meta' === $hit ) { $prop = Nodebook_Props::match( 'companies' === $entity ? 'company' : 'contact', $h ); $hit = $prop ? $prop : $hit; } $map[ $i ] = $hit ? $hit : '__meta'; } return $map; } /** * Process the next batch. Returns the job's stats plus progress. */ public static function process( $token ) { $job = self::get_job( $token ); if ( ! $job || ! file_exists( $job['file'] ) ) { return new WP_Error( 'job', __( 'This import has expired. Please upload the file again.', 'nodebook' ) ); } $fh = fopen( $job['file'], 'r' ); fseek( $fh, (int) $job['offset'] ); $n = 0; $opts = $job['options']; $headers = $job['headers']; while ( $n < self::BATCH && ( $row = fgetcsv( $fh, 0, $job['delim'] ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition ++$n; ++$job['stats']['rows']; if ( array( null ) === $row || ! array_filter( $row, 'strlen' ) ) { continue; } $data = array(); $meta = array(); $props = array(); $segments = array(); $consent = null; foreach ( $row as $i => $value ) { $value = trim( (string) $value ); $target = isset( $job['map'][ $i ] ) ? $job['map'][ $i ] : '__skip'; if ( '' === $value || '__skip' === $target ) { continue; } // Undo our own formula-injection guard on round trips. if ( "'" === $value[0] && isset( $value[1] ) && in_array( $value[1], array( '=', '+', '-', '@' ), true ) ) { $value = substr( $value, 1 ); } if ( Nodebook_Props::is_key( $target ) ) { $props[ $target ] = $value; } elseif ( '__meta' === $target ) { $meta[ isset( $headers[ $i ] ) ? $headers[ $i ] : 'Column ' . ( $i + 1 ) ] = $value; } elseif ( 'custom_fields' === $target ) { $decoded = json_decode( $value, true ); if ( is_array( $decoded ) ) { $meta = array_merge( $meta, $decoded ); } } elseif ( 'email_status' === $target ) { $consent = Nodebook_Subscription::normalize( 'Not asked' === $value ? '' : $value ); } elseif ( 'segments' === $target ) { $segments = array_merge( $segments, array_filter( array_map( 'trim', preg_split( '/[;|]/', $value ) ) ) ); } elseif ( 'full_name' === $target ) { $parts = preg_split( '/\s+/', $value, 2 ); $data['first_name'] = $data['first_name'] ?? $parts[0]; $data['last_name'] = $data['last_name'] ?? ( $parts[1] ?? '' ); } else { $data[ $target ] = $value; } } if ( $meta ) { list( $more, $meta ) = Nodebook_Props::split_meta( 'companies' === $job['entity'] ? 'company' : 'contact', $meta ); $props += $more; if ( $meta ) { $data['meta'] = $meta; } } if ( 'companies' === $job['entity'] ) { if ( empty( $data['name'] ) && empty( $data['domain'] ) ) { ++$job['stats']['skipped']; continue; } unset( $data['created_at'] ); $r = Nodebook_Companies::upsert( $data, ! empty( $opts['update'] ) ? 'overwrite' : 'fill' ); } else { if ( empty( $data['email'] ) && empty( $data['phone'] ) ) { ++$job['stats']['skipped']; continue; } unset( $data['created_at'], $data['orders_count'], $data['total_spent'], $data['visits_count'], $data['first_seen'], $data['last_seen'] ); if ( empty( $data['status'] ) && ! empty( $opts['status'] ) ) { $data['status'] = $opts['status']; } elseif ( ! empty( $data['status'] ) ) { $data['status'] = self::status_slug( $data['status'] ); } if ( empty( $data['source'] ) ) { /* translators: %s: file name */ $data['source'] = sprintf( __( 'CSV import (%s)', 'nodebook' ), $job['name'] ); } if ( isset( $data['email'] ) && ! is_email( $data['email'] ) ) { unset( $data['email'] ); if ( empty( $data['phone'] ) ) { ++$job['stats']['skipped']; continue; } } $exists = ! empty( $data['email'] ) ? Nodebook_Contacts::find_by_email( $data['email'] ) : null; if ( $exists && empty( $opts['update'] ) ) { $r = array( 'id' => $exists['id'], 'created' => false, 'untouched' => true ); } else { $r = Nodebook_Contacts::upsert( $data, 'overwrite' ); } if ( $r['id'] ) { if ( $r['created'] ) { Nodebook_Activities::add( $r['id'], 'import', sprintf( /* translators: %s: file name */ __( 'Imported from %s', 'nodebook' ), $job['name'] ) ); } if ( ! empty( $opts['segment'] ) ) { Nodebook_Segments::add_contacts( (int) $opts['segment'], array( $r['id'] ) ); } foreach ( $segments as $seg_name ) { Nodebook_Segments::add_contacts( self::static_segment_id( $seg_name ), array( $r['id'] ) ); } // A CSV is a record from another system, not a fresh opt-in: an unsubscribe there is respected, // but it cannot re-subscribe someone who unsubscribed here (see Nodebook_Subscription::set()). // An opt-out list is applied even when existing contacts are otherwise left as they are. if ( null !== $consent && '' !== $consent && ( empty( $r['untouched'] ) || in_array( $consent, array( 'unsubscribed', 'bounced', 'complained' ), true ) ) ) { Nodebook_Subscription::set( $r['id'], $consent, array( /* translators: %s: file name */ 'source' => sprintf( __( 'CSV import (%s)', 'nodebook' ), $job['name'] ), ) ); } } } if ( ! empty( $r['id'] ) && $props && empty( $r['untouched'] ) ) { Nodebook_Props::set( 'companies' === $job['entity'] ? 'company' : 'contact', (int) $r['id'], $props, 'overwrite_nonempty' ); } if ( empty( $r['id'] ) ) { ++$job['stats']['skipped']; } elseif ( ! empty( $r['untouched'] ) ) { ++$job['stats']['skipped']; } elseif ( $r['created'] ) { ++$job['stats']['created']; } else { ++$job['stats']['updated']; } } $job['offset'] = ftell( $fh ); $done = feof( $fh ) || 0 === $n; fclose( $fh ); self::save_job( $token, $job ); $span = max( 1, (int) $job['size'] - (int) $job['start'] ); $progress = $done ? 100 : min( 99, (int) floor( ( (int) $job['offset'] - (int) $job['start'] ) / $span * 100 ) ); if ( $done ) { self::delete_job( $token ); } return array_merge( $job['stats'], array( 'done' => $done, 'progress' => $progress, ) ); } private static function status_slug( $value ) { $value = strtolower( trim( $value ) ); foreach ( Nodebook_Fields::statuses() as $slug => $label ) { if ( $value === $slug || strtolower( $label ) === $value ) { return $slug; } } return ''; } private static $segment_cache = array(); private static function static_segment_id( $name ) { $key = strtolower( $name ); if ( isset( self::$segment_cache[ $key ] ) ) { return self::$segment_cache[ $key ]; } foreach ( Nodebook_Segments::all( 'static' ) as $s ) { if ( strtolower( $s['name'] ) === $key ) { self::$segment_cache[ $key ] = (int) $s['id']; return (int) $s['id']; } } $id = Nodebook_Segments::save( array( 'name' => $name, 'type' => 'static', ) ); self::$segment_cache[ $key ] = $id; return $id; } }