| 1 | <?php |
| 2 | |
| 3 | namespace WordPressdotorg\Forums; |
| 4 | |
| 5 | class Topic_NSFW { |
| 6 | const FIELD_NAME = 'wporg_bbp_topic_nsfw'; |
| 7 | const META = '_wporg_bbp_topic_nsfw'; |
| 8 | |
| 9 | public function __construct() { |
| 10 | add_filter( 'bbp_get_topic_title', array( $this, 'add_nsfw_label' ), 10, 2 ); |
| 11 | |
| 12 | add_action( 'bbp_theme_before_topic_form_subscriptions', array( $this, 'display_nsfw_checkbox' ), 15 ); |
| 13 | |
| 14 | add_action( 'bbp_new_topic_post_extras', array( $this, 'update_nsfw_status' ) ); |
| 15 | add_action( 'bbp_edit_topic_post_extras', array( $this, 'update_nsfw_status' ) ); |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Adds the NSFW label to the topic title. |
| 20 | * |
| 21 | * @param string $title The topic title. |
| 22 | * @param int $topic_id The topic ID. |
| 23 | * @return string The topic title with/without the NSFW label. |
| 24 | */ |
| 25 | public function add_nsfw_label( $title, $topic_id ) { |
| 26 | // Don't run in the admin. |
| 27 | if ( is_admin() ) { |
| 28 | return $title; |
| 29 | } |
| 30 | |
| 31 | // Don't run when viewing a topic edit page or a reply edit page. |
| 32 | if ( bbp_is_topic_edit() || bbp_is_reply_edit() ) { |
| 33 | return $title; |
| 34 | } |
| 35 | |
| 36 | if ( $this->is_nsfw_topic( $topic_id ) ) { |
| 37 | $title = sprintf( |
| 38 | '<abbr title="%s">%s</abbr> ', |
| 39 | esc_attr__( 'Not safe for work', 'wporg-forums' ), |
| 40 | esc_html__( '[NSFW]', 'wporg-forums' ) |
| 41 | ) . $title; |
| 42 | } |
| 43 | |
| 44 | return $title; |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Outputs the topic NSFW label checkbox. |
| 49 | */ |
| 50 | public function display_nsfw_checkbox() { |
| 51 | $is_nsfw = $this->is_nsfw_topic(); |
| 52 | ?> |
| 53 | <p> |
| 54 | <label for="<?php echo esc_attr( self::FIELD_NAME ); ?>"> |
| 55 | <input type="checkbox" name="<?php echo esc_attr( self::FIELD_NAME ); ?>" id="<?php echo esc_attr( self::FIELD_NAME ); ?>" value="yes"<?php checked( $is_nsfw, 'yes' ); ?>> |
| 56 | <?php esc_html_e( 'My site or content may be considered Not Safe for Work (NSFW)', 'wporg-forums' ); ?> |
| 57 | </label> |
| 58 | </p> |
| 59 | <?php |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Adds or deletes the NSFW label. |
| 64 | * |
| 65 | * @param int $topic_id The topic ID. |
| 66 | */ |
| 67 | public function update_nsfw_status( $topic_id ) { |
| 68 | if ( isset( $_POST[ self::FIELD_NAME ] ) ) { |
| 69 | update_post_meta( $topic_id, self::META, 'yes' ); |
| 70 | } else { |
| 71 | delete_post_meta( $topic_id, self::META ); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Checks if the topic is tagged with the NSFW label. |
| 77 | * |
| 78 | * @return string "yes" if the topic has NSFW label or empty otherwise. |
| 79 | */ |
| 80 | public function is_nsfw_topic() { |
| 81 | return get_post_meta( get_the_ID(), self::META, true ); |
| 82 | } |
| 83 | } |