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