0.01, 'blocking' => false, /** This filter is documented in WordPress Core wp-includes/class-wp-http-streams.php */ 'sslverify' => apply_filters('https_local_ssl_verify', false), 'body' => [ 'nonce' => wp_create_nonce($this->nonce_action_for_task($task)), 'action' => self::ADMIN_POST_ACTION, 'task' => $task, 'args' => json_encode($args), ], 'headers' => [ 'cookie' => implode('; ', $this->get_cookies()), ], ]; $logger = new AmazonAI_Logger(); $logger->log(sprintf('%s Triggering background task %s', __METHOD__, $task)); return wp_remote_post($url, $request_args); } /** * Run task as a WP action * * @see https://developer.wordpress.org/reference/functions/__/ Localize string * @see https://developer.wordpress.org/reference/functions/do_action_ref_array/ Run action * @see https://developer.wordpress.org/reference/functions/wp_die/ Kill request and display message * @see https://developer.wordpress.org/reference/functions/wp_verify_nonce/ Verify cryptographic token */ public function run() { $task = (array_key_exists('task', $_POST)) ? trim($_POST['task']) : ''; $args = (array_key_exists('args', $_POST)) ? json_decode($_POST['args']) : []; if ( empty($task) ) { error_log(sprintf('%s Invalid background task. Missing task.', __METHOD__)); wp_die(__('Invalid background task.', 'amazon-polly'), 'Invalid Request', 400); } if ( ! is_array($args) ) { error_log(sprintf('%s Invalid background task args.', __METHOD__)); wp_die(__('Invalid background task args.', 'amazon-polly'), 'Invalid Request', 400); } if ( ! isset($_POST['nonce']) || 1 !== wp_verify_nonce($_POST['nonce'], $this->nonce_action_for_task($task)) ) { error_log(sprintf('%s Expired background task request for task %s', __METHOD__, $task)); wp_die(__('Expired background task request.', 'amazon-polly'), 'Expired Request', 403); } $logger = new AmazonAI_Logger(); $logger->log(sprintf('%s Running background task %s', __METHOD__, $task)); /** * Fires when running a background task * * The dynamic portion of the hook name, `$task`, refers to the task * that being run. */ do_action_ref_array(sprintf('amazon_polly_background_task_%s', $task), $args); } /** * Return current user's cookies to authenticate a background request as the current user * * @return array Sanitized cookies */ private function get_cookies() { $cookies = []; foreach ( $_COOKIE as $name => $value ) { $sanitized_value = is_array($value) ? serialize($value) : $value; $sanitized_value = urlencode($sanitized_value); $cookies[] = sprintf("%s=%s", $name, $sanitized_value); } return $cookies; } /** * Generate nonce action name for task * * @param $task * * @return string */ private function nonce_action_for_task($task) { return sprintf('%s:%s', self::ADMIN_POST_ACTION, $task); } }