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
;
27 use Wikimedia\Rdbms\ResultWrapper
;
28 use Wikimedia\Rdbms\IDatabase
;
31 * This class contains a list of pages that the client has requested.
32 * Initially, when the client passes in titles=, pageids=, or revisions=
33 * parameter, an instance of the ApiPageSet class will normalize titles,
34 * determine if the pages/revisions exist, and prefetch any additional page
37 * When a generator is used, the result of the generator will become the input
38 * for the second instance of this class, and all subsequent actions will use
39 * the second instance for all their work.
42 * @since 1.21 derives from ApiBase instead of ApiQueryBase
44 class ApiPageSet
extends ApiBase
{
46 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
49 const DISABLE_GENERATORS
= 1;
53 private $mResolveRedirects;
54 private $mConvertTitles;
55 private $mAllowGenerator;
57 private $mAllPages = []; // [ns][dbkey] => page_id or negative when missing
58 private $mTitles = [];
59 private $mGoodAndMissingPages = []; // [ns][dbkey] => page_id or negative when missing
60 private $mGoodPages = []; // [ns][dbkey] => page_id
61 private $mGoodTitles = [];
62 private $mMissingPages = []; // [ns][dbkey] => fake page_id
63 private $mMissingTitles = [];
64 /** @var array [fake_page_id] => [ 'title' => $title, 'invalidreason' => $reason ] */
65 private $mInvalidTitles = [];
66 private $mMissingPageIDs = [];
67 private $mRedirectTitles = [];
68 private $mSpecialTitles = [];
69 private $mAllSpecials = []; // separate from mAllPages to avoid breaking getAllTitlesByNamespace()
70 private $mNormalizedTitles = [];
71 private $mInterwikiTitles = [];
73 private $mPendingRedirectIDs = [];
74 private $mResolvedRedirectTitles = [];
75 private $mConvertedTitles = [];
76 private $mGoodRevIDs = [];
77 private $mLiveRevIDs = [];
78 private $mDeletedRevIDs = [];
79 private $mMissingRevIDs = [];
80 private $mGeneratorData = []; // [ns][dbkey] => data array
81 private $mFakePageId = -1;
82 private $mCacheMode = 'public';
83 private $mRequestedPageFields = [];
85 private $mDefaultNamespace = NS_MAIN
;
86 /** @var callable|null */
87 private $mRedirectMergePolicy;
90 * Add all items from $values into the result
91 * @param array $result Output
92 * @param array $values Values to add
93 * @param string[] $flags The names of boolean flags to mark this element
94 * @param string $name If given, name of the value
96 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
97 foreach ( $values as $val ) {
98 if ( $val instanceof Title
) {
100 ApiQueryBase
::addTitleInfo( $v, $val );
101 } elseif ( $name !== null ) {
102 $v = [ $name => $val ];
106 foreach ( $flags as $flag ) {
114 * @param ApiBase $dbSource Module implementing getDB().
115 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
116 * @param int $flags Zero or more flags like DISABLE_GENERATORS
117 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
118 * @since 1.21 accepts $flags instead of two boolean values
120 public function __construct( ApiBase
$dbSource, $flags = 0, $defaultNamespace = NS_MAIN
) {
121 parent
::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
122 $this->mDbSource
= $dbSource;
123 $this->mAllowGenerator
= ( $flags & ApiPageSet
::DISABLE_GENERATORS
) == 0;
124 $this->mDefaultNamespace
= $defaultNamespace;
126 $this->mParams
= $this->extractRequestParams();
127 $this->mResolveRedirects
= $this->mParams
['redirects'];
128 $this->mConvertTitles
= $this->mParams
['converttitles'];
132 * In case execute() is not called, call this method to mark all relevant parameters as used
133 * This prevents unused parameters from being reported as warnings
135 public function executeDryRun() {
136 $this->executeInternal( true );
140 * Populate the PageSet from the request parameters.
142 public function execute() {
143 $this->executeInternal( false );
147 * Populate the PageSet from the request parameters.
148 * @param bool $isDryRun If true, instantiates generator, but only to mark
149 * relevant parameters as used
151 private function executeInternal( $isDryRun ) {
152 $generatorName = $this->mAllowGenerator ?
$this->mParams
['generator'] : null;
153 if ( isset( $generatorName ) ) {
154 $dbSource = $this->mDbSource
;
155 if ( !$dbSource instanceof ApiQuery
) {
156 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
157 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
159 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
160 if ( $generator === null ) {
161 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
163 if ( !$generator instanceof ApiQueryGeneratorBase
) {
164 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
166 // Create a temporary pageset to store generator's output,
167 // add any additional fields generator may need, and execute pageset to populate titles/pageids
168 $tmpPageSet = new ApiPageSet( $dbSource, ApiPageSet
::DISABLE_GENERATORS
);
169 $generator->setGeneratorMode( $tmpPageSet );
170 $this->mCacheMode
= $generator->getCacheMode( $generator->extractRequestParams() );
173 $generator->requestExtraData( $tmpPageSet );
175 $tmpPageSet->executeInternal( $isDryRun );
177 // populate this pageset with the generator output
179 $generator->executeGenerator( $this );
181 // Avoid PHP 7.1 warning of passing $this by reference
183 Hooks
::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$apiModule ] );
185 // Prevent warnings from being reported on these parameters
186 $main = $this->getMain();
187 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
188 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
193 $this->resolvePendingRedirects();
196 // Only one of the titles/pageids/revids is allowed at the same time
198 if ( isset( $this->mParams
['titles'] ) ) {
199 $dataSource = 'titles';
201 if ( isset( $this->mParams
['pageids'] ) ) {
202 if ( isset( $dataSource ) ) {
205 'apierror-invalidparammix-cannotusewith',
206 $this->encodeParamName( 'pageids' ),
207 $this->encodeParamName( $dataSource )
212 $dataSource = 'pageids';
214 if ( isset( $this->mParams
['revids'] ) ) {
215 if ( isset( $dataSource ) ) {
218 'apierror-invalidparammix-cannotusewith',
219 $this->encodeParamName( 'revids' ),
220 $this->encodeParamName( $dataSource )
225 $dataSource = 'revids';
229 // Populate page information with the original user input
230 switch ( $dataSource ) {
232 $this->initFromTitles( $this->mParams
['titles'] );
235 $this->initFromPageIds( $this->mParams
['pageids'] );
238 if ( $this->mResolveRedirects
) {
239 $this->addWarning( 'apiwarn-redirectsandrevids' );
241 $this->mResolveRedirects
= false;
242 $this->initFromRevIDs( $this->mParams
['revids'] );
245 // Do nothing - some queries do not need any of the data sources.
253 * Check whether this PageSet is resolving redirects
256 public function isResolvingRedirects() {
257 return $this->mResolveRedirects
;
261 * Return the parameter name that is the source of data for this PageSet
263 * If multiple source parameters are specified (e.g. titles and pageids),
264 * one will be named arbitrarily.
266 * @return string|null
268 public function getDataSource() {
269 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
272 if ( isset( $this->mParams
['titles'] ) ) {
275 if ( isset( $this->mParams
['pageids'] ) ) {
278 if ( isset( $this->mParams
['revids'] ) ) {
286 * Request an additional field from the page table.
287 * Must be called before execute()
288 * @param string $fieldName Field name
290 public function requestField( $fieldName ) {
291 $this->mRequestedPageFields
[$fieldName] = null;
295 * Get the value of a custom field previously requested through
297 * @param string $fieldName Field name
298 * @return mixed Field value
300 public function getCustomField( $fieldName ) {
301 return $this->mRequestedPageFields
[$fieldName];
305 * Get the fields that have to be queried from the page table:
306 * the ones requested through requestField() and a few basic ones
308 * @return array Array of field names
310 public function getPageTableFields() {
311 // Ensure we get minimum required fields
312 // DON'T change this order
314 'page_namespace' => null,
315 'page_title' => null,
319 if ( $this->mResolveRedirects
) {
320 $pageFlds['page_is_redirect'] = null;
323 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
324 $pageFlds['page_content_model'] = null;
327 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
328 $pageFlds['page_lang'] = null;
331 foreach ( LinkCache
::getSelectFields() as $field ) {
332 $pageFlds[$field] = null;
335 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
337 return array_keys( $pageFlds );
341 * Returns an array [ns][dbkey] => page_id for all requested titles.
342 * page_id is a unique negative number in case title was not found.
343 * Invalid titles will also have negative page IDs and will be in namespace 0
346 public function getAllTitlesByNamespace() {
347 return $this->mAllPages
;
351 * All Title objects provided.
354 public function getTitles() {
355 return $this->mTitles
;
359 * Returns the number of unique pages (not revisions) in the set.
362 public function getTitleCount() {
363 return count( $this->mTitles
);
367 * Returns an array [ns][dbkey] => page_id for all good titles.
370 public function getGoodTitlesByNamespace() {
371 return $this->mGoodPages
;
375 * Title objects that were found in the database.
376 * @return Title[] Array page_id (int) => Title (obj)
378 public function getGoodTitles() {
379 return $this->mGoodTitles
;
383 * Returns the number of found unique pages (not revisions) in the set.
386 public function getGoodTitleCount() {
387 return count( $this->mGoodTitles
);
391 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
392 * fake_page_id is a unique negative number.
395 public function getMissingTitlesByNamespace() {
396 return $this->mMissingPages
;
400 * Title objects that were NOT found in the database.
401 * The array's index will be negative for each item
404 public function getMissingTitles() {
405 return $this->mMissingTitles
;
409 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
412 public function getGoodAndMissingTitlesByNamespace() {
413 return $this->mGoodAndMissingPages
;
417 * Title objects for good and missing titles.
420 public function getGoodAndMissingTitles() {
421 return $this->mGoodTitles +
$this->mMissingTitles
;
425 * Titles that were deemed invalid by Title::newFromText()
426 * The array's index will be unique and negative for each item
427 * @deprecated since 1.26, use self::getInvalidTitlesAndReasons()
428 * @return string[] Array of strings (not Title objects)
430 public function getInvalidTitles() {
431 wfDeprecated( __METHOD__
, '1.26' );
432 return array_map( function ( $t ) {
434 }, $this->mInvalidTitles
);
438 * Titles that were deemed invalid by Title::newFromText()
439 * The array's index will be unique and negative for each item
440 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
442 public function getInvalidTitlesAndReasons() {
443 return $this->mInvalidTitles
;
447 * Page IDs that were not found in the database
448 * @return array Array of page IDs
450 public function getMissingPageIDs() {
451 return $this->mMissingPageIDs
;
455 * Get a list of redirect resolutions - maps a title to its redirect
456 * target, as an array of output-ready arrays
459 public function getRedirectTitles() {
460 return $this->mRedirectTitles
;
464 * Get a list of redirect resolutions - maps a title to its redirect
465 * target. Includes generator data for redirect source when available.
466 * @param ApiResult $result
467 * @return array Array of prefixed_title (string) => Title object
470 public function getRedirectTitlesAsResult( $result = null ) {
472 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
474 'from' => strval( $titleStrFrom ),
475 'to' => $titleTo->getPrefixedText(),
477 if ( $titleTo->hasFragment() ) {
478 $r['tofragment'] = $titleTo->getFragment();
480 if ( $titleTo->isExternal() ) {
481 $r['tointerwiki'] = $titleTo->getInterwiki();
483 if ( isset( $this->mResolvedRedirectTitles
[$titleStrFrom] ) ) {
484 $titleFrom = $this->mResolvedRedirectTitles
[$titleStrFrom];
485 $ns = $titleFrom->getNamespace();
486 $dbkey = $titleFrom->getDBkey();
487 if ( isset( $this->mGeneratorData
[$ns][$dbkey] ) ) {
488 $r = array_merge( $this->mGeneratorData
[$ns][$dbkey], $r );
494 if ( !empty( $values ) && $result ) {
495 ApiResult
::setIndexedTagName( $values, 'r' );
502 * Get a list of title normalizations - maps a title to its normalized
504 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
506 public function getNormalizedTitles() {
507 return $this->mNormalizedTitles
;
511 * Get a list of title normalizations - maps a title to its normalized
512 * version in the form of result array.
513 * @param ApiResult $result
514 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
517 public function getNormalizedTitlesAsResult( $result = null ) {
521 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
522 $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr );
524 'fromencoded' => $encode,
525 'from' => $encode ?
rawurlencode( $rawTitleStr ) : $rawTitleStr,
529 if ( !empty( $values ) && $result ) {
530 ApiResult
::setIndexedTagName( $values, 'n' );
537 * Get a list of title conversions - maps a title to its converted
539 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
541 public function getConvertedTitles() {
542 return $this->mConvertedTitles
;
546 * Get a list of title conversions - maps a title to its converted
547 * version as a result array.
548 * @param ApiResult $result
549 * @return array Array of (from, to) strings
552 public function getConvertedTitlesAsResult( $result = null ) {
554 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
556 'from' => $rawTitleStr,
560 if ( !empty( $values ) && $result ) {
561 ApiResult
::setIndexedTagName( $values, 'c' );
568 * Get a list of interwiki titles - maps a title to its interwiki
570 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
572 public function getInterwikiTitles() {
573 return $this->mInterwikiTitles
;
577 * Get a list of interwiki titles - maps a title to its interwiki
579 * @param ApiResult $result
581 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
584 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
586 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
588 'title' => $rawTitleStr,
589 'iw' => $interwikiStr,
592 $title = Title
::newFromText( $rawTitleStr );
593 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
597 if ( !empty( $values ) && $result ) {
598 ApiResult
::setIndexedTagName( $values, 'i' );
605 * Get an array of invalid/special/missing titles.
607 * @param array $invalidChecks List of types of invalid titles to include.
608 * Recognized values are:
609 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
610 * - special: Titles from $this->getSpecialTitles()
611 * - missingIds: ids from $this->getMissingPageIDs()
612 * - missingRevIds: ids from $this->getMissingRevisionIDs()
613 * - missingTitles: Titles from $this->getMissingTitles()
614 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
615 * @return array Array suitable for inclusion in the response
618 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
619 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
622 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
623 self
::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
625 if ( in_array( 'special', $invalidChecks ) ) {
628 foreach ( $this->getSpecialTitles() as $title ) {
629 if ( $title->isKnown() ) {
635 self
::addValues( $result, $unknown, [ 'special', 'missing' ] );
636 self
::addValues( $result, $known, [ 'special' ] );
638 if ( in_array( 'missingIds', $invalidChecks ) ) {
639 self
::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
641 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
642 self
::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
644 if ( in_array( 'missingTitles', $invalidChecks ) ) {
647 foreach ( $this->getMissingTitles() as $title ) {
648 if ( $title->isKnown() ) {
654 self
::addValues( $result, $unknown, [ 'missing' ] );
655 self
::addValues( $result, $known, [ 'missing', 'known' ] );
657 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
658 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
665 * Get the list of valid revision IDs (requested with the revids= parameter)
666 * @return array Array of revID (int) => pageID (int)
668 public function getRevisionIDs() {
669 return $this->mGoodRevIDs
;
673 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
674 * @return array Array of revID (int) => pageID (int)
676 public function getLiveRevisionIDs() {
677 return $this->mLiveRevIDs
;
681 * Get the list of revision IDs that were associated with deleted titles.
682 * @return array Array of revID (int) => pageID (int)
684 public function getDeletedRevisionIDs() {
685 return $this->mDeletedRevIDs
;
689 * Revision IDs that were not found in the database
690 * @return array Array of revision IDs
692 public function getMissingRevisionIDs() {
693 return $this->mMissingRevIDs
;
697 * Revision IDs that were not found in the database as result array.
698 * @param ApiResult $result
699 * @return array Array of revision IDs
702 public function getMissingRevisionIDsAsResult( $result = null ) {
704 foreach ( $this->getMissingRevisionIDs() as $revid ) {
709 if ( !empty( $values ) && $result ) {
710 ApiResult
::setIndexedTagName( $values, 'rev' );
717 * Get the list of titles with negative namespace
720 public function getSpecialTitles() {
721 return $this->mSpecialTitles
;
725 * Returns the number of revisions (requested with revids= parameter).
726 * @return int Number of revisions.
728 public function getRevisionCount() {
729 return count( $this->getRevisionIDs() );
733 * Populate this PageSet from a list of Titles
734 * @param array $titles Array of Title objects
736 public function populateFromTitles( $titles ) {
737 $this->initFromTitles( $titles );
741 * Populate this PageSet from a list of page IDs
742 * @param array $pageIDs Array of page IDs
744 public function populateFromPageIDs( $pageIDs ) {
745 $this->initFromPageIds( $pageIDs );
749 * Populate this PageSet from a rowset returned from the database
751 * Note that the query result must include the columns returned by
752 * $this->getPageTableFields().
754 * @param IDatabase $db
755 * @param ResultWrapper $queryResult Query result object
757 public function populateFromQueryResult( $db, $queryResult ) {
758 $this->initFromQueryResult( $queryResult );
762 * Populate this PageSet from a list of revision IDs
763 * @param array $revIDs Array of revision IDs
765 public function populateFromRevisionIDs( $revIDs ) {
766 $this->initFromRevIDs( $revIDs );
770 * Extract all requested fields from the row received from the database
771 * @param stdClass $row Result row
773 public function processDbRow( $row ) {
774 // Store Title object in various data structures
775 $title = Title
::newFromRow( $row );
777 LinkCache
::singleton()->addGoodLinkObjFromRow( $title, $row );
779 $pageId = intval( $row->page_id
);
780 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
781 $this->mTitles
[] = $title;
783 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
784 $this->mPendingRedirectIDs
[$pageId] = $title;
786 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
787 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
788 $this->mGoodTitles
[$pageId] = $title;
791 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
792 $fieldValues[$pageId] = $row->$fieldName;
797 * This method populates internal variables with page information
798 * based on the given array of title strings.
801 * #1 For each title, get data from `page` table
802 * #2 If page was not found in the DB, store it as missing
804 * Additionally, when resolving redirects:
805 * #3 If no more redirects left, stop.
806 * #4 For each redirect, get its target from the `redirect` table.
807 * #5 Substitute the original LinkBatch object with the new list
808 * #6 Repeat from step #1
810 * @param array $titles Array of Title objects or strings
812 private function initFromTitles( $titles ) {
813 // Get validated and normalized title objects
814 $linkBatch = $this->processTitlesArray( $titles );
815 if ( $linkBatch->isEmpty() ) {
819 $db = $this->getDB();
820 $set = $linkBatch->constructSet( 'page', $db );
822 // Get pageIDs data from the `page` table
823 $res = $db->select( 'page', $this->getPageTableFields(), $set,
826 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
827 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
829 // Resolve any found redirects
830 $this->resolvePendingRedirects();
834 * Does the same as initFromTitles(), but is based on page IDs instead
835 * @param array $pageids Array of page IDs
837 private function initFromPageIds( $pageids ) {
842 $pageids = array_map( 'intval', $pageids ); // paranoia
843 $remaining = array_flip( $pageids );
845 $pageids = self
::getPositiveIntegers( $pageids );
848 if ( !empty( $pageids ) ) {
850 'page_id' => $pageids
852 $db = $this->getDB();
854 // Get pageIDs data from the `page` table
855 $res = $db->select( 'page', $this->getPageTableFields(), $set,
859 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
861 // Resolve any found redirects
862 $this->resolvePendingRedirects();
866 * Iterate through the result of the query on 'page' table,
867 * and for each row create and store title object and save any extra fields requested.
868 * @param ResultWrapper $res DB Query result
869 * @param array $remaining Array of either pageID or ns/title elements (optional).
870 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
871 * @param bool $processTitles Must be provided together with $remaining.
872 * If true, treat $remaining as an array of [ns][title]
873 * If false, treat it as an array of [pageIDs]
875 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
876 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
877 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
882 foreach ( $res as $row ) {
883 $pageId = intval( $row->page_id
);
885 // Remove found page from the list of remaining items
886 if ( isset( $remaining ) ) {
887 if ( $processTitles ) {
888 unset( $remaining[$row->page_namespace
][$row->page_title
] );
890 unset( $remaining[$pageId] );
894 // Store any extra fields requested by modules
895 $this->processDbRow( $row );
897 // Need gender information
898 if ( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
899 $usernames[] = $row->page_title
;
904 if ( isset( $remaining ) ) {
905 // Any items left in the $remaining list are added as missing
906 if ( $processTitles ) {
907 // The remaining titles in $remaining are non-existent pages
908 $linkCache = LinkCache
::singleton();
909 foreach ( $remaining as $ns => $dbkeys ) {
910 foreach ( array_keys( $dbkeys ) as $dbkey ) {
911 $title = Title
::makeTitle( $ns, $dbkey );
912 $linkCache->addBadLinkObj( $title );
913 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
914 $this->mMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
915 $this->mGoodAndMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
916 $this->mMissingTitles
[$this->mFakePageId
] = $title;
917 $this->mFakePageId
--;
918 $this->mTitles
[] = $title;
920 // need gender information
921 if ( MWNamespace
::hasGenderDistinction( $ns ) ) {
922 $usernames[] = $dbkey;
927 // The remaining pageids do not exist
928 if ( !$this->mMissingPageIDs
) {
929 $this->mMissingPageIDs
= array_keys( $remaining );
931 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
936 // Get gender information
937 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
938 $genderCache->doQuery( $usernames, __METHOD__
);
942 * Does the same as initFromTitles(), but is based on revision IDs
944 * @param array $revids Array of revision IDs
946 private function initFromRevIDs( $revids ) {
951 $revids = array_map( 'intval', $revids ); // paranoia
952 $db = $this->getDB();
954 $remaining = array_flip( $revids );
956 $revids = self
::getPositiveIntegers( $revids );
958 if ( !empty( $revids ) ) {
959 $tables = [ 'revision', 'page' ];
960 $fields = [ 'rev_id', 'rev_page' ];
961 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
963 // Get pageIDs data from the `page` table
964 $res = $db->select( $tables, $fields, $where, __METHOD__
);
965 foreach ( $res as $row ) {
966 $revid = intval( $row->rev_id
);
967 $pageid = intval( $row->rev_page
);
968 $this->mGoodRevIDs
[$revid] = $pageid;
969 $this->mLiveRevIDs
[$revid] = $pageid;
970 $pageids[$pageid] = '';
971 unset( $remaining[$revid] );
975 $this->mMissingRevIDs
= array_keys( $remaining );
977 // Populate all the page information
978 $this->initFromPageIds( array_keys( $pageids ) );
980 // If the user can see deleted revisions, pull out the corresponding
981 // titles from the archive table and include them too. We ignore
982 // ar_page_id because deleted revisions are tied by title, not page_id.
983 if ( !empty( $this->mMissingRevIDs
) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
984 $remaining = array_flip( $this->mMissingRevIDs
);
985 $tables = [ 'archive' ];
986 $fields = [ 'ar_rev_id', 'ar_namespace', 'ar_title' ];
987 $where = [ 'ar_rev_id' => $this->mMissingRevIDs
];
989 $res = $db->select( $tables, $fields, $where, __METHOD__
);
991 foreach ( $res as $row ) {
992 $revid = intval( $row->ar_rev_id
);
993 $titles[$revid] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
994 unset( $remaining[$revid] );
997 $this->initFromTitles( $titles );
999 foreach ( $titles as $revid => $title ) {
1000 $ns = $title->getNamespace();
1001 $dbkey = $title->getDBkey();
1003 // Handle converted titles
1004 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
1005 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
1007 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
1008 $ns = $title->getNamespace();
1009 $dbkey = $title->getDBkey();
1012 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
1013 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1014 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1016 $remaining[$revid] = true;
1020 $this->mMissingRevIDs
= array_keys( $remaining );
1025 * Resolve any redirects in the result if redirect resolution was
1026 * requested. This function is called repeatedly until all redirects
1027 * have been resolved.
1029 private function resolvePendingRedirects() {
1030 if ( $this->mResolveRedirects
) {
1031 $db = $this->getDB();
1032 $pageFlds = $this->getPageTableFields();
1034 // Repeat until all redirects have been resolved
1035 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
1036 while ( $this->mPendingRedirectIDs
) {
1037 // Resolve redirects by querying the pagelinks table, and repeat the process
1038 // Create a new linkBatch object for the next pass
1039 $linkBatch = $this->getRedirectTargets();
1041 if ( $linkBatch->isEmpty() ) {
1045 $set = $linkBatch->constructSet( 'page', $db );
1046 if ( $set === false ) {
1050 // Get pageIDs data from the `page` table
1051 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1053 // Hack: get the ns:titles stored in [ns => array(titles)] format
1054 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1060 * Get the targets of the pending redirects from the database
1062 * Also creates entries in the redirect table for redirects that don't
1066 private function getRedirectTargets() {
1067 $titlesToResolve = [];
1068 $db = $this->getDB();
1078 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ],
1081 foreach ( $res as $row ) {
1082 $rdfrom = intval( $row->rd_from
);
1083 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1084 $to = Title
::makeTitle(
1090 $this->mResolvedRedirectTitles
[$from] = $this->mPendingRedirectIDs
[$rdfrom];
1091 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1092 if ( $to->isExternal() ) {
1093 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1094 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1095 $titlesToResolve[] = $to;
1097 $this->mRedirectTitles
[$from] = $to;
1100 if ( $this->mPendingRedirectIDs
) {
1101 // We found pages that aren't in the redirect table
1103 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1104 $page = WikiPage
::factory( $title );
1105 $rt = $page->insertRedirect();
1107 // What the hell. Let's just ignore this
1110 if ( $rt->isExternal() ) {
1111 $this->mInterwikiTitles
[$rt->getPrefixedText()] = $rt->getInterwiki();
1112 } elseif ( !isset( $this->mAllPages
[$rt->getNamespace()][$rt->getDBkey()] ) ) {
1113 $titlesToResolve[] = $rt;
1115 $from = $title->getPrefixedText();
1116 $this->mResolvedRedirectTitles
[$from] = $title;
1117 $this->mRedirectTitles
[$from] = $rt;
1118 unset( $this->mPendingRedirectIDs
[$id] );
1122 return $this->processTitlesArray( $titlesToResolve );
1126 * Get the cache mode for the data generated by this module.
1127 * All PageSet users should take into account whether this returns a more-restrictive
1128 * cache mode than the using module itself. For possible return values and other
1129 * details about cache modes, see ApiMain::setCacheMode()
1131 * Public caching will only be allowed if *all* the modules that supply
1132 * data for a given request return a cache mode of public.
1134 * @param array|null $params
1138 public function getCacheMode( $params = null ) {
1139 return $this->mCacheMode
;
1143 * Given an array of title strings, convert them into Title objects.
1144 * Alternatively, an array of Title objects may be given.
1145 * This method validates access rights for the title,
1146 * and appends normalization values to the output.
1148 * @param array $titles Array of Title objects or strings
1151 private function processTitlesArray( $titles ) {
1153 $linkBatch = new LinkBatch();
1155 foreach ( $titles as $title ) {
1156 if ( is_string( $title ) ) {
1158 $titleObj = Title
::newFromTextThrow( $title, $this->mDefaultNamespace
);
1159 } catch ( MalformedTitleException
$ex ) {
1160 // Handle invalid titles gracefully
1161 if ( !isset( $this->mAllPages
[0][$title] ) ) {
1162 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1163 $this->mInvalidTitles
[$this->mFakePageId
] = [
1165 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1167 $this->mFakePageId
--;
1169 continue; // There's nothing else we can do
1174 $unconvertedTitle = $titleObj->getPrefixedText();
1175 $titleWasConverted = false;
1176 if ( $titleObj->isExternal() ) {
1177 // This title is an interwiki link.
1178 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1180 // Variants checking
1182 if ( $this->mConvertTitles
&&
1183 count( $wgContLang->getVariants() ) > 1 &&
1184 !$titleObj->exists()
1186 // Language::findVariantLink will modify titleText and titleObj into
1187 // the canonical variant if possible
1188 $titleText = is_string( $title ) ?
$title : $titleObj->getPrefixedText();
1189 $wgContLang->findVariantLink( $titleText, $titleObj );
1190 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1193 if ( $titleObj->getNamespace() < 0 ) {
1194 // Handle Special and Media pages
1195 $titleObj = $titleObj->fixSpecialName();
1196 $ns = $titleObj->getNamespace();
1197 $dbkey = $titleObj->getDBkey();
1198 if ( !isset( $this->mAllSpecials
[$ns][$dbkey] ) ) {
1199 $this->mAllSpecials
[$ns][$dbkey] = $this->mFakePageId
;
1200 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1201 $this->mFakePageId
--;
1205 $linkBatch->addObj( $titleObj );
1209 // Make sure we remember the original title that was
1210 // given to us. This way the caller can correlate new
1211 // titles with the originally requested when e.g. the
1212 // namespace is localized or the capitalization is
1214 if ( $titleWasConverted ) {
1215 $this->mConvertedTitles
[$unconvertedTitle] = $titleObj->getPrefixedText();
1216 // In this case the page can't be Special.
1217 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1218 $this->mNormalizedTitles
[$title] = $unconvertedTitle;
1220 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1221 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1224 // Need gender information
1225 if ( MWNamespace
::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1226 $usernames[] = $titleObj->getText();
1229 // Get gender information
1230 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
1231 $genderCache->doQuery( $usernames, __METHOD__
);
1237 * Set data for a title.
1239 * This data may be extracted into an ApiResult using
1240 * self::populateGeneratorData. This should generally be limited to
1241 * data that is likely to be particularly useful to end users rather than
1242 * just being a dump of everything returned in non-generator mode.
1244 * Redirects here will *not* be followed, even if 'redirects' was
1245 * specified, since in the case of multiple redirects we can't know which
1246 * source's data to use on the target.
1248 * @param Title $title
1249 * @param array $data
1251 public function setGeneratorData( Title
$title, array $data ) {
1252 $ns = $title->getNamespace();
1253 $dbkey = $title->getDBkey();
1254 $this->mGeneratorData
[$ns][$dbkey] = $data;
1258 * Controls how generator data about a redirect source is merged into
1259 * the generator data for the redirect target. When not set no data
1260 * is merged. Note that if multiple titles redirect to the same target
1261 * the order of operations is undefined.
1263 * Example to include generated data from redirect in target, prefering
1264 * the data generated for the destination when there is a collision:
1266 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1267 * return $current + $new;
1271 * @param callable|null $callable Recieves two array arguments, first the
1272 * generator data for the redirect target and second the generator data
1273 * for the redirect source. Returns the resulting generator data to use
1274 * for the redirect target.
1276 public function setRedirectMergePolicy( $callable ) {
1277 $this->mRedirectMergePolicy
= $callable;
1281 * Populate the generator data for all titles in the result
1283 * The page data may be inserted into an ApiResult object or into an
1284 * associative array. The $path parameter specifies the path within the
1285 * ApiResult or array to find the "pages" node.
1287 * The "pages" node itself must be an associative array mapping the page ID
1288 * or fake page ID values returned by this pageset (see
1289 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1290 * associative arrays of page data. Each of those subarrays will have the
1291 * data from self::setGeneratorData() merged in.
1293 * Data that was set by self::setGeneratorData() for pages not in the
1294 * "pages" node will be ignored.
1296 * @param ApiResult|array &$result
1297 * @param array $path
1298 * @return bool Whether the data fit
1300 public function populateGeneratorData( &$result, array $path = [] ) {
1301 if ( $result instanceof ApiResult
) {
1302 $data = $result->getResultData( $path );
1303 if ( $data === null ) {
1308 foreach ( $path as $key ) {
1309 if ( !isset( $data[$key] ) ) {
1310 // Path isn't in $result, so nothing to add, so everything
1314 $data = &$data[$key];
1317 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1320 foreach ( $this->mSpecialTitles
as $id => $title ) {
1321 $pages[$title->getDBkey()] = $id;
1324 if ( !isset( $this->mAllPages
[$ns] ) ) {
1325 // No known titles in the whole namespace. Skip it.
1328 $pages = $this->mAllPages
[$ns];
1330 foreach ( $dbkeys as $dbkey => $genData ) {
1331 if ( !isset( $pages[$dbkey] ) ) {
1332 // Unknown title. Forget it.
1335 $pageId = $pages[$dbkey];
1336 if ( !isset( $data[$pageId] ) ) {
1337 // $pageId didn't make it into the result. Ignore it.
1341 if ( $result instanceof ApiResult
) {
1342 $path2 = array_merge( $path, [ $pageId ] );
1343 foreach ( $genData as $key => $value ) {
1344 if ( !$result->addValue( $path2, $key, $value ) ) {
1349 $data[$pageId] = array_merge( $data[$pageId], $genData );
1354 // Merge data generated about redirect titles into the redirect destination
1355 if ( $this->mRedirectMergePolicy
) {
1356 foreach ( $this->mResolvedRedirectTitles
as $titleFrom ) {
1358 while ( isset( $this->mRedirectTitles
[$dest->getPrefixedText()] ) ) {
1359 $dest = $this->mRedirectTitles
[$dest->getPrefixedText()];
1361 $fromNs = $titleFrom->getNamespace();
1362 $fromDBkey = $titleFrom->getDBkey();
1363 $toPageId = $dest->getArticleID();
1364 if ( isset( $data[$toPageId] ) &&
1365 isset( $this->mGeneratorData
[$fromNs][$fromDBkey] )
1367 // It is necesary to set both $data and add to $result, if an ApiResult,
1368 // to ensure multiple redirects to the same destination are all merged.
1369 $data[$toPageId] = call_user_func(
1370 $this->mRedirectMergePolicy
,
1372 $this->mGeneratorData
[$fromNs][$fromDBkey]
1374 if ( $result instanceof ApiResult
) {
1375 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult
::OVERRIDE
) ) {
1387 * Get the database connection (read-only)
1390 protected function getDB() {
1391 return $this->mDbSource
->getDB();
1395 * Returns the input array of integers with all values < 0 removed
1397 * @param array $array
1400 private static function getPositiveIntegers( $array ) {
1401 // T27734 API: possible issue with revids validation
1402 // It seems with a load of revision rows, MySQL gets upset
1403 // Remove any < 0 integers, as they can't be valid
1404 foreach ( $array as $i => $int ) {
1406 unset( $array[$i] );
1413 public function getAllowedParams( $flags = 0 ) {
1416 ApiBase
::PARAM_ISMULTI
=> true,
1417 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1420 ApiBase
::PARAM_TYPE
=> 'integer',
1421 ApiBase
::PARAM_ISMULTI
=> true,
1422 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1425 ApiBase
::PARAM_TYPE
=> 'integer',
1426 ApiBase
::PARAM_ISMULTI
=> true,
1427 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1430 ApiBase
::PARAM_TYPE
=> null,
1431 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1432 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'g',
1435 ApiBase
::PARAM_DFLT
=> false,
1436 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1437 ?
'api-pageset-param-redirects-generator'
1438 : 'api-pageset-param-redirects-nogenerator',
1440 'converttitles' => [
1441 ApiBase
::PARAM_DFLT
=> false,
1442 ApiBase
::PARAM_HELP_MSG
=> [
1443 'api-pageset-param-converttitles',
1444 [ Message
::listParam( LanguageConverter
::$languagesWithVariants, 'text' ) ],
1449 if ( !$this->mAllowGenerator
) {
1450 unset( $result['generator'] );
1451 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1452 $result['generator'][ApiBase
::PARAM_TYPE
] = 'submodule';
1453 $result['generator'][ApiBase
::PARAM_SUBMODULE_MAP
] = $this->getGenerators();
1459 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1460 parent
::handleParamNormalization( $paramName, $value, $rawValue );
1462 if ( $paramName === 'titles' ) {
1463 // For the 'titles' parameter, we want to split it like ApiBase would
1464 // and add any changed titles to $this->mNormalizedTitles
1465 $value = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1466 $l = count( $value );
1467 $rawValue = $this->explodeMultiValue( $rawValue, $l );
1468 for ( $i = 0; $i < $l; $i++
) {
1469 if ( $value[$i] !== $rawValue[$i] ) {
1470 $this->mNormalizedTitles
[$rawValue[$i]] = $value[$i];
1476 private static $generators = null;
1479 * Get an array of all available generators
1482 private function getGenerators() {
1483 if ( self
::$generators === null ) {
1484 $query = $this->mDbSource
;
1485 if ( !( $query instanceof ApiQuery
) ) {
1486 // If the parent container of this pageset is not ApiQuery,
1487 // we must create it to get module manager
1488 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1491 $prefix = $query->getModulePath() . '+';
1492 $mgr = $query->getModuleManager();
1493 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1494 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1495 $gens[$name] = $prefix . $name;
1499 self
::$generators = $gens;
1502 return self
::$generators;