Merge "RCFilters UI: Scroll to filter when selected"
[lhc/web/wiklou.git] / includes / api / ApiPageSet.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 24, 2006
6 *
7 * Copyright © 2006, 2013 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * This class contains a list of pages that the client has requested.
30 * Initially, when the client passes in titles=, pageids=, or revisions=
31 * parameter, an instance of the ApiPageSet class will normalize titles,
32 * determine if the pages/revisions exist, and prefetch any additional page
33 * data requested.
34 *
35 * When a generator is used, the result of the generator will become the input
36 * for the second instance of this class, and all subsequent actions will use
37 * the second instance for all their work.
38 *
39 * @ingroup API
40 * @since 1.21 derives from ApiBase instead of ApiQueryBase
41 */
42 class ApiPageSet extends ApiBase {
43 /**
44 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
45 * @since 1.21
46 */
47 const DISABLE_GENERATORS = 1;
48
49 private $mDbSource;
50 private $mParams;
51 private $mResolveRedirects;
52 private $mConvertTitles;
53 private $mAllowGenerator;
54
55 private $mAllPages = []; // [ns][dbkey] => page_id or negative when missing
56 private $mTitles = [];
57 private $mGoodAndMissingPages = []; // [ns][dbkey] => page_id or negative when missing
58 private $mGoodPages = []; // [ns][dbkey] => page_id
59 private $mGoodTitles = [];
60 private $mMissingPages = []; // [ns][dbkey] => fake page_id
61 private $mMissingTitles = [];
62 /** @var array [fake_page_id] => [ 'title' => $title, 'invalidreason' => $reason ] */
63 private $mInvalidTitles = [];
64 private $mMissingPageIDs = [];
65 private $mRedirectTitles = [];
66 private $mSpecialTitles = [];
67 private $mNormalizedTitles = [];
68 private $mInterwikiTitles = [];
69 /** @var Title[] */
70 private $mPendingRedirectIDs = [];
71 private $mResolvedRedirectTitles = [];
72 private $mConvertedTitles = [];
73 private $mGoodRevIDs = [];
74 private $mLiveRevIDs = [];
75 private $mDeletedRevIDs = [];
76 private $mMissingRevIDs = [];
77 private $mGeneratorData = []; // [ns][dbkey] => data array
78 private $mFakePageId = -1;
79 private $mCacheMode = 'public';
80 private $mRequestedPageFields = [];
81 /** @var int */
82 private $mDefaultNamespace = NS_MAIN;
83 /** @var callable|null */
84 private $mRedirectMergePolicy;
85
86 /**
87 * Add all items from $values into the result
88 * @param array $result Output
89 * @param array $values Values to add
90 * @param string[] $flags The names of boolean flags to mark this element
91 * @param string $name If given, name of the value
92 */
93 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
94 foreach ( $values as $val ) {
95 if ( $val instanceof Title ) {
96 $v = [];
97 ApiQueryBase::addTitleInfo( $v, $val );
98 } elseif ( $name !== null ) {
99 $v = [ $name => $val ];
100 } else {
101 $v = $val;
102 }
103 foreach ( $flags as $flag ) {
104 $v[$flag] = true;
105 }
106 $result[] = $v;
107 }
108 }
109
110 /**
111 * @param ApiBase $dbSource Module implementing getDB().
112 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
113 * @param int $flags Zero or more flags like DISABLE_GENERATORS
114 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
115 * @since 1.21 accepts $flags instead of two boolean values
116 */
117 public function __construct( ApiBase $dbSource, $flags = 0, $defaultNamespace = NS_MAIN ) {
118 parent::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
119 $this->mDbSource = $dbSource;
120 $this->mAllowGenerator = ( $flags & ApiPageSet::DISABLE_GENERATORS ) == 0;
121 $this->mDefaultNamespace = $defaultNamespace;
122
123 $this->mParams = $this->extractRequestParams();
124 $this->mResolveRedirects = $this->mParams['redirects'];
125 $this->mConvertTitles = $this->mParams['converttitles'];
126 }
127
128 /**
129 * In case execute() is not called, call this method to mark all relevant parameters as used
130 * This prevents unused parameters from being reported as warnings
131 */
132 public function executeDryRun() {
133 $this->executeInternal( true );
134 }
135
136 /**
137 * Populate the PageSet from the request parameters.
138 */
139 public function execute() {
140 $this->executeInternal( false );
141 }
142
143 /**
144 * Populate the PageSet from the request parameters.
145 * @param bool $isDryRun If true, instantiates generator, but only to mark
146 * relevant parameters as used
147 */
148 private function executeInternal( $isDryRun ) {
149 $generatorName = $this->mAllowGenerator ? $this->mParams['generator'] : null;
150 if ( isset( $generatorName ) ) {
151 $dbSource = $this->mDbSource;
152 if ( !$dbSource instanceof ApiQuery ) {
153 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
154 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
155 }
156 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
157 if ( $generator === null ) {
158 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
159 }
160 if ( !$generator instanceof ApiQueryGeneratorBase ) {
161 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
162 }
163 // Create a temporary pageset to store generator's output,
164 // add any additional fields generator may need, and execute pageset to populate titles/pageids
165 $tmpPageSet = new ApiPageSet( $dbSource, ApiPageSet::DISABLE_GENERATORS );
166 $generator->setGeneratorMode( $tmpPageSet );
167 $this->mCacheMode = $generator->getCacheMode( $generator->extractRequestParams() );
168
169 if ( !$isDryRun ) {
170 $generator->requestExtraData( $tmpPageSet );
171 }
172 $tmpPageSet->executeInternal( $isDryRun );
173
174 // populate this pageset with the generator output
175 if ( !$isDryRun ) {
176 $generator->executeGenerator( $this );
177
178 // Avoid PHP 7.1 warning of passing $this by reference
179 $apiModule = $this;
180 Hooks::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$apiModule ] );
181 } else {
182 // Prevent warnings from being reported on these parameters
183 $main = $this->getMain();
184 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
185 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
186 }
187 }
188
189 if ( !$isDryRun ) {
190 $this->resolvePendingRedirects();
191 }
192 } else {
193 // Only one of the titles/pageids/revids is allowed at the same time
194 $dataSource = null;
195 if ( isset( $this->mParams['titles'] ) ) {
196 $dataSource = 'titles';
197 }
198 if ( isset( $this->mParams['pageids'] ) ) {
199 if ( isset( $dataSource ) ) {
200 $this->dieWithError(
201 [
202 'apierror-invalidparammix-cannotusewith',
203 $this->encodeParamName( 'pageids' ),
204 $this->encodeParamName( $dataSource )
205 ],
206 'multisource'
207 );
208 }
209 $dataSource = 'pageids';
210 }
211 if ( isset( $this->mParams['revids'] ) ) {
212 if ( isset( $dataSource ) ) {
213 $this->dieWithError(
214 [
215 'apierror-invalidparammix-cannotusewith',
216 $this->encodeParamName( 'revids' ),
217 $this->encodeParamName( $dataSource )
218 ],
219 'multisource'
220 );
221 }
222 $dataSource = 'revids';
223 }
224
225 if ( !$isDryRun ) {
226 // Populate page information with the original user input
227 switch ( $dataSource ) {
228 case 'titles':
229 $this->initFromTitles( $this->mParams['titles'] );
230 break;
231 case 'pageids':
232 $this->initFromPageIds( $this->mParams['pageids'] );
233 break;
234 case 'revids':
235 if ( $this->mResolveRedirects ) {
236 $this->addWarning( 'apiwarn-redirectsandrevids' );
237 }
238 $this->mResolveRedirects = false;
239 $this->initFromRevIDs( $this->mParams['revids'] );
240 break;
241 default:
242 // Do nothing - some queries do not need any of the data sources.
243 break;
244 }
245 }
246 }
247 }
248
249 /**
250 * Check whether this PageSet is resolving redirects
251 * @return bool
252 */
253 public function isResolvingRedirects() {
254 return $this->mResolveRedirects;
255 }
256
257 /**
258 * Return the parameter name that is the source of data for this PageSet
259 *
260 * If multiple source parameters are specified (e.g. titles and pageids),
261 * one will be named arbitrarily.
262 *
263 * @return string|null
264 */
265 public function getDataSource() {
266 if ( $this->mAllowGenerator && isset( $this->mParams['generator'] ) ) {
267 return 'generator';
268 }
269 if ( isset( $this->mParams['titles'] ) ) {
270 return 'titles';
271 }
272 if ( isset( $this->mParams['pageids'] ) ) {
273 return 'pageids';
274 }
275 if ( isset( $this->mParams['revids'] ) ) {
276 return 'revids';
277 }
278
279 return null;
280 }
281
282 /**
283 * Request an additional field from the page table.
284 * Must be called before execute()
285 * @param string $fieldName Field name
286 */
287 public function requestField( $fieldName ) {
288 $this->mRequestedPageFields[$fieldName] = null;
289 }
290
291 /**
292 * Get the value of a custom field previously requested through
293 * requestField()
294 * @param string $fieldName Field name
295 * @return mixed Field value
296 */
297 public function getCustomField( $fieldName ) {
298 return $this->mRequestedPageFields[$fieldName];
299 }
300
301 /**
302 * Get the fields that have to be queried from the page table:
303 * the ones requested through requestField() and a few basic ones
304 * we always need
305 * @return array Array of field names
306 */
307 public function getPageTableFields() {
308 // Ensure we get minimum required fields
309 // DON'T change this order
310 $pageFlds = [
311 'page_namespace' => null,
312 'page_title' => null,
313 'page_id' => null,
314 ];
315
316 if ( $this->mResolveRedirects ) {
317 $pageFlds['page_is_redirect'] = null;
318 }
319
320 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
321 $pageFlds['page_content_model'] = null;
322 }
323
324 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
325 $pageFlds['page_lang'] = null;
326 }
327
328 foreach ( LinkCache::getSelectFields() as $field ) {
329 $pageFlds[$field] = null;
330 }
331
332 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields );
333
334 return array_keys( $pageFlds );
335 }
336
337 /**
338 * Returns an array [ns][dbkey] => page_id for all requested titles.
339 * page_id is a unique negative number in case title was not found.
340 * Invalid titles will also have negative page IDs and will be in namespace 0
341 * @return array
342 */
343 public function getAllTitlesByNamespace() {
344 return $this->mAllPages;
345 }
346
347 /**
348 * All Title objects provided.
349 * @return Title[]
350 */
351 public function getTitles() {
352 return $this->mTitles;
353 }
354
355 /**
356 * Returns the number of unique pages (not revisions) in the set.
357 * @return int
358 */
359 public function getTitleCount() {
360 return count( $this->mTitles );
361 }
362
363 /**
364 * Returns an array [ns][dbkey] => page_id for all good titles.
365 * @return array
366 */
367 public function getGoodTitlesByNamespace() {
368 return $this->mGoodPages;
369 }
370
371 /**
372 * Title objects that were found in the database.
373 * @return Title[] Array page_id (int) => Title (obj)
374 */
375 public function getGoodTitles() {
376 return $this->mGoodTitles;
377 }
378
379 /**
380 * Returns the number of found unique pages (not revisions) in the set.
381 * @return int
382 */
383 public function getGoodTitleCount() {
384 return count( $this->mGoodTitles );
385 }
386
387 /**
388 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
389 * fake_page_id is a unique negative number.
390 * @return array
391 */
392 public function getMissingTitlesByNamespace() {
393 return $this->mMissingPages;
394 }
395
396 /**
397 * Title objects that were NOT found in the database.
398 * The array's index will be negative for each item
399 * @return Title[]
400 */
401 public function getMissingTitles() {
402 return $this->mMissingTitles;
403 }
404
405 /**
406 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
407 * @return array
408 */
409 public function getGoodAndMissingTitlesByNamespace() {
410 return $this->mGoodAndMissingPages;
411 }
412
413 /**
414 * Title objects for good and missing titles.
415 * @return array
416 */
417 public function getGoodAndMissingTitles() {
418 return $this->mGoodTitles + $this->mMissingTitles;
419 }
420
421 /**
422 * Titles that were deemed invalid by Title::newFromText()
423 * The array's index will be unique and negative for each item
424 * @deprecated since 1.26, use self::getInvalidTitlesAndReasons()
425 * @return string[] Array of strings (not Title objects)
426 */
427 public function getInvalidTitles() {
428 wfDeprecated( __METHOD__, '1.26' );
429 return array_map( function ( $t ) {
430 return $t['title'];
431 }, $this->mInvalidTitles );
432 }
433
434 /**
435 * Titles that were deemed invalid by Title::newFromText()
436 * The array's index will be unique and negative for each item
437 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
438 */
439 public function getInvalidTitlesAndReasons() {
440 return $this->mInvalidTitles;
441 }
442
443 /**
444 * Page IDs that were not found in the database
445 * @return array Array of page IDs
446 */
447 public function getMissingPageIDs() {
448 return $this->mMissingPageIDs;
449 }
450
451 /**
452 * Get a list of redirect resolutions - maps a title to its redirect
453 * target, as an array of output-ready arrays
454 * @return Title[]
455 */
456 public function getRedirectTitles() {
457 return $this->mRedirectTitles;
458 }
459
460 /**
461 * Get a list of redirect resolutions - maps a title to its redirect
462 * target. Includes generator data for redirect source when available.
463 * @param ApiResult $result
464 * @return array Array of prefixed_title (string) => Title object
465 * @since 1.21
466 */
467 public function getRedirectTitlesAsResult( $result = null ) {
468 $values = [];
469 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
470 $r = [
471 'from' => strval( $titleStrFrom ),
472 'to' => $titleTo->getPrefixedText(),
473 ];
474 if ( $titleTo->hasFragment() ) {
475 $r['tofragment'] = $titleTo->getFragment();
476 }
477 if ( $titleTo->isExternal() ) {
478 $r['tointerwiki'] = $titleTo->getInterwiki();
479 }
480 if ( isset( $this->mResolvedRedirectTitles[$titleStrFrom] ) ) {
481 $titleFrom = $this->mResolvedRedirectTitles[$titleStrFrom];
482 $ns = $titleFrom->getNamespace();
483 $dbkey = $titleFrom->getDBkey();
484 if ( isset( $this->mGeneratorData[$ns][$dbkey] ) ) {
485 $r = array_merge( $this->mGeneratorData[$ns][$dbkey], $r );
486 }
487 }
488
489 $values[] = $r;
490 }
491 if ( !empty( $values ) && $result ) {
492 ApiResult::setIndexedTagName( $values, 'r' );
493 }
494
495 return $values;
496 }
497
498 /**
499 * Get a list of title normalizations - maps a title to its normalized
500 * version.
501 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
502 */
503 public function getNormalizedTitles() {
504 return $this->mNormalizedTitles;
505 }
506
507 /**
508 * Get a list of title normalizations - maps a title to its normalized
509 * version in the form of result array.
510 * @param ApiResult $result
511 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
512 * @since 1.21
513 */
514 public function getNormalizedTitlesAsResult( $result = null ) {
515 global $wgContLang;
516
517 $values = [];
518 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
519 $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr );
520 $values[] = [
521 'fromencoded' => $encode,
522 'from' => $encode ? rawurlencode( $rawTitleStr ) : $rawTitleStr,
523 'to' => $titleStr
524 ];
525 }
526 if ( !empty( $values ) && $result ) {
527 ApiResult::setIndexedTagName( $values, 'n' );
528 }
529
530 return $values;
531 }
532
533 /**
534 * Get a list of title conversions - maps a title to its converted
535 * version.
536 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
537 */
538 public function getConvertedTitles() {
539 return $this->mConvertedTitles;
540 }
541
542 /**
543 * Get a list of title conversions - maps a title to its converted
544 * version as a result array.
545 * @param ApiResult $result
546 * @return array Array of (from, to) strings
547 * @since 1.21
548 */
549 public function getConvertedTitlesAsResult( $result = null ) {
550 $values = [];
551 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
552 $values[] = [
553 'from' => $rawTitleStr,
554 'to' => $titleStr
555 ];
556 }
557 if ( !empty( $values ) && $result ) {
558 ApiResult::setIndexedTagName( $values, 'c' );
559 }
560
561 return $values;
562 }
563
564 /**
565 * Get a list of interwiki titles - maps a title to its interwiki
566 * prefix.
567 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
568 */
569 public function getInterwikiTitles() {
570 return $this->mInterwikiTitles;
571 }
572
573 /**
574 * Get a list of interwiki titles - maps a title to its interwiki
575 * prefix as result.
576 * @param ApiResult $result
577 * @param bool $iwUrl
578 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
579 * @since 1.21
580 */
581 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
582 $values = [];
583 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
584 $item = [
585 'title' => $rawTitleStr,
586 'iw' => $interwikiStr,
587 ];
588 if ( $iwUrl ) {
589 $title = Title::newFromText( $rawTitleStr );
590 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT );
591 }
592 $values[] = $item;
593 }
594 if ( !empty( $values ) && $result ) {
595 ApiResult::setIndexedTagName( $values, 'i' );
596 }
597
598 return $values;
599 }
600
601 /**
602 * Get an array of invalid/special/missing titles.
603 *
604 * @param array $invalidChecks List of types of invalid titles to include.
605 * Recognized values are:
606 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
607 * - special: Titles from $this->getSpecialTitles()
608 * - missingIds: ids from $this->getMissingPageIDs()
609 * - missingRevIds: ids from $this->getMissingRevisionIDs()
610 * - missingTitles: Titles from $this->getMissingTitles()
611 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
612 * @return array Array suitable for inclusion in the response
613 * @since 1.23
614 */
615 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
616 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
617 ) {
618 $result = [];
619 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
620 self::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
621 }
622 if ( in_array( 'special', $invalidChecks ) ) {
623 $known = [];
624 $unknown = [];
625 foreach ( $this->getSpecialTitles() as $title ) {
626 if ( $title->isKnown() ) {
627 $known[] = $title;
628 } else {
629 $unknown[] = $title;
630 }
631 }
632 self::addValues( $result, $unknown, [ 'special', 'missing' ] );
633 self::addValues( $result, $known, [ 'special' ] );
634 }
635 if ( in_array( 'missingIds', $invalidChecks ) ) {
636 self::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
637 }
638 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
639 self::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
640 }
641 if ( in_array( 'missingTitles', $invalidChecks ) ) {
642 $known = [];
643 $unknown = [];
644 foreach ( $this->getMissingTitles() as $title ) {
645 if ( $title->isKnown() ) {
646 $known[] = $title;
647 } else {
648 $unknown[] = $title;
649 }
650 }
651 self::addValues( $result, $unknown, [ 'missing' ] );
652 self::addValues( $result, $known, [ 'missing', 'known' ] );
653 }
654 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
655 self::addValues( $result, $this->getInterwikiTitlesAsResult() );
656 }
657
658 return $result;
659 }
660
661 /**
662 * Get the list of valid revision IDs (requested with the revids= parameter)
663 * @return array Array of revID (int) => pageID (int)
664 */
665 public function getRevisionIDs() {
666 return $this->mGoodRevIDs;
667 }
668
669 /**
670 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
671 * @return array Array of revID (int) => pageID (int)
672 */
673 public function getLiveRevisionIDs() {
674 return $this->mLiveRevIDs;
675 }
676
677 /**
678 * Get the list of revision IDs that were associated with deleted titles.
679 * @return array Array of revID (int) => pageID (int)
680 */
681 public function getDeletedRevisionIDs() {
682 return $this->mDeletedRevIDs;
683 }
684
685 /**
686 * Revision IDs that were not found in the database
687 * @return array Array of revision IDs
688 */
689 public function getMissingRevisionIDs() {
690 return $this->mMissingRevIDs;
691 }
692
693 /**
694 * Revision IDs that were not found in the database as result array.
695 * @param ApiResult $result
696 * @return array Array of revision IDs
697 * @since 1.21
698 */
699 public function getMissingRevisionIDsAsResult( $result = null ) {
700 $values = [];
701 foreach ( $this->getMissingRevisionIDs() as $revid ) {
702 $values[$revid] = [
703 'revid' => $revid
704 ];
705 }
706 if ( !empty( $values ) && $result ) {
707 ApiResult::setIndexedTagName( $values, 'rev' );
708 }
709
710 return $values;
711 }
712
713 /**
714 * Get the list of titles with negative namespace
715 * @return Title[]
716 */
717 public function getSpecialTitles() {
718 return $this->mSpecialTitles;
719 }
720
721 /**
722 * Returns the number of revisions (requested with revids= parameter).
723 * @return int Number of revisions.
724 */
725 public function getRevisionCount() {
726 return count( $this->getRevisionIDs() );
727 }
728
729 /**
730 * Populate this PageSet from a list of Titles
731 * @param array $titles Array of Title objects
732 */
733 public function populateFromTitles( $titles ) {
734 $this->initFromTitles( $titles );
735 }
736
737 /**
738 * Populate this PageSet from a list of page IDs
739 * @param array $pageIDs Array of page IDs
740 */
741 public function populateFromPageIDs( $pageIDs ) {
742 $this->initFromPageIds( $pageIDs );
743 }
744
745 /**
746 * Populate this PageSet from a rowset returned from the database
747 *
748 * Note that the query result must include the columns returned by
749 * $this->getPageTableFields().
750 *
751 * @param IDatabase $db
752 * @param ResultWrapper $queryResult Query result object
753 */
754 public function populateFromQueryResult( $db, $queryResult ) {
755 $this->initFromQueryResult( $queryResult );
756 }
757
758 /**
759 * Populate this PageSet from a list of revision IDs
760 * @param array $revIDs Array of revision IDs
761 */
762 public function populateFromRevisionIDs( $revIDs ) {
763 $this->initFromRevIDs( $revIDs );
764 }
765
766 /**
767 * Extract all requested fields from the row received from the database
768 * @param stdClass $row Result row
769 */
770 public function processDbRow( $row ) {
771 // Store Title object in various data structures
772 $title = Title::newFromRow( $row );
773
774 LinkCache::singleton()->addGoodLinkObjFromRow( $title, $row );
775
776 $pageId = intval( $row->page_id );
777 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
778 $this->mTitles[] = $title;
779
780 if ( $this->mResolveRedirects && $row->page_is_redirect == '1' ) {
781 $this->mPendingRedirectIDs[$pageId] = $title;
782 } else {
783 $this->mGoodPages[$row->page_namespace][$row->page_title] = $pageId;
784 $this->mGoodAndMissingPages[$row->page_namespace][$row->page_title] = $pageId;
785 $this->mGoodTitles[$pageId] = $title;
786 }
787
788 foreach ( $this->mRequestedPageFields as $fieldName => &$fieldValues ) {
789 $fieldValues[$pageId] = $row->$fieldName;
790 }
791 }
792
793 /**
794 * This method populates internal variables with page information
795 * based on the given array of title strings.
796 *
797 * Steps:
798 * #1 For each title, get data from `page` table
799 * #2 If page was not found in the DB, store it as missing
800 *
801 * Additionally, when resolving redirects:
802 * #3 If no more redirects left, stop.
803 * #4 For each redirect, get its target from the `redirect` table.
804 * #5 Substitute the original LinkBatch object with the new list
805 * #6 Repeat from step #1
806 *
807 * @param array $titles Array of Title objects or strings
808 */
809 private function initFromTitles( $titles ) {
810 // Get validated and normalized title objects
811 $linkBatch = $this->processTitlesArray( $titles );
812 if ( $linkBatch->isEmpty() ) {
813 return;
814 }
815
816 $db = $this->getDB();
817 $set = $linkBatch->constructSet( 'page', $db );
818
819 // Get pageIDs data from the `page` table
820 $res = $db->select( 'page', $this->getPageTableFields(), $set,
821 __METHOD__ );
822
823 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
824 $this->initFromQueryResult( $res, $linkBatch->data, true ); // process Titles
825
826 // Resolve any found redirects
827 $this->resolvePendingRedirects();
828 }
829
830 /**
831 * Does the same as initFromTitles(), but is based on page IDs instead
832 * @param array $pageids Array of page IDs
833 */
834 private function initFromPageIds( $pageids ) {
835 if ( !$pageids ) {
836 return;
837 }
838
839 $pageids = array_map( 'intval', $pageids ); // paranoia
840 $remaining = array_flip( $pageids );
841
842 $pageids = self::getPositiveIntegers( $pageids );
843
844 $res = null;
845 if ( !empty( $pageids ) ) {
846 $set = [
847 'page_id' => $pageids
848 ];
849 $db = $this->getDB();
850
851 // Get pageIDs data from the `page` table
852 $res = $db->select( 'page', $this->getPageTableFields(), $set,
853 __METHOD__ );
854 }
855
856 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
857
858 // Resolve any found redirects
859 $this->resolvePendingRedirects();
860 }
861
862 /**
863 * Iterate through the result of the query on 'page' table,
864 * and for each row create and store title object and save any extra fields requested.
865 * @param ResultWrapper $res DB Query result
866 * @param array $remaining Array of either pageID or ns/title elements (optional).
867 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
868 * @param bool $processTitles Must be provided together with $remaining.
869 * If true, treat $remaining as an array of [ns][title]
870 * If false, treat it as an array of [pageIDs]
871 */
872 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
873 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
874 ApiBase::dieDebug( __METHOD__, 'Missing $processTitles parameter when $remaining is provided' );
875 }
876
877 $usernames = [];
878 if ( $res ) {
879 foreach ( $res as $row ) {
880 $pageId = intval( $row->page_id );
881
882 // Remove found page from the list of remaining items
883 if ( isset( $remaining ) ) {
884 if ( $processTitles ) {
885 unset( $remaining[$row->page_namespace][$row->page_title] );
886 } else {
887 unset( $remaining[$pageId] );
888 }
889 }
890
891 // Store any extra fields requested by modules
892 $this->processDbRow( $row );
893
894 // Need gender information
895 if ( MWNamespace::hasGenderDistinction( $row->page_namespace ) ) {
896 $usernames[] = $row->page_title;
897 }
898 }
899 }
900
901 if ( isset( $remaining ) ) {
902 // Any items left in the $remaining list are added as missing
903 if ( $processTitles ) {
904 // The remaining titles in $remaining are non-existent pages
905 $linkCache = LinkCache::singleton();
906 foreach ( $remaining as $ns => $dbkeys ) {
907 foreach ( array_keys( $dbkeys ) as $dbkey ) {
908 $title = Title::makeTitle( $ns, $dbkey );
909 $linkCache->addBadLinkObj( $title );
910 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
911 $this->mMissingPages[$ns][$dbkey] = $this->mFakePageId;
912 $this->mGoodAndMissingPages[$ns][$dbkey] = $this->mFakePageId;
913 $this->mMissingTitles[$this->mFakePageId] = $title;
914 $this->mFakePageId--;
915 $this->mTitles[] = $title;
916
917 // need gender information
918 if ( MWNamespace::hasGenderDistinction( $ns ) ) {
919 $usernames[] = $dbkey;
920 }
921 }
922 }
923 } else {
924 // The remaining pageids do not exist
925 if ( !$this->mMissingPageIDs ) {
926 $this->mMissingPageIDs = array_keys( $remaining );
927 } else {
928 $this->mMissingPageIDs = array_merge( $this->mMissingPageIDs, array_keys( $remaining ) );
929 }
930 }
931 }
932
933 // Get gender information
934 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
935 $genderCache->doQuery( $usernames, __METHOD__ );
936 }
937
938 /**
939 * Does the same as initFromTitles(), but is based on revision IDs
940 * instead
941 * @param array $revids Array of revision IDs
942 */
943 private function initFromRevIDs( $revids ) {
944 if ( !$revids ) {
945 return;
946 }
947
948 $revids = array_map( 'intval', $revids ); // paranoia
949 $db = $this->getDB();
950 $pageids = [];
951 $remaining = array_flip( $revids );
952
953 $revids = self::getPositiveIntegers( $revids );
954
955 if ( !empty( $revids ) ) {
956 $tables = [ 'revision', 'page' ];
957 $fields = [ 'rev_id', 'rev_page' ];
958 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
959
960 // Get pageIDs data from the `page` table
961 $res = $db->select( $tables, $fields, $where, __METHOD__ );
962 foreach ( $res as $row ) {
963 $revid = intval( $row->rev_id );
964 $pageid = intval( $row->rev_page );
965 $this->mGoodRevIDs[$revid] = $pageid;
966 $this->mLiveRevIDs[$revid] = $pageid;
967 $pageids[$pageid] = '';
968 unset( $remaining[$revid] );
969 }
970 }
971
972 $this->mMissingRevIDs = array_keys( $remaining );
973
974 // Populate all the page information
975 $this->initFromPageIds( array_keys( $pageids ) );
976
977 // If the user can see deleted revisions, pull out the corresponding
978 // titles from the archive table and include them too. We ignore
979 // ar_page_id because deleted revisions are tied by title, not page_id.
980 if ( !empty( $this->mMissingRevIDs ) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
981 $remaining = array_flip( $this->mMissingRevIDs );
982 $tables = [ 'archive' ];
983 $fields = [ 'ar_rev_id', 'ar_namespace', 'ar_title' ];
984 $where = [ 'ar_rev_id' => $this->mMissingRevIDs ];
985
986 $res = $db->select( $tables, $fields, $where, __METHOD__ );
987 $titles = [];
988 foreach ( $res as $row ) {
989 $revid = intval( $row->ar_rev_id );
990 $titles[$revid] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
991 unset( $remaining[$revid] );
992 }
993
994 $this->initFromTitles( $titles );
995
996 foreach ( $titles as $revid => $title ) {
997 $ns = $title->getNamespace();
998 $dbkey = $title->getDBkey();
999
1000 // Handle converted titles
1001 if ( !isset( $this->mAllPages[$ns][$dbkey] ) &&
1002 isset( $this->mConvertedTitles[$title->getPrefixedText()] )
1003 ) {
1004 $title = Title::newFromText( $this->mConvertedTitles[$title->getPrefixedText()] );
1005 $ns = $title->getNamespace();
1006 $dbkey = $title->getDBkey();
1007 }
1008
1009 if ( isset( $this->mAllPages[$ns][$dbkey] ) ) {
1010 $this->mGoodRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
1011 $this->mDeletedRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
1012 } else {
1013 $remaining[$revid] = true;
1014 }
1015 }
1016
1017 $this->mMissingRevIDs = array_keys( $remaining );
1018 }
1019 }
1020
1021 /**
1022 * Resolve any redirects in the result if redirect resolution was
1023 * requested. This function is called repeatedly until all redirects
1024 * have been resolved.
1025 */
1026 private function resolvePendingRedirects() {
1027 if ( $this->mResolveRedirects ) {
1028 $db = $this->getDB();
1029 $pageFlds = $this->getPageTableFields();
1030
1031 // Repeat until all redirects have been resolved
1032 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
1033 while ( $this->mPendingRedirectIDs ) {
1034 // Resolve redirects by querying the pagelinks table, and repeat the process
1035 // Create a new linkBatch object for the next pass
1036 $linkBatch = $this->getRedirectTargets();
1037
1038 if ( $linkBatch->isEmpty() ) {
1039 break;
1040 }
1041
1042 $set = $linkBatch->constructSet( 'page', $db );
1043 if ( $set === false ) {
1044 break;
1045 }
1046
1047 // Get pageIDs data from the `page` table
1048 $res = $db->select( 'page', $pageFlds, $set, __METHOD__ );
1049
1050 // Hack: get the ns:titles stored in [ns => array(titles)] format
1051 $this->initFromQueryResult( $res, $linkBatch->data, true );
1052 }
1053 }
1054 }
1055
1056 /**
1057 * Get the targets of the pending redirects from the database
1058 *
1059 * Also creates entries in the redirect table for redirects that don't
1060 * have one.
1061 * @return LinkBatch
1062 */
1063 private function getRedirectTargets() {
1064 $lb = new LinkBatch();
1065 $db = $this->getDB();
1066
1067 $res = $db->select(
1068 'redirect',
1069 [
1070 'rd_from',
1071 'rd_namespace',
1072 'rd_fragment',
1073 'rd_interwiki',
1074 'rd_title'
1075 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs ) ],
1076 __METHOD__
1077 );
1078 foreach ( $res as $row ) {
1079 $rdfrom = intval( $row->rd_from );
1080 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
1081 $to = Title::makeTitle(
1082 $row->rd_namespace,
1083 $row->rd_title,
1084 $row->rd_fragment,
1085 $row->rd_interwiki
1086 );
1087 $this->mResolvedRedirectTitles[$from] = $this->mPendingRedirectIDs[$rdfrom];
1088 unset( $this->mPendingRedirectIDs[$rdfrom] );
1089 if ( $to->isExternal() ) {
1090 $this->mInterwikiTitles[$to->getPrefixedText()] = $to->getInterwiki();
1091 } elseif ( !isset( $this->mAllPages[$row->rd_namespace][$row->rd_title] ) ) {
1092 $lb->add( $row->rd_namespace, $row->rd_title );
1093 }
1094 $this->mRedirectTitles[$from] = $to;
1095 }
1096
1097 if ( $this->mPendingRedirectIDs ) {
1098 // We found pages that aren't in the redirect table
1099 // Add them
1100 foreach ( $this->mPendingRedirectIDs as $id => $title ) {
1101 $page = WikiPage::factory( $title );
1102 $rt = $page->insertRedirect();
1103 if ( !$rt ) {
1104 // What the hell. Let's just ignore this
1105 continue;
1106 }
1107 $lb->addObj( $rt );
1108 $from = $title->getPrefixedText();
1109 $this->mResolvedRedirectTitles[$from] = $title;
1110 $this->mRedirectTitles[$from] = $rt;
1111 unset( $this->mPendingRedirectIDs[$id] );
1112 }
1113 }
1114
1115 return $lb;
1116 }
1117
1118 /**
1119 * Get the cache mode for the data generated by this module.
1120 * All PageSet users should take into account whether this returns a more-restrictive
1121 * cache mode than the using module itself. For possible return values and other
1122 * details about cache modes, see ApiMain::setCacheMode()
1123 *
1124 * Public caching will only be allowed if *all* the modules that supply
1125 * data for a given request return a cache mode of public.
1126 *
1127 * @param array|null $params
1128 * @return string
1129 * @since 1.21
1130 */
1131 public function getCacheMode( $params = null ) {
1132 return $this->mCacheMode;
1133 }
1134
1135 /**
1136 * Given an array of title strings, convert them into Title objects.
1137 * Alternatively, an array of Title objects may be given.
1138 * This method validates access rights for the title,
1139 * and appends normalization values to the output.
1140 *
1141 * @param array $titles Array of Title objects or strings
1142 * @return LinkBatch
1143 */
1144 private function processTitlesArray( $titles ) {
1145 $usernames = [];
1146 $linkBatch = new LinkBatch();
1147
1148 foreach ( $titles as $title ) {
1149 if ( is_string( $title ) ) {
1150 try {
1151 $titleObj = Title::newFromTextThrow( $title, $this->mDefaultNamespace );
1152 } catch ( MalformedTitleException $ex ) {
1153 // Handle invalid titles gracefully
1154 $this->mAllPages[0][$title] = $this->mFakePageId;
1155 $this->mInvalidTitles[$this->mFakePageId] = [
1156 'title' => $title,
1157 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1158 ];
1159 $this->mFakePageId--;
1160 continue; // There's nothing else we can do
1161 }
1162 } else {
1163 $titleObj = $title;
1164 }
1165 $unconvertedTitle = $titleObj->getPrefixedText();
1166 $titleWasConverted = false;
1167 if ( $titleObj->isExternal() ) {
1168 // This title is an interwiki link.
1169 $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki();
1170 } else {
1171 // Variants checking
1172 global $wgContLang;
1173 if ( $this->mConvertTitles &&
1174 count( $wgContLang->getVariants() ) > 1 &&
1175 !$titleObj->exists()
1176 ) {
1177 // Language::findVariantLink will modify titleText and titleObj into
1178 // the canonical variant if possible
1179 $titleText = is_string( $title ) ? $title : $titleObj->getPrefixedText();
1180 $wgContLang->findVariantLink( $titleText, $titleObj );
1181 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1182 }
1183
1184 if ( $titleObj->getNamespace() < 0 ) {
1185 // Handle Special and Media pages
1186 $titleObj = $titleObj->fixSpecialName();
1187 $this->mSpecialTitles[$this->mFakePageId] = $titleObj;
1188 $this->mFakePageId--;
1189 } else {
1190 // Regular page
1191 $linkBatch->addObj( $titleObj );
1192 }
1193 }
1194
1195 // Make sure we remember the original title that was
1196 // given to us. This way the caller can correlate new
1197 // titles with the originally requested when e.g. the
1198 // namespace is localized or the capitalization is
1199 // different
1200 if ( $titleWasConverted ) {
1201 $this->mConvertedTitles[$unconvertedTitle] = $titleObj->getPrefixedText();
1202 // In this case the page can't be Special.
1203 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1204 $this->mNormalizedTitles[$title] = $unconvertedTitle;
1205 }
1206 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1207 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
1208 }
1209
1210 // Need gender information
1211 if ( MWNamespace::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1212 $usernames[] = $titleObj->getText();
1213 }
1214 }
1215 // Get gender information
1216 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
1217 $genderCache->doQuery( $usernames, __METHOD__ );
1218
1219 return $linkBatch;
1220 }
1221
1222 /**
1223 * Set data for a title.
1224 *
1225 * This data may be extracted into an ApiResult using
1226 * self::populateGeneratorData. This should generally be limited to
1227 * data that is likely to be particularly useful to end users rather than
1228 * just being a dump of everything returned in non-generator mode.
1229 *
1230 * Redirects here will *not* be followed, even if 'redirects' was
1231 * specified, since in the case of multiple redirects we can't know which
1232 * source's data to use on the target.
1233 *
1234 * @param Title $title
1235 * @param array $data
1236 */
1237 public function setGeneratorData( Title $title, array $data ) {
1238 $ns = $title->getNamespace();
1239 $dbkey = $title->getDBkey();
1240 $this->mGeneratorData[$ns][$dbkey] = $data;
1241 }
1242
1243 /**
1244 * Controls how generator data about a redirect source is merged into
1245 * the generator data for the redirect target. When not set no data
1246 * is merged. Note that if multiple titles redirect to the same target
1247 * the order of operations is undefined.
1248 *
1249 * Example to include generated data from redirect in target, prefering
1250 * the data generated for the destination when there is a collision:
1251 * @code
1252 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1253 * return $current + $new;
1254 * } );
1255 * @endcode
1256 *
1257 * @param callable|null $callable Recieves two array arguments, first the
1258 * generator data for the redirect target and second the generator data
1259 * for the redirect source. Returns the resulting generator data to use
1260 * for the redirect target.
1261 */
1262 public function setRedirectMergePolicy( $callable ) {
1263 $this->mRedirectMergePolicy = $callable;
1264 }
1265
1266 /**
1267 * Populate the generator data for all titles in the result
1268 *
1269 * The page data may be inserted into an ApiResult object or into an
1270 * associative array. The $path parameter specifies the path within the
1271 * ApiResult or array to find the "pages" node.
1272 *
1273 * The "pages" node itself must be an associative array mapping the page ID
1274 * or fake page ID values returned by this pageset (see
1275 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1276 * associative arrays of page data. Each of those subarrays will have the
1277 * data from self::setGeneratorData() merged in.
1278 *
1279 * Data that was set by self::setGeneratorData() for pages not in the
1280 * "pages" node will be ignored.
1281 *
1282 * @param ApiResult|array &$result
1283 * @param array $path
1284 * @return bool Whether the data fit
1285 */
1286 public function populateGeneratorData( &$result, array $path = [] ) {
1287 if ( $result instanceof ApiResult ) {
1288 $data = $result->getResultData( $path );
1289 if ( $data === null ) {
1290 return true;
1291 }
1292 } else {
1293 $data = &$result;
1294 foreach ( $path as $key ) {
1295 if ( !isset( $data[$key] ) ) {
1296 // Path isn't in $result, so nothing to add, so everything
1297 // "fits"
1298 return true;
1299 }
1300 $data = &$data[$key];
1301 }
1302 }
1303 foreach ( $this->mGeneratorData as $ns => $dbkeys ) {
1304 if ( $ns === -1 ) {
1305 $pages = [];
1306 foreach ( $this->mSpecialTitles as $id => $title ) {
1307 $pages[$title->getDBkey()] = $id;
1308 }
1309 } else {
1310 if ( !isset( $this->mAllPages[$ns] ) ) {
1311 // No known titles in the whole namespace. Skip it.
1312 continue;
1313 }
1314 $pages = $this->mAllPages[$ns];
1315 }
1316 foreach ( $dbkeys as $dbkey => $genData ) {
1317 if ( !isset( $pages[$dbkey] ) ) {
1318 // Unknown title. Forget it.
1319 continue;
1320 }
1321 $pageId = $pages[$dbkey];
1322 if ( !isset( $data[$pageId] ) ) {
1323 // $pageId didn't make it into the result. Ignore it.
1324 continue;
1325 }
1326
1327 if ( $result instanceof ApiResult ) {
1328 $path2 = array_merge( $path, [ $pageId ] );
1329 foreach ( $genData as $key => $value ) {
1330 if ( !$result->addValue( $path2, $key, $value ) ) {
1331 return false;
1332 }
1333 }
1334 } else {
1335 $data[$pageId] = array_merge( $data[$pageId], $genData );
1336 }
1337 }
1338 }
1339
1340 // Merge data generated about redirect titles into the redirect destination
1341 if ( $this->mRedirectMergePolicy ) {
1342 foreach ( $this->mResolvedRedirectTitles as $titleFrom ) {
1343 $dest = $titleFrom;
1344 while ( isset( $this->mRedirectTitles[$dest->getPrefixedText()] ) ) {
1345 $dest = $this->mRedirectTitles[$dest->getPrefixedText()];
1346 }
1347 $fromNs = $titleFrom->getNamespace();
1348 $fromDBkey = $titleFrom->getDBkey();
1349 $toPageId = $dest->getArticleID();
1350 if ( isset( $data[$toPageId] ) &&
1351 isset( $this->mGeneratorData[$fromNs][$fromDBkey] )
1352 ) {
1353 // It is necesary to set both $data and add to $result, if an ApiResult,
1354 // to ensure multiple redirects to the same destination are all merged.
1355 $data[$toPageId] = call_user_func(
1356 $this->mRedirectMergePolicy,
1357 $data[$toPageId],
1358 $this->mGeneratorData[$fromNs][$fromDBkey]
1359 );
1360 if ( $result instanceof ApiResult ) {
1361 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE ) ) {
1362 return false;
1363 }
1364 }
1365 }
1366 }
1367 }
1368
1369 return true;
1370 }
1371
1372 /**
1373 * Get the database connection (read-only)
1374 * @return Database
1375 */
1376 protected function getDB() {
1377 return $this->mDbSource->getDB();
1378 }
1379
1380 /**
1381 * Returns the input array of integers with all values < 0 removed
1382 *
1383 * @param array $array
1384 * @return array
1385 */
1386 private static function getPositiveIntegers( $array ) {
1387 // T27734 API: possible issue with revids validation
1388 // It seems with a load of revision rows, MySQL gets upset
1389 // Remove any < 0 integers, as they can't be valid
1390 foreach ( $array as $i => $int ) {
1391 if ( $int < 0 ) {
1392 unset( $array[$i] );
1393 }
1394 }
1395
1396 return $array;
1397 }
1398
1399 public function getAllowedParams( $flags = 0 ) {
1400 $result = [
1401 'titles' => [
1402 ApiBase::PARAM_ISMULTI => true,
1403 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-titles',
1404 ],
1405 'pageids' => [
1406 ApiBase::PARAM_TYPE => 'integer',
1407 ApiBase::PARAM_ISMULTI => true,
1408 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-pageids',
1409 ],
1410 'revids' => [
1411 ApiBase::PARAM_TYPE => 'integer',
1412 ApiBase::PARAM_ISMULTI => true,
1413 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-revids',
1414 ],
1415 'generator' => [
1416 ApiBase::PARAM_TYPE => null,
1417 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-generator',
1418 ApiBase::PARAM_SUBMODULE_PARAM_PREFIX => 'g',
1419 ],
1420 'redirects' => [
1421 ApiBase::PARAM_DFLT => false,
1422 ApiBase::PARAM_HELP_MSG => $this->mAllowGenerator
1423 ? 'api-pageset-param-redirects-generator'
1424 : 'api-pageset-param-redirects-nogenerator',
1425 ],
1426 'converttitles' => [
1427 ApiBase::PARAM_DFLT => false,
1428 ApiBase::PARAM_HELP_MSG => [
1429 'api-pageset-param-converttitles',
1430 [ Message::listParam( LanguageConverter::$languagesWithVariants, 'text' ) ],
1431 ],
1432 ],
1433 ];
1434
1435 if ( !$this->mAllowGenerator ) {
1436 unset( $result['generator'] );
1437 } elseif ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
1438 $result['generator'][ApiBase::PARAM_TYPE] = 'submodule';
1439 $result['generator'][ApiBase::PARAM_SUBMODULE_MAP] = $this->getGenerators();
1440 }
1441
1442 return $result;
1443 }
1444
1445 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1446 parent::handleParamNormalization( $paramName, $value, $rawValue );
1447
1448 if ( $paramName === 'titles' ) {
1449 // For the 'titles' parameter, we want to split it like ApiBase would
1450 // and add any changed titles to $this->mNormalizedTitles
1451 $value = $this->explodeMultiValue( $value, self::LIMIT_SML2 + 1 );
1452 $l = count( $value );
1453 $rawValue = $this->explodeMultiValue( $rawValue, $l );
1454 for ( $i = 0; $i < $l; $i++ ) {
1455 if ( $value[$i] !== $rawValue[$i] ) {
1456 $this->mNormalizedTitles[$rawValue[$i]] = $value[$i];
1457 }
1458 }
1459 }
1460 }
1461
1462 private static $generators = null;
1463
1464 /**
1465 * Get an array of all available generators
1466 * @return array
1467 */
1468 private function getGenerators() {
1469 if ( self::$generators === null ) {
1470 $query = $this->mDbSource;
1471 if ( !( $query instanceof ApiQuery ) ) {
1472 // If the parent container of this pageset is not ApiQuery,
1473 // we must create it to get module manager
1474 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1475 }
1476 $gens = [];
1477 $prefix = $query->getModulePath() . '+';
1478 $mgr = $query->getModuleManager();
1479 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1480 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1481 $gens[$name] = $prefix . $name;
1482 }
1483 }
1484 ksort( $gens );
1485 self::$generators = $gens;
1486 }
1487
1488 return self::$generators;
1489 }
1490 }