Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
CRAP
n/a
0 / 0
jetpack_matt_random_redirect
n/a
0 / 0
n/a
0 / 0
24
1<?php
2/**
3 * Plugin Name: Random Redirect
4 * Plugin URI: https://wordpress.org/extend/plugins/random-redirect/
5 * Description: Allows you to create a link to yourblog.example.com/?random which will redirect someone to a random post on your blog, in a StumbleUpon-like fashion.
6 * Version: 1.2-wpcom
7 * Author: Matt Mullenweg
8 * Author URI: https://ma.tt/
9 * Text Domain: jetpack
10 *
11 * @package automattic/jetpack
12 */
13
14// phpcs:disable WordPress.Security.NonceVerification -- No changes to the site here, it just redirects.
15
16/*
17 * This module was removed from the plugin in 13.6 and restored in 16.1. In the meantime some themes
18 * and plugins started shipping their own copy of the function below, so only declare it when nothing
19 * else has, to avoid a fatal error. The declaration must stay inside this conditional: PHP binds
20 * unconditional top-level function declarations when the file is compiled, before any check could run.
21 */
22if ( ! function_exists( 'jetpack_matt_random_redirect' ) ) {
23    /**
24     * Redirects to a random post on the site.
25     *
26     * @deprecated $$next-version$$ WordPress 7.2 and later handle random content redirects in core, and Jetpack loads this only on older versions.
27     */
28    function jetpack_matt_random_redirect() {
29        /**
30         * Allows disabling the random redirect feature.
31         *
32         * @since 16.1
33         *
34         * @param bool $enabled Whether the random redirect feature is enabled. Default true.
35         */
36        if ( ! apply_filters( 'jetpack_random_redirect_enabled', true ) ) {
37            return;
38        }
39
40        // Verify that the Random Redirect plugin this code is from is not active
41        // See https://plugins.trac.wordpress.org/ticket/1898
42        if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
43            require_once ABSPATH . 'wp-admin/includes/plugin.php';
44            if ( is_plugin_active( 'random-redirect/random-redirect.php' ) ) {
45                return;
46            }
47        }
48
49        // Acceptable URL formats: /[...]/?random=[post type], /?random, /&random, /&random=1
50        if ( ! isset( $_GET['random'] ) && ! ( isset( $_SERVER['REQUEST_URI'] ) && in_array( strtolower( $_SERVER['REQUEST_URI'] ), array( '/&random', '/&random=1' ), true ) ) ) {
51            return;
52        }
53
54        // Ignore POST requests.
55        if ( ! empty( $_POST ) ) {
56            return;
57        }
58
59        // Persistent AppEngine abuse.  ORDER BY RAND is expensive.
60        if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && strstr( filter_var( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 'AppEngine-Google' ) ) {
61            wp_die( 'Please <a href="https://en.support.wordpress.com/contact/" rel="noopener noreferrer" target="_blank">contact support</a>' );
62        }
63
64        $where      = array(
65            "post_password = ''",
66            "post_status = 'publish'",
67        );
68        $where_args = array();
69
70        // Set default post type.
71        $post_type = get_post_type();
72
73        // Change the post type if the parameter is set.
74        if ( isset( $_GET['random_post_type'] ) && post_type_exists( sanitize_key( $_GET['random_post_type'] ) ) ) {
75            $post_type = sanitize_key( $_GET['random_post_type'] );
76        }
77
78        // Don't show a random page if 'page' isn't specified as the post type specifically.
79        if ( 'page' === $post_type && is_front_page() && ! isset( $_GET['random_post_type'] ) ) {
80            $post_type = 'post';
81        }
82
83        $where[]      = 'p.post_type = %s';
84        $where_args[] = $post_type;
85
86        // Set author name if we're on an author archive.
87        if ( is_author() ) {
88            $where[]      = 'post_author = %s';
89            $where_args[] = get_the_author_meta( 'ID' );
90        }
91
92        // Set default category type
93        if ( is_category() ) {
94            $category = get_the_category();
95            if ( isset( $category ) && ! empty( $category ) ) {
96                $random_cat_id = $category[0]->term_id;
97            }
98        }
99
100        // Set the category ID if the parameter is set.
101        if ( isset( $_GET['random_cat_id'] ) ) {
102            $random_cat_id = (int) $_GET['random_cat_id'];
103        }
104
105        global $wpdb;
106
107        $where = implode( ' AND ', $where );
108
109        // Pick a post via COUNT plus a random OFFSET rather than ORDER BY RAND(), which randomizes and sorts every candidate row on each request.
110        if ( isset( $random_cat_id ) ) {
111            $from_where = "FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = %s) INNER JOIN  $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE $where";
112            $query_args = array_merge( array( $random_cat_id ), $where_args );
113        } else {
114            $from_where = "FROM $wpdb->posts AS p WHERE $where";
115            $query_args = $where_args;
116        }
117
118        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
119        $post_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( DISTINCT p.ID ) $from_where", ...$query_args ) );
120
121        if ( $post_count < 1 ) {
122            return;
123        }
124
125        $query_args[] = wp_rand( 0, $post_count - 1 );
126        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
127        $random_id = $wpdb->get_var( $wpdb->prepare( "SELECT DISTINCT p.ID $from_where ORDER BY p.ID LIMIT 1 OFFSET %d", ...$query_args ) );
128
129        if ( ! $random_id ) {
130            return;
131        }
132
133        // @phan-suppress-next-line PhanTypeMismatchArgument
134        $permalink = get_permalink( $random_id );
135        wp_safe_redirect( $permalink );
136        exit( 0 );
137    }
138
139    add_action( 'template_redirect', 'jetpack_matt_random_redirect' );
140}