auth = $auth; add_action( 'rest_api_init', array( $this, 'register_routes' ) ); add_filter( 'rest_pre_serve_request', array( $this, 'serve_proxy_asset_image' ), 10, 4 ); add_filter( 'rest_pre_serve_request', array( $this, 'serve_proxy_stream' ), 9, 4 ); } /** * Register REST API routes */ public function register_routes() { register_rest_route( 'agents24x7/v1', '/query', array( 'methods' => 'POST', 'callback' => array( $this, 'proxy_query' ), 'permission_callback' => array( $this, 'check_read_permissions' ), ) ); register_rest_route( 'agents24x7/v1', '/mutation', array( 'methods' => 'POST', 'callback' => array( $this, 'proxy_mutation' ), 'permission_callback' => array( $this, 'check_admin_permissions' ), ) ); register_rest_route( 'agents24x7/v1', '/action', array( 'methods' => 'POST', 'callback' => array( $this, 'proxy_action' ), 'permission_callback' => array( $this, 'check_admin_permissions' ), ) ); register_rest_route( 'agents24x7/v1', '/stream', array( 'methods' => 'POST', 'callback' => array( $this, 'proxy_stream_action' ), 'permission_callback' => array( $this, 'check_admin_permissions' ), ) ); register_rest_route( 'agents24x7/v1', '/company-knowledge', array( 'methods' => array( 'GET', 'POST', 'DELETE' ), 'callback' => array( $this, 'proxy_company_knowledge' ), 'permission_callback' => array( $this, 'check_read_permissions' ), ) ); register_rest_route( 'agents24x7/v1', '/assets', array( array( 'methods' => 'POST', 'callback' => array( $this, 'proxy_asset_upload' ), 'permission_callback' => array( $this, 'check_admin_permissions' ), ), array( 'methods' => 'GET', 'callback' => array( $this, 'proxy_asset_image' ), 'permission_callback' => array( $this, 'check_read_permissions' ), ), ) ); register_rest_route( 'agents24x7/v1', '/service-status', array( 'methods' => 'GET', 'callback' => array( $this, 'service_status' ), 'permission_callback' => array( $this, 'check_read_permissions' ), ) ); } /** Let the admin app check recovery without sending another account or chat request. */ public function service_status() { return rest_ensure_response( array( 'available' => Agents24x7_Service_Status::is_available(), ) ); } /** * Check permissions * * @return bool */ public function check_read_permissions() { return current_user_can( 'edit_posts' ); } /** Require an administrator for routes that can change data or invoke actions. */ public function check_admin_permissions() { return current_user_can( 'manage_options' ); } /** Confirm the plugin has a live platform token for this site. */ public function is_platform_linked() { return $this->auth->is_authenticated(); } /** Call one read or chat platform RPC from a WordPress ability. */ public function call_platform_function( $type, $function, $args ) { if ( ! in_array( $type, array( 'query', 'action' ), true ) || ! is_string( $function ) || ! is_array( $args ) ) { return new WP_Error( 'invalid_request', esc_html__( 'Invalid Agents24x7 request.', 'agents24x7' ), array( 'status' => 400 ) ); } return $this->proxy_platform_function( $type, $function, $args ); } /** * Proxy query request * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error */ public function proxy_query( $request ) { return $this->proxy_convex_request( 'query', $request ); } /** * Proxy mutation request * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error */ public function proxy_mutation( $request ) { return $this->proxy_convex_request( 'mutation', $request ); } /** * Proxy action request * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error */ public function proxy_action( $request ) { return $this->proxy_convex_request( 'action', $request ); } /** Prepare the existing authenticated send action for incremental relay. */ public function proxy_stream_action( $request ) { if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', esc_html__( 'Plugin not connected to Agents24x7', 'agents24x7' ), array( 'status' => 401 ) ); } if ( Agents24x7_Service_Status::is_known_unavailable() ) { return $this->service_unavailable_error(); } if ( ! function_exists( 'curl_init' ) ) { return new WP_Error( 'stream_unavailable', esc_html__( 'Incremental chat is unavailable on this host.', 'agents24x7' ), array( 'status' => 501 ) ); } $params = $request->get_json_params(); if ( ! isset( $params['function'], $params['args'] ) || 'wordpress/aiAgents:streamMessage' !== $params['function'] || ! is_array( $params['args'] ) ) { return new WP_Error( 'invalid_request', esc_html__( 'Invalid chat stream request', 'agents24x7' ), array( 'status' => 400 ) ); } $this->pending_stream = array( 'url' => trailingslashit( Agents24x7_Config::get_api_url() ) . 'wordpress/api', 'headers' => array_merge( $this->auth->get_auth_headers(), array( 'Content-Type' => 'application/json', 'Accept' => 'text/event-stream', 'X-WordPress-Site' => home_url(), 'X-WordPress-WooCommerce' => class_exists( 'WooCommerce' ) ? 'true' : 'false', 'X-WordPress-User' => get_current_user_id(), ), $this->viewer_locale_header() ), 'body' => wp_json_encode( array( 'type' => 'action', 'functionName' => $params['function'], 'args' => $params['args'], ) ), 'function' => $params['function'], ); return new WP_REST_Response( null, 200, array( 'X-Agents24x7-Stream-Proxy' => '1', 'Content-Type' => 'text/event-stream; charset=utf-8', 'Cache-Control' => 'no-cache, no-transform', 'X-Accel-Buffering' => 'no', ) ); } /** Relay chunks when the host supports cURL; other hosts use the existing action fallback. */ public function serve_proxy_stream( $served, $result, $request, $server ) { $result_headers = $result instanceof WP_REST_Response ? $result->get_headers() : array(); if ( ! $result instanceof WP_REST_Response || ! isset( $result_headers['X-Agents24x7-Stream-Proxy'] ) || '1' !== $result_headers['X-Agents24x7-Stream-Proxy'] || empty( $this->pending_stream ) ) { return $served; } $pending = $this->pending_stream; $this->pending_stream = null; $status = 0; $content_type = 'text/event-stream; charset=utf-8'; $curl = curl_init( $pending['url'] ); curl_setopt_array( $curl, array( CURLOPT_POST => true, CURLOPT_POSTFIELDS => $pending['body'], CURLOPT_HTTPHEADER => $this->format_curl_headers( $pending['headers'] ), CURLOPT_CONNECTTIMEOUT => 8, CURLOPT_TIMEOUT => 90, CURLOPT_HEADERFUNCTION => function ( $handle, $line ) use ( &$status, &$content_type ) { if ( preg_match( '/^HTTP\/\S+\s+(\d+)/i', $line, $matches ) ) { $status = (int) $matches[1]; } elseif ( 0 === stripos( $line, 'Content-Type:' ) ) { $upstream_type = trim( substr( $line, strlen( 'Content-Type:' ) ) ); $content_type = false !== stripos( $upstream_type, 'text/event-stream' ) ? 'text/event-stream; charset=utf-8' : 'application/json; charset=utf-8'; } return strlen( $line ); }, CURLOPT_WRITEFUNCTION => function ( $handle, $chunk ) use ( &$status, &$content_type ) { if ( ! headers_sent() ) { status_header( $status ?: 200 ); header( 'Content-Type: ' . $content_type ); header( 'Cache-Control: no-cache, no-transform' ); header( 'X-Accel-Buffering: no' ); while ( ob_get_level() > 0 ) { ob_end_flush(); } } echo $chunk; flush(); return connection_aborted() ? 0 : strlen( $chunk ); }, ) ); $ok = curl_exec( $curl ); $curl_status = (int) curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ); $this->log_api_usage( 'action', $pending['function'], $curl_status ); if ( false === $ok && ! headers_sent() ) { status_header( 502 ); header( 'Content-Type: application/json; charset=utf-8' ); echo wp_json_encode( array( 'code' => 'upstream_unavailable', 'message' => esc_html__( 'The chat stream is unavailable.', 'agents24x7' ) ) ); } curl_close( $curl ); return true; } /** Convert the WordPress header map to cURL's list format. */ private function format_curl_headers( $headers ) { $formatted = array(); foreach ( $headers as $name => $value ) { $formatted[] = $name . ': ' . $value; } return $formatted; } /** Company files use the same private storage and bounded upload path as the portal. */ public function proxy_company_knowledge( $request ) { if ( 'GET' !== $request->get_method() && ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'forbidden', 'Only administrators can change company files.', array( 'status' => 403 ) ); } if ( 'POST' === $request->get_method() ) { return $this->proxy_asset_upload( $request, true ); } if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', 'Plugin not connected.', array( 'status' => 401 ) ); } $url = rtrim( AGENTS24X7_APP_URL, '/' ) . '/wordpress/company-knowledge'; if ( 'DELETE' === $request->get_method() ) { $id = $request->get_param( 'id' ); if ( ! is_string( $id ) || ! preg_match( '/^[0-9a-f-]{36}$/i', $id ) ) { return new WP_Error( 'invalid_request', 'Choose a company file.', array( 'status' => 400 ) ); } $url .= '?id=' . rawurlencode( $id ); } $response = wp_remote_request( $url, array( 'method' => $request->get_method(), 'headers' => $this->auth->get_auth_headers(), 'timeout' => 30 ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'service_unavailable', 'Company files could not be loaded.', array( 'status' => 502 ) ); } return new WP_REST_Response( json_decode( wp_remote_retrieve_body( $response ), true ), wp_remote_retrieve_response_code( $response ) ); } /** Proxy one image upload through the server-held WordPress API token. */ public function proxy_asset_upload( $request, $company_knowledge = false ) { if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', esc_html__( 'Plugin not connected to Agents24x7', 'agents24x7' ), array( 'status' => 401 ) ); } $files = $request->get_file_params(); $file = isset( $files['file'] ) ? $files['file'] : null; $agent_id = $request->get_param( 'agentId' ); if ( ! is_array( $file ) || empty( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) || ( ! $company_knowledge && ( empty( $agent_id ) || ! preg_match( '/^[0-9a-f-]{36}$/i', $agent_id ) ) ) ) { return new WP_Error( 'invalid_request', esc_html__( 'Choose one image file and chat to attach it to.', 'agents24x7' ), array( 'status' => 400 ) ); } if ( ! empty( $file['error'] ) || filesize( $file['tmp_name'] ) > 10 * MB_IN_BYTES ) { return new WP_Error( 'file_too_large', esc_html__( 'Image files must be 10 MiB or smaller.', 'agents24x7' ), array( 'status' => 413 ) ); } $bytes = file_get_contents( $file['tmp_name'] ); if ( false === $bytes ) { return new WP_Error( 'invalid_request', esc_html__( 'The image could not be read.', 'agents24x7' ), array( 'status' => 400 ) ); } $boundary = wp_generate_password( 24, false ); $filename = sanitize_file_name( isset( $file['name'] ) ? $file['name'] : 'image' ); $body = '--' . $boundary . "\r\n" . "Content-Disposition: form-data; name=\"agentId\"\r\n\r\n" . $agent_id . "\r\n" . '--' . $boundary . "\r\n" . 'Content-Disposition: form-data; name="file"; filename="' . $filename . "\"\r\n" . 'Content-Type: ' . ( isset( $file['type'] ) ? sanitize_mime_type( $file['type'] ) : 'application/octet-stream' ) . "\r\n\r\n" . $bytes . "\r\n--" . $boundary . "--\r\n"; if ( $company_knowledge && $request->get_param( 'id' ) ) { $id = $request->get_param( 'id' ); if ( ! is_string( $id ) || ! preg_match( '/^[0-9a-f-]{36}$/i', $id ) ) { return new WP_Error( 'invalid_request', 'Choose a company file.', array( 'status' => 400 ) ); } $body = '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"id\"\r\n\r\n" . $id . "\r\n" . $body; } $headers = array_merge( $this->auth->get_auth_headers(), array( 'Content-Type' => 'multipart/form-data; boundary=' . $boundary ) ); $response = wp_remote_post( rtrim( AGENTS24X7_APP_URL, '/' ) . ( $company_knowledge ? '/wordpress/company-knowledge' : '/wordpress/assets' ), array( 'headers' => $headers, 'body' => $body, 'timeout' => 30 ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'service_unavailable', esc_html__( 'The image could not be uploaded. Please try again.', 'agents24x7' ), array( 'status' => 502 ) ); } $status = wp_remote_retrieve_response_code( $response ); return new WP_REST_Response( json_decode( wp_remote_retrieve_body( $response ), true ), $status ); } /** Proxy an organisation-scoped image read; the platform validates the token and asset id. */ public function proxy_asset_image( $request ) { if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', esc_html__( 'Plugin not connected to Agents24x7', 'agents24x7' ), array( 'status' => 401 ) ); } $asset_id = $request->get_param( 'assetId' ); $url = rtrim( AGENTS24X7_APP_URL, '/' ) . '/wordpress/assets'; if ( null !== $asset_id && '' !== $asset_id ) { if ( ! is_string( $asset_id ) || ! preg_match( '/^[0-9a-f-]{36}$/i', $asset_id ) ) { return new WP_Error( 'invalid_request', esc_html__( 'Choose an image to view.', 'agents24x7' ), array( 'status' => 400 ) ); } $url = add_query_arg( 'assetId', $asset_id, $url ); } $response = wp_remote_get( $url, array( 'headers' => $this->auth->get_auth_headers(), 'timeout' => 30 ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'service_unavailable', esc_html__( 'The image is not available.', 'agents24x7' ), array( 'status' => 502 ) ); } $status = wp_remote_retrieve_response_code( $response ); $content_type = wp_remote_retrieve_header( $response, 'content-type' ); if ( 200 === $status && is_string( $content_type ) && false !== strpos( $content_type, 'application/json' ) ) { return new WP_REST_Response( json_decode( wp_remote_retrieve_body( $response ), true ), 200 ); } if ( 200 !== $status || ! in_array( $content_type, array( 'image/jpeg', 'image/png', 'image/webp' ), true ) ) { return new WP_Error( 'asset_not_found', esc_html__( 'Image not found.', 'agents24x7' ), array( 'status' => 404 ) ); } return new WP_REST_Response( wp_remote_retrieve_body( $response ), 200, array( 'Content-Type' => $content_type, 'Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff' ) ); } /** WordPress REST JSON-encodes strings; stream proxy image bytes unchanged. */ public function serve_proxy_asset_image( $served, $result, $request, $server ) { if ( $served || 'GET' !== $request->get_method() || '/agents24x7/v1/assets' !== $request->get_route() || ! $result instanceof WP_REST_Response ) { return $served; } $response_headers = $result->get_headers(); $content_type = $response_headers['Content-Type'] ?? $response_headers['content-type'] ?? ''; if ( ! in_array( $content_type, array( 'image/jpeg', 'image/png', 'image/webp' ), true ) ) { return $served; } status_header( $result->get_status() ); header( 'Content-Type: ' . $content_type ); header( 'Cache-Control: private, no-store' ); header( 'X-Content-Type-Options: nosniff' ); echo $result->get_data(); return true; } /** * Proxy request to Convex * * @param string $type Request type (query, mutation, action) * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error */ private function proxy_convex_request( $type, $request ) { try { // Check if we have an API token if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', esc_html__( 'Plugin not connected to Agents24x7', 'agents24x7' ), array( 'status' => 401 ) ); } $params = $request->get_json_params(); if ( ! isset( $params['function'] ) || ! isset( $params['args'] ) ) { return new WP_Error( 'invalid_request', esc_html__( 'Missing required parameters: function, args', 'agents24x7' ), array( 'status' => 400 ) ); } return $this->proxy_platform_function( $type, $params['function'], $params['args'] ); } catch ( Exception $e ) { return new WP_Error( 'server_error', 'Internal server error: ' . $e->getMessage(), array( 'status' => 500 ) ); } } /** * The viewer's admin language, so platform refusals and notices read in the language this admin sees. * Optional on the platform side: requests without it fall back to the agent's language. */ private function viewer_locale_header() { $locale = function_exists( 'get_user_locale' ) ? get_user_locale() : ( function_exists( 'get_locale' ) ? get_locale() : '' ); return is_string( $locale ) && '' !== $locale ? array( 'X-WordPress-Locale' => $locale ) : array(); } /** Send a named function through the plugin's authenticated platform connection. */ private function proxy_platform_function( $type, $function, $args ) { if ( 'wordpress/notifications:get' === $function && ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'forbidden', esc_html__( 'You need administrative access to use this plugin.', 'agents24x7' ), array( 'status' => 403 ) ); } try { if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', esc_html__( 'Plugin not connected to Agents24x7', 'agents24x7' ), array( 'status' => 401 ) ); } if ( Agents24x7_Service_Status::is_known_unavailable() ) { return $this->service_unavailable_error(); } if ( in_array( $function, array( 'wordpress/support:getAgentPage', 'wordpress/support:updateSettings' ), true ) ) { $args['hasWoocommerce'] = class_exists( 'WooCommerce' ); } // WordPress decodes JSON objects as associative arrays, including empty records. if ( isset( $args['socialIntegrationLinks'] ) && array() === $args['socialIntegrationLinks'] ) { $args['socialIntegrationLinks'] = (object) array(); } $api_url = trailingslashit( Agents24x7_Config::get_api_url() ) . 'wordpress/api'; // Prepare headers $headers = array_merge( $this->auth->get_auth_headers(), array( 'Content-Type' => 'application/json', 'X-WordPress-Site' => home_url(), 'X-WordPress-WooCommerce' => class_exists( 'WooCommerce' ) ? 'true' : 'false', 'X-WordPress-User' => get_current_user_id(), ), $this->viewer_locale_header() ); // Make the request $response = wp_remote_post( $api_url, array( 'headers' => $headers, 'body' => wp_json_encode( array( 'type' => $type, 'functionName' => $function, 'args' => $args, ) ), 'timeout' => 30, ) ); if ( is_wp_error( $response ) ) { return $this->transport_failed( $response ); } $status_code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); // Log API usage for debugging $this->log_api_usage( $type, $function, $status_code ); if ( $this->is_gateway_failure( $status_code ) ) { Agents24x7_Service_Status::mark_unavailable(); return $this->service_unavailable_error(); } // Handle 401 authentication errors specifically if ( $status_code === 401 ) { // Clear the invalid/expired token $this->auth->disconnect(); return new WP_Error( 'authentication_expired', esc_html__( 'Your connection to Agents24x7 has expired. Please reconnect.', 'agents24x7' ), array( 'status' => 401, 'requires_reauthentication' => true ) ); } if ( $status_code >= 400 ) { $error_message = isset( $data['error'] ) ? $data['error'] : esc_html__( 'API request failed', 'agents24x7' ); // The platform's own error code (e.g. NOT_AVAILABLE) rides in // the body; keep it in the WP_Error data so the admin app can // distinguish feature-level outages from generic failures. $error_data = array( 'status' => $status_code ); if ( isset( $data['code'] ) && is_string( $data['code'] ) ) { $error_data['code'] = $data['code']; } if ( isset( $data['details'] ) && is_array( $data['details'] ) ) { $error_data['details'] = $data['details']; } return new WP_Error( 'api_error', $error_message, $error_data ); } if ( in_array( $function, array( 'wordpress/approval:decide', 'wordpress/approval:approveAll', 'wordpress/workItems:action', 'wordpress/support:caseDecision' ), true ) ) { do_action( 'agents24x7_approval_changed' ); } return new WP_REST_Response( $data, $status_code ); } catch ( Exception $e ) { return new WP_Error( 'server_error', 'Internal server error: ' . $e->getMessage(), array( 'status' => 500 ) ); } } /** * Call disconnectFromPlugin action * * @param string $site_url Site URL to disconnect * @return array|WP_Error API response or error */ public function disconnect_from_plugin( $site_url ) { try { // Check if we have an API token if ( ! $this->auth->is_authenticated() ) { return new WP_Error( 'not_authenticated', esc_html__( 'Plugin not connected to Agents24x7', 'agents24x7' ) ); } if ( Agents24x7_Service_Status::is_known_unavailable() ) { return $this->service_unavailable_error(); } $api_url = trailingslashit( Agents24x7_Config::get_api_url() ) . 'wordpress/api'; // Prepare headers $headers = array_merge( $this->auth->get_auth_headers(), array( 'Content-Type' => 'application/json', 'X-WordPress-Site' => home_url(), 'X-WordPress-WooCommerce' => class_exists( 'WooCommerce' ) ? 'true' : 'false', 'X-WordPress-User' => get_current_user_id(), ) ); // Make the request $response = wp_remote_post( $api_url, array( 'headers' => $headers, 'body' => wp_json_encode( array( 'type' => 'action', 'functionName' => 'wordpress/plugin:disconnectFromPlugin', 'args' => array( 'siteUrl' => $site_url ), ) ), 'timeout' => 30, ) ); if ( is_wp_error( $response ) ) { return $this->transport_failed( $response ); } $status_code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); // Log API usage for debugging $this->log_api_usage( 'action', 'wordpress/plugin:disconnectFromPlugin', $status_code ); if ( $this->is_gateway_failure( $status_code ) ) { Agents24x7_Service_Status::mark_unavailable(); return $this->service_unavailable_error(); } // Handle 401 authentication errors specifically if ( $status_code === 401 ) { // Token is already invalid, just return specific error return new WP_Error( 'authentication_expired', esc_html__( 'Your connection to Agents24x7 has expired. Please reconnect.', 'agents24x7' ) ); } if ( $status_code >= 400 ) { $error_message = isset( $data['error'] ) ? $data['error'] : esc_html__( 'API request failed', 'agents24x7' ); $error_data = array( 'status' => $status_code ); if ( isset( $data['code'] ) && is_string( $data['code'] ) ) { $error_data['code'] = $data['code']; } if ( isset( $data['details'] ) && is_array( $data['details'] ) ) { $error_data['details'] = $data['details']; } return new WP_Error( 'api_error', $error_message, $error_data ); } return $data; } catch ( Exception $e ) { return new WP_Error( 'server_error', 'Internal server error: ' . $e->getMessage() ); } } /** * Handle a request that never got an HTTP response * * The transport detail (DNS, TLS, timeout) goes to the debug log; the * site owner gets a plain message, and the outage is remembered so the * next requests fail fast instead of each waiting out the timeout. * * @param WP_Error $error Transport error from wp_remote_post * @return WP_Error */ private function transport_failed( $error ) { Agents24x7_Logger::error( 'Backend request failed: ' . $error->get_error_message() ); Agents24x7_Service_Status::mark_unavailable(); return $this->service_unavailable_error(); } /** * Whether a status code means the backend is down rather than the request wrong * * @param int $status_code HTTP status code * @return bool */ private function is_gateway_failure( $status_code ) { return in_array( (int) $status_code, array( 502, 503, 504 ), true ); } /** * The error returned while the backend is unreachable * * @return WP_Error */ private function service_unavailable_error() { return new WP_Error( 'service_unavailable', Agents24x7_Service_Status::unavailable_message(), array( 'status' => 503 ) ); } /** * Log API usage * * @param string $type Request type * @param string $function Function name * @param int $status_code Response status code */ private function log_api_usage( $type, $function, $status_code ) { Agents24x7_Logger::info( sprintf( '[Agents24x7 API] %s %s - Status: %d', strtoupper( $type ), $function, $status_code ) ); } }