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 = array(); // [ns][dbkey] => page_id or negative when missing
55 private $mTitles = array();
56 private $mGoodAndMissingPages = array(); // [ns][dbkey] => page_id or negative when missing
57 private $mGoodPages = array(); // [ns][dbkey] => page_id
58 private $mGoodTitles = array();
59 private $mMissingPages = array(); // [ns][dbkey] => fake page_id
60 private $mMissingTitles = array();
61 private $mInvalidTitles = array();
62 private $mMissingPageIDs = array();
63 private $mRedirectTitles = array();
64 private $mSpecialTitles = array();
65 private $mNormalizedTitles = array();
66 private $mInterwikiTitles = array();
68 private $mPendingRedirectIDs = array();
69 private $mConvertedTitles = array();
70 private $mGoodRevIDs = array();
71 private $mLiveRevIDs = array();
72 private $mDeletedRevIDs = array();
73 private $mMissingRevIDs = array();
74 private $mGeneratorData = array(); // [ns][dbkey] => data array
75 private $mFakePageId = -1;
76 private $mCacheMode = 'public';
77 private $mRequestedPageFields = array();
79 private $mDefaultNamespace = NS_MAIN
;
82 * Add all items from $values into the result
83 * @param array $result Output
84 * @param array $values Values to add
85 * @param string $flag The name of the boolean flag to mark this element
86 * @param string $name If given, name of the value
88 private static function addValues( array &$result, $values, $flag = null, $name = null ) {
89 foreach ( $values as $val ) {
90 if ( $val instanceof Title
) {
92 ApiQueryBase
::addTitleInfo( $v, $val );
93 } elseif ( $name !== null ) {
94 $v = array( $name => $val );
98 if ( $flag !== null ) {
106 * @param ApiBase $dbSource Module implementing getDB().
107 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
108 * @param int $flags Zero or more flags like DISABLE_GENERATORS
109 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
110 * @since 1.21 accepts $flags instead of two boolean values
112 public function __construct( ApiBase
$dbSource, $flags = 0, $defaultNamespace = NS_MAIN
) {
113 parent
::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
114 $this->mDbSource
= $dbSource;
115 $this->mAllowGenerator
= ( $flags & ApiPageSet
::DISABLE_GENERATORS
) == 0;
116 $this->mDefaultNamespace
= $defaultNamespace;
119 $this->mParams
= $this->extractRequestParams();
120 $this->mResolveRedirects
= $this->mParams
['redirects'];
121 $this->mConvertTitles
= $this->mParams
['converttitles'];
126 * In case execute() is not called, call this method to mark all relevant parameters as used
127 * This prevents unused parameters from being reported as warnings
129 public function executeDryRun() {
130 $this->executeInternal( true );
134 * Populate the PageSet from the request parameters.
136 public function execute() {
137 $this->executeInternal( false );
141 * Populate the PageSet from the request parameters.
142 * @param bool $isDryRun If true, instantiates generator, but only to mark
143 * relevant parameters as used
145 private function executeInternal( $isDryRun ) {
148 $generatorName = $this->mAllowGenerator ?
$this->mParams
['generator'] : null;
149 if ( isset( $generatorName ) ) {
150 $dbSource = $this->mDbSource
;
151 $isQuery = $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' );
155 // Enable profiling for query module because it will be used for db sql profiling
156 $dbSource->profileIn();
158 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
159 if ( $generator === null ) {
160 $this->dieUsage( 'Unknown generator=' . $generatorName, 'badgenerator' );
162 if ( !$generator instanceof ApiQueryGeneratorBase
) {
163 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
165 // Create a temporary pageset to store generator's output,
166 // add any additional fields generator may need, and execute pageset to populate titles/pageids
167 $tmpPageSet = new ApiPageSet( $dbSource, ApiPageSet
::DISABLE_GENERATORS
);
168 $generator->setGeneratorMode( $tmpPageSet );
169 $this->mCacheMode
= $generator->getCacheMode( $generator->extractRequestParams() );
172 $generator->requestExtraData( $tmpPageSet );
174 $tmpPageSet->executeInternal( $isDryRun );
176 // populate this pageset with the generator output
178 $generator->profileIn();
181 $generator->executeGenerator( $this );
182 Hooks
::run( 'APIQueryGeneratorAfterExecute', array( &$generator, &$this ) );
184 // Prevent warnings from being reported on these parameters
185 $main = $this->getMain();
186 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
187 $main->getVal( $generator->encodeParamName( $paramName ) );
190 $generator->profileOut();
194 $this->resolvePendingRedirects();
198 // If this pageset is not part of the query, we called profileIn() above
199 $dbSource->profileOut();
202 // Only one of the titles/pageids/revids is allowed at the same time
204 if ( isset( $this->mParams
['titles'] ) ) {
205 $dataSource = 'titles';
207 if ( isset( $this->mParams
['pageids'] ) ) {
208 if ( isset( $dataSource ) ) {
209 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
211 $dataSource = 'pageids';
213 if ( isset( $this->mParams
['revids'] ) ) {
214 if ( isset( $dataSource ) ) {
215 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
217 $dataSource = 'revids';
221 // Populate page information with the original user input
222 switch ( $dataSource ) {
224 $this->initFromTitles( $this->mParams
['titles'] );
227 $this->initFromPageIds( $this->mParams
['pageids'] );
230 if ( $this->mResolveRedirects
) {
231 $this->setWarning( 'Redirect resolution cannot be used ' .
232 'together with the revids= parameter. Any redirects ' .
233 'the revids= point to have not been resolved.' );
235 $this->mResolveRedirects
= false;
236 $this->initFromRevIDs( $this->mParams
['revids'] );
239 // Do nothing - some queries do not need any of the data sources.
248 * Check whether this PageSet is resolving redirects
251 public function isResolvingRedirects() {
252 return $this->mResolveRedirects
;
256 * Return the parameter name that is the source of data for this PageSet
258 * If multiple source parameters are specified (e.g. titles and pageids),
259 * one will be named arbitrarily.
261 * @return string|null
263 public function getDataSource() {
264 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
267 if ( isset( $this->mParams
['titles'] ) ) {
270 if ( isset( $this->mParams
['pageids'] ) ) {
273 if ( isset( $this->mParams
['revids'] ) ) {
281 * Request an additional field from the page table.
282 * Must be called before execute()
283 * @param string $fieldName Field name
285 public function requestField( $fieldName ) {
286 $this->mRequestedPageFields
[$fieldName] = null;
290 * Get the value of a custom field previously requested through
292 * @param string $fieldName Field name
293 * @return mixed Field value
295 public function getCustomField( $fieldName ) {
296 return $this->mRequestedPageFields
[$fieldName];
300 * Get the fields that have to be queried from the page table:
301 * the ones requested through requestField() and a few basic ones
303 * @return array Array of field names
305 public function getPageTableFields() {
306 // Ensure we get minimum required fields
307 // DON'T change this order
309 'page_namespace' => null,
310 'page_title' => null,
314 if ( $this->mResolveRedirects
) {
315 $pageFlds['page_is_redirect'] = null;
318 // only store non-default fields
319 $this->mRequestedPageFields
= array_diff_key( $this->mRequestedPageFields
, $pageFlds );
321 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
323 return array_keys( $pageFlds );
327 * Returns an array [ns][dbkey] => page_id for all requested titles.
328 * page_id is a unique negative number in case title was not found.
329 * Invalid titles will also have negative page IDs and will be in namespace 0
332 public function getAllTitlesByNamespace() {
333 return $this->mAllPages
;
337 * All Title objects provided.
340 public function getTitles() {
341 return $this->mTitles
;
345 * Returns the number of unique pages (not revisions) in the set.
348 public function getTitleCount() {
349 return count( $this->mTitles
);
353 * Returns an array [ns][dbkey] => page_id for all good titles.
356 public function getGoodTitlesByNamespace() {
357 return $this->mGoodPages
;
361 * Title objects that were found in the database.
362 * @return Title[] Array page_id (int) => Title (obj)
364 public function getGoodTitles() {
365 return $this->mGoodTitles
;
369 * Returns the number of found unique pages (not revisions) in the set.
372 public function getGoodTitleCount() {
373 return count( $this->mGoodTitles
);
377 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
378 * fake_page_id is a unique negative number.
381 public function getMissingTitlesByNamespace() {
382 return $this->mMissingPages
;
386 * Title objects that were NOT found in the database.
387 * The array's index will be negative for each item
390 public function getMissingTitles() {
391 return $this->mMissingTitles
;
395 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
398 public function getGoodAndMissingTitlesByNamespace() {
399 return $this->mGoodAndMissingPages
;
403 * Title objects for good and missing titles.
406 public function getGoodAndMissingTitles() {
407 return $this->mGoodTitles +
$this->mMissingTitles
;
411 * Titles that were deemed invalid by Title::newFromText()
412 * The array's index will be unique and negative for each item
413 * @return string[] Array of strings (not Title objects)
415 public function getInvalidTitles() {
416 return $this->mInvalidTitles
;
420 * Page IDs that were not found in the database
421 * @return array Array of page IDs
423 public function getMissingPageIDs() {
424 return $this->mMissingPageIDs
;
428 * Get a list of redirect resolutions - maps a title to its redirect
429 * target, as an array of output-ready arrays
432 public function getRedirectTitles() {
433 return $this->mRedirectTitles
;
437 * Get a list of redirect resolutions - maps a title to its redirect
439 * @param ApiResult $result
440 * @return array Array of prefixed_title (string) => Title object
443 public function getRedirectTitlesAsResult( $result = null ) {
445 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
447 'from' => strval( $titleStrFrom ),
448 'to' => $titleTo->getPrefixedText(),
450 if ( $titleTo->hasFragment() ) {
451 $r['tofragment'] = $titleTo->getFragment();
453 if ( $titleTo->isExternal() ) {
454 $r['tointerwiki'] = $titleTo->getInterwiki();
458 if ( !empty( $values ) && $result ) {
459 $result->setIndexedTagName( $values, 'r' );
466 * Get a list of title normalizations - maps a title to its normalized
468 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
470 public function getNormalizedTitles() {
471 return $this->mNormalizedTitles
;
475 * Get a list of title normalizations - maps a title to its normalized
476 * version in the form of result array.
477 * @param ApiResult $result
478 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
481 public function getNormalizedTitlesAsResult( $result = null ) {
483 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
485 'from' => $rawTitleStr,
489 if ( !empty( $values ) && $result ) {
490 $result->setIndexedTagName( $values, 'n' );
497 * Get a list of title conversions - maps a title to its converted
499 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
501 public function getConvertedTitles() {
502 return $this->mConvertedTitles
;
506 * Get a list of title conversions - maps a title to its converted
507 * version as a result array.
508 * @param ApiResult $result
509 * @return array Array of (from, to) strings
512 public function getConvertedTitlesAsResult( $result = null ) {
514 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
516 'from' => $rawTitleStr,
520 if ( !empty( $values ) && $result ) {
521 $result->setIndexedTagName( $values, 'c' );
528 * Get a list of interwiki titles - maps a title to its interwiki
530 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
532 public function getInterwikiTitles() {
533 return $this->mInterwikiTitles
;
537 * Get a list of interwiki titles - maps a title to its interwiki
539 * @param ApiResult $result
541 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
544 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
546 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
548 'title' => $rawTitleStr,
549 'iw' => $interwikiStr,
552 $title = Title
::newFromText( $rawTitleStr );
553 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
557 if ( !empty( $values ) && $result ) {
558 $result->setIndexedTagName( $values, 'i' );
565 * Get an array of invalid/special/missing titles.
567 * @param array $invalidChecks List of types of invalid titles to include.
568 * Recognized values are:
569 * - invalidTitles: Titles from $this->getInvalidTitles()
570 * - special: Titles from $this->getSpecialTitles()
571 * - missingIds: ids from $this->getMissingPageIDs()
572 * - missingRevIds: ids from $this->getMissingRevisionIDs()
573 * - missingTitles: Titles from $this->getMissingTitles()
574 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
575 * @return array Array suitable for inclusion in the response
578 public function getInvalidTitlesAndRevisions( $invalidChecks = array( 'invalidTitles',
579 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' )
582 if ( in_array( "invalidTitles", $invalidChecks ) ) {
583 self
::addValues( $result, $this->getInvalidTitles(), 'invalid', 'title' );
585 if ( in_array( "special", $invalidChecks ) ) {
586 self
::addValues( $result, $this->getSpecialTitles(), 'special', 'title' );
588 if ( in_array( "missingIds", $invalidChecks ) ) {
589 self
::addValues( $result, $this->getMissingPageIDs(), 'missing', 'pageid' );
591 if ( in_array( "missingRevIds", $invalidChecks ) ) {
592 self
::addValues( $result, $this->getMissingRevisionIDs(), 'missing', 'revid' );
594 if ( in_array( "missingTitles", $invalidChecks ) ) {
595 self
::addValues( $result, $this->getMissingTitles(), 'missing' );
597 if ( in_array( "interwikiTitles", $invalidChecks ) ) {
598 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
605 * Get the list of valid revision IDs (requested with the revids= parameter)
606 * @return array Array of revID (int) => pageID (int)
608 public function getRevisionIDs() {
609 return $this->mGoodRevIDs
;
613 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
614 * @return array Array of revID (int) => pageID (int)
616 public function getLiveRevisionIDs() {
617 return $this->mLiveRevIDs
;
621 * Get the list of revision IDs that were associated with deleted titles.
622 * @return array Array of revID (int) => pageID (int)
624 public function getDeletedRevisionIDs() {
625 return $this->mDeletedRevIDs
;
629 * Revision IDs that were not found in the database
630 * @return array Array of revision IDs
632 public function getMissingRevisionIDs() {
633 return $this->mMissingRevIDs
;
637 * Revision IDs that were not found in the database as result array.
638 * @param ApiResult $result
639 * @return array Array of revision IDs
642 public function getMissingRevisionIDsAsResult( $result = null ) {
644 foreach ( $this->getMissingRevisionIDs() as $revid ) {
645 $values[$revid] = array(
649 if ( !empty( $values ) && $result ) {
650 $result->setIndexedTagName( $values, 'rev' );
657 * Get the list of titles with negative namespace
660 public function getSpecialTitles() {
661 return $this->mSpecialTitles
;
665 * Returns the number of revisions (requested with revids= parameter).
666 * @return int Number of revisions.
668 public function getRevisionCount() {
669 return count( $this->getRevisionIDs() );
673 * Populate this PageSet from a list of Titles
674 * @param array $titles Array of Title objects
676 public function populateFromTitles( $titles ) {
678 $this->initFromTitles( $titles );
683 * Populate this PageSet from a list of page IDs
684 * @param array $pageIDs Array of page IDs
686 public function populateFromPageIDs( $pageIDs ) {
688 $this->initFromPageIds( $pageIDs );
693 * Populate this PageSet from a rowset returned from the database
695 * Note that the query result must include the columns returned by
696 * $this->getPageTableFields().
698 * @param DatabaseBase $db
699 * @param ResultWrapper $queryResult Query result object
701 public function populateFromQueryResult( $db, $queryResult ) {
703 $this->initFromQueryResult( $queryResult );
708 * Populate this PageSet from a list of revision IDs
709 * @param array $revIDs Array of revision IDs
711 public function populateFromRevisionIDs( $revIDs ) {
713 $this->initFromRevIDs( $revIDs );
718 * Extract all requested fields from the row received from the database
719 * @param stdClass $row Result row
721 public function processDbRow( $row ) {
722 // Store Title object in various data structures
723 $title = Title
::newFromRow( $row );
725 $pageId = intval( $row->page_id
);
726 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
727 $this->mTitles
[] = $title;
729 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
730 $this->mPendingRedirectIDs
[$pageId] = $title;
732 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
733 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
734 $this->mGoodTitles
[$pageId] = $title;
737 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
738 $fieldValues[$pageId] = $row->$fieldName;
743 * Do not use, does nothing, will be removed
744 * @deprecated since 1.21
746 public function finishPageSetGeneration() {
747 wfDeprecated( __METHOD__
, '1.21' );
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 $this->profileDBIn();
778 $res = $db->select( 'page', $this->getPageTableFields(), $set,
780 $this->profileDBOut();
782 // Hack: get the ns:titles stored in array(ns => array(titles)) format
783 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
785 // Resolve any found redirects
786 $this->resolvePendingRedirects();
790 * Does the same as initFromTitles(), but is based on page IDs instead
791 * @param array $pageids Array of page IDs
793 private function initFromPageIds( $pageids ) {
798 $pageids = array_map( 'intval', $pageids ); // paranoia
799 $remaining = array_flip( $pageids );
801 $pageids = self
::getPositiveIntegers( $pageids );
804 if ( !empty( $pageids ) ) {
806 'page_id' => $pageids
808 $db = $this->getDB();
810 // Get pageIDs data from the `page` table
811 $this->profileDBIn();
812 $res = $db->select( 'page', $this->getPageTableFields(), $set,
814 $this->profileDBOut();
817 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
819 // Resolve any found redirects
820 $this->resolvePendingRedirects();
824 * Iterate through the result of the query on 'page' table,
825 * and for each row create and store title object and save any extra fields requested.
826 * @param ResultWrapper $res DB Query result
827 * @param array $remaining Array of either pageID or ns/title elements (optional).
828 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
829 * @param bool $processTitles Must be provided together with $remaining.
830 * If true, treat $remaining as an array of [ns][title]
831 * If false, treat it as an array of [pageIDs]
833 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
834 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
835 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
838 $usernames = array();
840 foreach ( $res as $row ) {
841 $pageId = intval( $row->page_id
);
843 // Remove found page from the list of remaining items
844 if ( isset( $remaining ) ) {
845 if ( $processTitles ) {
846 unset( $remaining[$row->page_namespace
][$row->page_title
] );
848 unset( $remaining[$pageId] );
852 // Store any extra fields requested by modules
853 $this->processDbRow( $row );
855 // Need gender information
856 if ( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
857 $usernames[] = $row->page_title
;
862 if ( isset( $remaining ) ) {
863 // Any items left in the $remaining list are added as missing
864 if ( $processTitles ) {
865 // The remaining titles in $remaining are non-existent pages
866 foreach ( $remaining as $ns => $dbkeys ) {
867 foreach ( array_keys( $dbkeys ) as $dbkey ) {
868 $title = Title
::makeTitle( $ns, $dbkey );
869 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
870 $this->mMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
871 $this->mGoodAndMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
872 $this->mMissingTitles
[$this->mFakePageId
] = $title;
873 $this->mFakePageId
--;
874 $this->mTitles
[] = $title;
876 // need gender information
877 if ( MWNamespace
::hasGenderDistinction( $ns ) ) {
878 $usernames[] = $dbkey;
883 // The remaining pageids do not exist
884 if ( !$this->mMissingPageIDs
) {
885 $this->mMissingPageIDs
= array_keys( $remaining );
887 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
892 // Get gender information
893 $genderCache = GenderCache
::singleton();
894 $genderCache->doQuery( $usernames, __METHOD__
);
898 * Does the same as initFromTitles(), but is based on revision IDs
900 * @param array $revids Array of revision IDs
902 private function initFromRevIDs( $revids ) {
907 $revids = array_map( 'intval', $revids ); // paranoia
908 $db = $this->getDB();
910 $remaining = array_flip( $revids );
912 $revids = self
::getPositiveIntegers( $revids );
914 if ( !empty( $revids ) ) {
915 $tables = array( 'revision', 'page' );
916 $fields = array( 'rev_id', 'rev_page' );
917 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
919 // Get pageIDs data from the `page` table
920 $this->profileDBIn();
921 $res = $db->select( $tables, $fields, $where, __METHOD__
);
922 foreach ( $res as $row ) {
923 $revid = intval( $row->rev_id
);
924 $pageid = intval( $row->rev_page
);
925 $this->mGoodRevIDs
[$revid] = $pageid;
926 $this->mLiveRevIDs
[$revid] = $pageid;
927 $pageids[$pageid] = '';
928 unset( $remaining[$revid] );
930 $this->profileDBOut();
933 $this->mMissingRevIDs
= array_keys( $remaining );
935 // Populate all the page information
936 $this->initFromPageIds( array_keys( $pageids ) );
938 // If the user can see deleted revisions, pull out the corresponding
939 // titles from the archive table and include them too. We ignore
940 // ar_page_id because deleted revisions are tied by title, not page_id.
941 if ( !empty( $this->mMissingRevIDs
) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
942 $remaining = array_flip( $this->mMissingRevIDs
);
943 $tables = array( 'archive' );
944 $fields = array( 'ar_rev_id', 'ar_namespace', 'ar_title' );
945 $where = array( 'ar_rev_id' => $this->mMissingRevIDs
);
947 $this->profileDBIn();
948 $res = $db->select( $tables, $fields, $where, __METHOD__
);
950 foreach ( $res as $row ) {
951 $revid = intval( $row->ar_rev_id
);
952 $titles[$revid] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
953 unset( $remaining[$revid] );
955 $this->profileDBOut();
957 $this->initFromTitles( $titles );
959 foreach ( $titles as $revid => $title ) {
960 $ns = $title->getNamespace();
961 $dbkey = $title->getDBkey();
963 // Handle converted titles
964 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
965 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
967 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
968 $ns = $title->getNamespace();
969 $dbkey = $title->getDBkey();
972 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
973 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
974 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
976 $remaining[$revid] = true;
980 $this->mMissingRevIDs
= array_keys( $remaining );
985 * Resolve any redirects in the result if redirect resolution was
986 * requested. This function is called repeatedly until all redirects
987 * have been resolved.
989 private function resolvePendingRedirects() {
990 if ( $this->mResolveRedirects
) {
991 $db = $this->getDB();
992 $pageFlds = $this->getPageTableFields();
994 // Repeat until all redirects have been resolved
995 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
996 while ( $this->mPendingRedirectIDs
) {
997 // Resolve redirects by querying the pagelinks table, and repeat the process
998 // Create a new linkBatch object for the next pass
999 $linkBatch = $this->getRedirectTargets();
1001 if ( $linkBatch->isEmpty() ) {
1005 $set = $linkBatch->constructSet( 'page', $db );
1006 if ( $set === false ) {
1010 // Get pageIDs data from the `page` table
1011 $this->profileDBIn();
1012 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1013 $this->profileDBOut();
1015 // Hack: get the ns:titles stored in array(ns => array(titles)) format
1016 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1022 * Get the targets of the pending redirects from the database
1024 * Also creates entries in the redirect table for redirects that don't
1028 private function getRedirectTargets() {
1029 $lb = new LinkBatch();
1030 $db = $this->getDB();
1032 $this->profileDBIn();
1041 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ),
1044 $this->profileDBOut();
1045 foreach ( $res as $row ) {
1046 $rdfrom = intval( $row->rd_from
);
1047 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1048 $to = Title
::makeTitle(
1054 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1055 if ( $to->isExternal() ) {
1056 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1057 } elseif ( !isset( $this->mAllPages
[$row->rd_namespace
][$row->rd_title
] ) ) {
1058 $lb->add( $row->rd_namespace
, $row->rd_title
);
1060 $this->mRedirectTitles
[$from] = $to;
1063 if ( $this->mPendingRedirectIDs
) {
1064 // We found pages that aren't in the redirect table
1066 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1067 $page = WikiPage
::factory( $title );
1068 $rt = $page->insertRedirect();
1070 // What the hell. Let's just ignore this
1074 $this->mRedirectTitles
[$title->getPrefixedText()] = $rt;
1075 unset( $this->mPendingRedirectIDs
[$id] );
1083 * Get the cache mode for the data generated by this module.
1084 * All PageSet users should take into account whether this returns a more-restrictive
1085 * cache mode than the using module itself. For possible return values and other
1086 * details about cache modes, see ApiMain::setCacheMode()
1088 * Public caching will only be allowed if *all* the modules that supply
1089 * data for a given request return a cache mode of public.
1091 * @param array|null $params
1095 public function getCacheMode( $params = null ) {
1096 return $this->mCacheMode
;
1100 * Given an array of title strings, convert them into Title objects.
1101 * Alternatively, an array of Title objects may be given.
1102 * This method validates access rights for the title,
1103 * and appends normalization values to the output.
1105 * @param array $titles Array of Title objects or strings
1108 private function processTitlesArray( $titles ) {
1109 $usernames = array();
1110 $linkBatch = new LinkBatch();
1112 foreach ( $titles as $title ) {
1113 if ( is_string( $title ) ) {
1114 $titleObj = Title
::newFromText( $title, $this->mDefaultNamespace
);
1119 // Handle invalid titles gracefully
1120 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1121 $this->mInvalidTitles
[$this->mFakePageId
] = $title;
1122 $this->mFakePageId
--;
1123 continue; // There's nothing else we can do
1125 $unconvertedTitle = $titleObj->getPrefixedText();
1126 $titleWasConverted = false;
1127 if ( $titleObj->isExternal() ) {
1128 // This title is an interwiki link.
1129 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1131 // Variants checking
1133 if ( $this->mConvertTitles
&&
1134 count( $wgContLang->getVariants() ) > 1 &&
1135 !$titleObj->exists()
1137 // Language::findVariantLink will modify titleText and titleObj into
1138 // the canonical variant if possible
1139 $titleText = is_string( $title ) ?
$title : $titleObj->getPrefixedText();
1140 $wgContLang->findVariantLink( $titleText, $titleObj );
1141 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1144 if ( $titleObj->getNamespace() < 0 ) {
1145 // Handle Special and Media pages
1146 $titleObj = $titleObj->fixSpecialName();
1147 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1148 $this->mFakePageId
--;
1151 $linkBatch->addObj( $titleObj );
1155 // Make sure we remember the original title that was
1156 // given to us. This way the caller can correlate new
1157 // titles with the originally requested when e.g. the
1158 // namespace is localized or the capitalization is
1160 if ( $titleWasConverted ) {
1161 $this->mConvertedTitles
[$unconvertedTitle] = $titleObj->getPrefixedText();
1162 // In this case the page can't be Special.
1163 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1164 $this->mNormalizedTitles
[$title] = $unconvertedTitle;
1166 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1167 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1170 // Need gender information
1171 if ( MWNamespace
::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1172 $usernames[] = $titleObj->getText();
1175 // Get gender information
1176 $genderCache = GenderCache
::singleton();
1177 $genderCache->doQuery( $usernames, __METHOD__
);
1183 * Set data for a title.
1185 * This data may be extracted into an ApiResult using
1186 * self::populateGeneratorData. This should generally be limited to
1187 * data that is likely to be particularly useful to end users rather than
1188 * just being a dump of everything returned in non-generator mode.
1190 * Redirects here will *not* be followed, even if 'redirects' was
1191 * specified, since in the case of multiple redirects we can't know which
1192 * source's data to use on the target.
1194 * @param Title $title
1195 * @param array $data
1197 public function setGeneratorData( Title
$title, array $data ) {
1198 $ns = $title->getNamespace();
1199 $dbkey = $title->getDBkey();
1200 $this->mGeneratorData
[$ns][$dbkey] = $data;
1204 * Populate the generator data for all titles in the result
1206 * The page data may be inserted into an ApiResult object or into an
1207 * associative array. The $path parameter specifies the path within the
1208 * ApiResult or array to find the "pages" node.
1210 * The "pages" node itself must be an associative array mapping the page ID
1211 * or fake page ID values returned by this pageset (see
1212 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1213 * associative arrays of page data. Each of those subarrays will have the
1214 * data from self::setGeneratorData() merged in.
1216 * Data that was set by self::setGeneratorData() for pages not in the
1217 * "pages" node will be ignored.
1219 * @param ApiResult|array &$result
1220 * @param array $path
1221 * @return bool Whether the data fit
1223 public function populateGeneratorData( &$result, array $path = array() ) {
1224 if ( $result instanceof ApiResult
) {
1225 $data = $result->getData();
1229 foreach ( $path as $key ) {
1230 if ( !isset( $data[$key] ) ) {
1231 // Path isn't in $result, so nothing to add, so everything
1235 $data = &$data[$key];
1237 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1240 foreach ( $this->mSpecialTitles
as $id => $title ) {
1241 $pages[$title->getDBkey()] = $id;
1244 if ( !isset( $this->mAllPages
[$ns] ) ) {
1245 // No known titles in the whole namespace. Skip it.
1248 $pages = $this->mAllPages
[$ns];
1250 foreach ( $dbkeys as $dbkey => $genData ) {
1251 if ( !isset( $pages[$dbkey] ) ) {
1252 // Unknown title. Forget it.
1255 $pageId = $pages[$dbkey];
1256 if ( !isset( $data[$pageId] ) ) {
1257 // $pageId didn't make it into the result. Ignore it.
1261 if ( $result instanceof ApiResult
) {
1262 $path2 = array_merge( $path, array( $pageId ) );
1263 foreach ( $genData as $key => $value ) {
1264 if ( !$result->addValue( $path2, $key, $value ) ) {
1269 $data[$pageId] = array_merge( $data[$pageId], $genData );
1277 * Get the database connection (read-only)
1278 * @return DatabaseBase
1280 protected function getDB() {
1281 return $this->mDbSource
->getDB();
1285 * Returns the input array of integers with all values < 0 removed
1287 * @param array $array
1290 private static function getPositiveIntegers( $array ) {
1291 // bug 25734 API: possible issue with revids validation
1292 // It seems with a load of revision rows, MySQL gets upset
1293 // Remove any < 0 integers, as they can't be valid
1294 foreach ( $array as $i => $int ) {
1296 unset( $array[$i] );
1303 public function getAllowedParams( $flags = 0 ) {
1306 ApiBase
::PARAM_ISMULTI
=> true,
1307 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1310 ApiBase
::PARAM_TYPE
=> 'integer',
1311 ApiBase
::PARAM_ISMULTI
=> true,
1312 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1315 ApiBase
::PARAM_TYPE
=> 'integer',
1316 ApiBase
::PARAM_ISMULTI
=> true,
1317 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1319 'generator' => array(
1320 ApiBase
::PARAM_TYPE
=> null,
1321 ApiBase
::PARAM_VALUE_LINKS
=> array(),
1322 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1324 'redirects' => array(
1325 ApiBase
::PARAM_DFLT
=> false,
1326 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1327 ?
'api-pageset-param-redirects-generator'
1328 : 'api-pageset-param-redirects-nogenerator',
1330 'converttitles' => array(
1331 ApiBase
::PARAM_DFLT
=> false,
1332 ApiBase
::PARAM_HELP_MSG
=> array(
1333 'api-pageset-param-converttitles',
1334 $this->getLanguage()->commaList( LanguageConverter
::$languagesWithVariants ),
1339 if ( !$this->mAllowGenerator
) {
1340 unset( $result['generator'] );
1341 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1342 foreach ( $this->getGenerators() as $g ) {
1343 $result['generator'][ApiBase
::PARAM_TYPE
][] = $g;
1344 $result['generator'][ApiBase
::PARAM_VALUE_LINKS
][$g] = "Special:ApiHelp/query+$g";
1351 private static $generators = null;
1354 * Get an array of all available generators
1357 private function getGenerators() {
1358 if ( self
::$generators === null ) {
1359 $query = $this->mDbSource
;
1360 if ( !( $query instanceof ApiQuery
) ) {
1361 // If the parent container of this pageset is not ApiQuery,
1362 // we must create it to get module manager
1363 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1366 $mgr = $query->getModuleManager();
1367 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1368 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1373 self
::$generators = $gens;
1376 return self
::$generators;