[ Index ]

PHP Cross Reference of BBPress

title

Body

[close]

/src/includes/common/ -> functions.php (source)

   1  <?php
   2  
   3  /**
   4   * bbPress Common Functions
   5   *
   6   * Common functions are ones that are used by more than one component, like
   7   * forums, topics, replies, users, topic tags, etc...
   8   *
   9   * @package bbPress
  10   * @subpackage Functions
  11   */
  12  
  13  // Exit if accessed directly
  14  defined( 'ABSPATH' ) || exit;
  15  
  16  /**
  17   * Return array of bbPress registered post types
  18   *
  19   * @since 2.6.0 bbPress (r6813)
  20   *
  21   * @param array $args Array of arguments to pass into `get_post_types()`
  22   *
  23   * @return array
  24   */
  25  function bbp_get_post_types( $args = array() ) {
  26  
  27      // Parse args
  28      $r = bbp_parse_args( $args, array(
  29          'source' => 'bbpress'
  30      ), 'get_post_types' );
  31  
  32      // Return post types
  33      return get_post_types( $r );
  34  }
  35  
  36  /** URLs **********************************************************************/
  37  
  38  /**
  39   * Return the unescaped redirect_to request value
  40   *
  41   * @bbPress (r4655)
  42   *
  43   * @return string The URL to redirect to, if set
  44   */
  45  function bbp_get_redirect_to() {
  46  
  47      // Check 'redirect_to' request parameter
  48      $retval = ! empty( $_REQUEST['redirect_to'] )
  49          ? $_REQUEST['redirect_to']
  50          : '';
  51  
  52      // Filter & return
  53      return apply_filters( 'bbp_get_redirect_to', $retval );
  54  }
  55  
  56  /**
  57   * Append 'view=all' to query string if it's already there from referer
  58   *
  59   * @since 2.0.0 bbPress (r3325)
  60   *
  61   * @param string $original_link Original Link to be modified
  62   * @param bool $force Override bbp_get_view_all() check
  63   * @return string The link with 'view=all' appended if necessary
  64   */
  65  function bbp_add_view_all( $original_link = '', $force = false ) {
  66  
  67      // Are we appending the view=all vars?
  68      $link = ( bbp_get_view_all() || ! empty( $force ) )
  69          ? add_query_arg( array( 'view' => 'all' ), $original_link )
  70          : $original_link;
  71  
  72      // Filter & return
  73      return apply_filters( 'bbp_add_view_all', $link, $original_link );
  74  }
  75  
  76  /**
  77   * Remove 'view=all' from query string
  78   *
  79   * @since 2.0.0 bbPress (r3325)
  80   *
  81   * @param string $original_link Original Link to be modified
  82   * @return string The link with 'view=all' appended if necessary
  83   */
  84  function bbp_remove_view_all( $original_link = '' ) {
  85  
  86      // Remove `view' argument
  87      $link = remove_query_arg( 'view', $original_link );
  88  
  89      // Filter & return
  90      return apply_filters( 'bbp_remove_view_all', $link, $original_link );
  91  }
  92  
  93  /**
  94   * If current user can and is viewing all topics/replies
  95   *
  96   * @since 2.0.0 bbPress (r3325)
  97   *
  98   * @param string $cap Capability used to ensure user can view all
  99   *
 100   * @return bool Whether current user can and is viewing all
 101   */
 102  function bbp_get_view_all( $cap = 'moderate' ) {
 103      $retval = ( ( ! empty( $_GET['view'] ) && ( 'all' === $_GET['view'] ) && current_user_can( $cap ) ) );
 104  
 105      // Filter & return
 106      return (bool) apply_filters( 'bbp_get_view_all', (bool) $retval, $cap );
 107  }
 108  
 109  /**
 110   * Assist pagination by returning correct page number
 111   *
 112   * @since 2.0.0 bbPress (r2628)
 113   *
 114   * @return int Current page number
 115   */
 116  function bbp_get_paged() {
 117      $wp_query = bbp_get_wp_query();
 118  
 119      // Check the query var
 120      if ( get_query_var( 'paged' ) ) {
 121          $paged = get_query_var( 'paged' );
 122  
 123      // Check query paged
 124      } elseif ( ! empty( $wp_query->query['paged'] ) ) {
 125          $paged = $wp_query->query['paged'];
 126      }
 127  
 128      // Paged found
 129      if ( ! empty( $paged ) ) {
 130          return (int) $paged;
 131      }
 132  
 133      // Default to first page
 134      return 1;
 135  }
 136  
 137  /** Misc **********************************************************************/
 138  
 139  /**
 140   * Return the unique non-empty values of an array.
 141   *
 142   * @since 2.6.0 bbPress (r6481)
 143   *
 144   * @param array $array Array to get values of
 145   *
 146   * @return array
 147   */
 148  function bbp_get_unique_array_values( $array = array() ) {
 149      return array_unique( array_filter( array_values( $array ) ) );
 150  }
 151  
 152  /**
 153   * Fix post author id on post save
 154   *
 155   * When a logged in user changes the status of an anonymous reply or topic, or
 156   * edits it, the post_author field is set to the logged in user's id. This
 157   * function fixes that.
 158   *
 159   * @since 2.0.0 bbPress (r2734)
 160   *
 161   * @param array $data Post data
 162   * @param array $postarr Original post array (includes post id)
 163   * @return array Data
 164   */
 165  function bbp_fix_post_author( $data = array(), $postarr = array() ) {
 166  
 167      // Post is not being updated or the post_author is already 0, return
 168      if ( empty( $postarr['ID'] ) || empty( $data['post_author'] ) ) {
 169          return $data;
 170      }
 171  
 172      // Post is not a topic or reply, return
 173      if ( ! in_array( $data['post_type'], array( bbp_get_topic_post_type(), bbp_get_reply_post_type() ), true ) ) {
 174          return $data;
 175      }
 176  
 177      // Is the post by an anonymous user?
 178      if ( ( bbp_get_topic_post_type() === $data['post_type'] && ! bbp_is_topic_anonymous( $postarr['ID'] ) ) ||
 179           ( bbp_get_reply_post_type() === $data['post_type'] && ! bbp_is_reply_anonymous( $postarr['ID'] ) ) ) {
 180          return $data;
 181      }
 182  
 183      // The post is being updated. It is a topic or a reply and is written by an anonymous user.
 184      // Set the post_author back to 0
 185      $data['post_author'] = 0;
 186  
 187      return $data;
 188  }
 189  
 190  /**
 191   * Check a date against the length of time something can be edited.
 192   *
 193   * It is recommended to leave $utc set to true and to work with UTC/GMT dates.
 194   * Turning this off will use the WordPress offset which is likely undesirable.
 195   *
 196   * @since 2.0.0 bbPress (r3133)
 197   * @since 2.6.0 bbPress (r6868) Inverted some logic and added unit tests
 198   *
 199   * @param string  $datetime Gets run through strtotime()
 200   * @param boolean $utc      Default true. Is the timestamp in UTC?
 201   *
 202   * @return bool True by default, if date is past, or editing is disabled.
 203   */
 204  function bbp_past_edit_lock( $datetime = '', $utc = true ) {
 205  
 206      // Default value
 207      $retval = true;
 208  
 209      // Check if date and editing is allowed
 210      if ( bbp_allow_content_edit() ) {
 211  
 212          // Get number of minutes to allow editing for
 213          $minutes = bbp_get_edit_lock();
 214  
 215          // 0 minutes means forever, so can never be past edit-lock time
 216          if ( 0 === $minutes ) {
 217              $retval = false;
 218  
 219          // Checking against a specific datetime
 220          } elseif ( ! empty( $datetime ) ) {
 221  
 222              // Period of time
 223              $lockable = "+{$minutes} minutes";
 224              if ( true === $utc ) {
 225                  $lockable .= " UTC";
 226              }
 227  
 228              // Now
 229              $cur_time  = current_time( 'timestamp', $utc );
 230  
 231              // Get the duration in seconds
 232              $duration  = strtotime( $lockable ) - $cur_time;
 233  
 234              // Diff the times down to seconds
 235              $lock_time = strtotime( $lockable, $cur_time );
 236              $past_time = strtotime( $datetime, $cur_time );
 237              $diff_time = ( $lock_time - $past_time ) - $duration;
 238  
 239              // 0 minutes set, so allow editing forever
 240              if ( 0 === $minutes ) {
 241                  $retval = false;
 242  
 243              // Check if less than lock time
 244              } elseif ( $diff_time < $duration ) {
 245                  $retval = false;
 246              }
 247          }
 248      }
 249  
 250      // Filter & return
 251      return (bool) apply_filters( 'bbp_past_edit_lock', $retval, $datetime, $utc );
 252  }
 253  
 254  /**
 255   * Get number of days something should remain trashed for before it is cleaned
 256   * up by WordPress Cron. If set to 0, items will skip trash and be deleted
 257   * immediately.
 258   *
 259   * @since 2.6.0 bbPress (r6424)
 260   *
 261   * @param string $context Provide context for additional filtering
 262   * @return int Number of days items remain in trash
 263   */
 264  function bbp_get_trash_days( $context = 'forum' ) {
 265  
 266      // Sanitize the context
 267      $context = sanitize_key( $context );
 268  
 269      // Check the WordPress constant
 270      $days    = defined( 'EMPTY_TRASH_DAYS' )
 271          ? (int) EMPTY_TRASH_DAYS
 272          : 30;
 273  
 274      // Filter & return
 275      return (int) apply_filters( 'bbp_get_trash_days', $days, $context );
 276  }
 277  
 278  /** Statistics ****************************************************************/
 279  
 280  /**
 281   * Get the forum statistics
 282   *
 283   * @since 2.0.0 bbPress (r2769)
 284   * @since 2.6.0 bbPress (r6055) Introduced the `count_pending_topics` and
 285   *                               `count_pending_replies` arguments.
 286   *
 287   * @param array $args Optional. The function supports these arguments (all
 288   *                     default to true):
 289   *  - count_users: Count users?
 290   *  - count_forums: Count forums?
 291   *  - count_topics: Count topics? If set to false, private, spammed and trashed
 292   *                   topics are also not counted.
 293   *  - count_pending_topics: Count pending topics? (only counted if the current
 294   *                           user has edit_others_topics cap)
 295   *  - count_private_topics: Count private topics? (only counted if the current
 296   *                           user has read_private_topics cap)
 297   *  - count_spammed_topics: Count spammed topics? (only counted if the current
 298   *                           user has edit_others_topics cap)
 299   *  - count_trashed_topics: Count trashed topics? (only counted if the current
 300   *                           user has view_trash cap)
 301   *  - count_replies: Count replies? If set to false, private, spammed and
 302   *                   trashed replies are also not counted.
 303   *  - count_pending_replies: Count pending replies? (only counted if the current
 304   *                           user has edit_others_replies cap)
 305   *  - count_private_replies: Count private replies? (only counted if the current
 306   *                           user has read_private_replies cap)
 307   *  - count_spammed_replies: Count spammed replies? (only counted if the current
 308   *                           user has edit_others_replies cap)
 309   *  - count_trashed_replies: Count trashed replies? (only counted if the current
 310   *                           user has view_trash cap)
 311   *  - count_tags: Count tags? If set to false, empty tags are also not counted
 312   *  - count_empty_tags: Count empty tags?
 313   * @return object Walked forum tree
 314   */
 315  function bbp_get_statistics( $args = array() ) {
 316  
 317      // Parse arguments against default values
 318      $r = bbp_parse_args( $args, array(
 319  
 320          // Users
 321          'count_users'           => true,
 322  
 323          // Forums
 324          'count_forums'          => true,
 325  
 326          // Topics
 327          'count_topics'          => true,
 328          'count_pending_topics'  => true,
 329          'count_private_topics'  => true,
 330          'count_spammed_topics'  => true,
 331          'count_trashed_topics'  => true,
 332  
 333          // Replies
 334          'count_replies'         => true,
 335          'count_pending_replies' => true,
 336          'count_private_replies' => true,
 337          'count_spammed_replies' => true,
 338          'count_trashed_replies' => true,
 339  
 340          // Topic tags
 341          'count_tags'            => true,
 342          'count_empty_tags'      => true
 343  
 344      ), 'get_statistics' );
 345  
 346      // Defaults
 347      $topic_count     = $topic_count_hidden    = 0;
 348      $reply_count     = $reply_count_hidden    = 0;
 349      $topic_tag_count = $empty_topic_tag_count = 0;
 350      $hidden_topic_title = $hidden_reply_title = '';
 351  
 352      // Users
 353      $user_count = ! empty( $r['count_users'] )
 354          ? bbp_get_total_users()
 355          : 0;
 356  
 357      // Forums
 358      $forum_count = ! empty( $r['count_forums'] )
 359          ? wp_count_posts( bbp_get_forum_post_type() )->publish
 360          : 0;
 361  
 362      // Post statuses
 363      $pending = bbp_get_pending_status_id();
 364      $private = bbp_get_private_status_id();
 365      $spam    = bbp_get_spam_status_id();
 366      $trash   = bbp_get_trash_status_id();
 367      $closed  = bbp_get_closed_status_id();
 368  
 369      // Topics
 370      if ( ! empty( $r['count_topics'] ) ) {
 371          $all_topics  = wp_count_posts( bbp_get_topic_post_type() );
 372  
 373          // Published (publish + closed)
 374          $topic_count = $all_topics->publish + $all_topics->{$closed};
 375  
 376          if ( current_user_can( 'read_private_topics' ) || current_user_can( 'edit_others_topics' ) || current_user_can( 'view_trash' ) ) {
 377  
 378              // Declare empty arrays
 379              $topics = $topic_titles = array();
 380  
 381              // Pending
 382              $topics['pending'] = ( ! empty( $r['count_pending_topics'] ) && current_user_can( 'edit_others_topics' ) )
 383                  ? (int) $all_topics->{$pending}
 384                  : 0;
 385  
 386              // Private
 387              $topics['private'] = ( ! empty( $r['count_private_topics'] ) && current_user_can( 'read_private_topics' ) )
 388                  ? (int) $all_topics->{$private}
 389                  : 0;
 390  
 391              // Spam
 392              $topics['spammed'] = ( ! empty( $r['count_spammed_topics'] ) && current_user_can( 'edit_others_topics'  ) )
 393                  ? (int) $all_topics->{$spam}
 394                  : 0;
 395  
 396              // Trash
 397              $topics['trashed'] = ( ! empty( $r['count_trashed_topics'] ) && current_user_can( 'view_trash' ) )
 398                  ? (int) $all_topics->{$trash}
 399                  : 0;
 400  
 401              // Total hidden (pending + private + spam + trash)
 402              $topic_count_hidden = $topics['pending'] + $topics['private'] + $topics['spammed'] + $topics['trashed'];
 403  
 404              // Generate the hidden topic count's title attribute
 405              $topic_titles[] = ! empty( $topics['pending'] )
 406                  ? sprintf( esc_html__( 'Pending: %s', 'bbpress' ), bbp_number_format_i18n( $topics['pending'] ) )
 407                  : '';
 408  
 409              $topic_titles[] = ! empty( $topics['private'] )
 410                  ? sprintf( esc_html__( 'Private: %s', 'bbpress' ), bbp_number_format_i18n( $topics['private'] ) )
 411                  : '';
 412  
 413              $topic_titles[] = ! empty( $topics['spammed'] )
 414                  ? sprintf( esc_html__( 'Spammed: %s', 'bbpress' ), bbp_number_format_i18n( $topics['spammed'] ) )
 415                  : '';
 416  
 417              $topic_titles[] = ! empty( $topics['trashed'] )
 418                  ? sprintf( esc_html__( 'Trashed: %s', 'bbpress' ), bbp_number_format_i18n( $topics['trashed'] ) )
 419                  : '';
 420  
 421              // Compile the hidden topic title
 422              $hidden_topic_title = implode( ' | ', array_filter( $topic_titles ) );
 423          }
 424      }
 425  
 426      // Replies
 427      if ( ! empty( $r['count_replies'] ) ) {
 428  
 429          $all_replies = wp_count_posts( bbp_get_reply_post_type() );
 430  
 431          // Published
 432          $reply_count = $all_replies->publish;
 433  
 434          if ( current_user_can( 'read_private_replies' ) || current_user_can( 'edit_others_replies' ) || current_user_can( 'view_trash' ) ) {
 435  
 436              // Declare empty arrays
 437              $replies = $reply_titles = array();
 438  
 439              // Pending
 440              $replies['pending'] = ( ! empty( $r['count_pending_replies'] ) && current_user_can( 'edit_others_replies' ) )
 441                  ? (int) $all_replies->{$pending}
 442                  : 0;
 443  
 444              // Private
 445              $replies['private'] = ( ! empty( $r['count_private_replies'] ) && current_user_can( 'read_private_replies' ) )
 446                  ? (int) $all_replies->{$private}
 447                  : 0;
 448  
 449              // Spam
 450              $replies['spammed'] = ( ! empty( $r['count_spammed_replies'] ) && current_user_can( 'edit_others_replies'  ) )
 451                  ? (int) $all_replies->{$spam}
 452                  : 0;
 453  
 454              // Trash
 455              $replies['trashed'] = ( ! empty( $r['count_trashed_replies'] ) && current_user_can( 'view_trash' ) )
 456                  ? (int) $all_replies->{$trash}
 457                  : 0;
 458  
 459              // Total hidden (pending + private + spam + trash)
 460              $reply_count_hidden = $replies['pending'] + $replies['private'] + $replies['spammed'] + $replies['trashed'];
 461  
 462              // Generate the hidden topic count's title attribute
 463              $reply_titles[] = ! empty( $replies['pending'] )
 464                  ? sprintf( esc_html__( 'Pending: %s', 'bbpress' ), bbp_number_format_i18n( $replies['pending'] ) )
 465                  : '';
 466              $reply_titles[] = ! empty( $replies['private'] )
 467                  ? sprintf( esc_html__( 'Private: %s', 'bbpress' ), bbp_number_format_i18n( $replies['private'] ) )
 468                  : '';
 469  
 470              $reply_titles[] = ! empty( $replies['spammed'] )
 471                  ? sprintf( esc_html__( 'Spammed: %s', 'bbpress' ), bbp_number_format_i18n( $replies['spammed'] ) )
 472                  : '';
 473  
 474              $reply_titles[] = ! empty( $replies['trashed'] )
 475                  ? sprintf( esc_html__( 'Trashed: %s', 'bbpress' ), bbp_number_format_i18n( $replies['trashed'] ) )
 476                  : '';
 477  
 478              // Compile the hidden replies title
 479              $hidden_reply_title = implode( ' | ', array_filter( $reply_titles ) );
 480          }
 481      }
 482  
 483      // Topic Tags
 484      if ( ! empty( $r['count_tags'] ) && bbp_allow_topic_tags() ) {
 485  
 486          // Get the count
 487          $topic_tag_count = wp_count_terms( bbp_get_topic_tag_tax_id(), array( 'hide_empty' => true ) );
 488  
 489          // Empty tags
 490          if ( ! empty( $r['count_empty_tags'] ) && current_user_can( 'edit_topic_tags' ) ) {
 491              $empty_topic_tag_count = wp_count_terms( bbp_get_topic_tag_tax_id() ) - $topic_tag_count;
 492          }
 493      }
 494  
 495      // Tally the tallies
 496      $counts = array_filter( array_map( 'absint', compact(
 497          'user_count',
 498          'forum_count',
 499          'topic_count',
 500          'topic_count_hidden',
 501          'reply_count',
 502          'reply_count_hidden',
 503          'topic_tag_count',
 504          'empty_topic_tag_count'
 505      ) ) );
 506  
 507      // Define return value
 508      $statistics = array();
 509  
 510      // Loop through and store the integer and i18n formatted counts.
 511      foreach ( $counts as $key => $count ) {
 512          $statistics[ $key ]         = bbp_number_format_i18n( $count );
 513          $statistics[ "{$key}_int" ] = $count;
 514      }
 515  
 516      // Add the hidden (topic/reply) count title attribute strings because we
 517      // don't need to run the math functions on these (see above)
 518      $statistics['hidden_topic_title'] = $hidden_topic_title;
 519      $statistics['hidden_reply_title'] = $hidden_reply_title;
 520  
 521      // Filter & return
 522      return (array) apply_filters( 'bbp_get_statistics', $statistics, $r, $args );
 523  }
 524  
 525  /** New/edit topic/reply helpers **********************************************/
 526  
 527  /**
 528   * Filter anonymous post data
 529   *
 530   * We use REMOTE_ADDR here directly. If you are behind a proxy, you should
 531   * ensure that it is properly set, such as in wp-config.php, for your
 532   * environment. See {@link https://core.trac.wordpress.org/ticket/9235}
 533   *
 534   * Note that bbp_pre_anonymous_filters() is responsible for sanitizing each
 535   * of the filtered core anonymous values here.
 536   *
 537   * If there are any errors, those are directly added to {@link bbPress:errors}
 538   *
 539   * @since 2.0.0 bbPress (r2734)
 540   *
 541   * @param array $args Optional. If no args are there, then $_POST values are
 542   * @return bool|array False on errors, values in an array on success
 543   */
 544  function bbp_filter_anonymous_post_data( $args = array() ) {
 545  
 546      // Parse arguments against default values
 547      $r = bbp_parse_args( $args, array(
 548          'bbp_anonymous_name'    => ! empty( $_POST['bbp_anonymous_name']    ) ? $_POST['bbp_anonymous_name']    : false,
 549          'bbp_anonymous_email'   => ! empty( $_POST['bbp_anonymous_email']   ) ? $_POST['bbp_anonymous_email']   : false,
 550          'bbp_anonymous_website' => ! empty( $_POST['bbp_anonymous_website'] ) ? $_POST['bbp_anonymous_website'] : false,
 551      ), 'filter_anonymous_post_data' );
 552  
 553      // Strip invalid characters
 554      $r = bbp_sanitize_anonymous_post_author( $r );
 555  
 556      // Filter name
 557      $r['bbp_anonymous_name'] = apply_filters( 'bbp_pre_anonymous_post_author_name', $r['bbp_anonymous_name'] );
 558      if ( empty( $r['bbp_anonymous_name'] ) ) {
 559          bbp_add_error( 'bbp_anonymous_name',  __( '<strong>ERROR</strong>: Invalid author name.', 'bbpress' ) );
 560      }
 561  
 562      // Filter email address
 563      $r['bbp_anonymous_email'] = apply_filters( 'bbp_pre_anonymous_post_author_email', $r['bbp_anonymous_email'] );
 564      if ( empty( $r['bbp_anonymous_email'] ) ) {
 565          bbp_add_error( 'bbp_anonymous_email', __( '<strong>ERROR</strong>: Invalid email address.', 'bbpress' ) );
 566      }
 567  
 568      // Website is optional (can be empty)
 569      $r['bbp_anonymous_website'] = apply_filters( 'bbp_pre_anonymous_post_author_website', $r['bbp_anonymous_website'] );
 570  
 571      // Filter & return
 572      return (array) apply_filters( 'bbp_filter_anonymous_post_data', $r, $args );
 573  }
 574  
 575  /**
 576   * Sanitize an array of anonymous post author data
 577   *
 578   * @since 2.6.0 bbPress (r6400)
 579   *
 580   * @param array $anonymous_data
 581   * @return array
 582   */
 583  function bbp_sanitize_anonymous_post_author( $anonymous_data = array() ) {
 584  
 585      // Make sure anonymous data is an array
 586      if ( ! is_array( $anonymous_data ) ) {
 587          $anonymous_data = array();
 588      }
 589  
 590      // Map meta data to comment fields (as guides for stripping invalid text)
 591      $fields = array(
 592          'bbp_anonymous_name'    => 'comment_author',
 593          'bbp_anonymous_email'   => 'comment_author_email',
 594          'bbp_anonymous_website' => 'comment_author_url'
 595      );
 596  
 597      // Setup a new return array
 598      $r = $anonymous_data;
 599  
 600      // Get the database
 601      $bbp_db = bbp_db();
 602  
 603      // Strip invalid text from fields
 604      foreach ( $fields as $bbp_field => $comment_field ) {
 605          if ( ! empty( $r[ $bbp_field ] ) ) {
 606              $r[ $bbp_field ] = $bbp_db->strip_invalid_text_for_column( $bbp_db->comments, $comment_field, $r[ $bbp_field ] );
 607          }
 608      }
 609  
 610      // Filter & return
 611      return (array) apply_filters( 'bbp_sanitize_anonymous_post_author', $r, $anonymous_data );
 612  }
 613  
 614  /**
 615   * Update the relevant meta-data for an anonymous post author
 616   *
 617   * @since 2.6.0 bbPress (r6400)
 618   *
 619   * @param int    $post_id
 620   * @param array  $anonymous_data
 621   * @param string $post_type
 622   */
 623  function bbp_update_anonymous_post_author( $post_id = 0, $anonymous_data = array(), $post_type = '' ) {
 624  
 625      // Maybe look for anonymous
 626      if ( empty( $anonymous_data ) ) {
 627          $anonymous_data = bbp_filter_anonymous_post_data();
 628      }
 629  
 630      // Sanitize parameters
 631      $post_id   = (int) $post_id;
 632      $post_type = sanitize_key( $post_type );
 633  
 634      // Bail if missing required data
 635      if ( empty( $post_id ) || empty( $post_type ) || empty( $anonymous_data ) ) {
 636          return;
 637      }
 638  
 639      // Parse arguments against default values
 640      $r = bbp_parse_args( $anonymous_data, array(
 641          'bbp_anonymous_name'    => '',
 642          'bbp_anonymous_email'   => '',
 643          'bbp_anonymous_website' => '',
 644      ), "update_{$post_type}" );
 645  
 646      // Update all anonymous metas
 647      foreach ( $r as $anon_key => $anon_value ) {
 648          update_post_meta( $post_id, '_' . $anon_key, (string) $anon_value, false );
 649      }
 650  }
 651  
 652  /**
 653   * Check for duplicate topics/replies
 654   *
 655   * Check to make sure that a user is not making a duplicate post
 656   *
 657   * @since 2.0.0 bbPress (r2763)
 658   *
 659   * @param array $post_data Contains information about the comment
 660   * @return bool True if it is not a duplicate, false if it is
 661   */
 662  function bbp_check_for_duplicate( $post_data = array() ) {
 663  
 664      // Parse arguments against default values
 665      $r = bbp_parse_args( $post_data, array(
 666          'post_author'    => 0,
 667          'post_type'      => array( bbp_get_topic_post_type(), bbp_get_reply_post_type() ),
 668          'post_parent'    => 0,
 669          'post_content'   => '',
 670          'post_status'    => bbp_get_trash_status_id(),
 671          'anonymous_data' => array()
 672      ), 'check_for_duplicate' );
 673  
 674      // No duplicate checks for those who can throttle
 675      if ( user_can( (int) $r['post_author'], 'throttle' ) ) {
 676          return true;
 677      }
 678  
 679      // Get the DB
 680      $bbp_db = bbp_db();
 681  
 682      // Default clauses
 683      $join = $where = '';
 684  
 685      // Check for anonymous post
 686      if ( empty( $r['post_author'] ) && ( ! empty( $r['anonymous_data'] ) && ! empty( $r['anonymous_data']['bbp_anonymous_email'] ) ) ) {
 687  
 688          // Sanitize the email address for querying
 689          $email = sanitize_email( $r['anonymous_data']['bbp_anonymous_email'] );
 690  
 691          // Only proceed
 692          if ( ! empty( $email ) && is_email( $email ) ) {
 693  
 694              // Get the meta SQL
 695              $clauses = get_meta_sql( array( array(
 696                  'key'   => '_bbp_anonymous_email',
 697                  'value' => $email,
 698              ) ), 'post', $bbp_db->posts, 'ID' );
 699  
 700              // Set clauses
 701              $join  = $clauses['join'];
 702  
 703              // "'", "%", "$" and are valid characters in email addresses
 704              $where = $bbp_db->remove_placeholder_escape( $clauses['where'] );
 705          }
 706      }
 707  
 708      // Unslash $r to pass through DB->prepare()
 709      //
 710      // @see: https://bbpress.trac.wordpress.org/ticket/2185/
 711      // @see: https://core.trac.wordpress.org/changeset/23973/
 712      $r = wp_unslash( $r );
 713  
 714      // Prepare duplicate check query
 715      $query  = "SELECT ID FROM {$bbp_db->posts} {$join}";
 716      $query .= $bbp_db->prepare( "WHERE post_type = %s AND post_status != %s AND post_author = %d AND post_content = %s", $r['post_type'], $r['post_status'], $r['post_author'], $r['post_content'] );
 717      $query .= ! empty( $r['post_parent'] )
 718          ? $bbp_db->prepare( " AND post_parent = %d", $r['post_parent'] )
 719          : '';
 720      $query .= $where;
 721      $query .= " LIMIT 1";
 722      $dupe   = apply_filters( 'bbp_check_for_duplicate_query', $query, $r );
 723  
 724      // Dupe found
 725      if ( $bbp_db->get_var( $dupe ) ) {
 726          do_action( 'bbp_check_for_duplicate_trigger', $post_data );
 727          return false;
 728      }
 729  
 730      // Dupe not found
 731      return true;
 732  }
 733  
 734  /**
 735   * Check for flooding
 736   *
 737   * Check to make sure that a user is not making too many posts in a short amount
 738   * of time.
 739   *
 740   * @since 2.0.0 bbPress (r2734)
 741   *
 742   * @param array $anonymous_data Optional - if it's an anonymous post. Do not
 743   *                              supply if supplying $author_id. Should be
 744   *                              sanitized (see {@link bbp_filter_anonymous_post_data()}
 745   * @param int $author_id Optional. Supply if it's a post by a logged in user.
 746   *                        Do not supply if supplying $anonymous_data.
 747   * @return bool True if there is no flooding, false if there is
 748   */
 749  function bbp_check_for_flood( $anonymous_data = array(), $author_id = 0 ) {
 750  
 751      // Allow for flood check to be skipped
 752      if ( apply_filters( 'bbp_bypass_check_for_flood', false, $anonymous_data, $author_id ) ) {
 753          return true;
 754      }
 755  
 756      // Option disabled. No flood checks.
 757      $throttle_time = get_option( '_bbp_throttle_time' );
 758      if ( empty( $throttle_time ) || ! bbp_allow_content_throttle() ) {
 759          return true;
 760      }
 761  
 762      // User is anonymous, so check a transient based on the IP
 763      if ( ! empty( $anonymous_data ) ) {
 764          $last_posted = get_transient( '_bbp_' . bbp_current_author_ip() . '_last_posted' );
 765  
 766          if ( ! empty( $last_posted ) && ( time() < ( $last_posted + $throttle_time ) ) ) {
 767              return false;
 768          }
 769  
 770      // User is logged in, so check their last posted time
 771      } elseif ( ! empty( $author_id ) ) {
 772          $author_id   = (int) $author_id;
 773          $last_posted = bbp_get_user_last_posted( $author_id );
 774  
 775          if ( ! empty( $last_posted ) && ( time() < ( $last_posted + $throttle_time ) ) && ! user_can( $author_id, 'throttle' ) ) {
 776              return false;
 777          }
 778      } else {
 779          return false;
 780      }
 781  
 782      return true;
 783  }
 784  
 785  /**
 786   * Checks topics and replies against the discussion moderation of blocked keys
 787   *
 788   * @since 2.1.0 bbPress (r3581)
 789   *
 790   * @param array $anonymous_data Optional - if it's an anonymous post. Do not
 791   *                              supply if supplying $author_id. Should be
 792   *                              sanitized (see {@link bbp_filter_anonymous_post_data()}
 793   * @param int $author_id Topic or reply author ID
 794   * @param string $title The title of the content
 795   * @param string $content The content being posted
 796   * @param mixed  $strict  False for moderation_keys. True for blacklist_keys.
 797   *                        String for custom keys.
 798   * @return bool True if test is passed, false if fail
 799   */
 800  function bbp_check_for_moderation( $anonymous_data = array(), $author_id = 0, $title = '', $content = '', $strict = false ) {
 801  
 802      // Custom moderation option key
 803      if ( is_string( $strict ) ) {
 804          $strict = sanitize_key( $strict );
 805  
 806          // Use custom key
 807          if ( ! empty( $strict ) ) {
 808              $hook_name   = $strict;
 809              $option_name = "{$strict}_keys";
 810  
 811          // Key was invalid, so default to moderation keys
 812          } else {
 813              $strict = false;
 814          }
 815      }
 816  
 817      // Strict mode uses WordPress "blacklist" settings
 818      if ( true === $strict ) {
 819          $hook_name   = 'blacklist';
 820          $option_name = 'blacklist_keys';
 821  
 822      // Non-strict uses WordPress "moderation" settings
 823      } elseif ( false === $strict ) {
 824          $hook_name   = 'moderation';
 825          $option_name = 'moderation_keys';
 826      }
 827  
 828      // Allow for moderation check to be skipped
 829      if ( apply_filters( "bbp_bypass_check_for_{$hook_name}", false, $anonymous_data, $author_id, $title, $content, $strict ) ) {
 830          return true;
 831      }
 832  
 833      // Maybe perform some author-specific capability checks
 834      if ( ! empty( $author_id ) ) {
 835  
 836          // Bail if user is a keymaster
 837          if ( bbp_is_user_keymaster( $author_id ) ) {
 838              return true;
 839  
 840          // Bail if user can moderate
 841          // https://bbpress.trac.wordpress.org/ticket/2726
 842          } elseif ( ( false === $strict ) && user_can( $author_id, 'moderate' ) ) {
 843              return true;
 844          }
 845      }
 846  
 847      // Define local variable(s)
 848      $_post     = array();
 849      $match_out = '';
 850  
 851      /** Max Links *************************************************************/
 852  
 853      // Only check max_links when not being strict
 854      if ( false === $strict ) {
 855          $max_links = get_option( 'comment_max_links' );
 856          if ( ! empty( $max_links ) ) {
 857  
 858              // How many links?
 859              $num_links = preg_match_all( '/(http|ftp|https):\/\//i', $content, $match_out );
 860  
 861              // Allow for bumping the max to include the user's URL
 862              if ( ! empty( $_post['url'] ) ) {
 863                  $num_links = apply_filters( 'comment_max_links_url', $num_links, $_post['url'], $content );
 864              }
 865  
 866              // Das ist zu viele links!
 867              if ( $num_links >= $max_links ) {
 868                  return false;
 869              }
 870          }
 871      }
 872  
 873      /** Moderation ************************************************************/
 874  
 875      /**
 876       * Filters the bbPress moderation keys.
 877       *
 878       * @since 2.6.0 bbPress (r6050)
 879       *
 880       * @param string $moderation List of moderation keys. One per new line.
 881       */
 882      $moderation = apply_filters( "bbp_{$hook_name}_keys", trim( get_option( $option_name ) ) );
 883  
 884      // Bail if no words to look for
 885      if ( empty( $moderation ) ) {
 886          return true;
 887      }
 888  
 889      /** User Data *************************************************************/
 890  
 891      // Map anonymous user data
 892      if ( ! empty( $anonymous_data ) ) {
 893          $_post['author'] = $anonymous_data['bbp_anonymous_name'];
 894          $_post['email']  = $anonymous_data['bbp_anonymous_email'];
 895          $_post['url']    = $anonymous_data['bbp_anonymous_website'];
 896  
 897      // Map current user data
 898      } elseif ( ! empty( $author_id ) ) {
 899  
 900          // Get author data
 901          $user = get_userdata( $author_id );
 902  
 903          // If data exists, map it
 904          if ( ! empty( $user ) ) {
 905              $_post['author'] = $user->display_name;
 906              $_post['email']  = $user->user_email;
 907              $_post['url']    = $user->user_url;
 908          }
 909      }
 910  
 911      // Current user IP and user agent
 912      $_post['user_ip'] = bbp_current_author_ip();
 913      $_post['user_ua'] = bbp_current_author_ua();
 914  
 915      // Post title and content
 916      $_post['title']   = $title;
 917      $_post['content'] = $content;
 918  
 919      // Ensure HTML tags are not being used to bypass the moderation list.
 920      $_post['comment_without_html'] = wp_strip_all_tags( $content );
 921  
 922      /** Words *****************************************************************/
 923  
 924      // Get words separated by new lines
 925      $words = explode( "\n", $moderation );
 926  
 927      // Loop through words
 928      foreach ( (array) $words as $word ) {
 929  
 930          // Trim the whitespace from the word
 931          $word = trim( $word );
 932  
 933          // Skip empty lines
 934          if ( empty( $word ) ) {
 935              continue;
 936          }
 937  
 938          // Do some escaping magic so that '#' chars in the
 939          // spam words don't break things:
 940          $word    = preg_quote( $word, '#' );
 941          $pattern = "#{$word}#i";
 942  
 943          // Loop through post data
 944          foreach ( $_post as $post_data ) {
 945  
 946              // Check each user data for current word
 947              if ( preg_match( $pattern, $post_data ) ) {
 948  
 949                  // Post does not pass
 950                  return false;
 951              }
 952          }
 953      }
 954  
 955      // Check passed successfully
 956      return true;
 957  }
 958  
 959  /**
 960   * Deprecated. Use bbp_check_for_moderation() with strict flag set.
 961   *
 962   * @since 2.0.0 bbPress (r3446)
 963   * @since 2.6.0 bbPress (r6854)
 964   * @deprecated 2.6.0 Use bbp_check_for_moderation() with strict flag set
 965   */
 966  function bbp_check_for_blacklist( $anonymous_data = array(), $author_id = 0, $title = '', $content = '' ) {
 967      return bbp_check_for_moderation( $anonymous_data, $author_id, $title, $content, false );
 968  }
 969  
 970  /** Subscriptions *************************************************************/
 971  
 972  /**
 973   * Get the "Do Not Reply" email address to use when sending subscription emails.
 974   *
 975   * We make some educated guesses here based on the home URL. Filters are
 976   * available to customize this address further. In the future, we may consider
 977   * using `admin_email` instead, though this is not normally publicized.
 978   *
 979   * We use `$_SERVER['SERVER_NAME']` here to mimic similar functionality in
 980   * WordPress core. Previously, we used `get_home_url()` to use already validated
 981   * user input, but it was causing issues in some installations.
 982   *
 983   * @since 2.6.0 bbPress (r5409)
 984   *
 985   * @see  wp_mail
 986   * @see  wp_notify_postauthor
 987   * @link https://bbpress.trac.wordpress.org/ticket/2618
 988   *
 989   * @return string
 990   */
 991  function bbp_get_do_not_reply_address() {
 992      $sitename = strtolower( $_SERVER['SERVER_NAME'] );
 993      if ( substr( $sitename, 0, 4 ) === 'www.' ) {
 994          $sitename = substr( $sitename, 4 );
 995      }
 996  
 997      // Filter & return
 998      return apply_filters( 'bbp_get_do_not_reply_address', 'noreply@' . $sitename );
 999  }
1000  
1001  /**
1002   * Sends notification emails for new replies to subscribed topics
1003   *
1004   * Gets new post ID and check if there are subscribed users to that topic, and
1005   * if there are, send notifications
1006   *
1007   * Note: in bbPress 2.6, we've moved away from 1 email per subscriber to 1 email
1008   * with everyone BCC'd. This may have negative repercussions for email services
1009   * that limit the number of addresses in a BCC field (often to around 500.) In
1010   * those cases, we recommend unhooking this function and creating your own
1011   * custom email script.
1012   *
1013   * @since 2.6.0 bbPress (r5413)
1014   *
1015   * @param int $reply_id ID of the newly made reply
1016   * @param int $topic_id ID of the topic of the reply
1017   * @param int $forum_id ID of the forum of the reply
1018   * @param array $anonymous_data Optional - if it's an anonymous post. Do not
1019   *                              supply if supplying $author_id. Should be
1020   *                              sanitized (see {@link bbp_filter_anonymous_post_data()}
1021   * @param int $reply_author ID of the topic author ID
1022   * @return bool True on success, false on failure
1023   */
1024  function bbp_notify_topic_subscribers( $reply_id = 0, $topic_id = 0, $forum_id = 0, $anonymous_data = array(), $reply_author = 0 ) {
1025  
1026      // Bail if subscriptions are turned off
1027      if ( ! bbp_is_subscriptions_active() ) {
1028          return false;
1029      }
1030  
1031      // Bail if importing
1032      if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
1033          return false;
1034      }
1035  
1036      /** Validation ************************************************************/
1037  
1038      $reply_id = bbp_get_reply_id( $reply_id );
1039      $topic_id = bbp_get_topic_id( $topic_id );
1040      $forum_id = bbp_get_forum_id( $forum_id );
1041  
1042      /** Topic *****************************************************************/
1043  
1044      // Bail if topic is not public (includes closed)
1045      if ( ! bbp_is_topic_public( $topic_id ) ) {
1046          return false;
1047      }
1048  
1049      /** Reply *****************************************************************/
1050  
1051      // Bail if reply is not published
1052      if ( ! bbp_is_reply_published( $reply_id ) ) {
1053          return false;
1054      }
1055  
1056      // Poster name
1057      $reply_author_name = bbp_get_reply_author_display_name( $reply_id );
1058  
1059      /** Users *****************************************************************/
1060  
1061      // Get topic subscribers and bail if empty
1062      $user_ids = bbp_get_subscribers( $topic_id );
1063  
1064      // Remove the reply author from the list.
1065      $reply_author_key = array_search( (int) $reply_author, $user_ids, true );
1066      if ( false !== $reply_author_key ) {
1067          unset( $user_ids[ $reply_author_key ] );
1068      }
1069  
1070      // Dedicated filter to manipulate user ID's to send emails to
1071      $user_ids = (array) apply_filters( 'bbp_topic_subscription_user_ids', $user_ids );
1072  
1073      // Bail of the reply author was the only one subscribed.
1074      if ( empty( $user_ids ) ) {
1075          return false;
1076      }
1077  
1078      // Get email addresses, bail if empty
1079      $email_addresses = bbp_get_email_addresses_from_user_ids( $user_ids );
1080      if ( empty( $email_addresses ) ) {
1081          return false;
1082      }
1083  
1084      /** Mail ******************************************************************/
1085  
1086      // Remove filters from reply content and topic title to prevent content
1087      // from being encoded with HTML entities, wrapped in paragraph tags, etc...
1088      bbp_remove_all_filters( 'bbp_get_reply_content' );
1089      bbp_remove_all_filters( 'bbp_get_topic_title'   );
1090      bbp_remove_all_filters( 'the_title'             );
1091  
1092      // Strip tags from text and setup mail data
1093      $blog_name         = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
1094      $topic_title       = wp_specialchars_decode( strip_tags( bbp_get_topic_title( $topic_id ) ), ENT_QUOTES );
1095      $reply_author_name = wp_specialchars_decode( strip_tags( $reply_author_name ), ENT_QUOTES );
1096      $reply_content     = wp_specialchars_decode( strip_tags( bbp_get_reply_content( $reply_id ) ), ENT_QUOTES );
1097      $reply_url         = bbp_get_reply_url( $reply_id );
1098  
1099      // For plugins to filter messages per reply/topic/user
1100      $message = sprintf( esc_html__( '%1$s wrote:
1101  
1102  %2$s
1103  
1104  Post Link: %3$s
1105  
1106  -----------
1107  
1108  You are receiving this email because you subscribed to a forum topic.
1109  
1110  Login and visit the topic to unsubscribe from these emails.', 'bbpress' ),
1111  
1112          $reply_author_name,
1113          $reply_content,
1114          $reply_url
1115      );
1116  
1117      $message = apply_filters( 'bbp_subscription_mail_message', $message, $reply_id, $topic_id );
1118      if ( empty( $message ) ) {
1119          return;
1120      }
1121  
1122      // For plugins to filter titles per reply/topic/user
1123      $subject = apply_filters( 'bbp_subscription_mail_title', '[' . $blog_name . '] ' . $topic_title, $reply_id, $topic_id );
1124      if ( empty( $subject ) ) {
1125          return;
1126      }
1127  
1128      /** Headers ***************************************************************/
1129  
1130      // Get the noreply@ address
1131      $no_reply   = bbp_get_do_not_reply_address();
1132  
1133      // Setup "From" email address
1134      $from_email = apply_filters( 'bbp_subscription_from_email', $no_reply );
1135  
1136      // Setup the From header
1137      $headers = array( 'From: ' . get_bloginfo( 'name' ) . ' <' . $from_email . '>' );
1138  
1139      // Loop through addresses
1140      foreach ( (array) $email_addresses as $address ) {
1141          $headers[] = 'Bcc: ' . $address;
1142      }
1143  
1144      /** Send it ***************************************************************/
1145  
1146      // Custom headers
1147      $headers  = apply_filters( 'bbp_subscription_mail_headers', $headers  );
1148       $to_email = apply_filters( 'bbp_subscription_to_email',     $no_reply );
1149  
1150      do_action( 'bbp_pre_notify_subscribers', $reply_id, $topic_id, $user_ids );
1151  
1152      // Send notification email
1153      wp_mail( $to_email, $subject, $message, $headers );
1154  
1155      do_action( 'bbp_post_notify_subscribers', $reply_id, $topic_id, $user_ids );
1156  
1157      // Restore previously removed filters
1158      bbp_restore_all_filters( 'bbp_get_topic_content' );
1159      bbp_restore_all_filters( 'bbp_get_topic_title'   );
1160      bbp_restore_all_filters( 'the_title'             );
1161  
1162      return true;
1163  }
1164  
1165  /**
1166   * Sends notification emails for new topics to subscribed forums
1167   *
1168   * Gets new post ID and check if there are subscribed users to that forum, and
1169   * if there are, send notifications
1170   *
1171   * Note: in bbPress 2.6, we've moved away from 1 email per subscriber to 1 email
1172   * with everyone BCC'd. This may have negative repercussions for email services
1173   * that limit the number of addresses in a BCC field (often to around 500.) In
1174   * those cases, we recommend unhooking this function and creating your own
1175   * custom email script.
1176   *
1177   * @since 2.5.0 bbPress (r5156)
1178   *
1179   * @param int $topic_id ID of the newly made reply
1180   * @param int $forum_id ID of the forum for the topic
1181   * @param array $anonymous_data Optional - if it's an anonymous post. Do not
1182   *                              supply if supplying $author_id. Should be
1183   *                              sanitized (see {@link bbp_filter_anonymous_post_data()}
1184   * @param int $topic_author ID of the topic author ID
1185   * @return bool True on success, false on failure
1186   */
1187  function bbp_notify_forum_subscribers( $topic_id = 0, $forum_id = 0, $anonymous_data = array(), $topic_author = 0 ) {
1188  
1189      // Bail if subscriptions are turned off
1190      if ( ! bbp_is_subscriptions_active() ) {
1191          return false;
1192      }
1193  
1194      // Bail if importing
1195      if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
1196          return false;
1197      }
1198  
1199      /** Validation ************************************************************/
1200  
1201      $topic_id = bbp_get_topic_id( $topic_id );
1202      $forum_id = bbp_get_forum_id( $forum_id );
1203  
1204      /**
1205       * Necessary for backwards compatibility
1206       *
1207       * @see https://bbpress.trac.wordpress.org/ticket/2620
1208       */
1209      $user_id  = 0;
1210  
1211      /** Topic *****************************************************************/
1212  
1213      // Bail if topic is not public (includes closed)
1214      if ( ! bbp_is_topic_public( $topic_id ) ) {
1215          return false;
1216      }
1217  
1218      // Poster name
1219      $topic_author_name = bbp_get_topic_author_display_name( $topic_id );
1220  
1221      /** Users *****************************************************************/
1222  
1223      // Get topic subscribers and bail if empty
1224      $user_ids = bbp_get_subscribers( $forum_id );
1225  
1226      // Remove the topic author from the list.
1227      $topic_author_key = array_search( (int) $topic_author, $user_ids, true );
1228      if ( false !== $topic_author_key ) {
1229          unset( $user_ids[ $topic_author_key ] );
1230      }
1231  
1232      // Dedicated filter to manipulate user ID's to send emails to
1233      $user_ids = (array) apply_filters( 'bbp_forum_subscription_user_ids', $user_ids );
1234  
1235      // Bail of the reply author was the only one subscribed.
1236      if ( empty( $user_ids ) ) {
1237          return false;
1238      }
1239  
1240      // Get email addresses, bail if empty
1241      $email_addresses = bbp_get_email_addresses_from_user_ids( $user_ids );
1242      if ( empty( $email_addresses ) ) {
1243          return false;
1244      }
1245  
1246      /** Mail ******************************************************************/
1247  
1248      // Remove filters from reply content and topic title to prevent content
1249      // from being encoded with HTML entities, wrapped in paragraph tags, etc...
1250      bbp_remove_all_filters( 'bbp_get_topic_content' );
1251      bbp_remove_all_filters( 'bbp_get_topic_title'   );
1252      bbp_remove_all_filters( 'the_title'             );
1253  
1254      // Strip tags from text and setup mail data
1255      $blog_name         = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
1256      $topic_title       = wp_specialchars_decode( strip_tags( bbp_get_topic_title( $topic_id ) ), ENT_QUOTES );
1257      $topic_author_name = wp_specialchars_decode( strip_tags( $topic_author_name ), ENT_QUOTES );
1258      $topic_content     = wp_specialchars_decode( strip_tags( bbp_get_topic_content( $topic_id ) ), ENT_QUOTES );
1259      $topic_url         = get_permalink( $topic_id );
1260  
1261      // For plugins to filter messages per reply/topic/user
1262      $message = sprintf( esc_html__( '%1$s wrote:
1263  
1264  %2$s
1265  
1266  Topic Link: %3$s
1267  
1268  -----------
1269  
1270  You are receiving this email because you subscribed to a forum.
1271  
1272  Login and visit the topic to unsubscribe from these emails.', 'bbpress' ),
1273  
1274          $topic_author_name,
1275          $topic_content,
1276          $topic_url
1277      );
1278  
1279      $message = apply_filters( 'bbp_forum_subscription_mail_message', $message, $topic_id, $forum_id, $user_id );
1280      if ( empty( $message ) ) {
1281          return;
1282      }
1283  
1284      // For plugins to filter titles per reply/topic/user
1285      $subject = apply_filters( 'bbp_forum_subscription_mail_title', '[' . $blog_name . '] ' . $topic_title, $topic_id, $forum_id, $user_id );
1286      if ( empty( $subject ) ) {
1287          return;
1288      }
1289  
1290      /** Headers ***************************************************************/
1291  
1292      // Get the noreply@ address
1293      $no_reply   = bbp_get_do_not_reply_address();
1294  
1295      // Setup "From" email address
1296      $from_email = apply_filters( 'bbp_subscription_from_email', $no_reply );
1297  
1298      // Setup the From header
1299      $headers = array( 'From: ' . get_bloginfo( 'name' ) . ' <' . $from_email . '>' );
1300  
1301      // Loop through addresses
1302      foreach ( (array) $email_addresses as $address ) {
1303          $headers[] = 'Bcc: ' . $address;
1304      }
1305  
1306      /** Send it ***************************************************************/
1307  
1308      // Custom headers
1309      $headers  = apply_filters( 'bbp_subscription_mail_headers', $headers  );
1310      $to_email = apply_filters( 'bbp_subscription_to_email',     $no_reply );
1311  
1312      do_action( 'bbp_pre_notify_forum_subscribers', $topic_id, $forum_id, $user_ids );
1313  
1314      // Send notification email
1315      wp_mail( $to_email, $subject, $message, $headers );
1316  
1317      do_action( 'bbp_post_notify_forum_subscribers', $topic_id, $forum_id, $user_ids );
1318  
1319      // Restore previously removed filters
1320      bbp_restore_all_filters( 'bbp_get_topic_content' );
1321      bbp_restore_all_filters( 'bbp_get_topic_title'   );
1322      bbp_restore_all_filters( 'the_title'             );
1323  
1324      return true;
1325  }
1326  
1327  /**
1328   * Sends notification emails for new replies to subscribed topics
1329   *
1330   * This function is deprecated. Please use: bbp_notify_topic_subscribers()
1331   *
1332   * @since 2.0.0 bbPress (r2668)
1333   *
1334   * @deprecated 2.6.0 bbPress (r5412)
1335   *
1336   * @param int $reply_id ID of the newly made reply
1337   * @param int $topic_id ID of the topic of the reply
1338   * @param int $forum_id ID of the forum of the reply
1339   * @param array $anonymous_data Optional - if it's an anonymous post. Do not
1340   *                              supply if supplying $author_id. Should be
1341   *                              sanitized (see {@link bbp_filter_anonymous_post_data()}
1342   * @param int $reply_author ID of the topic author ID
1343   *
1344   * @return bool True on success, false on failure
1345   */
1346  function bbp_notify_subscribers( $reply_id = 0, $topic_id = 0, $forum_id = 0, $anonymous_data = array(), $reply_author = 0 ) {
1347      return bbp_notify_topic_subscribers( $reply_id, $topic_id, $forum_id, $anonymous_data, $reply_author );
1348  }
1349  
1350  /**
1351   * Return an array of user email addresses from an array of user IDs
1352   *
1353   * @since 2.6.0 bbPress (r6722)
1354   *
1355   * @param array $user_ids
1356   * @return array
1357   */
1358  function bbp_get_email_addresses_from_user_ids( $user_ids = array() ) {
1359  
1360      // Default return value
1361      $retval = array();
1362  
1363      // Maximum number of users to get per database query
1364      $limit = apply_filters( 'bbp_get_users_chunk_limit', 100 );
1365  
1366      // Only do the work if there are user IDs to query for
1367      if ( ! empty( $user_ids ) ) {
1368  
1369          // Get total number of sets
1370          $steps = ceil( count( $user_ids ) / $limit );
1371          $range = array_map( 'intval', range( 1, $steps ) );
1372  
1373          // Loop through users
1374          foreach ( $range as $loop ) {
1375  
1376              // Initial loop has no offset
1377              $offset = ( 1 === $loop )
1378                  ? 0
1379                  : $limit * $loop;
1380  
1381              // Calculate user IDs to include
1382              $loop_ids = array_slice( $user_ids, $offset, $limit );
1383  
1384              // Skip if something went wrong
1385              if ( empty( $loop_ids ) ) {
1386                  continue;
1387              }
1388  
1389              // Call get_users() in a way that users are cached
1390              $loop_users = get_users( array(
1391                  'blog_id' => 0,
1392                  'fields'  => 'all_with_meta',
1393                  'include' => $loop_ids
1394              ) );
1395  
1396              // Pluck emails from users
1397              $loop_emails = wp_list_pluck( $loop_users, 'user_email' );
1398  
1399              // Clean-up memory, for big user sets
1400              unset( $loop_users );
1401  
1402              // Merge users into return value
1403              if ( ! empty( $loop_emails ) ) {
1404                  $retval = array_merge( $retval, $loop_emails );
1405              }
1406          }
1407  
1408          // No duplicates
1409          $retval = bbp_get_unique_array_values( $retval );
1410      }
1411  
1412      // Filter & return
1413      return apply_filters( 'bbp_get_email_addresses_from_user_ids', $retval, $user_ids, $limit );
1414  }
1415  
1416  /** Login *********************************************************************/
1417  
1418  /**
1419   * Return a clean and reliable logout URL
1420   *
1421   * This function is used to filter `logout_url`. If no $redirect_to value is
1422   * passed, it will default to the request uri, then the forum root.
1423   *
1424   * See: `wp_logout_url()`
1425   *
1426   * @since 2.1.0 bbPress (2815)
1427   *
1428   * @param string $url URL used to log out
1429   * @param string $redirect_to Where to redirect to?
1430   *
1431   * @return string The url
1432   */
1433  function bbp_logout_url( $url = '', $redirect_to = '' ) {
1434  
1435      // If there is no redirect in the URL, let's add one...
1436      if ( ! strstr( $url, 'redirect_to' ) ) {
1437  
1438          // Get the forum root, to maybe use as a default
1439          $forum_root = bbp_get_root_url();
1440  
1441          // No redirect passed, so check referer and fallback to request uri
1442          if ( empty( $redirect_to ) ) {
1443  
1444              // Check for a valid referer
1445              $redirect_to = wp_get_referer();
1446  
1447              // Fallback to request uri if invalid referer
1448              if ( false === $redirect_to ) {
1449                  $redirect_to = bbp_get_url_scheme() . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1450              }
1451          }
1452  
1453          // Filter the $redirect_to destination
1454          $filtered  = apply_filters( 'bbp_logout_url_redirect_to', $redirect_to );
1455  
1456          // Validate $redirect_to, default to root
1457          $validated = wp_validate_redirect( $filtered, $forum_root );
1458  
1459          // Assemble $redirect_to and add it (encoded) to full $url
1460          $appended  = add_query_arg( array( 'loggedout'   => 'true'   ), $validated );
1461          $encoded   = urlencode( $appended );
1462          $url       = add_query_arg( array( 'redirect_to' => $encoded ), $url       );
1463      }
1464  
1465      // Filter & return
1466      return apply_filters( 'bbp_logout_url', $url, $redirect_to );
1467  }
1468  
1469  /** Queries *******************************************************************/
1470  
1471  /**
1472   * Merge user defined arguments into defaults array.
1473   *
1474   * This function is used throughout bbPress to allow for either a string or array
1475   * to be merged into another array. It is identical to wp_parse_args() except
1476   * it allows for arguments to be passively or aggressively filtered using the
1477   * optional $filter_key parameter.
1478   *
1479   * @since 2.1.0 bbPress (r3839)
1480   *
1481   * @param string|array $args Value to merge with $defaults
1482   * @param array $defaults Array that serves as the defaults.
1483   * @param string $filter_key String to key the filters from
1484   * @return array Merged user defined values with defaults.
1485   */
1486  function bbp_parse_args( $args, $defaults = array(), $filter_key = '' ) {
1487  
1488      // Setup a temporary array from $args
1489      if ( is_object( $args ) ) {
1490          $r = get_object_vars( $args );
1491      } elseif ( is_array( $args ) ) {
1492          $r =& $args;
1493      } else {
1494          wp_parse_str( $args, $r );
1495      }
1496  
1497      // Passively filter the args before the parse
1498      if ( ! empty( $filter_key ) ) {
1499          $r = apply_filters( "bbp_before_{$filter_key}_parse_args", $r, $args, $defaults );
1500      }
1501  
1502      // Parse
1503      if ( is_array( $defaults ) && ! empty( $defaults ) ) {
1504          $r = array_merge( $defaults, $r );
1505      }
1506  
1507      // Aggressively filter the args after the parse
1508      if ( ! empty( $filter_key ) ) {
1509          $r = apply_filters( "bbp_after_{$filter_key}_parse_args", $r, $args, $defaults );
1510      }
1511  
1512      // Return the parsed results
1513      return $r;
1514  }
1515  
1516  /**
1517   * Adds ability to include or exclude specific post_parent ID's
1518   *
1519   * @since 2.0.0 bbPress (r2996)
1520   *
1521   * @deprecated 2.5.8 bbPress (r5814)
1522   *
1523   * @global WP $wp
1524   * @param string $where
1525   * @param WP_Query $object
1526   * @return string
1527   */
1528  function bbp_query_post_parent__in( $where, $object = '' ) {
1529      global $wp;
1530  
1531      // Noop if WP core supports this already
1532      if ( in_array( 'post_parent__in', $wp->private_query_vars, true ) ) {
1533          return $where;
1534      }
1535  
1536      // Bail if no object passed
1537      if ( empty( $object ) ) {
1538          return $where;
1539      }
1540  
1541      // Only 1 post_parent so return $where
1542      if ( is_numeric( $object->query_vars['post_parent'] ) ) {
1543          return $where;
1544      }
1545  
1546      // Get the DB
1547      $bbp_db = bbp_db();
1548  
1549      // Including specific post_parent's
1550      if ( ! empty( $object->query_vars['post_parent__in'] ) ) {
1551          $ids    = implode( ',', wp_parse_id_list( $object->query_vars['post_parent__in'] ) );
1552          $where .= " AND {$bbp_db->posts}.post_parent IN ($ids)";
1553  
1554      // Excluding specific post_parent's
1555      } elseif ( ! empty( $object->query_vars['post_parent__not_in'] ) ) {
1556          $ids    = implode( ',', wp_parse_id_list( $object->query_vars['post_parent__not_in'] ) );
1557          $where .= " AND {$bbp_db->posts}.post_parent NOT IN ($ids)";
1558      }
1559  
1560      // Return possibly modified $where
1561      return $where;
1562  }
1563  
1564  /**
1565   * Query the DB and get the last public post_id that has parent_id as post_parent
1566   *
1567   * @since 2.0.0 bbPress (r2868)
1568   * @since 2.6.0 bbPress (r5954) Replace direct queries with WP_Query() objects
1569   *
1570   * @param int    $parent_id Parent id.
1571   * @param string $post_type Post type. Defaults to 'post'.
1572   * @return int The last active post_id
1573   */
1574  function bbp_get_public_child_last_id( $parent_id = 0, $post_type = 'post' ) {
1575  
1576      // Bail if nothing passed
1577      if ( empty( $parent_id ) ) {
1578          return false;
1579      }
1580  
1581      // Get the public posts status
1582      $post_status = array( bbp_get_public_status_id() );
1583  
1584      // Add closed status if topic post type
1585      if ( bbp_get_topic_post_type() === $post_type ) {
1586          $post_status[] = bbp_get_closed_status_id();
1587      }
1588  
1589      $query = new WP_Query( array(
1590          'fields'         => 'ids',
1591          'post_parent'    => $parent_id,
1592          'post_status'    => $post_status,
1593          'post_type'      => $post_type,
1594          'posts_per_page' => 1,
1595          'orderby'        => array(
1596              'post_date' => 'DESC',
1597              'ID'        => 'DESC'
1598          ),
1599  
1600          // Performance
1601          'suppress_filters'       => true,
1602          'update_post_term_cache' => false,
1603          'update_post_meta_cache' => false,
1604          'ignore_sticky_posts'    => true,
1605          'no_found_rows'          => true
1606      ) );
1607      $child_id = array_shift( $query->posts );
1608      unset( $query );
1609  
1610      // Filter & return
1611      return (int) apply_filters( 'bbp_get_public_child_last_id', $child_id, $parent_id, $post_type );
1612  }
1613  
1614  /**
1615   * Query the database for child counts, grouped by type & status
1616   *
1617   * @since 2.6.0 bbPress (r6826)
1618   *
1619   * @param int $parent_id
1620   */
1621  function bbp_get_child_counts( $parent_id = 0 ) {
1622  
1623      // Create cache key
1624      $parent_id    = absint( $parent_id );
1625      $key          = md5( serialize( array( 'parent_id' => $parent_id, 'post_type' => bbp_get_post_types() ) ) );
1626      $last_changed = wp_cache_get_last_changed( 'bbpress_posts' );
1627      $cache_key    = "bbp_child_counts:{$key}:{$last_changed}";
1628  
1629      // Check for cache and set if needed
1630      $retval = wp_cache_get( $cache_key, 'bbpress_posts' );
1631      if ( false === $retval ) {
1632  
1633          // Setup the DB & query
1634          $bbp_db = bbp_db();
1635          $sql    = "SELECT
1636                          p.post_type AS type,
1637                          p.post_status AS status,
1638                          COUNT( * ) AS count
1639                      FROM {$bbp_db->posts} AS p
1640                          LEFT JOIN {$bbp_db->postmeta} AS pm
1641                              ON p.ID = pm.post_id
1642                              AND pm.meta_key = %s
1643                      WHERE pm.meta_value = %d
1644                      GROUP BY p.post_status, p.post_type";
1645  
1646          // Get prepare vars
1647          $post_type = get_post_type( $parent_id );
1648          $meta_key  = "_bbp_{$post_type}_id";
1649  
1650          // Prepare & get results
1651          $query     = $bbp_db->prepare( $sql, $meta_key, $parent_id );
1652          $results   = $bbp_db->get_results( $query, ARRAY_A );
1653  
1654          // Setup return value
1655          $retval    = wp_list_pluck( $results, 'type', 'type' );
1656          $statuses  = get_post_stati();
1657  
1658          // Loop through results
1659          foreach ( $results as $row ) {
1660  
1661              // Setup empties
1662              if ( ! is_array( $retval[ $row['type'] ] ) ) {
1663                  $retval[ $row['type'] ] = array_fill_keys( $statuses, 0 );
1664              }
1665  
1666              // Set statuses
1667              $retval[ $row['type'] ][ $row['status'] ] = bbp_number_not_negative( $row['count'] );
1668          }
1669  
1670          // Always cache the results
1671          wp_cache_set( $cache_key, $retval, 'bbpress_posts' );
1672      }
1673  
1674      // Make sure results are INTs
1675      return (array) apply_filters( 'bbp_get_child_counts', $retval, $parent_id );
1676  }
1677  
1678  /**
1679   * Filter a list of child counts, from `bbp_get_child_counts()`
1680   *
1681   * @since 2.6.0 bbPress (r6826)
1682   *
1683   * @param int    $parent_id  ID of post to get child counts from
1684   * @param array  $types      Optional. An array of post types to filter by
1685   * @param array  $statuses   Optional. An array of post statuses to filter by
1686   *
1687   * @return array A list of objects or object fields.
1688   */
1689  function bbp_filter_child_counts_list( $parent_id = 0, $types = array( 'post' ), $statuses = array() ) {
1690  
1691      // Setup local vars
1692      $retval   = array();
1693      $types    = array_flip( (array) $types    );
1694      $statuses = array_flip( (array) $statuses );
1695      $counts   = bbp_get_child_counts( $parent_id );
1696  
1697      // Loop through counts by type
1698      foreach ( $counts as $type => $type_counts ) {
1699  
1700          // Skip if not this type
1701          if ( ! isset( $types[ $type ] ) ) {
1702              continue;
1703          }
1704  
1705          // Maybe filter statuses
1706          if ( ! empty( $statuses ) ) {
1707              $type_counts = array_intersect_key( $type_counts, $statuses );
1708          }
1709  
1710          // Add type counts to return array
1711          $retval[ $type ] = $type_counts;
1712      }
1713  
1714      // Filter & return
1715      return (array) apply_filters( 'bbp_filter_child_counts_list', $retval, $parent_id, $types, $statuses );
1716  }
1717  
1718  /**
1719   * Query the DB and get a count of public children
1720   *
1721   * @since 2.0.0 bbPress (r2868)
1722   * @since 2.6.0 bbPress (r5954) Replace direct queries with WP_Query() objects
1723   *
1724   * @param int    $parent_id Parent id.
1725   * @param string $post_type Post type. Defaults to 'post'.
1726   * @return int The number of children
1727   */
1728  function bbp_get_public_child_count( $parent_id = 0, $post_type = 'post' ) {
1729  
1730      // Bail if nothing passed
1731      if ( empty( $post_type ) ) {
1732          return false;
1733      }
1734  
1735      // Which statuses
1736      switch ( $post_type ) {
1737  
1738          // Forum
1739          case bbp_get_forum_post_type() :
1740              $post_status = array( bbp_get_public_status_id() );
1741              break;
1742  
1743          // Topic
1744          case bbp_get_topic_post_type() :
1745              $post_status = bbp_get_public_topic_statuses();
1746              break;
1747  
1748          // Reply
1749          case bbp_get_reply_post_type() :
1750          default :
1751              $post_status = bbp_get_public_reply_statuses();
1752              break;
1753      }
1754  
1755      // Get counts
1756      $counts      = bbp_filter_child_counts_list( $parent_id, $post_type, $post_status );
1757      $child_count = isset( $counts[ $post_type ] )
1758          ? bbp_number_not_negative( array_sum( array_values( $counts[ $post_type ] ) ) )
1759          : 0;
1760  
1761      // Filter & return
1762      return (int) apply_filters( 'bbp_get_public_child_count', $child_count, $parent_id, $post_type );
1763  }
1764  /**
1765   * Query the DB and get a count of public children
1766   *
1767   * @since 2.0.0 bbPress (r2868)
1768   * @since 2.6.0 bbPress (r5954) Replace direct queries with WP_Query() objects
1769   *
1770   * @param int    $parent_id Parent id.
1771   * @param string $post_type Post type. Defaults to 'post'.
1772   * @return int The number of children
1773   */
1774  function bbp_get_non_public_child_count( $parent_id = 0, $post_type = 'post' ) {
1775  
1776      // Bail if nothing passed
1777      if ( empty( $parent_id ) || empty( $post_type ) ) {
1778          return false;
1779      }
1780  
1781      // Which statuses
1782      switch ( $post_type ) {
1783  
1784          // Forum
1785          case bbp_get_forum_post_type() :
1786              $post_status = array( bbp_get_private_status_id(), bbp_get_hidden_status_id() );
1787              break;
1788  
1789          // Topic
1790          case bbp_get_topic_post_type() :
1791              $post_status = bbp_get_non_public_topic_statuses();
1792              break;
1793  
1794          // Reply
1795          case bbp_get_reply_post_type() :
1796          default :
1797              $post_status = bbp_get_non_public_reply_statuses();
1798              break;
1799      }
1800  
1801      // Get counts
1802      $counts      = bbp_filter_child_counts_list( $parent_id, $post_type, $post_status );
1803      $child_count = isset( $counts[ $post_type ] )
1804          ? bbp_number_not_negative( array_sum( array_values( $counts[ $post_type ] ) ) )
1805          : 0;
1806  
1807      // Filter & return
1808      return (int) apply_filters( 'bbp_get_non_public_child_count', $child_count, $parent_id, $post_type );
1809  }
1810  
1811  /**
1812   * Query the DB and get the child id's of public children
1813   *
1814   * @since 2.0.0 bbPress (r2868)
1815   * @since 2.6.0 bbPress (r5954) Replace direct queries with WP_Query() objects
1816   *
1817   * @param int    $parent_id Parent id.
1818   * @param string $post_type Post type. Defaults to 'post'.
1819   *
1820   * @return array The array of children
1821   */
1822  function bbp_get_public_child_ids( $parent_id = 0, $post_type = 'post' ) {
1823  
1824      // Bail if nothing passed
1825      if ( empty( $parent_id ) || empty( $post_type ) ) {
1826          return array();
1827      }
1828  
1829      // Get the public post status
1830      $post_status = array( bbp_get_public_status_id() );
1831  
1832      // Add closed status if topic post type
1833      if ( bbp_get_topic_post_type() === $post_type ) {
1834          $post_status[] = bbp_get_closed_status_id();
1835      }
1836  
1837      $query = new WP_Query( array(
1838          'fields'         => 'ids',
1839          'post_parent'    => $parent_id,
1840          'post_status'    => $post_status,
1841          'post_type'      => $post_type,
1842          'posts_per_page' => -1,
1843          'orderby'        => array(
1844              'post_date' => 'DESC',
1845              'ID'        => 'DESC'
1846          ),
1847  
1848          // Performance
1849          'nopaging'               => true,
1850          'suppress_filters'       => true,
1851          'update_post_term_cache' => false,
1852          'update_post_meta_cache' => false,
1853          'ignore_sticky_posts'    => true,
1854          'no_found_rows'          => true
1855      ) );
1856      $child_ids = ! empty( $query->posts ) ? $query->posts : array();
1857      unset( $query );
1858  
1859      // Filter & return
1860      return (array) apply_filters( 'bbp_get_public_child_ids', $child_ids, $parent_id, $post_type );
1861  }
1862  
1863  /**
1864   * Query the DB and get the child id's of all children
1865   *
1866   * @since 2.0.0 bbPress (r3325)
1867   *
1868   * @param int $parent_id  Parent id
1869   * @param string $post_type Post type. Defaults to 'post'
1870   *
1871   * @return array The array of children
1872   */
1873  function bbp_get_all_child_ids( $parent_id = 0, $post_type = 'post' ) {
1874  
1875      // Bail if nothing passed
1876      if ( empty( $parent_id ) || empty( $post_type ) ) {
1877          return array();
1878      }
1879  
1880      // Check cache key
1881      $key          = md5( serialize( array( 'parent_id' => $parent_id, 'post_type' => $post_type ) ) );
1882      $last_changed = wp_cache_get_last_changed( 'bbpress_posts' );
1883      $cache_key    = "bbp_child_ids:{$key}:{$last_changed}";
1884  
1885      // Check for cache and set if needed
1886      $child_ids = wp_cache_get( $cache_key, 'bbpress_posts' );
1887      if ( false === $child_ids ) {
1888  
1889          // Join post statuses to specifically exclude together
1890          $not_in      = array( 'draft', 'future' );
1891          $post_status = "'" . implode( "', '", $not_in ) . "'";
1892          $bbp_db      = bbp_db();
1893  
1894          // Note that we can't use WP_Query here thanks to post_status assumptions
1895          $query       = $bbp_db->prepare( "SELECT ID FROM {$bbp_db->posts} WHERE post_parent = %d AND post_status NOT IN ( {$post_status} ) AND post_type = %s ORDER BY ID DESC", $parent_id, $post_type );
1896          $child_ids   = (array) $bbp_db->get_col( $query );
1897  
1898          // Always cache the results
1899          wp_cache_set( $cache_key, $child_ids, 'bbpress_posts' );
1900      }
1901  
1902      // Make sure results are INTs
1903      $child_ids = wp_parse_id_list( $child_ids );
1904  
1905      // Filter & return
1906      return (array) apply_filters( 'bbp_get_all_child_ids', $child_ids, $parent_id, $post_type );
1907  }
1908  
1909  /**
1910   * Prime familial post caches.
1911   *
1912   * This function uses _prime_post_caches() to prepare the object cache for
1913   * imminent requests to post objects that aren't naturally cached by the primary
1914   * WP_Query calls themselves. Post author caches are also primed.
1915   *
1916   * This is triggered when a `update_post_family_cache` argument is set to true.
1917   *
1918   * Also see: bbp_update_post_author_caches()
1919   *
1920   * @since 2.6.0 bbPress (r6699)
1921   *
1922   * @param array $objects Array of objects, fresh from a query
1923   *
1924   * @return bool True if some IDs were cached
1925   */
1926  function bbp_update_post_family_caches( $objects = array() ) {
1927  
1928      // Bail if no posts
1929      if ( empty( $objects ) ) {
1930          return false;
1931      }
1932  
1933      // Default value
1934      $post_ids = array();
1935  
1936      // Filter the types of IDs to prime
1937      $ids = apply_filters( 'bbp_update_post_family_caches', array(
1938          '_bbp_last_active_id',
1939          '_bbp_last_reply_id',
1940          '_bbp_last_topic_id',
1941          '_bbp_reply_to'
1942      ), $objects );
1943  
1944      // Get the last active IDs
1945      foreach ( $objects as $object ) {
1946          $object = get_post( $object );
1947  
1948          // Skip if post ID is empty.
1949          if ( empty( $object->ID ) ) {
1950              continue;
1951          }
1952  
1953          // Meta IDs
1954          foreach ( $ids as $key ) {
1955              $post_ids[] = get_post_meta( $object->ID, $key, true );
1956          }
1957  
1958          // This post ID is already cached, but the post author may not be
1959          $post_ids[] = $object->ID;
1960      }
1961  
1962      // Unique, non-zero values
1963      $post_ids = bbp_get_unique_array_values( $post_ids );
1964  
1965      // Bail if no IDs to prime
1966      if ( empty( $post_ids ) ) {
1967          return false;
1968      }
1969  
1970      // Prime post caches
1971      _prime_post_caches( $post_ids, true, true );
1972  
1973      // Prime post author caches
1974      bbp_update_post_author_caches( $post_ids );
1975  
1976      // Return
1977      return true;
1978  }
1979  
1980  /**
1981   * Prime post author caches.
1982   *
1983   * This function uses cache_users() to prepare the object cache for
1984   * imminent requests to user objects that aren't naturally cached by the primary
1985   * WP_Query calls themselves.
1986   *
1987   * This is triggered when a `update_post_author_cache` argument is set to true.
1988   *
1989   * @since 2.6.0 bbPress (r6699)
1990   *
1991   * @param array $objects Array of objects, fresh from a query
1992   *
1993   * @return bool True if some IDs were cached
1994   */
1995  function bbp_update_post_author_caches( $objects = array() ) {
1996  
1997      // Bail if no posts
1998      if ( empty( $objects ) ) {
1999          return false;
2000      }
2001  
2002      // Default value
2003      $user_ids = array();
2004  
2005      // Get the user IDs (could use wp_list_pluck() if this is ever a bottleneck)
2006      foreach ( $objects as $object ) {
2007          $object = get_post( $object );
2008  
2009          // Skip if post does not have an author ID.
2010          if ( empty( $object->post_author ) ) {
2011              continue;
2012          }
2013  
2014          // If post exists, add post author to the array.
2015          $user_ids[] = (int) $object->post_author;
2016      }
2017  
2018      // Unique, non-zero values
2019      $user_ids = bbp_get_unique_array_values( $user_ids );
2020  
2021      // Bail if no IDs to prime
2022      if ( empty( $user_ids ) ) {
2023          return false;
2024      }
2025  
2026      // Try to prime user caches
2027      cache_users( $user_ids );
2028  
2029      // Return
2030      return true;
2031  }
2032  
2033  /** Globals *******************************************************************/
2034  
2035  /**
2036   * Get the unfiltered value of a global $post's key
2037   *
2038   * Used most frequently when editing a forum/topic/reply
2039   *
2040   * @since 2.1.0 bbPress (r3694)
2041   *
2042   * @param string $field Name of the key
2043   * @param string $context How to sanitize - raw|edit|db|display|attribute|js
2044   * @return string Field value
2045   */
2046  function bbp_get_global_post_field( $field = 'ID', $context = 'edit' ) {
2047  
2048      // Get the post, and maybe get a field from it
2049      $post   = get_post();
2050      $retval = isset( $post->{$field} )
2051          ? sanitize_post_field( $field, $post->{$field}, $post->ID, $context )
2052          : '';
2053  
2054      // Filter & return
2055      return apply_filters( 'bbp_get_global_post_field', $retval, $post, $field, $context );
2056  }
2057  
2058  /** Nonces ********************************************************************/
2059  
2060  /**
2061   * Makes sure the user requested an action from another page on this site.
2062   *
2063   * To avoid security exploits within the theme.
2064   *
2065   * @since 2.1.0 bbPress (r4022)
2066   *
2067   * @param string $action Action nonce
2068   * @param string $query_arg where to look for nonce in $_REQUEST
2069   */
2070  function bbp_verify_nonce_request( $action = '', $query_arg = '_wpnonce' ) {
2071  
2072      /** Home URL **************************************************************/
2073  
2074      // Parse home_url() into pieces to remove query-strings, strange characters,
2075      // and other funny things that plugins might to do to it.
2076      $parsed_home = parse_url( home_url( '/', ( is_ssl() ? 'https' : 'http' ) ) );
2077  
2078      // Maybe include the port, if it's included
2079      if ( isset( $parsed_home['port'] ) ) {
2080          $parsed_host = $parsed_home['host'] . ':' . $parsed_home['port'];
2081      } else {
2082          $parsed_host = $parsed_home['host'];
2083      }
2084  
2085      // Set the home URL for use in comparisons
2086      $home_url = trim( strtolower( $parsed_home['scheme'] . '://' . $parsed_host . $parsed_home['path'] ), '/' );
2087  
2088      /** Requested URL *********************************************************/
2089  
2090      // Maybe include the port, if it's included in home_url()
2091      if ( isset( $parsed_home['port'] ) && false === strpos( $_SERVER['HTTP_HOST'], ':' ) ) {
2092          $request_host = $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'];
2093      } else {
2094          $request_host = $_SERVER['HTTP_HOST'];
2095      }
2096  
2097      // Build the currently requested URL
2098      $scheme        = bbp_get_url_scheme();
2099      $requested_url = strtolower( $scheme . $request_host . $_SERVER['REQUEST_URI'] );
2100  
2101      /** Look for match ********************************************************/
2102  
2103      /**
2104       * Filters the requested URL being nonce-verified.
2105       *
2106       * Useful for configurations like reverse proxying.
2107       *
2108       * @since 2.2.0 bbPress (r4361)
2109       *
2110       * @param string $requested_url The requested URL.
2111       */
2112      $matched_url = apply_filters( 'bbp_verify_nonce_request_url', $requested_url );
2113  
2114      // Check the nonce
2115      $result = isset( $_REQUEST[ $query_arg ] )
2116          ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action )
2117          : false;
2118  
2119      // Nonce check failed
2120      if ( empty( $result ) || empty( $action ) || ( strpos( $matched_url, $home_url ) !== 0 ) ) {
2121          $result = false;
2122      }
2123  
2124      /**
2125       * Fires at the end of the nonce verification check.
2126       *
2127       * @since 2.1.0 bbPress (r4023)
2128       *
2129       * @param string $action Action nonce.
2130       * @param bool   $result Boolean result of nonce verification.
2131       */
2132      do_action( 'bbp_verify_nonce_request', $action, $result );
2133  
2134      return $result;
2135  }
2136  
2137  /** Feeds *********************************************************************/
2138  
2139  /**
2140   * This function is hooked into the WordPress 'request' action and is
2141   * responsible for sniffing out the query vars and serving up RSS2 feeds if
2142   * the stars align and the user has requested a feed of any bbPress type.
2143   *
2144   * @since 2.0.0 bbPress (r3171)
2145   *
2146   * @param array $query_vars
2147   * @return array
2148   */
2149  function bbp_request_feed_trap( $query_vars = array() ) {
2150  
2151      // Looking at a feed
2152      if ( isset( $query_vars['feed'] ) ) {
2153  
2154          // Forum/Topic/Reply Feed
2155          if ( isset( $query_vars['post_type'] ) ) {
2156  
2157              // Matched post type
2158              $post_type = false;
2159  
2160              // Post types to check
2161              $post_types = array(
2162                  bbp_get_forum_post_type(),
2163                  bbp_get_topic_post_type(),
2164                  bbp_get_reply_post_type()
2165              );
2166  
2167              // Cast query vars as array outside of foreach loop
2168              $qv_array = (array) $query_vars['post_type'];
2169  
2170              // Check if this query is for a bbPress post type
2171              foreach ( $post_types as $bbp_pt ) {
2172                  if ( in_array( $bbp_pt, $qv_array, true ) ) {
2173                      $post_type = $bbp_pt;
2174                      break;
2175                  }
2176              }
2177  
2178              // Looking at a bbPress post type
2179              if ( ! empty( $post_type ) ) {
2180  
2181                  // Supported select query vars
2182                  $select_query_vars = array(
2183                      'p'        => false,
2184                      'name'     => false,
2185                      $post_type => false,
2186                  );
2187  
2188                  // Setup matched variables to select
2189                  foreach ( $query_vars as $key => $value ) {
2190                      if ( isset( $select_query_vars[ $key ] ) ) {
2191                          $select_query_vars[ $key ] = $value;
2192                      }
2193                  }
2194  
2195                  // Remove any empties
2196                  $select_query_vars = array_filter( $select_query_vars );
2197  
2198                  // What bbPress post type are we looking for feeds on?
2199                  switch ( $post_type ) {
2200  
2201                      // Forum
2202                      case bbp_get_forum_post_type() :
2203  
2204                          // Define local variable(s)
2205                          $meta_query = array();
2206  
2207                          // Single forum
2208                          if ( ! empty( $select_query_vars ) ) {
2209  
2210                              // Load up our own query
2211                              query_posts( array_merge( array(
2212                                  'post_type' => bbp_get_forum_post_type(),
2213                                  'feed'      => true
2214                              ), $select_query_vars ) );
2215  
2216                              // Restrict to specific forum ID
2217                              $meta_query = array( array(
2218                                  'key'     => '_bbp_forum_id',
2219                                  'value'   => bbp_get_forum_id(),
2220                                  'type'    => 'NUMERIC',
2221                                  'compare' => '='
2222                              ) );
2223                          }
2224  
2225                          // Only forum replies
2226                          if ( ! empty( $_GET['type'] ) && ( bbp_get_reply_post_type() === $_GET['type'] ) ) {
2227  
2228                              // The query
2229                              $the_query = array(
2230                                  'author'         => 0,
2231                                  'feed'           => true,
2232                                  'post_type'      => bbp_get_reply_post_type(),
2233                                  'post_parent'    => 'any',
2234                                  'post_status'    => bbp_get_public_reply_statuses(),
2235                                  'posts_per_page' => bbp_get_replies_per_rss_page(),
2236                                  'order'          => 'DESC',
2237                                  'meta_query'     => $meta_query
2238                              );
2239  
2240                              // Output the feed
2241                              bbp_display_replies_feed_rss2( $the_query );
2242  
2243                          // Only forum topics
2244                          } elseif ( ! empty( $_GET['type'] ) && ( bbp_get_topic_post_type() === $_GET['type'] ) ) {
2245  
2246                              // The query
2247                              $the_query = array(
2248                                  'author'         => 0,
2249                                  'feed'           => true,
2250                                  'post_type'      => bbp_get_topic_post_type(),
2251                                  'post_parent'    => bbp_get_forum_id(),
2252                                  'post_status'    => bbp_get_public_topic_statuses(),
2253                                  'posts_per_page' => bbp_get_topics_per_rss_page(),
2254                                  'order'          => 'DESC'
2255                              );
2256  
2257                              // Output the feed
2258                              bbp_display_topics_feed_rss2( $the_query );
2259  
2260                          // All forum topics and replies
2261                          } else {
2262  
2263                              // Exclude private/hidden forums if not looking at single
2264                              if ( empty( $select_query_vars ) ) {
2265                                  $meta_query = array( bbp_exclude_forum_ids( 'meta_query' ) );
2266                              }
2267  
2268                              // The query
2269                              $the_query = array(
2270                                  'author'         => 0,
2271                                  'feed'           => true,
2272                                  'post_type'      => array( bbp_get_reply_post_type(), bbp_get_topic_post_type() ),
2273                                  'post_parent'    => 'any',
2274                                  'post_status'    => bbp_get_public_topic_statuses(),
2275                                  'posts_per_page' => bbp_get_replies_per_rss_page(),
2276                                  'order'          => 'DESC',
2277                                  'meta_query'     => $meta_query
2278                              );
2279  
2280                              // Output the feed
2281                              bbp_display_replies_feed_rss2( $the_query );
2282                          }
2283  
2284                          break;
2285  
2286                      // Topic feed - Show replies
2287                      case bbp_get_topic_post_type() :
2288  
2289                          // Single topic
2290                          if ( ! empty( $select_query_vars ) ) {
2291  
2292                              // Load up our own query
2293                              query_posts( array_merge( array(
2294                                  'post_type' => bbp_get_topic_post_type(),
2295                                  'feed'      => true
2296                              ), $select_query_vars ) );
2297  
2298                              // Output the feed
2299                              bbp_display_replies_feed_rss2( array( 'feed' => true ) );
2300  
2301                          // All topics
2302                          } else {
2303  
2304                              // The query
2305                              $the_query = array(
2306                                  'author'         => 0,
2307                                  'feed'           => true,
2308                                  'post_parent'    => 'any',
2309                                  'posts_per_page' => bbp_get_topics_per_rss_page(),
2310                                  'show_stickies'  => false
2311                              );
2312  
2313                              // Output the feed
2314                              bbp_display_topics_feed_rss2( $the_query );
2315                          }
2316  
2317                          break;
2318  
2319                      // Replies
2320                      case bbp_get_reply_post_type() :
2321  
2322                          // The query
2323                          $the_query = array(
2324                              'posts_per_page' => bbp_get_replies_per_rss_page(),
2325                              'meta_query'     => array( array( ) ),
2326                              'feed'           => true
2327                          );
2328  
2329                          // All replies
2330                          if ( empty( $select_query_vars ) ) {
2331                              bbp_display_replies_feed_rss2( $the_query );
2332                          }
2333  
2334                          break;
2335                  }
2336              }
2337  
2338          // Single Topic Vview
2339          } elseif ( isset( $query_vars[ bbp_get_view_rewrite_id() ] ) ) {
2340  
2341              // Get the view
2342              $view = $query_vars[ bbp_get_view_rewrite_id() ];
2343  
2344              // We have a view to display a feed
2345              if ( ! empty( $view ) ) {
2346  
2347                  // Get the view query
2348                  $the_query = bbp_get_view_query_args( $view );
2349  
2350                  // Output the feed
2351                  bbp_display_topics_feed_rss2( $the_query );
2352              }
2353          }
2354  
2355          // @todo User profile feeds
2356      }
2357  
2358      // No feed so continue on
2359      return $query_vars;
2360  }
2361  
2362  /** Templates ******************************************************************/
2363  
2364  /**
2365   * Used to guess if page exists at requested path
2366   *
2367   * @since 2.0.0 bbPress (r3304)
2368   *
2369   * @param string $path
2370   * @return mixed False if no page, Page object if true
2371   */
2372  function bbp_get_page_by_path( $path = '' ) {
2373  
2374      // Default to false
2375      $retval = false;
2376  
2377      // Path is not empty
2378      if ( ! empty( $path ) ) {
2379  
2380          // Pretty permalinks are on so path might exist
2381          if ( get_option( 'permalink_structure' ) ) {
2382              $retval = get_page_by_path( $path );
2383          }
2384      }
2385  
2386      // Filter & return
2387      return apply_filters( 'bbp_get_page_by_path', $retval, $path );
2388  }
2389  
2390  /**
2391   * Sets the 404 status.
2392   *
2393   * Used primarily with topics/replies inside hidden forums.
2394   *
2395   * @since 2.0.0 bbPress (r3051)
2396   * @since 2.6.0 bbPress (r6583) Use status_header() & nocache_headers()
2397   *
2398   * @param WP_Query $query  The query being checked
2399   *
2400   * @return bool Always returns true
2401   */
2402  function bbp_set_404( $query = null ) {
2403  
2404      // Global fallback
2405      if ( empty( $query ) ) {
2406          $query = bbp_get_wp_query();
2407      }
2408  
2409      // Setup environment
2410      $query->set_404();
2411  
2412      // Setup request
2413      status_header( 404 );
2414      nocache_headers();
2415  }
2416  
2417  /**
2418   * Sets the 200 status header.
2419   *
2420   * @since 2.6.0 bbPress (r6583)
2421   */
2422  function bbp_set_200() {
2423      status_header( 200 );
2424  }
2425  
2426  /**
2427   * Maybe handle the default 404 handling for some bbPress conditions
2428   *
2429   * Some conditions (like private/hidden forums and edits) have their own checks
2430   * on `bbp_template_redirect` and are not currently 404s.
2431   *
2432   * @since 2.6.0 bbPress (r6555)
2433   *
2434   * @param bool $override Whether to override the default handler
2435   * @param WP_Query $wp_query The posts query being referenced
2436   *
2437   * @return bool False to leave alone, true to override
2438   */
2439  function bbp_pre_handle_404( $override = false, $wp_query = false ) {
2440  
2441      // Handle a bbPress 404 condition
2442      if ( isset( $wp_query->bbp_is_404 ) ) {
2443  
2444          // Either force a 404 when 200, or a 200 when 404
2445          $override = ( true === $wp_query->bbp_is_404 )
2446              ? bbp_set_404( $wp_query )
2447              : bbp_set_200();
2448      }
2449  
2450      // Return, maybe overridden
2451      return $override;
2452  }
2453  
2454  /**
2455   * Maybe pre-assign the posts that are returned from a WP_Query.
2456   *
2457   * This effectively short-circuits the default query for posts, which is
2458   * currently only used to avoid calling the main query when it's not necessary.
2459   *
2460   * @since 2.6.0 bbPress (r6580)
2461   *
2462   * @param mixed $posts Default null. Array of posts (possibly empty)
2463   * @param WP_Query $wp_query
2464   *
2465   * @return mixed Null if no override. Array if overridden.
2466   */
2467  function bbp_posts_pre_query( $posts = null, $wp_query = false ) {
2468  
2469      // Custom 404 handler is set, so set posts to empty array to avoid 2 queries
2470      if ( ! empty( $wp_query->bbp_is_404 ) ) {
2471          $posts = array();
2472      }
2473  
2474      // Return, maybe overridden
2475      return $posts;
2476  }
2477  
2478  /**
2479   * Get scheme for a URL based on is_ssl() results.
2480   *
2481   * @since 2.6.0 bbPress (r6759)
2482   *
2483   * @return string https:// if is_ssl(), otherwise http://
2484   */
2485  function bbp_get_url_scheme() {
2486      return is_ssl()
2487          ? 'https://'
2488          : 'http://';
2489  }
2490  
2491  /** Titles ********************************************************************/
2492  
2493  /**
2494   * Is a title longer that the maximum title length?
2495   *
2496   * Uses mb_strlen() in `8bit` mode to treat strings as raw. This matches the
2497   * behavior present in Comments, PHPMailer, RandomCompat, and others.
2498   *
2499   * @since 2.6.0 bbPress (r6783)
2500   *
2501   * @param string $title
2502   * @return bool
2503   */
2504  function bbp_is_title_too_long( $title = '' ) {
2505      $max    = bbp_get_title_max_length();
2506      $len    = mb_strlen( $title, '8bit' );
2507      $result = ( $len > $max );
2508  
2509      // Filter & return
2510      return (bool) apply_filters( 'bbp_is_title_too_long', $result, $title, $max, $len );
2511  }


Generated: Tue Jul 16 01:01:32 2019 Cross-referenced by PHPXref 0.7.1