c70629a92015622ab40bc8cb7c3a93815f6e45ec
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 wfRunHooks( '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();
455 if ( !empty( $values ) && $result ) {
456 $result->setIndexedTagName( $values, 'r' );
463 * Get a list of title normalizations - maps a title to its normalized
465 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
467 public function getNormalizedTitles() {
468 return $this->mNormalizedTitles
;
472 * Get a list of title normalizations - maps a title to its normalized
473 * version in the form of result array.
474 * @param ApiResult $result
475 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
478 public function getNormalizedTitlesAsResult( $result = null ) {
480 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
482 'from' => $rawTitleStr,
486 if ( !empty( $values ) && $result ) {
487 $result->setIndexedTagName( $values, 'n' );
494 * Get a list of title conversions - maps a title to its converted
496 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
498 public function getConvertedTitles() {
499 return $this->mConvertedTitles
;
503 * Get a list of title conversions - maps a title to its converted
504 * version as a result array.
505 * @param ApiResult $result
506 * @return array Array of (from, to) strings
509 public function getConvertedTitlesAsResult( $result = null ) {
511 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
513 'from' => $rawTitleStr,
517 if ( !empty( $values ) && $result ) {
518 $result->setIndexedTagName( $values, 'c' );
525 * Get a list of interwiki titles - maps a title to its interwiki
527 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
529 public function getInterwikiTitles() {
530 return $this->mInterwikiTitles
;
534 * Get a list of interwiki titles - maps a title to its interwiki
536 * @param ApiResult $result
538 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
541 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
543 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
545 'title' => $rawTitleStr,
546 'iw' => $interwikiStr,
549 $title = Title
::newFromText( $rawTitleStr );
550 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
554 if ( !empty( $values ) && $result ) {
555 $result->setIndexedTagName( $values, 'i' );
562 * Get an array of invalid/special/missing titles.
564 * @param array $invalidChecks List of types of invalid titles to include.
565 * Recognized values are:
566 * - invalidTitles: Titles from $this->getInvalidTitles()
567 * - special: Titles from $this->getSpecialTitles()
568 * - missingIds: ids from $this->getMissingPageIDs()
569 * - missingRevIds: ids from $this->getMissingRevisionIDs()
570 * - missingTitles: Titles from $this->getMissingTitles()
571 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
572 * @return array Array suitable for inclusion in the response
575 public function getInvalidTitlesAndRevisions( $invalidChecks = array( 'invalidTitles',
576 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' )
579 if ( in_array( "invalidTitles", $invalidChecks ) ) {
580 self
::addValues( $result, $this->getInvalidTitles(), 'invalid', 'title' );
582 if ( in_array( "special", $invalidChecks ) ) {
583 self
::addValues( $result, $this->getSpecialTitles(), 'special', 'title' );
585 if ( in_array( "missingIds", $invalidChecks ) ) {
586 self
::addValues( $result, $this->getMissingPageIDs(), 'missing', 'pageid' );
588 if ( in_array( "missingRevIds", $invalidChecks ) ) {
589 self
::addValues( $result, $this->getMissingRevisionIDs(), 'missing', 'revid' );
591 if ( in_array( "missingTitles", $invalidChecks ) ) {
592 self
::addValues( $result, $this->getMissingTitles(), 'missing' );
594 if ( in_array( "interwikiTitles", $invalidChecks ) ) {
595 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
602 * Get the list of valid revision IDs (requested with the revids= parameter)
603 * @return array Array of revID (int) => pageID (int)
605 public function getRevisionIDs() {
606 return $this->mGoodRevIDs
;
610 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
611 * @return array Array of revID (int) => pageID (int)
613 public function getLiveRevisionIDs() {
614 return $this->mLiveRevIDs
;
618 * Get the list of revision IDs that were associated with deleted titles.
619 * @return array Array of revID (int) => pageID (int)
621 public function getDeletedRevisionIDs() {
622 return $this->mDeletedRevIDs
;
626 * Revision IDs that were not found in the database
627 * @return array Array of revision IDs
629 public function getMissingRevisionIDs() {
630 return $this->mMissingRevIDs
;
634 * Revision IDs that were not found in the database as result array.
635 * @param ApiResult $result
636 * @return array Array of revision IDs
639 public function getMissingRevisionIDsAsResult( $result = null ) {
641 foreach ( $this->getMissingRevisionIDs() as $revid ) {
642 $values[$revid] = array(
646 if ( !empty( $values ) && $result ) {
647 $result->setIndexedTagName( $values, 'rev' );
654 * Get the list of titles with negative namespace
657 public function getSpecialTitles() {
658 return $this->mSpecialTitles
;
662 * Returns the number of revisions (requested with revids= parameter).
663 * @return int Number of revisions.
665 public function getRevisionCount() {
666 return count( $this->getRevisionIDs() );
670 * Populate this PageSet from a list of Titles
671 * @param array $titles Array of Title objects
673 public function populateFromTitles( $titles ) {
675 $this->initFromTitles( $titles );
680 * Populate this PageSet from a list of page IDs
681 * @param array $pageIDs Array of page IDs
683 public function populateFromPageIDs( $pageIDs ) {
685 $this->initFromPageIds( $pageIDs );
690 * Populate this PageSet from a rowset returned from the database
692 * Note that the query result must include the columns returned by
693 * $this->getPageTableFields().
695 * @param DatabaseBase $db
696 * @param ResultWrapper $queryResult Query result object
698 public function populateFromQueryResult( $db, $queryResult ) {
700 $this->initFromQueryResult( $queryResult );
705 * Populate this PageSet from a list of revision IDs
706 * @param array $revIDs Array of revision IDs
708 public function populateFromRevisionIDs( $revIDs ) {
710 $this->initFromRevIDs( $revIDs );
715 * Extract all requested fields from the row received from the database
716 * @param stdClass $row Result row
718 public function processDbRow( $row ) {
719 // Store Title object in various data structures
720 $title = Title
::newFromRow( $row );
722 $pageId = intval( $row->page_id
);
723 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
724 $this->mTitles
[] = $title;
726 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
727 $this->mPendingRedirectIDs
[$pageId] = $title;
729 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
730 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
731 $this->mGoodTitles
[$pageId] = $title;
734 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
735 $fieldValues[$pageId] = $row->$fieldName;
740 * Do not use, does nothing, will be removed
741 * @deprecated since 1.21
743 public function finishPageSetGeneration() {
744 wfDeprecated( __METHOD__
, '1.21' );
748 * This method populates internal variables with page information
749 * based on the given array of title strings.
752 * #1 For each title, get data from `page` table
753 * #2 If page was not found in the DB, store it as missing
755 * Additionally, when resolving redirects:
756 * #3 If no more redirects left, stop.
757 * #4 For each redirect, get its target from the `redirect` table.
758 * #5 Substitute the original LinkBatch object with the new list
759 * #6 Repeat from step #1
761 * @param array $titles Array of Title objects or strings
763 private function initFromTitles( $titles ) {
764 // Get validated and normalized title objects
765 $linkBatch = $this->processTitlesArray( $titles );
766 if ( $linkBatch->isEmpty() ) {
770 $db = $this->getDB();
771 $set = $linkBatch->constructSet( 'page', $db );
773 // Get pageIDs data from the `page` table
774 $this->profileDBIn();
775 $res = $db->select( 'page', $this->getPageTableFields(), $set,
777 $this->profileDBOut();
779 // Hack: get the ns:titles stored in array(ns => array(titles)) format
780 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
782 // Resolve any found redirects
783 $this->resolvePendingRedirects();
787 * Does the same as initFromTitles(), but is based on page IDs instead
788 * @param array $pageids Array of page IDs
790 private function initFromPageIds( $pageids ) {
795 $pageids = array_map( 'intval', $pageids ); // paranoia
796 $remaining = array_flip( $pageids );
798 $pageids = self
::getPositiveIntegers( $pageids );
801 if ( !empty( $pageids ) ) {
803 'page_id' => $pageids
805 $db = $this->getDB();
807 // Get pageIDs data from the `page` table
808 $this->profileDBIn();
809 $res = $db->select( 'page', $this->getPageTableFields(), $set,
811 $this->profileDBOut();
814 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
816 // Resolve any found redirects
817 $this->resolvePendingRedirects();
821 * Iterate through the result of the query on 'page' table,
822 * and for each row create and store title object and save any extra fields requested.
823 * @param ResultWrapper $res DB Query result
824 * @param array $remaining Array of either pageID or ns/title elements (optional).
825 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
826 * @param bool $processTitles Must be provided together with $remaining.
827 * If true, treat $remaining as an array of [ns][title]
828 * If false, treat it as an array of [pageIDs]
830 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
831 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
832 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
835 $usernames = array();
837 foreach ( $res as $row ) {
838 $pageId = intval( $row->page_id
);
840 // Remove found page from the list of remaining items
841 if ( isset( $remaining ) ) {
842 if ( $processTitles ) {
843 unset( $remaining[$row->page_namespace
][$row->page_title
] );
845 unset( $remaining[$pageId] );
849 // Store any extra fields requested by modules
850 $this->processDbRow( $row );
852 // Need gender information
853 if ( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
854 $usernames[] = $row->page_title
;
859 if ( isset( $remaining ) ) {
860 // Any items left in the $remaining list are added as missing
861 if ( $processTitles ) {
862 // The remaining titles in $remaining are non-existent pages
863 foreach ( $remaining as $ns => $dbkeys ) {
864 foreach ( array_keys( $dbkeys ) as $dbkey ) {
865 $title = Title
::makeTitle( $ns, $dbkey );
866 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
867 $this->mMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
868 $this->mGoodAndMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
869 $this->mMissingTitles
[$this->mFakePageId
] = $title;
870 $this->mFakePageId
--;
871 $this->mTitles
[] = $title;
873 // need gender information
874 if ( MWNamespace
::hasGenderDistinction( $ns ) ) {
875 $usernames[] = $dbkey;
880 // The remaining pageids do not exist
881 if ( !$this->mMissingPageIDs
) {
882 $this->mMissingPageIDs
= array_keys( $remaining );
884 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
889 // Get gender information
890 $genderCache = GenderCache
::singleton();
891 $genderCache->doQuery( $usernames, __METHOD__
);
895 * Does the same as initFromTitles(), but is based on revision IDs
897 * @param array $revids Array of revision IDs
899 private function initFromRevIDs( $revids ) {
904 $revids = array_map( 'intval', $revids ); // paranoia
905 $db = $this->getDB();
907 $remaining = array_flip( $revids );
909 $revids = self
::getPositiveIntegers( $revids );
911 if ( !empty( $revids ) ) {
912 $tables = array( 'revision', 'page' );
913 $fields = array( 'rev_id', 'rev_page' );
914 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
916 // Get pageIDs data from the `page` table
917 $this->profileDBIn();
918 $res = $db->select( $tables, $fields, $where, __METHOD__
);
919 foreach ( $res as $row ) {
920 $revid = intval( $row->rev_id
);
921 $pageid = intval( $row->rev_page
);
922 $this->mGoodRevIDs
[$revid] = $pageid;
923 $this->mLiveRevIDs
[$revid] = $pageid;
924 $pageids[$pageid] = '';
925 unset( $remaining[$revid] );
927 $this->profileDBOut();
930 $this->mMissingRevIDs
= array_keys( $remaining );
932 // Populate all the page information
933 $this->initFromPageIds( array_keys( $pageids ) );
935 // If the user can see deleted revisions, pull out the corresponding
936 // titles from the archive table and include them too. We ignore
937 // ar_page_id because deleted revisions are tied by title, not page_id.
938 if ( !empty( $this->mMissingRevIDs
) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
939 $remaining = array_flip( $this->mMissingRevIDs
);
940 $tables = array( 'archive' );
941 $fields = array( 'ar_rev_id', 'ar_namespace', 'ar_title' );
942 $where = array( 'ar_rev_id' => $this->mMissingRevIDs
);
944 $this->profileDBIn();
945 $res = $db->select( $tables, $fields, $where, __METHOD__
);
947 foreach ( $res as $row ) {
948 $revid = intval( $row->ar_rev_id
);
949 $titles[$revid] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
950 unset( $remaining[$revid] );
952 $this->profileDBOut();
954 $this->initFromTitles( $titles );
956 foreach ( $titles as $revid => $title ) {
957 $ns = $title->getNamespace();
958 $dbkey = $title->getDBkey();
960 // Handle converted titles
961 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
962 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
964 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
965 $ns = $title->getNamespace();
966 $dbkey = $title->getDBkey();
969 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
970 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
971 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
973 $remaining[$revid] = true;
977 $this->mMissingRevIDs
= array_keys( $remaining );
982 * Resolve any redirects in the result if redirect resolution was
983 * requested. This function is called repeatedly until all redirects
984 * have been resolved.
986 private function resolvePendingRedirects() {
987 if ( $this->mResolveRedirects
) {
988 $db = $this->getDB();
989 $pageFlds = $this->getPageTableFields();
991 // Repeat until all redirects have been resolved
992 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
993 while ( $this->mPendingRedirectIDs
) {
994 // Resolve redirects by querying the pagelinks table, and repeat the process
995 // Create a new linkBatch object for the next pass
996 $linkBatch = $this->getRedirectTargets();
998 if ( $linkBatch->isEmpty() ) {
1002 $set = $linkBatch->constructSet( 'page', $db );
1003 if ( $set === false ) {
1007 // Get pageIDs data from the `page` table
1008 $this->profileDBIn();
1009 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1010 $this->profileDBOut();
1012 // Hack: get the ns:titles stored in array(ns => array(titles)) format
1013 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1019 * Get the targets of the pending redirects from the database
1021 * Also creates entries in the redirect table for redirects that don't
1025 private function getRedirectTargets() {
1026 $lb = new LinkBatch();
1027 $db = $this->getDB();
1029 $this->profileDBIn();
1038 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ),
1041 $this->profileDBOut();
1042 foreach ( $res as $row ) {
1043 $rdfrom = intval( $row->rd_from
);
1044 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1045 $to = Title
::makeTitle(
1051 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1052 if ( !$to->isExternal() && !isset( $this->mAllPages
[$row->rd_namespace
][$row->rd_title
] ) ) {
1053 $lb->add( $row->rd_namespace
, $row->rd_title
);
1055 $this->mRedirectTitles
[$from] = $to;
1058 if ( $this->mPendingRedirectIDs
) {
1059 // We found pages that aren't in the redirect table
1061 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1062 $page = WikiPage
::factory( $title );
1063 $rt = $page->insertRedirect();
1065 // What the hell. Let's just ignore this
1069 $this->mRedirectTitles
[$title->getPrefixedText()] = $rt;
1070 unset( $this->mPendingRedirectIDs
[$id] );
1078 * Get the cache mode for the data generated by this module.
1079 * All PageSet users should take into account whether this returns a more-restrictive
1080 * cache mode than the using module itself. For possible return values and other
1081 * details about cache modes, see ApiMain::setCacheMode()
1083 * Public caching will only be allowed if *all* the modules that supply
1084 * data for a given request return a cache mode of public.
1086 * @param array|null $params
1090 public function getCacheMode( $params = null ) {
1091 return $this->mCacheMode
;
1095 * Given an array of title strings, convert them into Title objects.
1096 * Alternatively, an array of Title objects may be given.
1097 * This method validates access rights for the title,
1098 * and appends normalization values to the output.
1100 * @param array $titles Array of Title objects or strings
1103 private function processTitlesArray( $titles ) {
1104 $usernames = array();
1105 $linkBatch = new LinkBatch();
1107 foreach ( $titles as $title ) {
1108 if ( is_string( $title ) ) {
1109 $titleObj = Title
::newFromText( $title, $this->mDefaultNamespace
);
1114 // Handle invalid titles gracefully
1115 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1116 $this->mInvalidTitles
[$this->mFakePageId
] = $title;
1117 $this->mFakePageId
--;
1118 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 * Populate the generator data for all titles in the result
1201 * The page data may be inserted into an ApiResult object or into an
1202 * associative array. The $path parameter specifies the path within the
1203 * ApiResult or array to find the "pages" node.
1205 * The "pages" node itself must be an associative array mapping the page ID
1206 * or fake page ID values returned by this pageset (see
1207 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1208 * associative arrays of page data. Each of those subarrays will have the
1209 * data from self::setGeneratorData() merged in.
1211 * Data that was set by self::setGeneratorData() for pages not in the
1212 * "pages" node will be ignored.
1214 * @param ApiResult|array &$result
1215 * @param array $path
1216 * @return bool Whether the data fit
1218 public function populateGeneratorData( &$result, array $path = array() ) {
1219 if ( $result instanceof ApiResult
) {
1220 $data = $result->getData();
1224 foreach ( $path as $key ) {
1225 if ( !isset( $data[$key] ) ) {
1226 // Path isn't in $result, so nothing to add, so everything
1230 $data = &$data[$key];
1232 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1235 foreach ( $this->mSpecialTitles
as $id => $title ) {
1236 $pages[$title->getDBkey()] = $id;
1239 if ( !isset( $this->mAllPages
[$ns] ) ) {
1240 // No known titles in the whole namespace. Skip it.
1243 $pages = $this->mAllPages
[$ns];
1245 foreach ( $dbkeys as $dbkey => $genData ) {
1246 if ( !isset( $pages[$dbkey] ) ) {
1247 // Unknown title. Forget it.
1250 $pageId = $pages[$dbkey];
1251 if ( !isset( $data[$pageId] ) ) {
1252 // $pageId didn't make it into the result. Ignore it.
1256 if ( $result instanceof ApiResult
) {
1257 $path2 = array_merge( $path, array( $pageId ) );
1258 foreach ( $genData as $key => $value ) {
1259 if ( !$result->addValue( $path2, $key, $value ) ) {
1264 $data[$pageId] = array_merge( $data[$pageId], $genData );
1272 * Get the database connection (read-only)
1273 * @return DatabaseBase
1275 protected function getDB() {
1276 return $this->mDbSource
->getDB();
1280 * Returns the input array of integers with all values < 0 removed
1282 * @param array $array
1285 private static function getPositiveIntegers( $array ) {
1286 // bug 25734 API: possible issue with revids validation
1287 // It seems with a load of revision rows, MySQL gets upset
1288 // Remove any < 0 integers, as they can't be valid
1289 foreach ( $array as $i => $int ) {
1291 unset( $array[$i] );
1298 public function getAllowedParams( $flags = 0 ) {
1301 ApiBase
::PARAM_ISMULTI
=> true,
1302 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1305 ApiBase
::PARAM_TYPE
=> 'integer',
1306 ApiBase
::PARAM_ISMULTI
=> true,
1307 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1310 ApiBase
::PARAM_TYPE
=> 'integer',
1311 ApiBase
::PARAM_ISMULTI
=> true,
1312 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1314 'generator' => array(
1315 ApiBase
::PARAM_TYPE
=> null,
1316 ApiBase
::PARAM_VALUE_LINKS
=> array(),
1317 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1319 'redirects' => array(
1320 ApiBase
::PARAM_DFLT
=> false,
1321 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1322 ?
'api-pageset-param-redirects-generator'
1323 : 'api-pageset-param-redirects-nogenerator',
1325 'converttitles' => array(
1326 ApiBase
::PARAM_DFLT
=> false,
1327 ApiBase
::PARAM_HELP_MSG
=> array(
1328 'api-pageset-param-converttitles',
1329 $this->getLanguage()->commaList( LanguageConverter
::$languagesWithVariants ),
1334 if ( !$this->mAllowGenerator
) {
1335 unset( $result['generator'] );
1336 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1337 foreach ( $this->getGenerators() as $g ) {
1338 $result['generator'][ApiBase
::PARAM_TYPE
][] = $g;
1339 $result['generator'][ApiBase
::PARAM_VALUE_LINKS
][$g] = "Special:ApiHelp/query+$g";
1346 private static $generators = null;
1349 * Get an array of all available generators
1352 private function getGenerators() {
1353 if ( self
::$generators === null ) {
1354 $query = $this->mDbSource
;
1355 if ( !( $query instanceof ApiQuery
) ) {
1356 // If the parent container of this pageset is not ApiQuery,
1357 // we must create it to get module manager
1358 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1361 $mgr = $query->getModuleManager();
1362 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1363 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1368 self
::$generators = $gens;
1371 return self
::$generators;