BP_REST_Topics_Endpoint::create_item( WP_REST_Request $request )

Create a topic.

Description

Parameters

$request

(Required) Full details about the request.

Return

(WP_REST_Response) | WP_Error

Source

File: bp-forums/classes/class-bp-rest-topics-endpoint.php

	public function create_item( $request ) {
		$request->set_param( 'context', 'edit' );

		$topic = $this->prepare_topic_for_database( $request );

		// Define local variable(s).
		$forum_id       = 0;
		$topic_author   = 0;
		$anonymous_data = 0;
		$topic_title    = '';
		$topic_content  = '';
		$terms          = array( bbp_get_topic_tag_tax_id() => array() );

		/** Topic Author */
		if ( bbp_is_anonymous() ) {

			$anonymous_args = array(
				'bbp_anonymous_name'    => ! empty( $request['anonymous_name'] ) ? sanitize_text_field( $request['anonymous_name'] ) : '',
				'bbp_anonymous_email'   => ! empty( $request['anonymous_email'] ) ? sanitize_email( $request['anonymous_email'] ) : '',
				'bbp_anonymous_website' => ! empty( $request['anonymous_website'] ) ? sanitize_text_field( $request['anonymous_website'] ) : '',
			);

			// Filter anonymous data.
			$anonymous_data = bbp_filter_anonymous_post_data( $anonymous_args );

			// Anonymous data checks out, so set cookies, etc...
			if ( ! empty( $anonymous_data ) && is_array( $anonymous_data ) ) {
				bbp_set_current_anonymous_user_data( $anonymous_data );
			}

			// User is logged in.
		} else {

			// User cannot create topics.
			if ( ! current_user_can( 'publish_topics' ) ) {
				return new WP_Error(
					'bp_rest_bbp_topic_permissions',
					__( 'Sorry, You do not have permission to create new discussions.', 'buddyboss' ),
					array(
						'status' => rest_authorization_required_code(),
					)
				);
			}

			// Topic author is current user.
			$topic_author = bbp_get_current_user_id();
		}

		// Remove kses filters from title and content for capable users and if the nonce is verified.
		if ( current_user_can( 'unfiltered_html' ) ) {
			remove_filter( 'bbp_new_topic_pre_title', 'wp_filter_kses' );
			remove_filter( 'bbp_new_topic_pre_content', 'bbp_encode_bad', 10 );
		}

		/** Discussion Title */
		if ( ! empty( $topic->bbp_topic_title ) ) {
			$topic_title = esc_attr( wp_strip_all_tags( $topic->bbp_topic_title ) );
		}

		// Filter and sanitize.
		$topic_title = apply_filters( 'bbp_new_topic_pre_title', $topic_title );

		// No topic title.
		if ( empty( $topic_title ) ) {
			return new WP_Error(
				'bp_rest_bbp_topic_title',
				__( 'Sorry, Your discussion needs a subject.', 'buddyboss' ),
				array(
					'status' => 400,
				)
			);
		}

		/** Topic Content */
		if ( ! empty( $topic->bbp_topic_content ) ) {
			$topic_content = $topic->bbp_topic_content;
		}

		// Filter and sanitize.
		$topic_content = apply_filters( 'bbp_new_topic_pre_content', $topic_content );

		// No topic content.
		if (
			empty( $topic_content )
			&& empty( $request['bbp_media'] )
			&& empty( $request['bbp_media_gif'] )
		) {
			return new WP_Error(
				'bp_rest_bbp_topic_content',
				__( 'Sorry, Your discussion cannot be empty.', 'buddyboss' ),
				array(
					'status' => 400,
				)
			);
		}

		/** Topic Forum */
		// Error check the POST'ed topic id.
		if ( isset( $topic->bbp_forum_id ) ) {

			// Empty Forum id was passed.
			if ( empty( $topic->bbp_forum_id ) ) {
				return new WP_Error(
					'bp_rest_bbp_topic_forum_id',
					__( 'Sorry, Forum ID is missing.', 'buddyboss' ),
					array(
						'status' => 400,
					)
				);
				// Forum id is not a number.
			} elseif ( ! is_numeric( $topic->bbp_forum_id ) ) {
				return new WP_Error(
					'bp_rest_bbp_topic_forum_id',
					__( 'Sorry, Forum ID must be a number.', 'buddyboss' ),
					array(
						'status' => 400,
					)
				);

				// Forum id might be valid.
			} else {

				// Get the forum id.
				$posted_forum_id = intval( $topic->bbp_forum_id );

				// Forum id is empty.
				if ( 0 === $posted_forum_id ) {
					return new WP_Error(
						'bp_rest_bbp_topic_forum_id',
						__( 'Sorry, Forum ID is missing.', 'buddyboss' ),
						array(
							'status' => 400,
						)
					);

					// Forum id is a negative number.
				} elseif ( 0 > $posted_forum_id ) {
					return new WP_Error(
						'bp_rest_bbp_topic_forum_id',
						__( 'Sorry, Forum ID cannot be a negative number.', 'buddyboss' ),
						array(
							'status' => 400,
						)
					);

					// Forum does not exist.
				} elseif ( ! bbp_get_forum( $posted_forum_id ) ) {
					return new WP_Error(
						'bp_rest_bbp_topic_forum_id',
						__( 'Sorry, Forum does not exist.', 'buddyboss' ),
						array(
							'status' => 400,
						)
					);

					// Use the POST'ed forum id.
				} else {
					$forum_id = $posted_forum_id;
				}
			}
		}

		// Forum exists.
		if ( ! empty( $forum_id ) ) {

			// Forum is a category.
			if ( bbp_is_forum_category( $forum_id ) ) {
				return new WP_Error(
					'bp_rest_bbp_topic_forum_category',
					__( 'Sorry, This forum is a category. No discussions can be created in this forum.', 'buddyboss' ),
					array(
						'status' => 400,
					)
				);

				// Forum is not a category.
			} else {

				// Forum is closed and user cannot access.
				if ( bbp_is_forum_closed( $forum_id ) && ! current_user_can( 'edit_forum', $forum_id ) ) {
					return new WP_Error(
						'bp_rest_bbp_topic_forum_closed',
						__( 'Sorry, This forum has been closed to new discussions.', 'buddyboss' ),
						array(
							'status' => 400,
						)
					);
				}

				/**
				 * Added logic for group forum
				 * Current user is part of that group or not.
				 * We need to check manually because bbpress updating that caps only on group forum page and
				 * in API those conditional tag will not work.
				 */
				$is_member = false;
				$group_ids = array();
				if ( function_exists( 'bbp_get_forum_group_ids' ) ) {
					$group_ids = bbp_get_forum_group_ids( $forum_id );
					if ( ! empty( $group_ids ) ) {
						foreach ( $group_ids as $group_id ) {
							if ( groups_is_user_member( $topic_author, $group_id ) ) {
								$is_member = true;
								break;
							}
						}
					}
				}

				// Forum is private and user cannot access.
				if ( bbp_is_forum_private( $forum_id ) && ! bbp_is_user_keymaster() ) {
					if (
						( empty( $group_ids ) && ! current_user_can( 'read_private_forums' ) )
						|| ( ! empty( $group_ids ) && ! $is_member )
					) {
						return new WP_Error(
							'bp_rest_bbp_topic_forum_closed',
							__( 'Sorry, This forum is private and you do not have the capability to read or create new discussions in it.', 'buddyboss' ),
							array(
								'status' => 400,
							)
						);
					}

					// Forum is hidden and user cannot access.
				} elseif ( bbp_is_forum_hidden( $forum_id ) && ! bbp_is_user_keymaster() ) {
					if (
						( empty( $group_ids ) && ! current_user_can( 'read_hidden_forums' ) )
						|| ( ! empty( $group_ids ) && ! $is_member )
					) {
						return new WP_Error(
							'bp_rest_bbp_topic_forum_closed',
							__( 'Sorry, This forum is hidden and you do not have the capability to read or create new discussions in it.', 'buddyboss' ),
							array(
								'status' => 400,
							)
						);
					}
				}
			}
		}

		/** Topic Flooding */
		if ( ! bbp_check_for_flood( $anonymous_data, $topic_author ) ) {
			return new WP_Error(
				'bp_rest_bbp_topic_flood',
				__( 'Slow down; you move too fast.', 'buddyboss' ),
				array(
					'status' => 400,
				)
			);
		}

		/** Topic Duplicate */

		if ( ! bbp_check_for_duplicate(
			array(
				'post_type'      => bbp_get_topic_post_type(),
				'post_author'    => $topic_author,
				'post_content'   => $topic_content,
				'anonymous_data' => $anonymous_data,
			)
		) ) {
			return new WP_Error(
				'bp_rest_bbp_topic_duplicate',
				__( 'Duplicate discussion detected; it looks as though you\'ve already said that!', 'buddyboss' ),
				array(
					'status' => 400,
				)
			);
		}

		/** Topic Blacklist */
		if ( ! bbp_check_for_blacklist( $anonymous_data, $topic_author, $topic_title, $topic_content ) ) {
			return new WP_Error(
				'bp_rest_bbp_topic_blacklist',
				__( 'Sorry, Your discussion cannot be created at this time.', 'buddyboss' ),
				array(
					'status' => 400,
				)
			);
		}

		/** Topic Status */
		// Maybe put into moderation.
		if ( ! bbp_check_for_moderation( $anonymous_data, $topic_author, $topic_title, $topic_content ) ) {
			$topic_status = bbp_get_pending_status_id();

			// Check a whitelist of possible topic status ID's.
		} elseif ( ! empty( $topic->bbp_topic_status ) && in_array( $topic->bbp_topic_status, array_keys( bbp_get_topic_statuses() ), true ) ) {
			$topic_status = $topic->bbp_topic_status;

			// Default to published if nothing else.
		} else {
			$topic_status = bbp_get_public_status_id();
		}

		/** Topic Tags */
		if ( bbp_allow_topic_tags() && ! empty( $topic->bbp_topic_tags ) ) {

			// Escape tag input.
			$terms = esc_attr( wp_strip_all_tags( $topic->bbp_topic_tags ) );

			// Explode by comma.
			if ( strstr( $terms, ',' ) ) {
				$terms = explode( ',', $terms );
			}

			// Add topic tag ID as main key.
			$terms = array( bbp_get_topic_tag_tax_id() => $terms );
		}

		/** Additional Actions (Before Save) */
		do_action( 'bbp_new_topic_pre_extras', $forum_id );

		// Bail if errors.
		if ( bbp_has_errors() ) {
			return new WP_Error(
				'bp_rest_bbp_topic_unknown',
				__( 'Unknown error.', 'buddyboss' ),
				array(
					'status' => 400,
				)
			);
		}

		/** No Errors */
		// Add the content of the form to $topic_data as an array.
		// Just in time manipulation of topic data before being created.
		$topic_data = apply_filters(
			'bbp_new_topic_pre_insert',
			array(
				'post_author'    => $topic_author,
				'post_title'     => $topic_title,
				'post_content'   => $topic_content,
				'post_status'    => $topic_status,
				'post_parent'    => $forum_id,
				'post_type'      => bbp_get_topic_post_type(),
				'tax_input'      => $terms,
				'comment_status' => 'closed',
			)
		);

		// Insert topic.
		$topic_id = wp_insert_post( $topic_data );

		if ( empty( $topic_id ) || is_wp_error( $topic_id ) ) {
			$append_error = (
			( is_wp_error( $topic_id ) && $topic_id->get_error_message() )
				? __( 'The following problem(s) have been found with your topic: ', 'buddyboss' ) . $topic_id->get_error_message()
				: __( 'We are facing a problem to creating a topic.', 'buddyboss' )
			);

			return new WP_Error(
				'bp_rest_bbp_topic_error',
				$append_error,
				array(
					'status' => 400,
				)
			);
		}

		/** Trash Check */
		// If the forum is trash, or the topic_status is switched to.
		// trash, trash it properly.
		if (
			( bbp_get_trash_status_id() === get_post_field( 'post_status', $forum_id ) )
			|| ( bbp_get_trash_status_id() === $topic_data['post_status'] )
		) {

			// Trash the reply.
			wp_trash_post( $topic_id );
		}

		/** Spam Check */
		// If reply or topic are spam, officially spam this reply.
		if ( bbp_get_spam_status_id() === $topic_data['post_status'] ) {
			add_post_meta( $topic_id, '_bbp_spam_meta_status', bbp_get_public_status_id() );
		}

		/** Update counts, etc... */
		do_action( 'bbp_new_topic', $topic_id, $forum_id, $anonymous_data, $topic_author );

		/** Stickies */
		// Sticky check after 'bbp_new_topic' action so forum ID meta is set.
		if ( ! empty( $topic->bbp_stick_topic ) && in_array(
			$topic->bbp_stick_topic,
			array(
				'stick',
				'super',
				'unstick',
			),
			true
		) ) {

			// What's the caps?
			if ( current_user_can( 'moderate' ) ) {

				// What's the haps?
				switch ( $topic->bbp_stick_topic ) {

					// Sticky in this forum.
					case 'stick':
						bbp_stick_topic( $topic_id );
						break;

					// Super sticky in all forums.
					case 'super':
						bbp_stick_topic( $topic_id, true );
						break;

					// We can avoid this as it is a new topic.
					case 'unstick':
					default:
						break;
				}
			}
		}

		// Handle Subscription Checkbox.
		if ( bbp_is_subscriptions_active() ) {
			$author_id = bbp_get_user_id( 0, true, true );
			// Check if subscribed.
			$subscribed = bbp_is_user_subscribed( $author_id, $topic_id );

			// Subscribed and unsubscribing.
			if ( true === $subscribed && empty( $topic->bbp_topic_subscription ) ) {
				bbp_remove_user_subscription( $author_id, $topic_id );

				// Not subscribed and subscribing.
			} elseif ( false === $subscribed && ! empty( $topic->bbp_topic_subscription ) ) {
				bbp_add_user_subscription( $author_id, $topic_id );
			}
		}

		/** Additional Actions (After Save) */
		do_action( 'bbp_new_topic_post_extras', $topic_id );

		$topic         = get_post( $topic_id );
		$fields_update = $this->update_additional_fields_for_object( $topic, $request );

		if ( is_wp_error( $fields_update ) ) {
			return $fields_update;
		}

		$retval = $this->prepare_response_for_collection(
			$this->prepare_item_for_response( $topic, $request )
		);

		$response = rest_ensure_response( $retval );

		/**
		 * Fires after a topic is created and fetched via the REST API.
		 *
		 * @param array            $topic    Created topic.
		 * @param WP_REST_Response $response The response data.
		 * @param WP_REST_Request  $request  The request sent to the API.
		 *
		 * @since 0.1.0
		 */
		do_action( 'bp_rest_topic_create_item', $topic, $response, $request );

		return $response;
	}

Changelog

Changelog
Version Description
0.1.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.