'; const ICON_PHONE = ''; /** * Hooks the handler. * * @return void */ public static function register() { add_action( 'admin_post_' . self::ACTION, array( __CLASS__, 'handle' ) ); } /** * URL that prints the given AWBs. * * @param string[] $awbs AWBs. * @return string */ public static function url( array $awbs ) { $list = implode( ',', $awbs ); return wp_nonce_url( add_query_arg( array( 'action' => self::ACTION, 'awbs' => rawurlencode( $list ), ), admin_url( 'admin-post.php' ) ), self::selection_action( $list, 0 ) ); } /** * Nonce action bound to one exact selection, so a print link cannot be reused for other shipments. * * @param string $awbs Comma-separated AWBs as in the URL. * @param int $batch Batch ID, or 0. * @return string */ private static function selection_action( $awbs, $batch ) { return self::ACTION . '|' . md5( $awbs . '|' . (int) $batch ); } /** * URL that prints a whole batch. * * @param int $batch Batch (shipment header) ID. * @return string */ public static function batch_url( $batch ) { return wp_nonce_url( add_query_arg( array( 'action' => self::ACTION, 'batch' => (int) $batch, ), admin_url( 'admin-post.php' ) ), self::selection_action( '', $batch ) ); } /** * AWBs requested: `awbs` (comma-separated or array), or a `batch` to expand. * * @param AbsClient $client Client. * @return string[] * @throws AbsError When the batch cannot be listed. */ public static function requested_awbs( AbsClient $client ) { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Verified in handle(). $raw = isset( $_GET['awbs'] ) ? wp_unslash( $_GET['awbs'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. $awbs = is_array( $raw ) ? $raw : explode( ',', (string) $raw ); $awbs = array_values( array_unique( array_filter( array_map( 'sanitize_text_field', array_map( 'trim', array_map( 'strval', $awbs ) ) ) ) ) ); $batch = isset( $_GET['batch'] ) ? absint( $_GET['batch'] ) : 0; // phpcs:enable if ( $batch > 0 ) { $page = 1; do { $data = $client->post( 'shipments/list', array( 'shipmentHeaderIds' => array( $batch ), 'columns' => array( 'awb' ), 'page' => $page, 'limit' => self::MAX_AWBS, ) ); foreach ( isset( $data['data'] ) && is_array( $data['data'] ) ? $data['data'] : array() as $row ) { if ( ! empty( $row['awb'] ) ) { $awbs[] = (string) $row['awb']; } } ++$page; $enough = count( $awbs ) >= self::MAX_AWBS; } while ( ! empty( $data['hasMore'] ) && ! $enough ); } return array_slice( array_values( array_unique( $awbs ) ), 0, self::MAX_AWBS ); } /** * Outputs the print page. * * @return void */ public static function handle() { // A link signed for its exact selection (order screen, orders list, batches) may be used by // anyone who can edit orders. Free selections from the Shipments tab carry the generic nonce // and need the same capability as that tab. // phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput -- This is the nonce check. $nonce = isset( $_GET['_wpnonce'] ) ? sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ) : ''; $list = isset( $_GET['awbs'] ) && is_string( $_GET['awbs'] ) ? sanitize_text_field( wp_unslash( $_GET['awbs'] ) ) : ''; $batch = isset( $_GET['batch'] ) ? absint( $_GET['batch'] ) : 0; // phpcs:enable $signed = false !== wp_verify_nonce( $nonce, self::selection_action( $list, $batch ) ); $free = ! $signed && false !== wp_verify_nonce( $nonce, self::ACTION ); if ( ! ( $signed && current_user_can( OrderActions::CAPABILITY ) ) && ! ( $free && current_user_can( Menu::CAPABILITY ) ) ) { wp_die( esc_html__( 'This print link is not valid for you. Open it again from WooCommerce.', 'abs-courier' ), '', array( 'response' => 403 ) ); } $client = new AbsClient( Credentials::get() ); try { $awbs = self::requested_awbs( $client ); if ( empty( $awbs ) ) { wp_die( esc_html__( 'Choose at least one shipment to print.', 'abs-courier' ) ); } $data = $client->get( 'shipments/get-printable-awbs', array( 'awbs' => implode( ',', $awbs ), 'lang' => 'en', ) ); } catch ( AbsError $e ) { wp_die( esc_html( $e->getMessage() ) ); } $rows = isset( $data['data'] ) && is_array( $data['data'] ) ? $data['data'] : array(); if ( empty( $rows ) ) { wp_die( esc_html__( 'ABS Courier returned no printable waybills for this selection.', 'abs-courier' ) ); } nocache_headers(); self::render( $rows ); exit; } /** * Prints the HTML document. * * @param array $rows Printable rows from ABS. * @return void */ public static function render( array $rows ) { wp_register_script( 'abs-courier-jsbarcode', plugins_url( 'assets/vendor/jsbarcode/JsBarcode.all.js', ABS_COURIER_FILE ), array(), '3.12.3', false ); wp_register_script( 'abs-courier-qrcode', plugins_url( 'assets/vendor/qrcode-generator/qrcode.js', ABS_COURIER_FILE ), array(), '2.0.4', false ); wp_register_script( 'abs-courier-print', plugins_url( 'assets/admin/print.js', ABS_COURIER_FILE ), array( 'abs-courier-jsbarcode', 'abs-courier-qrcode' ), ABS_COURIER_VERSION, true ); wp_register_style( 'abs-courier-print', plugins_url( 'assets/admin/print.css', ABS_COURIER_FILE ), array(), ABS_COURIER_VERSION ); // Standalone document (no admin chrome), so wp_head()/wp_footer() never run: print the // registered assets directly. echo '' . esc_html__( 'ABS Courier waybills', 'abs-courier' ) . ''; wp_print_styles( array( 'abs-courier-print' ) ); wp_print_scripts( array( 'abs-courier-jsbarcode', 'abs-courier-qrcode' ) ); echo ''; printf( '
%2$s
', esc_html__( 'Print', 'abs-courier' ), esc_html( sprintf( /* translators: %d: number of waybills. */ _n( '%d waybill', '%d waybills', count( $rows ), 'abs-courier' ), count( $rows ) ) ) ); foreach ( array_chunk( $rows, 2 ) as $pair ) { echo '
'; foreach ( $pair as $row ) { self::waybill( (array) $row ); } echo '
'; } wp_print_scripts( array( 'abs-courier-print' ) ); echo ''; } /** * One waybill. * * @param array $row Printable row. * @return void */ private static function waybill( array $row ) { $bucket = static function ( $key ) use ( $row ) { return isset( $row[ $key ] ) && is_array( $row[ $key ] ) ? $row[ $key ] : array(); }; $header = $bucket( 'header' ); $account = $bucket( 'accountDetails' ); $consign = $bucket( 'consigneeDetails' ); $shipment = $bucket( 'shipmentDetails' ); $others = $bucket( 'others' ); $v = array( __CLASS__, 'text' ); $dash = static function ( $value ) { return '' !== $value ? $value : '-'; }; $awb = $v( $header, 'awb' ); $carrier = ! isset( $row['printsCarrierIdentity'] ) || false !== $row['printsCarrierIdentity']; $cash = '' !== $v( $consign, 'cash' ) ? $v( $consign, 'cash' ) : $v( $others, 'cash' ); $runner = $v( $shipment, 'runnerCode' ); $branch = array_key_exists( 'deliveryBranch', $others ) ? $dash( self::strip_zeros( $v( $others, 'deliveryBranch' ) ) ) : null; $main_acc = isset( $account['mainAccount'] ) && is_array( $account['mainAccount'] ) ? $account['mainAccount'] : array(); $row_main = isset( $row['mainAccount'] ) && is_array( $row['mainAccount'] ) ? $row['mainAccount'] : array(); $acct_no = ''; foreach ( array( $account, $main_acc, $row_main, $others ) as $source ) { if ( '' !== $v( $source, 'accountNumber' ) ) { $acct_no = $v( $source, 'accountNumber' ); break; } } $main = is_array( $account['mainAccount'] ?? null ) ? $v( $main_acc, 'name' ) : $v( $account, 'mainAccount' ); $dates = array_filter( array( __( 'Creation Date', 'abs-courier' ) => self::awb_date( $v( $header, 'creationDate' ) ), __( 'End Date', 'abs-courier' ) => self::awb_date( $v( $header, 'endDate' ) ), ) ); $weight = '' !== $v( $shipment, 'weight' ) ? self::strip_zeros( $v( $shipment, 'weight' ) . ' Kg' ) : ''; $pieces = (int) $v( $shipment, 'pieces' ); $opens = false; foreach ( isset( $shipment['extraServices'] ) && is_array( $shipment['extraServices'] ) ? $shipment['extraServices'] : array() as $service ) { $opens = $opens || self::is_open_shipment_service( self::label( $service ) ); } echo '
'; // Header: logo | QR + barcode | dates. echo '
'; printf( '
', esc_attr( '' !== $awb ? $awb : ( $carrier ? self::WEBSITE : '' ) ) ); printf( '
%1$s
', esc_attr( $awb ) ); echo '
'; if ( $dates ) { echo '
'; foreach ( $dates as $label => $value ) { printf( '
%1$s%2$s
', esc_html( $label ), esc_html( $value ) ); } echo '
'; } echo '
'; // Pickup and delivery cards. echo '
'; printf( '%s', esc_html__( 'Pickup Details', 'abs-courier' ) ); if ( '' !== $v( $account, 'returnBranch' ) ) { printf( '%s', esc_html( preg_replace( '/ Hub\b/', "\u{00A0}Hub", $v( $account, 'returnBranch' ) ) ) ); } echo '
'; self::field( __( 'Main', 'abs-courier' ), $dash( $main ) . ( '' !== $acct_no ? ' - ' . $acct_no : '' ) ); self::field( __( 'Sub', 'abs-courier' ), $dash( $v( $account, 'subAccount' ) ) ); self::field( __( 'Name', 'abs-courier' ), $dash( $v( $account, 'name' ) ) ); self::field( __( 'Phone', 'abs-courier' ), $dash( self::phones( $account['phone'] ?? '' ) ) ); self::field( __( 'Address', 'abs-courier' ), $dash( $v( $account, 'returnAddress' ) ) ); echo '
'; echo '
'; printf( '%s', esc_html__( 'Delivery Details', 'abs-courier' ) ); echo '
'; if ( '' !== $cash ) { printf( '
%1$s EGP
', esc_html( self::amount( $cash ) ) ); } echo '
'; $phone = ( isset( $consign['phone'] ) && '' !== $consign['phone'] ) ? $consign['phone'] : ( $consign['phones'] ?? '' ); self::field( __( 'Ref', 'abs-courier' ), $dash( $v( $consign, 'ref' ) ) ); self::field( __( 'Name', 'abs-courier' ), $dash( $v( $consign, 'name' ) ) ); self::field( __( 'Extra Consignees', 'abs-courier' ), $dash( self::extra_consignees( $consign['extraConsignees'] ?? ( $consign['extra_consignees'] ?? ( $others['extraConsignees'] ?? '' ) ) ) ) ); self::field( __( 'Phone', 'abs-courier' ), $dash( self::phones( $phone ) ) ); self::field( __( 'Address', 'abs-courier' ), $dash( $v( $consign, 'address' ) ) ); self::field( __( 'New Address', 'abs-courier' ), $dash( $v( $consign, 'newaddress' ) ) ); self::field( __( 'City', 'abs-courier' ), $v( $consign, 'city' ), true ); echo '
'; // Content strip with the open-shipment note, runner code and delivery branch. echo '
'; self::field( __( 'Content', 'abs-courier' ), $dash( $v( $shipment, 'content' ) ) ); self::field( __( 'Inst', 'abs-courier' ), $dash( $v( $shipment, 'specialInstruction' ) ) ); echo '
'; self::field( __( 'Product', 'abs-courier' ), $dash( $v( $shipment, 'product' ) ) ); self::field( __( 'Service', 'abs-courier' ), $dash( $v( $shipment, 'serviceName' ) ) ); /* translators: %d: number of pieces. */ echo $pieces > 0 ? '' . esc_html( sprintf( __( '%d Pieces', 'abs-courier' ), $pieces ) ) . '' : '-'; echo '' !== $weight ? '' . esc_html( $weight ) . '' : '-'; echo '
'; printf( '
%s
', esc_html( $opens ? 'يسمح بفتح الشحنة' : 'لا يسمح بفتح الشحنة' ) ); if ( '' !== $runner || null !== $branch ) { echo '
'; if ( '' !== $runner ) { printf( '
%2$s
', null !== $branch ? '' : ' last', esc_html( $runner ) ); } if ( null !== $branch ) { printf( '
%2$s
', '' !== $runner ? '' : ' alone', esc_html( $branch ) ); } echo '
'; } echo '
'; if ( $carrier ) { printf( '
%1$s%2$s%3$sHot line : %4$s
', self::ICON_GLOBE, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG. esc_html( self::WEBSITE ), self::ICON_PHONE, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG. esc_html( self::HOTLINE ) ); } echo '
'; } /** * One "Label: value" line. * * @param string $label Label. * @param string $value Value (already defaulted to "-" where needed). * @param bool $chip Show a non-empty value as a chip. * @return void */ private static function field( $label, $value, $chip = false ) { $shown = $chip && '' !== $value ? '' . esc_html( $value ) . '' : '' . esc_html( '' !== $value ? $value : '-' ) . ''; printf( '
%1$s: %2$s
', esc_html( $label ), $shown ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped above. } /** * Scalar value of a key, trimmed; '' when missing or not scalar. * * @param array $from Source. * @param string $key Key. * @return string */ private static function text( array $from, $key ) { $value = isset( $from[ $key ] ) && is_scalar( $from[ $key ] ) ? trim( (string) $from[ $key ] ) : ''; return in_array( $value, array( 'null', 'undefined' ), true ) ? '' : $value; } /** * Up to two phone numbers, without the leading "+2", comma separated. * * @param mixed $value Phone string or list. * @return string */ private static function phones( $value ) { $list = is_array( $value ) ? $value : preg_split( '/[,،\n\r-]+/u', is_scalar( $value ) ? (string) $value : '' ); $list = array_map( static function ( $phone ) { $phone = trim( is_scalar( $phone ) ? (string) $phone : '' ); return 0 === strpos( $phone, '+2' ) ? substr( $phone, 2 ) : $phone; }, (array) $list ); return implode( ', ', array_slice( array_values( array_filter( $list, 'strlen' ) ), 0, 2 ) ); } /** * Extra consignees as "Name (phone, phone) | …", or the string ABS sent. * * @param mixed $value String or list of {name, phones}. * @return string */ private static function extra_consignees( $value ) { if ( is_scalar( $value ) ) { return trim( (string) $value ); } $rows = array(); foreach ( is_array( $value ) ? $value : array() as $item ) { $name = is_array( $item ) && isset( $item['name'] ) && is_scalar( $item['name'] ) && '' !== trim( (string) $item['name'] ) ? trim( (string) $item['name'] ) : '-'; $phones = is_array( $item ) && isset( $item['phones'] ) && is_array( $item['phones'] ) ? array_filter( array_map( 'trim', array_map( 'strval', array_filter( $item['phones'], 'is_scalar' ) ) ), 'strlen' ) : array(); if ( '-' !== $name || $phones ) { $rows[] = $name . ' (' . ( $phones ? implode( ', ', $phones ) : '-' ) . ')'; } } return implode( ' | ', $rows ); } /** * Date as dd/mm/yyyy, or '' when missing or unreadable. * * @param string $value Date from ABS. * @return string */ private static function awb_date( $value ) { $time = '' !== $value ? strtotime( $value ) : false; return false === $time ? '' : wp_date( 'd/m/Y', $time ); } /** * Drops an all-zero fraction from a leading number: "7000.00" -> "7000", "1.50 Kg" -> "1.5 Kg". * * @param string $value Value. * @return string */ private static function strip_zeros( $value ) { return (string) preg_replace_callback( '/^(-?\d+)\.(\d+)(?=\s|$)/', static function ( $m ) { $fraction = rtrim( $m[2], '0' ); return '' !== $fraction ? $m[1] . '.' . $fraction : $m[1]; }, $value ); } /** * Cash as 3,415 / 3,415.5 (always Latin digits and commas: it is read by couriers). * * @param string $value Amount from ABS. * @return string */ private static function amount( $value ) { $formatted = number_format( is_numeric( $value ) ? (float) $value : 0.0, 2, '.', ',' ); return rtrim( rtrim( $formatted, '0' ), '.' ); } /** * True for the "Allow To Open Shipment" extra service, in any of its spellings. * * @param string $name Service name. * @return bool */ private static function is_open_shipment_service( $name ) { $name = strtr( $name, array( 'أ' => 'ا', 'إ' => 'ا', 'آ' => 'ا', 'ى' => 'ي', 'ة' => 'ه', ) ); $name = (string) preg_replace( '/[^a-z0-9\x{0621}-\x{064A}]/u', '', strtolower( $name ) ); return '' !== $name && ( 0 === strpos( $name, 'allowtoopenshipment' ) || 0 === strpos( $name, 'allowopenshipment' ) || in_array( $name, array( 'openshipment', 'canopen' ), true ) || false !== strpos( $name, 'بفتحالشحن' ) ); } /** * Name of an extra service entry (string or {name|value}). * * @param mixed $service Entry. * @return string */ private static function label( $service ) { if ( is_scalar( $service ) ) { return (string) $service; } foreach ( array( 'name', 'value', 'enName' ) as $key ) { if ( is_array( $service ) && isset( $service[ $key ] ) && is_scalar( $service[ $key ] ) ) { return (string) $service[ $key ]; } } return ''; } }