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
28 * This class contains a list of pages that the client has requested.
29 * Initially, when the client passes in titles=, pageids=, or revisions=
30 * parameter, an instance of the ApiPageSet class will normalize titles,
31 * determine if the pages/revisions exist, and prefetch any additional page
34 * When a generator is used, the result of the generator will become the input
35 * for the second instance of this class, and all subsequent actions will use
36 * the second instance for all their work.
39 * @since 1.21 derives from ApiBase instead of ApiQueryBase
41 class ApiPageSet
extends ApiBase
{
43 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
46 const DISABLE_GENERATORS
= 1;
50 private $mResolveRedirects;
51 private $mConvertTitles;
52 private $mAllowGenerator;
54 private $mAllPages = []; // [ns][dbkey] => page_id or negative when missing
55 private $mTitles = [];
56 private $mGoodAndMissingPages = []; // [ns][dbkey] => page_id or negative when missing
57 private $mGoodPages = []; // [ns][dbkey] => page_id
58 private $mGoodTitles = [];
59 private $mMissingPages = []; // [ns][dbkey] => fake page_id
60 private $mMissingTitles = [];
61 /** @var array [fake_page_id] => array( 'title' => $title, 'invalidreason' => $reason ) */
62 private $mInvalidTitles = [];
63 private $mMissingPageIDs = [];
64 private $mRedirectTitles = [];
65 private $mSpecialTitles = [];
66 private $mNormalizedTitles = [];
67 private $mInterwikiTitles = [];
69 private $mPendingRedirectIDs = [];
70 private $mResolvedRedirectTitles = [];
71 private $mConvertedTitles = [];
72 private $mGoodRevIDs = [];
73 private $mLiveRevIDs = [];
74 private $mDeletedRevIDs = [];
75 private $mMissingRevIDs = [];
76 private $mGeneratorData = []; // [ns][dbkey] => data array
77 private $mFakePageId = -1;
78 private $mCacheMode = 'public';
79 private $mRequestedPageFields = [];
81 private $mDefaultNamespace = NS_MAIN
;
82 /** @var callable|null */
83 private $mRedirectMergePolicy;
86 * Add all items from $values into the result
87 * @param array $result Output
88 * @param array $values Values to add
89 * @param string $flag The name of the boolean flag to mark this element
90 * @param string $name If given, name of the value
92 private static function addValues( array &$result, $values, $flag = null, $name = null ) {
93 foreach ( $values as $val ) {
94 if ( $val instanceof Title
) {
96 ApiQueryBase
::addTitleInfo( $v, $val );
97 } elseif ( $name !== null ) {
98 $v = [ $name => $val ];
102 if ( $flag !== null ) {
110 * @param ApiBase $dbSource Module implementing getDB().
111 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
112 * @param int $flags Zero or more flags like DISABLE_GENERATORS
113 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
114 * @since 1.21 accepts $flags instead of two boolean values
116 public function __construct( ApiBase
$dbSource, $flags = 0, $defaultNamespace = NS_MAIN
) {
117 parent
::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
118 $this->mDbSource
= $dbSource;
119 $this->mAllowGenerator
= ( $flags & ApiPageSet
::DISABLE_GENERATORS
) == 0;
120 $this->mDefaultNamespace
= $defaultNamespace;
122 $this->mParams
= $this->extractRequestParams();
123 $this->mResolveRedirects
= $this->mParams
['redirects'];
124 $this->mConvertTitles
= $this->mParams
['converttitles'];
128 * In case execute() is not called, call this method to mark all relevant parameters as used
129 * This prevents unused parameters from being reported as warnings
131 public function executeDryRun() {
132 $this->executeInternal( true );
136 * Populate the PageSet from the request parameters.
138 public function execute() {
139 $this->executeInternal( false );
143 * Populate the PageSet from the request parameters.
144 * @param bool $isDryRun If true, instantiates generator, but only to mark
145 * relevant parameters as used
147 private function executeInternal( $isDryRun ) {
148 $generatorName = $this->mAllowGenerator ?
$this->mParams
['generator'] : null;
149 if ( isset( $generatorName ) ) {
150 $dbSource = $this->mDbSource
;
151 if ( !$dbSource instanceof ApiQuery
) {
152 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
153 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
155 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
156 if ( $generator === null ) {
157 $this->dieUsage( 'Unknown generator=' . $generatorName, 'badgenerator' );
159 if ( !$generator instanceof ApiQueryGeneratorBase
) {
160 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
162 // Create a temporary pageset to store generator's output,
163 // add any additional fields generator may need, and execute pageset to populate titles/pageids
164 $tmpPageSet = new ApiPageSet( $dbSource, ApiPageSet
::DISABLE_GENERATORS
);
165 $generator->setGeneratorMode( $tmpPageSet );
166 $this->mCacheMode
= $generator->getCacheMode( $generator->extractRequestParams() );
169 $generator->requestExtraData( $tmpPageSet );
171 $tmpPageSet->executeInternal( $isDryRun );
173 // populate this pageset with the generator output
175 $generator->executeGenerator( $this );
176 Hooks
::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$this ] );
178 // Prevent warnings from being reported on these parameters
179 $main = $this->getMain();
180 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
181 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
186 $this->resolvePendingRedirects();
189 // Only one of the titles/pageids/revids is allowed at the same time
191 if ( isset( $this->mParams
['titles'] ) ) {
192 $dataSource = 'titles';
194 if ( isset( $this->mParams
['pageids'] ) ) {
195 if ( isset( $dataSource ) ) {
196 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
198 $dataSource = 'pageids';
200 if ( isset( $this->mParams
['revids'] ) ) {
201 if ( isset( $dataSource ) ) {
202 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
204 $dataSource = 'revids';
208 // Populate page information with the original user input
209 switch ( $dataSource ) {
211 $this->initFromTitles( $this->mParams
['titles'] );
214 $this->initFromPageIds( $this->mParams
['pageids'] );
217 if ( $this->mResolveRedirects
) {
218 $this->setWarning( 'Redirect resolution cannot be used ' .
219 'together with the revids= parameter. Any redirects ' .
220 'the revids= point to have not been resolved.' );
222 $this->mResolveRedirects
= false;
223 $this->initFromRevIDs( $this->mParams
['revids'] );
226 // Do nothing - some queries do not need any of the data sources.
234 * Check whether this PageSet is resolving redirects
237 public function isResolvingRedirects() {
238 return $this->mResolveRedirects
;
242 * Return the parameter name that is the source of data for this PageSet
244 * If multiple source parameters are specified (e.g. titles and pageids),
245 * one will be named arbitrarily.
247 * @return string|null
249 public function getDataSource() {
250 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
253 if ( isset( $this->mParams
['titles'] ) ) {
256 if ( isset( $this->mParams
['pageids'] ) ) {
259 if ( isset( $this->mParams
['revids'] ) ) {
267 * Request an additional field from the page table.
268 * Must be called before execute()
269 * @param string $fieldName Field name
271 public function requestField( $fieldName ) {
272 $this->mRequestedPageFields
[$fieldName] = null;
276 * Get the value of a custom field previously requested through
278 * @param string $fieldName Field name
279 * @return mixed Field value
281 public function getCustomField( $fieldName ) {
282 return $this->mRequestedPageFields
[$fieldName];
286 * Get the fields that have to be queried from the page table:
287 * the ones requested through requestField() and a few basic ones
289 * @return array Array of field names
291 public function getPageTableFields() {
292 // Ensure we get minimum required fields
293 // DON'T change this order
295 'page_namespace' => null,
296 'page_title' => null,
300 if ( $this->mResolveRedirects
) {
301 $pageFlds['page_is_redirect'] = null;
304 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
305 $pageFlds['page_content_model'] = null;
308 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
309 $pageFlds['page_lang'] = null;
312 // only store non-default fields
313 $this->mRequestedPageFields
= array_diff_key( $this->mRequestedPageFields
, $pageFlds );
315 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
317 return array_keys( $pageFlds );
321 * Returns an array [ns][dbkey] => page_id for all requested titles.
322 * page_id is a unique negative number in case title was not found.
323 * Invalid titles will also have negative page IDs and will be in namespace 0
326 public function getAllTitlesByNamespace() {
327 return $this->mAllPages
;
331 * All Title objects provided.
334 public function getTitles() {
335 return $this->mTitles
;
339 * Returns the number of unique pages (not revisions) in the set.
342 public function getTitleCount() {
343 return count( $this->mTitles
);
347 * Returns an array [ns][dbkey] => page_id for all good titles.
350 public function getGoodTitlesByNamespace() {
351 return $this->mGoodPages
;
355 * Title objects that were found in the database.
356 * @return Title[] Array page_id (int) => Title (obj)
358 public function getGoodTitles() {
359 return $this->mGoodTitles
;
363 * Returns the number of found unique pages (not revisions) in the set.
366 public function getGoodTitleCount() {
367 return count( $this->mGoodTitles
);
371 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
372 * fake_page_id is a unique negative number.
375 public function getMissingTitlesByNamespace() {
376 return $this->mMissingPages
;
380 * Title objects that were NOT found in the database.
381 * The array's index will be negative for each item
384 public function getMissingTitles() {
385 return $this->mMissingTitles
;
389 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
392 public function getGoodAndMissingTitlesByNamespace() {
393 return $this->mGoodAndMissingPages
;
397 * Title objects for good and missing titles.
400 public function getGoodAndMissingTitles() {
401 return $this->mGoodTitles +
$this->mMissingTitles
;
405 * Titles that were deemed invalid by Title::newFromText()
406 * The array's index will be unique and negative for each item
407 * @deprecated since 1.26, use self::getInvalidTitlesAndReasons()
408 * @return string[] Array of strings (not Title objects)
410 public function getInvalidTitles() {
411 wfDeprecated( __METHOD__
, '1.26' );
412 return array_map( function ( $t ) {
414 }, $this->mInvalidTitles
);
418 * Titles that were deemed invalid by Title::newFromText()
419 * The array's index will be unique and negative for each item
420 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
422 public function getInvalidTitlesAndReasons() {
423 return $this->mInvalidTitles
;
427 * Page IDs that were not found in the database
428 * @return array Array of page IDs
430 public function getMissingPageIDs() {
431 return $this->mMissingPageIDs
;
435 * Get a list of redirect resolutions - maps a title to its redirect
436 * target, as an array of output-ready arrays
439 public function getRedirectTitles() {
440 return $this->mRedirectTitles
;
444 * Get a list of redirect resolutions - maps a title to its redirect
445 * target. Includes generator data for redirect source when available.
446 * @param ApiResult $result
447 * @return array Array of prefixed_title (string) => Title object
450 public function getRedirectTitlesAsResult( $result = null ) {
452 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
454 'from' => strval( $titleStrFrom ),
455 'to' => $titleTo->getPrefixedText(),
457 if ( $titleTo->hasFragment() ) {
458 $r['tofragment'] = $titleTo->getFragment();
460 if ( $titleTo->isExternal() ) {
461 $r['tointerwiki'] = $titleTo->getInterwiki();
463 if ( isset( $this->mResolvedRedirectTitles
[$titleStrFrom] ) ) {
464 $titleFrom = $this->mResolvedRedirectTitles
[$titleStrFrom];
465 $ns = $titleFrom->getNamespace();
466 $dbkey = $titleFrom->getDBkey();
467 if ( isset( $this->mGeneratorData
[$ns][$dbkey] ) ) {
468 $r = array_merge( $this->mGeneratorData
[$ns][$dbkey], $r );
474 if ( !empty( $values ) && $result ) {
475 ApiResult
::setIndexedTagName( $values, 'r' );
482 * Get a list of title normalizations - maps a title to its normalized
484 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
486 public function getNormalizedTitles() {
487 return $this->mNormalizedTitles
;
491 * Get a list of title normalizations - maps a title to its normalized
492 * version in the form of result array.
493 * @param ApiResult $result
494 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
497 public function getNormalizedTitlesAsResult( $result = null ) {
499 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
501 'from' => $rawTitleStr,
505 if ( !empty( $values ) && $result ) {
506 ApiResult
::setIndexedTagName( $values, 'n' );
513 * Get a list of title conversions - maps a title to its converted
515 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
517 public function getConvertedTitles() {
518 return $this->mConvertedTitles
;
522 * Get a list of title conversions - maps a title to its converted
523 * version as a result array.
524 * @param ApiResult $result
525 * @return array Array of (from, to) strings
528 public function getConvertedTitlesAsResult( $result = null ) {
530 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
532 'from' => $rawTitleStr,
536 if ( !empty( $values ) && $result ) {
537 ApiResult
::setIndexedTagName( $values, 'c' );
544 * Get a list of interwiki titles - maps a title to its interwiki
546 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
548 public function getInterwikiTitles() {
549 return $this->mInterwikiTitles
;
553 * Get a list of interwiki titles - maps a title to its interwiki
555 * @param ApiResult $result
557 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
560 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
562 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
564 'title' => $rawTitleStr,
565 'iw' => $interwikiStr,
568 $title = Title
::newFromText( $rawTitleStr );
569 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
573 if ( !empty( $values ) && $result ) {
574 ApiResult
::setIndexedTagName( $values, 'i' );
581 * Get an array of invalid/special/missing titles.
583 * @param array $invalidChecks List of types of invalid titles to include.
584 * Recognized values are:
585 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
586 * - special: Titles from $this->getSpecialTitles()
587 * - missingIds: ids from $this->getMissingPageIDs()
588 * - missingRevIds: ids from $this->getMissingRevisionIDs()
589 * - missingTitles: Titles from $this->getMissingTitles()
590 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
591 * @return array Array suitable for inclusion in the response
594 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
595 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
598 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
599 self
::addValues( $result, $this->getInvalidTitlesAndReasons(), 'invalid' );
601 if ( in_array( 'special', $invalidChecks ) ) {
602 self
::addValues( $result, $this->getSpecialTitles(), 'special', 'title' );
604 if ( in_array( 'missingIds', $invalidChecks ) ) {
605 self
::addValues( $result, $this->getMissingPageIDs(), 'missing', 'pageid' );
607 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
608 self
::addValues( $result, $this->getMissingRevisionIDs(), 'missing', 'revid' );
610 if ( in_array( 'missingTitles', $invalidChecks ) ) {
611 self
::addValues( $result, $this->getMissingTitles(), 'missing' );
613 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
614 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
621 * Get the list of valid revision IDs (requested with the revids= parameter)
622 * @return array Array of revID (int) => pageID (int)
624 public function getRevisionIDs() {
625 return $this->mGoodRevIDs
;
629 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
630 * @return array Array of revID (int) => pageID (int)
632 public function getLiveRevisionIDs() {
633 return $this->mLiveRevIDs
;
637 * Get the list of revision IDs that were associated with deleted titles.
638 * @return array Array of revID (int) => pageID (int)
640 public function getDeletedRevisionIDs() {
641 return $this->mDeletedRevIDs
;
645 * Revision IDs that were not found in the database
646 * @return array Array of revision IDs
648 public function getMissingRevisionIDs() {
649 return $this->mMissingRevIDs
;
653 * Revision IDs that were not found in the database as result array.
654 * @param ApiResult $result
655 * @return array Array of revision IDs
658 public function getMissingRevisionIDsAsResult( $result = null ) {
660 foreach ( $this->getMissingRevisionIDs() as $revid ) {
665 if ( !empty( $values ) && $result ) {
666 ApiResult
::setIndexedTagName( $values, 'rev' );
673 * Get the list of titles with negative namespace
676 public function getSpecialTitles() {
677 return $this->mSpecialTitles
;
681 * Returns the number of revisions (requested with revids= parameter).
682 * @return int Number of revisions.
684 public function getRevisionCount() {
685 return count( $this->getRevisionIDs() );
689 * Populate this PageSet from a list of Titles
690 * @param array $titles Array of Title objects
692 public function populateFromTitles( $titles ) {
693 $this->initFromTitles( $titles );
697 * Populate this PageSet from a list of page IDs
698 * @param array $pageIDs Array of page IDs
700 public function populateFromPageIDs( $pageIDs ) {
701 $this->initFromPageIds( $pageIDs );
705 * Populate this PageSet from a rowset returned from the database
707 * Note that the query result must include the columns returned by
708 * $this->getPageTableFields().
710 * @param IDatabase $db
711 * @param ResultWrapper $queryResult Query result object
713 public function populateFromQueryResult( $db, $queryResult ) {
714 $this->initFromQueryResult( $queryResult );
718 * Populate this PageSet from a list of revision IDs
719 * @param array $revIDs Array of revision IDs
721 public function populateFromRevisionIDs( $revIDs ) {
722 $this->initFromRevIDs( $revIDs );
726 * Extract all requested fields from the row received from the database
727 * @param stdClass $row Result row
729 public function processDbRow( $row ) {
730 // Store Title object in various data structures
731 $title = Title
::newFromRow( $row );
733 $pageId = intval( $row->page_id
);
734 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
735 $this->mTitles
[] = $title;
737 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
738 $this->mPendingRedirectIDs
[$pageId] = $title;
740 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
741 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
742 $this->mGoodTitles
[$pageId] = $title;
745 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
746 $fieldValues[$pageId] = $row->$fieldName;
751 * This method populates internal variables with page information
752 * based on the given array of title strings.
755 * #1 For each title, get data from `page` table
756 * #2 If page was not found in the DB, store it as missing
758 * Additionally, when resolving redirects:
759 * #3 If no more redirects left, stop.
760 * #4 For each redirect, get its target from the `redirect` table.
761 * #5 Substitute the original LinkBatch object with the new list
762 * #6 Repeat from step #1
764 * @param array $titles Array of Title objects or strings
766 private function initFromTitles( $titles ) {
767 // Get validated and normalized title objects
768 $linkBatch = $this->processTitlesArray( $titles );
769 if ( $linkBatch->isEmpty() ) {
773 $db = $this->getDB();
774 $set = $linkBatch->constructSet( 'page', $db );
776 // Get pageIDs data from the `page` table
777 $res = $db->select( 'page', $this->getPageTableFields(), $set,
780 // Hack: get the ns:titles stored in array(ns => array(titles)) format
781 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
783 // Resolve any found redirects
784 $this->resolvePendingRedirects();
788 * Does the same as initFromTitles(), but is based on page IDs instead
789 * @param array $pageids Array of page IDs
791 private function initFromPageIds( $pageids ) {
796 $pageids = array_map( 'intval', $pageids ); // paranoia
797 $remaining = array_flip( $pageids );
799 $pageids = self
::getPositiveIntegers( $pageids );
802 if ( !empty( $pageids ) ) {
804 'page_id' => $pageids
806 $db = $this->getDB();
808 // Get pageIDs data from the `page` table
809 $res = $db->select( 'page', $this->getPageTableFields(), $set,
813 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
815 // Resolve any found redirects
816 $this->resolvePendingRedirects();
820 * Iterate through the result of the query on 'page' table,
821 * and for each row create and store title object and save any extra fields requested.
822 * @param ResultWrapper $res DB Query result
823 * @param array $remaining Array of either pageID or ns/title elements (optional).
824 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
825 * @param bool $processTitles Must be provided together with $remaining.
826 * If true, treat $remaining as an array of [ns][title]
827 * If false, treat it as an array of [pageIDs]
829 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
830 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
831 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
836 foreach ( $res as $row ) {
837 $pageId = intval( $row->page_id
);
839 // Remove found page from the list of remaining items
840 if ( isset( $remaining ) ) {
841 if ( $processTitles ) {
842 unset( $remaining[$row->page_namespace
][$row->page_title
] );
844 unset( $remaining[$pageId] );
848 // Store any extra fields requested by modules
849 $this->processDbRow( $row );
851 // Need gender information
852 if ( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
853 $usernames[] = $row->page_title
;
858 if ( isset( $remaining ) ) {
859 // Any items left in the $remaining list are added as missing
860 if ( $processTitles ) {
861 // The remaining titles in $remaining are non-existent pages
862 foreach ( $remaining as $ns => $dbkeys ) {
863 foreach ( array_keys( $dbkeys ) as $dbkey ) {
864 $title = Title
::makeTitle( $ns, $dbkey );
865 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
866 $this->mMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
867 $this->mGoodAndMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
868 $this->mMissingTitles
[$this->mFakePageId
] = $title;
869 $this->mFakePageId
--;
870 $this->mTitles
[] = $title;
872 // need gender information
873 if ( MWNamespace
::hasGenderDistinction( $ns ) ) {
874 $usernames[] = $dbkey;
879 // The remaining pageids do not exist
880 if ( !$this->mMissingPageIDs
) {
881 $this->mMissingPageIDs
= array_keys( $remaining );
883 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
888 // Get gender information
889 $genderCache = GenderCache
::singleton();
890 $genderCache->doQuery( $usernames, __METHOD__
);
894 * Does the same as initFromTitles(), but is based on revision IDs
896 * @param array $revids Array of revision IDs
898 private function initFromRevIDs( $revids ) {
903 $revids = array_map( 'intval', $revids ); // paranoia
904 $db = $this->getDB();
906 $remaining = array_flip( $revids );
908 $revids = self
::getPositiveIntegers( $revids );
910 if ( !empty( $revids ) ) {
911 $tables = [ 'revision', 'page' ];
912 $fields = [ 'rev_id', 'rev_page' ];
913 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
915 // Get pageIDs data from the `page` table
916 $res = $db->select( $tables, $fields, $where, __METHOD__
);
917 foreach ( $res as $row ) {
918 $revid = intval( $row->rev_id
);
919 $pageid = intval( $row->rev_page
);
920 $this->mGoodRevIDs
[$revid] = $pageid;
921 $this->mLiveRevIDs
[$revid] = $pageid;
922 $pageids[$pageid] = '';
923 unset( $remaining[$revid] );
927 $this->mMissingRevIDs
= array_keys( $remaining );
929 // Populate all the page information
930 $this->initFromPageIds( array_keys( $pageids ) );
932 // If the user can see deleted revisions, pull out the corresponding
933 // titles from the archive table and include them too. We ignore
934 // ar_page_id because deleted revisions are tied by title, not page_id.
935 if ( !empty( $this->mMissingRevIDs
) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
936 $remaining = array_flip( $this->mMissingRevIDs
);
937 $tables = [ 'archive' ];
938 $fields = [ 'ar_rev_id', 'ar_namespace', 'ar_title' ];
939 $where = [ 'ar_rev_id' => $this->mMissingRevIDs
];
941 $res = $db->select( $tables, $fields, $where, __METHOD__
);
943 foreach ( $res as $row ) {
944 $revid = intval( $row->ar_rev_id
);
945 $titles[$revid] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
946 unset( $remaining[$revid] );
949 $this->initFromTitles( $titles );
951 foreach ( $titles as $revid => $title ) {
952 $ns = $title->getNamespace();
953 $dbkey = $title->getDBkey();
955 // Handle converted titles
956 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
957 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
959 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
960 $ns = $title->getNamespace();
961 $dbkey = $title->getDBkey();
964 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
965 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
966 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
968 $remaining[$revid] = true;
972 $this->mMissingRevIDs
= array_keys( $remaining );
977 * Resolve any redirects in the result if redirect resolution was
978 * requested. This function is called repeatedly until all redirects
979 * have been resolved.
981 private function resolvePendingRedirects() {
982 if ( $this->mResolveRedirects
) {
983 $db = $this->getDB();
984 $pageFlds = $this->getPageTableFields();
986 // Repeat until all redirects have been resolved
987 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
988 while ( $this->mPendingRedirectIDs
) {
989 // Resolve redirects by querying the pagelinks table, and repeat the process
990 // Create a new linkBatch object for the next pass
991 $linkBatch = $this->getRedirectTargets();
993 if ( $linkBatch->isEmpty() ) {
997 $set = $linkBatch->constructSet( 'page', $db );
998 if ( $set === false ) {
1002 // Get pageIDs data from the `page` table
1003 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1005 // Hack: get the ns:titles stored in array(ns => array(titles)) format
1006 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1012 * Get the targets of the pending redirects from the database
1014 * Also creates entries in the redirect table for redirects that don't
1018 private function getRedirectTargets() {
1019 $lb = new LinkBatch();
1020 $db = $this->getDB();
1030 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ],
1033 foreach ( $res as $row ) {
1034 $rdfrom = intval( $row->rd_from
);
1035 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1036 $to = Title
::makeTitle(
1042 $this->mResolvedRedirectTitles
[$from] = $this->mPendingRedirectIDs
[$rdfrom];
1043 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1044 if ( $to->isExternal() ) {
1045 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1046 } elseif ( !isset( $this->mAllPages
[$row->rd_namespace
][$row->rd_title
] ) ) {
1047 $lb->add( $row->rd_namespace
, $row->rd_title
);
1049 $this->mRedirectTitles
[$from] = $to;
1052 if ( $this->mPendingRedirectIDs
) {
1053 // We found pages that aren't in the redirect table
1055 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1056 $page = WikiPage
::factory( $title );
1057 $rt = $page->insertRedirect();
1059 // What the hell. Let's just ignore this
1063 $from = $title->getPrefixedText();
1064 $this->mResolvedRedirectTitles
[$from] = $title;
1065 $this->mRedirectTitles
[$from] = $rt;
1066 unset( $this->mPendingRedirectIDs
[$id] );
1074 * Get the cache mode for the data generated by this module.
1075 * All PageSet users should take into account whether this returns a more-restrictive
1076 * cache mode than the using module itself. For possible return values and other
1077 * details about cache modes, see ApiMain::setCacheMode()
1079 * Public caching will only be allowed if *all* the modules that supply
1080 * data for a given request return a cache mode of public.
1082 * @param array|null $params
1086 public function getCacheMode( $params = null ) {
1087 return $this->mCacheMode
;
1091 * Given an array of title strings, convert them into Title objects.
1092 * Alternatively, an array of Title objects may be given.
1093 * This method validates access rights for the title,
1094 * and appends normalization values to the output.
1096 * @param array $titles Array of Title objects or strings
1099 private function processTitlesArray( $titles ) {
1101 $linkBatch = new LinkBatch();
1103 foreach ( $titles as $title ) {
1104 if ( is_string( $title ) ) {
1106 $titleObj = Title
::newFromTextThrow( $title, $this->mDefaultNamespace
);
1107 } catch ( MalformedTitleException
$ex ) {
1108 // Handle invalid titles gracefully
1109 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1110 $this->mInvalidTitles
[$this->mFakePageId
] = [
1112 'invalidreason' => $ex->getMessage(),
1114 $this->mFakePageId
--;
1115 continue; // There's nothing else we can do
1120 $unconvertedTitle = $titleObj->getPrefixedText();
1121 $titleWasConverted = false;
1122 if ( $titleObj->isExternal() ) {
1123 // This title is an interwiki link.
1124 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1126 // Variants checking
1128 if ( $this->mConvertTitles
&&
1129 count( $wgContLang->getVariants() ) > 1 &&
1130 !$titleObj->exists()
1132 // Language::findVariantLink will modify titleText and titleObj into
1133 // the canonical variant if possible
1134 $titleText = is_string( $title ) ?
$title : $titleObj->getPrefixedText();
1135 $wgContLang->findVariantLink( $titleText, $titleObj );
1136 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1139 if ( $titleObj->getNamespace() < 0 ) {
1140 // Handle Special and Media pages
1141 $titleObj = $titleObj->fixSpecialName();
1142 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1143 $this->mFakePageId
--;
1146 $linkBatch->addObj( $titleObj );
1150 // Make sure we remember the original title that was
1151 // given to us. This way the caller can correlate new
1152 // titles with the originally requested when e.g. the
1153 // namespace is localized or the capitalization is
1155 if ( $titleWasConverted ) {
1156 $this->mConvertedTitles
[$unconvertedTitle] = $titleObj->getPrefixedText();
1157 // In this case the page can't be Special.
1158 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1159 $this->mNormalizedTitles
[$title] = $unconvertedTitle;
1161 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1162 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1165 // Need gender information
1166 if ( MWNamespace
::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1167 $usernames[] = $titleObj->getText();
1170 // Get gender information
1171 $genderCache = GenderCache
::singleton();
1172 $genderCache->doQuery( $usernames, __METHOD__
);
1178 * Set data for a title.
1180 * This data may be extracted into an ApiResult using
1181 * self::populateGeneratorData. This should generally be limited to
1182 * data that is likely to be particularly useful to end users rather than
1183 * just being a dump of everything returned in non-generator mode.
1185 * Redirects here will *not* be followed, even if 'redirects' was
1186 * specified, since in the case of multiple redirects we can't know which
1187 * source's data to use on the target.
1189 * @param Title $title
1190 * @param array $data
1192 public function setGeneratorData( Title
$title, array $data ) {
1193 $ns = $title->getNamespace();
1194 $dbkey = $title->getDBkey();
1195 $this->mGeneratorData
[$ns][$dbkey] = $data;
1199 * Controls how generator data about a redirect source is merged into
1200 * the generator data for the redirect target. When not set no data
1201 * is merged. Note that if multiple titles redirect to the same target
1202 * the order of operations is undefined.
1204 * Example to include generated data from redirect in target, prefering
1205 * the data generated for the destination when there is a collision:
1207 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1208 * return $current + $new;
1212 * @param callable|null $callable Recieves two array arguments, first the
1213 * generator data for the redirect target and second the generator data
1214 * for the redirect source. Returns the resulting generator data to use
1215 * for the redirect target.
1217 public function setRedirectMergePolicy( $callable ) {
1218 $this->mRedirectMergePolicy
= $callable;
1222 * Populate the generator data for all titles in the result
1224 * The page data may be inserted into an ApiResult object or into an
1225 * associative array. The $path parameter specifies the path within the
1226 * ApiResult or array to find the "pages" node.
1228 * The "pages" node itself must be an associative array mapping the page ID
1229 * or fake page ID values returned by this pageset (see
1230 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1231 * associative arrays of page data. Each of those subarrays will have the
1232 * data from self::setGeneratorData() merged in.
1234 * Data that was set by self::setGeneratorData() for pages not in the
1235 * "pages" node will be ignored.
1237 * @param ApiResult|array &$result
1238 * @param array $path
1239 * @return bool Whether the data fit
1241 public function populateGeneratorData( &$result, array $path = [] ) {
1242 if ( $result instanceof ApiResult
) {
1243 $data = $result->getResultData( $path );
1244 if ( $data === null ) {
1249 foreach ( $path as $key ) {
1250 if ( !isset( $data[$key] ) ) {
1251 // Path isn't in $result, so nothing to add, so everything
1255 $data = &$data[$key];
1258 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1261 foreach ( $this->mSpecialTitles
as $id => $title ) {
1262 $pages[$title->getDBkey()] = $id;
1265 if ( !isset( $this->mAllPages
[$ns] ) ) {
1266 // No known titles in the whole namespace. Skip it.
1269 $pages = $this->mAllPages
[$ns];
1271 foreach ( $dbkeys as $dbkey => $genData ) {
1272 if ( !isset( $pages[$dbkey] ) ) {
1273 // Unknown title. Forget it.
1276 $pageId = $pages[$dbkey];
1277 if ( !isset( $data[$pageId] ) ) {
1278 // $pageId didn't make it into the result. Ignore it.
1282 if ( $result instanceof ApiResult
) {
1283 $path2 = array_merge( $path, [ $pageId ] );
1284 foreach ( $genData as $key => $value ) {
1285 if ( !$result->addValue( $path2, $key, $value ) ) {
1290 $data[$pageId] = array_merge( $data[$pageId], $genData );
1295 // Merge data generated about redirect titles into the redirect destination
1296 if ( $this->mRedirectMergePolicy
) {
1297 foreach ( $this->mResolvedRedirectTitles
as $titleFrom ) {
1299 while ( isset( $this->mRedirectTitles
[$dest->getPrefixedText()] ) ) {
1300 $dest = $this->mRedirectTitles
[$dest->getPrefixedText()];
1302 $fromNs = $titleFrom->getNamespace();
1303 $fromDBkey = $titleFrom->getDBkey();
1304 $toPageId = $dest->getArticleID();
1305 if ( isset( $data[$toPageId] ) &&
1306 isset( $this->mGeneratorData
[$fromNs][$fromDBkey] )
1308 // It is necesary to set both $data and add to $result, if an ApiResult,
1309 // to ensure multiple redirects to the same destination are all merged.
1310 $data[$toPageId] = call_user_func(
1311 $this->mRedirectMergePolicy
,
1313 $this->mGeneratorData
[$fromNs][$fromDBkey]
1315 if ( $result instanceof ApiResult
) {
1316 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult
::OVERRIDE
) ) {
1328 * Get the database connection (read-only)
1329 * @return DatabaseBase
1331 protected function getDB() {
1332 return $this->mDbSource
->getDB();
1336 * Returns the input array of integers with all values < 0 removed
1338 * @param array $array
1341 private static function getPositiveIntegers( $array ) {
1342 // bug 25734 API: possible issue with revids validation
1343 // It seems with a load of revision rows, MySQL gets upset
1344 // Remove any < 0 integers, as they can't be valid
1345 foreach ( $array as $i => $int ) {
1347 unset( $array[$i] );
1354 public function getAllowedParams( $flags = 0 ) {
1357 ApiBase
::PARAM_ISMULTI
=> true,
1358 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1361 ApiBase
::PARAM_TYPE
=> 'integer',
1362 ApiBase
::PARAM_ISMULTI
=> true,
1363 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1366 ApiBase
::PARAM_TYPE
=> 'integer',
1367 ApiBase
::PARAM_ISMULTI
=> true,
1368 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1371 ApiBase
::PARAM_TYPE
=> null,
1372 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1373 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'g',
1376 ApiBase
::PARAM_DFLT
=> false,
1377 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1378 ?
'api-pageset-param-redirects-generator'
1379 : 'api-pageset-param-redirects-nogenerator',
1381 'converttitles' => [
1382 ApiBase
::PARAM_DFLT
=> false,
1383 ApiBase
::PARAM_HELP_MSG
=> [
1384 'api-pageset-param-converttitles',
1385 new DeferredStringifier(
1386 function ( IContextSource
$context ) {
1387 return $context->getLanguage()
1388 ->commaList( LanguageConverter
::$languagesWithVariants );
1396 if ( !$this->mAllowGenerator
) {
1397 unset( $result['generator'] );
1398 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1399 $result['generator'][ApiBase
::PARAM_TYPE
] = 'submodule';
1400 $result['generator'][ApiBase
::PARAM_SUBMODULE_MAP
] = $this->getGenerators();
1406 private static $generators = null;
1409 * Get an array of all available generators
1412 private function getGenerators() {
1413 if ( self
::$generators === null ) {
1414 $query = $this->mDbSource
;
1415 if ( !( $query instanceof ApiQuery
) ) {
1416 // If the parent container of this pageset is not ApiQuery,
1417 // we must create it to get module manager
1418 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1421 $prefix = $query->getModulePath() . '+';
1422 $mgr = $query->getModuleManager();
1423 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1424 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1425 $gens[$name] = $prefix . $name;
1429 self
::$generators = $gens;
1432 return self
::$generators;