[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

/src/bp-activity/classes/ -> class-bp-activity-activity.php (source)

   1  <?php
   2  /**
   3   * BuddyPress Activity Classes
   4   *
   5   * @package BuddyPress
   6   * @subpackage Activity
   7   * @since 1.0.0
   8   */
   9  
  10  // Exit if accessed directly.
  11  defined( 'ABSPATH' ) || exit;
  12  
  13  /**
  14   * Database interaction class for the BuddyPress activity component.
  15   * Instance methods are available for creating/editing an activity,
  16   * static methods for querying activities.
  17   *
  18   * @since 1.0.0
  19   */
  20  class BP_Activity_Activity {
  21  
  22      /** Properties ************************************************************/
  23  
  24      /**
  25       * ID of the activity item.
  26       *
  27       * @since 1.0.0
  28       * @var int
  29       */
  30      var $id;
  31  
  32      /**
  33       * ID of the associated item.
  34       *
  35       * @since 1.0.0
  36       * @var int
  37       */
  38      var $item_id;
  39  
  40      /**
  41       * ID of the associated secondary item.
  42       *
  43       * @since 1.0.0
  44       * @var int
  45       */
  46      var $secondary_item_id;
  47  
  48      /**
  49       * ID of user associated with the activity item.
  50       *
  51       * @since 1.0.0
  52       * @var int
  53       */
  54      var $user_id;
  55  
  56      /**
  57       * The primary URL for the activity in RSS feeds.
  58       *
  59       * @since 1.0.0
  60       * @var string
  61       */
  62      var $primary_link;
  63  
  64      /**
  65       * BuddyPress component the activity item relates to.
  66       *
  67       * @since 1.2.0
  68       * @var string
  69       */
  70      var $component;
  71  
  72      /**
  73       * Activity type, eg 'new_blog_post'.
  74       *
  75       * @since 1.2.0
  76       * @var string
  77       */
  78      var $type;
  79  
  80      /**
  81       * Description of the activity, eg 'Alex updated his profile.'.
  82       *
  83       * @since 1.2.0
  84       * @var string
  85       */
  86      var $action;
  87  
  88      /**
  89       * The content of the activity item.
  90       *
  91       * @since 1.2.0
  92       * @var string
  93       */
  94      var $content;
  95  
  96      /**
  97       * The date the activity item was recorded, in 'Y-m-d h:i:s' format.
  98       *
  99       * @since 1.0.0
 100       * @var string
 101       */
 102      var $date_recorded;
 103  
 104      /**
 105       * Whether the item should be hidden in sitewide streams.
 106       *
 107       * @since 1.1.0
 108       * @var int
 109       */
 110      var $hide_sitewide = 0;
 111  
 112      /**
 113       * Node boundary start for activity or activity comment.
 114       *
 115       * @since 1.5.0
 116       * @var int
 117       */
 118      var $mptt_left;
 119  
 120      /**
 121       * Node boundary end for activity or activity comment.
 122       *
 123       * @since 1.5.0
 124       * @var int
 125       */
 126      var $mptt_right;
 127  
 128      /**
 129       * Whether this item is marked as spam.
 130       *
 131       * @since 1.6.0
 132       * @var int
 133       */
 134      var $is_spam;
 135  
 136      /**
 137       * Error holder.
 138       *
 139       * @since 2.6.0
 140       *
 141       * @var WP_Error
 142       */
 143      public $errors;
 144  
 145      /**
 146       * Error type to return. Either 'bool' or 'wp_error'.
 147       *
 148       * @since 2.6.0
 149       *
 150       * @var string
 151       */
 152      public $error_type = 'bool';
 153  
 154      /**
 155       * Constructor method.
 156       *
 157       * @since 1.5.0
 158       *
 159       * @param int|bool $id Optional. The ID of a specific activity item.
 160       */
 161  	public function __construct( $id = false ) {
 162          // Instantiate errors object.
 163          $this->errors = new WP_Error;
 164  
 165          if ( !empty( $id ) ) {
 166              $this->id = (int) $id;
 167              $this->populate();
 168          }
 169      }
 170  
 171      /**
 172       * Populate the object with data about the specific activity item.
 173       *
 174       * @since 1.0.0
 175       */
 176  	public function populate() {
 177          global $wpdb;
 178  
 179          $row = wp_cache_get( $this->id, 'bp_activity' );
 180  
 181          if ( false === $row ) {
 182              $bp  = buddypress();
 183              $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$bp->activity->table_name} WHERE id = %d", $this->id ) );
 184  
 185              wp_cache_set( $this->id, $row, 'bp_activity' );
 186          }
 187  
 188          if ( empty( $row ) ) {
 189              $this->id = 0;
 190              return;
 191          }
 192  
 193          $this->id                = (int) $row->id;
 194          $this->item_id           = (int) $row->item_id;
 195          $this->secondary_item_id = (int) $row->secondary_item_id;
 196          $this->user_id           = (int) $row->user_id;
 197          $this->primary_link      = $row->primary_link;
 198          $this->component         = $row->component;
 199          $this->type              = $row->type;
 200          $this->action            = $row->action;
 201          $this->content           = $row->content;
 202          $this->date_recorded     = $row->date_recorded;
 203          $this->hide_sitewide     = (int) $row->hide_sitewide;
 204          $this->mptt_left         = (int) $row->mptt_left;
 205          $this->mptt_right        = (int) $row->mptt_right;
 206          $this->is_spam           = (int) $row->is_spam;
 207  
 208          // Generate dynamic 'action' when possible.
 209          $action = bp_activity_generate_action_string( $this );
 210          if ( false !== $action ) {
 211              $this->action = $action;
 212  
 213              // If no callback is available, use the literal string from
 214              // the database row.
 215          } elseif ( ! empty( $row->action ) ) {
 216              $this->action = $row->action;
 217  
 218              // Provide a fallback to avoid PHP notices.
 219          } else {
 220              $this->action = '';
 221          }
 222      }
 223  
 224      /**
 225       * Save the activity item to the database.
 226       *
 227       * @since 1.0.0
 228       *
 229       * @return WP_Error|bool True on success.
 230       */
 231  	public function save() {
 232          global $wpdb;
 233  
 234          $bp = buddypress();
 235  
 236          $this->id                = apply_filters_ref_array( 'bp_activity_id_before_save',                array( $this->id,                &$this ) );
 237          $this->item_id           = apply_filters_ref_array( 'bp_activity_item_id_before_save',           array( $this->item_id,           &$this ) );
 238          $this->secondary_item_id = apply_filters_ref_array( 'bp_activity_secondary_item_id_before_save', array( $this->secondary_item_id, &$this ) );
 239          $this->user_id           = apply_filters_ref_array( 'bp_activity_user_id_before_save',           array( $this->user_id,           &$this ) );
 240          $this->primary_link      = apply_filters_ref_array( 'bp_activity_primary_link_before_save',      array( $this->primary_link,      &$this ) );
 241          $this->component         = apply_filters_ref_array( 'bp_activity_component_before_save',         array( $this->component,         &$this ) );
 242          $this->type              = apply_filters_ref_array( 'bp_activity_type_before_save',              array( $this->type,              &$this ) );
 243          $this->action            = apply_filters_ref_array( 'bp_activity_action_before_save',            array( $this->action,            &$this ) );
 244          $this->content           = apply_filters_ref_array( 'bp_activity_content_before_save',           array( $this->content,           &$this ) );
 245          $this->date_recorded     = apply_filters_ref_array( 'bp_activity_date_recorded_before_save',     array( $this->date_recorded,     &$this ) );
 246          $this->hide_sitewide     = apply_filters_ref_array( 'bp_activity_hide_sitewide_before_save',     array( $this->hide_sitewide,     &$this ) );
 247          $this->mptt_left         = apply_filters_ref_array( 'bp_activity_mptt_left_before_save',         array( $this->mptt_left,         &$this ) );
 248          $this->mptt_right        = apply_filters_ref_array( 'bp_activity_mptt_right_before_save',        array( $this->mptt_right,        &$this ) );
 249          $this->is_spam           = apply_filters_ref_array( 'bp_activity_is_spam_before_save',           array( $this->is_spam,           &$this ) );
 250  
 251          /**
 252           * Fires before the current activity item gets saved.
 253           *
 254           * Please use this hook to filter the properties above. Each part will be passed in.
 255           *
 256           * @since 1.0.0
 257           *
 258           * @param BP_Activity_Activity $this Current instance of the activity item being saved. Passed by reference.
 259           */
 260          do_action_ref_array( 'bp_activity_before_save', array( &$this ) );
 261  
 262          if ( 'wp_error' === $this->error_type && $this->errors->get_error_code() ) {
 263              return $this->errors;
 264          }
 265  
 266          if ( empty( $this->component ) || empty( $this->type ) ) {
 267              if ( 'bool' === $this->error_type ) {
 268                  return false;
 269              } else {
 270                  if ( empty( $this->component ) ) {
 271                      $this->errors->add( 'bp_activity_missing_component', __( 'You need to define a component parameter to insert activity.', 'buddypress' ) );
 272                  } else {
 273                      $this->errors->add( 'bp_activity_missing_type', __( 'You need to define a type parameter to insert activity.', 'buddypress' ) );
 274                  }
 275  
 276                  return $this->errors;
 277              }
 278          }
 279  
 280          /**
 281           * Use this filter to make the content of your activity required.
 282           *
 283           * @since 6.0.0
 284           *
 285           * @param bool   $value True if the content of the activity type is required.
 286           *                      False otherwise.
 287           * @param string $type  The type of the activity we are about to insert.
 288           */
 289          $type_requires_content = (bool) apply_filters( 'bp_activity_type_requires_content', $this->type === 'activity_update', $this->type );
 290          if ( $type_requires_content && ! $this->content ) {
 291              if ( 'bool' === $this->error_type ) {
 292                  return false;
 293              } else {
 294                  $this->errors->add( 'bp_activity_missing_content', __( 'Please enter some content to post.', 'buddypress' ) );
 295  
 296                  return $this->errors;
 297              }
 298          }
 299  
 300          if ( empty( $this->primary_link ) ) {
 301              $this->primary_link = bp_loggedin_user_domain();
 302          }
 303  
 304          // If we have an existing ID, update the activity item, otherwise insert it.
 305          if ( ! empty( $this->id ) ) {
 306              $q = $wpdb->prepare( "UPDATE {$bp->activity->table_name} SET user_id = %d, component = %s, type = %s, action = %s, content = %s, primary_link = %s, date_recorded = %s, item_id = %d, secondary_item_id = %d, hide_sitewide = %d, is_spam = %d WHERE id = %d", $this->user_id, $this->component, $this->type, $this->action, $this->content, $this->primary_link, $this->date_recorded, $this->item_id, $this->secondary_item_id, $this->hide_sitewide, $this->is_spam, $this->id );
 307          } else {
 308              $q = $wpdb->prepare( "INSERT INTO {$bp->activity->table_name} ( user_id, component, type, action, content, primary_link, date_recorded, item_id, secondary_item_id, hide_sitewide, is_spam ) VALUES ( %d, %s, %s, %s, %s, %s, %s, %d, %d, %d, %d )", $this->user_id, $this->component, $this->type, $this->action, $this->content, $this->primary_link, $this->date_recorded, $this->item_id, $this->secondary_item_id, $this->hide_sitewide, $this->is_spam );
 309          }
 310  
 311          if ( false === $wpdb->query( $q ) ) {
 312              return false;
 313          }
 314  
 315          // If this is a new activity item, set the $id property.
 316          if ( empty( $this->id ) ) {
 317              $this->id = $wpdb->insert_id;
 318  
 319              // If an existing activity item, prevent any changes to the content generating new @mention notifications.
 320          } else {
 321              add_filter( 'bp_activity_at_name_do_notifications', '__return_false' );
 322          }
 323  
 324          /**
 325           * Fires after an activity item has been saved to the database.
 326           *
 327           * @since 1.0.0
 328           *
 329           * @param BP_Activity_Activity $this Current instance of activity item being saved. Passed by reference.
 330           */
 331          do_action_ref_array( 'bp_activity_after_save', array( &$this ) );
 332  
 333          return true;
 334      }
 335  
 336      /** Static Methods ***************************************************/
 337  
 338      /**
 339       * Get activity items, as specified by parameters.
 340       *
 341       * @since 1.2.0
 342       * @since 2.4.0 Introduced the `$fields` parameter.
 343       * @since 2.9.0 Introduced the `$order_by` parameter.
 344       *
 345       * @see BP_Activity_Activity::get_filter_sql() for a description of the
 346       *      'filter' parameter.
 347       * @see WP_Meta_Query::queries for a description of the 'meta_query'
 348       *      parameter format.
 349       *
 350       * @param array $args {
 351       *     An array of arguments. All items are optional.
 352       *     @type int          $page              Which page of results to fetch. Using page=1 without per_page will result
 353       *                                           in no pagination. Default: 1.
 354       *     @type int|bool     $per_page          Number of results per page. Default: 25.
 355       *     @type int|bool     $max               Maximum number of results to return. Default: false (unlimited).
 356       *     @type string       $fields            Activity fields to return. Pass 'ids' to get only the activity IDs.
 357       *                                           'all' returns full activity objects.
 358       *     @type string       $sort              ASC or DESC. Default: 'DESC'.
 359       *     @type string       $order_by          Column to order results by.
 360       *     @type array        $exclude           Array of activity IDs to exclude. Default: false.
 361       *     @type array        $in                Array of ids to limit query by (IN). Default: false.
 362       *     @type array        $meta_query        Array of meta_query conditions. See WP_Meta_Query::queries.
 363       *     @type array        $date_query        Array of date_query conditions. See first parameter of
 364       *                                           WP_Date_Query::__construct().
 365       *     @type array        $filter_query      Array of advanced query conditions. See BP_Activity_Query::__construct().
 366       *     @type string|array $scope             Pre-determined set of activity arguments.
 367       *     @type array        $filter            See BP_Activity_Activity::get_filter_sql().
 368       *     @type string       $search_terms      Limit results by a search term. Default: false.
 369       *     @type bool         $display_comments  Whether to include activity comments. Default: false.
 370       *     @type bool         $show_hidden       Whether to show items marked hide_sitewide. Default: false.
 371       *     @type string       $spam              Spam status. Default: 'ham_only'.
 372       *     @type bool         $update_meta_cache Whether to pre-fetch metadata for queried activity items. Default: true.
 373       *     @type string|bool  $count_total       If true, an additional DB query is run to count the total activity items
 374       *                                           for the query. Default: false.
 375       * }
 376       * @return array The array returned has two keys:
 377       *               - 'total' is the count of located activities
 378       *               - 'activities' is an array of the located activities
 379       */
 380  	public static function get( $args = array() ) {
 381          global $wpdb;
 382  
 383          $function_args = func_get_args();
 384  
 385          // Backward compatibility with old method of passing arguments.
 386          if ( ! is_array( $args ) || count( $function_args ) > 1 ) {
 387              _deprecated_argument(
 388                  __METHOD__,
 389                  '1.6',
 390                  sprintf(
 391                      /* translators: 1: the name of the method. 2: the name of the file. */
 392                      esc_html__( 'Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress' ),
 393                      __METHOD__,
 394                      __FILE__
 395                  )
 396              );
 397  
 398              $old_args_keys = array(
 399                  0 => 'max',
 400                  1 => 'page',
 401                  2 => 'per_page',
 402                  3 => 'sort',
 403                  4 => 'search_terms',
 404                  5 => 'filter',
 405                  6 => 'display_comments',
 406                  7 => 'show_hidden',
 407                  8 => 'exclude',
 408                  9 => 'in',
 409                  10 => 'spam'
 410              );
 411  
 412              $args = bp_core_parse_args_array( $old_args_keys, $function_args );
 413          }
 414  
 415          $bp = buddypress();
 416          $r  = bp_parse_args(
 417              $args,
 418              array(
 419                  'page'              => 1,               // The current page.
 420                  'per_page'          => 25,              // Activity items per page.
 421                  'max'               => false,           // Max number of items to return.
 422                  'fields'            => 'all',           // Fields to include.
 423                  'sort'              => 'DESC',          // ASC or DESC.
 424                  'order_by'          => 'date_recorded', // Column to order by.
 425                  'exclude'           => false,           // Array of ids to exclude.
 426                  'in'                => false,           // Array of ids to limit query by (IN).
 427                  'meta_query'        => false,           // Filter by activitymeta.
 428                  'date_query'        => false,           // Filter by date.
 429                  'filter_query'      => false,           // Advanced filtering - see BP_Activity_Query.
 430                  'filter'            => false,           // See self::get_filter_sql().
 431                  'scope'             => false,           // Preset activity arguments.
 432                  'search_terms'      => false,           // Terms to search by.
 433                  'display_comments'  => false,           // Whether to include activity comments.
 434                  'show_hidden'       => false,           // Show items marked hide_sitewide.
 435                  'spam'              => 'ham_only',      // Spam status.
 436                  'update_meta_cache' => true,            // Whether or not to update meta cache.
 437                  'count_total'       => false,           // Whether or not to use count_total.
 438              )
 439          );
 440  
 441          // Select conditions.
 442          $select_sql = "SELECT DISTINCT a.id";
 443  
 444          $from_sql   = " FROM {$bp->activity->table_name} a";
 445  
 446          $join_sql   = '';
 447  
 448          // Where conditions.
 449          $where_conditions = array();
 450  
 451          // Excluded types.
 452          $excluded_types = array();
 453  
 454          // Scope takes precedence.
 455          if ( ! empty( $r['scope'] ) ) {
 456              $scope_query = self::get_scope_query_sql( $r['scope'], $r );
 457  
 458              // Add our SQL conditions if matches were found.
 459              if ( ! empty( $scope_query['sql'] ) ) {
 460                  $where_conditions['scope_query_sql'] = $scope_query['sql'];
 461              }
 462  
 463              // Override some arguments if needed.
 464              if ( ! empty( $scope_query['override'] ) ) {
 465                  $r = array_replace_recursive( $r, $scope_query['override'] );
 466              }
 467  
 468              // Advanced filtering.
 469          } elseif ( ! empty( $r['filter_query'] ) ) {
 470              $filter_query = new BP_Activity_Query( $r['filter_query'] );
 471              $sql          = $filter_query->get_sql();
 472              if ( ! empty( $sql ) ) {
 473                  $where_conditions['filter_query_sql'] = $sql;
 474              }
 475          }
 476  
 477          // Regular filtering.
 478          if ( $r['filter'] && $filter_sql = BP_Activity_Activity::get_filter_sql( $r['filter'] ) ) {
 479              $where_conditions['filter_sql'] = $filter_sql;
 480          }
 481  
 482          // Spam.
 483          if ( 'ham_only' == $r['spam'] ) {
 484              $where_conditions['spam_sql'] = 'a.is_spam = 0';
 485          } elseif ( 'spam_only' == $r['spam'] ) {
 486              $where_conditions['spam_sql'] = 'a.is_spam = 1';
 487          }
 488  
 489          // Searching.
 490          if ( $r['search_terms'] ) {
 491              $search_terms_like = '%' . bp_esc_like( $r['search_terms'] ) . '%';
 492              $where_conditions['search_sql'] = $wpdb->prepare( 'a.content LIKE %s', $search_terms_like );
 493  
 494              /**
 495               * Filters whether or not to include users for search parameters.
 496               *
 497               * @since 3.0.0
 498               *
 499               * @param bool $value Whether or not to include user search. Default false.
 500               */
 501              if ( apply_filters( 'bp_activity_get_include_user_search', false ) ) {
 502                  $user_search = get_user_by( 'slug', $r['search_terms'] );
 503                  if ( false !== $user_search ) {
 504                      $user_id                         = $user_search->ID;
 505                      $where_conditions['search_sql'] .= $wpdb->prepare( ' OR a.user_id = %d', $user_id );
 506                  }
 507              }
 508          }
 509  
 510          // Sorting.
 511          $sort = $r['sort'];
 512          if ( $sort != 'ASC' && $sort != 'DESC' ) {
 513              $sort = 'DESC';
 514          }
 515  
 516          switch( $r['order_by'] ) {
 517              case 'id' :
 518              case 'user_id' :
 519              case 'component' :
 520              case 'type' :
 521              case 'action' :
 522              case 'content' :
 523              case 'primary_link' :
 524              case 'item_id' :
 525              case 'secondary_item_id' :
 526              case 'date_recorded' :
 527              case 'hide_sitewide' :
 528              case 'mptt_left' :
 529              case 'mptt_right' :
 530              case 'is_spam' :
 531                  break;
 532  
 533              default :
 534                  $r['order_by'] = 'date_recorded';
 535                  break;
 536          }
 537          $order_by = 'a.' . $r['order_by'];
 538  
 539          // Hide Hidden Items?
 540          if ( ! $r['show_hidden'] ) {
 541              $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
 542          }
 543  
 544          // Exclude specified items.
 545          if ( ! empty( $r['exclude'] ) ) {
 546              $exclude = implode( ',', wp_parse_id_list( $r['exclude'] ) );
 547              $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
 548          }
 549  
 550          // The specific ids to which you want to limit the query.
 551          if ( ! empty( $r['in'] ) ) {
 552              $in = implode( ',', wp_parse_id_list( $r['in'] ) );
 553              $where_conditions['in'] = "a.id IN ({$in})";
 554          }
 555  
 556          // Process meta_query into SQL.
 557          $meta_query_sql = self::get_meta_query_sql( $r['meta_query'] );
 558  
 559          if ( ! empty( $meta_query_sql['join'] ) ) {
 560              $join_sql .= $meta_query_sql['join'];
 561          }
 562  
 563          if ( ! empty( $meta_query_sql['where'] ) ) {
 564              $where_conditions[] = $meta_query_sql['where'];
 565          }
 566  
 567          // Process date_query into SQL.
 568          $date_query_sql = self::get_date_query_sql( $r['date_query'] );
 569  
 570          if ( ! empty( $date_query_sql ) ) {
 571              $where_conditions['date'] = $date_query_sql;
 572          }
 573  
 574          // Alter the query based on whether we want to show activity item
 575          // comments in the stream like normal comments or threaded below
 576          // the activity.
 577          if ( false === $r['display_comments'] || 'threaded' === $r['display_comments'] ) {
 578              $excluded_types[] = 'activity_comment';
 579          }
 580  
 581          // Exclude 'last_activity' items unless the 'action' filter has
 582          // been explicitly set.
 583          if ( empty( $r['filter']['object'] ) ) {
 584              $excluded_types[] = 'last_activity';
 585          }
 586  
 587          // Build the excluded type sql part.
 588          if ( ! empty( $excluded_types ) ) {
 589              $not_in = "'" . implode( "', '", esc_sql( $excluded_types ) ) . "'";
 590              $where_conditions['excluded_types'] = "a.type NOT IN ({$not_in})";
 591          }
 592  
 593          /**
 594           * Filters the MySQL WHERE conditions for the Activity items get method.
 595           *
 596           * @since 1.9.0
 597           *
 598           * @param array  $where_conditions Current conditions for MySQL WHERE statement.
 599           * @param array  $r                Parsed arguments passed into method.
 600           * @param string $select_sql       Current SELECT MySQL statement at point of execution.
 601           * @param string $from_sql         Current FROM MySQL statement at point of execution.
 602           * @param string $join_sql         Current INNER JOIN MySQL statement at point of execution.
 603           */
 604          $where_conditions = apply_filters( 'bp_activity_get_where_conditions', $where_conditions, $r, $select_sql, $from_sql, $join_sql );
 605  
 606          // Join the where conditions together.
 607          $where_sql = 'WHERE ' . join( ' AND ', $where_conditions );
 608  
 609          /**
 610           * Filter the MySQL JOIN clause for the main activity query.
 611           *
 612           * @since 2.5.0
 613           *
 614           * @param string $join_sql   JOIN clause.
 615           * @param array  $r          Method parameters.
 616           * @param string $select_sql Current SELECT MySQL statement.
 617           * @param string $from_sql   Current FROM MySQL statement.
 618           * @param string $where_sql  Current WHERE MySQL statement.
 619           */
 620          $join_sql = apply_filters( 'bp_activity_get_join_sql', $join_sql, $r, $select_sql, $from_sql, $where_sql );
 621  
 622          // Sanitize page and per_page parameters.
 623          $page     = absint( $r['page']     );
 624          $per_page = absint( $r['per_page'] );
 625  
 626          $retval = array(
 627              'activities'     => null,
 628              'total'          => null,
 629              'has_more_items' => null,
 630          );
 631  
 632          /**
 633           * Filters if BuddyPress should use legacy query structure over current structure for version 2.0+.
 634           *
 635           * It is not recommended to use the legacy structure, but allowed to if needed.
 636           *
 637           * @since 2.0.0
 638           *
 639           * @param bool                 $value Whether to use legacy structure or not.
 640           * @param BP_Activity_Activity $value Current method being called.
 641           * @param array                $r     Parsed arguments passed into method.
 642           */
 643          if ( apply_filters( 'bp_use_legacy_activity_query', false, __METHOD__, $r ) ) {
 644  
 645              // Legacy queries joined against the user table.
 646              $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
 647              $from_sql   = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
 648  
 649              if ( ! empty( $page ) && ! empty( $per_page ) ) {
 650                  $pag_sql = $wpdb->prepare( "LIMIT %d, %d", absint( ( $page - 1 ) * $per_page ), $per_page );
 651  
 652                  /** This filter is documented in bp-activity/bp-activity-classes.php */
 653                  $activity_sql = apply_filters( 'bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}, a.id {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql );
 654              } else {
 655                  $pag_sql = '';
 656  
 657                  /**
 658                   * Filters the legacy MySQL query statement so plugins can alter before results are fetched.
 659                   *
 660                   * @since 1.5.0
 661                   *
 662                   * @param string $value      Concatenated MySQL statement pieces to be query results with for legacy query.
 663                   * @param string $select_sql Final SELECT MySQL statement portion for legacy query.
 664                   * @param string $from_sql   Final FROM MySQL statement portion for legacy query.
 665                   * @param string $where_sql  Final WHERE MySQL statement portion for legacy query.
 666                   * @param string $sort       Final sort direction for legacy query.
 667                   */
 668                  $activity_sql = apply_filters( 'bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}, a.id {$sort}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql );
 669              }
 670  
 671              /*
 672               * Queries that include 'last_activity' are cached separately,
 673               * since they are generally much less long-lived.
 674               */
 675              if ( preg_match( '/a\.type NOT IN \([^\)]*\'last_activity\'[^\)]*\)/', $activity_sql ) ) {
 676                  $cache_group = 'bp_activity';
 677              } else {
 678                  $cache_group = 'bp_activity_with_last_activity';
 679              }
 680  
 681              $activities = $wpdb->get_results( $activity_sql );
 682  
 683              // Integer casting for legacy activity query.
 684              foreach ( (array) $activities as $i => $ac ) {
 685                  $activities[ $i ]->id                = (int) $ac->id;
 686                  $activities[ $i ]->item_id           = (int) $ac->item_id;
 687                  $activities[ $i ]->secondary_item_id = (int) $ac->secondary_item_id;
 688                  $activities[ $i ]->user_id           = (int) $ac->user_id;
 689                  $activities[ $i ]->hide_sitewide     = (int) $ac->hide_sitewide;
 690                  $activities[ $i ]->mptt_left         = (int) $ac->mptt_left;
 691                  $activities[ $i ]->mptt_right        = (int) $ac->mptt_right;
 692                  $activities[ $i ]->is_spam           = (int) $ac->is_spam;
 693              }
 694  
 695          } else {
 696              // Query first for activity IDs.
 697              $activity_ids_sql = "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY {$order_by} {$sort}, a.id {$sort}";
 698  
 699              if ( ! empty( $per_page ) && ! empty( $page ) ) {
 700                  // We query for $per_page + 1 items in order to
 701                  // populate the has_more_items flag.
 702                  $activity_ids_sql .= $wpdb->prepare( " LIMIT %d, %d", absint( ( $page - 1 ) * $per_page ), $per_page + 1 );
 703              }
 704  
 705              /**
 706               * Filters the paged activities MySQL statement.
 707               *
 708               * @since 2.0.0
 709               *
 710               * @param string $activity_ids_sql MySQL statement used to query for Activity IDs.
 711               * @param array  $r                Array of arguments passed into method.
 712               */
 713              $activity_ids_sql = apply_filters( 'bp_activity_paged_activities_sql', $activity_ids_sql, $r );
 714  
 715              /*
 716               * Queries that include 'last_activity' are cached separately,
 717               * since they are generally much less long-lived.
 718               */
 719              if ( preg_match( '/a\.type NOT IN \([^\)]*\'last_activity\'[^\)]*\)/', $activity_ids_sql ) ) {
 720                  $cache_group = 'bp_activity';
 721              } else {
 722                  $cache_group = 'bp_activity_with_last_activity';
 723              }
 724  
 725              $cached = bp_core_get_incremented_cache( $activity_ids_sql, $cache_group );
 726              if ( false === $cached ) {
 727                  $activity_ids = $wpdb->get_col( $activity_ids_sql );
 728                  bp_core_set_incremented_cache( $activity_ids_sql, $cache_group, $activity_ids );
 729              } else {
 730                  $activity_ids = $cached;
 731              }
 732  
 733              $retval['has_more_items'] = ! empty( $per_page ) && count( $activity_ids ) > $per_page;
 734  
 735              // If we've fetched more than the $per_page value, we
 736              // can discard the extra now.
 737              if ( ! empty( $per_page ) && count( $activity_ids ) === $per_page + 1 ) {
 738                  array_pop( $activity_ids );
 739              }
 740  
 741              if ( 'ids' === $r['fields'] ) {
 742                  $activities = array_map( 'intval', $activity_ids );
 743              } else {
 744                  $activities = self::get_activity_data( $activity_ids );
 745              }
 746          }
 747  
 748          if ( 'ids' !== $r['fields'] ) {
 749              // Get the fullnames of users so we don't have to query in the loop.
 750              $activities = self::append_user_fullnames( $activities );
 751  
 752              // Get activity meta.
 753              $activity_ids = array();
 754              foreach ( (array) $activities as $activity ) {
 755                  $activity_ids[] = $activity->id;
 756              }
 757  
 758              if ( ! empty( $activity_ids ) && $r['update_meta_cache'] ) {
 759                  bp_activity_update_meta_cache( $activity_ids );
 760              }
 761  
 762              if ( $activities && $r['display_comments'] ) {
 763                  $activities = BP_Activity_Activity::append_comments( $activities, $r['spam'] );
 764              }
 765  
 766              // Pre-fetch data associated with activity users and other objects.
 767              BP_Activity_Activity::prefetch_object_data( $activities );
 768  
 769              // Generate action strings.
 770              $activities = BP_Activity_Activity::generate_action_strings( $activities );
 771          }
 772  
 773          $retval['activities'] = $activities;
 774  
 775          // If $max is set, only return up to the max results.
 776          if ( ! empty( $r['count_total'] ) ) {
 777  
 778              /**
 779               * Filters the total activities MySQL statement.
 780               *
 781               * @since 1.5.0
 782               *
 783               * @param string $value     MySQL statement used to query for total activities.
 784               * @param string $where_sql MySQL WHERE statement portion.
 785               * @param string $sort      Sort direction for query.
 786               */
 787              $total_activities_sql = apply_filters( 'bp_activity_total_activities_sql', "SELECT count(DISTINCT a.id) FROM {$bp->activity->table_name} a {$join_sql} {$where_sql}", $where_sql, $sort );
 788              $cached = bp_core_get_incremented_cache( $total_activities_sql, $cache_group );
 789              if ( false === $cached ) {
 790                  $total_activities = $wpdb->get_var( $total_activities_sql );
 791                  bp_core_set_incremented_cache( $total_activities_sql, $cache_group, $total_activities );
 792              } else {
 793                  $total_activities = $cached;
 794              }
 795  
 796              if ( !empty( $r['max'] ) ) {
 797                  if ( (int) $total_activities > (int) $r['max'] ) {
 798                      $total_activities = $r['max'];
 799                  }
 800              }
 801  
 802              $retval['total'] = $total_activities;
 803          }
 804  
 805          return $retval;
 806      }
 807  
 808      /**
 809       * Convert activity IDs to activity objects, as expected in template loop.
 810       *
 811       * @since 2.0.0
 812       *
 813       * @param array $activity_ids Array of activity IDs.
 814       * @return array
 815       */
 816  	protected static function get_activity_data( $activity_ids = array() ) {
 817          global $wpdb;
 818  
 819          // Bail if no activity ID's passed.
 820          if ( empty( $activity_ids ) ) {
 821              return array();
 822          }
 823  
 824          // Get BuddyPress.
 825          $bp = buddypress();
 826  
 827          $activities   = array();
 828          $uncached_ids = bp_get_non_cached_ids( $activity_ids, 'bp_activity' );
 829  
 830          // Prime caches as necessary.
 831          if ( ! empty( $uncached_ids ) ) {
 832              // Format the activity ID's for use in the query below.
 833              $uncached_ids_sql = implode( ',', wp_parse_id_list( $uncached_ids ) );
 834  
 835              // Fetch data from activity table, preserving order.
 836              $queried_adata = $wpdb->get_results( "SELECT * FROM {$bp->activity->table_name} WHERE id IN ({$uncached_ids_sql})");
 837  
 838              // Put that data into the placeholders created earlier,
 839              // and add it to the cache.
 840              foreach ( (array) $queried_adata as $adata ) {
 841                  wp_cache_set( $adata->id, $adata, 'bp_activity' );
 842              }
 843          }
 844  
 845          // Now fetch data from the cache.
 846          foreach ( $activity_ids as $activity_id ) {
 847              // Integer casting.
 848              $activity = wp_cache_get( $activity_id, 'bp_activity' );
 849              if ( ! empty( $activity ) ) {
 850                  $activity->id                = (int) $activity->id;
 851                  $activity->user_id           = (int) $activity->user_id;
 852                  $activity->item_id           = (int) $activity->item_id;
 853                  $activity->secondary_item_id = (int) $activity->secondary_item_id;
 854                  $activity->hide_sitewide     = (int) $activity->hide_sitewide;
 855                  $activity->mptt_left         = (int) $activity->mptt_left;
 856                  $activity->mptt_right        = (int) $activity->mptt_right;
 857                  $activity->is_spam           = (int) $activity->is_spam;
 858              }
 859  
 860              $activities[] = $activity;
 861          }
 862  
 863          // Then fetch user data.
 864          $user_query = new BP_User_Query( array(
 865              'user_ids'        => wp_list_pluck( $activities, 'user_id' ),
 866              'populate_extras' => false,
 867          ) );
 868  
 869          // Associated located user data with activity items.
 870          foreach ( $activities as $a_index => $a_item ) {
 871              $a_user_id = intval( $a_item->user_id );
 872              $a_user    = isset( $user_query->results[ $a_user_id ] ) ? $user_query->results[ $a_user_id ] : '';
 873  
 874              if ( !empty( $a_user ) ) {
 875                  $activities[ $a_index ]->user_email    = $a_user->user_email;
 876                  $activities[ $a_index ]->user_nicename = $a_user->user_nicename;
 877                  $activities[ $a_index ]->user_login    = $a_user->user_login;
 878                  $activities[ $a_index ]->display_name  = $a_user->display_name;
 879              }
 880          }
 881  
 882          return $activities;
 883      }
 884  
 885      /**
 886       * Append xProfile fullnames to an activity array.
 887       *
 888       * @since 2.0.0
 889       *
 890       * @param array $activities Activities array.
 891       * @return array
 892       */
 893  	protected static function append_user_fullnames( $activities ) {
 894  
 895          if ( bp_is_active( 'xprofile' ) && ! empty( $activities ) ) {
 896              $activity_user_ids = wp_list_pluck( $activities, 'user_id' );
 897  
 898              if ( ! empty( $activity_user_ids ) ) {
 899                  $fullnames = bp_core_get_user_displaynames( $activity_user_ids );
 900                  if ( ! empty( $fullnames ) ) {
 901                      foreach ( (array) $activities as $i => $activity ) {
 902                          if ( ! empty( $fullnames[ $activity->user_id ] ) ) {
 903                              $activities[ $i ]->user_fullname = $fullnames[ $activity->user_id ];
 904                          }
 905                      }
 906                  }
 907              }
 908          }
 909  
 910          return $activities;
 911      }
 912  
 913      /**
 914       * Pre-fetch data for objects associated with activity items.
 915       *
 916       * Activity items are associated with users, and often with other
 917       * BuddyPress data objects. Here, we pre-fetch data about these
 918       * associated objects, so that inline lookups - done primarily when
 919       * building action strings - do not result in excess database queries.
 920       *
 921       * The only object data required for activity component activity types
 922       * (activity_update and activity_comment) is related to users, and that
 923       * info is fetched separately in BP_Activity_Activity::get_activity_data().
 924       * So this method contains nothing but a filter that allows other
 925       * components, such as bp-friends and bp-groups, to hook in and prime
 926       * their own caches at the beginning of an activity loop.
 927       *
 928       * @since 2.0.0
 929       *
 930       * @param array $activities Array of activities.
 931       * @return array $activities Array of activities.
 932       */
 933  	protected static function prefetch_object_data( $activities ) {
 934  
 935          /**
 936           * Filters inside prefetch_object_data method to aid in pre-fetching object data associated with activity item.
 937           *
 938           * @since 2.0.0
 939           *
 940           * @param array $activities Array of activities.
 941           */
 942          return apply_filters( 'bp_activity_prefetch_object_data', $activities );
 943      }
 944  
 945      /**
 946       * Generate action strings for the activities located in BP_Activity_Activity::get().
 947       *
 948       * If no string can be dynamically generated for a given item
 949       * (typically because the activity type has not been properly
 950       * registered), the static 'action' value pulled from the database will
 951       * be left in place.
 952       *
 953       * @since 2.0.0
 954       *
 955       * @param array $activities Array of activities.
 956       * @return array
 957       */
 958  	protected static function generate_action_strings( $activities ) {
 959          foreach ( $activities as $key => $activity ) {
 960              $generated_action = bp_activity_generate_action_string( $activity );
 961              if ( false !== $generated_action ) {
 962                  $activity->action = $generated_action;
 963              }
 964  
 965              $activities[ $key ] = $activity;
 966          }
 967  
 968          return $activities;
 969      }
 970  
 971      /**
 972       * Get the SQL for the 'meta_query' param in BP_Activity_Activity::get().
 973       *
 974       * We use WP_Meta_Query to do the heavy lifting of parsing the
 975       * meta_query array and creating the necessary SQL clauses. However,
 976       * since BP_Activity_Activity::get() builds its SQL differently than
 977       * WP_Query, we have to alter the return value (stripping the leading
 978       * AND keyword from the 'where' clause).
 979       *
 980       * @since 1.8.0
 981       *
 982       * @param array $meta_query An array of meta_query filters. See the
 983       *                          documentation for WP_Meta_Query for details.
 984       * @return array $sql_array 'join' and 'where' clauses.
 985       */
 986  	public static function get_meta_query_sql( $meta_query = array() ) {
 987          global $wpdb;
 988  
 989          $sql_array = array(
 990              'join'  => '',
 991              'where' => '',
 992          );
 993  
 994          if ( ! empty( $meta_query ) ) {
 995              $activity_meta_query = new WP_Meta_Query( $meta_query );
 996  
 997              // WP_Meta_Query expects the table name at
 998              // $wpdb->activitymeta.
 999              $wpdb->activitymeta = buddypress()->activity->table_name_meta;
1000  
1001              $meta_sql = $activity_meta_query->get_sql( 'activity', 'a', 'id' );
1002  
1003              // Strip the leading AND - BP handles it in get().
1004              $sql_array['where'] = preg_replace( '/^\sAND/', '', $meta_sql['where'] );
1005              $sql_array['join']  = $meta_sql['join'];
1006          }
1007  
1008          return $sql_array;
1009      }
1010  
1011      /**
1012       * Get the SQL for the 'date_query' param in BP_Activity_Activity::get().
1013       *
1014       * We use BP_Date_Query, which extends WP_Date_Query, to do the heavy lifting
1015       * of parsing the date_query array and creating the necessary SQL clauses.
1016       * However, since BP_Activity_Activity::get() builds its SQL differently than
1017       * WP_Query, we have to alter the return value (stripping the leading AND
1018       * keyword from the query).
1019       *
1020       * @since 2.1.0
1021       *
1022       * @param array $date_query An array of date_query parameters. See the
1023       *                          documentation for the first parameter of WP_Date_Query.
1024       * @return string
1025       */
1026  	public static function get_date_query_sql( $date_query = array() ) {
1027          $sql = '';
1028  
1029          // Date query.
1030          if ( ! empty( $date_query ) && is_array( $date_query ) ) {
1031              $date_query = new BP_Date_Query( $date_query, 'date_recorded' );
1032              $sql = preg_replace( '/^\sAND/', '', $date_query->get_sql() );
1033          }
1034  
1035          return $sql;
1036      }
1037  
1038      /**
1039       * Get the SQL for the 'scope' param in BP_Activity_Activity::get().
1040       *
1041       * A scope is a predetermined set of activity arguments.  This method is used
1042       * to grab these activity arguments and override any existing args if needed.
1043       *
1044       * Can handle multiple scopes.
1045       *
1046       * @since 2.2.0
1047       *
1048       * @param  mixed $scope  The activity scope. Accepts string or array of scopes.
1049       * @param  array $r      Current activity arguments. Same as those of BP_Activity_Activity::get(),
1050       *                       but merged with defaults.
1051       * @return false|array 'sql' WHERE SQL string and 'override' activity args.
1052       */
1053  	public static function get_scope_query_sql( $scope = false, $r = array() ) {
1054  
1055          // Define arrays for future use.
1056          $query_args = array();
1057          $override   = array();
1058          $retval     = array();
1059  
1060          // Check for array of scopes.
1061          if ( is_array( $scope ) ) {
1062              $scopes = $scope;
1063  
1064              // Explode a comma separated string of scopes.
1065          } elseif ( is_string( $scope ) ) {
1066              $scopes = explode( ',', $scope );
1067          }
1068  
1069          // Bail if no scope passed.
1070          if ( empty( $scopes ) ) {
1071              return false;
1072          }
1073  
1074          // Helper to easily grab the 'user_id'.
1075          if ( ! empty( $r['filter']['user_id'] ) ) {
1076              $r['user_id'] = $r['filter']['user_id'];
1077          }
1078  
1079          // Parse each scope; yes! we handle multiples!
1080          foreach ( $scopes as $scope ) {
1081              $scope_args = array();
1082  
1083              /**
1084               * Plugins can hook here to set their activity arguments for custom scopes.
1085               *
1086               * This is a dynamic filter based on the activity scope. eg:
1087               *   - 'bp_activity_set_groups_scope_args'
1088               *   - 'bp_activity_set_friends_scope_args'
1089               *
1090               * To see how this filter is used, plugin devs should check out:
1091               *   - bp_groups_filter_activity_scope() - used for 'groups' scope
1092               *   - bp_friends_filter_activity_scope() - used for 'friends' scope
1093               *
1094               * @since 2.2.0
1095               *
1096               * @param array {
1097               *     Activity query clauses.
1098               *     @type array {
1099               *         Activity arguments for your custom scope.
1100               *         See {@link BP_Activity_Query::_construct()} for more details.
1101               *     }
1102               *     @type array  $override Optional. Override existing activity arguments passed by $r.
1103               *     }
1104               * }
1105               * @param array $r Current activity arguments passed in BP_Activity_Activity::get().
1106               */
1107              $scope_args = apply_filters( "bp_activity_set_{$scope}_scope_args", array(), $r );
1108  
1109              if ( ! empty( $scope_args ) ) {
1110                  // Merge override properties from other scopes
1111                  // this might be a problem...
1112                  if ( ! empty( $scope_args['override'] ) ) {
1113                      $override = array_merge( $override, $scope_args['override'] );
1114                      unset( $scope_args['override'] );
1115                  }
1116  
1117                  // Save scope args.
1118                  if ( ! empty( $scope_args ) ) {
1119                      $query_args[] = $scope_args;
1120                  }
1121              }
1122          }
1123  
1124          if ( ! empty( $query_args ) ) {
1125              // Set relation to OR.
1126              $query_args['relation'] = 'OR';
1127  
1128              $query = new BP_Activity_Query( $query_args );
1129              $sql   = $query->get_sql();
1130              if ( ! empty( $sql ) ) {
1131                  $retval['sql'] = $sql;
1132              }
1133          }
1134  
1135          if ( ! empty( $override ) ) {
1136              $retval['override'] = $override;
1137          }
1138  
1139          return $retval;
1140      }
1141  
1142      /**
1143       * In BuddyPress 1.2.x, this was used to retrieve specific activity stream items (for example, on an activity's permalink page).
1144       *
1145       * As of 1.5.x, use BP_Activity_Activity::get() with an 'in' parameter instead.
1146       *
1147       * @since 1.2.0
1148       *
1149       * @deprecated 1.5
1150       * @deprecated Use BP_Activity_Activity::get() with an 'in' parameter instead.
1151       *
1152       * @param mixed    $activity_ids     Array or comma-separated string of activity IDs to retrieve.
1153       * @param int|bool $max              Maximum number of results to return. (Optional; default is no maximum).
1154       * @param int      $page             The set of results that the user is viewing. Used in pagination. (Optional; default is 1).
1155       * @param int      $per_page         Specifies how many results per page. Used in pagination. (Optional; default is 25).
1156       * @param string   $sort             MySQL column sort; ASC or DESC. (Optional; default is DESC).
1157       * @param bool     $display_comments Retrieve an activity item's associated comments or not. (Optional; default is false).
1158       * @return array
1159       */
1160  	public static function get_specific( $activity_ids, $max = false, $page = 1, $per_page = 25, $sort = 'DESC', $display_comments = false ) {
1161          _deprecated_function(
1162              __FUNCTION__,
1163              '1.5',
1164              'Use BP_Activity_Activity::get() with the "in" parameter instead.'
1165          );
1166  
1167          return BP_Activity_Activity::get( $max, $page, $per_page, $sort, false, false, $display_comments, false, false, $activity_ids );
1168      }
1169  
1170      /**
1171       * Get the first activity ID that matches a set of criteria.
1172       *
1173       * @since 1.2.0
1174       *
1175       * @todo Should parameters be optional?
1176       *
1177       * @param int    $user_id           User ID to filter by.
1178       * @param string $component         Component to filter by.
1179       * @param string $type              Activity type to filter by.
1180       * @param int    $item_id           Associated item to filter by.
1181       * @param int    $secondary_item_id Secondary associated item to filter by.
1182       * @param string $action            Action to filter by.
1183       * @param string $content           Content to filter by.
1184       * @param string $date_recorded     Date to filter by.
1185       * @return int|false Activity ID on success, false if none is found.
1186       */
1187  	public static function get_id( $user_id, $component, $type, $item_id, $secondary_item_id, $action, $content, $date_recorded ) {
1188          global $wpdb;
1189  
1190          $bp = buddypress();
1191  
1192          $where_args = false;
1193  
1194          if ( ! empty( $user_id ) ) {
1195              $where_args[] = $wpdb->prepare( "user_id = %d", $user_id );
1196          }
1197  
1198          if ( ! empty( $component ) ) {
1199              $where_args[] = $wpdb->prepare( "component = %s", $component );
1200          }
1201  
1202          if ( ! empty( $type ) ) {
1203              $where_args[] = $wpdb->prepare( "type = %s", $type );
1204          }
1205  
1206          if ( ! empty( $item_id ) ) {
1207              $where_args[] = $wpdb->prepare( "item_id = %d", $item_id );
1208          }
1209  
1210          if ( ! empty( $secondary_item_id ) ) {
1211              $where_args[] = $wpdb->prepare( "secondary_item_id = %d", $secondary_item_id );
1212          }
1213  
1214          if ( ! empty( $action ) ) {
1215              $where_args[] = $wpdb->prepare( "action = %s", $action );
1216          }
1217  
1218          if ( ! empty( $content ) ) {
1219              $where_args[] = $wpdb->prepare( "content = %s", $content );
1220          }
1221  
1222          if ( ! empty( $date_recorded ) ) {
1223              $where_args[] = $wpdb->prepare( "date_recorded = %s", $date_recorded );
1224          }
1225  
1226          if ( ! empty( $where_args ) ) {
1227              $where_sql = 'WHERE ' . join( ' AND ', $where_args );
1228              $result = $wpdb->get_var( "SELECT id FROM {$bp->activity->table_name} {$where_sql}" );
1229  
1230              return is_numeric( $result ) ? (int) $result : false;
1231          }
1232  
1233          return false;
1234      }
1235  
1236      /**
1237       * Delete activity items from the database.
1238       *
1239       * To delete a specific activity item, pass an 'id' parameter.
1240       * Otherwise use the filters.
1241       *
1242       * @since 1.2.0
1243       *
1244       * @param array $args {
1245       *     @int    $id                Optional. The ID of a specific item to delete.
1246       *     @string $action            Optional. The action to filter by.
1247       *     @string $content           Optional. The content to filter by.
1248       *     @string $component         Optional. The component name to filter by.
1249       *     @string $type              Optional. The activity type to filter by.
1250       *     @string $primary_link      Optional. The primary URL to filter by.
1251       *     @int    $user_id           Optional. The user ID to filter by.
1252       *     @int    $item_id           Optional. The associated item ID to filter by.
1253       *     @int    $secondary_item_id Optional. The secondary associated item ID to filter by.
1254       *     @string $date_recorded     Optional. The date to filter by.
1255       *     @int    $hide_sitewide     Optional. Default: false.
1256       * }
1257       * @return array|bool An array of deleted activity IDs on success, false on failure.
1258       */
1259  	public static function delete( $args = array() ) {
1260          global $wpdb;
1261  
1262          $bp = buddypress();
1263          $r  = bp_parse_args(
1264              $args,
1265              array(
1266                  'id'                => false,
1267                  'action'            => false,
1268                  'content'           => false,
1269                  'component'         => false,
1270                  'type'              => false,
1271                  'primary_link'      => false,
1272                  'user_id'           => false,
1273                  'item_id'           => false,
1274                  'secondary_item_id' => false,
1275                  'date_recorded'     => false,
1276                  'hide_sitewide'     => false,
1277              )
1278          );
1279  
1280          // Setup empty array from where query arguments.
1281          $where_args = array();
1282  
1283          // ID.
1284          if ( ! empty( $r['id'] ) ) {
1285              $where_args[] = $wpdb->prepare( "id = %d", $r['id'] );
1286          }
1287  
1288          // User ID.
1289          if ( ! empty( $r['user_id'] ) ) {
1290              $where_args[] = $wpdb->prepare( "user_id = %d", $r['user_id'] );
1291          }
1292  
1293          // Action.
1294          if ( ! empty( $r['action'] ) ) {
1295              $where_args[] = $wpdb->prepare( "action = %s", $r['action'] );
1296          }
1297  
1298          // Content.
1299          if ( ! empty( $r['content'] ) ) {
1300              $where_args[] = $wpdb->prepare( "content = %s", $r['content'] );
1301          }
1302  
1303          // Component.
1304          if ( ! empty( $r['component'] ) ) {
1305              $where_args[] = $wpdb->prepare( "component = %s", $r['component'] );
1306          }
1307  
1308          // Type.
1309          if ( ! empty( $r['type'] ) ) {
1310              $where_args[] = $wpdb->prepare( "type = %s", $r['type'] );
1311          }
1312  
1313          // Primary Link.
1314          if ( ! empty( $r['primary_link'] ) ) {
1315              $where_args[] = $wpdb->prepare( "primary_link = %s", $r['primary_link'] );
1316          }
1317  
1318          // Item ID.
1319          if ( ! empty( $r['item_id'] ) ) {
1320              $where_args[] = $wpdb->prepare( "item_id = %d", $r['item_id'] );
1321          }
1322  
1323          // Secondary item ID.
1324          if ( ! empty( $r['secondary_item_id'] ) ) {
1325              $where_args[] = $wpdb->prepare( "secondary_item_id = %d", $r['secondary_item_id'] );
1326          }
1327  
1328          // Date Recorded.
1329          if ( ! empty( $r['date_recorded'] ) ) {
1330              $where_args[] = $wpdb->prepare( "date_recorded = %s", $r['date_recorded'] );
1331          }
1332  
1333          // Hidden sitewide.
1334          if ( ! empty( $r['hide_sitewide'] ) ) {
1335              $where_args[] = $wpdb->prepare( "hide_sitewide = %d", $r['hide_sitewide'] );
1336          }
1337  
1338          // Bail if no where arguments.
1339          if ( empty( $where_args ) ) {
1340              return false;
1341          }
1342  
1343          // Join the where arguments for querying.
1344          $where_sql = 'WHERE ' . join( ' AND ', $where_args );
1345  
1346          // Fetch all activities being deleted so we can perform more actions.
1347          $activities = $wpdb->get_results( "SELECT * FROM {$bp->activity->table_name} {$where_sql}" );
1348  
1349          /**
1350           * Action to allow intercepting activity items to be deleted.
1351           *
1352           * @since 2.3.0
1353           *
1354           * @param array $activities Array of activities.
1355           * @param array $r          Array of parsed arguments.
1356           */
1357          do_action_ref_array( 'bp_activity_before_delete', array( $activities, $r ) );
1358  
1359          // Attempt to delete activities from the database.
1360          $deleted = $wpdb->query( "DELETE FROM {$bp->activity->table_name} {$where_sql}" );
1361  
1362          // Bail if nothing was deleted.
1363          if ( empty( $deleted ) ) {
1364              return false;
1365          }
1366  
1367          /**
1368           * Action to allow intercepting activity items just deleted.
1369           *
1370           * @since 2.3.0
1371           *
1372           * @param array $activities Array of activities.
1373           * @param array $r          Array of parsed arguments.
1374           */
1375          do_action_ref_array( 'bp_activity_after_delete', array( $activities, $r ) );
1376  
1377          // Pluck the activity IDs out of the $activities array.
1378          $activity_ids = wp_parse_id_list( wp_list_pluck( $activities, 'id' ) );
1379  
1380          // Handle accompanying activity comments and meta deletion.
1381          if ( ! empty( $activity_ids ) ) {
1382  
1383              // Delete all activity meta entries for activity items.
1384              BP_Activity_Activity::delete_activity_meta_entries( $activity_ids );
1385  
1386              // Setup empty array for comments.
1387              $comment_ids = array();
1388  
1389              // Loop through activity ids and attempt to delete comments.
1390              foreach ( $activity_ids as $activity_id ) {
1391  
1392                  // Attempt to delete comments.
1393                  $comments = BP_Activity_Activity::delete( array(
1394                      'type'    => 'activity_comment',
1395                      'item_id' => $activity_id
1396                  ) );
1397  
1398                  // Merge IDs together.
1399                  if ( ! empty( $comments ) ) {
1400                      $comment_ids = array_merge( $comment_ids, $comments );
1401                  }
1402              }
1403  
1404              // Merge activity IDs with any deleted comment IDs.
1405              if ( ! empty( $comment_ids ) ) {
1406                  $activity_ids = array_unique( array_merge( $activity_ids, $comment_ids ) );
1407              }
1408          }
1409  
1410          return $activity_ids;
1411      }
1412  
1413      /**
1414       * Delete the comments associated with a set of activity items.
1415       *
1416       * This method is no longer used by BuddyPress, and it is recommended not to
1417       * use it going forward, and use BP_Activity_Activity::delete() instead.
1418       *
1419       * @since 1.2.0
1420       *
1421       * @deprecated 2.3.0
1422       *
1423       * @param array $activity_ids Activity IDs whose comments should be deleted.
1424       * @param bool  $delete_meta  Should we delete the activity meta items for these comments.
1425       * @return bool True on success.
1426       */
1427  	public static function delete_activity_item_comments( $activity_ids = array(), $delete_meta = true ) {
1428          global $wpdb;
1429  
1430          $bp = buddypress();
1431  
1432          $delete_meta  = (bool) $delete_meta;
1433          $activity_ids = implode( ',', wp_parse_id_list( $activity_ids ) );
1434  
1435          if ( $delete_meta ) {
1436              // Fetch the activity comment IDs for our deleted activity items.
1437              $activity_comment_ids = $wpdb->get_col( "SELECT id FROM {$bp->activity->table_name} WHERE type = 'activity_comment' AND item_id IN ({$activity_ids})" );
1438  
1439              if ( ! empty( $activity_comment_ids ) ) {
1440                  self::delete_activity_meta_entries( $activity_comment_ids );
1441              }
1442          }
1443  
1444          return $wpdb->query( "DELETE FROM {$bp->activity->table_name} WHERE type = 'activity_comment' AND item_id IN ({$activity_ids})" );
1445      }
1446  
1447      /**
1448       * Delete the meta entries associated with a set of activity items.
1449       *
1450       * @since 1.2.0
1451       *
1452       * @param array $activity_ids Activity IDs whose meta should be deleted.
1453       * @return bool True on success.
1454       */
1455  	public static function delete_activity_meta_entries( $activity_ids = array() ) {
1456          $activity_ids = wp_parse_id_list( $activity_ids );
1457  
1458          foreach ( $activity_ids as $activity_id ) {
1459              bp_activity_delete_meta( $activity_id );
1460          }
1461  
1462          return true;
1463      }
1464  
1465      /**
1466       * Append activity comments to their associated activity items.
1467       *
1468       * @since 1.2.0
1469       *
1470       * @global wpdb $wpdb WordPress database object.
1471       *
1472       * @param array  $activities Activities to fetch comments for.
1473       * @param string $spam       Optional. 'ham_only' (default), 'spam_only' or 'all'.
1474       * @return array The updated activities with nested comments.
1475       */
1476  	public static function append_comments( $activities, $spam = 'ham_only' ) {
1477          $activity_comments = array();
1478  
1479          // Now fetch the activity comments and parse them into the correct position in the activities array.
1480          foreach ( (array) $activities as $activity ) {
1481              $top_level_parent_id = 'activity_comment' == $activity->type ? $activity->item_id : 0;
1482              $activity_comments[$activity->id] = BP_Activity_Activity::get_activity_comments( $activity->id, $activity->mptt_left, $activity->mptt_right, $spam, $top_level_parent_id );
1483          }
1484  
1485          // Merge the comments with the activity items.
1486          foreach ( (array) $activities as $key => $activity ) {
1487              if ( isset( $activity_comments[$activity->id] ) ) {
1488                  $activities[$key]->children = $activity_comments[$activity->id];
1489              }
1490          }
1491  
1492          return $activities;
1493      }
1494  
1495      /**
1496       * Get activity comments that are associated with a specific activity ID.
1497       *
1498       * @since 1.2.0
1499       *
1500       * @global wpdb $wpdb WordPress database object.
1501       *
1502       * @param int    $activity_id         Activity ID to fetch comments for.
1503       * @param int    $left                Left-most node boundary.
1504       * @param int    $right               Right-most node boundary.
1505       * @param string $spam                Optional. 'ham_only' (default), 'spam_only' or 'all'.
1506       * @param int    $top_level_parent_id Optional. The id of the root-level parent activity item.
1507       * @return array The updated activities with nested comments.
1508       */
1509  	public static function get_activity_comments( $activity_id, $left, $right, $spam = 'ham_only', $top_level_parent_id = 0 ) {
1510          global $wpdb;
1511  
1512          $function_args = func_get_args();
1513  
1514          if ( empty( $top_level_parent_id ) ) {
1515              $top_level_parent_id = $activity_id;
1516          }
1517  
1518          $comments = wp_cache_get( $activity_id, 'bp_activity_comments' );
1519  
1520          // We store the string 'none' to cache the fact that the
1521          // activity item has no comments.
1522          if ( 'none' === $comments ) {
1523              $comments = false;
1524  
1525              // A true cache miss.
1526          } elseif ( empty( $comments ) ) {
1527  
1528              $bp = buddypress();
1529  
1530              // Select the user's fullname with the query.
1531              if ( bp_is_active( 'xprofile' ) ) {
1532                  $fullname_select = ", pd.value as user_fullname";
1533                  $fullname_from = ", {$bp->profile->table_name_data} pd ";
1534                  $fullname_where = "AND pd.user_id = a.user_id AND pd.field_id = 1";
1535  
1536                  // Prevent debug errors.
1537              } else {
1538                  $fullname_select = $fullname_from = $fullname_where = '';
1539              }
1540  
1541              // Don't retrieve activity comments marked as spam.
1542              if ( 'ham_only' == $spam ) {
1543                  $spam_sql = 'AND a.is_spam = 0';
1544              } elseif ( 'spam_only' == $spam ) {
1545                  $spam_sql = 'AND a.is_spam = 1';
1546              } else {
1547                  $spam_sql = '';
1548              }
1549  
1550              // Legacy query - not recommended.
1551  
1552              /**
1553               * Filters if BuddyPress should use the legacy activity query.
1554               *
1555               * @since 2.0.0
1556               *
1557               * @param bool                 $value     Whether or not to use the legacy query.
1558               * @param BP_Activity_Activity $value     Magic method referring to currently called method.
1559               * @param array                $func_args Array of the method's argument list.
1560               */
1561              if ( apply_filters( 'bp_use_legacy_activity_query', false, __METHOD__, $function_args ) ) {
1562  
1563                  /**
1564                   * Filters the MySQL prepared statement for the legacy activity query.
1565                   *
1566                   * @since 1.5.0
1567                   *
1568                   * @param string $value       Prepared statement for the activity query.
1569                   * @param int    $activity_id Activity ID to fetch comments for.
1570                   * @param int    $left        Left-most node boundary.
1571                   * @param int    $right       Right-most node boundary.
1572                   * @param string $spam_sql    SQL Statement portion to differentiate between ham or spam.
1573                   */
1574                  $sql = apply_filters( 'bp_activity_comments_user_join_filter', $wpdb->prepare( "SELECT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name{$fullname_select} FROM {$bp->activity->table_name} a, {$wpdb->users} u{$fullname_from} WHERE u.ID = a.user_id {$fullname_where} AND a.type = 'activity_comment' {$spam_sql} AND a.item_id = %d AND a.mptt_left > %d AND a.mptt_left < %d ORDER BY a.date_recorded ASC", $top_level_parent_id, $left, $right ), $activity_id, $left, $right, $spam_sql );
1575  
1576                  $descendants = $wpdb->get_results( $sql );
1577  
1578                  // We use the mptt BETWEEN clause to limit returned
1579                  // descendants to the correct part of the tree.
1580              } else {
1581                  $sql = $wpdb->prepare( "SELECT id FROM {$bp->activity->table_name} a WHERE a.type = 'activity_comment' {$spam_sql} AND a.item_id = %d and a.mptt_left > %d AND a.mptt_left < %d ORDER BY a.date_recorded ASC", $top_level_parent_id, $left, $right );
1582  
1583                  $descendant_ids = $wpdb->get_col( $sql );
1584                  $descendants    = self::get_activity_data( $descendant_ids );
1585                  $descendants    = self::append_user_fullnames( $descendants );
1586                  $descendants    = self::generate_action_strings( $descendants );
1587              }
1588  
1589              $ref = array();
1590  
1591              // Loop descendants and build an assoc array.
1592              foreach ( (array) $descendants as $d ) {
1593                  $d->children = array();
1594  
1595                  // If we have a reference on the parent.
1596                  if ( isset( $ref[ $d->secondary_item_id ] ) ) {
1597                      $ref[ $d->secondary_item_id ]->children[ $d->id ] = $d;
1598                      $ref[ $d->id ] =& $ref[ $d->secondary_item_id ]->children[ $d->id ];
1599  
1600                      // If we don't have a reference on the parent, put in the root level.
1601                  } else {
1602                      $comments[ $d->id ] = $d;
1603                      $ref[ $d->id ] =& $comments[ $d->id ];
1604                  }
1605              }
1606  
1607              // Calculate depth for each item.
1608              foreach ( $ref as &$r ) {
1609                  $depth = 1;
1610                  $parent_id = $r->secondary_item_id;
1611  
1612                  while ( $parent_id !== $r->item_id ) {
1613                      $depth++;
1614  
1615                      // When display_comments=stream, the parent comment may not be part of the
1616                      // returned results, so we manually fetch it.
1617                      if ( empty( $ref[ $parent_id ] ) ) {
1618                          $direct_parent = new BP_Activity_Activity( $parent_id );
1619                          if ( isset( $direct_parent->secondary_item_id ) ) {
1620                              // If the direct parent is not an activity update, that means we've reached
1621                              // the parent activity item (eg. new_blog_post).
1622                              if ( 'activity_update' !== $direct_parent->type ) {
1623                                  $parent_id = $r->item_id;
1624  
1625                              } else {
1626                                  $parent_id = $direct_parent->secondary_item_id;
1627                              }
1628  
1629                          } else {
1630                              // Something went wrong.  Short-circuit the depth calculation.
1631                              $parent_id = $r->item_id;
1632                          }
1633                      } else {
1634                          $parent_id = $ref[ $parent_id ]->secondary_item_id;
1635                      }
1636                  }
1637                  $r->depth = $depth;
1638              }
1639  
1640              // If we cache a value of false, it'll count as a cache
1641              // miss the next time the activity comments are fetched.
1642              // Storing the string 'none' is a hack workaround to
1643              // avoid unnecessary queries.
1644              if ( false === $comments ) {
1645                  $cache_value = 'none';
1646              } else {
1647                  $cache_value = $comments;
1648              }
1649  
1650              wp_cache_set( $activity_id, $cache_value, 'bp_activity_comments' );
1651          }
1652  
1653          return $comments;
1654      }
1655  
1656      /**
1657       * Rebuild nested comment tree under an activity or activity comment.
1658       *
1659       * @since 1.2.0
1660       *
1661       * @global wpdb $wpdb WordPress database object.
1662       *
1663       * @param int $parent_id ID of an activity or activity comment.
1664       * @param int $left      Node boundary start for activity or activity comment.
1665       * @return int Right Node boundary of activity or activity comment.
1666       */
1667  	public static function rebuild_activity_comment_tree( $parent_id, $left = 1 ) {
1668          global $wpdb;
1669  
1670          $bp = buddypress();
1671  
1672          // The right value of this node is the left value + 1.
1673          $right = intval( $left + 1 );
1674  
1675          // Get all descendants of this node.
1676          $comments    = BP_Activity_Activity::get_child_comments( $parent_id );
1677          $descendants = wp_list_pluck( $comments, 'id' );
1678  
1679          // Loop the descendants and recalculate the left and right values.
1680          foreach ( (array) $descendants as $descendant_id ) {
1681              $right = BP_Activity_Activity::rebuild_activity_comment_tree( $descendant_id, $right );
1682          }
1683  
1684          // We've got the left value, and now that we've processed the children
1685          // of this node we also know the right value.
1686          if ( 1 === $left ) {
1687              $wpdb->query( $wpdb->prepare( "UPDATE {$bp->activity->table_name} SET mptt_left = %d, mptt_right = %d WHERE id = %d", $left, $right, $parent_id ) );
1688          } else {
1689              $wpdb->query( $wpdb->prepare( "UPDATE {$bp->activity->table_name} SET mptt_left = %d, mptt_right = %d WHERE type = 'activity_comment' AND id = %d", $left, $right, $parent_id ) );
1690          }
1691  
1692          // Return the right value of this node + 1.
1693          return intval( $right + 1 );
1694      }
1695  
1696      /**
1697       * Get child comments of an activity or activity comment.
1698       *
1699       * @since 1.2.0
1700       *
1701       * @global wpdb $wpdb WordPress database object.
1702       *
1703       * @param int $parent_id ID of an activity or activity comment.
1704       * @return object Numerically indexed array of child comments.
1705       */
1706  	public static function get_child_comments( $parent_id ) {
1707          global $wpdb;
1708  
1709          $bp = buddypress();
1710  
1711          return $wpdb->get_results( $wpdb->prepare( "SELECT id FROM {$bp->activity->table_name} WHERE type = 'activity_comment' AND secondary_item_id = %d", $parent_id ) );
1712      }
1713  
1714      /**
1715       * Get a list of components that have recorded activity associated with them.
1716       *
1717       * @since 1.2.0
1718       *
1719       * @param bool $skip_last_activity If true, components will not be
1720       *                                 included if the only activity type associated with them is
1721       *                                 'last_activity'. (Since 2.0.0, 'last_activity' is stored in
1722       *                                 the activity table, but these items are not full-fledged
1723       *                                 activity items.) Default: true.
1724       * @return array List of component names.
1725       */
1726  	public static function get_recorded_components( $skip_last_activity = true ) {
1727          global $wpdb;
1728  
1729          $bp = buddypress();
1730  
1731          if ( true === $skip_last_activity ) {
1732              $components = $wpdb->get_col( "SELECT DISTINCT component FROM {$bp->activity->table_name} WHERE action != '' AND action != 'last_activity' ORDER BY component ASC" );
1733          } else {
1734              $components = $wpdb->get_col( "SELECT DISTINCT component FROM {$bp->activity->table_name} ORDER BY component ASC" );
1735          }
1736  
1737          return $components;
1738      }
1739  
1740      /**
1741       * Get sitewide activity items for use in an RSS feed.
1742       *
1743       * @since 1.0.0
1744       *
1745       * @param int $limit Optional. Number of items to fetch. Default: 35.
1746       * @return array $activity_feed List of activity items, with RSS data added.
1747       */
1748  	public static function get_sitewide_items_for_feed( $limit = 35 ) {
1749          $activities    = bp_activity_get_sitewide( array( 'max' => $limit ) );
1750          $activity_feed = array();
1751  
1752          for ( $i = 0, $count = count( $activities ); $i < $count; ++$i ) {
1753              $title                            = explode( '<span', $activities[$i]['content'] );
1754              $activity_feed[$i]['title']       = trim( strip_tags( $title[0] ) );
1755              $activity_feed[$i]['link']        = $activities[$i]['primary_link'];
1756              $activity_feed[$i]['description'] = @sprintf( $activities[$i]['content'], '' );
1757              $activity_feed[$i]['pubdate']     = $activities[$i]['date_recorded'];
1758          }
1759  
1760          return $activity_feed;
1761      }
1762  
1763      /**
1764       * Create SQL IN clause for filter queries.
1765       *
1766       * @since 1.5.0
1767       *
1768       * @see BP_Activity_Activity::get_filter_sql()
1769       *
1770       * @param string     $field The database field.
1771       * @param array|bool $items The values for the IN clause, or false when none are found.
1772       * @return string|false
1773       */
1774  	public static function get_in_operator_sql( $field, $items ) {
1775          global $wpdb;
1776  
1777          // Split items at the comma.
1778          if ( ! is_array( $items ) ) {
1779              $items = explode( ',', $items );
1780          }
1781  
1782          // Array of prepared integers or quoted strings.
1783          $items_prepared = array();
1784  
1785          // Clean up and format each item.
1786          foreach ( $items as $item ) {
1787              // Clean up the string.
1788              $item = trim( $item );
1789              // Pass everything through prepare for security and to safely quote strings.
1790              $items_prepared[] = ( is_numeric( $item ) ) ? $wpdb->prepare( '%d', $item ) : $wpdb->prepare( '%s', $item );
1791          }
1792  
1793          // Build IN operator sql syntax.
1794          if ( count( $items_prepared ) )
1795              return sprintf( '%s IN ( %s )', trim( $field ), implode( ',', $items_prepared ) );
1796          else
1797              return false;
1798      }
1799  
1800      /**
1801       * Create filter SQL clauses.
1802       *
1803       * @since 1.5.0
1804       *
1805       * @param array $filter_array {
1806       *     Fields and values to filter by.
1807       *
1808       *     @type array|string|int $user_id      User ID(s).
1809       *     @type array|string     $object       Corresponds to the 'component'
1810       *                                          column in the database.
1811       *     @type array|string     $action       Corresponds to the 'type' column
1812       *                                          in the database.
1813       *     @type array|string|int $primary_id   Corresponds to the 'item_id'
1814       *                                          column in the database.
1815       *     @type array|string|int $secondary_id Corresponds to the
1816       *                                          'secondary_item_id' column in the database.
1817       *     @type int              $offset       Return only those items with an ID greater
1818       *                                          than the offset value.
1819       *     @type string           $since        Return only those items that have a
1820       *                                          date_recorded value greater than a
1821       *                                          given MySQL-formatted date.
1822       * }
1823       * @return string The filter clause, for use in a SQL query.
1824       */
1825  	public static function get_filter_sql( $filter_array ) {
1826  
1827          $filter_sql = array();
1828  
1829          if ( !empty( $filter_array['user_id'] ) ) {
1830              $user_sql = BP_Activity_Activity::get_in_operator_sql( 'a.user_id', $filter_array['user_id'] );
1831              if ( !empty( $user_sql ) )
1832                  $filter_sql[] = $user_sql;
1833          }
1834  
1835          if ( !empty( $filter_array['object'] ) ) {
1836              $object_sql = BP_Activity_Activity::get_in_operator_sql( 'a.component', $filter_array['object'] );
1837              if ( !empty( $object_sql ) )
1838                  $filter_sql[] = $object_sql;
1839          }
1840  
1841          if ( !empty( $filter_array['action'] ) ) {
1842              $action_sql = BP_Activity_Activity::get_in_operator_sql( 'a.type', $filter_array['action'] );
1843              if ( ! empty( $action_sql ) )
1844                  $filter_sql[] = $action_sql;
1845          }
1846  
1847          if ( !empty( $filter_array['primary_id'] ) ) {
1848              $pid_sql = BP_Activity_Activity::get_in_operator_sql( 'a.item_id', $filter_array['primary_id'] );
1849              if ( !empty( $pid_sql ) )
1850                  $filter_sql[] = $pid_sql;
1851          }
1852  
1853          if ( !empty( $filter_array['secondary_id'] ) ) {
1854              $sid_sql = BP_Activity_Activity::get_in_operator_sql( 'a.secondary_item_id', $filter_array['secondary_id'] );
1855              if ( !empty( $sid_sql ) )
1856                  $filter_sql[] = $sid_sql;
1857          }
1858  
1859          if ( ! empty( $filter_array['offset'] ) ) {
1860              $sid_sql = absint( $filter_array['offset'] );
1861              $filter_sql[] = "a.id >= {$sid_sql}";
1862          }
1863  
1864          if ( ! empty( $filter_array['since'] ) ) {
1865              // Validate that this is a proper Y-m-d H:i:s date.
1866              // Trick: parse to UNIX date then translate back.
1867              $translated_date = date( 'Y-m-d H:i:s', strtotime( $filter_array['since'] ) );
1868              if ( $translated_date === $filter_array['since'] ) {
1869                  $filter_sql[] = "a.date_recorded > '{$translated_date}'";
1870              }
1871          }
1872  
1873          if ( empty( $filter_sql ) )
1874              return false;
1875  
1876          return join( ' AND ', $filter_sql );
1877      }
1878  
1879      /**
1880       * Get the date/time of last recorded activity.
1881       *
1882       * @since 1.2.0
1883       *
1884       * @return string ISO timestamp.
1885       */
1886  	public static function get_last_updated() {
1887          global $wpdb;
1888  
1889          $bp = buddypress();
1890  
1891          return $wpdb->get_var( "SELECT date_recorded FROM {$bp->activity->table_name} ORDER BY date_recorded DESC LIMIT 1" );
1892      }
1893  
1894      /**
1895       * Get favorite count for a given user.
1896       *
1897       * @since 1.2.0
1898       *
1899       * @param int $user_id The ID of the user whose favorites you're counting.
1900       * @return int $value A count of the user's favorites.
1901       */
1902  	public static function total_favorite_count( $user_id ) {
1903  
1904          // Get activities from user meta.
1905          $favorite_activity_entries = bp_get_user_meta( $user_id, 'bp_favorite_activities', true );
1906          if ( ! empty( $favorite_activity_entries ) ) {
1907              return count( $favorite_activity_entries );
1908          }
1909  
1910          // No favorites.
1911          return 0;
1912      }
1913  
1914      /**
1915       * Check whether an activity item exists with a given string content.
1916       *
1917       * @since 1.1.0
1918       *
1919       * @param string $content The content to filter by.
1920       * @return int|false The ID of the first matching item if found, otherwise false.
1921       */
1922  	public static function check_exists_by_content( $content ) {
1923          global $wpdb;
1924  
1925          $bp = buddypress();
1926  
1927          $result = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$bp->activity->table_name} WHERE content = %s", $content ) );
1928  
1929          return is_numeric( $result ) ? (int) $result : false;
1930      }
1931  
1932      /**
1933       * Hide all activity for a given user.
1934       *
1935       * @since 1.2.0
1936       *
1937       * @param int $user_id The ID of the user whose activity you want to mark hidden.
1938       * @return mixed
1939       */
1940  	public static function hide_all_for_user( $user_id ) {
1941          global $wpdb;
1942  
1943          $bp = buddypress();
1944  
1945          return $wpdb->get_var( $wpdb->prepare( "UPDATE {$bp->activity->table_name} SET hide_sitewide = 1 WHERE user_id = %d", $user_id ) );
1946      }
1947  }


Generated: Thu Oct 28 01:00:59 2021 Cross-referenced by PHPXref 0.7.1