> */ private const LOOKALIKES = [ 'order' => [ 'billing_email' => 'customer_email', 'billing_email_address' => 'customer_email', 'customer_email' => 'customer_email', 'email' => 'customer_email', 'email_address' => 'customer_email', 'guest_email' => 'customer_email', 'user_email' => 'customer_email', 'billing_phone' => 'customer_phone', 'billing_telephone' => 'customer_phone', 'customer_phone' => 'customer_phone', 'phone' => 'customer_phone', 'phone_number' => 'customer_phone', 'telephone' => 'customer_phone', 'shipping_phone' => 'shipping_phone', 'billing_first_name' => 'customer_name', 'billing_last_name' => 'customer_name', 'billing_full_name' => 'customer_name', 'billing_name' => 'customer_name', 'customer_name' => 'customer_name', 'first_name' => 'customer_name', 'full_name' => 'customer_name', 'last_name' => 'customer_name', 'billing_company' => 'billing_company', 'company' => 'billing_company', 'billing_address' => 'billing_address', 'billing_address_1' => 'billing_address', 'billing_address_2' => 'billing_address', 'billing_city' => 'billing_address', 'billing_postcode' => 'billing_address', 'billing_country' => 'billing_country', 'billing_state' => 'billing_state', 'shipping_first_name' => 'shipping_name', 'shipping_full_name' => 'shipping_name', 'shipping_last_name' => 'shipping_name', 'shipping_name' => 'shipping_name', 'shipping_address' => 'shipping_address', 'shipping_address_1' => 'shipping_address', 'shipping_address_2' => 'shipping_address', 'shipping_city' => 'shipping_address', 'shipping_postcode' => 'shipping_address', 'shipping_country' => 'shipping_country', 'shipping_state' => 'shipping_state', 'order_number' => 'order_number', 'order_number_formatted' => 'order_number', 'payment_method' => 'payment_method', 'payment_method_title' => 'payment_method', 'customer_note' => 'customer_note', 'order_comments' => 'customer_note', 'customer_user' => 'customer_id', 'customer_id' => 'customer_id', 'order_currency' => 'currency', 'order_total' => 'total', 'coupon_code' => 'coupons', ], 'item' => [ 'sku' => 'line_sku', 'product_sku' => 'line_sku', 'qty' => 'line_quantity', 'quantity' => 'line_quantity', 'product_name' => 'line_product', ], ]; /** * Column key for a meta key. * * @param string $meta_key Exact meta key. * @param string $scope 'order' or 'item'. */ public static function column( string $meta_key, string $scope = 'order' ): string { return ( 'item' === $scope ? self::ITEM : self::ORDER ) . $meta_key; } /** * Scope and meta key of a custom field column key, or null when the key * is not one or its meta key is not valid. * * @param mixed $key Column key. * @return array{0: string, 1: string}|null [ scope, meta key ]. */ public static function parse( mixed $key ): ?array { if ( ! is_string( $key ) ) { return null; } $prefixes = [ self::ORDER => 'order', self::ITEM => 'item', ]; foreach ( $prefixes as $prefix => $scope ) { if ( 0 === strncmp( $key, $prefix, strlen( $prefix ) ) ) { $meta_key = self::meta_key( substr( $key, strlen( $prefix ) ) ); return null === $meta_key ? null : [ $scope, $meta_key ]; } } return null; } /** * The meta key unchanged when it is one a store could have: valid UTF-8, * at most 255 bytes, not blank, no control characters. Otherwise null. * * @param mixed $meta_key Raw meta key. */ public static function meta_key( mixed $meta_key ): ?string { if ( ! is_string( $meta_key ) || '' === trim( $meta_key ) || strlen( $meta_key ) > self::MAX_KEY_BYTES ) { return null; } if ( 1 !== preg_match( '//u', $meta_key ) || 1 === preg_match( '/[\x00-\x1F\x7F]/', $meta_key ) ) { return null; } return $meta_key; } /** * Column name for a meta key: "_delivery_date" → "Delivery date". A * product attribute on a line ("pa_size") loses its "pa_" prefix; Fields * prefers the attribute's own name when WooCommerce knows it. The admin * app does the same (client/customFields.js), so a column restored before * the picker loads shows the same name. * * @param string $meta_key Meta key. * @param string $scope 'order' or 'item'. */ public static function label( string $meta_key, string $scope = 'order' ): string { $name = ltrim( $meta_key, '_' ); if ( 'item' === $scope && 0 === strncmp( $name, 'pa_', 3 ) ) { $name = substr( $name, 3 ); } $name = trim( (string) preg_replace( '/[\s_-]+/u', ' ', $name ) ); if ( '' === $name ) { return $meta_key; } return mb_strtoupper( mb_substr( $name, 0, 1 ) ) . mb_substr( $name, 1 ); } /** * A stored meta value as one cell. Lists are joined with ", ", keyed * arrays as "key: value"; nested arrays the same way, a few levels deep. * Objects have no text a merchant could use and are left empty. Strings * are written as stored: never unserialised again. * * @param mixed $value Meta value as WooCommerce returns it. * @param int $depth Nesting level (internal). */ public static function flatten( mixed $value, int $depth = 0 ): string { if ( is_bool( $value ) ) { return $value ? '1' : '0'; } if ( is_scalar( $value ) ) { return (string) $value; } if ( ! is_array( $value ) || $depth > 3 ) { return ''; } $list = array_keys( $value ) === array_keys( array_values( $value ) ); $parts = []; foreach ( $value as $key => $item ) { $text = self::flatten( $item, $depth + 1 ); if ( '' !== $text ) { $parts[] = $list ? $text : $key . ': ' . $text; } } return implode( ', ', $parts ); } /** * The built-in column a meta key duplicates, or null. * * @param string $meta_key Meta key. * @param string $scope 'order' or 'item'. */ public static function lookalike( string $meta_key, string $scope = 'order' ): ?string { $normal = (string) preg_replace( '/[\s-]+/', '_', strtolower( ltrim( trim( $meta_key ), '_' ) ) ); return self::LOOKALIKES[ 'item' === $scope ? 'item' : 'order' ][ $normal ] ?? null; } /** * Bookkeeping meta the picker leaves out (see HIDDEN). * * @param string $meta_key Meta key. */ public static function noise( string $meta_key ): bool { if ( in_array( $meta_key, self::HIDDEN, true ) ) { return true; } foreach ( self::HIDDEN_PREFIXES as $prefix ) { if ( 0 === strncmp( $meta_key, $prefix, strlen( $prefix ) ) ) { return true; } } return false; } /** * One cell for an order or a product line: every value stored under the * key, flattened and joined. Empty when the key isn't there. * * @param \WC_Data $data_object Order or order item. * @param string $meta_key Meta key. */ public static function value( \WC_Data $data_object, string $meta_key ): string { $parts = []; $raw = []; foreach ( $data_object->get_meta_data() as $meta ) { $data = $meta->get_data(); if ( (string) ( $data['key'] ?? '' ) !== $meta_key ) { continue; } $raw[] = $data['value'] ?? null; $text = self::flatten( self::attribute_term( $data_object, $meta_key, $data['value'] ?? null ) ); if ( '' !== $text ) { $parts[] = $text; } } /** * Filter one custom field cell, e.g. to write a timestamp as a date. * * @param string $value Cell text: the stored values flattened and joined with ", ". * @param array $raw Values as stored, one per meta entry with this key. * @param string $meta_key Meta key. * @param \WC_Data $data_object The order (\WC_Order) or product line (\WC_Order_Item_Product). */ return (string) apply_filters( 'modulary_export_meta_value', implode( ', ', $parts ), $raw, $meta_key, $data_object ); } /** * Column name for a meta key, using a product attribute's own name on * product lines ("pa_shoe-size" → "Shoe size" as the merchant named it). * * @param string $meta_key Meta key. * @param string $scope 'order' or 'item'. */ public static function column_label( string $meta_key, string $scope ): string { if ( 'item' === $scope && taxonomy_is_product_attribute( $meta_key ) ) { $name = trim( wp_strip_all_tags( wc_attribute_label( $meta_key ) ) ); if ( '' !== $name ) { return html_entity_decode( $name, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); } } return self::label( $meta_key, $scope ); } /** * Custom fields on the store's latest orders, for the "Add column" picker: * each key with a sample value, how many of the scanned orders have it, * and the built-in column it duplicates, if any. Most common first. * * Reads the newest orders through Query (wc_get_orders()), so both order * storages give the same answer. Nothing is cached or stored. * * @param int $limit Orders to scan (1 to MAX_SCAN). * @return array{orders: int, fields: array} */ public static function discover( int $limit = self::SCAN ): array { $limit = max( 1, min( self::MAX_SCAN, $limit ) ); $orders = ( new Query( new Filters() ) )->preview( $limit ); $found = []; foreach ( $orders as $order ) { $on_order = []; foreach ( $order->get_meta_data() as $meta ) { $on_order[ self::column( (string) ( $meta->get_data()['key'] ?? '' ) ) ] = $order; } $lines = 0; foreach ( $order->get_items() as $item ) { if ( ! $item instanceof \WC_Order_Item_Product ) { continue; } ++$lines; if ( $lines > self::SCAN_LINES ) { break; } foreach ( $item->get_meta_data() as $meta ) { $column = self::column( (string) ( $meta->get_data()['key'] ?? '' ), 'item' ); // The first line that has the key gives the sample, unless it is empty. if ( ! isset( $on_order[ $column ] ) || '' === self::sample( $on_order[ $column ], $column ) ) { $on_order[ $column ] = $item; } } } foreach ( $on_order as $column => $data_object ) { if ( ! isset( $found[ $column ] ) ) { if ( count( $found ) >= self::MAX_KEYS || ! self::listed( $column ) ) { continue; } $found[ $column ] = [ 'count' => 0, 'sample' => '', ]; } ++$found[ $column ]['count']; if ( '' === $found[ $column ]['sample'] ) { $found[ $column ]['sample'] = self::sample( $data_object, $column ); } } } $fields = []; foreach ( $found as $column => $seen ) { $parsed = self::parse( (string) $column ); $field = Fields::get( (string) $column ); if ( ! $parsed || ! $field ) { continue; } [ $scope, $meta_key ] = $parsed; // Only a column that exists (an add-on may remove one) can be suggested. $lookalike = null; $builtin = self::lookalike( $meta_key, $scope ); $suggested = null !== $builtin ? Fields::get( $builtin ) : null; if ( null !== $builtin && null !== $suggested ) { $lookalike = [ 'key' => $builtin, 'label' => (string) $suggested['label'], ]; } $fields[] = [ 'key' => (string) $column, 'meta' => $meta_key, 'scope' => $scope, 'label' => (string) $field['label'], 'group' => (string) $field['group'], 'sample' => $seen['sample'], 'count' => $seen['count'], 'lookalike' => $lookalike, ]; } usort( $fields, static fn( array $a, array $b ) => [ $b['count'], $b['scope'], strtolower( $a['meta'] ) ] <=> [ $a['count'], $a['scope'], strtolower( $b['meta'] ) ] ); return [ 'orders' => count( $orders ), 'fields' => $fields, ]; } /** * Whether the picker lists a key: valid, not bookkeeping, not hidden by * an add-on. * * @param string $column Column key. */ private static function listed( string $column ): bool { $parsed = self::parse( $column ); if ( ! $parsed ) { return false; } [ $scope, $meta_key ] = $parsed; /** * Filter whether the "Add column" picker offers a custom field. * * Hide an extension's internal meta (or show one we hide). Hidden keys * still export when a request asks for them. * * @param bool $show Default: false for WordPress / WooCommerce bookkeeping keys. * @param string $meta_key Meta key. * @param string $scope 'order' or 'item' (product line). */ return (bool) apply_filters( 'modulary_export_show_meta_key', ! self::noise( $meta_key ), $meta_key, $scope ); } /** * A short, one-line sample of a column's value for the picker. * * @param \WC_Data $data_object Order or product line. * @param string $column Column key. */ private static function sample( \WC_Data $data_object, string $column ): string { $parsed = self::parse( $column ); if ( ! $parsed ) { return ''; } $text = trim( (string) preg_replace( '/\s+/u', ' ', self::value( $data_object, $parsed[1] ) ) ); return mb_strlen( $text ) > self::SAMPLE_CHARS ? mb_substr( $text, 0, self::SAMPLE_CHARS - 1 ) . '…' : $text; } /** * A product attribute stored on a line is a term slug ("xl"); write the * term's name ("XL") the way the order screen shows it. * * @param \WC_Data $data_object Order or product line. * @param string $meta_key Meta key. * @param mixed $value Stored value. * @return mixed */ private static function attribute_term( \WC_Data $data_object, string $meta_key, mixed $value ): mixed { if ( ! $data_object instanceof \WC_Order_Item_Product || ! is_string( $value ) || '' === $value || ! taxonomy_is_product_attribute( $meta_key ) ) { return $value; } $term = get_term_by( 'slug', $value, $meta_key ); return $term instanceof \WP_Term ? html_entity_decode( $term->name, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) : $value; } }