— the administrator, marking one answered or closed * POST /support/test — the administrator, running the whole visitor path as a probe * * @package AI House */ defined( 'ABSPATH' ) || exit; /** * Class MYBOT_REST_Support */ class MYBOT_REST_Support { /** * Prefix put in front of the code when the failure came from a permission check. * * The status card prints the stored message as-is, so the prefix is what tells the reader * where to look: a plain code such as `mybot_requests_table_missing` points at the database, * while `permission: …` points at the request that never got as far as the handler. * * @var string */ const PERMISSION_PREFIX = 'permission: '; /** * Registers the routes. * * @return void */ public function register() { register_rest_route( MYBOT_REST_NAMESPACE, '/support', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'public_permission' ), 'args' => array( 'question' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', ), 'email' => array( 'required' => true, 'type' => 'string', ), 'name' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), 'phone' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), 'note' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_textarea_field', ), 'answer' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_textarea_field', ), 'session_id' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), 'lang' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_key', ), ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list_requests' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), 'args' => array( 'status' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_key', ), 'limit' => array( 'required' => false, 'type' => 'integer', 'default' => 50, ), ), ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/support/(?P\d+)', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'update_request' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), 'args' => array( 'status' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_key', ), ), ) ); /* * Registered before the `(?P\d+)` pattern can ever be asked to match "test": that route * only accepts digits, so there is no ambiguity — but the probe is declared first anyway, * because "which route wins" should not be something a reader has to verify. */ register_rest_route( MYBOT_REST_NAMESPACE, '/support/test', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'test_route' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), ) ); self::register_failure_capture(); } /** * Records the failures that happen before a handler is ever called. * * 1.6.2 gave every refusal inside the handler a trace, which answered "did my form arrive?" * for four of the five ways this route can refuse. The fifth way is the one that sits in front * of all the others, and it was still silent. * * `public_permission()` verifies the REST nonce. When that check throws — which is what a page * served from cache produces, because `config.nonce` is embedded in the HTML and a cached page * carries the nonce minted when the page was generated — WordPress builds its own `WP_Error` * and returns it from the permission callback. `create()` is never reached, so 1.6.2's trace * was never written, and the Status card went on saying *"Nothing has been sent yet"* while the * visitor was reading an error message. That single blind spot can produce exactly the report * "I filled the form in and nothing was saved anywhere". * * @return void */ public static function register_failure_capture() { add_filter( 'rest_authentication_errors', array( __CLASS__, 'capture_auth_error' ), 100, 3 ); } /** * Writes a trace when a request to the support route was refused before dispatch. * * The error is returned untouched: this observes, it never decides. * * @param WP_Error|null $result Error from an earlier authentication callback. * @param WP_REST_Server $server Server instance. * @param WP_REST_Request $request Request. * @return WP_Error|null The same value that was passed in. */ public static function capture_auth_error( $result, $server = null, $request = null ) { unset( $server ); if ( ! is_wp_error( $result ) || ! $request instanceof WP_REST_Request ) { return $result; } // `/mybot/v1/support/test` also starts with `/mybot/v1/support`, which is intended: the // probe the administrator runs goes through the same front door as the visitor's form. if ( 0 !== strpos( (string) $request->get_route(), '/' . MYBOT_REST_NAMESPACE . '/support' ) ) { return $result; } MYBOT_Requests::record_failed( self::PERMISSION_PREFIX . $result->get_error_code(), $result->get_error_message() ); return $result; } /** * Whether this request passed the public permission check, recording it when it did not. * * Called explicitly at the top of the handler rather than trusting the registered permission * callback: a request that fails a permission check never reaches a handler, so this is the * only place a handler can notice. The check costs one nonce hash, and it buys a trace that * names the exact refusal instead of leaving the reader to guess. * * @param WP_REST_Request $request Request. * @return true|WP_Error True when the request may proceed. */ protected function require_public_permission( $request ) { $allowed = MYBOT_REST_Controller::public_permission( $request ); if ( is_wp_error( $allowed ) ) { MYBOT_Requests::record_failed( self::PERMISSION_PREFIX . $allowed->get_error_code(), $allowed->get_error_message() ); } return $allowed; } /** * Stores a request from a visitor. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function create( $request ) { /* * First, the gate the visitor's request is most likely to fail and the one the Status card * could not see. Doing it here means the reason is written into the trace the administrator * reads, rather than stopping at the permission callback where nothing is recorded. */ $allowed = $this->require_public_permission( $request ); if ( is_wp_error( $allowed ) ) { return $allowed; } $settings = mybot()->settings; if ( ! $settings->get( 'support_enabled', 0 ) ) { $error = new WP_Error( 'mybot_support_disabled', __( 'Leaving a question for a human is switched off on this site.', 'aihouse' ), array( 'status' => 403 ) ); MYBOT_Requests::record_failed( $error->get_error_code(), $error->get_error_message() ); return $error; } $session_id = (string) $request->get_param( 'session_id' ); /* * The visitor cannot be rate limited by IP here the way the chat route does: the widget * has already spent that budget on the question itself. One request per session per few * minutes is enough to stop a loop, and a real visitor who needs to add something has * already been answered by the time they can send again. */ if ( MYBOT_Requests::recent_from_session( $session_id ) ) { $error = new WP_Error( 'mybot_support_duplicate', __( 'A question from this conversation was just sent. Please wait a few minutes before sending another.', 'aihouse' ), array( 'status' => 429 ) ); MYBOT_Requests::record_failed( $error->get_error_code(), $error->get_error_message() ); return $error; } $id = MYBOT_Requests::create( array( 'session_id' => $session_id, 'question' => (string) $request->get_param( 'question' ), 'answer' => (string) $request->get_param( 'answer' ), 'name' => (string) $request->get_param( 'name' ), 'email' => (string) $request->get_param( 'email' ), 'phone' => (string) $request->get_param( 'phone' ), 'note' => (string) $request->get_param( 'note' ), 'lang' => (string) $request->get_param( 'lang' ), ) ); if ( is_wp_error( $id ) ) { MYBOT_Requests::record_failed( $id->get_error_code(), $id->get_error_message() ); return $id; } /* * The moment the row exists is the moment worth recording: it is what turns "I filled the * form and nothing appeared" into "it was saved at 20:41 as request #7, so look again". */ MYBOT_Requests::record_saved( (int) $id ); // Notification failures are recorded on the request itself, never returned to the // visitor: their part is done, and telling them about our mail server helps nobody. MYBOT_Support_Notify::send( (int) $id ); return new WP_REST_Response( array( 'success' => true, 'id' => (int) $id, 'message' => __( 'Thank you. Your question was sent to our team, and we will reply by email.', 'aihouse' ), ), 200 ); } /** * Lists requests for the administrator. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function list_requests( $request ) { $limit = max( 1, min( 200, (int) $request->get_param( 'limit' ) ) ); return new WP_REST_Response( array( 'success' => true, 'counts' => MYBOT_Requests::counts(), 'requests' => MYBOT_Requests::recent( $limit, (string) $request->get_param( 'status' ) ), ), 200 ); } /** * Changes the status of a request. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function update_request( $request ) { $id = (int) $request->get_param( 'id' ); $status = (string) $request->get_param( 'status' ); if ( ! in_array( $status, MYBOT_Requests::STATUSES, true ) ) { return new WP_Error( 'mybot_support_status', __( 'Unknown status.', 'aihouse' ), array( 'status' => 400 ) ); } if ( ! MYBOT_Requests::set_status( $id, $status ) ) { return new WP_Error( 'mybot_support_update', __( 'The request could not be updated.', 'aihouse' ), array( 'status' => 500 ) ); } return new WP_REST_Response( array( 'success' => true, 'id' => $id, 'status' => $status, ), 200 ); } /** * Runs the visitor's path end to end, as a probe the administrator can press. * * Why this exists: "the form did not save anything" has five possible causes (feature off, nonce * refused, duplicate window, missing table, failed insert) and, before this, the only way to * tell them apart was for somebody to fill in the widget and then read a card. That is a * diagnostic that cannot be repeated on demand — which is the situation 3.28 describes. * * The probe writes a real row so the insert is genuinely tested, then deletes it. The row is * marked `status = 'closed'` so that a failure to delete it cannot leave a request looking like * it is waiting for somebody. `recent_from_session()` is skipped by using a session id no * visitor can have, so the five-minute duplicate window cannot make the probe fail. * * The trace is left alone on purpose: the probe must not overwrite the record of what a real * visitor's attempt did. * * @return WP_REST_Response */ public function test_route() { global $wpdb; $settings = mybot()->settings; $steps = array(); if ( ! $settings->get( 'support_enabled', 0 ) ) { $steps[] = array( 'step' => 'setting', 'ok' => false, 'message' => __( 'Leaving a question for a human is switched off on this site.', 'aihouse' ), ); return new WP_REST_Response( array( 'success' => false, 'steps' => $steps, ), 200 ); } $steps[] = array( 'step' => 'setting', 'ok' => true, 'message' => __( 'The feature is switched on.', 'aihouse' ), ); if ( ! MYBOT_Requests::table_exists() ) { $steps[] = array( 'step' => 'table', 'ok' => false, 'message' => __( 'The requests table does not exist. Deactivate and activate the plugin once so the database upgrade can create it.', 'aihouse' ), ); return new WP_REST_Response( array( 'success' => false, 'steps' => $steps, ), 200 ); } $steps[] = array( 'step' => 'table', 'ok' => true, 'message' => sprintf( /* translators: %s: database table name */ __( 'The table exists: %s', 'aihouse' ), MYBOT_Requests::table() ), ); $probe_session = 'mybot-probe-' . wp_generate_password( 12, false, false ); $id = MYBOT_Requests::create( array( 'session_id' => $probe_session, 'question' => __( 'Test of the hand-over path. This row is deleted immediately.', 'aihouse' ), 'answer' => '', 'name' => __( 'Test (AI House)', 'aihouse' ), 'email' => (string) get_option( 'admin_email' ), 'phone' => '', 'note' => '', 'lang' => '', ) ); if ( is_wp_error( $id ) ) { $steps[] = array( 'step' => 'insert', 'ok' => false, 'message' => $id->get_error_message(), 'code' => $id->get_error_code(), ); return new WP_REST_Response( array( 'success' => false, 'steps' => $steps, ), 200 ); } $id = (int) $id; $steps[] = array( 'step' => 'insert', 'ok' => true, 'message' => sprintf( /* translators: %d: request ID */ __( 'A row was written and read back as request #%d, so saving works.', 'aihouse' ), $id ), ); $stored = MYBOT_Requests::find( $id ); $steps[] = array( 'step' => 'read', 'ok' => is_array( $stored ), 'message' => is_array( $stored ) ? __( 'The row can be read back from the table.', 'aihouse' ) : __( 'The row was written but cannot be read back.', 'aihouse' ), ); // Notifications are not sent for the probe: MYBOT_Support_Notify::send() is deliberately // not called, so testing the path cannot email the shop owner a fake question. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $deleted = $wpdb->delete( MYBOT_Requests::table(), array( 'id' => $id ), array( '%d' ) ); $steps[] = array( 'step' => 'cleanup', 'ok' => false !== $deleted, 'message' => false !== $deleted ? __( 'The test row was deleted again.', 'aihouse' ) : sprintf( /* translators: %d: request ID */ __( 'The test row could not be deleted. Remove request #%d by hand.', 'aihouse' ), $id ), ); return new WP_REST_Response( array( 'success' => true, 'steps' => $steps, ), 200 ); } }