Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 136
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryRandom
0.00% covered (danger)
0.00%
0 / 135
0.00% covered (danger)
0.00%
0 / 9
1406
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 executeGenerator
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 runQuery
0.00% covered (danger)
0.00%
0 / 56
0.00% covered (danger)
0.00%
0 / 1
342
 run
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
156
 getCacheMode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
2
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3/**
4 * Copyright © 2008 Brent Garber
5 *
6 * @license GPL-2.0-or-later
7 * @file
8 */
9
10namespace MediaWiki\Api;
11
12use MediaWiki\Content\ContentHandlerFactory;
13use MediaWiki\Title\Title;
14use Wikimedia\ParamValidator\ParamValidator;
15use Wikimedia\ParamValidator\TypeDef\IntegerDef;
16
17/**
18 * Query module to get list of random pages
19 *
20 * @ingroup API
21 */
22class ApiQueryRandom extends ApiQueryGeneratorBase {
23
24    private ContentHandlerFactory $contentHandlerFactory;
25
26    public function __construct(
27        ApiQuery $query,
28        string $moduleName,
29        ContentHandlerFactory $contentHandlerFactory
30    ) {
31        parent::__construct( $query, $moduleName, 'rn' );
32        $this->contentHandlerFactory = $contentHandlerFactory;
33    }
34
35    public function execute() {
36        $this->run();
37    }
38
39    /** @inheritDoc */
40    public function executeGenerator( $resultPageSet ) {
41        $this->run( $resultPageSet );
42    }
43
44    /**
45     * Actually perform the query and add pages to the result.
46     * @param ApiPageSet|null $resultPageSet
47     * @param int $limit Number of pages to fetch
48     * @param string|null $start Starting page_random
49     * @param int|null $startId Starting page_id
50     * @param string|null $end Ending page_random
51     * @return array (int, string|null) Number of pages left to query and continuation string
52     */
53    protected function runQuery( $resultPageSet, $limit, $start, $startId, $end ) {
54        $params = $this->extractRequestParams();
55
56        $this->resetQueryParams();
57        $this->addTables( 'page' );
58        $this->addFields( [ 'page_id', 'page_random' ] );
59        if ( $resultPageSet === null ) {
60            $this->addFields( [ 'page_title', 'page_namespace' ] );
61        } else {
62            $this->addFields( $resultPageSet->getPageTableFields() );
63        }
64        $this->addWhereFld( 'page_namespace', $params['namespace'] );
65        if ( $params['redirect'] || $params['filterredir'] === 'redirects' ) {
66            $this->addWhereFld( 'page_is_redirect', 1 );
67        } elseif ( $params['filterredir'] === 'nonredirects' ) {
68            $this->addWhereFld( 'page_is_redirect', 0 );
69        } elseif ( $resultPageSet === null ) {
70            $this->addFields( [ 'page_is_redirect' ] );
71        }
72
73        $db = $this->getDB();
74        if ( isset( $params['minsize'] ) ) {
75            $this->addWhere( $db->expr( 'page_len', '>=', (int)$params['minsize'] ) );
76        }
77        if ( isset( $params['maxsize'] ) ) {
78            $this->addWhere( $db->expr( 'page_len', '<=', (int)$params['maxsize'] ) );
79        }
80
81        if ( isset( $params['contentmodel'] ) ) {
82            $this->addWhereFld( 'page_content_model', $params['contentmodel'] );
83        }
84
85        $this->addOption( 'LIMIT', $limit + 1 );
86
87        if ( $start !== null ) {
88            if ( $startId > 0 ) {
89                $this->addWhere( $db->buildComparison( '>=', [
90                    'page_random' => $start,
91                    'page_id' => $startId,
92                ] ) );
93            } else {
94                $this->addWhere( $db->buildComparison( '>=', [
95                    'page_random' => $start,
96                ] ) );
97            }
98        }
99        if ( $end !== null ) {
100            $this->addWhere( $db->expr( 'page_random', '<', $end ) );
101        }
102        $this->addOption( 'ORDER BY', [ 'page_random', 'page_id' ] );
103
104        $result = $this->getResult();
105        $path = [ 'query', $this->getModuleName() ];
106
107        $res = $this->select( __METHOD__ );
108
109        if ( $resultPageSet === null ) {
110            $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
111        }
112
113        $count = 0;
114        foreach ( $res as $row ) {
115            if ( $count++ >= $limit ) {
116                return [ 0, "{$row->page_random}|{$row->page_id}" ];
117            }
118            if ( $resultPageSet === null ) {
119                $title = Title::makeTitle( $row->page_namespace, $row->page_title );
120                $page = [
121                    'id' => (int)$row->page_id,
122                ];
123                ApiQueryBase::addTitleInfo( $page, $title );
124                if ( isset( $row->page_is_redirect ) ) {
125                    $page['redirect'] = (bool)$row->page_is_redirect;
126                }
127                $fit = $result->addValue( $path, null, $page );
128                if ( !$fit ) {
129                    return [ 0, "{$row->page_random}|{$row->page_id}" ];
130                }
131            } else {
132                $resultPageSet->processDbRow( $row );
133            }
134        }
135
136        return [ $limit - $count, null ];
137    }
138
139    /**
140     * @param ApiPageSet|null $resultPageSet
141     */
142    public function run( $resultPageSet = null ) {
143        $params = $this->extractRequestParams();
144
145        // Since 'filterredir' will always be set in $params, we have to dig
146        // into the WebRequest to see if it was actually passed.
147        $request = $this->getMain()->getRequest();
148        if ( $request->getCheck( $this->encodeParamName( 'filterredir' ) ) ) {
149            $this->requireMaxOneParameter( $params, 'filterredir', 'redirect' );
150        }
151
152        if ( isset( $params['continue'] ) ) {
153            $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string', 'int', 'string' ] );
154            $rand = $cont[0];
155            $start = $cont[1];
156            $startId = $cont[2];
157            $end = $cont[3] ? $rand : null;
158            $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $rand ) );
159            $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $start ) );
160            $this->dieContinueUsageIf( $cont[3] !== '0' && $cont[3] !== '1' );
161        } else {
162            $rand = wfRandom();
163            $start = $rand;
164            $startId = 0;
165            $end = null;
166        }
167
168        // Set the non-continue if this is being used as a generator
169        // (as a list it doesn't matter because lists never non-continue)
170        if ( $resultPageSet !== null ) {
171            $endFlag = $end === null ? 0 : 1;
172            $this->getContinuationManager()->addGeneratorNonContinueParam(
173                $this, 'continue', "$rand|$start|$startId|$endFlag"
174            );
175        }
176
177        [ $left, $continue ] =
178            $this->runQuery( $resultPageSet, $params['limit'], $start, $startId, $end );
179        if ( $end === null && $continue === null ) {
180            // Wrap around. We do this even if $left === 0 for continuation
181            // (saving a DB query in this rare case probably isn't worth the
182            // added code complexity it would require).
183            $end = $rand;
184            [ , $continue ] = $this->runQuery( $resultPageSet, $left, null, null, $end );
185        }
186
187        if ( $continue !== null ) {
188            $endFlag = $end === null ? 0 : 1;
189            $this->setContinueEnumParameter( 'continue', "$rand|$continue|$endFlag" );
190        }
191
192        if ( $resultPageSet === null ) {
193            $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
194        }
195    }
196
197    /** @inheritDoc */
198    public function getCacheMode( $params ) {
199        return 'public';
200    }
201
202    /** @inheritDoc */
203    public function getAllowedParams() {
204        return [
205            'namespace' => [
206                ParamValidator::PARAM_TYPE => 'namespace',
207                ParamValidator::PARAM_ISMULTI => true
208            ],
209            'filterredir' => [
210                ParamValidator::PARAM_TYPE => [ 'all', 'redirects', 'nonredirects' ],
211                ParamValidator::PARAM_DEFAULT => 'nonredirects', // for BC
212            ],
213            'minsize' => [
214                ParamValidator::PARAM_TYPE => 'integer',
215            ],
216            'maxsize' => [
217                ParamValidator::PARAM_TYPE => 'integer',
218            ],
219            'contentmodel' => [
220                ParamValidator::PARAM_TYPE => $this->contentHandlerFactory->getContentModels(),
221            ],
222            'redirect' => [
223                ParamValidator::PARAM_DEPRECATED => true,
224                ParamValidator::PARAM_DEFAULT => false,
225            ],
226            'limit' => [
227                ParamValidator::PARAM_TYPE => 'limit',
228                ParamValidator::PARAM_DEFAULT => 1,
229                IntegerDef::PARAM_MIN => 1,
230                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
231                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
232            ],
233            'continue' => [
234                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue'
235            ],
236        ];
237    }
238
239    /** @inheritDoc */
240    protected function getExamplesMessages() {
241        return [
242            'action=query&list=random&rnnamespace=0&rnlimit=2'
243                => 'apihelp-query+random-example-simple',
244            'action=query&generator=random&grnnamespace=0&grnlimit=2&prop=info'
245                => 'apihelp-query+random-example-generator',
246            'action=query&list=random&rnnamespace=0&rnlimit=1&minsize=500'
247                => 'apihelp-query+random-example-minsize',
248        ];
249    }
250
251    /** @inheritDoc */
252    public function getHelpUrls() {
253        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Random';
254    }
255}
256
257/** @deprecated class alias since 1.43 */
258class_alias( ApiQueryRandom::class, 'ApiQueryRandom' );