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