repository = $repository; } public function enqueue($entry_id, $action, $route, $payload, $max_attempts = 3) { global $wpdb; $entry_id = absint($entry_id); if (!$this->repository->get_entry($entry_id)) { return new \WP_Error('ssffw_no_entry', __('The submission no longer exists.', 'ssf-forms')); } $action = substr(sanitize_key($action), 0, 64); $route = substr(sanitize_text_field($route), 0, 190); if (!$action || !$route || !is_array($payload) || strlen(wp_json_encode($payload)) > 524288) { return new \WP_Error( 'ssffw_action_invalid', __('The workflow action is invalid.', 'ssf-forms'), ); } $key = hash('sha256', $entry_id . '|' . $action . '|' . $route); $table = $this->repository->table('actions'); $existing = $wpdb->get_row( $wpdb->prepare('SELECT * FROM %i WHERE action_key = %s', $table, $key), ARRAY_A, ); if ($existing) { return $this->decode($existing); } $now = current_time('mysql', true); $prior_suppress = $wpdb->suppress_errors(true); $inserted = $wpdb->insert($table, [ 'entry_id' => $entry_id, 'action' => $action, 'route' => $route, 'action_key' => $key, 'payload_json' => wp_json_encode($payload), 'status' => 'queued', 'attempts' => 0, 'max_attempts' => min(5, max(1, absint($max_attempts))), 'last_error' => '', 'next_attempt_at' => $now, 'created_at' => $now, 'updated_at' => $now, ]); $wpdb->suppress_errors($prior_suppress); $row = $wpdb->get_row( $wpdb->prepare('SELECT * FROM %i WHERE action_key = %s', $table, $key), ARRAY_A, ); return $row ? $this->decode($row) : new \WP_Error('ssffw_action_storage', __('The workflow could not be queued.', 'ssf-forms')); } public function list_for_entry($id) { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE entry_id = %d ORDER BY id ASC', $this->repository->table('actions'), absint($id), ), ARRAY_A, ); return array_map([$this, 'decode'], $rows ?: []); } public function get($id) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $this->repository->table('actions'), absint($id), ), ARRAY_A, ); return $row ? $this->decode($row) : null; } public function decode($row) { foreach (['id', 'entry_id', 'attempts', 'max_attempts'] as $key) { $row[$key] = (int) $row[$key]; } $row['payload'] = json_decode($row['payload_json'], true) ?: []; unset($row['payload_json'], $row['action_key']); return $row; } public function retry($id, $acknowledge_uncertain = false) { global $wpdb; if (!current_user_can('manage_options')) { return new \WP_Error( 'ssffw_forbidden', __('You cannot retry workflow actions.', 'ssf-forms'), [ 'status' => 403, ], ); } $action = $this->get($id); if (!$action || !$this->repository->get_entry($action['entry_id'])) { return new \WP_Error('ssffw_not_found', __('Workflow action not found.', 'ssf-forms'), [ 'status' => 404, ]); } if (in_array($action['status'], ['accepted', 'processing'], true)) { return new \WP_Error( 'ssffw_retry_conflict', __('An accepted or processing action cannot be retried.', 'ssf-forms'), ['status' => 409], ); } if ($action['status'] === 'uncertain' && !$acknowledge_uncertain) { return new \WP_Error( 'ssffw_uncertain', __( 'The previous outcome is unknown. Verify the destination before explicitly acknowledging a retry.', 'ssf-forms', ), ['status' => 409], ); } $now = current_time('mysql', true); $wpdb->update( $this->repository->table('actions'), [ 'status' => 'queued', 'attempts' => 0, 'last_error' => '', 'next_attempt_at' => $now, 'updated_at' => $now, ], ['id' => $action['id'], 'status' => $action['status']], ); return $this->get($id); } public function process($limit = 10) { global $wpdb; $limit = min(50, max(1, absint($limit))); $table = $this->repository->table('actions'); $now = current_time('mysql', true); $stale = gmdate('Y-m-d H:i:s', time() - 600); // An interrupted transport may already have accepted its message. Never automatically resend it. $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'uncertain', last_error = %s, updated_at = %s WHERE status = 'processing' AND updated_at < %s", $table, __( 'The previous worker ended without a confirmed outcome. Check the destination before retrying.', 'ssf-forms', ), $now, $stale, ), ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE status IN ('queued','retry') AND next_attempt_at <= %s ORDER BY id ASC LIMIT %d", $table, $now, $limit, ), ARRAY_A, ); $summary = ['processed' => 0, 'accepted' => 0, 'failed' => 0, 'retrying' => 0]; foreach ($rows ?: [] as $row) { $claimed = $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'processing', attempts = attempts + 1, updated_at = %s WHERE id = %d AND status = %s AND attempts = %d", $table, $now, $row['id'], $row['status'], $row['attempts'], ), ); if ($claimed !== 1) { continue; } $action = $this->get($row['id']); $entry = $this->repository->get_entry($action['entry_id']); if (!$entry) { $wpdb->delete($table, ['id' => $action['id']], ['%d']); continue; } $summary['processed']++; try { if ($action['action'] === 'mail') { $result = $this->mail($action); } else { $result = apply_filters('ssffw_execute_action', null, $action, $entry); if ($result === null) { $result = new \WP_Error( 'ssffw_missing_handler', __('The required workflow extension is unavailable.', 'ssf-forms'), ['retryable' => false], ); } } } catch (\Throwable $error) { $result = new \WP_Error( 'ssffw_workflow_exception', __( 'The workflow could not complete. Review its configuration before retrying.', 'ssf-forms', ), ['retryable' => false], ); } $accepted = $result === true || (is_array($result) && ($result['status'] ?? '') === 'accepted'); if ($accepted) { $state = [ 'status' => 'accepted', 'last_error' => '', 'updated_at' => current_time('mysql', true), ]; $summary['accepted']++; } else { $retryable = true; $message = __('The workflow destination did not accept the request.', 'ssf-forms'); if (is_wp_error($result)) { $message = sanitize_text_field($result->get_error_message()); $details = $result->get_error_data(); if (is_array($details) && array_key_exists('retryable', $details)) { $retryable = (bool) $details['retryable']; } } $again = $retryable && $action['attempts'] < $action['max_attempts']; $state = [ 'status' => $again ? 'retry' : 'failed', 'last_error' => substr($message, 0, 1000), 'updated_at' => current_time('mysql', true), 'next_attempt_at' => gmdate( 'Y-m-d H:i:s', time() + min(3600, 60 * 2 ** max(0, $action['attempts'] - 1)), ), ]; $summary[$again ? 'retrying' : 'failed']++; } $wpdb->update($table, $state, ['id' => $action['id'], 'status' => 'processing']); } return $summary; } private function mail($action) { $payload = $action['payload']; $recipients = ssffw()->validator->recipients($payload['to'] ?? []); if (is_wp_error($recipients) || !$recipients) { return new \WP_Error( 'ssffw_mail_config', __('Notification recipients need administrator attention.', 'ssf-forms'), ['retryable' => false], ); } $subject = str_replace( ["\r", "\n"], '', sanitize_text_field($payload['subject'] ?? __('Form submission', 'ssf-forms')), ); $accepted = wp_mail($recipients, $subject, (string) ($payload['body'] ?? ''), [ 'Content-Type: text/plain; charset=UTF-8', ]); return $accepted ? true : new \WP_Error( 'ssffw_mail_rejected', __( 'The WordPress mail transport did not accept the message. Review SMTP settings.', 'ssf-forms', ), ['retryable' => true], ); } }