WP_Async_Request.php
63 lines
| 1 | <?php |
| 2 | if (!defined('ABSPATH')) exit; |
| 3 | if ( ! class_exists( 'WP_Async_Request' ) ) { |
| 4 | abstract class WP_Async_Request { |
| 5 | protected $prefix = 'wp'; |
| 6 | protected $action = 'async_request'; |
| 7 | protected $identifier; |
| 8 | protected $data = array(); |
| 9 | public function __construct() { |
| 10 | $this->identifier = $this->prefix . '_' . $this->action; |
| 11 | add_action( 'wp_ajax_' . $this->identifier, array( $this, 'maybe_handle' ) ); |
| 12 | add_action( 'wp_ajax_nopriv_' . $this->identifier, array( $this, 'maybe_handle' ) ); |
| 13 | } |
| 14 | public function data( $data ) { |
| 15 | $this->data = $data; |
| 16 | return $this; |
| 17 | } |
| 18 | public function dispatch() { |
| 19 | $url = add_query_arg( $this->get_query_args(), $this->get_query_url() ); |
| 20 | $args = $this->get_post_args(); |
| 21 | return wp_remote_post( esc_url_raw( $url ), $args ); |
| 22 | } |
| 23 | protected function get_query_args() { |
| 24 | if ( property_exists( $this, 'query_args' ) ) { |
| 25 | return $this->query_args; |
| 26 | } |
| 27 | $args = array( |
| 28 | 'action' => $this->identifier, |
| 29 | 'nonce' => wp_create_nonce( $this->identifier ), |
| 30 | ); |
| 31 | return apply_filters( $this->identifier . '_query_args', $args ); |
| 32 | } |
| 33 | protected function get_query_url() { |
| 34 | if ( property_exists( $this, 'query_url' ) ) { |
| 35 | return $this->query_url; |
| 36 | } |
| 37 | $url = admin_url( 'admin-ajax.php' ); |
| 38 | return apply_filters( $this->identifier . '_query_url', $url ); |
| 39 | } |
| 40 | protected function get_post_args() { |
| 41 | if ( property_exists( $this, 'post_args' ) ) { |
| 42 | return $this->post_args; |
| 43 | } |
| 44 | $args = array( |
| 45 | 'timeout' => 0.01, |
| 46 | 'blocking' => false, |
| 47 | 'body' => $this->data, |
| 48 | 'cookies' => $_COOKIE, |
| 49 | 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), |
| 50 | ); |
| 51 | return apply_filters( $this->identifier . '_post_args', $args ); |
| 52 | } |
| 53 | public function maybe_handle() { |
| 54 | // Don't lock up other requests while processing. |
| 55 | session_write_close(); |
| 56 | check_ajax_referer( $this->identifier, 'nonce' ); |
| 57 | $this->handle(); |
| 58 | wp_die(); |
| 59 | } |
| 60 | abstract protected function handle(); |
| 61 | } |
| 62 | } |
| 63 |