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
22 use MediaWiki\MediaWikiServices
;
23 use Wikimedia\Rdbms\ResultWrapper
;
24 use Wikimedia\Rdbms\IDatabase
;
27 * This class contains a list of pages that the client has requested.
28 * Initially, when the client passes in titles=, pageids=, or revisions=
29 * parameter, an instance of the ApiPageSet class will normalize titles,
30 * determine if the pages/revisions exist, and prefetch any additional page
33 * When a generator is used, the result of the generator will become the input
34 * for the second instance of this class, and all subsequent actions will use
35 * the second instance for all their work.
38 * @since 1.21 derives from ApiBase instead of ApiQueryBase
40 class ApiPageSet
extends ApiBase
{
42 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
45 const DISABLE_GENERATORS
= 1;
49 private $mResolveRedirects;
50 private $mConvertTitles;
51 private $mAllowGenerator;
53 private $mAllPages = []; // [ns][dbkey] => page_id or negative when missing
54 private $mTitles = [];
55 private $mGoodAndMissingPages = []; // [ns][dbkey] => page_id or negative when missing
56 private $mGoodPages = []; // [ns][dbkey] => page_id
57 private $mGoodTitles = [];
58 private $mMissingPages = []; // [ns][dbkey] => fake page_id
59 private $mMissingTitles = [];
60 /** @var array [fake_page_id] => [ 'title' => $title, 'invalidreason' => $reason ] */
61 private $mInvalidTitles = [];
62 private $mMissingPageIDs = [];
63 private $mRedirectTitles = [];
64 private $mSpecialTitles = [];
65 private $mAllSpecials = []; // separate from mAllPages to avoid breaking getAllTitlesByNamespace()
66 private $mNormalizedTitles = [];
67 private $mInterwikiTitles = [];
69 private $mPendingRedirectIDs = [];
70 private $mPendingRedirectSpecialPages = []; // [dbkey] => [ Title $from, Title $to ]
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 & self
::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, self
::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 );
178 // Avoid PHP 7.1 warning of passing $this by reference
180 Hooks
::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$apiModule ] );
182 // Prevent warnings from being reported on these parameters
183 $main = $this->getMain();
184 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
185 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
190 $this->resolvePendingRedirects();
193 // Only one of the titles/pageids/revids is allowed at the same time
195 if ( isset( $this->mParams
['titles'] ) ) {
196 $dataSource = 'titles';
198 if ( isset( $this->mParams
['pageids'] ) ) {
199 if ( isset( $dataSource ) ) {
202 'apierror-invalidparammix-cannotusewith',
203 $this->encodeParamName( 'pageids' ),
204 $this->encodeParamName( $dataSource )
209 $dataSource = 'pageids';
211 if ( isset( $this->mParams
['revids'] ) ) {
212 if ( isset( $dataSource ) ) {
215 'apierror-invalidparammix-cannotusewith',
216 $this->encodeParamName( 'revids' ),
217 $this->encodeParamName( $dataSource )
222 $dataSource = 'revids';
226 // Populate page information with the original user input
227 switch ( $dataSource ) {
229 $this->initFromTitles( $this->mParams
['titles'] );
232 $this->initFromPageIds( $this->mParams
['pageids'] );
235 if ( $this->mResolveRedirects
) {
236 $this->addWarning( 'apiwarn-redirectsandrevids' );
238 $this->mResolveRedirects
= false;
239 $this->initFromRevIDs( $this->mParams
['revids'] );
242 // Do nothing - some queries do not need any of the data sources.
250 * Check whether this PageSet is resolving redirects
253 public function isResolvingRedirects() {
254 return $this->mResolveRedirects
;
258 * Return the parameter name that is the source of data for this PageSet
260 * If multiple source parameters are specified (e.g. titles and pageids),
261 * one will be named arbitrarily.
263 * @return string|null
265 public function getDataSource() {
266 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
269 if ( isset( $this->mParams
['titles'] ) ) {
272 if ( isset( $this->mParams
['pageids'] ) ) {
275 if ( isset( $this->mParams
['revids'] ) ) {
283 * Request an additional field from the page table.
284 * Must be called before execute()
285 * @param string $fieldName Field name
287 public function requestField( $fieldName ) {
288 $this->mRequestedPageFields
[$fieldName] = null;
292 * Get the value of a custom field previously requested through
294 * @param string $fieldName Field name
295 * @return mixed Field value
297 public function getCustomField( $fieldName ) {
298 return $this->mRequestedPageFields
[$fieldName];
302 * Get the fields that have to be queried from the page table:
303 * the ones requested through requestField() and a few basic ones
305 * @return array Array of field names
307 public function getPageTableFields() {
308 // Ensure we get minimum required fields
309 // DON'T change this order
311 'page_namespace' => null,
312 'page_title' => null,
316 if ( $this->mResolveRedirects
) {
317 $pageFlds['page_is_redirect'] = null;
320 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
321 $pageFlds['page_content_model'] = null;
324 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
325 $pageFlds['page_lang'] = null;
328 foreach ( LinkCache
::getSelectFields() as $field ) {
329 $pageFlds[$field] = null;
332 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
334 return array_keys( $pageFlds );
338 * Returns an array [ns][dbkey] => page_id for all requested titles.
339 * page_id is a unique negative number in case title was not found.
340 * Invalid titles will also have negative page IDs and will be in namespace 0
343 public function getAllTitlesByNamespace() {
344 return $this->mAllPages
;
348 * All Title objects provided.
351 public function getTitles() {
352 return $this->mTitles
;
356 * Returns the number of unique pages (not revisions) in the set.
359 public function getTitleCount() {
360 return count( $this->mTitles
);
364 * Returns an array [ns][dbkey] => page_id for all good titles.
367 public function getGoodTitlesByNamespace() {
368 return $this->mGoodPages
;
372 * Title objects that were found in the database.
373 * @return Title[] Array page_id (int) => Title (obj)
375 public function getGoodTitles() {
376 return $this->mGoodTitles
;
380 * Returns the number of found unique pages (not revisions) in the set.
383 public function getGoodTitleCount() {
384 return count( $this->mGoodTitles
);
388 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
389 * fake_page_id is a unique negative number.
392 public function getMissingTitlesByNamespace() {
393 return $this->mMissingPages
;
397 * Title objects that were NOT found in the database.
398 * The array's index will be negative for each item
401 public function getMissingTitles() {
402 return $this->mMissingTitles
;
406 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
409 public function getGoodAndMissingTitlesByNamespace() {
410 return $this->mGoodAndMissingPages
;
414 * Title objects for good and missing titles.
417 public function getGoodAndMissingTitles() {
418 return $this->mGoodTitles +
$this->mMissingTitles
;
422 * Titles that were deemed invalid by Title::newFromText()
423 * The array's index will be unique and negative for each item
424 * @deprecated since 1.26, use self::getInvalidTitlesAndReasons()
425 * @return string[] Array of strings (not Title objects)
427 public function getInvalidTitles() {
428 wfDeprecated( __METHOD__
, '1.26' );
429 return array_map( function ( $t ) {
431 }, $this->mInvalidTitles
);
435 * Titles that were deemed invalid by Title::newFromText()
436 * The array's index will be unique and negative for each item
437 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
439 public function getInvalidTitlesAndReasons() {
440 return $this->mInvalidTitles
;
444 * Page IDs that were not found in the database
445 * @return array Array of page IDs
447 public function getMissingPageIDs() {
448 return $this->mMissingPageIDs
;
452 * Get a list of redirect resolutions - maps a title to its redirect
453 * target, as an array of output-ready arrays
456 public function getRedirectTitles() {
457 return $this->mRedirectTitles
;
461 * Get a list of redirect resolutions - maps a title to its redirect
462 * target. Includes generator data for redirect source when available.
463 * @param ApiResult|null $result
464 * @return array Array of prefixed_title (string) => Title object
467 public function getRedirectTitlesAsResult( $result = null ) {
469 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
471 'from' => strval( $titleStrFrom ),
472 'to' => $titleTo->getPrefixedText(),
474 if ( $titleTo->hasFragment() ) {
475 $r['tofragment'] = $titleTo->getFragment();
477 if ( $titleTo->isExternal() ) {
478 $r['tointerwiki'] = $titleTo->getInterwiki();
480 if ( isset( $this->mResolvedRedirectTitles
[$titleStrFrom] ) ) {
481 $titleFrom = $this->mResolvedRedirectTitles
[$titleStrFrom];
482 $ns = $titleFrom->getNamespace();
483 $dbkey = $titleFrom->getDBkey();
484 if ( isset( $this->mGeneratorData
[$ns][$dbkey] ) ) {
485 $r = array_merge( $this->mGeneratorData
[$ns][$dbkey], $r );
491 if ( !empty( $values ) && $result ) {
492 ApiResult
::setIndexedTagName( $values, 'r' );
499 * Get a list of title normalizations - maps a title to its normalized
501 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
503 public function getNormalizedTitles() {
504 return $this->mNormalizedTitles
;
508 * Get a list of title normalizations - maps a title to its normalized
509 * version in the form of result array.
510 * @param ApiResult|null $result
511 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
514 public function getNormalizedTitlesAsResult( $result = null ) {
518 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
519 $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr );
521 'fromencoded' => $encode,
522 'from' => $encode ?
rawurlencode( $rawTitleStr ) : $rawTitleStr,
526 if ( !empty( $values ) && $result ) {
527 ApiResult
::setIndexedTagName( $values, 'n' );
534 * Get a list of title conversions - maps a title to its converted
536 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
538 public function getConvertedTitles() {
539 return $this->mConvertedTitles
;
543 * Get a list of title conversions - maps a title to its converted
544 * version as a result array.
545 * @param ApiResult|null $result
546 * @return array Array of (from, to) strings
549 public function getConvertedTitlesAsResult( $result = null ) {
551 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
553 'from' => $rawTitleStr,
557 if ( !empty( $values ) && $result ) {
558 ApiResult
::setIndexedTagName( $values, 'c' );
565 * Get a list of interwiki titles - maps a title to its interwiki
567 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
569 public function getInterwikiTitles() {
570 return $this->mInterwikiTitles
;
574 * Get a list of interwiki titles - maps a title to its interwiki
576 * @param ApiResult|null $result
578 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
581 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
583 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
585 'title' => $rawTitleStr,
586 'iw' => $interwikiStr,
589 $title = Title
::newFromText( $rawTitleStr );
590 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
594 if ( !empty( $values ) && $result ) {
595 ApiResult
::setIndexedTagName( $values, 'i' );
602 * Get an array of invalid/special/missing titles.
604 * @param array $invalidChecks List of types of invalid titles to include.
605 * Recognized values are:
606 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
607 * - special: Titles from $this->getSpecialTitles()
608 * - missingIds: ids from $this->getMissingPageIDs()
609 * - missingRevIds: ids from $this->getMissingRevisionIDs()
610 * - missingTitles: Titles from $this->getMissingTitles()
611 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
612 * @return array Array suitable for inclusion in the response
615 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
616 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
619 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
620 self
::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
622 if ( in_array( 'special', $invalidChecks ) ) {
625 foreach ( $this->getSpecialTitles() as $title ) {
626 if ( $title->isKnown() ) {
632 self
::addValues( $result, $unknown, [ 'special', 'missing' ] );
633 self
::addValues( $result, $known, [ 'special' ] );
635 if ( in_array( 'missingIds', $invalidChecks ) ) {
636 self
::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
638 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
639 self
::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
641 if ( in_array( 'missingTitles', $invalidChecks ) ) {
644 foreach ( $this->getMissingTitles() as $title ) {
645 if ( $title->isKnown() ) {
651 self
::addValues( $result, $unknown, [ 'missing' ] );
652 self
::addValues( $result, $known, [ 'missing', 'known' ] );
654 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
655 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
662 * Get the list of valid revision IDs (requested with the revids= parameter)
663 * @return array Array of revID (int) => pageID (int)
665 public function getRevisionIDs() {
666 return $this->mGoodRevIDs
;
670 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
671 * @return array Array of revID (int) => pageID (int)
673 public function getLiveRevisionIDs() {
674 return $this->mLiveRevIDs
;
678 * Get the list of revision IDs that were associated with deleted titles.
679 * @return array Array of revID (int) => pageID (int)
681 public function getDeletedRevisionIDs() {
682 return $this->mDeletedRevIDs
;
686 * Revision IDs that were not found in the database
687 * @return array Array of revision IDs
689 public function getMissingRevisionIDs() {
690 return $this->mMissingRevIDs
;
694 * Revision IDs that were not found in the database as result array.
695 * @param ApiResult|null $result
696 * @return array Array of revision IDs
699 public function getMissingRevisionIDsAsResult( $result = null ) {
701 foreach ( $this->getMissingRevisionIDs() as $revid ) {
706 if ( !empty( $values ) && $result ) {
707 ApiResult
::setIndexedTagName( $values, 'rev' );
714 * Get the list of titles with negative namespace
717 public function getSpecialTitles() {
718 return $this->mSpecialTitles
;
722 * Returns the number of revisions (requested with revids= parameter).
723 * @return int Number of revisions.
725 public function getRevisionCount() {
726 return count( $this->getRevisionIDs() );
730 * Populate this PageSet from a list of Titles
731 * @param array $titles Array of Title objects
733 public function populateFromTitles( $titles ) {
734 $this->initFromTitles( $titles );
738 * Populate this PageSet from a list of page IDs
739 * @param array $pageIDs Array of page IDs
741 public function populateFromPageIDs( $pageIDs ) {
742 $this->initFromPageIds( $pageIDs );
746 * Populate this PageSet from a rowset returned from the database
748 * Note that the query result must include the columns returned by
749 * $this->getPageTableFields().
751 * @param IDatabase $db
752 * @param ResultWrapper $queryResult
754 public function populateFromQueryResult( $db, $queryResult ) {
755 $this->initFromQueryResult( $queryResult );
759 * Populate this PageSet from a list of revision IDs
760 * @param array $revIDs Array of revision IDs
762 public function populateFromRevisionIDs( $revIDs ) {
763 $this->initFromRevIDs( $revIDs );
767 * Extract all requested fields from the row received from the database
768 * @param stdClass $row Result row
770 public function processDbRow( $row ) {
771 // Store Title object in various data structures
772 $title = Title
::newFromRow( $row );
774 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
775 $linkCache->addGoodLinkObjFromRow( $title, $row );
777 $pageId = intval( $row->page_id
);
778 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
779 $this->mTitles
[] = $title;
781 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
782 $this->mPendingRedirectIDs
[$pageId] = $title;
784 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
785 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
786 $this->mGoodTitles
[$pageId] = $title;
789 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
790 $fieldValues[$pageId] = $row->$fieldName;
795 * This method populates internal variables with page information
796 * based on the given array of title strings.
799 * #1 For each title, get data from `page` table
800 * #2 If page was not found in the DB, store it as missing
802 * Additionally, when resolving redirects:
803 * #3 If no more redirects left, stop.
804 * #4 For each redirect, get its target from the `redirect` table.
805 * #5 Substitute the original LinkBatch object with the new list
806 * #6 Repeat from step #1
808 * @param array $titles Array of Title objects or strings
810 private function initFromTitles( $titles ) {
811 // Get validated and normalized title objects
812 $linkBatch = $this->processTitlesArray( $titles );
813 if ( $linkBatch->isEmpty() ) {
814 // There might be special-page redirects
815 $this->resolvePendingRedirects();
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 = MediaWikiServices
::getInstance()->getLinkCache();
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 ||
$this->mPendingRedirectSpecialPages
) {
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();
1070 if ( $this->mPendingRedirectIDs
) {
1079 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ],
1082 foreach ( $res as $row ) {
1083 $rdfrom = intval( $row->rd_from
);
1084 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1085 $to = Title
::makeTitle(
1091 $this->mResolvedRedirectTitles
[$from] = $this->mPendingRedirectIDs
[$rdfrom];
1092 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1093 if ( $to->isExternal() ) {
1094 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1095 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1096 $titlesToResolve[] = $to;
1098 $this->mRedirectTitles
[$from] = $to;
1101 if ( $this->mPendingRedirectIDs
) {
1102 // We found pages that aren't in the redirect table
1104 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1105 $page = WikiPage
::factory( $title );
1106 $rt = $page->insertRedirect();
1108 // What the hell. Let's just ignore this
1111 if ( $rt->isExternal() ) {
1112 $this->mInterwikiTitles
[$rt->getPrefixedText()] = $rt->getInterwiki();
1113 } elseif ( !isset( $this->mAllPages
[$rt->getNamespace()][$rt->getDBkey()] ) ) {
1114 $titlesToResolve[] = $rt;
1116 $from = $title->getPrefixedText();
1117 $this->mResolvedRedirectTitles
[$from] = $title;
1118 $this->mRedirectTitles
[$from] = $rt;
1119 unset( $this->mPendingRedirectIDs
[$id] );
1124 if ( $this->mPendingRedirectSpecialPages
) {
1125 foreach ( $this->mPendingRedirectSpecialPages
as $key => list( $from, $to ) ) {
1126 $fromKey = $from->getPrefixedText();
1127 $this->mResolvedRedirectTitles
[$fromKey] = $from;
1128 $this->mRedirectTitles
[$fromKey] = $to;
1129 if ( $to->isExternal() ) {
1130 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1131 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1132 $titlesToResolve[] = $to;
1135 $this->mPendingRedirectSpecialPages
= [];
1137 // Set private caching since we don't know what criteria the
1138 // special pages used to decide on these redirects.
1139 $this->mCacheMode
= 'private';
1142 return $this->processTitlesArray( $titlesToResolve );
1146 * Get the cache mode for the data generated by this module.
1147 * All PageSet users should take into account whether this returns a more-restrictive
1148 * cache mode than the using module itself. For possible return values and other
1149 * details about cache modes, see ApiMain::setCacheMode()
1151 * Public caching will only be allowed if *all* the modules that supply
1152 * data for a given request return a cache mode of public.
1154 * @param array|null $params
1158 public function getCacheMode( $params = null ) {
1159 return $this->mCacheMode
;
1163 * Given an array of title strings, convert them into Title objects.
1164 * Alternatively, an array of Title objects may be given.
1165 * This method validates access rights for the title,
1166 * and appends normalization values to the output.
1168 * @param array $titles Array of Title objects or strings
1171 private function processTitlesArray( $titles ) {
1173 $linkBatch = new LinkBatch();
1175 foreach ( $titles as $title ) {
1176 if ( is_string( $title ) ) {
1178 $titleObj = Title
::newFromTextThrow( $title, $this->mDefaultNamespace
);
1179 } catch ( MalformedTitleException
$ex ) {
1180 // Handle invalid titles gracefully
1181 if ( !isset( $this->mAllPages
[0][$title] ) ) {
1182 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1183 $this->mInvalidTitles
[$this->mFakePageId
] = [
1185 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1187 $this->mFakePageId
--;
1189 continue; // There's nothing else we can do
1194 $unconvertedTitle = $titleObj->getPrefixedText();
1195 $titleWasConverted = false;
1196 if ( $titleObj->isExternal() ) {
1197 // This title is an interwiki link.
1198 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1200 // Variants checking
1202 if ( $this->mConvertTitles
&&
1203 $wgContLang->hasVariants() &&
1204 !$titleObj->exists()
1206 // Language::findVariantLink will modify titleText and titleObj into
1207 // the canonical variant if possible
1208 $titleText = is_string( $title ) ?
$title : $titleObj->getPrefixedText();
1209 $wgContLang->findVariantLink( $titleText, $titleObj );
1210 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1213 if ( $titleObj->getNamespace() < 0 ) {
1214 // Handle Special and Media pages
1215 $titleObj = $titleObj->fixSpecialName();
1216 $ns = $titleObj->getNamespace();
1217 $dbkey = $titleObj->getDBkey();
1218 if ( !isset( $this->mAllSpecials
[$ns][$dbkey] ) ) {
1219 $this->mAllSpecials
[$ns][$dbkey] = $this->mFakePageId
;
1221 if ( $ns === NS_SPECIAL
&& $this->mResolveRedirects
) {
1222 $special = SpecialPageFactory
::getPage( $dbkey );
1223 if ( $special instanceof RedirectSpecialArticle
) {
1224 // Only RedirectSpecialArticle is intended to redirect to an article, other kinds of
1225 // RedirectSpecialPage are probably applying weird URL parameters we don't want to handle.
1226 $context = new DerivativeContext( $this );
1227 $context->setTitle( $titleObj );
1228 $context->setRequest( new FauxRequest
);
1229 $special->setContext( $context );
1230 list( /* $alias */, $subpage ) = SpecialPageFactory
::resolveAlias( $dbkey );
1231 $target = $special->getRedirect( $subpage );
1235 $this->mPendingRedirectSpecialPages
[$dbkey] = [ $titleObj, $target ];
1237 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1238 $this->mFakePageId
--;
1243 $linkBatch->addObj( $titleObj );
1247 // Make sure we remember the original title that was
1248 // given to us. This way the caller can correlate new
1249 // titles with the originally requested when e.g. the
1250 // namespace is localized or the capitalization is
1252 if ( $titleWasConverted ) {
1253 $this->mConvertedTitles
[$unconvertedTitle] = $titleObj->getPrefixedText();
1254 // In this case the page can't be Special.
1255 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1256 $this->mNormalizedTitles
[$title] = $unconvertedTitle;
1258 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1259 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1262 // Need gender information
1263 if ( MWNamespace
::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1264 $usernames[] = $titleObj->getText();
1267 // Get gender information
1268 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
1269 $genderCache->doQuery( $usernames, __METHOD__
);
1275 * Set data for a title.
1277 * This data may be extracted into an ApiResult using
1278 * self::populateGeneratorData. This should generally be limited to
1279 * data that is likely to be particularly useful to end users rather than
1280 * just being a dump of everything returned in non-generator mode.
1282 * Redirects here will *not* be followed, even if 'redirects' was
1283 * specified, since in the case of multiple redirects we can't know which
1284 * source's data to use on the target.
1286 * @param Title $title
1287 * @param array $data
1289 public function setGeneratorData( Title
$title, array $data ) {
1290 $ns = $title->getNamespace();
1291 $dbkey = $title->getDBkey();
1292 $this->mGeneratorData
[$ns][$dbkey] = $data;
1296 * Controls how generator data about a redirect source is merged into
1297 * the generator data for the redirect target. When not set no data
1298 * is merged. Note that if multiple titles redirect to the same target
1299 * the order of operations is undefined.
1301 * Example to include generated data from redirect in target, prefering
1302 * the data generated for the destination when there is a collision:
1304 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1305 * return $current + $new;
1309 * @param callable|null $callable Recieves two array arguments, first the
1310 * generator data for the redirect target and second the generator data
1311 * for the redirect source. Returns the resulting generator data to use
1312 * for the redirect target.
1314 public function setRedirectMergePolicy( $callable ) {
1315 $this->mRedirectMergePolicy
= $callable;
1319 * Populate the generator data for all titles in the result
1321 * The page data may be inserted into an ApiResult object or into an
1322 * associative array. The $path parameter specifies the path within the
1323 * ApiResult or array to find the "pages" node.
1325 * The "pages" node itself must be an associative array mapping the page ID
1326 * or fake page ID values returned by this pageset (see
1327 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1328 * associative arrays of page data. Each of those subarrays will have the
1329 * data from self::setGeneratorData() merged in.
1331 * Data that was set by self::setGeneratorData() for pages not in the
1332 * "pages" node will be ignored.
1334 * @param ApiResult|array &$result
1335 * @param array $path
1336 * @return bool Whether the data fit
1338 public function populateGeneratorData( &$result, array $path = [] ) {
1339 if ( $result instanceof ApiResult
) {
1340 $data = $result->getResultData( $path );
1341 if ( $data === null ) {
1346 foreach ( $path as $key ) {
1347 if ( !isset( $data[$key] ) ) {
1348 // Path isn't in $result, so nothing to add, so everything
1352 $data = &$data[$key];
1355 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1356 if ( $ns === NS_SPECIAL
) {
1358 foreach ( $this->mSpecialTitles
as $id => $title ) {
1359 $pages[$title->getDBkey()] = $id;
1362 if ( !isset( $this->mAllPages
[$ns] ) ) {
1363 // No known titles in the whole namespace. Skip it.
1366 $pages = $this->mAllPages
[$ns];
1368 foreach ( $dbkeys as $dbkey => $genData ) {
1369 if ( !isset( $pages[$dbkey] ) ) {
1370 // Unknown title. Forget it.
1373 $pageId = $pages[$dbkey];
1374 if ( !isset( $data[$pageId] ) ) {
1375 // $pageId didn't make it into the result. Ignore it.
1379 if ( $result instanceof ApiResult
) {
1380 $path2 = array_merge( $path, [ $pageId ] );
1381 foreach ( $genData as $key => $value ) {
1382 if ( !$result->addValue( $path2, $key, $value ) ) {
1387 $data[$pageId] = array_merge( $data[$pageId], $genData );
1392 // Merge data generated about redirect titles into the redirect destination
1393 if ( $this->mRedirectMergePolicy
) {
1394 foreach ( $this->mResolvedRedirectTitles
as $titleFrom ) {
1396 while ( isset( $this->mRedirectTitles
[$dest->getPrefixedText()] ) ) {
1397 $dest = $this->mRedirectTitles
[$dest->getPrefixedText()];
1399 $fromNs = $titleFrom->getNamespace();
1400 $fromDBkey = $titleFrom->getDBkey();
1401 $toPageId = $dest->getArticleID();
1402 if ( isset( $data[$toPageId] ) &&
1403 isset( $this->mGeneratorData
[$fromNs][$fromDBkey] )
1405 // It is necesary to set both $data and add to $result, if an ApiResult,
1406 // to ensure multiple redirects to the same destination are all merged.
1407 $data[$toPageId] = call_user_func(
1408 $this->mRedirectMergePolicy
,
1410 $this->mGeneratorData
[$fromNs][$fromDBkey]
1412 if ( $result instanceof ApiResult
) {
1413 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult
::OVERRIDE
) ) {
1425 * Get the database connection (read-only)
1428 protected function getDB() {
1429 return $this->mDbSource
->getDB();
1433 * Returns the input array of integers with all values < 0 removed
1435 * @param array $array
1438 private static function getPositiveIntegers( $array ) {
1439 // T27734 API: possible issue with revids validation
1440 // It seems with a load of revision rows, MySQL gets upset
1441 // Remove any < 0 integers, as they can't be valid
1442 foreach ( $array as $i => $int ) {
1444 unset( $array[$i] );
1451 public function getAllowedParams( $flags = 0 ) {
1454 ApiBase
::PARAM_ISMULTI
=> true,
1455 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1458 ApiBase
::PARAM_TYPE
=> 'integer',
1459 ApiBase
::PARAM_ISMULTI
=> true,
1460 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1463 ApiBase
::PARAM_TYPE
=> 'integer',
1464 ApiBase
::PARAM_ISMULTI
=> true,
1465 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1468 ApiBase
::PARAM_TYPE
=> null,
1469 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1470 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'g',
1473 ApiBase
::PARAM_DFLT
=> false,
1474 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1475 ?
'api-pageset-param-redirects-generator'
1476 : 'api-pageset-param-redirects-nogenerator',
1478 'converttitles' => [
1479 ApiBase
::PARAM_DFLT
=> false,
1480 ApiBase
::PARAM_HELP_MSG
=> [
1481 'api-pageset-param-converttitles',
1482 [ Message
::listParam( LanguageConverter
::$languagesWithVariants, 'text' ) ],
1487 if ( !$this->mAllowGenerator
) {
1488 unset( $result['generator'] );
1489 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1490 $result['generator'][ApiBase
::PARAM_TYPE
] = 'submodule';
1491 $result['generator'][ApiBase
::PARAM_SUBMODULE_MAP
] = $this->getGenerators();
1497 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1498 parent
::handleParamNormalization( $paramName, $value, $rawValue );
1500 if ( $paramName === 'titles' ) {
1501 // For the 'titles' parameter, we want to split it like ApiBase would
1502 // and add any changed titles to $this->mNormalizedTitles
1503 $value = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1504 $l = count( $value );
1505 $rawValue = $this->explodeMultiValue( $rawValue, $l );
1506 for ( $i = 0; $i < $l; $i++
) {
1507 if ( $value[$i] !== $rawValue[$i] ) {
1508 $this->mNormalizedTitles
[$rawValue[$i]] = $value[$i];
1514 private static $generators = null;
1517 * Get an array of all available generators
1520 private function getGenerators() {
1521 if ( self
::$generators === null ) {
1522 $query = $this->mDbSource
;
1523 if ( !( $query instanceof ApiQuery
) ) {
1524 // If the parent container of this pageset is not ApiQuery,
1525 // we must create it to get module manager
1526 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1529 $prefix = $query->getModulePath() . '+';
1530 $mgr = $query->getModuleManager();
1531 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1532 if ( is_subclass_of( $class, ApiQueryGeneratorBase
::class ) ) {
1533 $gens[$name] = $prefix . $name;
1537 self
::$generators = $gens;
1540 return self
::$generators;