PluginProbe
bbPress / 2.6.6
bbPress v2.6.6
trunk 2.0 2.0-beta-1 2.0-beta-2b 2.0-beta-3 2.0-beta-3b 2.0-rc-2 2.0-rc-3 2.0-rc-4 2.0-rc-5 2.0.1 2.0.2 2.0.3 2.1 2.1-beta-1 2.1-rc1 2.1-rc2 2.1-rc3 2.1-rc4 2.1.1 2.1.2 2.1.3 2.2 2.2.1 2.2.2 All 71 releases
bbpress / includes / common / functions.php

functions.php in bbPress 2.6.6, at includes/common/functions.php

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