WP_Async_Task()

Description #

Source #

File: lib/class-wp-async-task.php

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
abstract class WP_Async_Task {
 
    /**
     * Constant identifier for a task that should be available to logged-in users
     *
     * See constructor documentation for more details.
     */
    const LOGGED_IN = 1;
 
    /**
     * Constant identifier for a task that should be available to logged-out users
     *
     * See constructor documentation for more details.
     */
    const LOGGED_OUT = 2;
 
    /**
     * Constant identifier for a task that should be available to all users regardless of auth status
     *
     * See constructor documentation for more details.
     */
    const BOTH = 3;
 
    /**
     * This is the argument count for the main action set in the constructor. It
     * is set to an arbitrarily high value of twenty, but can be overridden if
     * necessary
     *
     * @var int
     */
    protected $argument_count = 20;
 
    /**
     * Priority to fire intermediate action.
     *
     * @var int
     */
    protected $priority = 10;
 
    /**
     * @var string
     */
    protected $action;
 
    /**
     * @var array
     */
    protected $_body_data;
 
    /**
     * Constructor to wire up the necessary actions
     *
     * Which hooks the asynchronous postback happens on can be set by the
     * $auth_level parameter. There are essentially three options: logged in users
     * only, logged out users only, or both. Set this when you instantiate an
     * object by using one of the three class constants to do so:
     *  - LOGGED_IN
     *  - LOGGED_OUT
     *  - BOTH
     * $auth_level defaults to BOTH
     *
     * @throws Exception If the class' $action value hasn't been set
     *
     * @param int $auth_level The authentication level to use (see above)
     */
    public function __construct( $auth_level = self::BOTH ) {
        if ( empty( $this->action ) ) {
            throw new Exception( 'Action not defined for class ' . __CLASS__ );
        }
        add_action( $this->action, array( $this, 'launch' ), (int) $this->priority, (int) $this->argument_count );
        if ( $auth_level & self::LOGGED_IN ) {
            add_action( "admin_post_wp_async_$this->action", array( $this, 'handle_postback' ) );
        }
        if ( $auth_level & self::LOGGED_OUT ) {
            add_action( "admin_post_nopriv_wp_async_$this->action", array( $this, 'handle_postback' ) );
        }
    }
 
    /**
     * Add the shutdown action for launching the real postback if we don't
     * get an exception thrown by prepare_data().
     *
     * @uses func_get_args() To grab any arguments passed by the action
     */
    public function launch() {
        $data = func_get_args();
        try {
            $data = $this->prepare_data( $data );
        } catch ( Exception $e ) {
            return;
        }
 
        $data['action'] = "wp_async_$this->action";
        $data['_nonce'] = $this->create_async_nonce();
 
        $this->_body_data = $data;
 
        if ( ! has_action( 'shutdown', array( $this, 'launch_on_shutdown' ) ) ) {
            add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
        }
    }
 
    /**
     * Launch the request on the WordPress shutdown hook
     *
     * On VIP we got into data races due to the postback sometimes completing
     * faster than the data could propogate to the database server cluster.
     * This made WordPress get empty data sets from the database without
     * failing. On their advice, we're moving the actual firing of the async
     * postback to the shutdown hook. Supposedly that will ensure that the
     * data at least has time to get into the object cache.
     *
     * @uses $_COOKIE        To send a cookie header for async postback
     * @uses apply_filters()
     * @uses admin_url()
     * @uses wp_remote_post()
     */
    public function launch_on_shutdown() {
        if ( ! empty( $this->_body_data ) ) {
            $cookies = array();
            foreach ( $_COOKIE as $name => $value ) {
                $cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
            }
 
            $request_args = array(
                'timeout'   => 0.01,
                'blocking'  => false,
                'sslverify' => apply_filters( 'https_local_ssl_verify', true ),
                'body'      => $this->_body_data,
                'headers'   => array(
                    'cookie' => implode( '; ', $cookies ),
                ),
                'compress'  => true,
            );
 
            $url = admin_url( 'admin-post.php' );
 
            wp_remote_post( $url, $request_args );
        }
    }
 
    /**
     * Verify the postback is valid, then fire any scheduled events.
     *
     * @uses is_user_logged_in()
     * @uses add_filter()
     * @uses wp_die()
     */
    public function handle_postback() {
        $nonce = ap_sanitize_unslash( '_nonce', 'r' );
 
        if ( ! empty( $nonce ) && false !== $this->verify_async_nonce( $nonce ) ) {
            if ( ! is_user_logged_in() ) {
                $this->action = "nopriv_$this->action";
            }
            $this->run_action();
        }
 
        add_filter(
            'wp_die_handler',
            function() {
                die();
            }
        );
        wp_die();
    }
 
    /**
     * Create a random, one time use token.
     *
     * Based entirely on wp_create_nonce() but does not tie the nonce to the
     * current logged-in user.
     *
     * @uses wp_nonce_tick()
     * @uses wp_hash()
     *
     * @return string The one-time use token
     */
    protected function create_async_nonce() {
        $action = $this->get_nonce_action();
        $i      = wp_nonce_tick();
 
        return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
    }
 
    /**
     * Verify that the correct nonce was used within the time limit.
     *
     * @uses wp_nonce_tick()
     * @uses wp_hash()
     *
     * @param string $nonce Nonce to be verified
     *
     * @return bool Whether the nonce check passed or failed
     */
    protected function verify_async_nonce( $nonce ) {
        $action = $this->get_nonce_action();
        $i      = wp_nonce_tick();
 
        // Nonce generated 0-12 hours ago
        if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
            return 1;
        }
 
        // Nonce generated 12-24 hours ago
        if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
            return 2;
        }
 
        // Invalid nonce
        return false;
    }
 
    /**
     * Get a nonce action based on the $action property of the class
     *
     * @return string The nonce action for the current instance
     */
    protected function get_nonce_action() {
        $action = $this->action;
        if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
            $action = substr( $action, 7 );
        }
        $action = "wp_async_$action";
        return $action;
    }
 
    /**
     * Prepare any data to be passed to the asynchronous postback
     *
     * The array this function receives will be a numerically keyed array from
     * func_get_args(). It is expected that you will return an associative array
     * so that the $_POST values used in the asynchronous call will make sense.
     *
     * The array you send back may or may not have anything to do with the data
     * passed into this method. It all depends on the implementation details and
     * what data is needed in the asynchronous postback.
     *
     * Do not set values for 'action' or '_nonce', as those will get overwritten
     * later in launch().
     *
     * @throws Exception If the postback should not occur for any reason
     *
     * @param array $data The raw data received by the launch method
     *
     * @return array The prepared data
     */
    abstract protected function prepare_data( $data );
 
    /**
     * Run the do_action function for the asynchronous postback.
     *
     * This method needs to fetch and sanitize any and all data from the $_POST
     * superglobal and provide them to the do_action call.
     *
     * The action should be constructed as "wp_async_task_$this->action"
     */
    abstract protected function run_action();
 
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment