MediaWiki REL1_39
ApiQueryRandom.php
Go to the documentation of this file.
1<?php
2
26
33
38 public function __construct( ApiQuery $query, $moduleName ) {
39 parent::__construct( $query, $moduleName, 'rn' );
40 }
41
42 public function execute() {
43 $this->run();
44 }
45
46 public function executeGenerator( $resultPageSet ) {
47 $this->run( $resultPageSet );
48 }
49
59 protected function runQuery( $resultPageSet, $limit, $start, $startId, $end ) {
60 $params = $this->extractRequestParams();
61
62 $this->resetQueryParams();
63 $this->addTables( 'page' );
64 $this->addFields( [ 'page_id', 'page_random' ] );
65 if ( $resultPageSet === null ) {
66 $this->addFields( [ 'page_title', 'page_namespace' ] );
67 } else {
68 $this->addFields( $resultPageSet->getPageTableFields() );
69 }
70 $this->addWhereFld( 'page_namespace', $params['namespace'] );
71 if ( $params['redirect'] || $params['filterredir'] === 'redirects' ) {
72 $this->addWhereFld( 'page_is_redirect', 1 );
73 } elseif ( $params['filterredir'] === 'nonredirects' ) {
74 $this->addWhereFld( 'page_is_redirect', 0 );
75 } elseif ( $resultPageSet === null ) {
76 $this->addFields( [ 'page_is_redirect' ] );
77 }
78 $this->addOption( 'LIMIT', $limit + 1 );
79
80 if ( $start !== null ) {
81 $start = $this->getDB()->addQuotes( $start );
82 if ( $startId > 0 ) {
83 $startId = (int)$startId; // safety
84 $this->addWhere( "page_random = $start AND page_id >= $startId OR page_random > $start" );
85 } else {
86 $this->addWhere( "page_random >= $start" );
87 }
88 }
89 if ( $end !== null ) {
90 $this->addWhere( 'page_random < ' . $this->getDB()->addQuotes( $end ) );
91 }
92 $this->addOption( 'ORDER BY', [ 'page_random', 'page_id' ] );
93
94 $result = $this->getResult();
95 $path = [ 'query', $this->getModuleName() ];
96
97 $res = $this->select( __METHOD__ );
98
99 if ( $resultPageSet === null ) {
100 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
101 }
102
103 $count = 0;
104 foreach ( $res as $row ) {
105 if ( $count++ >= $limit ) {
106 return [ 0, "{$row->page_random}|{$row->page_id}" ];
107 }
108 if ( $resultPageSet === null ) {
109 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
110 $page = [
111 'id' => (int)$row->page_id,
112 ];
114 if ( isset( $row->page_is_redirect ) ) {
115 $page['redirect'] = (bool)$row->page_is_redirect;
116 }
117 $fit = $result->addValue( $path, null, $page );
118 if ( !$fit ) {
119 return [ 0, "{$row->page_random}|{$row->page_id}" ];
120 }
121 } else {
122 $resultPageSet->processDbRow( $row );
123 }
124 }
125
126 return [ $limit - $count, null ];
127 }
128
132 public function run( $resultPageSet = null ) {
133 $params = $this->extractRequestParams();
134
135 // Since 'filterredir" will always be set in $params, we have to dig
136 // into the WebRequest to see if it was actually passed.
137 $request = $this->getMain()->getRequest();
138 if ( $request->getCheck( $this->encodeParamName( 'filterredir' ) ) ) {
139 $this->requireMaxOneParameter( $params, 'filterredir', 'redirect' );
140 }
141
142 if ( isset( $params['continue'] ) ) {
143 $cont = explode( '|', $params['continue'] );
144 $this->dieContinueUsageIf( count( $cont ) != 4 );
145 $rand = $cont[0];
146 $start = $cont[1];
147 $startId = (int)$cont[2];
148 $end = $cont[3] ? $rand : null;
149 $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $rand ) );
150 $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $start ) );
151 $this->dieContinueUsageIf( $cont[2] !== (string)$startId );
152 $this->dieContinueUsageIf( $cont[3] !== '0' && $cont[3] !== '1' );
153 } else {
154 $rand = wfRandom();
155 $start = $rand;
156 $startId = 0;
157 $end = null;
158 }
159
160 // Set the non-continue if this is being used as a generator
161 // (as a list it doesn't matter because lists never non-continue)
162 if ( $resultPageSet !== null ) {
163 $endFlag = $end === null ? 0 : 1;
164 $this->getContinuationManager()->addGeneratorNonContinueParam(
165 $this, 'continue', "$rand|$start|$startId|$endFlag"
166 );
167 }
168
169 list( $left, $continue ) =
170 $this->runQuery( $resultPageSet, $params['limit'], $start, $startId, $end );
171 if ( $end === null && $continue === null ) {
172 // Wrap around. We do this even if $left === 0 for continuation
173 // (saving a DB query in this rare case probably isn't worth the
174 // added code complexity it would require).
175 $end = $rand;
176 list( $left, $continue ) = $this->runQuery( $resultPageSet, $left, null, null, $end );
177 }
178
179 if ( $continue !== null ) {
180 $endFlag = $end === null ? 0 : 1;
181 $this->setContinueEnumParameter( 'continue', "$rand|$continue|$endFlag" );
182 }
183
184 if ( $resultPageSet === null ) {
185 $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
186 }
187 }
188
189 public function getCacheMode( $params ) {
190 return 'public';
191 }
192
193 public function getAllowedParams() {
194 return [
195 'namespace' => [
196 ParamValidator::PARAM_TYPE => 'namespace',
197 ParamValidator::PARAM_ISMULTI => true
198 ],
199 'filterredir' => [
200 ParamValidator::PARAM_TYPE => [ 'all', 'redirects', 'nonredirects' ],
201 ParamValidator::PARAM_DEFAULT => 'nonredirects', // for BC
202 ],
203 'redirect' => [
204 ParamValidator::PARAM_DEPRECATED => true,
205 ParamValidator::PARAM_DEFAULT => false,
206 ],
207 'limit' => [
208 ParamValidator::PARAM_TYPE => 'limit',
209 ParamValidator::PARAM_DEFAULT => 1,
210 IntegerDef::PARAM_MIN => 1,
211 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
212 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
213 ],
214 'continue' => [
215 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue'
216 ],
217 ];
218 }
219
220 protected function getExamplesMessages() {
221 return [
222 'action=query&list=random&rnnamespace=0&rnlimit=2'
223 => 'apihelp-query+random-example-simple',
224 'action=query&generator=random&grnnamespace=0&grnlimit=2&prop=info'
225 => 'apihelp-query+random-example-generator',
226 ];
227 }
228
229 public function getHelpUrls() {
230 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Random';
231 }
232}
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:1643
getMain()
Get the main module.
Definition ApiBase.php:514
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:221
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:938
getResult()
Get the result object.
Definition ApiBase.php:629
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:765
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:163
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:223
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:498
getContinuationManager()
Definition ApiBase.php:663
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:41
Service for formatting and validating API parameters.
Type definition for integer types.
return true
Definition router.php:92