get_setting('sandbox', 0); } protected function endpoint() { $base = $this->is_sandbox() ? $this->test_base_url() : $this->base_url(); if ($base === '') { $base = $this->base_url(); } return rtrim($base, '/'); } protected function common_schema() { return array( 'sandbox' => array( 'type' => 'checkbox', 'label' => __('Use the test environment', 'ai-eshop-optimizer'), 'help' => __('Point this carrier at its sandbox. Create one shipment and open the label before you untick this — a mapping that reads correctly can still be refused by the carrier, and finding that out on a real parcel is expensive.', 'ai-eshop-optimizer'), ), ); } protected function request($method, $path, $body = null, array $headers = array(), $timeout = 45) { $url = (strpos($path, 'http') === 0) ? $path : $this->endpoint() . '/' . ltrim($path, '/'); $args = array( 'method' => strtoupper($method), 'timeout' => (int) $timeout, 'redirection' => 0, 'headers' => array_merge(array( 'Accept' => 'application/json', 'Content-Type' => 'application/json', ), $headers), ); if ($body !== null) { $args['body'] = wp_json_encode($body); } $resp = wp_remote_request($url, $args); if (is_wp_error($resp)) { return new WP_Error('aieo_courier_transport', sprintf( __('%1$s could not be reached: %2$s', 'ai-eshop-optimizer'), $this->label(), $resp->get_error_message() )); } $code = (int) wp_remote_retrieve_response_code($resp); $raw = (string) wp_remote_retrieve_body($resp); $json = json_decode($raw, true); if ($code < 200 || $code >= 300) { $msg = $this->extract_error(is_array($json) ? $json : array(), $raw); error_log('[AIEO-' . strtoupper($this->code()) . '-FAIL] ' . $args['method'] . ' ' . $url . ' http=' . $code . ' sent=' . substr((string) ($args['body'] ?? ''), 0, 1200) . ' got=' . substr($raw, 0, 1200)); return new WP_Error('aieo_courier_http_' . $code, $msg !== '' ? $msg : sprintf( __('%1$s returned HTTP %2$d', 'ai-eshop-optimizer'), $this->label(), $code )); } if ($raw !== '' && !is_array($json)) { return new WP_Error('aieo_courier_shape', sprintf( __('%s returned something that is not JSON.', 'ai-eshop-optimizer'), $this->label() )); } return is_array($json) ? $json : array(); } protected function extract_error(array $json, $raw = '') { $out = array(); $walk = function ($node) use (&$walk, &$out) { if (is_string($node)) { $node = trim($node); if ($node !== '' && strlen($node) > 3) { $out[] = $node; } return; } if (!is_array($node)) { return; } foreach (array('message', 'detail', 'errorDescription', 'title', 'description') as $k) { if (isset($node[$k]) && is_string($node[$k]) && trim($node[$k]) !== '') { $out[] = trim($node[$k]); } } foreach (array('errors', 'additionalDetails', 'error', 'errorMessages') as $k) { if (isset($node[$k])) { $walk($node[$k]); } } }; $walk($json); $out = array_values(array_unique(array_filter($out))); if (!empty($out)) { return implode(' · ', array_slice($out, 0, 3)); } $raw = trim(wp_strip_all_tags((string) $raw)); return $raw !== '' ? mb_substr($raw, 0, 300) : ''; } protected function oauth_token($token_path, array $form) { $key = 'aieo_ff_tok_' . md5($this->code() . '|' . $this->endpoint() . '|' . wp_json_encode(array_keys($form)) . '|' . md5(wp_json_encode($form))); $cached = get_transient($key); if (is_string($cached) && $cached !== '') { return $cached; } $url = (strpos($token_path, 'http') === 0) ? $token_path : $this->endpoint() . '/' . ltrim($token_path, '/'); $resp = wp_remote_post($url, array( 'timeout' => 30, 'redirection' => 0, 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', ), 'body' => $form, )); if (is_wp_error($resp)) { return new WP_Error('aieo_courier_transport', $resp->get_error_message()); } $code = (int) wp_remote_retrieve_response_code($resp); $json = json_decode((string) wp_remote_retrieve_body($resp), true); if ($code < 200 || $code >= 300 || empty($json['access_token'])) { $msg = $this->extract_error(is_array($json) ? $json : array(), (string) wp_remote_retrieve_body($resp)); return new WP_Error('aieo_courier_auth', $msg !== '' ? $msg : sprintf( __('%1$s rejected the credentials (HTTP %2$d).', 'ai-eshop-optimizer'), $this->label(), $code )); } $token = (string) $json['access_token']; $ttl = isset($json['expires_in']) ? (int) $json['expires_in'] : 3600; set_transient($key, $token, max(60, $ttl - self::TOKEN_SAFETY_MARGIN)); return $token; } protected function request_raw($method, $path, $body = null, array $headers = array(), $timeout = 60) { $url = (strpos($path, 'http') === 0) ? $path : $this->endpoint() . '/' . ltrim($path, '/'); $args = array( 'method' => strtoupper($method), 'timeout' => (int) $timeout, 'redirection' => 0, 'headers' => array_merge(array('Content-Type' => 'application/json'), $headers), ); if ($body !== null) { $args['body'] = wp_json_encode($body); } $resp = wp_remote_request($url, $args); if (is_wp_error($resp)) { return new WP_Error('aieo_courier_transport', $resp->get_error_message()); } $code = (int) wp_remote_retrieve_response_code($resp); $raw = (string) wp_remote_retrieve_body($resp); if ($code < 200 || $code >= 300) { $json = json_decode($raw, true); $msg = $this->extract_error(is_array($json) ? $json : array(), $raw); error_log('[AIEO-' . strtoupper($this->code()) . '-FAIL] ' . $args['method'] . ' ' . $url . ' http=' . $code . ' sent=' . substr((string) ($args['body'] ?? ''), 0, 1200) . ' got=' . substr($raw, 0, 800)); return new WP_Error('aieo_courier_http_' . $code, $msg !== '' ? $msg : sprintf( __('%1$s returned HTTP %2$d', 'ai-eshop-optimizer'), $this->label(), $code )); } return array( 'body' => $raw, 'content_type' => (string) wp_remote_retrieve_header($resp, 'content-type'), ); } protected function split_multipart($body, $content_type) { if (!preg_match('/boundary="?([^";]+)"?/i', (string) $content_type, $m)) { return array(); } $boundary = '--' . trim($m[1]); $out = array(); foreach (explode($boundary, (string) $body) as $chunk) { $chunk = ltrim($chunk, "\r\n"); if ($chunk === '' || strpos($chunk, '--') === 0) { continue; } $split = preg_split("/\r?\n\r?\n/", $chunk, 2); if (count($split) !== 2) { continue; } $out[] = array( 'headers' => $split[0], 'payload' => rtrim($split[1], "\r\n"), ); } return $out; } protected function fetch_binary($url, array $headers = array(), $timeout = 45) { $resp = wp_remote_get($url, array( 'timeout' => (int) $timeout, 'redirection' => 3, 'headers' => array_merge(array('Accept' => '*/*'), $headers), )); if (is_wp_error($resp)) { return new WP_Error('aieo_courier_transport', $resp->get_error_message()); } $code = (int) wp_remote_retrieve_response_code($resp); $body = (string) wp_remote_retrieve_body($resp); if ($code < 200 || $code >= 300) { $json = json_decode($body, true); $msg = $this->extract_error(is_array($json) ? $json : array(), $body); return new WP_Error('aieo_courier_http_' . $code, $msg !== '' ? $msg : sprintf( __('%1$s returned HTTP %2$d for the label.', 'ai-eshop-optimizer'), $this->label(), $code )); } if ($body === '') { return new WP_Error('aieo_courier_empty', sprintf( __('%s returned an empty label.', 'ai-eshop-optimizer'), $this->label() )); } return $body; } protected function decode_label($b64) { $bytes = base64_decode((string) $b64, true); if ($bytes === false || $bytes === '') { return array('ok' => false, 'pdf' => null, 'mime' => '', 'error' => sprintf( __('%s returned a label we could not decode.', 'ai-eshop-optimizer'), $this->label() )); } $head = substr($bytes, 0, 4); if ($head === '%PDF') { $mime = 'application/pdf'; } elseif (substr($bytes, 0, 8) === "\x89PNG\r\n\x1a\n") { $mime = 'image/png'; } elseif (substr($bytes, 0, 3) === "\xff\xd8\xff") { $mime = 'image/jpeg'; } elseif (substr($bytes, 0, 3) === 'GIF') { $mime = 'image/gif'; } elseif (substr($bytes, 0, 2) === "\x1b\x40") { $mime = 'application/x-epl'; } elseif (strpos(substr($bytes, 0, 16), '^XA') !== false) { $mime = 'application/x-zpl'; } else { $mime = 'application/octet-stream'; } return array('ok' => true, 'pdf' => $bytes, 'mime' => $mime, 'error' => null); } protected function split_address($address) { $address = trim((string) $address); if ($address !== '' && preg_match('/^(.*?)[\s,]+([0-9]+[A-Za-z]?)\s*$/u', $address, $m)) { return array(trim($m[1]), trim($m[2])); } return array($address, ''); } protected function split_name($name) { $name = trim(preg_replace('/\s+/u', ' ', (string) $name)); if ($name === '') { return array('', ''); } $parts = explode(' ', $name); $first = array_shift($parts); return array($first, implode(' ', $parts)); } protected function digits($phone) { return preg_replace('/\D+/', '', (string) $phone); } protected function reference(array $payload, $max = 30) { return mb_substr(trim((string) ($payload['reference_1'] ?? '')), 0, $max); } }