Update git submodules
[mediawiki.git] / includes / api / ApiPageSet.php
blob16941cf10dbdc49989ed0cbf2db0a815b2f0a6bf
1 <?php
2 /**
3 * Copyright © 2006, 2013 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 use MediaWiki\Api\Validator\SubmoduleDef;
24 use MediaWiki\Cache\LinkBatchFactory;
25 use MediaWiki\Linker\LinkTarget;
26 use MediaWiki\MainConfigNames;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Page\PageIdentity;
29 use MediaWiki\Page\PageReference;
30 use MediaWiki\Request\FauxRequest;
31 use MediaWiki\SpecialPage\RedirectSpecialArticle;
32 use MediaWiki\SpecialPage\SpecialPageFactory;
33 use MediaWiki\Title\MalformedTitleException;
34 use MediaWiki\Title\NamespaceInfo;
35 use MediaWiki\Title\Title;
36 use MediaWiki\Title\TitleFactory;
37 use Wikimedia\ParamValidator\ParamValidator;
38 use Wikimedia\Rdbms\IDatabase;
39 use Wikimedia\Rdbms\IResultWrapper;
41 /**
42 * This class contains a list of pages that the client has requested.
43 * Initially, when the client passes in titles=, pageids=, or revisions=
44 * parameter, an instance of the ApiPageSet class will normalize titles,
45 * determine if the pages/revisions exist, and prefetch any additional page
46 * data requested.
48 * When a generator is used, the result of the generator will become the input
49 * for the second instance of this class, and all subsequent actions will use
50 * the second instance for all their work.
52 * @ingroup API
53 * @since 1.21 derives from ApiBase instead of ApiQueryBase
55 class ApiPageSet extends ApiBase {
56 /**
57 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
58 * @since 1.21
60 private const DISABLE_GENERATORS = 1;
62 /** @var ApiBase used for getDb() call */
63 private $mDbSource;
65 /** @var array */
66 private $mParams;
68 /** @var bool */
69 private $mResolveRedirects;
71 /** @var bool */
72 private $mConvertTitles;
74 /** @var bool */
75 private $mAllowGenerator;
77 /** @var int[][] [ns][dbkey] => page_id or negative when missing */
78 private $mAllPages = [];
80 /** @var Title[] */
81 private $mTitles = [];
83 /** @var int[][] [ns][dbkey] => page_id or negative when missing */
84 private $mGoodAndMissingPages = [];
86 /** @var int[][] [ns][dbkey] => page_id */
87 private $mGoodPages = [];
89 /** @var Title[] */
90 private $mGoodTitles = [];
92 /** @var int[][] [ns][dbkey] => fake page_id */
93 private $mMissingPages = [];
95 /** @var Title[] */
96 private $mMissingTitles = [];
98 /** @var array[] [fake_page_id] => [ 'title' => $title, 'invalidreason' => $reason ] */
99 private $mInvalidTitles = [];
101 /** @var int[] */
102 private $mMissingPageIDs = [];
104 /** @var Title[] */
105 private $mRedirectTitles = [];
107 /** @var Title[] */
108 private $mSpecialTitles = [];
110 /** @var int[][] separate from mAllPages to avoid breaking getAllTitlesByNamespace() */
111 private $mAllSpecials = [];
113 /** @var string[] */
114 private $mNormalizedTitles = [];
116 /** @var string[] */
117 private $mInterwikiTitles = [];
119 /** @var Title[] */
120 private $mPendingRedirectIDs = [];
122 /** @var Title[][] [dbkey] => [ Title $from, Title $to ] */
123 private $mPendingRedirectSpecialPages = [];
125 /** @var Title[] */
126 private $mResolvedRedirectTitles = [];
128 /** @var string[] */
129 private $mConvertedTitles = [];
131 /** @var int[] Array of revID (int) => pageID (int) */
132 private $mGoodRevIDs = [];
134 /** @var int[] Array of revID (int) => pageID (int) */
135 private $mLiveRevIDs = [];
137 /** @var int[] Array of revID (int) => pageID (int) */
138 private $mDeletedRevIDs = [];
140 /** @var int[] */
141 private $mMissingRevIDs = [];
143 /** @var array[][] [ns][dbkey] => data array */
144 private $mGeneratorData = [];
146 /** @var int */
147 private $mFakePageId = -1;
149 /** @var string */
150 private $mCacheMode = 'public';
152 /** @var array */
153 private $mRequestedPageFields = [];
155 /** @var int */
156 private $mDefaultNamespace;
158 /** @var callable|null */
159 private $mRedirectMergePolicy;
161 /** @var string[]|null see getGenerators() */
162 private static $generators = null;
164 private Language $contentLanguage;
165 private LinkCache $linkCache;
166 private NamespaceInfo $namespaceInfo;
167 private GenderCache $genderCache;
168 private LinkBatchFactory $linkBatchFactory;
169 private TitleFactory $titleFactory;
170 private ILanguageConverter $languageConverter;
171 private SpecialPageFactory $specialPageFactory;
174 * Add all items from $values into the result
175 * @param array &$result Output
176 * @param array $values Values to add
177 * @param string[] $flags The names of boolean flags to mark this element
178 * @param string|null $name If given, name of the value
180 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
181 foreach ( $values as $val ) {
182 if ( $val instanceof Title ) {
183 $v = [];
184 ApiQueryBase::addTitleInfo( $v, $val );
185 } elseif ( $name !== null ) {
186 $v = [ $name => $val ];
187 } else {
188 $v = $val;
190 foreach ( $flags as $flag ) {
191 $v[$flag] = true;
193 $result[] = $v;
198 * @param ApiBase $dbSource Module implementing getDB().
199 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
200 * @param int $flags Zero or more flags like DISABLE_GENERATORS
201 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
202 * @since 1.21 accepts $flags instead of two boolean values
204 public function __construct( ApiBase $dbSource, $flags = 0, $defaultNamespace = NS_MAIN ) {
205 parent::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
206 $this->mDbSource = $dbSource;
207 $this->mAllowGenerator = ( $flags & self::DISABLE_GENERATORS ) == 0;
208 $this->mDefaultNamespace = $defaultNamespace;
210 $this->mParams = $this->extractRequestParams();
211 $this->mResolveRedirects = $this->mParams['redirects'];
212 $this->mConvertTitles = $this->mParams['converttitles'];
214 // Needs service injection - T283314
215 $services = MediaWikiServices::getInstance();
216 $this->contentLanguage = $services->getContentLanguage();
217 $this->linkCache = $services->getLinkCache();
218 $this->namespaceInfo = $services->getNamespaceInfo();
219 $this->genderCache = $services->getGenderCache();
220 $this->linkBatchFactory = $services->getLinkBatchFactory();
221 $this->titleFactory = $services->getTitleFactory();
222 $this->languageConverter = $services->getLanguageConverterFactory()
223 ->getLanguageConverter( $this->contentLanguage );
224 $this->specialPageFactory = $services->getSpecialPageFactory();
228 * In case execute() is not called, call this method to mark all relevant parameters as used
229 * This prevents unused parameters from being reported as warnings
231 public function executeDryRun() {
232 $this->executeInternal( true );
236 * Populate the PageSet from the request parameters.
238 public function execute() {
239 $this->executeInternal( false );
243 * Populate the PageSet from the request parameters.
244 * @param bool $isDryRun If true, instantiates generator, but only to mark
245 * relevant parameters as used
247 private function executeInternal( $isDryRun ) {
248 $generatorName = $this->mAllowGenerator ? $this->mParams['generator'] : null;
249 if ( isset( $generatorName ) ) {
250 $dbSource = $this->mDbSource;
251 if ( !$dbSource instanceof ApiQuery ) {
252 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
253 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
255 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
256 if ( $generator === null ) {
257 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
259 if ( !$generator instanceof ApiQueryGeneratorBase ) {
260 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
262 // Create a temporary pageset to store generator's output,
263 // add any additional fields generator may need, and execute pageset to populate titles/pageids
264 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
265 $tmpPageSet = new ApiPageSet( $dbSource, self::DISABLE_GENERATORS );
266 $generator->setGeneratorMode( $tmpPageSet );
267 $this->mCacheMode = $generator->getCacheMode( $generator->extractRequestParams() );
269 if ( !$isDryRun ) {
270 $generator->requestExtraData( $tmpPageSet );
272 $tmpPageSet->executeInternal( $isDryRun );
274 // populate this pageset with the generator output
275 if ( !$isDryRun ) {
276 $generator->executeGenerator( $this );
278 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable T240141
279 $this->getHookRunner()->onAPIQueryGeneratorAfterExecute( $generator, $this );
280 } else {
281 // Prevent warnings from being reported on these parameters
282 $main = $this->getMain();
283 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
284 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
288 if ( !$isDryRun ) {
289 $this->resolvePendingRedirects();
291 } else {
292 // Only one of the titles/pageids/revids is allowed at the same time
293 $dataSource = null;
294 if ( isset( $this->mParams['titles'] ) ) {
295 $dataSource = 'titles';
297 if ( isset( $this->mParams['pageids'] ) ) {
298 if ( isset( $dataSource ) ) {
299 $this->dieWithError(
301 'apierror-invalidparammix-cannotusewith',
302 $this->encodeParamName( 'pageids' ),
303 $this->encodeParamName( $dataSource )
305 'multisource'
308 $dataSource = 'pageids';
310 if ( isset( $this->mParams['revids'] ) ) {
311 if ( isset( $dataSource ) ) {
312 $this->dieWithError(
314 'apierror-invalidparammix-cannotusewith',
315 $this->encodeParamName( 'revids' ),
316 $this->encodeParamName( $dataSource )
318 'multisource'
321 $dataSource = 'revids';
324 if ( !$isDryRun ) {
325 // Populate page information with the original user input
326 switch ( $dataSource ) {
327 case 'titles':
328 $this->initFromTitles( $this->mParams['titles'] );
329 break;
330 case 'pageids':
331 $this->initFromPageIds( $this->mParams['pageids'] );
332 break;
333 case 'revids':
334 if ( $this->mResolveRedirects ) {
335 $this->addWarning( 'apiwarn-redirectsandrevids' );
337 $this->mResolveRedirects = false;
338 $this->initFromRevIDs( $this->mParams['revids'] );
339 break;
340 default:
341 // Do nothing - some queries do not need any of the data sources.
342 break;
349 * Check whether this PageSet is resolving redirects
350 * @return bool
352 public function isResolvingRedirects() {
353 return $this->mResolveRedirects;
357 * Return the parameter name that is the source of data for this PageSet
359 * If multiple source parameters are specified (e.g. titles and pageids),
360 * one will be named arbitrarily.
362 * @return string|null
364 public function getDataSource() {
365 if ( $this->mAllowGenerator && isset( $this->mParams['generator'] ) ) {
366 return 'generator';
368 if ( isset( $this->mParams['titles'] ) ) {
369 return 'titles';
371 if ( isset( $this->mParams['pageids'] ) ) {
372 return 'pageids';
374 if ( isset( $this->mParams['revids'] ) ) {
375 return 'revids';
378 return null;
382 * Request an additional field from the page table.
383 * Must be called before execute()
384 * @param string $fieldName
386 public function requestField( $fieldName ) {
387 $this->mRequestedPageFields[$fieldName] = null;
391 * Get the value of a custom field previously requested through
392 * requestField()
393 * @param string $fieldName
394 * @return mixed Field value
396 public function getCustomField( $fieldName ) {
397 return $this->mRequestedPageFields[$fieldName];
401 * Get the fields that have to be queried from the page table:
402 * the ones requested through requestField() and a few basic ones
403 * we always need
404 * @return string[] Array of field names
406 public function getPageTableFields() {
407 // Ensure we get minimum required fields
408 // DON'T change this order
409 $pageFlds = [
410 'page_namespace' => null,
411 'page_title' => null,
412 'page_id' => null,
415 if ( $this->mResolveRedirects ) {
416 $pageFlds['page_is_redirect'] = null;
419 $pageFlds['page_content_model'] = null;
421 if ( $this->getConfig()->get( MainConfigNames::PageLanguageUseDB ) ) {
422 $pageFlds['page_lang'] = null;
425 foreach ( LinkCache::getSelectFields() as $field ) {
426 $pageFlds[$field] = null;
429 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields );
431 return array_keys( $pageFlds );
435 * Returns an array [ns][dbkey] => page_id for all requested titles.
436 * page_id is a unique negative number in case title was not found.
437 * Invalid titles will also have negative page IDs and will be in namespace 0
438 * @return array
440 public function getAllTitlesByNamespace() {
441 return $this->mAllPages;
445 * All existing and missing pages including redirects.
446 * Does not include special pages, interwiki links, and invalid titles.
447 * If redirects are resolved, both the redirect and the target will be included here.
449 * @deprecated since 1.37, use getPages() instead.
450 * @return Title[]
452 public function getTitles() {
453 return $this->mTitles;
457 * All existing and missing pages including redirects.
458 * Does not include special pages, interwiki links, and invalid titles.
459 * If redirects are resolved, both the redirect and the target will be included here.
461 * @since 1.37
462 * @return PageIdentity[]
464 public function getPages(): array {
465 return $this->mTitles;
469 * Returns the number of unique pages (not revisions) in the set.
470 * @return int
472 public function getTitleCount() {
473 return count( $this->mTitles );
477 * Returns an array [ns][dbkey] => page_id for all good titles.
478 * @return array
480 public function getGoodTitlesByNamespace() {
481 return $this->mGoodPages;
485 * Title objects that were found in the database, including redirects.
486 * If redirects are resolved, this will include existing redirect targets.
487 * @deprecated since 1.37, use getGoodPages() instead.
488 * @return Title[] Array page_id (int) => Title (obj)
490 public function getGoodTitles() {
491 return $this->mGoodTitles;
495 * Pages that were found in the database, including redirects.
496 * If redirects are resolved, this will include existing redirect targets.
497 * @since 1.37
498 * @return PageIdentity[] Array page_id (int) => PageIdentity (obj)
500 public function getGoodPages(): array {
501 return $this->mGoodTitles;
505 * Returns the number of found unique pages (not revisions) in the set.
506 * @return int
508 public function getGoodTitleCount() {
509 return count( $this->mGoodTitles );
513 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
514 * fake_page_id is a unique negative number.
515 * @return array
517 public function getMissingTitlesByNamespace() {
518 return $this->mMissingPages;
522 * Title objects that were NOT found in the database.
523 * The array's index will be negative for each item.
524 * If redirects are resolved, this will include missing redirect targets.
525 * @deprecated since 1.37, use getMissingPages instead.
526 * @return Title[]
528 public function getMissingTitles() {
529 return $this->mMissingTitles;
533 * Pages that were NOT found in the database.
534 * The array's index will be negative for each item.
535 * If redirects are resolved, this will include missing redirect targets.
536 * @since 1.37
537 * @return PageIdentity[]
539 public function getMissingPages(): array {
540 return $this->mMissingTitles;
544 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
545 * @return array
547 public function getGoodAndMissingTitlesByNamespace() {
548 return $this->mGoodAndMissingPages;
552 * Title objects for good and missing titles.
553 * @deprecated since 1.37, use getGoodAndMissingPages() instead.
554 * @return Title[]
556 public function getGoodAndMissingTitles() {
557 return $this->mGoodTitles + $this->mMissingTitles;
561 * Pages for good and missing titles.
562 * @since 1.37
563 * @return PageIdentity[]
565 public function getGoodAndMissingPages(): array {
566 return $this->mGoodTitles + $this->mMissingTitles;
570 * Titles that were deemed invalid by Title::newFromText()
571 * The array's index will be unique and negative for each item
572 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
574 public function getInvalidTitlesAndReasons() {
575 return $this->mInvalidTitles;
579 * Page IDs that were not found in the database
580 * @return int[] Array of page IDs
582 public function getMissingPageIDs() {
583 return $this->mMissingPageIDs;
587 * Get a list of redirect resolutions - maps a title to its redirect
588 * target.
589 * @deprecated since 1.37, use getRedirectTargets instead.
590 * @return Title[]
592 public function getRedirectTitles() {
593 return $this->mRedirectTitles;
597 * Get a list of redirect resolutions - maps a title to its redirect
598 * target.
599 * @since 1.37
600 * @return LinkTarget[]
602 public function getRedirectTargets(): array {
603 return $this->mRedirectTitles;
607 * Get a list of redirect resolutions - maps a title to its redirect
608 * target. Includes generator data for redirect source when available.
609 * @param ApiResult|null $result
610 * @return string[][]
611 * @since 1.21
613 public function getRedirectTitlesAsResult( $result = null ) {
614 $values = [];
615 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
616 $r = [
617 'from' => strval( $titleStrFrom ),
618 'to' => $titleTo->getPrefixedText(),
620 if ( $titleTo->hasFragment() ) {
621 $r['tofragment'] = $titleTo->getFragment();
623 if ( $titleTo->isExternal() ) {
624 $r['tointerwiki'] = $titleTo->getInterwiki();
626 if ( isset( $this->mResolvedRedirectTitles[$titleStrFrom] ) ) {
627 $titleFrom = $this->mResolvedRedirectTitles[$titleStrFrom];
628 $ns = $titleFrom->getNamespace();
629 $dbkey = $titleFrom->getDBkey();
630 if ( isset( $this->mGeneratorData[$ns][$dbkey] ) ) {
631 $r = array_merge( $this->mGeneratorData[$ns][$dbkey], $r );
635 $values[] = $r;
637 if ( $values && $result ) {
638 ApiResult::setIndexedTagName( $values, 'r' );
641 return $values;
645 * Get a list of title normalizations - maps a title to its normalized
646 * version.
647 * @return string[] Array of raw_prefixed_title (string) => prefixed_title (string)
649 public function getNormalizedTitles() {
650 return $this->mNormalizedTitles;
654 * Get a list of title normalizations - maps a title to its normalized
655 * version in the form of result array.
656 * @param ApiResult|null $result
657 * @return string[][]
658 * @since 1.21
660 public function getNormalizedTitlesAsResult( $result = null ) {
661 $values = [];
662 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
663 $encode = $this->contentLanguage->normalize( $rawTitleStr ) !== $rawTitleStr;
664 $values[] = [
665 'fromencoded' => $encode,
666 'from' => $encode ? rawurlencode( $rawTitleStr ) : $rawTitleStr,
667 'to' => $titleStr
670 if ( $values && $result ) {
671 ApiResult::setIndexedTagName( $values, 'n' );
674 return $values;
678 * Get a list of title conversions - maps a title to its converted
679 * version.
680 * @return string[] Array of raw_prefixed_title (string) => prefixed_title (string)
682 public function getConvertedTitles() {
683 return $this->mConvertedTitles;
687 * Get a list of title conversions - maps a title to its converted
688 * version as a result array.
689 * @param ApiResult|null $result
690 * @return string[][] Array of (from, to) strings
691 * @since 1.21
693 public function getConvertedTitlesAsResult( $result = null ) {
694 $values = [];
695 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
696 $values[] = [
697 'from' => $rawTitleStr,
698 'to' => $titleStr
701 if ( $values && $result ) {
702 ApiResult::setIndexedTagName( $values, 'c' );
705 return $values;
709 * Get a list of interwiki titles - maps a title to its interwiki
710 * prefix.
711 * @return string[] Array of raw_prefixed_title (string) => interwiki_prefix (string)
713 public function getInterwikiTitles() {
714 return $this->mInterwikiTitles;
718 * Get a list of interwiki titles - maps a title to its interwiki
719 * prefix as result.
720 * @param ApiResult|null $result
721 * @param bool $iwUrl
722 * @return string[][]
723 * @since 1.21
725 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
726 $values = [];
727 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
728 $item = [
729 'title' => $rawTitleStr,
730 'iw' => $interwikiStr,
732 if ( $iwUrl ) {
733 $title = $this->titleFactory->newFromText( $rawTitleStr );
734 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT );
736 $values[] = $item;
738 if ( $values && $result ) {
739 ApiResult::setIndexedTagName( $values, 'i' );
742 return $values;
746 * Get an array of invalid/special/missing titles.
748 * @param string[] $invalidChecks List of types of invalid titles to include.
749 * Recognized values are:
750 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
751 * - special: Titles from $this->getSpecialTitles()
752 * - missingIds: ids from $this->getMissingPageIDs()
753 * - missingRevIds: ids from $this->getMissingRevisionIDs()
754 * - missingTitles: Titles from $this->getMissingTitles()
755 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
756 * @return array Array suitable for inclusion in the response
757 * @since 1.23
759 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
760 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
762 $result = [];
763 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
764 self::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
766 if ( in_array( 'special', $invalidChecks ) ) {
767 $known = [];
768 $unknown = [];
769 foreach ( $this->getSpecialTitles() as $title ) {
770 if ( $title->isKnown() ) {
771 $known[] = $title;
772 } else {
773 $unknown[] = $title;
776 self::addValues( $result, $unknown, [ 'special', 'missing' ] );
777 self::addValues( $result, $known, [ 'special' ] );
779 if ( in_array( 'missingIds', $invalidChecks ) ) {
780 self::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
782 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
783 self::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
785 if ( in_array( 'missingTitles', $invalidChecks ) ) {
786 $known = [];
787 $unknown = [];
788 foreach ( $this->getMissingTitles() as $title ) {
789 if ( $title->isKnown() ) {
790 $known[] = $title;
791 } else {
792 $unknown[] = $title;
795 self::addValues( $result, $unknown, [ 'missing' ] );
796 self::addValues( $result, $known, [ 'missing', 'known' ] );
798 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
799 self::addValues( $result, $this->getInterwikiTitlesAsResult() );
802 return $result;
806 * Get the list of valid revision IDs (requested with the revids= parameter)
807 * @return int[] Array of revID (int) => pageID (int)
809 public function getRevisionIDs() {
810 return $this->mGoodRevIDs;
814 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
815 * @return int[] Array of revID (int) => pageID (int)
817 public function getLiveRevisionIDs() {
818 return $this->mLiveRevIDs;
822 * Get the list of revision IDs that were associated with deleted titles.
823 * @return int[] Array of revID (int) => pageID (int)
825 public function getDeletedRevisionIDs() {
826 return $this->mDeletedRevIDs;
830 * Revision IDs that were not found in the database
831 * @return int[] Array of revision IDs
833 public function getMissingRevisionIDs() {
834 return $this->mMissingRevIDs;
838 * Revision IDs that were not found in the database as result array.
839 * @param ApiResult|null $result
840 * @return int[][]
841 * @since 1.21
843 public function getMissingRevisionIDsAsResult( $result = null ) {
844 $values = [];
845 foreach ( $this->getMissingRevisionIDs() as $revid ) {
846 $values[$revid] = [
847 'revid' => $revid,
848 'missing' => true,
851 if ( $values && $result ) {
852 ApiResult::setIndexedTagName( $values, 'rev' );
855 return $values;
859 * Get the list of titles with negative namespace
860 * @deprecated since 1.37, use getSpecialPages() instead.
861 * @return Title[]
863 public function getSpecialTitles() {
864 return $this->mSpecialTitles;
868 * Get the list of pages with negative namespace
869 * @since 1.37
870 * @return PageReference[]
872 public function getSpecialPages(): array {
873 return $this->mSpecialTitles;
877 * Returns the number of revisions (requested with revids= parameter).
878 * @return int Number of revisions.
880 public function getRevisionCount() {
881 return count( $this->getRevisionIDs() );
885 * Populate this PageSet
886 * @param string[]|LinkTarget[]|PageReference[] $titles
888 public function populateFromTitles( $titles ) {
889 $this->initFromTitles( $titles );
893 * Populate this PageSet from a list of page IDs
894 * @param int[] $pageIDs
896 public function populateFromPageIDs( $pageIDs ) {
897 $this->initFromPageIds( $pageIDs );
901 * Populate this PageSet from a rowset returned from the database
903 * Note that the query result must include the columns returned by
904 * $this->getPageTableFields().
906 * @param IDatabase $db
907 * @param IResultWrapper $queryResult
909 public function populateFromQueryResult( $db, $queryResult ) {
910 $this->initFromQueryResult( $queryResult );
914 * Populate this PageSet from a list of revision IDs
915 * @param int[] $revIDs Array of revision IDs
917 public function populateFromRevisionIDs( $revIDs ) {
918 $this->initFromRevIDs( $revIDs );
922 * Extract all requested fields from the row received from the database
923 * @param stdClass $row Result row
925 public function processDbRow( $row ) {
926 // Store Title object in various data structures
927 $title = $this->titleFactory->newFromRow( $row );
929 $this->linkCache->addGoodLinkObjFromRow( $title, $row );
931 $pageId = (int)$row->page_id;
932 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
933 $this->mTitles[] = $title;
935 if ( $this->mResolveRedirects && $row->page_is_redirect == '1' ) {
936 $this->mPendingRedirectIDs[$pageId] = $title;
937 } else {
938 $this->mGoodPages[$row->page_namespace][$row->page_title] = $pageId;
939 $this->mGoodAndMissingPages[$row->page_namespace][$row->page_title] = $pageId;
940 $this->mGoodTitles[$pageId] = $title;
943 foreach ( $this->mRequestedPageFields as $fieldName => &$fieldValues ) {
944 $fieldValues[$pageId] = $row->$fieldName;
949 * This method populates internal variables with page information
950 * based on the given array of title strings.
952 * Steps:
953 * #1 For each title, get data from `page` table
954 * #2 If page was not found in the DB, store it as missing
956 * Additionally, when resolving redirects:
957 * #3 If no more redirects left, stop.
958 * #4 For each redirect, get its target from the `redirect` table.
959 * #5 Substitute the original LinkBatch object with the new list
960 * #6 Repeat from step #1
962 * @param string[]|LinkTarget[]|PageReference[] $titles
964 private function initFromTitles( $titles ) {
965 // Get validated and normalized title objects
966 $linkBatch = $this->processTitlesArray( $titles );
967 if ( $linkBatch->isEmpty() ) {
968 // There might be special-page redirects
969 $this->resolvePendingRedirects();
970 return;
973 $db = $this->getDB();
975 // Get pageIDs data from the `page` table
976 $res = $db->newSelectQueryBuilder()
977 ->select( $this->getPageTableFields() )
978 ->from( 'page' )
979 ->where( $linkBatch->constructSet( 'page', $db ) )
980 ->caller( __METHOD__ )
981 ->fetchResultSet();
983 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
984 $this->initFromQueryResult( $res, $linkBatch->data, true ); // process Titles
986 // Resolve any found redirects
987 $this->resolvePendingRedirects();
991 * Does the same as initFromTitles(), but is based on page IDs instead
992 * @param int[] $pageids
993 * @param bool $filterIds Whether the IDs need filtering
995 private function initFromPageIds( $pageids, $filterIds = true ) {
996 if ( !$pageids ) {
997 return;
1000 $pageids = array_map( 'intval', $pageids ); // paranoia
1001 $remaining = array_fill_keys( $pageids, true );
1003 if ( $filterIds ) {
1004 $pageids = $this->filterIDs( [ [ 'page', 'page_id' ] ], $pageids );
1007 $res = null;
1008 if ( $pageids ) {
1009 $db = $this->getDB();
1011 // Get pageIDs data from the `page` table
1012 $res = $db->newSelectQueryBuilder()
1013 ->select( $this->getPageTableFields() )
1014 ->from( 'page' )
1015 ->where( [ 'page_id' => $pageids ] )
1016 ->caller( __METHOD__ )
1017 ->fetchResultSet();
1020 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
1022 // Resolve any found redirects
1023 $this->resolvePendingRedirects();
1027 * Iterate through the result of the query on 'page' table,
1028 * and for each row create and store title object and save any extra fields requested.
1029 * @param IResultWrapper|null $res DB Query result
1030 * @param array|null &$remaining Array of either pageID or ns/title elements (optional).
1031 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
1032 * @param bool|null $processTitles Must be provided together with $remaining.
1033 * If true, treat $remaining as an array of [ns][title]
1034 * If false, treat it as an array of [pageIDs]
1036 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
1037 if ( $remaining !== null && $processTitles === null ) {
1038 ApiBase::dieDebug( __METHOD__, 'Missing $processTitles parameter when $remaining is provided' );
1041 $usernames = [];
1042 if ( $res ) {
1043 foreach ( $res as $row ) {
1044 $pageId = (int)$row->page_id;
1046 // Remove found page from the list of remaining items
1047 if ( $remaining ) {
1048 if ( $processTitles ) {
1049 unset( $remaining[$row->page_namespace][$row->page_title] );
1050 } else {
1051 unset( $remaining[$pageId] );
1055 // Store any extra fields requested by modules
1056 $this->processDbRow( $row );
1058 // Need gender information
1059 if ( $this->namespaceInfo->hasGenderDistinction( $row->page_namespace ) ) {
1060 $usernames[] = $row->page_title;
1065 if ( $remaining ) {
1066 // Any items left in the $remaining list are added as missing
1067 if ( $processTitles ) {
1068 // The remaining titles in $remaining are non-existent pages
1069 foreach ( $remaining as $ns => $dbkeys ) {
1070 foreach ( $dbkeys as $dbkey => $_ ) {
1071 $title = $this->titleFactory->makeTitle( $ns, $dbkey );
1072 $this->linkCache->addBadLinkObj( $title );
1073 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
1074 $this->mMissingPages[$ns][$dbkey] = $this->mFakePageId;
1075 $this->mGoodAndMissingPages[$ns][$dbkey] = $this->mFakePageId;
1076 $this->mMissingTitles[$this->mFakePageId] = $title;
1077 $this->mFakePageId--;
1078 $this->mTitles[] = $title;
1080 // need gender information
1081 if ( $this->namespaceInfo->hasGenderDistinction( $ns ) ) {
1082 $usernames[] = $dbkey;
1086 } else {
1087 // The remaining pageids do not exist
1088 if ( !$this->mMissingPageIDs ) {
1089 $this->mMissingPageIDs = array_keys( $remaining );
1090 } else {
1091 $this->mMissingPageIDs = array_merge( $this->mMissingPageIDs, array_keys( $remaining ) );
1096 // Get gender information
1097 $this->genderCache->doQuery( $usernames, __METHOD__ );
1101 * Does the same as initFromTitles(), but is based on revision IDs
1102 * instead
1103 * @param int[] $revids Array of revision IDs
1105 private function initFromRevIDs( $revids ) {
1106 if ( !$revids ) {
1107 return;
1110 $revids = array_map( 'intval', $revids ); // paranoia
1111 $db = $this->getDB();
1112 $pageids = [];
1113 $remaining = array_fill_keys( $revids, true );
1115 $revids = $this->filterIDs( [ [ 'revision', 'rev_id' ], [ 'archive', 'ar_rev_id' ] ], $revids );
1116 $goodRemaining = array_fill_keys( $revids, true );
1118 if ( $revids ) {
1119 $fields = [ 'rev_id', 'rev_page' ];
1121 // Get pageIDs data from the `page` table
1122 $res = $db->newSelectQueryBuilder()
1123 ->select( $fields )
1124 ->from( 'page' )
1125 ->where( [ 'rev_id' => $revids ] )
1126 ->join( 'revision', null, [ 'rev_page = page_id' ] )
1127 ->caller( __METHOD__ )
1128 ->fetchResultSet();
1129 foreach ( $res as $row ) {
1130 $revid = (int)$row->rev_id;
1131 $pageid = (int)$row->rev_page;
1132 $this->mGoodRevIDs[$revid] = $pageid;
1133 $this->mLiveRevIDs[$revid] = $pageid;
1134 $pageids[$pageid] = '';
1135 unset( $remaining[$revid] );
1136 unset( $goodRemaining[$revid] );
1140 // Populate all the page information
1141 $this->initFromPageIds( array_keys( $pageids ), false );
1143 // If the user can see deleted revisions, pull out the corresponding
1144 // titles from the archive table and include them too. We ignore
1145 // ar_page_id because deleted revisions are tied by title, not page_id.
1146 if ( $goodRemaining &&
1147 $this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
1149 $res = $db->newSelectQueryBuilder()
1150 ->select( [ 'ar_rev_id', 'ar_namespace', 'ar_title' ] )
1151 ->from( 'archive' )
1152 ->where( [ 'ar_rev_id' => array_keys( $goodRemaining ) ] )
1153 ->caller( __METHOD__ )
1154 ->fetchResultSet();
1156 $titles = [];
1157 foreach ( $res as $row ) {
1158 $revid = (int)$row->ar_rev_id;
1159 $titles[$revid] = $this->titleFactory->makeTitle( $row->ar_namespace, $row->ar_title );
1160 unset( $remaining[$revid] );
1163 $this->initFromTitles( $titles );
1165 foreach ( $titles as $revid => $title ) {
1166 $ns = $title->getNamespace();
1167 $dbkey = $title->getDBkey();
1169 // Handle converted titles
1170 if ( !isset( $this->mAllPages[$ns][$dbkey] ) &&
1171 isset( $this->mConvertedTitles[$title->getPrefixedText()] )
1173 $title = $this->titleFactory->newFromText( $this->mConvertedTitles[$title->getPrefixedText()] );
1174 $ns = $title->getNamespace();
1175 $dbkey = $title->getDBkey();
1178 if ( isset( $this->mAllPages[$ns][$dbkey] ) ) {
1179 $this->mGoodRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
1180 $this->mDeletedRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
1181 } else {
1182 $remaining[$revid] = true;
1187 $this->mMissingRevIDs = array_keys( $remaining );
1191 * Resolve any redirects in the result if redirect resolution was
1192 * requested. This function is called repeatedly until all redirects
1193 * have been resolved.
1195 private function resolvePendingRedirects() {
1196 if ( $this->mResolveRedirects ) {
1197 $db = $this->getDB();
1199 // Repeat until all redirects have been resolved
1200 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
1201 while ( $this->mPendingRedirectIDs || $this->mPendingRedirectSpecialPages ) {
1202 // Resolve redirects by querying the pagelinks table, and repeat the process
1203 // Create a new linkBatch object for the next pass
1204 $linkBatch = $this->loadRedirectTargets();
1206 if ( $linkBatch->isEmpty() ) {
1207 break;
1210 $set = $linkBatch->constructSet( 'page', $db );
1211 if ( $set === false ) {
1212 break;
1215 // Get pageIDs data from the `page` table
1216 $res = $db->newSelectQueryBuilder()
1217 ->select( $this->getPageTableFields() )
1218 ->from( 'page' )
1219 ->where( $set )
1220 ->caller( __METHOD__ )
1221 ->fetchResultSet();
1223 // Hack: get the ns:titles stored in [ns => array(titles)] format
1224 $this->initFromQueryResult( $res, $linkBatch->data, true );
1230 * Get the targets of the pending redirects from the database
1232 * Also creates entries in the redirect table for redirects that don't
1233 * have one.
1234 * @return LinkBatch
1236 private function loadRedirectTargets() {
1237 $titlesToResolve = [];
1238 $db = $this->getDB();
1240 if ( $this->mPendingRedirectIDs ) {
1241 $res = $db->newSelectQueryBuilder()
1242 ->select( [
1243 'rd_from',
1244 'rd_namespace',
1245 'rd_fragment',
1246 'rd_interwiki',
1247 'rd_title'
1249 ->from( 'redirect' )
1250 ->where( [ 'rd_from' => array_keys( $this->mPendingRedirectIDs ) ] )
1251 ->caller( __METHOD__ )
1252 ->fetchResultSet();
1254 foreach ( $res as $row ) {
1255 $rdfrom = (int)$row->rd_from;
1256 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
1257 $to = $this->titleFactory->makeTitle(
1258 $row->rd_namespace,
1259 $row->rd_title,
1260 $row->rd_fragment ?? '',
1261 $row->rd_interwiki ?? ''
1263 $this->mResolvedRedirectTitles[$from] = $this->mPendingRedirectIDs[$rdfrom];
1264 unset( $this->mPendingRedirectIDs[$rdfrom] );
1265 if ( $to->isExternal() ) {
1266 $this->mInterwikiTitles[$to->getPrefixedText()] = $to->getInterwiki();
1267 } elseif ( !isset( $this->mAllPages[$to->getNamespace()][$to->getDBkey()] )
1268 && !( $this->mConvertTitles && isset( $this->mConvertedTitles[$to->getPrefixedText()] ) )
1270 $titlesToResolve[] = $to;
1272 $this->mRedirectTitles[$from] = $to;
1276 if ( $this->mPendingRedirectSpecialPages ) {
1277 foreach ( $this->mPendingRedirectSpecialPages as [ $from, $to ] ) {
1278 /** @var Title $from */
1279 $fromKey = $from->getPrefixedText();
1280 $this->mResolvedRedirectTitles[$fromKey] = $from;
1281 $this->mRedirectTitles[$fromKey] = $to;
1282 if ( $to->isExternal() ) {
1283 $this->mInterwikiTitles[$to->getPrefixedText()] = $to->getInterwiki();
1284 } elseif ( !isset( $this->mAllPages[$to->getNamespace()][$to->getDBkey()] ) ) {
1285 $titlesToResolve[] = $to;
1288 $this->mPendingRedirectSpecialPages = [];
1290 // Set private caching since we don't know what criteria the
1291 // special pages used to decide on these redirects.
1292 $this->mCacheMode = 'private';
1295 return $this->processTitlesArray( $titlesToResolve );
1299 * Get the cache mode for the data generated by this module.
1300 * All PageSet users should take into account whether this returns a more-restrictive
1301 * cache mode than the using module itself. For possible return values and other
1302 * details about cache modes, see ApiMain::setCacheMode()
1304 * Public caching will only be allowed if *all* the modules that supply
1305 * data for a given request return a cache mode of public.
1307 * @param array|null $params
1308 * @return string
1309 * @since 1.21
1311 public function getCacheMode( $params = null ) {
1312 return $this->mCacheMode;
1316 * Given an array of title strings, convert them into Title objects.
1317 * Alternatively, an array of Title objects may be given.
1318 * This method validates access rights for the title,
1319 * and appends normalization values to the output.
1321 * @param string[]|LinkTarget[]|PageReference[] $titles
1322 * @return LinkBatch
1324 private function processTitlesArray( $titles ) {
1325 $linkBatch = $this->linkBatchFactory->newLinkBatch();
1327 /** @var Title[] $titleObjects */
1328 $titleObjects = [];
1329 foreach ( $titles as $index => $title ) {
1330 if ( is_string( $title ) ) {
1331 try {
1332 /** @var Title $titleObj */
1333 $titleObj = $this->titleFactory->newFromTextThrow( $title, $this->mDefaultNamespace );
1334 } catch ( MalformedTitleException $ex ) {
1335 // Handle invalid titles gracefully
1336 if ( !isset( $this->mAllPages[0][$title] ) ) {
1337 $this->mAllPages[0][$title] = $this->mFakePageId;
1338 $this->mInvalidTitles[$this->mFakePageId] = [
1339 'title' => $title,
1340 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1342 $this->mFakePageId--;
1344 continue; // There's nothing else we can do
1346 } elseif ( $title instanceof LinkTarget ) {
1347 $titleObj = $this->titleFactory->newFromLinkTarget( $title );
1348 } else {
1349 $titleObj = $this->titleFactory->newFromPageReference( $title );
1352 $titleObjects[$index] = $titleObj;
1355 // Get gender information
1356 $this->genderCache->doTitlesArray( $titleObjects, __METHOD__ );
1358 foreach ( $titleObjects as $index => $titleObj ) {
1359 $title = is_string( $titles[$index] ) ? $titles[$index] : false;
1360 $unconvertedTitle = $titleObj->getPrefixedText();
1361 $titleWasConverted = false;
1362 if ( $titleObj->isExternal() ) {
1363 // This title is an interwiki link.
1364 $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki();
1365 } else {
1366 // Variants checking
1367 if (
1368 $this->mConvertTitles
1369 && $this->languageConverter->hasVariants()
1370 && !$titleObj->exists()
1372 // ILanguageConverter::findVariantLink will modify titleText and
1373 // titleObj into the canonical variant if possible
1374 $titleText = $title !== false ? $title : $titleObj->getPrefixedText();
1375 $this->languageConverter->findVariantLink( $titleText, $titleObj );
1376 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1379 if ( $titleObj->getNamespace() < 0 ) {
1380 // Handle Special and Media pages
1381 $titleObj = $titleObj->fixSpecialName();
1382 $ns = $titleObj->getNamespace();
1383 $dbkey = $titleObj->getDBkey();
1384 if ( !isset( $this->mAllSpecials[$ns][$dbkey] ) ) {
1385 $this->mAllSpecials[$ns][$dbkey] = $this->mFakePageId;
1386 $target = null;
1387 if ( $ns === NS_SPECIAL && $this->mResolveRedirects ) {
1388 $special = $this->specialPageFactory->getPage( $dbkey );
1389 if ( $special instanceof RedirectSpecialArticle ) {
1390 // Only RedirectSpecialArticle is intended to redirect to an article, other kinds of
1391 // RedirectSpecialPage are probably applying weird URL parameters we don't want to
1392 // handle.
1393 $context = new DerivativeContext( $this );
1394 $context->setTitle( $titleObj );
1395 $context->setRequest( new FauxRequest );
1396 $special->setContext( $context );
1397 [ /* $alias */, $subpage ] = $this->specialPageFactory->resolveAlias( $dbkey );
1398 $target = $special->getRedirect( $subpage );
1401 if ( $target ) {
1402 $this->mPendingRedirectSpecialPages[$dbkey] = [ $titleObj, $target ];
1403 } else {
1404 $this->mSpecialTitles[$this->mFakePageId] = $titleObj;
1405 $this->mFakePageId--;
1408 } else {
1409 // Regular page
1410 $linkBatch->addObj( $titleObj );
1414 // Make sure we remember the original title that was
1415 // given to us. This way the caller can correlate new
1416 // titles with the originally requested when e.g. the
1417 // namespace is localized or the capitalization is
1418 // different
1419 if ( $titleWasConverted ) {
1420 $this->mConvertedTitles[$unconvertedTitle] = $titleObj->getPrefixedText();
1421 // In this case the page can't be Special.
1422 if ( $title !== false && $title !== $unconvertedTitle ) {
1423 $this->mNormalizedTitles[$title] = $unconvertedTitle;
1425 } elseif ( $title !== false && $title !== $titleObj->getPrefixedText() ) {
1426 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
1430 return $linkBatch;
1434 * Set data for a title.
1436 * This data may be extracted into an ApiResult using
1437 * self::populateGeneratorData. This should generally be limited to
1438 * data that is likely to be particularly useful to end users rather than
1439 * just being a dump of everything returned in non-generator mode.
1441 * Redirects here will *not* be followed, even if 'redirects' was
1442 * specified, since in the case of multiple redirects we can't know which
1443 * source's data to use on the target.
1445 * @param PageReference|LinkTarget $title
1446 * @param array $data
1448 public function setGeneratorData( $title, array $data ) {
1449 $ns = $title->getNamespace();
1450 $dbkey = $title->getDBkey();
1451 $this->mGeneratorData[$ns][$dbkey] = $data;
1455 * Controls how generator data about a redirect source is merged into
1456 * the generator data for the redirect target. When not set no data
1457 * is merged. Note that if multiple titles redirect to the same target
1458 * the order of operations is undefined.
1460 * Example to include generated data from redirect in target, prefering
1461 * the data generated for the destination when there is a collision:
1462 * @code
1463 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1464 * return $current + $new;
1465 * } );
1466 * @endcode
1468 * @param callable|null $callable Recieves two array arguments, first the
1469 * generator data for the redirect target and second the generator data
1470 * for the redirect source. Returns the resulting generator data to use
1471 * for the redirect target.
1473 public function setRedirectMergePolicy( $callable ) {
1474 $this->mRedirectMergePolicy = $callable;
1478 * Resolve the title a redirect points to.
1480 * Will follow sequential redirects to find the final page. In
1481 * the case of a redirect cycle the original page will be returned.
1482 * self::resolvePendingRedirects must be executed before calling
1483 * this method.
1485 * @param Title $titleFrom A title from $this->mResolvedRedirectTitles
1486 * @return Title
1488 private function resolveRedirectTitleDest( Title $titleFrom ): Title {
1489 $seen = [];
1490 $dest = $titleFrom;
1491 while ( isset( $this->mRedirectTitles[$dest->getPrefixedText()] ) ) {
1492 $dest = $this->mRedirectTitles[$dest->getPrefixedText()];
1493 if ( isset( $seen[$dest->getPrefixedText()] ) ) {
1494 return $titleFrom;
1496 $seen[$dest->getPrefixedText()] = true;
1498 return $dest;
1502 * Populate the generator data for all titles in the result
1504 * The page data may be inserted into an ApiResult object or into an
1505 * associative array. The $path parameter specifies the path within the
1506 * ApiResult or array to find the "pages" node.
1508 * The "pages" node itself must be an associative array mapping the page ID
1509 * or fake page ID values returned by this pageset (see
1510 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1511 * associative arrays of page data. Each of those subarrays will have the
1512 * data from self::setGeneratorData() merged in.
1514 * Data that was set by self::setGeneratorData() for pages not in the
1515 * "pages" node will be ignored.
1517 * @param ApiResult|array &$result
1518 * @param array $path
1519 * @return bool Whether the data fit
1521 public function populateGeneratorData( &$result, array $path = [] ) {
1522 if ( $result instanceof ApiResult ) {
1523 $data = $result->getResultData( $path );
1524 if ( $data === null ) {
1525 return true;
1527 } else {
1528 $data = &$result;
1529 foreach ( $path as $key ) {
1530 if ( !isset( $data[$key] ) ) {
1531 // Path isn't in $result, so nothing to add, so everything
1532 // "fits"
1533 return true;
1535 $data = &$data[$key];
1538 foreach ( $this->mGeneratorData as $ns => $dbkeys ) {
1539 if ( $ns === NS_SPECIAL ) {
1540 $pages = [];
1541 foreach ( $this->mSpecialTitles as $id => $title ) {
1542 $pages[$title->getDBkey()] = $id;
1544 } else {
1545 if ( !isset( $this->mAllPages[$ns] ) ) {
1546 // No known titles in the whole namespace. Skip it.
1547 continue;
1549 $pages = $this->mAllPages[$ns];
1551 foreach ( $dbkeys as $dbkey => $genData ) {
1552 if ( !isset( $pages[$dbkey] ) ) {
1553 // Unknown title. Forget it.
1554 continue;
1556 $pageId = $pages[$dbkey];
1557 if ( !isset( $data[$pageId] ) ) {
1558 // $pageId didn't make it into the result. Ignore it.
1559 continue;
1562 if ( $result instanceof ApiResult ) {
1563 $path2 = array_merge( $path, [ $pageId ] );
1564 foreach ( $genData as $key => $value ) {
1565 if ( !$result->addValue( $path2, $key, $value ) ) {
1566 return false;
1569 } else {
1570 $data[$pageId] = array_merge( $data[$pageId], $genData );
1575 // Merge data generated about redirect titles into the redirect destination
1576 if ( $this->mRedirectMergePolicy ) {
1577 foreach ( $this->mResolvedRedirectTitles as $titleFrom ) {
1578 $dest = $this->resolveRedirectTitleDest( $titleFrom );
1579 $fromNs = $titleFrom->getNamespace();
1580 $fromDBkey = $titleFrom->getDBkey();
1581 $toPageId = $dest->getArticleID();
1582 if ( isset( $data[$toPageId] ) &&
1583 isset( $this->mGeneratorData[$fromNs][$fromDBkey] )
1585 // It is necessary to set both $data and add to $result, if an ApiResult,
1586 // to ensure multiple redirects to the same destination are all merged.
1587 $data[$toPageId] = call_user_func(
1588 $this->mRedirectMergePolicy,
1589 $data[$toPageId],
1590 $this->mGeneratorData[$fromNs][$fromDBkey]
1592 if ( $result instanceof ApiResult &&
1593 !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE )
1595 return false;
1601 return true;
1605 * Get the database connection (read-only)
1606 * @return \Wikimedia\Rdbms\IReadableDatabase
1608 protected function getDB() {
1609 return $this->mDbSource->getDB();
1612 public function getAllowedParams( $flags = 0 ) {
1613 $result = [
1614 'titles' => [
1615 ParamValidator::PARAM_ISMULTI => true,
1616 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-titles',
1618 'pageids' => [
1619 ParamValidator::PARAM_TYPE => 'integer',
1620 ParamValidator::PARAM_ISMULTI => true,
1621 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-pageids',
1623 'revids' => [
1624 ParamValidator::PARAM_TYPE => 'integer',
1625 ParamValidator::PARAM_ISMULTI => true,
1626 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-revids',
1628 'generator' => [
1629 ParamValidator::PARAM_TYPE => null,
1630 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-generator',
1631 SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX => 'g',
1633 'redirects' => [
1634 ParamValidator::PARAM_DEFAULT => false,
1635 ApiBase::PARAM_HELP_MSG => $this->mAllowGenerator
1636 ? 'api-pageset-param-redirects-generator'
1637 : 'api-pageset-param-redirects-nogenerator',
1639 'converttitles' => [
1640 ParamValidator::PARAM_DEFAULT => false,
1641 ApiBase::PARAM_HELP_MSG => [
1642 'api-pageset-param-converttitles',
1643 [ Message::listParam( LanguageConverter::$languagesWithVariants, 'text' ) ],
1648 if ( !$this->mAllowGenerator ) {
1649 unset( $result['generator'] );
1650 } elseif ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
1651 $result['generator'][ParamValidator::PARAM_TYPE] = 'submodule';
1652 $result['generator'][SubmoduleDef::PARAM_SUBMODULE_MAP] = $this->getGenerators();
1655 return $result;
1658 public function handleParamNormalization( $paramName, $value, $rawValue ) {
1659 parent::handleParamNormalization( $paramName, $value, $rawValue );
1661 if ( $paramName === 'titles' ) {
1662 // For the 'titles' parameter, we want to split it like ApiBase would
1663 // and add any changed titles to $this->mNormalizedTitles
1664 $value = ParamValidator::explodeMultiValue( $value, self::LIMIT_SML2 + 1 );
1665 $l = count( $value );
1666 $rawValue = ParamValidator::explodeMultiValue( $rawValue, $l );
1667 for ( $i = 0; $i < $l; $i++ ) {
1668 if ( $value[$i] !== $rawValue[$i] ) {
1669 $this->mNormalizedTitles[$rawValue[$i]] = $value[$i];
1676 * Get an array of all available generators
1677 * @return string[]
1679 private function getGenerators() {
1680 if ( self::$generators === null ) {
1681 $query = $this->mDbSource;
1682 if ( !( $query instanceof ApiQuery ) ) {
1683 // If the parent container of this pageset is not ApiQuery,
1684 // we must create it to get module manager
1685 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1687 $gens = [];
1688 $prefix = $query->getModulePath() . '+';
1689 $mgr = $query->getModuleManager();
1690 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1691 if ( is_subclass_of( $class, ApiQueryGeneratorBase::class ) ) {
1692 $gens[$name] = $prefix . $name;
1695 ksort( $gens );
1696 self::$generators = $gens;
1699 return self::$generators;