[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * BuddyPress Messages Classes.
   4   *
   5   * @package BuddyPress
   6   * @subpackage MessagesClasses
   7   * @since 1.0.0
   8   */
   9  
  10  // Exit if accessed directly.
  11  defined( 'ABSPATH' ) || exit;
  12  
  13  /**
  14   * BuddyPress Message Thread class.
  15   *
  16   * @since 1.0.0
  17   */
  18  class BP_Messages_Thread {
  19  
  20      /**
  21       * The message thread ID.
  22       *
  23       * @since 1.0.0
  24       * @var int
  25       */
  26      public $thread_id;
  27  
  28      /**
  29       * The current messages.
  30       *
  31       * @since 1.0.0
  32       * @var array
  33       */
  34      public $messages;
  35  
  36      /**
  37       * The current recipients in the message thread.
  38       *
  39       * @since 1.0.0
  40       * @var array
  41       */
  42      public $recipients;
  43  
  44      /**
  45       * The user IDs of all messages in the message thread.
  46       *
  47       * @since 1.2.0
  48       * @var array
  49       */
  50      public $sender_ids;
  51  
  52      /**
  53       * The unread count for the logged-in user.
  54       *
  55       * @since 1.2.0
  56       * @var int
  57       */
  58      public $unread_count;
  59  
  60      /**
  61       * The content of the last message in this thread.
  62       *
  63       * @since 1.2.0
  64       * @var string
  65       */
  66      public $last_message_content;
  67  
  68      /**
  69       * The date of the last message in this thread.
  70       *
  71       * @since 1.2.0
  72       * @var string
  73       */
  74      public $last_message_date;
  75  
  76      /**
  77       * The ID of the last message in this thread.
  78       *
  79       * @since 1.2.0
  80       * @var int
  81       */
  82      public $last_message_id;
  83  
  84      /**
  85       * The subject of the last message in this thread.
  86       *
  87       * @since 1.2.0
  88       * @var string
  89       */
  90      public $last_message_subject;
  91  
  92      /**
  93       * The user ID of the author of the last message in this thread.
  94       *
  95       * @since 1.2.0
  96       * @var int
  97       */
  98      public $last_sender_id;
  99  
 100      /**
 101       * Sort order of the messages in this thread (ASC or DESC).
 102       *
 103       * @since 1.5.0
 104       * @var string
 105       */
 106      public $messages_order;
 107  
 108      /**
 109       * Constructor.
 110       *
 111       * @since 1.0.0
 112       * @since 10.0.0 Updated the `$args` with new paremeters.
 113       *
 114       * @param int    $thread_id          The message thread ID.
 115       * @param string $order              The order to sort the messages. Either 'ASC' or 'DESC'.
 116       *                                   Defaults to 'ASC'.
 117       * @param array  $args               {
 118       *     Array of arguments.
 119       *     @type int         $user_id             ID of the user to get the unread count.
 120       *     @type bool        $update_meta_cache   Whether to pre-fetch metadata for
 121       *                                            queried message items. Default: true.
 122       *     @type int|null    $page                Page of messages being requested. Default to null, meaning all.
 123       *     @type int|null    $per_page            Messages to return per page. Default to null, meaning all.
 124       *     @type string      $order               The order to sort the messages. Either 'ASC' or 'DESC'.
 125       *                                            Defaults to 'ASC'.
 126       *     @type int|null    $recipients_page     Page of recipients being requested. Default to null, meaning all.
 127       *     @type int|null    $recipients_per_page Recipients to return per page. Defaults to null, meaning all.
 128       * }
 129       */
 130  	public function __construct( $thread_id = 0, $order = 'ASC', $args = array() ) {
 131          if ( ! empty( $thread_id ) ) {
 132              $this->populate( $thread_id, $order, $args );
 133          }
 134      }
 135  
 136      /**
 137       * Populate method.
 138       *
 139       * Used in the constructor.
 140       *
 141       * @since 1.0.0
 142       * @since 10.0.0 Updated the `$args` with new paremeters.
 143       *
 144       * @param int    $thread_id                   The message thread ID.
 145       * @param string $order                       The order to sort the messages. Either 'ASC' or 'DESC'.
 146       *                                            Defaults to 'ASC'.
 147       * @param array  $args                        {
 148       *     Array of arguments.
 149       *     @type int         $user_id             ID of the user to get the unread count.
 150       *     @type bool        $update_meta_cache   Whether to pre-fetch metadata for
 151       *                                            queried message items. Default: true.
 152       *     @type int|null    $page                Page of messages being requested. Default to null, meaning all.
 153       *     @type int|null    $per_page            Messages to return per page. Default to null, meaning all.
 154       *     @type string      $order               The order to sort the messages. Either 'ASC' or 'DESC'.
 155       *                                            Defaults to 'ASC'.
 156       *     @type int|null    $recipients_page     Page of recipients being requested. Default to null, meaning all.
 157       *     @type int|null    $recipients_per_page Recipients to return per page. Defaults to null, meaning all.
 158       * }
 159       * @return bool False if there are no messages.
 160       */
 161  	public function populate( $thread_id = 0, $order = 'ASC', $args = array() ) {
 162  
 163          if ( ! in_array( strtoupper( $order ), array( 'ASC', 'DESC' ), true ) ) {
 164              $order = 'ASC';
 165          }
 166  
 167          $user_id =
 168              bp_displayed_user_id() ?
 169              bp_displayed_user_id() :
 170              bp_loggedin_user_id();
 171  
 172          // Merge $args with our defaults.
 173          $r = bp_parse_args(
 174              $args,
 175              array(
 176                  'user_id'             => $user_id,
 177                  'update_meta_cache'   => true,
 178                  'page'                => null,
 179                  'per_page'            => null,
 180                  'order'               => $order,
 181                  'recipients_page'     => null,
 182                  'recipients_per_page' => null,
 183              )
 184          );
 185  
 186          $this->messages_order = $order;
 187          $this->thread_id      = (int) $thread_id;
 188  
 189          // Get messages for thread.
 190          $this->messages = self::get_messages( $this->thread_id, $r );
 191  
 192          if ( empty( $this->messages ) ) {
 193              return false;
 194          }
 195  
 196          $last_message_index         = count( $this->messages ) - 1;
 197          $this->last_message_id      = $this->messages[ $last_message_index ]->id;
 198          $this->last_message_date    = $this->messages[ $last_message_index ]->date_sent;
 199          $this->last_sender_id       = $this->messages[ $last_message_index ]->sender_id;
 200          $this->last_message_subject = $this->messages[ $last_message_index ]->subject;
 201          $this->last_message_content = $this->messages[ $last_message_index ]->message;
 202  
 203          foreach ( (array) $this->messages as $key => $message ) {
 204              $this->sender_ids[ $message->sender_id ] = $message->sender_id;
 205          }
 206  
 207          // Fetch the recipients.
 208          $this->recipients = $this->get_recipients( $thread_id, $r );
 209  
 210          // Get the unread count for the user.
 211          if ( isset( $this->recipients[ $r['user_id'] ] ) ) {
 212              $this->unread_count = $this->recipients[ $r['user_id'] ]->unread_count;
 213          }
 214  
 215          // Grab all message meta.
 216          if ( true === (bool) $r['update_meta_cache'] ) {
 217              bp_messages_update_meta_cache( wp_list_pluck( $this->messages, 'id' ) );
 218          }
 219  
 220          /**
 221           * Fires after a BP_Messages_Thread object has been populated.
 222           *
 223           * @since 2.2.0
 224           * @since 10.0.0 Added `$r` as a parameter.
 225           *
 226           * @param BP_Messages_Thread $this Message thread object.
 227           * @param array              $r    Array of paremeters.
 228           */
 229          do_action( 'bp_messages_thread_post_populate', $this, $r );
 230      }
 231  
 232      /**
 233       * Mark a thread initialized in this class as read.
 234       *
 235       * @since 1.0.0
 236       *
 237       * @see BP_Messages_Thread::mark_as_read()
 238       */
 239  	public function mark_read() {
 240          self::mark_as_read( $this->thread_id );
 241      }
 242  
 243      /**
 244       * Mark a thread initialized in this class as unread.
 245       *
 246       * @since 1.0.0
 247       *
 248       * @see BP_Messages_Thread::mark_as_unread()
 249       */
 250  	public function mark_unread() {
 251          self::mark_as_unread( $this->thread_id );
 252      }
 253  
 254      /**
 255       * Returns recipients for a message thread.
 256       *
 257       * @since 1.0.0
 258       * @since 2.3.0  Added `$thread_id` as a parameter.
 259       * @since 10.0.0 Added `$args` as a parameter.
 260       *
 261       * @global BuddyPress $bp The one true BuddyPress instance.
 262       * @global wpdb $wpdb WordPress database object.
 263       *
 264       * @param int   $thread_id Message thread ID.
 265       * @param array $args      {
 266       *     Array of arguments.
 267       *     @type int|null $recipients_page     Page of recipients being requested. Default to all.
 268       *     @type int|null $recipients_per_page Recipients to return per page. Defaults to all.
 269       * }
 270       * @return array
 271       */
 272  	public function get_recipients( $thread_id = 0, $args = array() ) {
 273          global $wpdb;
 274  
 275          if ( empty( $thread_id ) ) {
 276              $thread_id = $this->thread_id;
 277          }
 278  
 279          $thread_id = (int) $thread_id;
 280  
 281          if ( empty( $thread_id ) ) {
 282              return array();
 283          }
 284  
 285          $bp = buddypress();
 286          $r  = bp_parse_args(
 287              $args,
 288              array(
 289                  'recipients_page'     => null,
 290                  'recipients_per_page' => null,
 291              )
 292          );
 293  
 294          // Get recipients from cache if available.
 295          $recipients = wp_cache_get( 'thread_recipients_' . $thread_id, 'bp_messages' );
 296  
 297          // Get recipients and cache it.
 298          if ( empty( $recipients ) ) {
 299  
 300              // Query recipients.
 301              $results = $wpdb->get_results(
 302                  $wpdb->prepare(
 303                      "SELECT * FROM {$bp->messages->table_name_recipients} WHERE thread_id = %d",
 304                      $thread_id
 305                  )
 306              );
 307  
 308              $recipients = array();
 309              foreach ( (array) $results as $recipient ) {
 310                  $recipient_properties              = get_object_vars( $recipient );
 311                  $recipients[ $recipient->user_id ] = (object) array_map( 'intval', $recipient_properties );
 312              }
 313  
 314              // Cache recipients.
 315              wp_cache_set( 'thread_recipients_' . $thread_id, (array) $recipients, 'bp_messages' );
 316          }
 317  
 318          // Paginate the results.
 319          if ( ! empty( $recipients ) && $r['recipients_per_page'] && $r['recipients_page'] ) {
 320              $start      = ( $r['recipients_page'] - 1 ) * ( $r['recipients_per_page'] );
 321              $recipients = array_slice( $recipients, $start, $r['recipients_per_page'] );
 322          }
 323  
 324          /**
 325           * Filters the recipients of a message thread.
 326           *
 327           * @since 2.2.0
 328           * @since 10.0.0 Added `$r` as a parameter.
 329           *
 330           * @param array $recipients Array of recipient objects.
 331           * @param int   $thread_id  ID of the thread.
 332           * @param array $r          An array of parameters.
 333           */
 334          return apply_filters( 'bp_messages_thread_get_recipients', (array) $recipients, (int) $thread_id, (array) $r );
 335      }
 336  
 337      /** Static Functions ******************************************************/
 338  
 339      /**
 340       * Get messages associated with a thread.
 341       *
 342       * @since 2.3.0
 343       * @since 10.0.0 Added `$args` as a parameter.
 344       *
 345       * @global BuddyPress $bp The one true BuddyPress instance.
 346       * @global wpdb $wpdb WordPress database object.
 347       *
 348       * @param int   $thread_id The message thread ID.
 349       * @param array $args      {
 350       *     Array of arguments.
 351       *     @type int|null    $page     Page of messages being requested. Default to all.
 352       *     @type int|null    $per_page Messages to return per page. Default to all.
 353       *     @type string      $order    The order to sort the messages. Either 'ASC' or 'DESC'.
 354       *                                 Defaults to 'ASC'.
 355       * }
 356       * @return array
 357       */
 358  	public static function get_messages( $thread_id = 0, $args = array() ) {
 359          global $wpdb;
 360  
 361          $thread_id = (int) $thread_id;
 362          if ( empty( $thread_id ) ) {
 363              return array();
 364          }
 365  
 366          $bp = buddypress();
 367          $r  = bp_parse_args(
 368              $args,
 369              array(
 370                  'page'     => null,
 371                  'per_page' => null,
 372                  'order'    => 'ASC',
 373              )
 374          );
 375  
 376          // Fallback.
 377          if ( ! in_array( strtoupper( $r['order'] ), array( 'ASC', 'DESC' ), true ) ) {
 378              $r['order'] = 'ASC';
 379          }
 380  
 381          // Get messages from cache if available.
 382          $messages = wp_cache_get( $thread_id, 'bp_messages_threads' );
 383  
 384          // Get messages and cache it.
 385          if ( empty( $messages ) ) {
 386  
 387              // Query messages.
 388              $messages = $wpdb->get_results(
 389                  $wpdb->prepare(
 390                      "SELECT * FROM {$bp->messages->table_name_messages} WHERE thread_id = %d ORDER BY date_sent ASC",
 391                      $thread_id
 392                  )
 393              );
 394  
 395              foreach ( $messages as $key => $data ) {
 396                  $messages[ $key ]->id        = (int) $messages[ $key ]->id;
 397                  $messages[ $key ]->thread_id = (int) $messages[ $key ]->thread_id;
 398                  $messages[ $key ]->sender_id = (int) $messages[ $key ]->sender_id;
 399              }
 400  
 401              // Cache messages.
 402              wp_cache_set( $thread_id, (array) $messages, 'bp_messages_threads' );
 403          }
 404  
 405          // Flip if order is DESC.
 406          if ( 'DESC' === strtoupper( $r['order'] ) ) {
 407              $messages = array_reverse( $messages );
 408          }
 409  
 410          // Paginate the results.
 411          if ( ! empty( $messages ) && $r['per_page'] && $r['page'] ) {
 412              $start    = ( $r['page'] - 1 ) * ( $r['per_page'] );
 413              $messages = array_slice( $messages, $start, $r['per_page'] );
 414          }
 415  
 416          /**
 417           * Filters the messages associated with a thread.
 418           *
 419           * @since 10.0.0
 420           *
 421           * @param array $messages   Array of message objects.
 422           * @param int   $thread_id  ID of the thread.
 423           * @param array $r          An array of parameters.
 424           */
 425          return apply_filters( 'bp_messages_thread_get_messages', (array) $messages, (int) $thread_id, (array) $r );
 426      }
 427  
 428      /**
 429       * Static method to get message recipients by thread ID.
 430       *
 431       * @since 2.3.0
 432       *
 433       * @param int $thread_id The thread ID.
 434       * @return array
 435       */
 436  	public static function get_recipients_for_thread( $thread_id = 0 ) {
 437          $thread = new self( false );
 438          return $thread->get_recipients( $thread_id );
 439      }
 440  
 441      /**
 442       * Mark messages in a thread as deleted or delete all messages in a thread.
 443       *
 444       * Note: All messages in a thread are deleted once every recipient in a thread
 445       * has marked the thread as deleted.
 446       *
 447       * @since 1.0.0
 448       * @since 2.7.0 The $user_id parameter was added. Previously the current user
 449       *              was always assumed.
 450       *
 451       * @global BuddyPress $bp The one true BuddyPress instance.
 452       * @global wpdb $wpdb WordPress database object.
 453       *
 454       * @param int $thread_id The message thread ID.
 455       * @param int $user_id The ID of the user in the thread to mark messages as
 456       *                     deleted for. Defaults to the current logged-in user.
 457       *
 458       * @return bool
 459       */
 460  	public static function delete( $thread_id = 0, $user_id = 0 ) {
 461          global $wpdb;
 462  
 463          $thread_id = (int) $thread_id;
 464          $user_id = (int) $user_id;
 465  
 466          if ( empty( $user_id ) ) {
 467              $user_id = bp_loggedin_user_id();
 468          }
 469  
 470          /**
 471           * Fires before a message thread is marked as deleted.
 472           *
 473           * @since 2.2.0
 474           * @since 2.7.0 The $user_id parameter was added.
 475           *
 476           * @param int $thread_id ID of the thread being deleted.
 477           * @param int $user_id   ID of the user that the thread is being deleted for.
 478           */
 479          do_action( 'bp_messages_thread_before_mark_delete', $thread_id, $user_id );
 480  
 481          $bp = buddypress();
 482  
 483          // Mark messages as deleted
 484          $wpdb->query( $wpdb->prepare( "UPDATE {$bp->messages->table_name_recipients} SET is_deleted = 1 WHERE thread_id = %d AND user_id = %d", $thread_id, $user_id ) );
 485  
 486          // Get the message ids in order to pass to the action.
 487          $message_ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$bp->messages->table_name_messages} WHERE thread_id = %d", $thread_id ) );
 488  
 489          // Check to see if any more recipients remain for this message.
 490          $recipients = $wpdb->get_results( $wpdb->prepare( "SELECT id FROM {$bp->messages->table_name_recipients} WHERE thread_id = %d AND is_deleted = 0", $thread_id ) );
 491  
 492          // No more recipients so delete all messages associated with the thread.
 493          if ( empty( $recipients ) ) {
 494  
 495              /**
 496               * Fires before an entire message thread is deleted.
 497               *
 498               * @since 2.2.0
 499               *
 500               * @param int   $thread_id   ID of the thread being deleted.
 501               * @param array $message_ids IDs of messages being deleted.
 502               */
 503              do_action( 'bp_messages_thread_before_delete', $thread_id, $message_ids );
 504  
 505              // Delete all the messages.
 506              $wpdb->query( $wpdb->prepare( "DELETE FROM {$bp->messages->table_name_messages} WHERE thread_id = %d", $thread_id ) );
 507  
 508              // Do something for each message ID.
 509              foreach ( $message_ids as $message_id ) {
 510  
 511                  // Delete message meta.
 512                  bp_messages_delete_meta( $message_id );
 513  
 514                  /**
 515                   * Fires after a message is deleted. This hook is poorly named.
 516                   *
 517                   * @since 1.0.0
 518                   *
 519                   * @param int $message_id ID of the message.
 520                   */
 521                  do_action( 'messages_thread_deleted_thread', $message_id );
 522              }
 523  
 524              // Delete all the recipients.
 525              $wpdb->query( $wpdb->prepare( "DELETE FROM {$bp->messages->table_name_recipients} WHERE thread_id = %d", $thread_id ) );
 526          }
 527  
 528          /**
 529           * Fires after a message thread is either marked as deleted or deleted.
 530           *
 531           * @since 2.2.0
 532           * @since 2.7.0 The $user_id parameter was added.
 533           *
 534           * @param int   $thread_id   ID of the thread being deleted.
 535           * @param array $message_ids IDs of messages being deleted.
 536           * @param int   $user_id     ID of the user the threads were deleted for.
 537           */
 538          do_action( 'bp_messages_thread_after_delete', $thread_id, $message_ids, $user_id );
 539  
 540          return true;
 541      }
 542  
 543      /**
 544       * Get current message threads for a user.
 545       *
 546       * @since 1.0.0
 547       *
 548       * @global BuddyPress $bp The one true BuddyPress instance.
 549       * @global wpdb $wpdb WordPress database object.
 550       *
 551       * @param array $args {
 552       *     Array of arguments.
 553       *     @type int    $user_id      The user ID.
 554       *     @type string $box          The type of mailbox to get. Either 'inbox' or 'sentbox'.
 555       *                                Defaults to 'inbox'.
 556       *     @type string $type         The type of messages to get. Either 'all' or 'unread'
 557       *                                or 'read'. Defaults to 'all'.
 558       *     @type int    $limit        The number of messages to get. Defaults to null.
 559       *     @type int    $page         The page number to get. Defaults to null.
 560       *     @type string $search_terms The search term to use. Defaults to ''.
 561       *     @type array  $meta_query   Meta query arguments. See WP_Meta_Query for more details.
 562       * }
 563       * @return array|bool Array on success. Boolean false on failure.
 564       */
 565  	public static function get_current_threads_for_user( $args = array() ) {
 566          global $wpdb;
 567  
 568          $function_args = func_get_args();
 569  
 570          // Backward compatibility with old method of passing arguments.
 571          if ( ! is_array( $args ) || count( $function_args ) > 1 ) {
 572              _deprecated_argument(
 573                  __METHOD__,
 574                  '2.2.0',
 575                  sprintf(
 576                      /* translators: 1: the name of the method. 2: the name of the file. */
 577                      esc_html__( 'Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'buddypress' ),
 578                      __METHOD__,
 579                      __FILE__
 580                  )
 581              );
 582  
 583              $old_args_keys = array(
 584                  0 => 'user_id',
 585                  1 => 'box',
 586                  2 => 'type',
 587                  3 => 'limit',
 588                  4 => 'page',
 589                  5 => 'search_terms',
 590              );
 591  
 592              $args = bp_core_parse_args_array( $old_args_keys, $function_args );
 593          }
 594  
 595          $r = bp_parse_args(
 596              $args,
 597              array(
 598                  'user_id'      => false,
 599                  'box'          => 'inbox',
 600                  'type'         => 'all',
 601                  'limit'        => null,
 602                  'page'         => null,
 603                  'search_terms' => '',
 604                  'meta_query'   => array(),
 605              )
 606          );
 607  
 608          $pag_sql = $type_sql = $search_sql = $user_id_sql = $sender_sql = '';
 609          $meta_query_sql = array(
 610              'join'  => '',
 611              'where' => ''
 612          );
 613  
 614          if ( $r['limit'] && $r['page'] ) {
 615              $pag_sql = $wpdb->prepare( " LIMIT %d, %d", intval( ( $r['page'] - 1 ) * $r['limit'] ), intval( $r['limit'] ) );
 616          }
 617  
 618          if ( $r['type'] == 'unread' ) {
 619              $type_sql = " AND r.unread_count != 0 ";
 620          } elseif ( $r['type'] == 'read' ) {
 621              $type_sql = " AND r.unread_count = 0 ";
 622          }
 623  
 624          if ( ! empty( $r['search_terms'] ) ) {
 625              $search_terms_like = '%' . bp_esc_like( $r['search_terms'] ) . '%';
 626              $search_sql        = $wpdb->prepare( "AND ( subject LIKE %s OR message LIKE %s )", $search_terms_like, $search_terms_like );
 627          }
 628  
 629          $r['user_id'] = (int) $r['user_id'];
 630  
 631          // Default deleted SQL.
 632          $deleted_sql = 'r.is_deleted = 0';
 633  
 634          switch ( $r['box'] ) {
 635              case 'sentbox' :
 636                  $user_id_sql = 'AND ' . $wpdb->prepare( 'm.sender_id = %d', $r['user_id'] );
 637                  $sender_sql  = 'AND m.sender_id = r.user_id';
 638                  break;
 639  
 640              case 'inbox' :
 641                  $user_id_sql = 'AND ' . $wpdb->prepare( 'r.user_id = %d', $r['user_id'] );
 642                  $sender_sql  = 'AND r.sender_only = 0';
 643                  break;
 644  
 645              default :
 646                  // Omit user-deleted threads from all other custom message boxes.
 647                  $deleted_sql = $wpdb->prepare( '( r.user_id = %d AND r.is_deleted = 0 )', $r['user_id'] );
 648                  break;
 649          }
 650  
 651          // Process meta query into SQL.
 652          $meta_query = self::get_meta_query_sql( $r['meta_query'] );
 653          if ( ! empty( $meta_query['join'] ) ) {
 654              $meta_query_sql['join'] = $meta_query['join'];
 655          }
 656          if ( ! empty( $meta_query['where'] ) ) {
 657              $meta_query_sql['where'] = $meta_query['where'];
 658          }
 659  
 660          $bp = buddypress();
 661  
 662          // Set up SQL array.
 663          $sql = array();
 664          $sql['select'] = 'SELECT m.thread_id, MAX(m.date_sent) AS date_sent';
 665          $sql['from']   = "FROM {$bp->messages->table_name_recipients} r INNER JOIN {$bp->messages->table_name_messages} m ON m.thread_id = r.thread_id {$meta_query_sql['join']}";
 666          $sql['where']  = "WHERE {$deleted_sql} {$user_id_sql} {$sender_sql} {$type_sql} {$search_sql} {$meta_query_sql['where']}";
 667          $sql['misc']   = "GROUP BY m.thread_id ORDER BY date_sent DESC {$pag_sql}";
 668  
 669          // Get thread IDs.
 670          $thread_ids = $wpdb->get_results( implode( ' ', $sql ) );
 671          if ( empty( $thread_ids ) ) {
 672              return false;
 673          }
 674  
 675          // Adjust $sql to work for thread total.
 676          $sql['select'] = 'SELECT COUNT( DISTINCT m.thread_id )';
 677          unset( $sql['misc'] );
 678          $total_threads = $wpdb->get_var( implode( ' ', $sql ) );
 679  
 680          // Sort threads by date_sent.
 681          foreach( (array) $thread_ids as $thread ) {
 682              $sorted_threads[ $thread->thread_id ] = strtotime( $thread->date_sent );
 683          }
 684  
 685          arsort( $sorted_threads );
 686  
 687          $threads = array();
 688          foreach ( (array) $sorted_threads as $thread_id => $date_sent ) {
 689              $threads[] = new BP_Messages_Thread( $thread_id, 'ASC', array(
 690                  'update_meta_cache' => false
 691              ) );
 692          }
 693  
 694          /**
 695           * Filters the results of the query for a user's message threads.
 696           *
 697           * @since 2.2.0
 698           *
 699           * @param array $value {
 700           *     @type array $threads       Array of threads. Passed by reference.
 701           *     @type int   $total_threads Number of threads found by the query.
 702           * }
 703           */
 704          return apply_filters( 'bp_messages_thread_current_threads', array(
 705              'threads' => &$threads,
 706              'total'   => (int) $total_threads
 707          ) );
 708      }
 709  
 710      /**
 711       * Get the SQL for the 'meta_query' param in BP_Messages_Thread::get_current_threads_for_user().
 712       *
 713       * We use WP_Meta_Query to do the heavy lifting of parsing the meta_query array
 714       * and creating the necessary SQL clauses.
 715       *
 716       * @since 2.2.0
 717       *
 718       * @global wpdb $wpdb WordPress database object.
 719       *
 720       * @param array $meta_query An array of meta_query filters. See the
 721       *                          documentation for WP_Meta_Query for details.
 722       * @return array $sql_array 'join' and 'where' clauses.
 723       */
 724  	public static function get_meta_query_sql( $meta_query = array() ) {
 725          global $wpdb;
 726  
 727          $sql_array = array(
 728              'join'  => '',
 729              'where' => '',
 730          );
 731  
 732          if ( ! empty( $meta_query ) ) {
 733              $meta_query = new WP_Meta_Query( $meta_query );
 734  
 735              // WP_Meta_Query expects the table name at
 736              // $wpdb->messagemeta.
 737              $wpdb->messagemeta = buddypress()->messages->table_name_meta;
 738  
 739              return $meta_query->get_sql( 'message', 'm', 'id' );
 740          }
 741  
 742          return $sql_array;
 743      }
 744  
 745      /**
 746       * Mark a thread as read.
 747       *
 748       * @since 1.0.0
 749       * @since 9.0.0 Added the `user_id` parameter.
 750       *
 751       * @global BuddyPress $bp The one true BuddyPress instance.
 752       * @global wpdb $wpdb WordPress database object.
 753       *
 754       * @param int $thread_id The message thread ID.
 755       * @param int $user_id   The user the thread will be marked as read.
 756       *
 757       * @return bool|int Number of threads marked as read or false on error.
 758       */
 759  	public static function mark_as_read( $thread_id = 0, $user_id = 0 ) {
 760          global $wpdb;
 761  
 762          if ( empty( $user_id ) ) {
 763              $user_id =
 764                  bp_displayed_user_id() ?
 765                  bp_displayed_user_id() :
 766                  bp_loggedin_user_id();
 767          }
 768  
 769          $bp     = buddypress();
 770          $retval = $wpdb->query( $wpdb->prepare( "UPDATE {$bp->messages->table_name_recipients} SET unread_count = 0 WHERE user_id = %d AND thread_id = %d", $user_id, $thread_id ) );
 771  
 772          wp_cache_delete( 'thread_recipients_' . $thread_id, 'bp_messages' );
 773          wp_cache_delete( $user_id, 'bp_messages_unread_count' );
 774  
 775          /**
 776           * Fires when messages thread was marked as read.
 777           *
 778           * @since 2.8.0
 779           * @since 9.0.0 Added the `user_id` parameter.
 780           *
 781           * @param int $thread_id The message thread ID.
 782           * @param int $user_id   The user the thread will be marked as read.
 783           */
 784          do_action( 'messages_thread_mark_as_read', $thread_id, $user_id );
 785  
 786          return $retval;
 787      }
 788  
 789      /**
 790       * Mark a thread as unread.
 791       *
 792       * @since 1.0.0
 793       * @since 9.0.0 Added the `user_id` parameter.
 794       *
 795       * @global BuddyPress $bp The one true BuddyPress instance.
 796       * @global wpdb $wpdb WordPress database object.
 797       *
 798       * @param int $thread_id The message thread ID.
 799       * @param int $user_id   The user the thread will be marked as unread.
 800       *
 801       * @return bool|int Number of threads marked as unread or false on error.
 802       */
 803  	public static function mark_as_unread( $thread_id = 0, $user_id = 0 ) {
 804          global $wpdb;
 805  
 806          if ( empty( $user_id ) ) {
 807              $user_id =
 808                  bp_displayed_user_id() ?
 809                  bp_displayed_user_id() :
 810                  bp_loggedin_user_id();
 811          }
 812  
 813          $bp     = buddypress();
 814          $retval = $wpdb->query( $wpdb->prepare( "UPDATE {$bp->messages->table_name_recipients} SET unread_count = 1 WHERE user_id = %d AND thread_id = %d", $user_id, $thread_id ) );
 815  
 816          wp_cache_delete( 'thread_recipients_' . $thread_id, 'bp_messages' );
 817          wp_cache_delete( $user_id, 'bp_messages_unread_count' );
 818  
 819          /**
 820           * Fires when messages thread was marked as unread.
 821           *
 822           * @since 2.8.0
 823           * @since 9.0.0  Added the `$user_id` parameter.
 824           * @since 10.0.0 Added the `$retval` parameter.
 825           *
 826           * @param int      $thread_id The message thread ID.
 827           * @param int      $user_id   The user the thread will be marked as unread.
 828           * @param bool|int $retval     =Number of threads marked as unread or false on error.
 829           */
 830          do_action( 'messages_thread_mark_as_unread', $thread_id, $user_id, $retval );
 831  
 832          return $retval;
 833      }
 834  
 835      /**
 836       * Returns the total number of message threads for a user.
 837       *
 838       * @since 1.0.0
 839       *
 840       * @param int    $user_id The user ID.
 841       * @param string $box     The type of mailbox to get. Either 'inbox' or 'sentbox'.
 842       *                        Defaults to 'inbox'.
 843       * @param string $type    The type of messages to get. Either 'all' or 'unread'.
 844       *                        or 'read'. Defaults to 'all'.
 845       * @return int Total thread count for the provided user.
 846       */
 847  	public static function get_total_threads_for_user( $user_id, $box = 'inbox', $type = 'all' ) {
 848          global $wpdb;
 849  
 850          $exclude_sender = $type_sql = '';
 851          if ( $box !== 'sentbox' ) {
 852              $exclude_sender = 'AND sender_only != 1';
 853          }
 854  
 855          if ( $type === 'unread' ) {
 856              $type_sql = 'AND unread_count != 0';
 857          } elseif ( $type === 'read' ) {
 858              $type_sql = 'AND unread_count = 0';
 859          }
 860  
 861          $bp = buddypress();
 862  
 863          return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(thread_id) FROM {$bp->messages->table_name_recipients} WHERE user_id = %d AND is_deleted = 0 {$exclude_sender} {$type_sql}", $user_id ) );
 864      }
 865  
 866      /**
 867       * Determine if the logged-in user is a sender of any message in a thread.
 868       *
 869       * @since 1.0.0
 870       *
 871       * @global BuddyPress $bp The one true BuddyPress instance.
 872       * @global wpdb $wpdb WordPress database object.
 873       *
 874       * @param int $thread_id The message thread ID.
 875       * @return bool
 876       */
 877  	public static function user_is_sender( $thread_id ) {
 878          global $wpdb;
 879  
 880          $bp = buddypress();
 881  
 882          $sender_ids = $wpdb->get_col( $wpdb->prepare( "SELECT sender_id FROM {$bp->messages->table_name_messages} WHERE thread_id = %d", $thread_id ) );
 883  
 884          if ( empty( $sender_ids ) ) {
 885              return false;
 886          }
 887  
 888          return in_array( bp_loggedin_user_id(), $sender_ids, true );
 889      }
 890  
 891      /**
 892       * Returns the userlink of the last sender in a message thread.
 893       *
 894       * @since 1.0.0
 895       *
 896       * @global BuddyPress $bp The one true BuddyPress instance.
 897       * @global wpdb $wpdb WordPress database object.
 898       *
 899       * @param int $thread_id The message thread ID.
 900       * @return string|bool The user link on success. Boolean false on failure.
 901       */
 902  	public static function get_last_sender( $thread_id ) {
 903          global $wpdb;
 904  
 905          $bp = buddypress();
 906  
 907          if ( ! $sender_id = $wpdb->get_var( $wpdb->prepare( "SELECT sender_id FROM {$bp->messages->table_name_messages} WHERE thread_id = %d GROUP BY sender_id ORDER BY date_sent LIMIT 1", $thread_id ) ) ) {
 908              return false;
 909          }
 910  
 911          return bp_core_get_userlink( $sender_id, true );
 912      }
 913  
 914      /**
 915       * Gets the unread message count for a user.
 916       *
 917       * @since 1.0.0
 918       *
 919       * @global BuddyPress $bp The one true BuddyPress instance.
 920       * @global wpdb $wpdb WordPress database object.
 921       *
 922       * @param int $user_id The user ID.
 923       * @return int Total inbox unread count for user.
 924       */
 925  	public static function get_inbox_count( $user_id = 0 ) {
 926          global $wpdb;
 927  
 928          if ( empty( $user_id ) ) {
 929              $user_id = bp_loggedin_user_id();
 930          }
 931  
 932          $unread_count = wp_cache_get( $user_id, 'bp_messages_unread_count' );
 933  
 934          if ( false === $unread_count ) {
 935              $bp = buddypress();
 936  
 937              $unread_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT SUM(unread_count) FROM {$bp->messages->table_name_recipients} WHERE user_id = %d AND is_deleted = 0 AND sender_only = 0", $user_id ) );
 938  
 939              wp_cache_set( $user_id, $unread_count, 'bp_messages_unread_count' );
 940          }
 941  
 942          /**
 943           * Filters a user's unread message count.
 944           *
 945           * @since 2.2.0
 946           *
 947           * @param int $unread_count Unread message count.
 948           * @param int $user_id      ID of the user.
 949           */
 950          return apply_filters( 'messages_thread_get_inbox_count', (int) $unread_count, $user_id );
 951      }
 952  
 953      /**
 954       * Checks whether a user is a part of a message thread discussion.
 955       *
 956       * @since 1.0.0
 957       *
 958       * @param int $thread_id The message thread ID.
 959       * @param int $user_id   The user ID. Default: ID of the logged-in user.
 960       * @return int|null The recorded recipient ID on success, null on failure.
 961       */
 962  	public static function check_access( $thread_id, $user_id = 0 ) {
 963  
 964          if ( empty( $user_id ) ) {
 965              $user_id = bp_loggedin_user_id();
 966          }
 967  
 968          $recipients = self::get_recipients_for_thread( $thread_id );
 969  
 970          if ( isset( $recipients[ $user_id ] ) && 0 === $recipients[ $user_id ]->is_deleted ) {
 971              return $recipients[ $user_id ]->id;
 972          }
 973  
 974          return null;
 975      }
 976  
 977      /**
 978       * Checks whether a message thread exists.
 979       *
 980       * @since 1.0.0
 981       *
 982       * @param int $thread_id The message thread ID.
 983       * @return bool|int|null The message thread ID on success, null on failure.
 984       */
 985  	public static function is_valid( $thread_id = 0 ) {
 986  
 987          // Bail if no thread ID is passed.
 988          if ( empty( $thread_id ) ) {
 989              return false;
 990          }
 991  
 992          $thread = self::get_messages( $thread_id );
 993  
 994          if ( ! empty( $thread ) ) {
 995              return $thread_id;
 996          } else {
 997              return null;
 998          }
 999      }
1000  
1001      /**
1002       * Returns a string containing all the message recipient userlinks.
1003       *
1004       * String is comma-delimited.
1005       *
1006       * If a message thread has more than four users, the returned string is simply
1007       * "X Recipients" where "X" is the number of recipients in the message thread.
1008       *
1009       * @since 1.0.0
1010       *
1011       * @param array $recipients Array containing the message recipients (array of objects).
1012       * @return string String of message recipent userlinks.
1013       */
1014  	public static function get_recipient_links( $recipients ) {
1015  
1016          if ( count( $recipients ) >= 5 ) {
1017              /* translators: %s: number of message recipients */
1018              return sprintf( __( '%s Recipients', 'buddypress' ), number_format_i18n( count( $recipients ) ) );
1019          }
1020  
1021          $recipient_links = array();
1022  
1023          foreach ( (array) $recipients as $recipient ) {
1024              $recipient_link = bp_core_get_userlink( $recipient->user_id );
1025  
1026              if ( empty( $recipient_link ) ) {
1027                  $recipient_link = __( 'Deleted User', 'buddypress' );
1028              }
1029  
1030              $recipient_links[] = $recipient_link;
1031          }
1032  
1033          return implode( ', ', (array) $recipient_links );
1034      }
1035  
1036      /**
1037       * Upgrade method for the older BP message thread DB table.
1038       *
1039       * @todo We should remove this. No one is going to upgrade from v1.1, right?
1040       *
1041       * @since 1.2.0
1042       *
1043       * @global BuddyPress $bp The one true BuddyPress instance.
1044       * @global wpdb $wpdb WordPress database object.
1045       *
1046       * @return bool
1047       */
1048  	public static function update_tables() {
1049          global $wpdb;
1050  
1051          $bp_prefix = bp_core_get_table_prefix();
1052          $errors    = false;
1053          $threads   = $wpdb->get_results( "SELECT * FROM {$bp_prefix}bp_messages_threads" );
1054  
1055          // Nothing to update, just return true to remove the table.
1056          if ( empty( $threads ) ) {
1057              return true;
1058          }
1059  
1060          $bp = buddypress();
1061  
1062          foreach( (array) $threads as $thread ) {
1063              $message_ids = maybe_unserialize( $thread->message_ids );
1064  
1065              if ( ! empty( $message_ids ) ) {
1066                  $message_ids = implode( ',', $message_ids );
1067  
1068                  // Add the thread_id to the messages table.
1069                  if ( ! $wpdb->query( $wpdb->prepare( "UPDATE {$bp->messages->table_name_messages} SET thread_id = %d WHERE id IN ({$message_ids})", $thread->id ) ) ) {
1070                      $errors = true;
1071                  }
1072              }
1073          }
1074  
1075          return (bool) ! $errors;
1076      }
1077  }


Generated: Sun Sep 19 01:01:40 2021 Cross-referenced by PHPXref 0.7.1