enabled() ) { $vars[] = self::QUERY_VAR; } return $vars; } /** * Redirect a cloaked link to its review's affiliate URL, before the main * query runs. Unknown slugs get the normal 404 page. * * @param WP $wp Current request. * @return void */ public function handle_request( $wp ) { if ( empty( $wp->query_vars[ self::QUERY_VAR ] ) ) { return; } $review_id = self::find_review( $wp->query_vars[ self::QUERY_VAR ] ); $target = $review_id ? self::get_target( $review_id ) : ''; if ( ! $target ) { $wp->query_vars = array( 'error' => '404' ); return; } if ( $this->should_count_click( $review_id ) ) { self::record_click( $review_id ); } // A cached redirect never reaches PHP, so it would stop counting clicks. nocache_headers(); header( 'X-Robots-Tag: noindex, nofollow' ); wp_redirect( $target, (int) apply_filters( 'affreviews_link_redirect_status', 307, $review_id ), 'Affiliate Reviews' ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- The target is an external affiliate link. exit; } /** * The published review that owns a link slug. * * @param string $slug Link slug. * @param string $status Post status to match, 'any' for all but trash. * @param int $exclude Review to leave out. * @return int Review ID, 0 when none. */ public static function find_review( $slug, $status = 'publish', $exclude = 0 ) { $slug = sanitize_title( $slug ); if ( '' === $slug ) { return 0; } $ids = get_posts( array( 'post_type' => AFFREVIEWS_CPT, 'post_status' => $status, 'posts_per_page' => 1, 'fields' => 'ids', 'no_found_rows' => true, 'post__not_in' => $exclude ? array( (int) $exclude ) : array(), 'meta_key' => self::SLUG_META, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => $slug, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value ) ); return $ids ? (int) $ids[0] : 0; } /** * A review's affiliate link, if it is a web URL. * * @param int $review_id Review. * @return string */ public static function get_target( $review_id ) { $target = (string) get_post_meta( $review_id, 'affreviews_afflink', true ); return in_array( wp_parse_url( $target, PHP_URL_SCHEME ), array( 'http', 'https' ), true ) ? $target : ''; } /** * A slug no other review uses, made unique the way post slugs are (-2, -3…). * * @param string $slug Requested slug. * @param int $post_id Review the slug is for. * @return string Empty when the slug is empty. */ public static function unique_slug( $slug, $post_id ) { $slug = sanitize_title( $slug ); if ( '' === $slug ) { return ''; } $base = $slug; $suffix = 1; while ( self::find_review( $slug, 'any', $post_id ) ) { ++$suffix; $slug = $base . '-' . $suffix; } return $slug; } /** * Keep link slugs unique after a block editor save. The REST response is * built after this runs, so the panel shows the slug that was stored. * * @param WP_Post $post Saved review. * @return void */ public function dedupe_saved_slug( $post ) { $slug = (string) get_post_meta( $post->ID, self::SLUG_META, true ); if ( '' === $slug ) { return; } $unique = self::unique_slug( $slug, $post->ID ); if ( $unique !== $slug ) { update_post_meta( $post->ID, self::SLUG_META, $unique ); } } /** * Keep link slugs unique however they are saved. The Custom Fields * endpoints and XML-RPC skip the checks of the block editor and the * classic screen, and a second review with the same slug would take over * the first one's link. * * @param int $meta_id Meta ID. * @param int $post_id Post ID. * @param string $meta_key Meta key. * @param mixed $meta_value Saved value. * @return void */ public function dedupe_slug_meta( $meta_id, $post_id, $meta_key, $meta_value ) { if ( self::SLUG_META !== $meta_key || ! is_string( $meta_value ) || '' === $meta_value ) { return; } $unique = self::unique_slug( $meta_value, $post_id ); if ( $unique !== $meta_value ) { update_post_meta( $post_id, self::SLUG_META, $unique ); } } /** * Whether this request is a click worth counting: not a bot, a prefetch * or someone editing the site. * * @param int $review_id Review being clicked. * @return bool */ public function should_count_click( $review_id ) { $agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET'; $purpose = isset( $_SERVER['HTTP_SEC_PURPOSE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_SEC_PURPOSE'] ) ) : ( isset( $_SERVER['HTTP_PURPOSE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_PURPOSE'] ) ) : '' ); $bots = apply_filters( 'affreviews_link_bot_pattern', '/bot|crawl|spider|slurp|facebookexternalhit|embedly|preview|lighthouse|headless|curl|wget|python|java\/|go-http|okhttp/i' ); $count = 'GET' === $method && '' !== $agent && ! preg_match( $bots, $agent ) && false === stripos( $purpose, 'prefetch' ) && ! current_user_can( 'edit_posts' ); return (bool) apply_filters( 'affreviews_link_count_click', $count, $review_id ); } /** * Clicks table name. * * @return string */ public static function table() { global $wpdb; return $wpdb->prefix . 'affreviews_clicks'; } /** * Create the clicks table: one row per review per day, no visitor data. * * @return void */ public static function maybe_create_table() { if ( self::DB_VERSION === get_option( 'affreviews_clicks_db_version' ) ) { return; } global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( 'CREATE TABLE ' . self::table() . ' ( review_id bigint(20) unsigned NOT NULL, click_date date NOT NULL, clicks int(10) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (review_id,click_date) ) ' . $wpdb->get_charset_collate() . ';' ); update_option( 'affreviews_clicks_db_version', self::DB_VERSION ); } /** * Add one click to today's count for a review. * * @param int $review_id Review. * @return void */ public static function record_click( $review_id ) { global $wpdb; self::maybe_create_table(); $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table named from $wpdb->prefix; counters must not be cached. $wpdb->query( $wpdb->prepare( "INSERT INTO {$table} (review_id, click_date, clicks) VALUES (%d, %s, 1) ON DUPLICATE KEY UPDATE clicks = clicks + 1", $review_id, current_time( 'Y-m-d' ) ) ); do_action( 'affreviews_link_clicked', $review_id ); } /** * Click totals for reviews: all time and the last 30 days. * * @param int[] $review_ids Reviews. * @return array review ID => array( 'total' => int, 'recent' => int ) */ public static function get_click_counts( $review_ids ) { global $wpdb; $review_ids = array_filter( array_map( 'intval', (array) $review_ids ) ); if ( ! $review_ids || self::DB_VERSION !== get_option( 'affreviews_clicks_db_version' ) ) { return array(); } $since = gmdate( 'Y-m-d', strtotime( current_time( 'Y-m-d' ) . ' -29 days' ) ); $table = self::table(); $in = implode( ',', array_fill( 0, count( $review_ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table named from $wpdb->prefix; $in holds one %d per ID. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT review_id, SUM(clicks) AS total, SUM(IF(click_date >= %s, clicks, 0)) AS recent FROM {$table} WHERE review_id IN ({$in}) GROUP BY review_id", $since, ...array_values( $review_ids ) ) ); $counts = array(); foreach ( $rows as $row ) { $counts[ (int) $row->review_id ] = array( 'total' => (int) $row->total, 'recent' => (int) $row->recent, ); } return $counts; } /** * Remove a deleted review's clicks. * * @param int $post_id Deleted post. * @return void */ public function delete_clicks( $post_id ) { global $wpdb; if ( AFFREVIEWS_CPT !== get_post_type( $post_id ) || self::DB_VERSION !== get_option( 'affreviews_clicks_db_version' ) ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete( self::table(), array( 'review_id' => (int) $post_id ), array( '%d' ) ); } /** * Rebuild the rewrite rules and create the clicks table when cloaking is * turned on or off, or its prefix may have changed (the reviews slug * affects it too). * * @param mixed $old_value Previous General settings. * @param mixed $value New General settings. * @return void */ public function settings_updated( $old_value, $value ) { $old = is_array( $old_value ) ? $old_value : array(); $new = is_array( $value ) ? $value : array(); $was_enabled = ! empty( $old['link_cloaking'] ); $enabled = ! empty( $new['link_cloaking'] ); if ( ! $was_enabled && ! $enabled ) { return; } $changed = $was_enabled !== $enabled; foreach ( array( 'link_prefix', 'reviews_slug', 'reviews_visibility' ) as $key ) { $changed = $changed || ( $old[ $key ] ?? '' ) !== ( $new[ $key ] ?? '' ); } if ( ! $changed ) { return; } // Rebuilt on the next request, once the rule reflects the new settings. delete_option( 'rewrite_rules' ); if ( $enabled ) { self::maybe_create_table(); } } /** * Same as settings_updated() for a site saving its General settings the * first time. * * @param string $option Option name. * @param mixed $value General settings. * @return void */ public function settings_added( $option, $value ) { $this->settings_updated( array(), $value ); } /** * Add the "Link" column to the reviews list. * * @param array $columns List columns. * @return array */ public function add_list_column( $columns ) { if ( ! $this->enabled() ) { return $columns; } $out = array(); foreach ( $columns as $key => $label ) { $out[ $key ] = $label; if ( 'title' === $key ) { $out['affreviews_link'] = __( 'Affiliate link', 'affiliate-reviews' ); } } return $out; } /** * The "Link" column: cloaked URL and click counts. * * @param string $column Column key. * @param int $post_id Review. * @return void */ public function render_list_column( $column, $post_id ) { static $counts = null; if ( 'affreviews_link' !== $column ) { return; } $slug = (string) get_post_meta( $post_id, self::SLUG_META, true ); if ( '' === $slug ) { echo '' . esc_html__( 'Not cloaked', 'affiliate-reviews' ) . ''; return; } if ( null === $counts ) { global $wp_query; $counts = self::get_click_counts( wp_list_pluck( (array) $wp_query->posts, 'ID' ) ); } $url = affreviews_get_cloaked_url( $slug ); $clicks = $counts[ $post_id ] ?? array( 'total' => 0, 'recent' => 0, ); printf( '%s
', esc_html( wp_make_link_relative( $url ) ) ); printf( /* translators: 1: clicks in the last 30 days. 2: clicks in total. */ esc_html__( '%1$s clicks (30 days) · %2$s total', 'affiliate-reviews' ), esc_html( number_format_i18n( $clicks['recent'] ) ), esc_html( number_format_i18n( $clicks['total'] ) ) ); } }