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 $mPendingRedirectSpecialPages = []; // [dbkey] => [ Title $from, Title $to ]
75 private $mResolvedRedirectTitles = [];
76 private $mConvertedTitles = [];
77 private $mGoodRevIDs = [];
78 private $mLiveRevIDs = [];
79 private $mDeletedRevIDs = [];
80 private $mMissingRevIDs = [];
81 private $mGeneratorData = []; // [ns][dbkey] => data array
82 private $mFakePageId = -1;
83 private $mCacheMode = 'public';
84 private $mRequestedPageFields = [];
86 private $mDefaultNamespace = NS_MAIN
;
87 /** @var callable|null */
88 private $mRedirectMergePolicy;
91 * Add all items from $values into the result
92 * @param array $result Output
93 * @param array $values Values to add
94 * @param string[] $flags The names of boolean flags to mark this element
95 * @param string $name If given, name of the value
97 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
98 foreach ( $values as $val ) {
99 if ( $val instanceof Title
) {
101 ApiQueryBase
::addTitleInfo( $v, $val );
102 } elseif ( $name !== null ) {
103 $v = [ $name => $val ];
107 foreach ( $flags as $flag ) {
115 * @param ApiBase $dbSource Module implementing getDB().
116 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
117 * @param int $flags Zero or more flags like DISABLE_GENERATORS
118 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
119 * @since 1.21 accepts $flags instead of two boolean values
121 public function __construct( ApiBase
$dbSource, $flags = 0, $defaultNamespace = NS_MAIN
) {
122 parent
::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
123 $this->mDbSource
= $dbSource;
124 $this->mAllowGenerator
= ( $flags & self
::DISABLE_GENERATORS
) == 0;
125 $this->mDefaultNamespace
= $defaultNamespace;
127 $this->mParams
= $this->extractRequestParams();
128 $this->mResolveRedirects
= $this->mParams
['redirects'];
129 $this->mConvertTitles
= $this->mParams
['converttitles'];
133 * In case execute() is not called, call this method to mark all relevant parameters as used
134 * This prevents unused parameters from being reported as warnings
136 public function executeDryRun() {
137 $this->executeInternal( true );
141 * Populate the PageSet from the request parameters.
143 public function execute() {
144 $this->executeInternal( false );
148 * Populate the PageSet from the request parameters.
149 * @param bool $isDryRun If true, instantiates generator, but only to mark
150 * relevant parameters as used
152 private function executeInternal( $isDryRun ) {
153 $generatorName = $this->mAllowGenerator ?
$this->mParams
['generator'] : null;
154 if ( isset( $generatorName ) ) {
155 $dbSource = $this->mDbSource
;
156 if ( !$dbSource instanceof ApiQuery
) {
157 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
158 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
160 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
161 if ( $generator === null ) {
162 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
164 if ( !$generator instanceof ApiQueryGeneratorBase
) {
165 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
167 // Create a temporary pageset to store generator's output,
168 // add any additional fields generator may need, and execute pageset to populate titles/pageids
169 $tmpPageSet = new ApiPageSet( $dbSource, self
::DISABLE_GENERATORS
);
170 $generator->setGeneratorMode( $tmpPageSet );
171 $this->mCacheMode
= $generator->getCacheMode( $generator->extractRequestParams() );
174 $generator->requestExtraData( $tmpPageSet );
176 $tmpPageSet->executeInternal( $isDryRun );
178 // populate this pageset with the generator output
180 $generator->executeGenerator( $this );
182 // Avoid PHP 7.1 warning of passing $this by reference
184 Hooks
::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$apiModule ] );
186 // Prevent warnings from being reported on these parameters
187 $main = $this->getMain();
188 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
189 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
194 $this->resolvePendingRedirects();
197 // Only one of the titles/pageids/revids is allowed at the same time
199 if ( isset( $this->mParams
['titles'] ) ) {
200 $dataSource = 'titles';
202 if ( isset( $this->mParams
['pageids'] ) ) {
203 if ( isset( $dataSource ) ) {
206 'apierror-invalidparammix-cannotusewith',
207 $this->encodeParamName( 'pageids' ),
208 $this->encodeParamName( $dataSource )
213 $dataSource = 'pageids';
215 if ( isset( $this->mParams
['revids'] ) ) {
216 if ( isset( $dataSource ) ) {
219 'apierror-invalidparammix-cannotusewith',
220 $this->encodeParamName( 'revids' ),
221 $this->encodeParamName( $dataSource )
226 $dataSource = 'revids';
230 // Populate page information with the original user input
231 switch ( $dataSource ) {
233 $this->initFromTitles( $this->mParams
['titles'] );
236 $this->initFromPageIds( $this->mParams
['pageids'] );
239 if ( $this->mResolveRedirects
) {
240 $this->addWarning( 'apiwarn-redirectsandrevids' );
242 $this->mResolveRedirects
= false;
243 $this->initFromRevIDs( $this->mParams
['revids'] );
246 // Do nothing - some queries do not need any of the data sources.
254 * Check whether this PageSet is resolving redirects
257 public function isResolvingRedirects() {
258 return $this->mResolveRedirects
;
262 * Return the parameter name that is the source of data for this PageSet
264 * If multiple source parameters are specified (e.g. titles and pageids),
265 * one will be named arbitrarily.
267 * @return string|null
269 public function getDataSource() {
270 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
273 if ( isset( $this->mParams
['titles'] ) ) {
276 if ( isset( $this->mParams
['pageids'] ) ) {
279 if ( isset( $this->mParams
['revids'] ) ) {
287 * Request an additional field from the page table.
288 * Must be called before execute()
289 * @param string $fieldName Field name
291 public function requestField( $fieldName ) {
292 $this->mRequestedPageFields
[$fieldName] = null;
296 * Get the value of a custom field previously requested through
298 * @param string $fieldName Field name
299 * @return mixed Field value
301 public function getCustomField( $fieldName ) {
302 return $this->mRequestedPageFields
[$fieldName];
306 * Get the fields that have to be queried from the page table:
307 * the ones requested through requestField() and a few basic ones
309 * @return array Array of field names
311 public function getPageTableFields() {
312 // Ensure we get minimum required fields
313 // DON'T change this order
315 'page_namespace' => null,
316 'page_title' => null,
320 if ( $this->mResolveRedirects
) {
321 $pageFlds['page_is_redirect'] = null;
324 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
325 $pageFlds['page_content_model'] = null;
328 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
329 $pageFlds['page_lang'] = null;
332 foreach ( LinkCache
::getSelectFields() as $field ) {
333 $pageFlds[$field] = null;
336 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
338 return array_keys( $pageFlds );
342 * Returns an array [ns][dbkey] => page_id for all requested titles.
343 * page_id is a unique negative number in case title was not found.
344 * Invalid titles will also have negative page IDs and will be in namespace 0
347 public function getAllTitlesByNamespace() {
348 return $this->mAllPages
;
352 * All Title objects provided.
355 public function getTitles() {
356 return $this->mTitles
;
360 * Returns the number of unique pages (not revisions) in the set.
363 public function getTitleCount() {
364 return count( $this->mTitles
);
368 * Returns an array [ns][dbkey] => page_id for all good titles.
371 public function getGoodTitlesByNamespace() {
372 return $this->mGoodPages
;
376 * Title objects that were found in the database.
377 * @return Title[] Array page_id (int) => Title (obj)
379 public function getGoodTitles() {
380 return $this->mGoodTitles
;
384 * Returns the number of found unique pages (not revisions) in the set.
387 public function getGoodTitleCount() {
388 return count( $this->mGoodTitles
);
392 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
393 * fake_page_id is a unique negative number.
396 public function getMissingTitlesByNamespace() {
397 return $this->mMissingPages
;
401 * Title objects that were NOT found in the database.
402 * The array's index will be negative for each item
405 public function getMissingTitles() {
406 return $this->mMissingTitles
;
410 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
413 public function getGoodAndMissingTitlesByNamespace() {
414 return $this->mGoodAndMissingPages
;
418 * Title objects for good and missing titles.
421 public function getGoodAndMissingTitles() {
422 return $this->mGoodTitles +
$this->mMissingTitles
;
426 * Titles that were deemed invalid by Title::newFromText()
427 * The array's index will be unique and negative for each item
428 * @deprecated since 1.26, use self::getInvalidTitlesAndReasons()
429 * @return string[] Array of strings (not Title objects)
431 public function getInvalidTitles() {
432 wfDeprecated( __METHOD__
, '1.26' );
433 return array_map( function ( $t ) {
435 }, $this->mInvalidTitles
);
439 * Titles that were deemed invalid by Title::newFromText()
440 * The array's index will be unique and negative for each item
441 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
443 public function getInvalidTitlesAndReasons() {
444 return $this->mInvalidTitles
;
448 * Page IDs that were not found in the database
449 * @return array Array of page IDs
451 public function getMissingPageIDs() {
452 return $this->mMissingPageIDs
;
456 * Get a list of redirect resolutions - maps a title to its redirect
457 * target, as an array of output-ready arrays
460 public function getRedirectTitles() {
461 return $this->mRedirectTitles
;
465 * Get a list of redirect resolutions - maps a title to its redirect
466 * target. Includes generator data for redirect source when available.
467 * @param ApiResult $result
468 * @return array Array of prefixed_title (string) => Title object
471 public function getRedirectTitlesAsResult( $result = null ) {
473 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
475 'from' => strval( $titleStrFrom ),
476 'to' => $titleTo->getPrefixedText(),
478 if ( $titleTo->hasFragment() ) {
479 $r['tofragment'] = $titleTo->getFragment();
481 if ( $titleTo->isExternal() ) {
482 $r['tointerwiki'] = $titleTo->getInterwiki();
484 if ( isset( $this->mResolvedRedirectTitles
[$titleStrFrom] ) ) {
485 $titleFrom = $this->mResolvedRedirectTitles
[$titleStrFrom];
486 $ns = $titleFrom->getNamespace();
487 $dbkey = $titleFrom->getDBkey();
488 if ( isset( $this->mGeneratorData
[$ns][$dbkey] ) ) {
489 $r = array_merge( $this->mGeneratorData
[$ns][$dbkey], $r );
495 if ( !empty( $values ) && $result ) {
496 ApiResult
::setIndexedTagName( $values, 'r' );
503 * Get a list of title normalizations - maps a title to its normalized
505 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
507 public function getNormalizedTitles() {
508 return $this->mNormalizedTitles
;
512 * Get a list of title normalizations - maps a title to its normalized
513 * version in the form of result array.
514 * @param ApiResult $result
515 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
518 public function getNormalizedTitlesAsResult( $result = null ) {
522 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
523 $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr );
525 'fromencoded' => $encode,
526 'from' => $encode ?
rawurlencode( $rawTitleStr ) : $rawTitleStr,
530 if ( !empty( $values ) && $result ) {
531 ApiResult
::setIndexedTagName( $values, 'n' );
538 * Get a list of title conversions - maps a title to its converted
540 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
542 public function getConvertedTitles() {
543 return $this->mConvertedTitles
;
547 * Get a list of title conversions - maps a title to its converted
548 * version as a result array.
549 * @param ApiResult $result
550 * @return array Array of (from, to) strings
553 public function getConvertedTitlesAsResult( $result = null ) {
555 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
557 'from' => $rawTitleStr,
561 if ( !empty( $values ) && $result ) {
562 ApiResult
::setIndexedTagName( $values, 'c' );
569 * Get a list of interwiki titles - maps a title to its interwiki
571 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
573 public function getInterwikiTitles() {
574 return $this->mInterwikiTitles
;
578 * Get a list of interwiki titles - maps a title to its interwiki
580 * @param ApiResult $result
582 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
585 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
587 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
589 'title' => $rawTitleStr,
590 'iw' => $interwikiStr,
593 $title = Title
::newFromText( $rawTitleStr );
594 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
598 if ( !empty( $values ) && $result ) {
599 ApiResult
::setIndexedTagName( $values, 'i' );
606 * Get an array of invalid/special/missing titles.
608 * @param array $invalidChecks List of types of invalid titles to include.
609 * Recognized values are:
610 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
611 * - special: Titles from $this->getSpecialTitles()
612 * - missingIds: ids from $this->getMissingPageIDs()
613 * - missingRevIds: ids from $this->getMissingRevisionIDs()
614 * - missingTitles: Titles from $this->getMissingTitles()
615 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
616 * @return array Array suitable for inclusion in the response
619 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
620 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
623 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
624 self
::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
626 if ( in_array( 'special', $invalidChecks ) ) {
629 foreach ( $this->getSpecialTitles() as $title ) {
630 if ( $title->isKnown() ) {
636 self
::addValues( $result, $unknown, [ 'special', 'missing' ] );
637 self
::addValues( $result, $known, [ 'special' ] );
639 if ( in_array( 'missingIds', $invalidChecks ) ) {
640 self
::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
642 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
643 self
::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
645 if ( in_array( 'missingTitles', $invalidChecks ) ) {
648 foreach ( $this->getMissingTitles() as $title ) {
649 if ( $title->isKnown() ) {
655 self
::addValues( $result, $unknown, [ 'missing' ] );
656 self
::addValues( $result, $known, [ 'missing', 'known' ] );
658 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
659 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
666 * Get the list of valid revision IDs (requested with the revids= parameter)
667 * @return array Array of revID (int) => pageID (int)
669 public function getRevisionIDs() {
670 return $this->mGoodRevIDs
;
674 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
675 * @return array Array of revID (int) => pageID (int)
677 public function getLiveRevisionIDs() {
678 return $this->mLiveRevIDs
;
682 * Get the list of revision IDs that were associated with deleted titles.
683 * @return array Array of revID (int) => pageID (int)
685 public function getDeletedRevisionIDs() {
686 return $this->mDeletedRevIDs
;
690 * Revision IDs that were not found in the database
691 * @return array Array of revision IDs
693 public function getMissingRevisionIDs() {
694 return $this->mMissingRevIDs
;
698 * Revision IDs that were not found in the database as result array.
699 * @param ApiResult $result
700 * @return array Array of revision IDs
703 public function getMissingRevisionIDsAsResult( $result = null ) {
705 foreach ( $this->getMissingRevisionIDs() as $revid ) {
710 if ( !empty( $values ) && $result ) {
711 ApiResult
::setIndexedTagName( $values, 'rev' );
718 * Get the list of titles with negative namespace
721 public function getSpecialTitles() {
722 return $this->mSpecialTitles
;
726 * Returns the number of revisions (requested with revids= parameter).
727 * @return int Number of revisions.
729 public function getRevisionCount() {
730 return count( $this->getRevisionIDs() );
734 * Populate this PageSet from a list of Titles
735 * @param array $titles Array of Title objects
737 public function populateFromTitles( $titles ) {
738 $this->initFromTitles( $titles );
742 * Populate this PageSet from a list of page IDs
743 * @param array $pageIDs Array of page IDs
745 public function populateFromPageIDs( $pageIDs ) {
746 $this->initFromPageIds( $pageIDs );
750 * Populate this PageSet from a rowset returned from the database
752 * Note that the query result must include the columns returned by
753 * $this->getPageTableFields().
755 * @param IDatabase $db
756 * @param ResultWrapper $queryResult Query result object
758 public function populateFromQueryResult( $db, $queryResult ) {
759 $this->initFromQueryResult( $queryResult );
763 * Populate this PageSet from a list of revision IDs
764 * @param array $revIDs Array of revision IDs
766 public function populateFromRevisionIDs( $revIDs ) {
767 $this->initFromRevIDs( $revIDs );
771 * Extract all requested fields from the row received from the database
772 * @param stdClass $row Result row
774 public function processDbRow( $row ) {
775 // Store Title object in various data structures
776 $title = Title
::newFromRow( $row );
778 LinkCache
::singleton()->addGoodLinkObjFromRow( $title, $row );
780 $pageId = intval( $row->page_id
);
781 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
782 $this->mTitles
[] = $title;
784 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
785 $this->mPendingRedirectIDs
[$pageId] = $title;
787 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
788 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
789 $this->mGoodTitles
[$pageId] = $title;
792 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
793 $fieldValues[$pageId] = $row->$fieldName;
798 * This method populates internal variables with page information
799 * based on the given array of title strings.
802 * #1 For each title, get data from `page` table
803 * #2 If page was not found in the DB, store it as missing
805 * Additionally, when resolving redirects:
806 * #3 If no more redirects left, stop.
807 * #4 For each redirect, get its target from the `redirect` table.
808 * #5 Substitute the original LinkBatch object with the new list
809 * #6 Repeat from step #1
811 * @param array $titles Array of Title objects or strings
813 private function initFromTitles( $titles ) {
814 // Get validated and normalized title objects
815 $linkBatch = $this->processTitlesArray( $titles );
816 if ( $linkBatch->isEmpty() ) {
817 // There might be special-page redirects
818 $this->resolvePendingRedirects();
822 $db = $this->getDB();
823 $set = $linkBatch->constructSet( 'page', $db );
825 // Get pageIDs data from the `page` table
826 $res = $db->select( 'page', $this->getPageTableFields(), $set,
829 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
830 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
832 // Resolve any found redirects
833 $this->resolvePendingRedirects();
837 * Does the same as initFromTitles(), but is based on page IDs instead
838 * @param array $pageids Array of page IDs
840 private function initFromPageIds( $pageids ) {
845 $pageids = array_map( 'intval', $pageids ); // paranoia
846 $remaining = array_flip( $pageids );
848 $pageids = self
::getPositiveIntegers( $pageids );
851 if ( !empty( $pageids ) ) {
853 'page_id' => $pageids
855 $db = $this->getDB();
857 // Get pageIDs data from the `page` table
858 $res = $db->select( 'page', $this->getPageTableFields(), $set,
862 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
864 // Resolve any found redirects
865 $this->resolvePendingRedirects();
869 * Iterate through the result of the query on 'page' table,
870 * and for each row create and store title object and save any extra fields requested.
871 * @param ResultWrapper $res DB Query result
872 * @param array $remaining Array of either pageID or ns/title elements (optional).
873 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
874 * @param bool $processTitles Must be provided together with $remaining.
875 * If true, treat $remaining as an array of [ns][title]
876 * If false, treat it as an array of [pageIDs]
878 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
879 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
880 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
885 foreach ( $res as $row ) {
886 $pageId = intval( $row->page_id
);
888 // Remove found page from the list of remaining items
889 if ( isset( $remaining ) ) {
890 if ( $processTitles ) {
891 unset( $remaining[$row->page_namespace
][$row->page_title
] );
893 unset( $remaining[$pageId] );
897 // Store any extra fields requested by modules
898 $this->processDbRow( $row );
900 // Need gender information
901 if ( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
902 $usernames[] = $row->page_title
;
907 if ( isset( $remaining ) ) {
908 // Any items left in the $remaining list are added as missing
909 if ( $processTitles ) {
910 // The remaining titles in $remaining are non-existent pages
911 $linkCache = LinkCache
::singleton();
912 foreach ( $remaining as $ns => $dbkeys ) {
913 foreach ( array_keys( $dbkeys ) as $dbkey ) {
914 $title = Title
::makeTitle( $ns, $dbkey );
915 $linkCache->addBadLinkObj( $title );
916 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
917 $this->mMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
918 $this->mGoodAndMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
919 $this->mMissingTitles
[$this->mFakePageId
] = $title;
920 $this->mFakePageId
--;
921 $this->mTitles
[] = $title;
923 // need gender information
924 if ( MWNamespace
::hasGenderDistinction( $ns ) ) {
925 $usernames[] = $dbkey;
930 // The remaining pageids do not exist
931 if ( !$this->mMissingPageIDs
) {
932 $this->mMissingPageIDs
= array_keys( $remaining );
934 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
939 // Get gender information
940 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
941 $genderCache->doQuery( $usernames, __METHOD__
);
945 * Does the same as initFromTitles(), but is based on revision IDs
947 * @param array $revids Array of revision IDs
949 private function initFromRevIDs( $revids ) {
954 $revids = array_map( 'intval', $revids ); // paranoia
955 $db = $this->getDB();
957 $remaining = array_flip( $revids );
959 $revids = self
::getPositiveIntegers( $revids );
961 if ( !empty( $revids ) ) {
962 $tables = [ 'revision', 'page' ];
963 $fields = [ 'rev_id', 'rev_page' ];
964 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
966 // Get pageIDs data from the `page` table
967 $res = $db->select( $tables, $fields, $where, __METHOD__
);
968 foreach ( $res as $row ) {
969 $revid = intval( $row->rev_id
);
970 $pageid = intval( $row->rev_page
);
971 $this->mGoodRevIDs
[$revid] = $pageid;
972 $this->mLiveRevIDs
[$revid] = $pageid;
973 $pageids[$pageid] = '';
974 unset( $remaining[$revid] );
978 $this->mMissingRevIDs
= array_keys( $remaining );
980 // Populate all the page information
981 $this->initFromPageIds( array_keys( $pageids ) );
983 // If the user can see deleted revisions, pull out the corresponding
984 // titles from the archive table and include them too. We ignore
985 // ar_page_id because deleted revisions are tied by title, not page_id.
986 if ( !empty( $this->mMissingRevIDs
) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
987 $remaining = array_flip( $this->mMissingRevIDs
);
988 $tables = [ 'archive' ];
989 $fields = [ 'ar_rev_id', 'ar_namespace', 'ar_title' ];
990 $where = [ 'ar_rev_id' => $this->mMissingRevIDs
];
992 $res = $db->select( $tables, $fields, $where, __METHOD__
);
994 foreach ( $res as $row ) {
995 $revid = intval( $row->ar_rev_id
);
996 $titles[$revid] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
997 unset( $remaining[$revid] );
1000 $this->initFromTitles( $titles );
1002 foreach ( $titles as $revid => $title ) {
1003 $ns = $title->getNamespace();
1004 $dbkey = $title->getDBkey();
1006 // Handle converted titles
1007 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
1008 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
1010 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
1011 $ns = $title->getNamespace();
1012 $dbkey = $title->getDBkey();
1015 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
1016 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1017 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1019 $remaining[$revid] = true;
1023 $this->mMissingRevIDs
= array_keys( $remaining );
1028 * Resolve any redirects in the result if redirect resolution was
1029 * requested. This function is called repeatedly until all redirects
1030 * have been resolved.
1032 private function resolvePendingRedirects() {
1033 if ( $this->mResolveRedirects
) {
1034 $db = $this->getDB();
1035 $pageFlds = $this->getPageTableFields();
1037 // Repeat until all redirects have been resolved
1038 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
1039 while ( $this->mPendingRedirectIDs ||
$this->mPendingRedirectSpecialPages
) {
1040 // Resolve redirects by querying the pagelinks table, and repeat the process
1041 // Create a new linkBatch object for the next pass
1042 $linkBatch = $this->getRedirectTargets();
1044 if ( $linkBatch->isEmpty() ) {
1048 $set = $linkBatch->constructSet( 'page', $db );
1049 if ( $set === false ) {
1053 // Get pageIDs data from the `page` table
1054 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1056 // Hack: get the ns:titles stored in [ns => array(titles)] format
1057 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1063 * Get the targets of the pending redirects from the database
1065 * Also creates entries in the redirect table for redirects that don't
1069 private function getRedirectTargets() {
1070 $titlesToResolve = [];
1071 $db = $this->getDB();
1073 if ( $this->mPendingRedirectIDs
) {
1082 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ],
1085 foreach ( $res as $row ) {
1086 $rdfrom = intval( $row->rd_from
);
1087 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1088 $to = Title
::makeTitle(
1094 $this->mResolvedRedirectTitles
[$from] = $this->mPendingRedirectIDs
[$rdfrom];
1095 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1096 if ( $to->isExternal() ) {
1097 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1098 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1099 $titlesToResolve[] = $to;
1101 $this->mRedirectTitles
[$from] = $to;
1104 if ( $this->mPendingRedirectIDs
) {
1105 // We found pages that aren't in the redirect table
1107 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1108 $page = WikiPage
::factory( $title );
1109 $rt = $page->insertRedirect();
1111 // What the hell. Let's just ignore this
1114 if ( $rt->isExternal() ) {
1115 $this->mInterwikiTitles
[$rt->getPrefixedText()] = $rt->getInterwiki();
1116 } elseif ( !isset( $this->mAllPages
[$rt->getNamespace()][$rt->getDBkey()] ) ) {
1117 $titlesToResolve[] = $rt;
1119 $from = $title->getPrefixedText();
1120 $this->mResolvedRedirectTitles
[$from] = $title;
1121 $this->mRedirectTitles
[$from] = $rt;
1122 unset( $this->mPendingRedirectIDs
[$id] );
1127 if ( $this->mPendingRedirectSpecialPages
) {
1128 foreach ( $this->mPendingRedirectSpecialPages
as $key => list( $from, $to ) ) {
1129 $fromKey = $from->getPrefixedText();
1130 $this->mResolvedRedirectTitles
[$fromKey] = $from;
1131 $this->mRedirectTitles
[$fromKey] = $to;
1132 if ( $to->isExternal() ) {
1133 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1134 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1135 $titlesToResolve[] = $to;
1138 $this->mPendingRedirectSpecialPages
= [];
1140 // Set private caching since we don't know what criteria the
1141 // special pages used to decide on these redirects.
1142 $this->mCacheMode
= 'private';
1145 return $this->processTitlesArray( $titlesToResolve );
1149 * Get the cache mode for the data generated by this module.
1150 * All PageSet users should take into account whether this returns a more-restrictive
1151 * cache mode than the using module itself. For possible return values and other
1152 * details about cache modes, see ApiMain::setCacheMode()
1154 * Public caching will only be allowed if *all* the modules that supply
1155 * data for a given request return a cache mode of public.
1157 * @param array|null $params
1161 public function getCacheMode( $params = null ) {
1162 return $this->mCacheMode
;
1166 * Given an array of title strings, convert them into Title objects.
1167 * Alternatively, an array of Title objects may be given.
1168 * This method validates access rights for the title,
1169 * and appends normalization values to the output.
1171 * @param array $titles Array of Title objects or strings
1174 private function processTitlesArray( $titles ) {
1176 $linkBatch = new LinkBatch();
1178 foreach ( $titles as $title ) {
1179 if ( is_string( $title ) ) {
1181 $titleObj = Title
::newFromTextThrow( $title, $this->mDefaultNamespace
);
1182 } catch ( MalformedTitleException
$ex ) {
1183 // Handle invalid titles gracefully
1184 if ( !isset( $this->mAllPages
[0][$title] ) ) {
1185 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1186 $this->mInvalidTitles
[$this->mFakePageId
] = [
1188 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1190 $this->mFakePageId
--;
1192 continue; // There's nothing else we can do
1197 $unconvertedTitle = $titleObj->getPrefixedText();
1198 $titleWasConverted = false;
1199 if ( $titleObj->isExternal() ) {
1200 // This title is an interwiki link.
1201 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1203 // Variants checking
1205 if ( $this->mConvertTitles
&&
1206 count( $wgContLang->getVariants() ) > 1 &&
1207 !$titleObj->exists()
1209 // Language::findVariantLink will modify titleText and titleObj into
1210 // the canonical variant if possible
1211 $titleText = is_string( $title ) ?
$title : $titleObj->getPrefixedText();
1212 $wgContLang->findVariantLink( $titleText, $titleObj );
1213 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1216 if ( $titleObj->getNamespace() < 0 ) {
1217 // Handle Special and Media pages
1218 $titleObj = $titleObj->fixSpecialName();
1219 $ns = $titleObj->getNamespace();
1220 $dbkey = $titleObj->getDBkey();
1221 if ( !isset( $this->mAllSpecials
[$ns][$dbkey] ) ) {
1222 $this->mAllSpecials
[$ns][$dbkey] = $this->mFakePageId
;
1224 if ( $ns === NS_SPECIAL
&& $this->mResolveRedirects
) {
1225 $special = SpecialPageFactory
::getPage( $dbkey );
1226 if ( $special instanceof RedirectSpecialArticle
) {
1227 // Only RedirectSpecialArticle is intended to redirect to an article, other kinds of
1228 // RedirectSpecialPage are probably applying weird URL parameters we don't want to handle.
1229 $context = new DerivativeContext( $this );
1230 $context->setTitle( $titleObj );
1231 $context->setRequest( new FauxRequest
);
1232 $special->setContext( $context );
1233 list( /* $alias */, $subpage ) = SpecialPageFactory
::resolveAlias( $dbkey );
1234 $target = $special->getRedirect( $subpage );
1238 $this->mPendingRedirectSpecialPages
[$dbkey] = [ $titleObj, $target ];
1240 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1241 $this->mFakePageId
--;
1246 $linkBatch->addObj( $titleObj );
1250 // Make sure we remember the original title that was
1251 // given to us. This way the caller can correlate new
1252 // titles with the originally requested when e.g. the
1253 // namespace is localized or the capitalization is
1255 if ( $titleWasConverted ) {
1256 $this->mConvertedTitles
[$unconvertedTitle] = $titleObj->getPrefixedText();
1257 // In this case the page can't be Special.
1258 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1259 $this->mNormalizedTitles
[$title] = $unconvertedTitle;
1261 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1262 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1265 // Need gender information
1266 if ( MWNamespace
::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1267 $usernames[] = $titleObj->getText();
1270 // Get gender information
1271 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
1272 $genderCache->doQuery( $usernames, __METHOD__
);
1278 * Set data for a title.
1280 * This data may be extracted into an ApiResult using
1281 * self::populateGeneratorData. This should generally be limited to
1282 * data that is likely to be particularly useful to end users rather than
1283 * just being a dump of everything returned in non-generator mode.
1285 * Redirects here will *not* be followed, even if 'redirects' was
1286 * specified, since in the case of multiple redirects we can't know which
1287 * source's data to use on the target.
1289 * @param Title $title
1290 * @param array $data
1292 public function setGeneratorData( Title
$title, array $data ) {
1293 $ns = $title->getNamespace();
1294 $dbkey = $title->getDBkey();
1295 $this->mGeneratorData
[$ns][$dbkey] = $data;
1299 * Controls how generator data about a redirect source is merged into
1300 * the generator data for the redirect target. When not set no data
1301 * is merged. Note that if multiple titles redirect to the same target
1302 * the order of operations is undefined.
1304 * Example to include generated data from redirect in target, prefering
1305 * the data generated for the destination when there is a collision:
1307 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1308 * return $current + $new;
1312 * @param callable|null $callable Recieves two array arguments, first the
1313 * generator data for the redirect target and second the generator data
1314 * for the redirect source. Returns the resulting generator data to use
1315 * for the redirect target.
1317 public function setRedirectMergePolicy( $callable ) {
1318 $this->mRedirectMergePolicy
= $callable;
1322 * Populate the generator data for all titles in the result
1324 * The page data may be inserted into an ApiResult object or into an
1325 * associative array. The $path parameter specifies the path within the
1326 * ApiResult or array to find the "pages" node.
1328 * The "pages" node itself must be an associative array mapping the page ID
1329 * or fake page ID values returned by this pageset (see
1330 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1331 * associative arrays of page data. Each of those subarrays will have the
1332 * data from self::setGeneratorData() merged in.
1334 * Data that was set by self::setGeneratorData() for pages not in the
1335 * "pages" node will be ignored.
1337 * @param ApiResult|array &$result
1338 * @param array $path
1339 * @return bool Whether the data fit
1341 public function populateGeneratorData( &$result, array $path = [] ) {
1342 if ( $result instanceof ApiResult
) {
1343 $data = $result->getResultData( $path );
1344 if ( $data === null ) {
1349 foreach ( $path as $key ) {
1350 if ( !isset( $data[$key] ) ) {
1351 // Path isn't in $result, so nothing to add, so everything
1355 $data = &$data[$key];
1358 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1359 if ( $ns === NS_SPECIAL
) {
1361 foreach ( $this->mSpecialTitles
as $id => $title ) {
1362 $pages[$title->getDBkey()] = $id;
1365 if ( !isset( $this->mAllPages
[$ns] ) ) {
1366 // No known titles in the whole namespace. Skip it.
1369 $pages = $this->mAllPages
[$ns];
1371 foreach ( $dbkeys as $dbkey => $genData ) {
1372 if ( !isset( $pages[$dbkey] ) ) {
1373 // Unknown title. Forget it.
1376 $pageId = $pages[$dbkey];
1377 if ( !isset( $data[$pageId] ) ) {
1378 // $pageId didn't make it into the result. Ignore it.
1382 if ( $result instanceof ApiResult
) {
1383 $path2 = array_merge( $path, [ $pageId ] );
1384 foreach ( $genData as $key => $value ) {
1385 if ( !$result->addValue( $path2, $key, $value ) ) {
1390 $data[$pageId] = array_merge( $data[$pageId], $genData );
1395 // Merge data generated about redirect titles into the redirect destination
1396 if ( $this->mRedirectMergePolicy
) {
1397 foreach ( $this->mResolvedRedirectTitles
as $titleFrom ) {
1399 while ( isset( $this->mRedirectTitles
[$dest->getPrefixedText()] ) ) {
1400 $dest = $this->mRedirectTitles
[$dest->getPrefixedText()];
1402 $fromNs = $titleFrom->getNamespace();
1403 $fromDBkey = $titleFrom->getDBkey();
1404 $toPageId = $dest->getArticleID();
1405 if ( isset( $data[$toPageId] ) &&
1406 isset( $this->mGeneratorData
[$fromNs][$fromDBkey] )
1408 // It is necesary to set both $data and add to $result, if an ApiResult,
1409 // to ensure multiple redirects to the same destination are all merged.
1410 $data[$toPageId] = call_user_func(
1411 $this->mRedirectMergePolicy
,
1413 $this->mGeneratorData
[$fromNs][$fromDBkey]
1415 if ( $result instanceof ApiResult
) {
1416 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult
::OVERRIDE
) ) {
1428 * Get the database connection (read-only)
1431 protected function getDB() {
1432 return $this->mDbSource
->getDB();
1436 * Returns the input array of integers with all values < 0 removed
1438 * @param array $array
1441 private static function getPositiveIntegers( $array ) {
1442 // T27734 API: possible issue with revids validation
1443 // It seems with a load of revision rows, MySQL gets upset
1444 // Remove any < 0 integers, as they can't be valid
1445 foreach ( $array as $i => $int ) {
1447 unset( $array[$i] );
1454 public function getAllowedParams( $flags = 0 ) {
1457 ApiBase
::PARAM_ISMULTI
=> true,
1458 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1461 ApiBase
::PARAM_TYPE
=> 'integer',
1462 ApiBase
::PARAM_ISMULTI
=> true,
1463 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1466 ApiBase
::PARAM_TYPE
=> 'integer',
1467 ApiBase
::PARAM_ISMULTI
=> true,
1468 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1471 ApiBase
::PARAM_TYPE
=> null,
1472 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1473 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'g',
1476 ApiBase
::PARAM_DFLT
=> false,
1477 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1478 ?
'api-pageset-param-redirects-generator'
1479 : 'api-pageset-param-redirects-nogenerator',
1481 'converttitles' => [
1482 ApiBase
::PARAM_DFLT
=> false,
1483 ApiBase
::PARAM_HELP_MSG
=> [
1484 'api-pageset-param-converttitles',
1485 [ Message
::listParam( LanguageConverter
::$languagesWithVariants, 'text' ) ],
1490 if ( !$this->mAllowGenerator
) {
1491 unset( $result['generator'] );
1492 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1493 $result['generator'][ApiBase
::PARAM_TYPE
] = 'submodule';
1494 $result['generator'][ApiBase
::PARAM_SUBMODULE_MAP
] = $this->getGenerators();
1500 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1501 parent
::handleParamNormalization( $paramName, $value, $rawValue );
1503 if ( $paramName === 'titles' ) {
1504 // For the 'titles' parameter, we want to split it like ApiBase would
1505 // and add any changed titles to $this->mNormalizedTitles
1506 $value = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1507 $l = count( $value );
1508 $rawValue = $this->explodeMultiValue( $rawValue, $l );
1509 for ( $i = 0; $i < $l; $i++
) {
1510 if ( $value[$i] !== $rawValue[$i] ) {
1511 $this->mNormalizedTitles
[$rawValue[$i]] = $value[$i];
1517 private static $generators = null;
1520 * Get an array of all available generators
1523 private function getGenerators() {
1524 if ( self
::$generators === null ) {
1525 $query = $this->mDbSource
;
1526 if ( !( $query instanceof ApiQuery
) ) {
1527 // If the parent container of this pageset is not ApiQuery,
1528 // we must create it to get module manager
1529 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1532 $prefix = $query->getModulePath() . '+';
1533 $mgr = $query->getModuleManager();
1534 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1535 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1536 $gens[$name] = $prefix . $name;
1540 self
::$generators = $gens;
1543 return self
::$generators;