MediaWiki  master
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  $db = $this->getDB();
82  if ( $startId > 0 ) {
83  $this->addWhere( $db->buildComparison( '>=', [
84  'page_random' => $start,
85  'page_id' => $startId,
86  ] ) );
87  } else {
88  $this->addWhere( $db->buildComparison( '>=', [
89  'page_random' => $start,
90  ] ) );
91  }
92  }
93  if ( $end !== null ) {
94  $this->addWhere( 'page_random < ' . $this->getDB()->addQuotes( $end ) );
95  }
96  $this->addOption( 'ORDER BY', [ 'page_random', 'page_id' ] );
97 
98  $result = $this->getResult();
99  $path = [ 'query', $this->getModuleName() ];
100 
101  $res = $this->select( __METHOD__ );
102 
103  if ( $resultPageSet === null ) {
104  $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
105  }
106 
107  $count = 0;
108  foreach ( $res as $row ) {
109  if ( $count++ >= $limit ) {
110  return [ 0, "{$row->page_random}|{$row->page_id}" ];
111  }
112  if ( $resultPageSet === null ) {
113  $title = Title::makeTitle( $row->page_namespace, $row->page_title );
114  $page = [
115  'id' => (int)$row->page_id,
116  ];
118  if ( isset( $row->page_is_redirect ) ) {
119  $page['redirect'] = (bool)$row->page_is_redirect;
120  }
121  $fit = $result->addValue( $path, null, $page );
122  if ( !$fit ) {
123  return [ 0, "{$row->page_random}|{$row->page_id}" ];
124  }
125  } else {
126  $resultPageSet->processDbRow( $row );
127  }
128  }
129 
130  return [ $limit - $count, null ];
131  }
132 
136  public function run( $resultPageSet = null ) {
137  $params = $this->extractRequestParams();
138 
139  // Since 'filterredir" will always be set in $params, we have to dig
140  // into the WebRequest to see if it was actually passed.
141  $request = $this->getMain()->getRequest();
142  if ( $request->getCheck( $this->encodeParamName( 'filterredir' ) ) ) {
143  $this->requireMaxOneParameter( $params, 'filterredir', 'redirect' );
144  }
145 
146  if ( isset( $params['continue'] ) ) {
147  $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string', 'int', 'string' ] );
148  $rand = $cont[0];
149  $start = $cont[1];
150  $startId = $cont[2];
151  $end = $cont[3] ? $rand : null;
152  $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $rand ) );
153  $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $start ) );
154  $this->dieContinueUsageIf( $cont[3] !== '0' && $cont[3] !== '1' );
155  } else {
156  $rand = wfRandom();
157  $start = $rand;
158  $startId = 0;
159  $end = null;
160  }
161 
162  // Set the non-continue if this is being used as a generator
163  // (as a list it doesn't matter because lists never non-continue)
164  if ( $resultPageSet !== null ) {
165  $endFlag = $end === null ? 0 : 1;
166  $this->getContinuationManager()->addGeneratorNonContinueParam(
167  $this, 'continue', "$rand|$start|$startId|$endFlag"
168  );
169  }
170 
171  [ $left, $continue ] =
172  $this->runQuery( $resultPageSet, $params['limit'], $start, $startId, $end );
173  if ( $end === null && $continue === null ) {
174  // Wrap around. We do this even if $left === 0 for continuation
175  // (saving a DB query in this rare case probably isn't worth the
176  // added code complexity it would require).
177  $end = $rand;
178  [ , $continue ] = $this->runQuery( $resultPageSet, $left, null, null, $end );
179  }
180 
181  if ( $continue !== null ) {
182  $endFlag = $end === null ? 0 : 1;
183  $this->setContinueEnumParameter( 'continue', "$rand|$continue|$endFlag" );
184  }
185 
186  if ( $resultPageSet === null ) {
187  $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
188  }
189  }
190 
191  public function getCacheMode( $params ) {
192  return 'public';
193  }
194 
195  public function getAllowedParams() {
196  return [
197  'namespace' => [
198  ParamValidator::PARAM_TYPE => 'namespace',
199  ParamValidator::PARAM_ISMULTI => true
200  ],
201  'filterredir' => [
202  ParamValidator::PARAM_TYPE => [ 'all', 'redirects', 'nonredirects' ],
203  ParamValidator::PARAM_DEFAULT => 'nonredirects', // for BC
204  ],
205  'redirect' => [
206  ParamValidator::PARAM_DEPRECATED => true,
207  ParamValidator::PARAM_DEFAULT => false,
208  ],
209  'limit' => [
210  ParamValidator::PARAM_TYPE => 'limit',
211  ParamValidator::PARAM_DEFAULT => 1,
212  IntegerDef::PARAM_MIN => 1,
213  IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
214  IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
215  ],
216  'continue' => [
217  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue'
218  ],
219  ];
220  }
221 
222  protected function getExamplesMessages() {
223  return [
224  'action=query&list=random&rnnamespace=0&rnlimit=2'
225  => 'apihelp-query+random-example-simple',
226  'action=query&generator=random&grnnamespace=0&grnlimit=2&prop=info'
227  => 'apihelp-query+random-example-generator',
228  ];
229  }
230 
231  public function getHelpUrls() {
232  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Random';
233  }
234 }
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:1683
getMain()
Get the main module.
Definition: ApiBase.php:515
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition: ApiBase.php:1644
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:222
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:939
getResult()
Get the result object.
Definition: ApiBase.php:630
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:766
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:164
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:224
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:499
getContinuationManager()
Definition: ApiBase.php:664
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
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:641
Service for formatting and validating API parameters.
Type definition for integer types.
Definition: IntegerDef.php:23
return true
Definition: router.php:90