plugin = $plugin; } public function register() { add_action('rest_api_init', [$this, 'routes']); add_filter('rest_pre_serve_request', [$this, 'serve_export'], 10, 4); } public function routes() { $private = [$this, 'can_manage']; register_rest_route('ssffw/v1', '/forms', [ [ 'methods' => 'GET', 'callback' => function ($r) { return $this->plugin->repository->list_forms(['status' => $r->get_param('status')]); }, 'permission_callback' => $private, ], [ 'methods' => 'POST', 'callback' => function ($r) { return $this->plugin->repository->save_form($this->body($r)); }, 'permission_callback' => $private, ], ]); register_rest_route('ssffw/v1', '/forms/(?P\d+)', [ ['methods' => 'GET', 'callback' => [$this, 'get_form'], 'permission_callback' => $private], [ 'methods' => 'PUT,PATCH', 'callback' => function ($r) { return $this->plugin->repository->save_form($this->body($r), absint($r['id'])); }, 'permission_callback' => $private, ], [ 'methods' => 'DELETE', 'callback' => function ($r) { return $this->plugin->repository->delete_form(absint($r['id'])); }, 'permission_callback' => $private, ], ]); register_rest_route('ssffw/v1', '/forms/import', [ 'methods' => 'POST', 'callback' => [$this, 'import_form'], 'permission_callback' => $private, ]); register_rest_route('ssffw/v1', '/forms/(?P\d+)/submit', [ 'methods' => 'POST', 'callback' => [$this, 'submit'], 'permission_callback' => '__return_true', ]); register_rest_route('ssffw/v1', '/entries', [ 'methods' => 'GET', 'callback' => function ($r) { return $this->plugin->repository->list_entries($r->get_params()); }, 'permission_callback' => $private, ]); register_rest_route('ssffw/v1', '/entries/(?P\d+)', [ ['methods' => 'GET', 'callback' => [$this, 'get_entry'], 'permission_callback' => $private], [ 'methods' => 'DELETE', 'callback' => function ($r) { $result = $this->plugin->repository->delete_entry(absint($r['id'])); return is_wp_error($result) ? $result : ['deleted' => true]; }, 'permission_callback' => $private, ], ]); register_rest_route('ssffw/v1', '/entries/export', [ 'methods' => 'GET', 'callback' => [$this, 'export_entries'], 'permission_callback' => $private, ]); register_rest_route('ssffw/v1', '/actions/(?P\d+)/retry', [ 'methods' => 'POST', 'callback' => function ($r) { return $this->plugin->queue->retry( absint($r['id']), $r->get_param('acknowledge_uncertain') === true, ); }, 'permission_callback' => $private, ]); register_rest_route('ssffw/v1', '/actions/process', [ 'methods' => 'POST', 'callback' => function () { return $this->plugin->queue->process(10); }, 'permission_callback' => $private, ]); } public function can_manage($request) { if (!is_user_logged_in() || !current_user_can('manage_options')) { return new \WP_Error('ssffw_forbidden', __('You cannot manage these forms.', 'ssf-forms'), [ 'status' => 403, ]); } $nonce = $request->get_header('X-WP-Nonce') ?: $request->get_param('_wpnonce'); $nonce = is_string($nonce) ? sanitize_text_field($nonce) : ''; if (!$nonce || !wp_verify_nonce($nonce, 'wp_rest')) { return new \WP_Error( 'ssffw_rest_nonce', __('Refresh this page before managing forms.', 'ssf-forms'), [ 'status' => 403, ], ); } return true; } private function body($request) { $body = $request->get_json_params(); if (!is_array($body)) { $body = $request->get_body_params(); } if (isset($body['form']) && is_array($body['form'])) { return $body['form']; } if (isset($body['schema']) && is_array($body['schema'])) { return $body['schema']; } return is_array($body) ? $body : []; } public function get_form($request) { $form = $this->plugin->repository->get_form(absint($request['id'])); if (!$form) { return new \WP_Error('ssffw_not_found', __('Form not found.', 'ssf-forms'), [ 'status' => 404, ]); } if ($request->get_param('export')) { return [ 'plugin' => 'ssf-forms', 'version' => SSFFW_VERSION, 'form' => $this->plugin->validator->export_form($form), ]; } return $form; } public function import_form($request) { if (strlen((string) $request->get_body()) > 524288) { return new \WP_Error( 'ssffw_import_size', __('The form configuration is too large.', 'ssf-forms'), [ 'status' => 413, ], ); } $schema = $this->body($request); if (!$schema) { return new \WP_Error( 'ssffw_import_invalid', __('Choose a valid SSF form configuration.', 'ssf-forms'), [ 'status' => 400, ], ); } $schema = $this->plugin->validator->export_form($schema); return $this->plugin->repository->save_form($schema); } public function get_entry($request) { $entry = $this->plugin->repository->get_entry(absint($request['id'])); if (!$entry) { return new \WP_Error('ssffw_not_found', __('Submission not found.', 'ssf-forms'), [ 'status' => 404, ]); } $entry['actions'] = $this->plugin->queue->list_for_entry($entry['id']); $entry['extension_actions'] = apply_filters('ssffw_entry_actions', [], $entry); return $entry; } public function submit($request) { $id = absint($request['id']); $form = $this->plugin->repository->get_form($id); if (!$form || $form['status'] !== 'publish') { return new \WP_Error('ssffw_unavailable', __('This form is not available.', 'ssf-forms'), [ 'status' => 404, ]); } $nonce = $request->get_param('form_nonce'); $nonce = is_string($nonce) ? sanitize_text_field($nonce) : ''; if (!$nonce || !wp_verify_nonce($nonce, 'ssffw_submit_' . $id)) { return new \WP_Error( 'ssffw_form_nonce', __('This form has expired. Refresh the page and try again.', 'ssf-forms'), ['status' => 403], ); } if ($request->get_param('website') !== null && $request->get_param('website') !== '') { return new \WP_Error( 'ssffw_rejected', __('The submission could not be accepted.', 'ssf-forms'), [ 'status' => 400, ], ); } if (strlen((string) $request->get_body()) > 1048576) { return new \WP_Error('ssffw_size', __('This submission is too large.', 'ssf-forms'), [ 'status' => 413, ]); } if ($request->get_file_params()) { return new \WP_Error( 'ssffw_upload_flow', __('Use the private upload control before submitting this form.', 'ssf-forms'), ['status' => 400], ); } if (!$this->allow_request($id)) { return new \WP_Error( 'ssffw_rate_limit', __('Too many attempts. Wait a few minutes before trying again.', 'ssf-forms'), ['status' => 429], ); } $values = $request->get_param('values'); if (is_string($values)) { $values = json_decode($values, true); } if (!is_array($values)) { return new \WP_Error('ssffw_values', __('The submitted values are invalid.', 'ssf-forms'), [ 'status' => 400, ]); } $result = $this->plugin->repository->submit($id, $values, [ 'submission_id' => $request->get_param('submission_id'), 'request' => $request, 'user_id' => get_current_user_id(), ]); if (!is_wp_error($result)) { $result['message'] = $form['settings']['success_message'] ?? __('Your submission has been saved.', 'ssf-forms'); } return $result; } private function allow_request($form_id) { global $wpdb; $limit = max(1, min(1000, (int) apply_filters('ssffw_rate_limit', 20, $form_id))); $window = 600; $ip = isset($_SERVER['REMOTE_ADDR']) && is_string($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : ''; $ip = filter_var($ip, FILTER_VALIDATE_IP) ?: 'unknown'; $key = hash_hmac( 'sha256', $form_id . '|' . $ip . '|' . (int) floor(time() / $window), wp_salt('nonce'), ); $table = $this->plugin->repository->table('rates'); $updated = $wpdb->query( $wpdb->prepare('UPDATE %i SET hits = hits + 1 WHERE rate_key = %s', $table, $key), ); if ($updated === 0) { $prior_suppress = $wpdb->suppress_errors(true); $insert = $wpdb->insert($table, [ 'rate_key' => $key, 'hits' => 1, 'expires_at' => time() + $window * 2, ]); $wpdb->suppress_errors($prior_suppress); if (!$insert) { $wpdb->query( $wpdb->prepare('UPDATE %i SET hits = hits + 1 WHERE rate_key = %s', $table, $key), ); } } if ($updated === false) { return false; } $hits = $wpdb->get_var($wpdb->prepare('SELECT hits FROM %i WHERE rate_key = %s', $table, $key)); return is_numeric($hits) && (int) $hits <= $limit; } public function export_entries($request) { $args = $request->get_params(); $args['per_page'] = 100; $args['page'] = 1; $batch = $this->plugin->repository->list_entries($args); if ($batch['total'] > 10000) { return new \WP_Error( 'ssffw_export_size', __( 'Export up to 10,000 matching entries at once. Select a form or search to narrow this export.', 'ssf-forms', ), ['status' => 413], ); } $entries = $batch['items']; while (count($entries) < $batch['total']) { $args['page']++; $next = $this->plugin->repository->list_entries($args); if (!$next['items']) { break; } $entries = array_merge($entries, $next['items']); } $format = $request->get_param('format') === 'json' ? 'json' : 'csv'; if ($format === 'json') { $body = wp_json_encode( ['plugin' => 'ssf-forms', 'exported_at_utc' => gmdate('c'), 'entries' => $entries], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE, ); } else { $fields = []; foreach ($entries as $entry) { foreach (array_keys($entry['values']) as $field) { $fields[$field] = true; } } $columns = array_merge( ['id', 'form_id', 'form_title', 'submission_id', 'schema_version', 'created_at', 'status'], array_map(static function ($id) { return 'field:' . $id; }, array_keys($fields)), ); $stream = fopen('php://temp', 'w+'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Bounded CSV memory/temp stream, not persistent plugin-directory storage. fputcsv($stream, array_map([__CLASS__, 'csv_cell'], $columns), ',', '"', ''); foreach ($entries as $entry) { $row = []; foreach ($columns as $column) { $row[] = self::csv_cell( strpos($column, 'field:') === 0 ? $entry['values'][substr($column, 6)] ?? '' : $entry[$column] ?? '', ); } fputcsv($stream, $row, ',', '"', ''); } rewind($stream); $body = stream_get_contents($stream); fclose($stream); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Close the CSV memory/temp stream. } if (strlen($body) > 16777216) { return new \WP_Error( 'ssffw_export_size', __('This export exceeds 16 MB. Select a form or search to narrow the export.', 'ssf-forms'), ['status' => 413], ); } $response = new \WP_REST_Response($body); $response->header( 'Content-Type', $format === 'json' ? 'application/json; charset=UTF-8' : 'text/csv; charset=UTF-8', ); $response->header( 'Content-Disposition', 'attachment; filename="ssf-form-entries-' . gmdate('Y-m-d-His') . '.' . $format . '"', ); $response->header('Cache-Control', 'no-store, private'); $response->header('X-Content-Type-Options', 'nosniff'); $response->header('X-SSFFW-Raw', '1'); return $response; } public static function csv_cell($value) { if (is_array($value) || is_object($value)) { $value = wp_json_encode($value); } if (is_bool($value)) { $value = $value ? __('Yes', 'ssf-forms') : __('No', 'ssf-forms'); } $value = (string) $value; if (preg_match('/^\s*[=+\-@]/u', $value)) { $value = "'" . $value; } return $value; } public function serve_export($served, $result, $request, $server) { if ( strpos($request->get_route(), '/ssffw/v1/') !== 0 || !($result instanceof \WP_REST_Response) ) { return $served; } $headers = $result->get_headers(); if (($headers['X-SSFFW-Raw'] ?? '') !== '1') { return $served; } echo $result->get_data(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Authorized CSV/JSON attachment with fixed MIME, nosniff and no-store headers; HTML escaping would corrupt exported answers. return true; } }