Merge "Simplify code to avoid interpreting "$" characters in string replacement"
[mediawiki.git] / includes / api / ApiQueryRandom.php
blob1f6d9cc33c8b7211b4e892881abf2f1c34bc24e5
1 <?php
3 /**
4 * Copyright © 2008 Brent Garber
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
21 * @file
24 namespace MediaWiki\Api;
26 use MediaWiki\Title\Title;
27 use Wikimedia\ParamValidator\ParamValidator;
28 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
30 /**
31 * Query module to get list of random pages
33 * @ingroup API
35 class ApiQueryRandom extends ApiQueryGeneratorBase {
37 /**
38 * @param ApiQuery $query
39 * @param string $moduleName
41 public function __construct( ApiQuery $query, $moduleName ) {
42 parent::__construct( $query, $moduleName, 'rn' );
45 public function execute() {
46 $this->run();
49 public function executeGenerator( $resultPageSet ) {
50 $this->run( $resultPageSet );
53 /**
54 * Actually perform the query and add pages to the result.
55 * @param ApiPageSet|null $resultPageSet
56 * @param int $limit Number of pages to fetch
57 * @param string|null $start Starting page_random
58 * @param int|null $startId Starting page_id
59 * @param string|null $end Ending page_random
60 * @return array (int, string|null) Number of pages left to query and continuation string
62 protected function runQuery( $resultPageSet, $limit, $start, $startId, $end ) {
63 $params = $this->extractRequestParams();
65 $this->resetQueryParams();
66 $this->addTables( 'page' );
67 $this->addFields( [ 'page_id', 'page_random' ] );
68 if ( $resultPageSet === null ) {
69 $this->addFields( [ 'page_title', 'page_namespace' ] );
70 } else {
71 $this->addFields( $resultPageSet->getPageTableFields() );
73 $this->addWhereFld( 'page_namespace', $params['namespace'] );
74 if ( $params['redirect'] || $params['filterredir'] === 'redirects' ) {
75 $this->addWhereFld( 'page_is_redirect', 1 );
76 } elseif ( $params['filterredir'] === 'nonredirects' ) {
77 $this->addWhereFld( 'page_is_redirect', 0 );
78 } elseif ( $resultPageSet === null ) {
79 $this->addFields( [ 'page_is_redirect' ] );
81 $this->addOption( 'LIMIT', $limit + 1 );
83 if ( $start !== null ) {
84 $db = $this->getDB();
85 if ( $startId > 0 ) {
86 $this->addWhere( $db->buildComparison( '>=', [
87 'page_random' => $start,
88 'page_id' => $startId,
89 ] ) );
90 } else {
91 $this->addWhere( $db->buildComparison( '>=', [
92 'page_random' => $start,
93 ] ) );
96 if ( $end !== null ) {
97 $this->addWhere( $this->getDB()->expr( 'page_random', '<', $end ) );
99 $this->addOption( 'ORDER BY', [ 'page_random', 'page_id' ] );
101 $result = $this->getResult();
102 $path = [ 'query', $this->getModuleName() ];
104 $res = $this->select( __METHOD__ );
106 if ( $resultPageSet === null ) {
107 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
110 $count = 0;
111 foreach ( $res as $row ) {
112 if ( $count++ >= $limit ) {
113 return [ 0, "{$row->page_random}|{$row->page_id}" ];
115 if ( $resultPageSet === null ) {
116 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
117 $page = [
118 'id' => (int)$row->page_id,
120 ApiQueryBase::addTitleInfo( $page, $title );
121 if ( isset( $row->page_is_redirect ) ) {
122 $page['redirect'] = (bool)$row->page_is_redirect;
124 $fit = $result->addValue( $path, null, $page );
125 if ( !$fit ) {
126 return [ 0, "{$row->page_random}|{$row->page_id}" ];
128 } else {
129 $resultPageSet->processDbRow( $row );
133 return [ $limit - $count, null ];
137 * @param ApiPageSet|null $resultPageSet
139 public function run( $resultPageSet = null ) {
140 $params = $this->extractRequestParams();
142 // Since 'filterredir" will always be set in $params, we have to dig
143 // into the WebRequest to see if it was actually passed.
144 $request = $this->getMain()->getRequest();
145 if ( $request->getCheck( $this->encodeParamName( 'filterredir' ) ) ) {
146 $this->requireMaxOneParameter( $params, 'filterredir', 'redirect' );
149 if ( isset( $params['continue'] ) ) {
150 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string', 'int', 'string' ] );
151 $rand = $cont[0];
152 $start = $cont[1];
153 $startId = $cont[2];
154 $end = $cont[3] ? $rand : null;
155 $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $rand ) );
156 $this->dieContinueUsageIf( !preg_match( '/^0\.\d+$/', $start ) );
157 $this->dieContinueUsageIf( $cont[3] !== '0' && $cont[3] !== '1' );
158 } else {
159 $rand = wfRandom();
160 $start = $rand;
161 $startId = 0;
162 $end = null;
165 // Set the non-continue if this is being used as a generator
166 // (as a list it doesn't matter because lists never non-continue)
167 if ( $resultPageSet !== null ) {
168 $endFlag = $end === null ? 0 : 1;
169 $this->getContinuationManager()->addGeneratorNonContinueParam(
170 $this, 'continue', "$rand|$start|$startId|$endFlag"
174 [ $left, $continue ] =
175 $this->runQuery( $resultPageSet, $params['limit'], $start, $startId, $end );
176 if ( $end === null && $continue === null ) {
177 // Wrap around. We do this even if $left === 0 for continuation
178 // (saving a DB query in this rare case probably isn't worth the
179 // added code complexity it would require).
180 $end = $rand;
181 [ , $continue ] = $this->runQuery( $resultPageSet, $left, null, null, $end );
184 if ( $continue !== null ) {
185 $endFlag = $end === null ? 0 : 1;
186 $this->setContinueEnumParameter( 'continue', "$rand|$continue|$endFlag" );
189 if ( $resultPageSet === null ) {
190 $this->getResult()->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
194 public function getCacheMode( $params ) {
195 return 'public';
198 public function getAllowedParams() {
199 return [
200 'namespace' => [
201 ParamValidator::PARAM_TYPE => 'namespace',
202 ParamValidator::PARAM_ISMULTI => true
204 'filterredir' => [
205 ParamValidator::PARAM_TYPE => [ 'all', 'redirects', 'nonredirects' ],
206 ParamValidator::PARAM_DEFAULT => 'nonredirects', // for BC
208 'redirect' => [
209 ParamValidator::PARAM_DEPRECATED => true,
210 ParamValidator::PARAM_DEFAULT => false,
212 'limit' => [
213 ParamValidator::PARAM_TYPE => 'limit',
214 ParamValidator::PARAM_DEFAULT => 1,
215 IntegerDef::PARAM_MIN => 1,
216 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
217 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
219 'continue' => [
220 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue'
225 protected function getExamplesMessages() {
226 return [
227 'action=query&list=random&rnnamespace=0&rnlimit=2'
228 => 'apihelp-query+random-example-simple',
229 'action=query&generator=random&grnnamespace=0&grnlimit=2&prop=info'
230 => 'apihelp-query+random-example-generator',
234 public function getHelpUrls() {
235 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Random';
239 /** @deprecated class alias since 1.43 */
240 class_alias( ApiQueryRandom::class, 'ApiQueryRandom' );