token = ! empty( $token ) ? $token : $this->get_stored_token(); } /** * Get stored token from options. * * @return string */ private function get_stored_token() { $encrypted = get_option( 'ajaxpress_cf_api_token', '' ); $token = $this->decrypt_token( $encrypted ); // Debug logging. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'AjaxPress CF Get Stored Token - Encrypted length: ' . strlen( $encrypted ) ); error_log( 'AjaxPress CF Get Stored Token - Decrypted length: ' . strlen( $token ) ); if ( empty( $token ) && ! empty( $encrypted ) ) { error_log( 'AjaxPress CF Get Stored Token - Decryption failed!' ); } } return $token; } /** * Encrypt token for storage. * * @param string $token Plain token. * @return string Encrypted token. */ public function encrypt_token( $token ) { if ( empty( $token ) ) { return ''; } $key = $this->get_encryption_key(); $iv = openssl_random_pseudo_bytes( 16 ); $encrypted = openssl_encrypt( $token, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv ); return base64_encode( $iv . $encrypted ); } /** * Decrypt stored token. * * @param string $encrypted_data Encrypted token. * @return string Plain token. */ private function decrypt_token( $encrypted_data ) { if ( empty( $encrypted_data ) ) { return ''; } $key = $this->get_encryption_key(); $data = base64_decode( $encrypted_data ); if ( strlen( $data ) < 16 ) { return ''; } $iv = substr( $data, 0, 16 ); $encrypted = substr( $data, 16 ); $decrypted = openssl_decrypt( $encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv ); return false !== $decrypted ? $decrypted : ''; } /** * Get encryption key. * * @return string */ private function get_encryption_key() { if ( defined( 'AJAXPRESS_ENCRYPTION_KEY' ) ) { return AJAXPRESS_ENCRYPTION_KEY; } return wp_salt( 'auth' ); } /** * Make API request. * * @param string $endpoint API endpoint. * @param string $method HTTP method. * @param array $body Request body. * @return array|WP_Error */ private function request( $endpoint, $method = 'GET', $body = null ) { if ( empty( $this->token ) ) { return new \WP_Error( 'cf_no_token', __( 'API token is not configured.', 'ajaxpress' ) ); } $url = self::API_BASE . $endpoint; $args = array( 'timeout' => 30, 'headers' => array( 'Authorization' => 'Bearer ' . $this->token, ), ); if ( null !== $body ) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode( $body ); } // Use appropriate WP HTTP function based on method. if ( 'GET' === $method ) { $response = wp_remote_get( $url, $args ); } elseif ( 'POST' === $method ) { $response = wp_remote_post( $url, $args ); } else { $args['method'] = $method; $response = wp_remote_request( $url, $args ); } // Debug logging. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'AjaxPress CF API Request: ' . $method . ' ' . $url ); error_log( 'AjaxPress CF API Headers: ' . print_r( $args['headers'], true ) ); if ( is_wp_error( $response ) ) { error_log( 'AjaxPress CF API WP_Error: ' . $response->get_error_message() ); } else { error_log( 'AjaxPress CF API Response Code: ' . wp_remote_retrieve_response_code( $response ) ); error_log( 'AjaxPress CF API Response Body: ' . wp_remote_retrieve_body( $response ) ); } } if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); $response_body = json_decode( wp_remote_retrieve_body( $response ), true ); // Handle HTTP errors. if ( $code >= 400 ) { $error_msg = isset( $response_body['errors'][0]['message'] ) ? $response_body['errors'][0]['message'] : __( 'API request failed', 'ajaxpress' ); return new \WP_Error( 'cf_api_error', $error_msg, array( 'status' => $code ) ); } // Handle CF API errors (success: false). if ( isset( $response_body['success'] ) && false === $response_body['success'] ) { $error_msg = isset( $response_body['errors'][0]['message'] ) ? $response_body['errors'][0]['message'] : __( 'Cloudflare API returned an error', 'ajaxpress' ); return new \WP_Error( 'cf_api_error', $error_msg ); } return $response_body; } /** * Verify token validity. * * @return array|WP_Error Token verification result. */ public function verify_token() { return $this->request( '/user/tokens/verify' ); } /** * Get user details. * * @return array|WP_Error */ public function get_user() { return $this->request( '/user' ); } /** * List zones (domains) in account. * * @param string $account_id Optional account ID filter. * @return array|WP_Error */ public function list_zones( $account_id = '' ) { $endpoint = '/zones?per_page=50&status=active'; if ( $account_id ) { $endpoint .= '&account.id=' . $account_id; } return $this->request( $endpoint ); } /** * Get zone details. * * @param string $zone_id Zone ID. * @return array|WP_Error */ public function get_zone( $zone_id ) { return $this->request( '/zones/' . $zone_id ); } /** * List accounts. * * @return array|WP_Error */ public function list_accounts() { return $this->request( '/accounts' ); } /** * Upload worker script (ES modules format). * * @param string $account_id Account ID. * @param string $script_name Worker script name. * @param string $script_content Worker script content. * @return array|WP_Error */ public function upload_worker( $account_id, $script_name, $script_content ) { $url = self::API_BASE . '/accounts/' . $account_id . '/workers/scripts/' . $script_name; // Build multipart form data for ES modules. $boundary = wp_generate_password( 24, false ); // Metadata specifying this is an ES module. $metadata = wp_json_encode( array( 'main_module' => 'worker.js', ) ); // Build multipart body. $body = ''; // Metadata part. $body .= '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="metadata"' . "\r\n"; $body .= 'Content-Type: application/json' . "\r\n\r\n"; $body .= $metadata . "\r\n"; // Worker script part. $body .= '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="worker.js"; filename="worker.js"' . "\r\n"; $body .= 'Content-Type: application/javascript+module' . "\r\n\r\n"; $body .= $script_content . "\r\n"; // End boundary. $body .= '--' . $boundary . '--' . "\r\n"; $response = wp_remote_request( $url, array( 'method' => 'PUT', 'timeout' => 30, 'headers' => array( 'Authorization' => 'Bearer ' . $this->token, 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, ), 'body' => $body, ) ); // Debug logging. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'AjaxPress CF Worker Upload URL: ' . $url ); if ( is_wp_error( $response ) ) { error_log( 'AjaxPress CF Worker Upload Error: ' . $response->get_error_message() ); } else { error_log( 'AjaxPress CF Worker Upload Response Code: ' . wp_remote_retrieve_response_code( $response ) ); error_log( 'AjaxPress CF Worker Upload Response Body: ' . wp_remote_retrieve_body( $response ) ); } } if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); $response_body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code >= 400 ) { $error_msg = isset( $response_body['errors'][0]['message'] ) ? $response_body['errors'][0]['message'] : 'Failed to upload worker'; return new \WP_Error( 'cf_worker_error', $error_msg ); } return $response_body; } /** * Delete worker script. * * @param string $account_id Account ID. * @param string $script_name Worker script name. * @return array|WP_Error */ public function delete_worker( $account_id, $script_name ) { return $this->request( '/accounts/' . $account_id . '/workers/scripts/' . $script_name, 'DELETE' ); } /** * Create worker route. * * @param string $zone_id Zone ID. * @param string $pattern Route pattern (e.g., example.com/*). * @param string $script_name Worker script name. * @return array|WP_Error */ public function create_route( $zone_id, $pattern, $script_name ) { return $this->request( '/zones/' . $zone_id . '/workers/routes', 'POST', array( 'pattern' => $pattern, 'script' => $script_name, ) ); } /** * List worker routes. * * @param string $zone_id Zone ID. * @return array|WP_Error */ public function list_routes( $zone_id ) { return $this->request( '/zones/' . $zone_id . '/workers/routes' ); } /** * Delete worker route. * * @param string $zone_id Zone ID. * @param string $route_id Route ID. * @return array|WP_Error */ public function delete_route( $zone_id, $route_id ) { return $this->request( '/zones/' . $zone_id . '/workers/routes/' . $route_id, 'DELETE' ); } /** * Purge cache by URLs. * * @param string $zone_id Zone ID. * @param array $urls URLs to purge (max 30). * @return array|WP_Error */ public function purge_urls( $zone_id, $urls ) { return $this->request( '/zones/' . $zone_id . '/purge_cache', 'POST', array( 'files' => array_slice( $urls, 0, 30 ) ) ); } /** * Purge entire cache for zone. * * @param string $zone_id Zone ID. * @return array|WP_Error */ public function purge_all( $zone_id ) { return $this->request( '/zones/' . $zone_id . '/purge_cache', 'POST', array( 'purge_everything' => true ) ); } /** * Get worker script for caching. * * @param array $options Configuration options. * @return string Worker script content. */ public function get_worker_script( $options = array() ) { $bypass_patterns = isset( $options['bypass_patterns'] ) ? $options['bypass_patterns'] : array( '/wp-admin', '/wp-json', '/wp-login', '/checkout', '/cart' ); $bypass_cookies = isset( $options['bypass_cookies'] ) ? $options['bypass_cookies'] : array( 'wordpress_logged_in_' ); $patterns_js = wp_json_encode( $bypass_patterns ); $cookies_js = wp_json_encode( $bypass_cookies ); return << cookie.includes(c))) { const response = await fetch(request); const newResponse = new Response(response.body, response); newResponse.headers.set('X-AjaxPress-Cache', 'BYPASS'); return newResponse; } // Bypass patterns const bypassPatterns = {$patterns_js}; if (bypassPatterns.some(p => url.pathname.startsWith(p))) { return fetch(request); } // Skip non-HTML requests (assets) const ext = url.pathname.split('.').pop().toLowerCase(); const skipExtensions = ['js', 'css', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'woff', 'woff2', 'ttf', 'eot', 'webp', 'avif']; if (skipExtensions.includes(ext)) { return fetch(request); } // Check cache const cache = caches.default; let response = await cache.match(request); if (response) { const newResponse = new Response(response.body, response); newResponse.headers.set('X-AjaxPress-Cache', 'HIT'); return newResponse; } // Fetch from origin response = await fetch(request); // Only cache successful HTML responses if (response.status === 200 && response.headers.get('Content-Type')?.includes('text/html')) { const clone = response.clone(); ctx.waitUntil(cache.put(request, clone)); } const newResponse = new Response(response.body, response); newResponse.headers.set('X-AjaxPress-Cache', 'MISS'); return newResponse; } }; JAVASCRIPT; } } }