Skip to:
Content

BuddyPress.org

Ticket #6930: 6930.wp-async-task-example.patch

File 6930.wp-async-task-example.patch, 12.7 KB (added by r-a-y, 9 years ago)
  • src/bp-activity/bp-activity-actions.php

     
    3131add_action( 'bp_init', 'bp_register_activity_actions', 8 );
    3232
    3333/**
     34 * Register asynchronous hooks for the activity component.
     35 *
     36 * @since 2.6.0
     37 */
     38function bp_activity_register_async_actions() {
     39        if ( false === class_exists( 'WP_Async_Task' ) ) {
     40                require buddypress()->core->path . 'bp-core/lib/wp-async-task.php';
     41        }
     42
     43        // @todo Alter this when autoloading is ready.
     44        if ( false === class_exists( 'BP_Activity_Async_Mentions' ) ) {
     45                require dirname( __FILE__ ) . '/classes/class-bp-activity-async-mentions.php';
     46        }
     47
     48        buddypress()->activity->async = new stdClass;
     49        buddypress()->activity->async->mentions = new BP_Activity_Async_Mentions;
     50}
     51add_action( 'bp_init', 'bp_activity_register_async_actions' );
     52
     53/**
    3454 * Catch and route requests for single activity item permalinks.
    3555 *
    3656 * @since 1.2.0
  • src/bp-activity/bp-activity-filters.php

     
    305305                foreach( (array) $usernames as $user_id => $username ) {
    306306                        $activity->content = preg_replace( '/(@' . $username . '\b)/', "<a href='" . bp_core_get_user_domain( $user_id ) . "' rel='nofollow'>@$username</a>", $activity->content );
    307307                }
    308 
    309                 // Add our hook to send @mention emails after the activity item is saved.
    310                 add_action( 'bp_activity_after_save', 'bp_activity_at_name_send_emails' );
    311 
    312                 // Temporary variable to avoid having to run bp_activity_find_mentions() again.
    313                 buddypress()->activity->mentioned_users = $usernames;
    314308        }
    315309}
    316310
     
    330324                return;
    331325        }
    332326
    333         // If our temporary variable doesn't exist, stop now.
    334         if ( empty( buddypress()->activity->mentioned_users ) )
     327        // Get usernames.
     328        $usernames = bp_activity_find_mentions( strip_tags( $activity->content ) );
     329        if ( empty( $usernames ) ) {
    335330                return;
    336 
    337         // Grab our temporary variable from bp_activity_at_name_filter_updates().
    338         $usernames = buddypress()->activity->mentioned_users;
    339 
    340         // Get rid of temporary variable.
    341         unset( buddypress()->activity->mentioned_users );
     331        }
    342332
    343333        // Send @mentions and setup BP notifications.
    344334        foreach( (array) $usernames as $user_id => $username ) {
     
    362352                bp_activity_update_mention_count_for_user( $user_id, $activity->id );
    363353        }
    364354}
     355add_action( 'bp_activity_async_mentions', 'bp_activity_at_name_send_emails' );
    365356
    366357/**
    367358 * Catch links in activity text so rel=nofollow can be added.
  • new file src/bp-activity/classes/class-bp-activity-async-mentions.php

    new file mode 100644
    - +  
     1<?php
     2/**
     3 * BuddyPress Activity Async Mentions.
     4 *
     5 * @package BuddyPress
     6 * @since 2.6.0
     7 */
     8
     9// Exit if accessed directly.
     10defined( 'ABSPATH' ) || exit;
     11
     12/**
     13 * Send activity mentions asynchronously.
     14 *
     15 * Instead of sending activity mention notifications when the activity item is
     16 * being saved, offset this task to another page load.
     17 *
     18 * @since 2.6.0
     19 */
     20class BP_Activity_Async_Mentions extends WP_Async_Task {
     21       
     22        /**
     23         * Hook that WP Async Task should attach itself to.
     24         *
     25         * @var string
     26         */
     27        protected $action = 'bp_activity_after_save';
     28
     29        /**
     30         * How many arguments are we passing to the hook?
     31         *
     32         * @var int
     33         */
     34        protected $argument_count = 1;
     35
     36        /**
     37         * Static initializer.
     38         */
     39        public static function init() {
     40                return new self();
     41        }
     42
     43        /**
     44         * Prepare data for the asynchronous request
     45         *
     46         * @param  array $data Function arguments from our hook as an array.
     47         * @return array Data to pass to the next pageload.
     48         */
     49        protected function prepare_data( $data ) {
     50                $activity = $data[0];
     51
     52                // Are mentions disabled?
     53                if ( ! bp_activity_do_mentions() ) {
     54                        throw new Exception( 'BP Activity: Mentions disabled.' );
     55                }
     56
     57                $usernames = bp_activity_find_mentions( strip_tags( $activity->content ) );
     58
     59                // Bail if no mentions.
     60                if ( empty( $usernames ) ) {
     61                        throw new Exception( 'BP Activity: No mentions found.' );
     62                }
     63
     64                // Prepare data for offloading.
     65                return array(
     66                        'activity_id' => $activity->id,
     67                );
     68        }
     69
     70        /**
     71         * Run the async task action.
     72         *
     73         * Uses the data passed from prepare_data().
     74         */
     75        protected function run_action() {
     76                $activity = new BP_Activity_Activity( $_POST['activity_id'] );
     77
     78                /**
     79                 * Do something when activity mentions async sending is being processed.
     80                 *
     81                 * @since 2.6.0
     82                 *
     83                 * @param BP_Activity_Activity $activity
     84                 */
     85                do_action( 'bp_activity_async_mentions', $activity );
     86        }
     87
     88}
     89 No newline at end of file
  • new file src/bp-core/lib/wp-async-task.php

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