MediaWiki master
ApiQueryRandom.php
Go to the documentation of this file.
1<?php
2
24namespace MediaWiki\Api;
25
29
36
37 public function __construct( ApiQuery $query, string $moduleName ) {
38 parent::__construct( $query, $moduleName, 'rn' );
39 }
40
41 public function execute() {
42 $this->run();
43 }
44
45 public function executeGenerator( $resultPageSet ) {
46 $this->run( $resultPageSet );
47 }
48
58 protected function runQuery( $resultPageSet, $limit, $start, $startId, $end ) {
60
61 $this->resetQueryParams();
62 $this->addTables( 'page' );
63 $this->addFields( [ 'page_id', 'page_random' ] );
64 if ( $resultPageSet === null ) {
65 $this->addFields( [ 'page_title', 'page_namespace' ] );
66 } else {
67 $this->addFields( $resultPageSet->getPageTableFields() );
68 }
69 $this->addWhereFld( 'page_namespace', $params['namespace'] );
70 if ( $params['redirect'] || $params['filterredir'] === 'redirects' ) {
71 $this->addWhereFld( 'page_is_redirect', 1 );
72 } elseif ( $params['filterredir'] === 'nonredirects' ) {
73 $this->addWhereFld( 'page_is_redirect', 0 );
74 } elseif ( $resultPageSet === null ) {
75 $this->addFields( [ 'page_is_redirect' ] );
76 }
77 $this->addOption( 'LIMIT', $limit + 1 );
78
79 if ( $start !== null ) {
80 $db = $this->getDB();
81 if ( $startId > 0 ) {
82 $this->addWhere( $db->buildComparison( '>=', [
83 'page_random' => $start,
84 'page_id' => $startId,
85 ] ) );
86 } else {
87 $this->addWhere( $db->buildComparison( '>=', [
88 'page_random' => $start,
89 ] ) );
90 }
91 }
92 if ( $end !== null ) {
93 $this->addWhere( $this->getDB()->expr( 'page_random', '<', $end ) );
94 }
95 $this->addOption( 'ORDER BY', [ 'page_random', 'page_id' ] );
96
97 $result = $this->getResult();
98 $path = [ 'query', $this->getModuleName() ];
99
100 $res = $this->select( __METHOD__ );
101
102 if ( $resultPageSet === null ) {
103 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
104 }
105
106 $count = 0;
107 foreach ( $res as $row ) {
108 if ( $count++ >= $limit ) {
109 return [ 0, "{$row->page_random}|{$row->page_id}" ];
110 }
111 if ( $resultPageSet === null ) {
112 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
113 $page = [
114 'id' => (int)$row->page_id,
115 ];
116 ApiQueryBase::addTitleInfo( $page, $title );
117 if ( isset( $row->page_is_redirect ) ) {
118 $page['redirect'] = (bool)$row->page_is_redirect;
119 }
120 $fit = $result->addValue( $path, null, $page );
121 if ( !$fit ) {
122 return [ 0, "{$row->page_random}|{$row->page_id}" ];
123 }
124 } else {
125 $resultPageSet->processDbRow( $row );
126 }
127 }
128
129 return [ $limit - $count, null ];
130 }
131
135 public function run( $resultPageSet = null ) {
136 $params = $this->extractRequestParams();
137
138 // Since 'filterredir" will always be set in $params, we have to dig
139 // into the WebRequest to see if it was actually passed.
140 $request = $this->getMain()->getRequest();
141 if ( $request->getCheck( $this->encodeParamName( 'filterredir' ) ) ) {
142 $this->requireMaxOneParameter( $params, 'filterredir', 'redirect' );
143 }
144
145 if ( isset( $params['continue'] ) ) {
146 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string', 'int', 'string' ] );
147 $rand = $cont[0];
148 $start = $cont[1];
149 $startId = $cont[2];
150 $end = $cont[3] ? $rand : null;
151 $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $rand ) );
152 $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $start ) );
153 $this->dieContinueUsageIf( $cont[3] !== '0' && $cont[3] !== '1' );
154 } else {
155 $rand = wfRandom();
156 $start = $rand;
157 $startId = 0;
158 $end = null;
159 }
160
161 // Set the non-continue if this is being used as a generator
162 // (as a list it doesn't matter because lists never non-continue)
163 if ( $resultPageSet !== null ) {
164 $endFlag = $end === null ? 0 : 1;
165 $this->getContinuationManager()->addGeneratorNonContinueParam(
166 $this, 'continue', "$rand|$start|$startId|$endFlag"
167 );
168 }
169
170 [ $left, $continue ] =
171 $this->runQuery( $resultPageSet, $params['limit'], $start, $startId, $end );
172 if ( $end === null && $continue === null ) {
173 // Wrap around. We do this even if $left === 0 for continuation
174 // (saving a DB query in this rare case probably isn't worth the
175 // added code complexity it would require).
176 $end = $rand;
177 [ , $continue ] = $this->runQuery( $resultPageSet, $left, null, null, $end );
178 }
179
180 if ( $continue !== null ) {
181 $endFlag = $end === null ? 0 : 1;
182 $this->setContinueEnumParameter( 'continue', "$rand|$continue|$endFlag" );
183 }
184
185 if ( $resultPageSet === null ) {
186 $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
187 }
188 }
189
190 public function getCacheMode( $params ) {
191 return 'public';
192 }
193
194 public function getAllowedParams() {
195 return [
196 'namespace' => [
197 ParamValidator::PARAM_TYPE => 'namespace',
198 ParamValidator::PARAM_ISMULTI => true
199 ],
200 'filterredir' => [
201 ParamValidator::PARAM_TYPE => [ 'all', 'redirects', 'nonredirects' ],
202 ParamValidator::PARAM_DEFAULT => 'nonredirects', // for BC
203 ],
204 'redirect' => [
205 ParamValidator::PARAM_DEPRECATED => true,
206 ParamValidator::PARAM_DEFAULT => false,
207 ],
208 'limit' => [
209 ParamValidator::PARAM_TYPE => 'limit',
210 ParamValidator::PARAM_DEFAULT => 1,
211 IntegerDef::PARAM_MIN => 1,
212 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
213 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
214 ],
215 'continue' => [
216 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue'
217 ],
218 ];
219 }
220
221 protected function getExamplesMessages() {
222 return [
223 'action=query&list=random&rnnamespace=0&rnlimit=2'
224 => 'apihelp-query+random-example-simple',
225 'action=query&generator=random&grnnamespace=0&grnlimit=2&prop=info'
226 => 'apihelp-query+random-example-generator',
227 ];
228 }
229
230 public function getHelpUrls() {
231 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Random';
232 }
233}
234
236class_alias( ApiQueryRandom::class, 'ApiQueryRandom' );
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
array $params
The job parameters.
run()
Run the job.
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:571
getMain()
Get the main module.
Definition ApiBase.php:589
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1807
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1768
getResult()
Get the result object.
Definition ApiBase.php:710
requireMaxOneParameter( $params,... $required)
Dies if more than one parameter from a certain set of parameters are set and not false.
Definition ApiBase.php:1025
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:184
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:251
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:851
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:249
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
getDB()
Get the Query database connection (read-only)
select( $method, $extraQuery=[], ?array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
resetQueryParams()
Blank the internal arrays with query parameters.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addFields( $value)
Add a set of fields to select to the internal array.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
Query module to get list of random pages.
__construct(ApiQuery $query, string $moduleName)
getExamplesMessages()
Returns usage examples for this module.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
runQuery( $resultPageSet, $limit, $start, $startId, $end)
Actually perform the query and add pages to the result.
executeGenerator( $resultPageSet)
Execute this module as a generator.
getHelpUrls()
Return links to more detailed help pages about the module.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getCacheMode( $params)
Get the cache mode for the data generated by this module.
run( $resultPageSet=null)
This is the main query class.
Definition ApiQuery.php:48
Represents a title within MediaWiki.
Definition Title.php:78
Service for formatting and validating API parameters.
Type definition for integer types.