5 * Created on Sep 24, 2006
7 * Copyright © 2006 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.
40 class ApiPageSet
extends ApiQueryBase
{
42 private $mAllPages; // [ns][dbkey] => page_id or negative when missing
43 private $mTitles, $mGoodTitles, $mMissingTitles, $mInvalidTitles;
44 private $mMissingPageIDs, $mRedirectTitles, $mSpecialTitles;
45 private $mNormalizedTitles, $mInterwikiTitles;
46 private $mResolveRedirects, $mPendingRedirectIDs;
47 private $mConvertTitles, $mConvertedTitles;
48 private $mGoodRevIDs, $mMissingRevIDs;
51 private $mRequestedPageFields;
55 * @param $query ApiQueryBase
56 * @param $resolveRedirects bool Whether redirects should be resolved
57 * @param $convertTitles bool
59 public function __construct( $query, $resolveRedirects = false, $convertTitles = false ) {
60 parent
::__construct( $query, 'query' );
62 $this->mAllPages
= array();
63 $this->mTitles
= array();
64 $this->mGoodTitles
= array();
65 $this->mMissingTitles
= array();
66 $this->mInvalidTitles
= array();
67 $this->mMissingPageIDs
= array();
68 $this->mRedirectTitles
= array();
69 $this->mNormalizedTitles
= array();
70 $this->mInterwikiTitles
= array();
71 $this->mGoodRevIDs
= array();
72 $this->mMissingRevIDs
= array();
73 $this->mSpecialTitles
= array();
75 $this->mRequestedPageFields
= array();
76 $this->mResolveRedirects
= $resolveRedirects;
77 if ( $resolveRedirects ) {
78 $this->mPendingRedirectIDs
= array();
81 $this->mConvertTitles
= $convertTitles;
82 $this->mConvertedTitles
= array();
84 $this->mFakePageId
= - 1;
88 * Check whether this PageSet is resolving redirects
91 public function isResolvingRedirects() {
92 return $this->mResolveRedirects
;
96 * Request an additional field from the page table. Must be called
98 * @param $fieldName string Field name
100 public function requestField( $fieldName ) {
101 $this->mRequestedPageFields
[$fieldName] = null;
105 * Get the value of a custom field previously requested through
107 * @param $fieldName string Field name
108 * @return mixed Field value
110 public function getCustomField( $fieldName ) {
111 return $this->mRequestedPageFields
[$fieldName];
115 * Get the fields that have to be queried from the page table:
116 * the ones requested through requestField() and a few basic ones
118 * @return array of field names
120 public function getPageTableFields() {
121 // Ensure we get minimum required fields
122 // DON'T change this order
124 'page_namespace' => null,
125 'page_title' => null,
129 if ( $this->mResolveRedirects
) {
130 $pageFlds['page_is_redirect'] = null;
133 // only store non-default fields
134 $this->mRequestedPageFields
= array_diff_key( $this->mRequestedPageFields
, $pageFlds );
136 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
137 return array_keys( $pageFlds );
141 * Returns an array [ns][dbkey] => page_id for all requested titles.
142 * page_id is a unique negative number in case title was not found.
143 * Invalid titles will also have negative page IDs and will be in namespace 0
146 public function getAllTitlesByNamespace() {
147 return $this->mAllPages
;
151 * All Title objects provided.
152 * @return array of Title objects
154 public function getTitles() {
155 return $this->mTitles
;
159 * Returns the number of unique pages (not revisions) in the set.
162 public function getTitleCount() {
163 return count( $this->mTitles
);
167 * Title objects that were found in the database.
168 * @return array page_id (int) => Title (obj)
170 public function getGoodTitles() {
171 return $this->mGoodTitles
;
175 * Returns the number of found unique pages (not revisions) in the set.
178 public function getGoodTitleCount() {
179 return count( $this->mGoodTitles
);
183 * Title objects that were NOT found in the database.
184 * The array's index will be negative for each item
185 * @return array of Title objects
187 public function getMissingTitles() {
188 return $this->mMissingTitles
;
192 * Titles that were deemed invalid by Title::newFromText()
193 * The array's index will be unique and negative for each item
194 * @return array of strings (not Title objects)
196 public function getInvalidTitles() {
197 return $this->mInvalidTitles
;
201 * Page IDs that were not found in the database
202 * @return array of page IDs
204 public function getMissingPageIDs() {
205 return $this->mMissingPageIDs
;
209 * Get a list of redirect resolutions - maps a title to its redirect
211 * @return array prefixed_title (string) => Title object
213 public function getRedirectTitles() {
214 return $this->mRedirectTitles
;
218 * Get a list of title normalizations - maps a title to its normalized
220 * @return array raw_prefixed_title (string) => prefixed_title (string)
222 public function getNormalizedTitles() {
223 return $this->mNormalizedTitles
;
227 * Get a list of title conversions - maps a title to its converted
229 * @return array raw_prefixed_title (string) => prefixed_title (string)
231 public function getConvertedTitles() {
232 return $this->mConvertedTitles
;
236 * Get a list of interwiki titles - maps a title to its interwiki
238 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
240 public function getInterwikiTitles() {
241 return $this->mInterwikiTitles
;
245 * Get the list of revision IDs (requested with the revids= parameter)
246 * @return array revID (int) => pageID (int)
248 public function getRevisionIDs() {
249 return $this->mGoodRevIDs
;
253 * Revision IDs that were not found in the database
254 * @return array of revision IDs
256 public function getMissingRevisionIDs() {
257 return $this->mMissingRevIDs
;
261 * Get the list of titles with negative namespace
262 * @return array Title
264 public function getSpecialTitles() {
265 return $this->mSpecialTitles
;
269 * Returns the number of revisions (requested with revids= parameter)\
272 public function getRevisionCount() {
273 return count( $this->getRevisionIDs() );
277 * Populate the PageSet from the request parameters.
279 public function execute() {
281 $params = $this->extractRequestParams();
283 // Only one of the titles/pageids/revids is allowed at the same time
285 if ( isset( $params['titles'] ) ) {
286 $dataSource = 'titles';
288 if ( isset( $params['pageids'] ) ) {
289 if ( isset( $dataSource ) ) {
290 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
292 $dataSource = 'pageids';
294 if ( isset( $params['revids'] ) ) {
295 if ( isset( $dataSource ) ) {
296 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
298 $dataSource = 'revids';
301 switch ( $dataSource ) {
303 $this->initFromTitles( $params['titles'] );
306 $this->initFromPageIds( $params['pageids'] );
309 if ( $this->mResolveRedirects
) {
310 $this->setWarning( 'Redirect resolution cannot be used together with the revids= parameter. ' .
311 'Any redirects the revids= point to have not been resolved.' );
313 $this->mResolveRedirects
= false;
314 $this->initFromRevIDs( $params['revids'] );
317 // Do nothing - some queries do not need any of the data sources.
324 * Populate this PageSet from a list of Titles
325 * @param $titles array of Title objects
327 public function populateFromTitles( $titles ) {
329 $this->initFromTitles( $titles );
334 * Populate this PageSet from a list of page IDs
335 * @param $pageIDs array of page IDs
337 public function populateFromPageIDs( $pageIDs ) {
339 $this->initFromPageIds( $pageIDs );
344 * Populate this PageSet from a rowset returned from the database
345 * @param $db DatabaseBase object
346 * @param $queryResult ResultWrapper Query result object
348 public function populateFromQueryResult( $db, $queryResult ) {
350 $this->initFromQueryResult( $queryResult );
355 * Populate this PageSet from a list of revision IDs
356 * @param $revIDs array of revision IDs
358 public function populateFromRevisionIDs( $revIDs ) {
360 $this->initFromRevIDs( $revIDs );
365 * Extract all requested fields from the row received from the database
366 * @param $row Result row
368 public function processDbRow( $row ) {
369 // Store Title object in various data structures
370 $title = Title
::newFromRow( $row );
372 $pageId = intval( $row->page_id
);
373 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
374 $this->mTitles
[] = $title;
376 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
377 $this->mPendingRedirectIDs
[$pageId] = $title;
379 $this->mGoodTitles
[$pageId] = $title;
382 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
383 $fieldValues[$pageId] = $row-> $fieldName;
388 * Resolve redirects, if applicable
390 public function finishPageSetGeneration() {
392 $this->resolvePendingRedirects();
397 * This method populates internal variables with page information
398 * based on the given array of title strings.
401 * #1 For each title, get data from `page` table
402 * #2 If page was not found in the DB, store it as missing
404 * Additionally, when resolving redirects:
405 * #3 If no more redirects left, stop.
406 * #4 For each redirect, get its target from the `redirect` table.
407 * #5 Substitute the original LinkBatch object with the new list
408 * #6 Repeat from step #1
410 * @param $titles array of Title objects or strings
412 private function initFromTitles( $titles ) {
413 // Get validated and normalized title objects
414 $linkBatch = $this->processTitlesArray( $titles );
415 if ( $linkBatch->isEmpty() ) {
419 $db = $this->getDB();
420 $set = $linkBatch->constructSet( 'page', $db );
422 // Get pageIDs data from the `page` table
423 $this->profileDBIn();
424 $res = $db->select( 'page', $this->getPageTableFields(), $set,
426 $this->profileDBOut();
428 // Hack: get the ns:titles stored in array(ns => array(titles)) format
429 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
431 // Resolve any found redirects
432 $this->resolvePendingRedirects();
436 * Does the same as initFromTitles(), but is based on page IDs instead
437 * @param $pageids array of page IDs
439 private function initFromPageIds( $pageids ) {
440 if ( !count( $pageids ) ) {
444 $pageids = array_map( 'intval', $pageids ); // paranoia
445 $remaining = array_flip( $pageids );
447 $pageids = self
::getPositiveIntegers( $pageids );
450 if ( count( $pageids ) ) {
452 'page_id' => $pageids
454 $db = $this->getDB();
456 // Get pageIDs data from the `page` table
457 $this->profileDBIn();
458 $res = $db->select( 'page', $this->getPageTableFields(), $set,
460 $this->profileDBOut();
463 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
465 // Resolve any found redirects
466 $this->resolvePendingRedirects();
470 * Iterate through the result of the query on 'page' table,
471 * and for each row create and store title object and save any extra fields requested.
472 * @param $res ResultWrapper DB Query result
473 * @param $remaining array of either pageID or ns/title elements (optional).
474 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
475 * @param $processTitles bool Must be provided together with $remaining.
476 * If true, treat $remaining as an array of [ns][title]
477 * If false, treat it as an array of [pageIDs]
479 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
480 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
481 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
484 $usernames = array();
486 foreach ( $res as $row ) {
487 $pageId = intval( $row->page_id
);
489 // Remove found page from the list of remaining items
490 if ( isset( $remaining ) ) {
491 if ( $processTitles ) {
492 unset( $remaining[$row->page_namespace
][$row->page_title
] );
494 unset( $remaining[$pageId] );
498 // Store any extra fields requested by modules
499 $this->processDbRow( $row );
501 // Need gender information
502 if( MWNamespace
::hasGenderDistinction( $row->page_namespace
) ) {
503 $usernames[] = $row->page_title
;
508 if ( isset( $remaining ) ) {
509 // Any items left in the $remaining list are added as missing
510 if ( $processTitles ) {
511 // The remaining titles in $remaining are non-existent pages
512 foreach ( $remaining as $ns => $dbkeys ) {
513 foreach ( array_keys( $dbkeys ) as $dbkey ) {
514 $title = Title
::makeTitle( $ns, $dbkey );
515 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
516 $this->mMissingTitles
[$this->mFakePageId
] = $title;
517 $this->mFakePageId
--;
518 $this->mTitles
[] = $title;
520 // need gender information
521 if( MWNamespace
::hasGenderDistinction( $ns ) ) {
522 $usernames[] = $dbkey;
527 // The remaining pageids do not exist
528 if ( !$this->mMissingPageIDs
) {
529 $this->mMissingPageIDs
= array_keys( $remaining );
531 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
536 // Get gender information
537 $genderCache = GenderCache
::singleton();
538 $genderCache->doQuery( $usernames, __METHOD__
);
542 * Does the same as initFromTitles(), but is based on revision IDs
544 * @param $revids array of revision IDs
546 private function initFromRevIDs( $revids ) {
547 if ( !count( $revids ) ) {
551 $revids = array_map( 'intval', $revids ); // paranoia
552 $db = $this->getDB();
554 $remaining = array_flip( $revids );
556 $revids = self
::getPositiveIntegers( $revids );
558 if ( count( $revids ) ) {
559 $tables = array( 'revision', 'page' );
560 $fields = array( 'rev_id', 'rev_page' );
561 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
563 // Get pageIDs data from the `page` table
564 $this->profileDBIn();
565 $res = $db->select( $tables, $fields, $where, __METHOD__
);
566 foreach ( $res as $row ) {
567 $revid = intval( $row->rev_id
);
568 $pageid = intval( $row->rev_page
);
569 $this->mGoodRevIDs
[$revid] = $pageid;
570 $pageids[$pageid] = '';
571 unset( $remaining[$revid] );
573 $this->profileDBOut();
576 $this->mMissingRevIDs
= array_keys( $remaining );
578 // Populate all the page information
579 $this->initFromPageIds( array_keys( $pageids ) );
583 * Resolve any redirects in the result if redirect resolution was
584 * requested. This function is called repeatedly until all redirects
585 * have been resolved.
587 private function resolvePendingRedirects() {
588 if ( $this->mResolveRedirects
) {
589 $db = $this->getDB();
590 $pageFlds = $this->getPageTableFields();
592 // Repeat until all redirects have been resolved
593 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
594 while ( $this->mPendingRedirectIDs
) {
595 // Resolve redirects by querying the pagelinks table, and repeat the process
596 // Create a new linkBatch object for the next pass
597 $linkBatch = $this->getRedirectTargets();
599 if ( $linkBatch->isEmpty() ) {
603 $set = $linkBatch->constructSet( 'page', $db );
604 if ( $set === false ) {
608 // Get pageIDs data from the `page` table
609 $this->profileDBIn();
610 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
611 $this->profileDBOut();
613 // Hack: get the ns:titles stored in array(ns => array(titles)) format
614 $this->initFromQueryResult( $res, $linkBatch->data
, true );
620 * Get the targets of the pending redirects from the database
622 * Also creates entries in the redirect table for redirects that don't
626 private function getRedirectTargets() {
627 $lb = new LinkBatch();
628 $db = $this->getDB();
630 $this->profileDBIn();
639 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ),
642 $this->profileDBOut();
643 foreach ( $res as $row ) {
644 $rdfrom = intval( $row->rd_from
);
645 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
646 $to = Title
::makeTitle( $row->rd_namespace
, $row->rd_title
, $row->rd_fragment
, $row->rd_interwiki
);
647 unset( $this->mPendingRedirectIDs
[$rdfrom] );
648 if ( !isset( $this->mAllPages
[$row->rd_namespace
][$row->rd_title
] ) ) {
649 $lb->add( $row->rd_namespace
, $row->rd_title
);
651 $this->mRedirectTitles
[$from] = $to;
654 if ( $this->mPendingRedirectIDs
) {
655 // We found pages that aren't in the redirect table
657 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
658 $page = WikiPage
::factory( $title );
659 $rt = $page->insertRedirect();
661 // What the hell. Let's just ignore this
665 $this->mRedirectTitles
[$title->getPrefixedText()] = $rt;
666 unset( $this->mPendingRedirectIDs
[$id] );
673 * Given an array of title strings, convert them into Title objects.
674 * Alternativelly, an array of Title objects may be given.
675 * This method validates access rights for the title,
676 * and appends normalization values to the output.
678 * @param $titles array of Title objects or strings
681 private function processTitlesArray( $titles ) {
682 $genderCache = GenderCache
::singleton();
683 $genderCache->doTitlesArray( $titles, __METHOD__
);
685 $linkBatch = new LinkBatch();
687 foreach ( $titles as $title ) {
688 $titleObj = is_string( $title ) ? Title
::newFromText( $title ) : $title;
690 // Handle invalid titles gracefully
691 $this->mAllpages
[0][$title] = $this->mFakePageId
;
692 $this->mInvalidTitles
[$this->mFakePageId
] = $title;
693 $this->mFakePageId
--;
694 continue; // There's nothing else we can do
696 $unconvertedTitle = $titleObj->getPrefixedText();
697 $titleWasConverted = false;
698 $iw = $titleObj->getInterwiki();
699 if ( strval( $iw ) !== '' ) {
700 // This title is an interwiki link.
701 $this->mInterwikiTitles
[$titleObj->getPrefixedText()] = $iw;
705 if ( $this->mConvertTitles
&&
706 count( $wgContLang->getVariants() ) > 1 &&
707 !$titleObj->exists() ) {
708 // Language::findVariantLink will modify titleObj into
709 // the canonical variant if possible
710 $wgContLang->findVariantLink( $title, $titleObj );
711 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
714 if ( $titleObj->getNamespace() < 0 ) {
715 // Handle Special and Media pages
716 $titleObj = $titleObj->fixSpecialName();
717 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
718 $this->mFakePageId
--;
721 $linkBatch->addObj( $titleObj );
725 // Make sure we remember the original title that was
726 // given to us. This way the caller can correlate new
727 // titles with the originally requested when e.g. the
728 // namespace is localized or the capitalization is
730 if ( $titleWasConverted ) {
731 $this->mConvertedTitles
[$title] = $titleObj->getPrefixedText();
732 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
733 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
741 * Returns the input array of integers with all values < 0 removed
743 * @param $array array
746 private static function getPositiveIntegers( $array ) {
747 // bug 25734 API: possible issue with revids validation
748 // It seems with a load of revision rows, MySQL gets upset
749 // Remove any < 0 integers, as they can't be valid
750 foreach( $array as $i => $int ) {
759 public function getAllowedParams() {
762 ApiBase
::PARAM_ISMULTI
=> true
765 ApiBase
::PARAM_TYPE
=> 'integer',
766 ApiBase
::PARAM_ISMULTI
=> true
769 ApiBase
::PARAM_TYPE
=> 'integer',
770 ApiBase
::PARAM_ISMULTI
=> true
775 public function getParamDescription() {
777 'titles' => 'A list of titles to work on',
778 'pageids' => 'A list of page IDs to work on',
779 'revids' => 'A list of revision IDs to work on'
783 public function getPossibleErrors() {
784 return array_merge( parent
::getPossibleErrors(), array(
785 array( 'code' => 'multisource', 'info' => "Cannot use 'pageids' at the same time as 'dataSource'" ),
786 array( 'code' => 'multisource', 'info' => "Cannot use 'revids' at the same time as 'dataSource'" ),
790 public function getVersion() {
791 return __CLASS__
. ': $Id$';