Example #1
0
 /**
  * @group bp_activity_update_meta_cache
  */
 public function test_bp_activity_update_meta_cache()
 {
     $a1 = $this->factory->activity->create();
     $a2 = $this->factory->activity->create();
     // Set up some data
     bp_activity_update_meta($a1, 'foo', 'bar');
     bp_activity_update_meta($a1, 'Boone', 'Rules');
     bp_activity_update_meta($a2, 'foo', 'baz');
     bp_activity_update_meta($a2, 'BuddyPress', 'Is Cool');
     // Prime the cache for $a1
     bp_activity_get_meta($a1, 'foo');
     // Ensure an empty cache for $a2
     wp_cache_delete($a2, 'activity_meta');
     bp_activity_update_meta_cache(array($a1, $a2));
     $expected = array($a1 => array('foo' => array('bar'), 'Boone' => array('Rules')), $a2 => array('foo' => array('baz'), 'BuddyPress' => array('Is Cool')));
     $found = array($a1 => wp_cache_get($a1, 'activity_meta'), $a2 => wp_cache_get($a2, 'activity_meta'));
     $this->assertEquals($expected, $found);
 }
 /**
  * Get activity items, as specified by parameters
  *
  * @param array $args See $defaults for explanation of arguments
  * @return array
  */
 function get($args = array())
 {
     global $wpdb, $bp;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'max', 1 => 'page', 2 => 'per_page', 3 => 'sort', 4 => 'search_terms', 5 => 'filter', 6 => 'display_comments', 7 => 'show_hidden', 8 => 'exclude', 9 => 'in', 10 => 'spam');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('page' => 1, 'per_page' => 25, 'max' => false, 'sort' => 'DESC', 'exclude' => false, 'in' => false, 'meta_query' => false, 'filter' => false, 'search_terms' => false, 'display_comments' => false, 'show_hidden' => false, 'spam' => 'ham_only');
     $r = wp_parse_args($args, $defaults);
     extract($r);
     // Select conditions
     $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
     $from_sql = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
     $join_sql = '';
     // Where conditions
     $where_conditions = array();
     // Spam
     if ('ham_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 0';
     } elseif ('spam_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 1';
     }
     // Searching
     if ($search_terms) {
         $search_terms = esc_sql($search_terms);
         $where_conditions['search_sql'] = "a.content LIKE '%%" . esc_sql(like_escape($search_terms)) . "%%'";
     }
     // Filtering
     if ($filter && ($filter_sql = BP_Activity_Activity::get_filter_sql($filter))) {
         $where_conditions['filter_sql'] = $filter_sql;
     }
     // Sorting
     if ($sort != 'ASC' && $sort != 'DESC') {
         $sort = 'DESC';
     }
     // Hide Hidden Items?
     if (!$show_hidden) {
         $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
     }
     // Exclude specified items
     if (!empty($exclude)) {
         $exclude = implode(',', wp_parse_id_list($exclude));
         $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
     }
     // The specific ids to which you want to limit the query
     if (!empty($in)) {
         $in = implode(',', wp_parse_id_list($in));
         $where_conditions['in'] = "a.id IN ({$in})";
     }
     // Process meta_query into SQL
     $meta_query_sql = self::get_meta_query_sql($meta_query);
     if (!empty($meta_query_sql['join'])) {
         $join_sql .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions[] = $meta_query_sql['where'];
     }
     // Alter the query based on whether we want to show activity item
     // comments in the stream like normal comments or threaded below
     // the activity.
     if (false === $display_comments || 'threaded' === $display_comments) {
         $where_conditions[] = "a.type != 'activity_comment'";
     }
     $where_sql = 'WHERE ' . join(' AND ', $where_conditions);
     // Define the preferred order for indexes
     $indexes = apply_filters('bp_activity_preferred_index_order', array('user_id', 'item_id', 'secondary_item_id', 'date_recorded', 'component', 'type', 'hide_sitewide', 'is_spam'));
     foreach ($indexes as $key => $index) {
         if (false !== strpos($where_sql, $index)) {
             $the_index = $index;
             break;
             // Take the first one we find
         }
     }
     if (!empty($the_index)) {
         $index_hint_sql = "USE INDEX ({$the_index})";
     } else {
         $index_hint_sql = '';
     }
     if (!empty($per_page) && !empty($page)) {
         // Make sure page values are absolute integers
         $page = absint($page);
         $per_page = absint($per_page);
         $pag_sql = $wpdb->prepare("LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page);
         $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
     } else {
         $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $select_sql, $from_sql, $where_sql, $sort));
     }
     $total_activities_sql = apply_filters('bp_activity_total_activities_sql', "SELECT count(DISTINCT a.id) FROM {$bp->activity->table_name} a {$index_hint_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $where_sql, $sort);
     $total_activities = $wpdb->get_var($total_activities_sql);
     // Get the fullnames of users so we don't have to query in the loop
     if (bp_is_active('xprofile') && !empty($activities)) {
         $activity_user_ids = wp_list_pluck($activities, 'user_id');
         $activity_user_ids = implode(',', wp_parse_id_list($activity_user_ids));
         if (!empty($activity_user_ids)) {
             if ($names = $wpdb->get_results("SELECT user_id, value AS user_fullname FROM {$bp->profile->table_name_data} WHERE field_id = 1 AND user_id IN ({$activity_user_ids})")) {
                 foreach ((array) $names as $name) {
                     $tmp_names[$name->user_id] = $name->user_fullname;
                 }
                 foreach ((array) $activities as $i => $activity) {
                     if (!empty($tmp_names[$activity->user_id])) {
                         $activities[$i]->user_fullname = $tmp_names[$activity->user_id];
                     }
                 }
                 unset($names);
                 unset($tmp_names);
             }
         }
     }
     // Get activity meta
     $activity_ids = array();
     foreach ((array) $activities as $activity) {
         $activity_ids[] = $activity->id;
     }
     if (!empty($activity_ids)) {
         bp_activity_update_meta_cache($activity_ids);
     }
     if ($activities && $display_comments) {
         $activities = BP_Activity_Activity::append_comments($activities, $spam);
     }
     // If $max is set, only return up to the max results
     if (!empty($max)) {
         if ((int) $total_activities > (int) $max) {
             $total_activities = $max;
         }
     }
     return array('activities' => $activities, 'total' => (int) $total_activities);
 }
 /**
  * Get activity items, as specified by parameters.
  *
  * @since 1.0.0
  * @since 2.4.0 Introduced the `$fields` parameter.
  *
  * @see BP_Activity_Activity::get_filter_sql() for a description of the
  *      'filter' parameter.
  * @see WP_Meta_Query::queries for a description of the 'meta_query'
  *      parameter format.
  *
  * @param array $args {
  *     An array of arguments. All items are optional.
  *     @type int          $page              Which page of results to fetch. Using page=1 without per_page will result
  *                                           in no pagination. Default: 1.
  *     @type int|bool     $per_page          Number of results per page. Default: 25.
  *     @type int|bool     $max               Maximum number of results to return. Default: false (unlimited).
  *     @type string       $fields            Activity fields to return. Pass 'ids' to get only the activity IDs.
  *                                           'all' returns full activity objects.
  *     @type string       $sort              ASC or DESC. Default: 'DESC'.
  *     @type array        $exclude           Array of activity IDs to exclude. Default: false.
  *     @type array        $in                Array of ids to limit query by (IN). Default: false.
  *     @type array        $meta_query        Array of meta_query conditions. See WP_Meta_Query::queries.
  *     @type array        $date_query        Array of date_query conditions. See first parameter of
  *                                           WP_Date_Query::__construct().
  *     @type array        $filter_query      Array of advanced query conditions. See BP_Activity_Query::__construct().
  *     @type string|array $scope             Pre-determined set of activity arguments.
  *     @type array        $filter            See BP_Activity_Activity::get_filter_sql().
  *     @type string       $search_terms      Limit results by a search term. Default: false.
  *     @type bool         $display_comments  Whether to include activity comments. Default: false.
  *     @type bool         $show_hidden       Whether to show items marked hide_sitewide. Default: false.
  *     @type string       $spam              Spam status. Default: 'ham_only'.
  *     @type bool         $update_meta_cache Whether to pre-fetch metadata for queried activity items. Default: true.
  *     @type string|bool  $count_total       If true, an additional DB query is run to count the total activity items
  *                                           for the query. Default: false.
  * }
  * @return array The array returned has two keys:
  *               - 'total' is the count of located activities
  *               - 'activities' is an array of the located activities
  */
 public static function get($args = array())
 {
     global $wpdb;
     // Backward compatibility with old method of passing arguments.
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'max', 1 => 'page', 2 => 'per_page', 3 => 'sort', 4 => 'search_terms', 5 => 'filter', 6 => 'display_comments', 7 => 'show_hidden', 8 => 'exclude', 9 => 'in', 10 => 'spam');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $bp = buddypress();
     $r = wp_parse_args($args, array('page' => 1, 'per_page' => 25, 'max' => false, 'fields' => 'all', 'sort' => 'DESC', 'exclude' => false, 'in' => false, 'meta_query' => false, 'date_query' => false, 'filter_query' => false, 'filter' => false, 'scope' => false, 'search_terms' => false, 'display_comments' => false, 'show_hidden' => false, 'spam' => 'ham_only', 'update_meta_cache' => true, 'count_total' => false));
     // Select conditions.
     $select_sql = "SELECT DISTINCT a.id";
     $from_sql = " FROM {$bp->activity->table_name} a";
     $join_sql = '';
     // Where conditions.
     $where_conditions = array();
     // Excluded types.
     $excluded_types = array();
     // Scope takes precedence.
     if (!empty($r['scope'])) {
         $scope_query = self::get_scope_query_sql($r['scope'], $r);
         // Add our SQL conditions if matches were found.
         if (!empty($scope_query['sql'])) {
             $where_conditions['scope_query_sql'] = $scope_query['sql'];
         }
         // Override some arguments if needed.
         if (!empty($scope_query['override'])) {
             $r = self::array_replace_recursive($r, $scope_query['override']);
         }
         // Advanced filtering.
     } elseif (!empty($r['filter_query'])) {
         $filter_query = new BP_Activity_Query($r['filter_query']);
         $sql = $filter_query->get_sql();
         if (!empty($sql)) {
             $where_conditions['filter_query_sql'] = $sql;
         }
     }
     // Regular filtering.
     if ($r['filter'] && ($filter_sql = BP_Activity_Activity::get_filter_sql($r['filter']))) {
         $where_conditions['filter_sql'] = $filter_sql;
     }
     // Spam.
     if ('ham_only' == $r['spam']) {
         $where_conditions['spam_sql'] = 'a.is_spam = 0';
     } elseif ('spam_only' == $r['spam']) {
         $where_conditions['spam_sql'] = 'a.is_spam = 1';
     }
     // Searching.
     if ($r['search_terms']) {
         $search_terms_like = '%' . bp_esc_like($r['search_terms']) . '%';
         $where_conditions['search_sql'] = $wpdb->prepare('a.content LIKE %s', $search_terms_like);
     }
     // Sorting.
     $sort = $r['sort'];
     if ($sort != 'ASC' && $sort != 'DESC') {
         $sort = 'DESC';
     }
     // Hide Hidden Items?
     if (!$r['show_hidden']) {
         $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
     }
     // Exclude specified items.
     if (!empty($r['exclude'])) {
         $exclude = implode(',', wp_parse_id_list($r['exclude']));
         $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
     }
     // The specific ids to which you want to limit the query.
     if (!empty($r['in'])) {
         $in = implode(',', wp_parse_id_list($r['in']));
         $where_conditions['in'] = "a.id IN ({$in})";
     }
     // Process meta_query into SQL.
     $meta_query_sql = self::get_meta_query_sql($r['meta_query']);
     if (!empty($meta_query_sql['join'])) {
         $join_sql .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions[] = $meta_query_sql['where'];
     }
     // Process date_query into SQL.
     $date_query_sql = self::get_date_query_sql($r['date_query']);
     if (!empty($date_query_sql)) {
         $where_conditions['date'] = $date_query_sql;
     }
     // Alter the query based on whether we want to show activity item
     // comments in the stream like normal comments or threaded below
     // the activity.
     if (false === $r['display_comments'] || 'threaded' === $r['display_comments']) {
         $excluded_types[] = 'activity_comment';
     }
     // Exclude 'last_activity' items unless the 'action' filter has
     // been explicitly set.
     if (empty($r['filter']['object'])) {
         $excluded_types[] = 'last_activity';
     }
     // Build the excluded type sql part.
     if (!empty($excluded_types)) {
         $not_in = "'" . implode("', '", esc_sql($excluded_types)) . "'";
         $where_conditions['excluded_types'] = "a.type NOT IN ({$not_in})";
     }
     /**
      * Filters the MySQL WHERE conditions for the Activity items get method.
      *
      * @since 1.9.0
      *
      * @param array  $where_conditions Current conditions for MySQL WHERE statement.
      * @param array  $r                Parsed arguments passed into method.
      * @param string $select_sql       Current SELECT MySQL statement at point of execution.
      * @param string $from_sql         Current FROM MySQL statement at point of execution.
      * @param string $join_sql         Current INNER JOIN MySQL statement at point of execution.
      */
     $where_conditions = apply_filters('bp_activity_get_where_conditions', $where_conditions, $r, $select_sql, $from_sql, $join_sql);
     // Join the where conditions together.
     $where_sql = 'WHERE ' . join(' AND ', $where_conditions);
     /**
      * Filters the preferred order of indexes for activity item.
      *
      * @since 1.6.0
      *
      * @param array $value Array of indexes in preferred order.
      */
     $indexes = apply_filters('bp_activity_preferred_index_order', array('user_id', 'item_id', 'secondary_item_id', 'date_recorded', 'component', 'type', 'hide_sitewide', 'is_spam'));
     foreach ($indexes as $key => $index) {
         if (false !== strpos($where_sql, $index)) {
             $the_index = $index;
             break;
             // Take the first one we find.
         }
     }
     if (!empty($the_index)) {
         $index_hint_sql = "USE INDEX ({$the_index})";
     } else {
         $index_hint_sql = '';
     }
     // Sanitize page and per_page parameters.
     $page = absint($r['page']);
     $per_page = absint($r['per_page']);
     $retval = array('activities' => null, 'total' => null, 'has_more_items' => null);
     /**
      * Filters if BuddyPress should use legacy query structure over current structure for version 2.0+.
      *
      * It is not recommended to use the legacy structure, but allowed to if needed.
      *
      * @since 2.0.0
      *
      * @param bool                 $value Whether to use legacy structure or not.
      * @param BP_Activity_Activity $value Current method being called.
      * @param array                $r     Parsed arguments passed into method.
      */
     if (apply_filters('bp_use_legacy_activity_query', false, __METHOD__, $r)) {
         // Legacy queries joined against the user table.
         $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
         $from_sql = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
         if (!empty($page) && !empty($per_page)) {
             $pag_sql = $wpdb->prepare("LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page);
             /** This filter is documented in bp-activity/bp-activity-classes.php */
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
         } else {
             $pag_sql = '';
             /**
              * Filters the legacy MySQL query statement so plugins can alter before results are fetched.
              *
              * @since 1.5.0
              *
              * @param string $value      Concatenated MySQL statement pieces to be query results with for legacy query.
              * @param string $select_sql Final SELECT MySQL statement portion for legacy query.
              * @param string $from_sql   Final FROM MySQL statement portion for legacy query.
              * @param string $where_sql  Final WHERE MySQL statement portion for legacy query.
              * @param string $sort       Final sort direction for legacy query.
              */
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
         }
     } else {
         // Query first for activity IDs.
         $activity_ids_sql = "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}";
         if (!empty($per_page) && !empty($page)) {
             // We query for $per_page + 1 items in order to
             // populate the has_more_items flag.
             $activity_ids_sql .= $wpdb->prepare(" LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page + 1);
         }
         /**
          * Filters the paged activities MySQL statement.
          *
          * @since 2.0.0
          *
          * @param string $activity_ids_sql MySQL statement used to query for Activity IDs.
          * @param array  $r                Array of arguments passed into method.
          */
         $activity_ids_sql = apply_filters('bp_activity_paged_activities_sql', $activity_ids_sql, $r);
         $activity_ids = $wpdb->get_col($activity_ids_sql);
         $retval['has_more_items'] = !empty($per_page) && count($activity_ids) > $per_page;
         // If we've fetched more than the $per_page value, we
         // can discard the extra now.
         if (!empty($per_page) && count($activity_ids) === $per_page + 1) {
             array_pop($activity_ids);
         }
         if ('ids' === $r['fields']) {
             $activities = array_map('intval', $activity_ids);
         } else {
             $activities = self::get_activity_data($activity_ids);
         }
     }
     if ('ids' !== $r['fields']) {
         // Get the fullnames of users so we don't have to query in the loop.
         $activities = self::append_user_fullnames($activities);
         // Get activity meta.
         $activity_ids = array();
         foreach ((array) $activities as $activity) {
             $activity_ids[] = $activity->id;
         }
         if (!empty($activity_ids) && $r['update_meta_cache']) {
             bp_activity_update_meta_cache($activity_ids);
         }
         if ($activities && $r['display_comments']) {
             $activities = BP_Activity_Activity::append_comments($activities, $r['spam']);
         }
         // Pre-fetch data associated with activity users and other objects.
         BP_Activity_Activity::prefetch_object_data($activities);
         // Generate action strings.
         $activities = BP_Activity_Activity::generate_action_strings($activities);
     }
     $retval['activities'] = $activities;
     // If $max is set, only return up to the max results.
     if (!empty($r['count_total'])) {
         /**
          * Filters the total activities MySQL statement.
          *
          * @since 1.5.0
          *
          * @param string $value     MySQL statement used to query for total activities.
          * @param string $where_sql MySQL WHERE statement portion.
          * @param string $sort      Sort direction for query.
          */
         $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);
         $total_activities = $wpdb->get_var($total_activities_sql);
         if (!empty($r['max'])) {
             if ((int) $total_activities > (int) $r['max']) {
                 $total_activities = $r['max'];
             }
         }
         $retval['total'] = $total_activities;
     }
     return $retval;
 }
Example #4
0
 /**
  * Get activity items, as specified by parameters
  *
  * @see BP_Activity_Activity::get_filter_sql() for a description of the
  *      'filter' parameter.
  * @see WP_Meta_Query::queries for a description of the 'meta_query'
  *      parameter format.
  *
  * @param array $args {
  *     An array of arguments. All items are optional.
  *     @type int $page Which page of results to fetch. Using page=1
  *                     without per_page will result in no pagination.
  *                     Default: 1.
  *     @type int|bool $per_page Number of results per page. Default: 25.
  *     @type int|bool $max Maximum number of results to return.
  *                         Default: false (unlimited).
  *     @type string $sort ASC or DESC. Default: 'DESC'.
  *     @type array $exclude Array of activity IDs to exclude.
  *                          Default: false.
  *     @type array $in Array of ids to limit query by (IN).
  *                     Default: false.
  *     @type array $meta_query An array of meta_query conditions.
  *                             See WP_Meta_Query::queries for description.
  *     @type array $date_query An array of date_query conditions.
  *                             See first parameter of WP_Date_Query::__construct()
  *                             for description.
  *     @type array $filter See BP_Activity_Activity::get_filter_sql().
  *     @type string $search_terms Limit results by a search term.
  *                                Default: false.
  *     @type bool $display_comments Whether to include activity comments.
  *                                  Default: false.
  *     @type bool $show_hidden Whether to show items marked hide_sitewide.
  *                             Default: false.
  *     @type string $spam Spam status. Default: 'ham_only'.
  *     @type bool $update_meta_cache Whether to pre-fetch metadata for
  *           queried activity items. Default: true.
  *     @type string|bool $count_total If true, an additional DB query
  *           is run to count the total activity items for the query.
  *           Default: false.
  * }
  * @return array The array returned has two keys:
  *     - 'total' is the count of located activities
  *     - 'activities' is an array of the located activities
  */
 public static function get($args = array())
 {
     global $wpdb, $bp;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.6', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress'), __METHOD__, __FILE__));
         $old_args_keys = array(0 => 'max', 1 => 'page', 2 => 'per_page', 3 => 'sort', 4 => 'search_terms', 5 => 'filter', 6 => 'display_comments', 7 => 'show_hidden', 8 => 'exclude', 9 => 'in', 10 => 'spam');
         $func_args = func_get_args();
         $args = bp_core_parse_args_array($old_args_keys, $func_args);
     }
     $defaults = array('page' => 1, 'per_page' => 25, 'max' => false, 'sort' => 'DESC', 'exclude' => false, 'in' => false, 'meta_query' => false, 'date_query' => false, 'filter' => false, 'search_terms' => false, 'display_comments' => false, 'show_hidden' => false, 'spam' => 'ham_only', 'update_meta_cache' => true, 'count_total' => false);
     $r = wp_parse_args($args, $defaults);
     extract($r);
     // Select conditions
     $select_sql = "SELECT DISTINCT a.id";
     $from_sql = " FROM {$bp->activity->table_name} a";
     $join_sql = '';
     // Where conditions
     $where_conditions = array();
     // Excluded types
     $excluded_types = array();
     // Spam
     if ('ham_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 0';
     } elseif ('spam_only' == $spam) {
         $where_conditions['spam_sql'] = 'a.is_spam = 1';
     }
     // Searching
     if ($search_terms) {
         $search_terms_like = '%' . bp_esc_like($search_terms) . '%';
         $where_conditions['search_sql'] = $wpdb->prepare('a.content LIKE %s', $search_terms_like);
     }
     // Filtering
     if ($filter && ($filter_sql = BP_Activity_Activity::get_filter_sql($filter))) {
         $where_conditions['filter_sql'] = $filter_sql;
     }
     // Sorting
     if ($sort != 'ASC' && $sort != 'DESC') {
         $sort = 'DESC';
     }
     // Hide Hidden Items?
     if (!$show_hidden) {
         $where_conditions['hidden_sql'] = "a.hide_sitewide = 0";
     }
     // Exclude specified items
     if (!empty($exclude)) {
         $exclude = implode(',', wp_parse_id_list($exclude));
         $where_conditions['exclude'] = "a.id NOT IN ({$exclude})";
     }
     // The specific ids to which you want to limit the query
     if (!empty($in)) {
         $in = implode(',', wp_parse_id_list($in));
         $where_conditions['in'] = "a.id IN ({$in})";
     }
     // Process meta_query into SQL
     $meta_query_sql = self::get_meta_query_sql($meta_query);
     if (!empty($meta_query_sql['join'])) {
         $join_sql .= $meta_query_sql['join'];
     }
     if (!empty($meta_query_sql['where'])) {
         $where_conditions[] = $meta_query_sql['where'];
     }
     // Process date_query into SQL
     $date_query_sql = self::get_date_query_sql($date_query);
     if (!empty($date_query_sql)) {
         $where_conditions['date'] = $date_query_sql;
     }
     // Alter the query based on whether we want to show activity item
     // comments in the stream like normal comments or threaded below
     // the activity.
     if (false === $display_comments || 'threaded' === $display_comments) {
         $excluded_types[] = 'activity_comment';
     }
     // Exclude 'last_activity' items unless the 'action' filter has
     // been explicitly set
     if (empty($filter['object'])) {
         $excluded_types[] = 'last_activity';
     }
     // Exclude 'new_member' items if xprofile component is not active
     if (!bp_is_active('xprofile')) {
         $excluded_types[] = 'new_member';
     }
     // Build the excluded type sql part
     if (!empty($excluded_types)) {
         $not_in = "'" . implode("', '", esc_sql($excluded_types)) . "'";
         $where_conditions['excluded_types'] = "a.type NOT IN ({$not_in})";
     }
     // Filter the where conditions
     $where_conditions = apply_filters('bp_activity_get_where_conditions', $where_conditions, $r, $select_sql, $from_sql, $join_sql);
     // Join the where conditions together
     $where_sql = 'WHERE ' . join(' AND ', $where_conditions);
     // Define the preferred order for indexes
     $indexes = apply_filters('bp_activity_preferred_index_order', array('user_id', 'item_id', 'secondary_item_id', 'date_recorded', 'component', 'type', 'hide_sitewide', 'is_spam'));
     foreach ($indexes as $key => $index) {
         if (false !== strpos($where_sql, $index)) {
             $the_index = $index;
             break;
             // Take the first one we find
         }
     }
     if (!empty($the_index)) {
         $index_hint_sql = "USE INDEX ({$the_index})";
     } else {
         $index_hint_sql = '';
     }
     // Sanitize page and per_page parameters
     $page = absint($page);
     $per_page = absint($per_page);
     $retval = array('activities' => null, 'total' => null, 'has_more_items' => null);
     // Filter and return true to use the legacy query structure (not recommended)
     if (apply_filters('bp_use_legacy_activity_query', false, __METHOD__, $r)) {
         // Legacy queries joined against the user table
         $select_sql = "SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name";
         $from_sql = " FROM {$bp->activity->table_name} a LEFT JOIN {$wpdb->users} u ON a.user_id = u.ID";
         if (!empty($page) && !empty($per_page)) {
             $pag_sql = $wpdb->prepare("LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page);
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort} {$pag_sql}", $select_sql, $from_sql, $where_sql, $sort, $pag_sql));
         } else {
             $activities = $wpdb->get_results(apply_filters('bp_activity_get_user_join_filter', "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}", $select_sql, $from_sql, $where_sql, $sort));
         }
     } else {
         // Query first for activity IDs
         $activity_ids_sql = "{$select_sql} {$from_sql} {$join_sql} {$where_sql} ORDER BY a.date_recorded {$sort}";
         if (!empty($per_page) && !empty($page)) {
             // We query for $per_page + 1 items in order to
             // populate the has_more_items flag
             $activity_ids_sql .= $wpdb->prepare(" LIMIT %d, %d", absint(($page - 1) * $per_page), $per_page + 1);
         }
         $activity_ids_sql = apply_filters('bp_activity_paged_activities_sql', $activity_ids_sql, $r);
         $activity_ids = $wpdb->get_col($activity_ids_sql);
         $retval['has_more_items'] = !empty($per_page) && count($activity_ids) > $per_page;
         // If we've fetched more than the $per_page value, we
         // can discard the extra now
         if (!empty($per_page) && count($activity_ids) === $per_page + 1) {
             array_pop($activity_ids);
         }
         $activities = self::get_activity_data($activity_ids);
     }
     // Get the fullnames of users so we don't have to query in the loop
     $activities = self::append_user_fullnames($activities);
     // Get activity meta
     $activity_ids = array();
     foreach ((array) $activities as $activity) {
         $activity_ids[] = $activity->id;
     }
     if (!empty($activity_ids) && $update_meta_cache) {
         bp_activity_update_meta_cache($activity_ids);
     }
     if ($activities && $display_comments) {
         $activities = BP_Activity_Activity::append_comments($activities, $spam);
     }
     // Pre-fetch data associated with activity users and other objects
     BP_Activity_Activity::prefetch_object_data($activities);
     // Generate action strings
     $activities = BP_Activity_Activity::generate_action_strings($activities);
     $retval['activities'] = $activities;
     // If $max is set, only return up to the max results
     if (!empty($r['count_total'])) {
         $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);
         $total_activities = $wpdb->get_var($total_activities_sql);
         if (!empty($max)) {
             if ((int) $total_activities > (int) $max) {
                 $total_activities = $max;
             }
         }
         $retval['total'] = $total_activities;
     }
     return $retval;
 }
function mpp_delete_activity_for_single_published_media($media_id)
{
    if (!function_exists('bp_is_active') || !bp_is_active('activity')) {
        return false;
        //or false?
    }
    global $wpdb;
    $bp = buddypress();
    //select ids , we need to delete comment too?
    $query = "SELECT activity_id FROM {$bp->activity->table_name_meta} WHERE  ( meta_key = %s AND meta_value = %d ) OR ( meta_key = %s AND meta_value = %d ) ";
    $query = $wpdb->prepare($query, '_mpp_attached_media_id', $media_id, '_mpp_media_id', $media_id);
    $activity_ids = $wpdb->get_col($query);
    if (empty($activity_ids)) {
        return false;
    }
    //cache the activity meta
    bp_activity_update_meta_cache($activity_ids);
    $to_delete_ids = array();
    foreach ($activity_ids as $activity_id) {
        $ids = mpp_activity_get_attached_media_ids($activity_id);
        if (count($ids) <= 1) {
            $to_delete_ids[] = $activity_id;
        }
    }
    if (empty($to_delete_ids)) {
        return false;
    }
    $list = '(' . join(',', $to_delete_ids) . ')';
    if (!$wpdb->query("DELETE FROM {$bp->activity->table_name} WHERE id IN {$list}")) {
        return false;
    }
    //delete  comments
    $activity_comment_ids = mpp_delete_activity_comments($to_delete_ids);
    //delete all activities
    $deleted_ids = array_merge($to_delete_ids, $activity_comment_ids);
    //get associated WordPress comment ids? No need to worry about that
    BP_Activity_Activity::delete_activity_meta_entries($deleted_ids);
}