Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.09% covered (warning)
84.09%
74 / 88
66.67% covered (warning)
66.67%
8 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialRandomPage
84.09% covered (warning)
84.09%
74 / 88
66.67% covered (warning)
66.67%
8 / 12
33.62
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getNamespaces
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setNamespace
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 isValidNS
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isRedirect
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
78.95% covered (warning)
78.95%
15 / 19
0.00% covered (danger)
0.00%
0 / 1
5.23
 parsePar
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 getNsList
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 getRandomTitle
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
4.07
 getQueryInfo
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
2
 selectRandomPageFromDB
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Specials;
8
9use MediaWiki\SpecialPage\SpecialPage;
10use MediaWiki\Title\NamespaceInfo;
11use MediaWiki\Title\Title;
12use Wikimedia\Rdbms\IConnectionProvider;
13
14/**
15 * Redirect to a random page
16 *
17 * @ingroup SpecialPage
18 * @author Rob Church <robchur@gmail.com>, Ilmari Karonen
19 */
20class SpecialRandomPage extends SpecialPage {
21    /** @var int[] namespaces to select pages from */
22    private $namespaces;
23    /** @var bool should the result be a redirect? */
24    protected $isRedir = false;
25    /** @var array Extra SQL statements */
26    protected $extra = [];
27
28    public function __construct(
29        private readonly IConnectionProvider $dbProvider,
30        NamespaceInfo $nsInfo,
31    ) {
32        parent::__construct( 'Randompage' );
33        $this->namespaces = $nsInfo->getContentNamespaces();
34    }
35
36    /**
37     * @return int[]
38     */
39    public function getNamespaces() {
40        return $this->namespaces;
41    }
42
43    /**
44     * @param int|false $ns
45     */
46    public function setNamespace( $ns ) {
47        if ( !$this->isValidNS( $ns ) ) {
48            $ns = NS_MAIN;
49        }
50        $this->namespaces = [ $ns ];
51    }
52
53    /**
54     * @param int|false $ns
55     */
56    private function isValidNS( $ns ): bool {
57        return $ns !== false && $ns >= 0;
58    }
59
60    /**
61     * select redirects instead of normal pages?
62     * @return bool
63     */
64    public function isRedirect() {
65        return $this->isRedir;
66    }
67
68    /** @inheritDoc */
69    public function execute( $par ) {
70        // T419273: Disallow most non-view actions, to make writing malicious user scripts harder.
71        $action = $this->getRequest()->getVal( 'action' );
72        $allowedActions = [ 'view', 'edit', 'history' ];
73        if ( $action && !in_array( $action, $allowedActions, true ) ) {
74            $this->setHeaders();
75            $this->getOutput()->addHTML(
76                $this->msg( 'randompage-disallowed-action' )->params( $action )->escaped()
77            );
78            return;
79        }
80
81        $this->parsePar( $par );
82
83        $title = $this->getRandomTitle();
84
85        if ( $title === null ) {
86            $this->setHeaders();
87            // Message: randompage-nopages, randomredirect-nopages
88            $this->getOutput()->addWikiMsg( strtolower( $this->getName() ) . '-nopages',
89                $this->getNsList(), count( $this->namespaces ) );
90            return;
91        }
92
93        $redirectParam = $this->isRedirect() ? [ 'redirect' => 'no' ] : [];
94        $query = array_merge( $this->getRequest()->getQueryValues(), $redirectParam );
95        unset( $query['title'] );
96        $this->getOutput()->redirect( $title->getFullURL( $query ) );
97    }
98
99    /**
100     * Parse the subpage parameter that specifies namespaces
101     *
102     * @param string $par Subpage to special page
103     */
104    private function parsePar( $par ) {
105        // Testing for stringiness since we want to catch
106        // the empty string to mean main namespace only.
107        if ( is_string( $par ) ) {
108            $ns = $this->getContentLanguage()->getNsIndex( $par );
109            if ( $ns === false && str_contains( $par, ',' ) ) {
110                $nsList = [];
111                // Comma separated list
112                $parSplit = explode( ',', $par );
113                foreach ( $parSplit as $potentialNs ) {
114                    $ns = $this->getContentLanguage()->getNsIndex( $potentialNs );
115                    if ( $this->isValidNS( $ns ) ) {
116                        $nsList[] = $ns;
117                    }
118                    // Remove duplicate values, and re-index array
119                    $nsList = array_unique( $nsList );
120                    $nsList = array_values( $nsList );
121                    if ( $nsList !== [] ) {
122                        $this->namespaces = $nsList;
123                    }
124                }
125            } else {
126                // Note, that the case of $par being something
127                // like "main" which is not a namespace, falls
128                // through to here, and sets NS_MAIN, allowing
129                // Special:Random/main or Special:Random/article
130                // to work as expected.
131                $this->setNamespace( $this->getContentLanguage()->getNsIndex( $par ) );
132            }
133        }
134    }
135
136    /**
137     * Get a comma-delimited list of namespaces we don't have
138     * any pages in
139     * @return string
140     */
141    private function getNsList() {
142        $contLang = $this->getContentLanguage();
143        $nsNames = [];
144        foreach ( $this->namespaces as $n ) {
145            if ( $n === NS_MAIN ) {
146                $nsNames[] = $this->msg( 'blanknamespace' )->plain();
147            } else {
148                $nsNames[] = $contLang->getNsText( $n );
149            }
150        }
151
152        return $contLang->commaList( $nsNames );
153    }
154
155    /**
156     * Choose a random title.
157     * @return Title|null Title object (or null if nothing to choose from)
158     */
159    public function getRandomTitle() {
160        $randstr = wfRandom();
161        $title = null;
162
163        if ( !$this->getHookRunner()->onSpecialRandomGetRandomTitle(
164            $randstr, $this->isRedir, $this->namespaces,
165            // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
166            $this->extra, $title )
167        ) {
168            return $title;
169        }
170
171        $row = $this->selectRandomPageFromDB( $randstr, __METHOD__ );
172
173        /* If we picked a value that was higher than any in
174         * the DB, wrap around and select the page with the
175         * lowest value instead!  One might think this would
176         * skew the distribution, but in fact it won't cause
177         * any more bias than what the page_random scheme
178         * causes anyway.  Trust me, I'm a mathematician. :)
179         */
180        if ( !$row ) {
181            $row = $this->selectRandomPageFromDB( 0, __METHOD__ );
182        }
183
184        if ( $row ) {
185            return Title::makeTitleSafe( $row->page_namespace, $row->page_title );
186        }
187
188        return null;
189    }
190
191    /**
192     * @param string $randstr
193     * @return array
194     */
195    protected function getQueryInfo( $randstr ) {
196        $dbr = $this->dbProvider->getReplicaDatabase();
197        $redirect = $this->isRedirect() ? 1 : 0;
198        $tables = [ 'page' ];
199        $conds = [
200            'page_namespace' => $this->namespaces,
201            'page_is_redirect' => $redirect,
202            $dbr->expr( 'page_random', '>=', $randstr ),
203            ...$this->extra,
204        ];
205        $joinConds = [];
206
207        // Allow extensions to modify the query
208        $this->getHookRunner()->onRandomPageQuery( $tables, $conds, $joinConds );
209
210        return [
211            'tables' => $tables,
212            'fields' => [ 'page_title', 'page_namespace' ],
213            'conds' => $conds,
214            'options' => [
215                'ORDER BY' => 'page_random',
216                'LIMIT' => 1,
217            ],
218            'join_conds' => $joinConds
219        ];
220    }
221
222    /**
223     * @param int|string $randstr
224     * @param string $fname
225     * @return \stdClass|false
226     */
227    private function selectRandomPageFromDB( $randstr, string $fname ) {
228        $dbr = $this->dbProvider->getReplicaDatabase();
229
230        $query = $this->getQueryInfo( $randstr );
231        return $dbr->newSelectQueryBuilder()
232            ->queryInfo( $query )
233            ->caller( $fname )
234            ->fetchRow();
235    }
236
237    /** @inheritDoc */
238    protected function getGroupName() {
239        return 'redirects';
240    }
241}
242
243// @codeCoverageIgnoreStart
244/**
245 * Retain the old class name for backwards compatibility.
246 * @deprecated since 1.41
247 */
248class_alias( SpecialRandomPage::class, 'SpecialRandomPage' );
249// @codeCoverageIgnoreEnd