5 * Created on Sep 24, 2006
7 * Copyright © 2006, 2013 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
26 use MediaWiki\MediaWikiServices
;
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
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.
40 * @since 1.21 derives from ApiBase instead of ApiQueryBase
42 class ApiPageSet
extends ApiBase
{
44 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
47 const DISABLE_GENERATORS
= 1;
51 private $mResolveRedirects;
52 private $mConvertTitles;
53 private $mAllowGenerator;
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 = [];
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 = [];
82 private $mDefaultNamespace = NS_MAIN
;
83 /** @var callable|null */
84 private $mRedirectMergePolicy;
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
93 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
94 foreach ( $values as $val ) {
95 if ( $val instanceof Title
) {
97 ApiQueryBase
::addTitleInfo( $v, $val );
98 } elseif ( $name !== null ) {
99 $v = [ $name => $val ];
103 foreach ( $flags as $flag ) {
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
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;
123 $this->mParams
= $this->extractRequestParams();
124 $this->mResolveRedirects
= $this->mParams
['redirects'];
125 $this->mConvertTitles
= $this->mParams
['converttitles'];
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
132 public function executeDryRun() {
133 $this->executeInternal( true );
137 * Populate the PageSet from the request parameters.
139 public function execute() {
140 $this->executeInternal( false );
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
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' );
156 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
157 if ( $generator === null ) {
158 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
160 if ( !$generator instanceof ApiQueryGeneratorBase
) {
161 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
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() );
170 $generator->requestExtraData( $tmpPageSet );
172 $tmpPageSet->executeInternal( $isDryRun );
174 // populate this pageset with the generator output
176 $generator->executeGenerator( $this );
177 Hooks
::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$this ] );
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 ) );
187 $this->resolvePendingRedirects();
190 // Only one of the titles/pageids/revids is allowed at the same time
192 if ( isset( $this->mParams
['titles'] ) ) {
193 $dataSource = 'titles';
195 if ( isset( $this->mParams
['pageids'] ) ) {
196 if ( isset( $dataSource ) ) {
199 'apierror-invalidparammix-cannotusewith',
200 $this->encodeParamName( 'pageids' ),
201 $this->encodeParamName( $dataSource )
206 $dataSource = 'pageids';
208 if ( isset( $this->mParams
['revids'] ) ) {
209 if ( isset( $dataSource ) ) {
212 'apierror-invalidparammix-cannotusewith',
213 $this->encodeParamName( 'revids' ),
214 $this->encodeParamName( $dataSource )
219 $dataSource = 'revids';
223 // Populate page information with the original user input
224 switch ( $dataSource ) {
226 $this->initFromTitles( $this->mParams
['titles'] );
229 $this->initFromPageIds( $this->mParams
['pageids'] );
232 if ( $this->mResolveRedirects
) {
233 $this->addWarning( 'apiwarn-redirectsandrevids' );
235 $this->mResolveRedirects
= false;
236 $this->initFromRevIDs( $this->mParams
['revids'] );
239 // Do nothing - some queries do not need any of the data sources.
247 * Check whether this PageSet is resolving redirects
250 public function isResolvingRedirects() {
251 return $this->mResolveRedirects
;
255 * Return the parameter name that is the source of data for this PageSet
257 * If multiple source parameters are specified (e.g. titles and pageids),
258 * one will be named arbitrarily.
260 * @return string|null
262 public function getDataSource() {
263 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
266 if ( isset( $this->mParams
['titles'] ) ) {
269 if ( isset( $this->mParams
['pageids'] ) ) {
272 if ( isset( $this->mParams
['revids'] ) ) {
280 * Request an additional field from the page table.
281 * Must be called before execute()
282 * @param string $fieldName Field name
284 public function requestField( $fieldName ) {
285 $this->mRequestedPageFields
[$fieldName] = null;
289 * Get the value of a custom field previously requested through
291 * @param string $fieldName Field name
292 * @return mixed Field value
294 public function getCustomField( $fieldName ) {
295 return $this->mRequestedPageFields
[$fieldName];
299 * Get the fields that have to be queried from the page table:
300 * the ones requested through requestField() and a few basic ones
302 * @return array Array of field names
304 public function getPageTableFields() {
305 // Ensure we get minimum required fields
306 // DON'T change this order
308 'page_namespace' => null,
309 'page_title' => null,
313 if ( $this->mResolveRedirects
) {
314 $pageFlds['page_is_redirect'] = null;
317 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
318 $pageFlds['page_content_model'] = null;
321 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
322 $pageFlds['page_lang'] = null;
325 foreach ( LinkCache
::getSelectFields() as $field ) {
326 $pageFlds[$field] = null;
329 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
331 return array_keys( $pageFlds );
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
340 public function getAllTitlesByNamespace() {
341 return $this->mAllPages
;
345 * All Title objects provided.
348 public function getTitles() {
349 return $this->mTitles
;
353 * Returns the number of unique pages (not revisions) in the set.
356 public function getTitleCount() {
357 return count( $this->mTitles
);
361 * Returns an array [ns][dbkey] => page_id for all good titles.
364 public function getGoodTitlesByNamespace() {
365 return $this->mGoodPages
;
369 * Title objects that were found in the database.
370 * @return Title[] Array page_id (int) => Title (obj)
372 public function getGoodTitles() {
373 return $this->mGoodTitles
;
377 * Returns the number of found unique pages (not revisions) in the set.
380 public function getGoodTitleCount() {
381 return count( $this->mGoodTitles
);
385 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
386 * fake_page_id is a unique negative number.
389 public function getMissingTitlesByNamespace() {
390 return $this->mMissingPages
;
394 * Title objects that were NOT found in the database.
395 * The array's index will be negative for each item
398 public function getMissingTitles() {
399 return $this->mMissingTitles
;
403 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
406 public function getGoodAndMissingTitlesByNamespace() {
407 return $this->mGoodAndMissingPages
;
411 * Title objects for good and missing titles.
414 public function getGoodAndMissingTitles() {
415 return $this->mGoodTitles +
$this->mMissingTitles
;
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)
424 public function getInvalidTitles() {
425 wfDeprecated( __METHOD__
, '1.26' );
426 return array_map( function ( $t ) {
428 }, $this->mInvalidTitles
);
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
436 public function getInvalidTitlesAndReasons() {
437 return $this->mInvalidTitles
;
441 * Page IDs that were not found in the database
442 * @return array Array of page IDs
444 public function getMissingPageIDs() {
445 return $this->mMissingPageIDs
;
449 * Get a list of redirect resolutions - maps a title to its redirect
450 * target, as an array of output-ready arrays
453 public function getRedirectTitles() {
454 return $this->mRedirectTitles
;
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
464 public function getRedirectTitlesAsResult( $result = null ) {
466 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
468 'from' => strval( $titleStrFrom ),
469 'to' => $titleTo->getPrefixedText(),
471 if ( $titleTo->hasFragment() ) {
472 $r['tofragment'] = $titleTo->getFragment();
474 if ( $titleTo->isExternal() ) {
475 $r['tointerwiki'] = $titleTo->getInterwiki();
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 );
488 if ( !empty( $values ) && $result ) {
489 ApiResult
::setIndexedTagName( $values, 'r' );
496 * Get a list of title normalizations - maps a title to its normalized
498 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
500 public function getNormalizedTitles() {
501 return $this->mNormalizedTitles
;
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)
511 public function getNormalizedTitlesAsResult( $result = null ) {
515 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
516 $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr );
518 'fromencoded' => $encode,
519 'from' => $encode ?
rawurlencode( $rawTitleStr ) : $rawTitleStr,
523 if ( !empty( $values ) && $result ) {
524 ApiResult
::setIndexedTagName( $values, 'n' );
531 * Get a list of title conversions - maps a title to its converted
533 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
535 public function getConvertedTitles() {
536 return $this->mConvertedTitles
;
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
546 public function getConvertedTitlesAsResult( $result = null ) {
548 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
550 'from' => $rawTitleStr,
554 if ( !empty( $values ) && $result ) {
555 ApiResult
::setIndexedTagName( $values, 'c' );
562 * Get a list of interwiki titles - maps a title to its interwiki
564 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
566 public function getInterwikiTitles() {
567 return $this->mInterwikiTitles
;
571 * Get a list of interwiki titles - maps a title to its interwiki
573 * @param ApiResult $result
575 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
578 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
580 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
582 'title' => $rawTitleStr,
583 'iw' => $interwikiStr,
586 $title = Title
::newFromText( $rawTitleStr );
587 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
591 if ( !empty( $values ) && $result ) {
592 ApiResult
::setIndexedTagName( $values, 'i' );
599 * Get an array of invalid/special/missing titles.
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
612 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
613 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
616 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
617 self
::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
619 if ( in_array( 'special', $invalidChecks ) ) {
622 foreach ( $this->getSpecialTitles() as $title ) {
623 if ( $title->isKnown() ) {
629 self
::addValues( $result, $unknown, [ 'special', 'missing' ] );
630 self
::addValues( $result, $known, [ 'special' ] );
632 if ( in_array( 'missingIds', $invalidChecks ) ) {
633 self
::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
635 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
636 self
::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
638 if ( in_array( 'missingTitles', $invalidChecks ) ) {
641 foreach ( $this->getMissingTitles() as $title ) {
642 if ( $title->isKnown() ) {
648 self
::addValues( $result, $unknown, [ 'missing' ] );
649 self
::addValues( $result, $known, [ 'missing', 'known' ] );
651 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
652 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
659 * Get the list of valid revision IDs (requested with the revids= parameter)
660 * @return array Array of revID (int) => pageID (int)
662 public function getRevisionIDs() {
663 return $this->mGoodRevIDs
;
667 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
668 * @return array Array of revID (int) => pageID (int)
670 public function getLiveRevisionIDs() {
671 return $this->mLiveRevIDs
;
675 * Get the list of revision IDs that were associated with deleted titles.
676 * @return array Array of revID (int) => pageID (int)
678 public function getDeletedRevisionIDs() {
679 return $this->mDeletedRevIDs
;
683 * Revision IDs that were not found in the database
684 * @return array Array of revision IDs
686 public function getMissingRevisionIDs() {
687 return $this->mMissingRevIDs
;
691 * Revision IDs that were not found in the database as result array.
692 * @param ApiResult $result
693 * @return array Array of revision IDs
696 public function getMissingRevisionIDsAsResult( $result = null ) {
698 foreach ( $this->getMissingRevisionIDs() as $revid ) {
703 if ( !empty( $values ) && $result ) {
704 ApiResult
::setIndexedTagName( $values, 'rev' );
711 * Get the list of titles with negative namespace
714 public function getSpecialTitles() {
715 return $this->mSpecialTitles
;
719 * Returns the number of revisions (requested with revids= parameter).
720 * @return int Number of revisions.
722 public function getRevisionCount() {
723 return count( $this->getRevisionIDs() );
727 * Populate this PageSet from a list of Titles
728 * @param array $titles Array of Title objects
730 public function populateFromTitles( $titles ) {
731 $this->initFromTitles( $titles );
735 * Populate this PageSet from a list of page IDs
736 * @param array $pageIDs Array of page IDs
738 public function populateFromPageIDs( $pageIDs ) {
739 $this->initFromPageIds( $pageIDs );
743 * Populate this PageSet from a rowset returned from the database
745 * Note that the query result must include the columns returned by
746 * $this->getPageTableFields().
748 * @param IDatabase $db
749 * @param ResultWrapper $queryResult Query result object
751 public function populateFromQueryResult( $db, $queryResult ) {
752 $this->initFromQueryResult( $queryResult );
756 * Populate this PageSet from a list of revision IDs
757 * @param array $revIDs Array of revision IDs
759 public function populateFromRevisionIDs( $revIDs ) {
760 $this->initFromRevIDs( $revIDs );
764 * Extract all requested fields from the row received from the database
765 * @param stdClass $row Result row
767 public function processDbRow( $row ) {
768 // Store Title object in various data structures
769 $title = Title
::newFromRow( $row );
771 LinkCache
::singleton()->addGoodLinkObjFromRow( $title, $row );
773 $pageId = intval( $row->page_id
);
774 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
775 $this->mTitles
[] = $title;
777 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
778 $this->mPendingRedirectIDs
[$pageId] = $title;
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;
785 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
786 $fieldValues[$pageId] = $row->$fieldName;
791 * This method populates internal variables with page information
792 * based on the given array of title strings.
795 * #1 For each title, get data from `page` table
796 * #2 If page was not found in the DB, store it as missing
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
804 * @param array $titles Array of Title objects or strings
806 private function initFromTitles( $titles ) {
807 // Get validated and normalized title objects
808 $linkBatch = $this->processTitlesArray( $titles );
809 if ( $linkBatch->isEmpty() ) {
813 $db = $this->getDB();
814 $set = $linkBatch->constructSet( 'page', $db );
816 // Get pageIDs data from the `page` table
817 $res = $db->select( 'page', $this->getPageTableFields(), $set,
820 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
821 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
823 // Resolve any found redirects
824 $this->resolvePendingRedirects();
828 * Does the same as initFromTitles(), but is based on page IDs instead
829 * @param array $pageids Array of page IDs
831 private function initFromPageIds( $pageids ) {
836 $pageids = array_map( 'intval', $pageids ); // paranoia
837 $remaining = array_flip( $pageids );
839 $pageids = self
::getPositiveIntegers( $pageids );
842 if ( !empty( $pageids ) ) {
844 'page_id' => $pageids
846 $db = $this->getDB();
848 // Get pageIDs data from the `page` table
849 $res = $db->select( 'page', $this->getPageTableFields(), $set,
853 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
855 // Resolve any found redirects
856 $this->resolvePendingRedirects();
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]
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' );
876 foreach ( $res as $row ) {
877 $pageId = intval( $row->page_id
);
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
] );
884 unset( $remaining[$pageId] );
888 // Store any extra fields requested by modules
889 $this->processDbRow( $row );
891 // Need gender information
892 if ( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
893 $usernames[] = $row->page_title
;
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;
914 // need gender information
915 if ( MWNamespace
::hasGenderDistinction( $ns ) ) {
916 $usernames[] = $dbkey;
921 // The remaining pageids do not exist
922 if ( !$this->mMissingPageIDs
) {
923 $this->mMissingPageIDs
= array_keys( $remaining );
925 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
930 // Get gender information
931 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
932 $genderCache->doQuery( $usernames, __METHOD__
);
936 * Does the same as initFromTitles(), but is based on revision IDs
938 * @param array $revids Array of revision IDs
940 private function initFromRevIDs( $revids ) {
945 $revids = array_map( 'intval', $revids ); // paranoia
946 $db = $this->getDB();
948 $remaining = array_flip( $revids );
950 $revids = self
::getPositiveIntegers( $revids );
952 if ( !empty( $revids ) ) {
953 $tables = [ 'revision', 'page' ];
954 $fields = [ 'rev_id', 'rev_page' ];
955 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
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] );
969 $this->mMissingRevIDs
= array_keys( $remaining );
971 // Populate all the page information
972 $this->initFromPageIds( array_keys( $pageids ) );
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
];
983 $res = $db->select( $tables, $fields, $where, __METHOD__
);
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] );
991 $this->initFromTitles( $titles );
993 foreach ( $titles as $revid => $title ) {
994 $ns = $title->getNamespace();
995 $dbkey = $title->getDBkey();
997 // Handle converted titles
998 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
999 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
1001 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
1002 $ns = $title->getNamespace();
1003 $dbkey = $title->getDBkey();
1006 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
1007 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1008 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1010 $remaining[$revid] = true;
1014 $this->mMissingRevIDs
= array_keys( $remaining );
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.
1023 private function resolvePendingRedirects() {
1024 if ( $this->mResolveRedirects
) {
1025 $db = $this->getDB();
1026 $pageFlds = $this->getPageTableFields();
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();
1035 if ( $linkBatch->isEmpty() ) {
1039 $set = $linkBatch->constructSet( 'page', $db );
1040 if ( $set === false ) {
1044 // Get pageIDs data from the `page` table
1045 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1047 // Hack: get the ns:titles stored in [ns => array(titles)] format
1048 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1054 * Get the targets of the pending redirects from the database
1056 * Also creates entries in the redirect table for redirects that don't
1060 private function getRedirectTargets() {
1061 $lb = new LinkBatch();
1062 $db = $this->getDB();
1072 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ],
1075 foreach ( $res as $row ) {
1076 $rdfrom = intval( $row->rd_from
);
1077 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1078 $to = Title
::makeTitle(
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
);
1091 $this->mRedirectTitles
[$from] = $to;
1094 if ( $this->mPendingRedirectIDs
) {
1095 // We found pages that aren't in the redirect table
1097 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1098 $page = WikiPage
::factory( $title );
1099 $rt = $page->insertRedirect();
1101 // What the hell. Let's just ignore this
1105 $from = $title->getPrefixedText();
1106 $this->mResolvedRedirectTitles
[$from] = $title;
1107 $this->mRedirectTitles
[$from] = $rt;
1108 unset( $this->mPendingRedirectIDs
[$id] );
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()
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.
1124 * @param array|null $params
1128 public function getCacheMode( $params = null ) {
1129 return $this->mCacheMode
;
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.
1138 * @param array $titles Array of Title objects or strings
1141 private function processTitlesArray( $titles ) {
1143 $linkBatch = new LinkBatch();
1145 foreach ( $titles as $title ) {
1146 if ( is_string( $title ) ) {
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
] = [
1154 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1156 $this->mFakePageId
--;
1157 continue; // There's nothing else we can do
1162 $unconvertedTitle = $titleObj->getPrefixedText();
1163 $titleWasConverted = false;
1164 if ( $titleObj->isExternal() ) {
1165 // This title is an interwiki link.
1166 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1168 // Variants checking
1170 if ( $this->mConvertTitles
&&
1171 count( $wgContLang->getVariants() ) > 1 &&
1172 !$titleObj->exists()
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();
1181 if ( $titleObj->getNamespace() < 0 ) {
1182 // Handle Special and Media pages
1183 $titleObj = $titleObj->fixSpecialName();
1184 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1185 $this->mFakePageId
--;
1188 $linkBatch->addObj( $titleObj );
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
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;
1203 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1204 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1207 // Need gender information
1208 if ( MWNamespace
::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1209 $usernames[] = $titleObj->getText();
1212 // Get gender information
1213 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
1214 $genderCache->doQuery( $usernames, __METHOD__
);
1220 * Set data for a title.
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.
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.
1231 * @param Title $title
1232 * @param array $data
1234 public function setGeneratorData( Title
$title, array $data ) {
1235 $ns = $title->getNamespace();
1236 $dbkey = $title->getDBkey();
1237 $this->mGeneratorData
[$ns][$dbkey] = $data;
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.
1246 * Example to include generated data from redirect in target, prefering
1247 * the data generated for the destination when there is a collision:
1249 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1250 * return $current + $new;
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.
1259 public function setRedirectMergePolicy( $callable ) {
1260 $this->mRedirectMergePolicy
= $callable;
1264 * Populate the generator data for all titles in the result
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.
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.
1276 * Data that was set by self::setGeneratorData() for pages not in the
1277 * "pages" node will be ignored.
1279 * @param ApiResult|array &$result
1280 * @param array $path
1281 * @return bool Whether the data fit
1283 public function populateGeneratorData( &$result, array $path = [] ) {
1284 if ( $result instanceof ApiResult
) {
1285 $data = $result->getResultData( $path );
1286 if ( $data === null ) {
1291 foreach ( $path as $key ) {
1292 if ( !isset( $data[$key] ) ) {
1293 // Path isn't in $result, so nothing to add, so everything
1297 $data = &$data[$key];
1300 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1303 foreach ( $this->mSpecialTitles
as $id => $title ) {
1304 $pages[$title->getDBkey()] = $id;
1307 if ( !isset( $this->mAllPages
[$ns] ) ) {
1308 // No known titles in the whole namespace. Skip it.
1311 $pages = $this->mAllPages
[$ns];
1313 foreach ( $dbkeys as $dbkey => $genData ) {
1314 if ( !isset( $pages[$dbkey] ) ) {
1315 // Unknown title. Forget it.
1318 $pageId = $pages[$dbkey];
1319 if ( !isset( $data[$pageId] ) ) {
1320 // $pageId didn't make it into the result. Ignore it.
1324 if ( $result instanceof ApiResult
) {
1325 $path2 = array_merge( $path, [ $pageId ] );
1326 foreach ( $genData as $key => $value ) {
1327 if ( !$result->addValue( $path2, $key, $value ) ) {
1332 $data[$pageId] = array_merge( $data[$pageId], $genData );
1337 // Merge data generated about redirect titles into the redirect destination
1338 if ( $this->mRedirectMergePolicy
) {
1339 foreach ( $this->mResolvedRedirectTitles
as $titleFrom ) {
1341 while ( isset( $this->mRedirectTitles
[$dest->getPrefixedText()] ) ) {
1342 $dest = $this->mRedirectTitles
[$dest->getPrefixedText()];
1344 $fromNs = $titleFrom->getNamespace();
1345 $fromDBkey = $titleFrom->getDBkey();
1346 $toPageId = $dest->getArticleID();
1347 if ( isset( $data[$toPageId] ) &&
1348 isset( $this->mGeneratorData
[$fromNs][$fromDBkey] )
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
,
1355 $this->mGeneratorData
[$fromNs][$fromDBkey]
1357 if ( $result instanceof ApiResult
) {
1358 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult
::OVERRIDE
) ) {
1370 * Get the database connection (read-only)
1373 protected function getDB() {
1374 return $this->mDbSource
->getDB();
1378 * Returns the input array of integers with all values < 0 removed
1380 * @param array $array
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 ) {
1389 unset( $array[$i] );
1396 public function getAllowedParams( $flags = 0 ) {
1399 ApiBase
::PARAM_ISMULTI
=> true,
1400 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1403 ApiBase
::PARAM_TYPE
=> 'integer',
1404 ApiBase
::PARAM_ISMULTI
=> true,
1405 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1408 ApiBase
::PARAM_TYPE
=> 'integer',
1409 ApiBase
::PARAM_ISMULTI
=> true,
1410 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1413 ApiBase
::PARAM_TYPE
=> null,
1414 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1415 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'g',
1418 ApiBase
::PARAM_DFLT
=> false,
1419 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1420 ?
'api-pageset-param-redirects-generator'
1421 : 'api-pageset-param-redirects-nogenerator',
1423 'converttitles' => [
1424 ApiBase
::PARAM_DFLT
=> false,
1425 ApiBase
::PARAM_HELP_MSG
=> [
1426 'api-pageset-param-converttitles',
1427 [ Message
::listParam( LanguageConverter
::$languagesWithVariants, 'text' ) ],
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();
1442 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1443 parent
::handleParamNormalization( $paramName, $value, $rawValue );
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];
1459 private static $generators = null;
1462 * Get an array of all available generators
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' );
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;
1482 self
::$generators = $gens;
1485 return self
::$generators;