validator = $validator; } public function table($name) { global $wpdb; return $wpdb->prefix . 'ssffw_' . $name; } public function list_forms($args = []) { global $wpdb; $table = $this->table('forms'); $status = in_array($args['status'] ?? '', ['draft', 'publish'], true) ? $args['status'] : ''; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE (%s = '' OR status = %s) ORDER BY updated_at DESC, id DESC LIMIT 1000", $table, $status, $status, ), ARRAY_A, ); return array_map([$this, 'decode_form'], $rows ?: []); } public function get_form($id) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare('SELECT * FROM %i WHERE id = %d', $this->table('forms'), absint($id)), ARRAY_A, ); return $row ? $this->decode_form($row) : null; } public function decode_form($row) { $form = json_decode($row['schema_json'], true); if (!is_array($form)) { $form = ['fields' => [], 'settings' => []]; } $form['id'] = (int) $row['id']; $form['title'] = $row['title']; $form['status'] = $row['status']; $form['version'] = (int) $row['version']; $form['created_at'] = $row['created_at']; $form['updated_at'] = $row['updated_at']; return $form; } public function save_form($schema, $id = 0) { global $wpdb; if (!current_user_can('manage_options')) { return $this->denied(); } $existing = $id ? $this->get_form($id) : null; if ($id && !$existing) { return new \WP_Error('ssffw_not_found', __('Form not found.', 'ssf-forms'), [ 'status' => 404, ]); } if ( $existing && isset($schema['version']) && (int) $schema['version'] !== (int) $existing['version'] ) { return new \WP_Error( 'ssffw_conflict', __('This form changed in another window. Reload it before saving.', 'ssf-forms'), ['status' => 409], ); } $form = $this->validator->schema($schema); if (is_wp_error($form)) { return $form; } $form['id'] = (int) $id; $form['version'] = $existing ? $existing['version'] + 1 : 1; $now = current_time('mysql', true); $data = [ 'title' => $form['title'], 'status' => $form['status'], 'version' => $form['version'], 'schema_json' => wp_json_encode($form), 'updated_at' => $now, ]; if ($existing) { $success = $wpdb->update($this->table('forms'), $data, [ 'id' => (int) $id, 'version' => $existing['version'], ]); if ($success === 0) { return new \WP_Error( 'ssffw_conflict', __('This form changed in another window. Reload it before saving.', 'ssf-forms'), ['status' => 409], ); } } else { $data['created_at'] = $now; $success = $wpdb->insert($this->table('forms'), $data); $id = (int) $wpdb->insert_id; } if ($success === false) { return $this->storage_error(); } return $this->get_form($id); } public function delete_form($id) { global $wpdb; if (!current_user_can('manage_options')) { return $this->denied(); } $form = $this->get_form($id); if (!$form) { return new \WP_Error('ssffw_not_found', __('Form not found.', 'ssf-forms'), [ 'status' => 404, ]); } $old_version = $form['version']; $form['status'] = 'draft'; $form['version']++; $success = $wpdb->update( $this->table('forms'), [ 'status' => 'draft', 'version' => $form['version'], 'schema_json' => wp_json_encode($form), 'updated_at' => current_time('mysql', true), ], ['id' => absint($id), 'version' => $old_version], ); if ($success === 0) { return new \WP_Error( 'ssffw_conflict', __('This form changed in another window. Reload it before unpublishing.', 'ssf-forms'), ['status' => 409], ); } return $success === false ? $this->storage_error() : $this->get_form($id); } public function list_entries($args = []) { global $wpdb; $page = max(1, absint($args['page'] ?? 1)); $per_page = min(100, max(1, absint($args['per_page'] ?? 20))); $form_id = absint($args['form_id'] ?? 0); $search = substr(sanitize_text_field($args['search'] ?? ''), 0, 200); $like = '%' . $wpdb->esc_like($search) . '%'; $table = $this->table('entries'); $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE (%d = 0 OR form_id = %d) AND (%s = '' OR values_json LIKE %s OR submission_id LIKE %s)", $table, $form_id, $form_id, $search, $like, $like, ), ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE (%d = 0 OR form_id = %d) AND (%s = '' OR values_json LIKE %s OR submission_id LIKE %s) ORDER BY id DESC LIMIT %d OFFSET %d", $table, $form_id, $form_id, $search, $like, $like, $per_page, ($page - 1) * $per_page, ), ARRAY_A, ); return [ 'items' => array_map([$this, 'decode_entry'], $rows ?: []), 'total' => $total, 'page' => $page, 'per_page' => $per_page, ]; } public function get_entry($id) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare('SELECT * FROM %i WHERE id = %d', $this->table('entries'), absint($id)), ARRAY_A, ); return $row ? $this->decode_entry($row) : null; } public function decode_entry($row) { foreach (['id', 'form_id', 'schema_version'] as $key) { $row[$key] = (int) $row[$key]; } $row['values'] = json_decode($row['values_json'], true) ?: []; $row['schema'] = json_decode($row['schema_json'], true) ?: []; $row['form_title'] = $row['schema']['title'] ?? __('Form', 'ssf-forms'); unset($row['values_json'], $row['schema_json'], $row['submission_key'], $row['payload_hash']); return $row; } public function delete_entry($id, $trusted = false) { global $wpdb; if (!$trusted && !current_user_can('manage_options')) { return $this->denied(); } $id = absint($id); if (!$this->get_entry($id)) { return new \WP_Error('ssffw_not_found', __('Submission not found.', 'ssf-forms'), [ 'status' => 404, ]); } $wpdb->query('START TRANSACTION'); $actions = $wpdb->delete($this->table('actions'), ['entry_id' => $id], ['%d']); $success = $wpdb->delete($this->table('entries'), ['id' => $id], ['%d']); if ($success === false || $actions === false) { $wpdb->query('ROLLBACK'); return $this->storage_error(); } try { do_action('ssffw_entry_deleted', $id); } catch (\Throwable $error) { $wpdb->query('ROLLBACK'); return new \WP_Error( 'ssffw_erase_extension', __( 'The submission could not be fully erased. Review its optional workflow storage.', 'ssf-forms', ), ['status' => 503], ); } if ($wpdb->query('COMMIT') === false) { $wpdb->query('ROLLBACK'); return $this->storage_error(); } return true; } public function submit($form_id, $values, $context = []) { global $wpdb; $form = $this->get_form($form_id); if (!$form || $form['status'] !== 'publish') { return new \WP_Error('ssffw_unavailable', __('This form is not available.', 'ssf-forms'), [ 'status' => 404, ]); } $submission_id = $context['submission_id'] ?? ''; if (!is_string($submission_id)) { return new \WP_Error( 'ssffw_submission_id', __('Refresh the form and try again.', 'ssf-forms'), [ 'status' => 400, ], ); } if ( !preg_match('/^[A-Za-z0-9_-]{32,128}$/D', str_replace('-', '', $submission_id)) || strlen($submission_id) > 128 ) { return new \WP_Error( 'ssffw_submission_id', __('Refresh the form and try again.', 'ssf-forms'), [ 'status' => 400, ], ); } if (!is_array($values) || strlen(wp_json_encode($values)) > 262144) { return new \WP_Error('ssffw_size', __('This submission is too large.', 'ssf-forms'), [ 'status' => 413, ]); } $key = hash('sha256', $submission_id); $hash = hash('sha256', wp_json_encode(self::canonical($values))); $existing = $this->existing_submission($form['id'], $key); if ($existing) { return $this->duplicate_result($existing, $hash); } $context['submission_id'] = $submission_id; $normalized = $this->validator->submission($form, $values, $context); if (is_wp_error($normalized)) { return $normalized; } $context = $this->validator->submission_context($context, $normalized); if (strlen(wp_json_encode($normalized)) > 262144) { return new \WP_Error('ssffw_size', __('This submission is too large.', 'ssf-forms'), [ 'status' => 413, ]); } $recipients = []; $mail_error = null; if (!empty($form['settings']['notification_enabled'])) { try { $recipients = apply_filters( 'ssffw_mail_recipients', $form['settings']['notification_to'] ?? '', $form, $normalized, ); } catch (\Throwable $error) { $recipients = new \WP_Error( 'ssffw_mail_config', __('Notification routing needs administrator attention.', 'ssf-forms'), ); } $recipients = is_wp_error($recipients) ? $recipients : $this->validator->recipients($recipients); if (is_wp_error($recipients) || !$recipients) { $mail_error = __('Notification recipients need administrator attention.', 'ssf-forms'); $recipients = []; } } $now = current_time('mysql', true); $wpdb->query('START TRANSACTION'); $prior_suppress = $wpdb->suppress_errors(true); $inserted = $wpdb->insert($this->table('entries'), [ 'form_id' => $form['id'], 'submission_id' => $submission_id, 'submission_key' => $key, 'payload_hash' => $hash, 'schema_version' => $form['version'], 'schema_json' => wp_json_encode($form), 'values_json' => wp_json_encode($normalized), 'status' => 'accepted', 'created_at' => $now, ]); $entry_id = (int) $wpdb->insert_id; $wpdb->suppress_errors($prior_suppress); if (!$inserted) { $wpdb->query('ROLLBACK'); $existing = $this->existing_submission($form['id'], $key); return $existing ? $this->duplicate_result($existing, $hash) : $this->storage_error(); } if ($recipients || $mail_error) { $subject = str_replace( ['{form_title}', '{submission_id}'], [$form['title'], $submission_id], $form['settings']['notification_subject'] ?? __('New form submission', 'ssf-forms'), ); $body = __('A submission was saved to ', 'ssf-forms') . $form['title'] . ".\nReference: " . $submission_id . "\n\n"; foreach ($form['fields'] as $field) { if (!array_key_exists($field['id'], $normalized)) { continue; } $answer = $normalized[$field['id']]; $body .= $field['label'] . ': ' . (is_scalar($answer) || $answer === null ? (is_bool($answer) ? ($answer ? __('Yes', 'ssf-forms') : __('No', 'ssf-forms')) : (string) $answer) : wp_json_encode($answer)) . "\n"; } $action = ssffw()->queue->enqueue($entry_id, 'mail', 'notification', [ 'to' => $recipients, 'subject' => $subject, 'body' => $body, ]); if (is_wp_error($action)) { $wpdb->query('ROLLBACK'); return $this->storage_error(); } if ($mail_error) { $wpdb->update( $this->table('actions'), ['status' => 'failed', 'last_error' => $mail_error], ['id' => $action['id']], ); } } if ($wpdb->query('COMMIT') === false) { $wpdb->query('ROLLBACK'); return $this->storage_error(); } try { do_action('ssffw_after_submit', $entry_id, $form, $normalized, $context); } catch (\Throwable $error) { $receipt = ssffw()->queue->enqueue($entry_id, 'extension', 'after-submit', []); if (!is_wp_error($receipt)) { $wpdb->update( $this->table('actions'), [ 'status' => 'failed', 'last_error' => __( 'An optional workflow could not be queued. The submission remains saved.', 'ssf-forms', ), ], ['id' => $receipt['id']], ); } } return [ 'id' => $entry_id, 'submission_id' => $submission_id, 'status' => 'accepted', 'duplicate' => false, ]; } private function existing_submission($form_id, $key) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT id,submission_id,status,payload_hash FROM %i WHERE form_id = %d AND submission_key = %s', $this->table('entries'), $form_id, $key, ), ARRAY_A, ); } private function duplicate_result($row, $hash) { if (!hash_equals($row['payload_hash'], $hash)) { return new \WP_Error( 'ssffw_submission_conflict', __( 'This submission reference was already used for different answers. Start a new submission.', 'ssf-forms', ), ['status' => 409], ); } return [ 'id' => (int) $row['id'], 'submission_id' => $row['submission_id'], 'status' => $row['status'], 'duplicate' => true, ]; } public static function canonical($value) { if (!is_array($value)) { return $value; } if ($value && array_keys($value) !== range(0, count($value) - 1)) { ksort($value, SORT_STRING); } foreach ($value as &$child) { $child = self::canonical($child); } return $value; } private function denied() { return new \WP_Error('ssffw_forbidden', __('You cannot manage these forms.', 'ssf-forms'), [ 'status' => 403, ]); } private function storage_error() { return new \WP_Error( 'ssffw_storage', __( 'The submission could not be saved. Please try again using the same submission reference.', 'ssf-forms', ), ['status' => 503], ); } }