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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiQueryBase.php' );
33 * This class contains a list of pages that the client has requested.
34 * Initially, when the client passes in titles=, pageids=, or revisions=
35 * parameter, an instance of the ApiPageSet class will normalize titles,
36 * determine if the pages/revisions exist, and prefetch any additional page
39 * When a generator is used, the result of the generator will become the input
40 * for the second instance of this class, and all subsequent actions will use
41 * the second instance for all their work.
45 class ApiPageSet
extends ApiQueryBase
{
47 private $mAllPages; // [ns][dbkey] => page_id or negative when missing
48 private $mTitles, $mGoodTitles, $mMissingTitles, $mInvalidTitles;
49 private $mMissingPageIDs, $mRedirectTitles, $mSpecialTitles;
50 private $mNormalizedTitles, $mInterwikiTitles;
51 private $mResolveRedirects, $mPendingRedirectIDs;
52 private $mConvertTitles, $mConvertedTitles;
53 private $mGoodRevIDs, $mMissingRevIDs;
56 private $mRequestedPageFields;
60 * @param $query ApiQuery
61 * @param $resolveRedirects bool Whether redirects should be resolved
62 * @param $convertTitles bool
64 public function __construct( $query, $resolveRedirects = false, $convertTitles = false ) {
65 parent
::__construct( $query, 'query' );
67 $this->mAllPages
= array();
68 $this->mTitles
= array();
69 $this->mGoodTitles
= array();
70 $this->mMissingTitles
= array();
71 $this->mInvalidTitles
= array();
72 $this->mMissingPageIDs
= array();
73 $this->mRedirectTitles
= array();
74 $this->mNormalizedTitles
= array();
75 $this->mInterwikiTitles
= array();
76 $this->mGoodRevIDs
= array();
77 $this->mMissingRevIDs
= array();
78 $this->mSpecialTitles
= array();
80 $this->mRequestedPageFields
= array();
81 $this->mResolveRedirects
= $resolveRedirects;
82 if ( $resolveRedirects ) {
83 $this->mPendingRedirectIDs
= array();
86 $this->mConvertTitles
= $convertTitles;
87 $this->mConvertedTitles
= array();
89 $this->mFakePageId
= - 1;
93 * Check whether this PageSet is resolving redirects
96 public function isResolvingRedirects() {
97 return $this->mResolveRedirects
;
101 * Request an additional field from the page table. Must be called
103 * @param $fieldName string Field name
105 public function requestField( $fieldName ) {
106 $this->mRequestedPageFields
[$fieldName] = null;
110 * Get the value of a custom field previously requested through
112 * @param $fieldName string Field name
113 * @return mixed Field value
115 public function getCustomField( $fieldName ) {
116 return $this->mRequestedPageFields
[$fieldName];
120 * Get the fields that have to be queried from the page table:
121 * the ones requested through requestField() and a few basic ones
123 * @return array of field names
125 public function getPageTableFields() {
126 // Ensure we get minimum required fields
127 // DON'T change this order
129 'page_namespace' => null,
130 'page_title' => null,
134 if ( $this->mResolveRedirects
) {
135 $pageFlds['page_is_redirect'] = null;
138 // only store non-default fields
139 $this->mRequestedPageFields
= array_diff_key( $this->mRequestedPageFields
, $pageFlds );
141 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
142 return array_keys( $pageFlds );
146 * Returns an array [ns][dbkey] => page_id for all requested titles.
147 * page_id is a unique negative number in case title was not found.
148 * Invalid titles will also have negative page IDs and will be in namespace 0
151 public function getAllTitlesByNamespace() {
152 return $this->mAllPages
;
156 * All Title objects provided.
157 * @return array of Title objects
159 public function getTitles() {
160 return $this->mTitles
;
164 * Returns the number of unique pages (not revisions) in the set.
167 public function getTitleCount() {
168 return count( $this->mTitles
);
172 * Title objects that were found in the database.
173 * @return array page_id (int) => Title (obj)
175 public function getGoodTitles() {
176 return $this->mGoodTitles
;
180 * Returns the number of found unique pages (not revisions) in the set.
183 public function getGoodTitleCount() {
184 return count( $this->mGoodTitles
);
188 * Title objects that were NOT found in the database.
189 * The array's index will be negative for each item
190 * @return array of Title objects
192 public function getMissingTitles() {
193 return $this->mMissingTitles
;
197 * Titles that were deemed invalid by Title::newFromText()
198 * The array's index will be unique and negative for each item
199 * @return array of strings (not Title objects)
201 public function getInvalidTitles() {
202 return $this->mInvalidTitles
;
206 * Page IDs that were not found in the database
207 * @return array of page IDs
209 public function getMissingPageIDs() {
210 return $this->mMissingPageIDs
;
214 * Get a list of redirect resolutions - maps a title to its redirect
216 * @return array prefixed_title (string) => Title object
218 public function getRedirectTitles() {
219 return $this->mRedirectTitles
;
223 * Get a list of title normalizations - maps a title to its normalized
225 * @return array raw_prefixed_title (string) => prefixed_title (string)
227 public function getNormalizedTitles() {
228 return $this->mNormalizedTitles
;
232 * Get a list of title conversions - maps a title to its converted
234 * @return array raw_prefixed_title (string) => prefixed_title (string)
236 public function getConvertedTitles() {
237 return $this->mConvertedTitles
;
241 * Get a list of interwiki titles - maps a title to its interwiki
243 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
245 public function getInterwikiTitles() {
246 return $this->mInterwikiTitles
;
250 * Get the list of revision IDs (requested with the revids= parameter)
251 * @return array revID (int) => pageID (int)
253 public function getRevisionIDs() {
254 return $this->mGoodRevIDs
;
258 * Revision IDs that were not found in the database
259 * @return array of revision IDs
261 public function getMissingRevisionIDs() {
262 return $this->mMissingRevIDs
;
266 * Get the list of titles with negative namespace
267 * @return array Title
269 public function getSpecialTitles() {
270 return $this->mSpecialTitles
;
274 * Returns the number of revisions (requested with revids= parameter)\
277 public function getRevisionCount() {
278 return count( $this->getRevisionIDs() );
282 * Populate the PageSet from the request parameters.
284 public function execute() {
286 $params = $this->extractRequestParams();
288 // Only one of the titles/pageids/revids is allowed at the same time
290 if ( isset( $params['titles'] ) ) {
291 $dataSource = 'titles';
293 if ( isset( $params['pageids'] ) ) {
294 if ( isset( $dataSource ) ) {
295 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
297 $dataSource = 'pageids';
299 if ( isset( $params['revids'] ) ) {
300 if ( isset( $dataSource ) ) {
301 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
303 $dataSource = 'revids';
306 switch ( $dataSource ) {
308 $this->initFromTitles( $params['titles'] );
311 $this->initFromPageIds( $params['pageids'] );
314 if ( $this->mResolveRedirects
) {
315 $this->setWarning( 'Redirect resolution cannot be used together with the revids= parameter. ' .
316 'Any redirects the revids= point to have not been resolved.' );
318 $this->mResolveRedirects
= false;
319 $this->initFromRevIDs( $params['revids'] );
322 // Do nothing - some queries do not need any of the data sources.
329 * Populate this PageSet from a list of Titles
330 * @param $titles array of Title objects
332 public function populateFromTitles( $titles ) {
334 $this->initFromTitles( $titles );
339 * Populate this PageSet from a list of page IDs
340 * @param $pageIDs array of page IDs
342 public function populateFromPageIDs( $pageIDs ) {
344 $this->initFromPageIds( $pageIDs );
349 * Populate this PageSet from a rowset returned from the database
350 * @param $db Database object
351 * @param $queryResult ResultWrapper Query result object
353 public function populateFromQueryResult( $db, $queryResult ) {
355 $this->initFromQueryResult( $queryResult );
360 * Populate this PageSet from a list of revision IDs
361 * @param $revIDs array of revision IDs
363 public function populateFromRevisionIDs( $revIDs ) {
365 $this->initFromRevIDs( $revIDs );
370 * Extract all requested fields from the row received from the database
371 * @param $row Result row
373 public function processDbRow( $row ) {
374 // Store Title object in various data structures
375 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
377 $pageId = intval( $row->page_id
);
378 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
379 $this->mTitles
[] = $title;
381 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
382 $this->mPendingRedirectIDs
[$pageId] = $title;
384 $this->mGoodTitles
[$pageId] = $title;
387 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
388 $fieldValues[$pageId] = $row-> $fieldName;
393 * Resolve redirects, if applicable
395 public function finishPageSetGeneration() {
397 $this->resolvePendingRedirects();
402 * This method populates internal variables with page information
403 * based on the given array of title strings.
406 * #1 For each title, get data from `page` table
407 * #2 If page was not found in the DB, store it as missing
409 * Additionally, when resolving redirects:
410 * #3 If no more redirects left, stop.
411 * #4 For each redirect, get its target from the `redirect` table.
412 * #5 Substitute the original LinkBatch object with the new list
413 * #6 Repeat from step #1
415 * @param $titles array of Title objects or strings
417 private function initFromTitles( $titles ) {
418 // Get validated and normalized title objects
419 $linkBatch = $this->processTitlesArray( $titles );
420 if ( $linkBatch->isEmpty() ) {
424 $db = $this->getDB();
425 $set = $linkBatch->constructSet( 'page', $db );
427 // Get pageIDs data from the `page` table
428 $this->profileDBIn();
429 $res = $db->select( 'page', $this->getPageTableFields(), $set,
431 $this->profileDBOut();
433 // Hack: get the ns:titles stored in array(ns => array(titles)) format
434 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
436 // Resolve any found redirects
437 $this->resolvePendingRedirects();
441 * Does the same as initFromTitles(), but is based on page IDs instead
442 * @param $pageids array of page IDs
444 private function initFromPageIds( $pageids ) {
445 if ( !count( $pageids ) ) {
449 $pageids = array_map( 'intval', $pageids ); // paranoia
451 'page_id' => $pageids
453 $db = $this->getDB();
455 // Get pageIDs data from the `page` table
456 $this->profileDBIn();
457 $res = $db->select( 'page', $this->getPageTableFields(), $set,
459 $this->profileDBOut();
461 $remaining = array_flip( $pageids );
462 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
464 // Resolve any found redirects
465 $this->resolvePendingRedirects();
469 * Iterate through the result of the query on 'page' table,
470 * and for each row create and store title object and save any extra fields requested.
471 * @param $res ResultWrapper DB Query result
472 * @param $remaining array of either pageID or ns/title elements (optional).
473 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
474 * @param $processTitles bool Must be provided together with $remaining.
475 * If true, treat $remaining as an array of [ns][title]
476 * If false, treat it as an array of [pageIDs]
478 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
479 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
480 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
483 foreach ( $res as $row ) {
484 $pageId = intval( $row->page_id
);
486 // Remove found page from the list of remaining items
487 if ( isset( $remaining ) ) {
488 if ( $processTitles ) {
489 unset( $remaining[$row->page_namespace
][$row->page_title
] );
491 unset( $remaining[$pageId] );
495 // Store any extra fields requested by modules
496 $this->processDbRow( $row );
499 if ( isset( $remaining ) ) {
500 // Any items left in the $remaining list are added as missing
501 if ( $processTitles ) {
502 // The remaining titles in $remaining are non-existent pages
503 foreach ( $remaining as $ns => $dbkeys ) {
504 foreach ( array_keys( $dbkeys ) as $dbkey ) {
505 $title = Title
::makeTitle( $ns, $dbkey );
506 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
507 $this->mMissingTitles
[$this->mFakePageId
] = $title;
508 $this->mFakePageId
--;
509 $this->mTitles
[] = $title;
513 // The remaining pageids do not exist
514 if ( !$this->mMissingPageIDs
) {
515 $this->mMissingPageIDs
= array_keys( $remaining );
517 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
524 * Does the same as initFromTitles(), but is based on revision IDs
526 * @param $revids array of revision IDs
528 private function initFromRevIDs( $revids ) {
529 if ( !count( $revids ) ) {
533 $revids = array_map( 'intval', $revids ); // paranoia
534 $db = $this->getDB();
536 $remaining = array_flip( $revids );
538 // bug 25734 API: possible issue with revids validation
539 // It seems with a load of revision rows, MySQL gets upset
540 // Remove any < 0 revids, as they can't be valid
541 foreach( $revids as $i => $revid ) {
543 unset( $revids[$i] );
547 $tables = array( 'revision', 'page' );
548 $fields = array( 'rev_id', 'rev_page' );
549 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
551 // Get pageIDs data from the `page` table
552 $this->profileDBIn();
553 $res = $db->select( $tables, $fields, $where, __METHOD__
);
554 foreach ( $res as $row ) {
555 $revid = intval( $row->rev_id
);
556 $pageid = intval( $row->rev_page
);
557 $this->mGoodRevIDs
[$revid] = $pageid;
558 $pageids[$pageid] = '';
559 unset( $remaining[$revid] );
561 $this->profileDBOut();
563 $this->mMissingRevIDs
= array_keys( $remaining );
565 // Populate all the page information
566 $this->initFromPageIds( array_keys( $pageids ) );
570 * Resolve any redirects in the result if redirect resolution was
571 * requested. This function is called repeatedly until all redirects
572 * have been resolved.
574 private function resolvePendingRedirects() {
575 if ( $this->mResolveRedirects
) {
576 $db = $this->getDB();
577 $pageFlds = $this->getPageTableFields();
579 // Repeat until all redirects have been resolved
580 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
581 while ( $this->mPendingRedirectIDs
) {
582 // Resolve redirects by querying the pagelinks table, and repeat the process
583 // Create a new linkBatch object for the next pass
584 $linkBatch = $this->getRedirectTargets();
586 if ( $linkBatch->isEmpty() ) {
590 $set = $linkBatch->constructSet( 'page', $db );
591 if ( $set === false ) {
595 // Get pageIDs data from the `page` table
596 $this->profileDBIn();
597 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
598 $this->profileDBOut();
600 // Hack: get the ns:titles stored in array(ns => array(titles)) format
601 $this->initFromQueryResult( $res, $linkBatch->data
, true );
607 * Get the targets of the pending redirects from the database
609 * Also creates entries in the redirect table for redirects that don't
613 private function getRedirectTargets() {
614 $lb = new LinkBatch();
615 $db = $this->getDB();
617 $this->profileDBIn();
626 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ),
629 $this->profileDBOut();
630 foreach ( $res as $row ) {
631 $rdfrom = intval( $row->rd_from
);
632 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
633 $to = Title
::makeTitle( $row->rd_namespace
, $row->rd_title
, $row->rd_fragment
, $row->rd_interwiki
);
634 unset( $this->mPendingRedirectIDs
[$rdfrom] );
635 if ( !isset( $this->mAllPages
[$row->rd_namespace
][$row->rd_title
] ) ) {
636 $lb->add( $row->rd_namespace
, $row->rd_title
);
638 $this->mRedirectTitles
[$from] = $to;
641 if ( $this->mPendingRedirectIDs
) {
642 // We found pages that aren't in the redirect table
644 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
645 $article = new Article( $title );
646 $rt = $article->insertRedirect();
648 // What the hell. Let's just ignore this
652 $this->mRedirectTitles
[$title->getPrefixedText()] = $rt;
653 unset( $this->mPendingRedirectIDs
[$id] );
660 * Given an array of title strings, convert them into Title objects.
661 * Alternativelly, an array of Title objects may be given.
662 * This method validates access rights for the title,
663 * and appends normalization values to the output.
665 * @param $titles array of Title objects or strings
668 private function processTitlesArray( $titles ) {
669 $linkBatch = new LinkBatch();
671 foreach ( $titles as $title ) {
672 $titleObj = is_string( $title ) ? Title
::newFromText( $title ) : $title;
674 // Handle invalid titles gracefully
675 $this->mAllpages
[0][$title] = $this->mFakePageId
;
676 $this->mInvalidTitles
[$this->mFakePageId
] = $title;
677 $this->mFakePageId
--;
678 continue; // There's nothing else we can do
680 $unconvertedTitle = $titleObj->getPrefixedText();
681 $titleWasConverted = false;
682 $iw = $titleObj->getInterwiki();
683 if ( strval( $iw ) !== '' ) {
684 // This title is an interwiki link.
685 $this->mInterwikiTitles
[$titleObj->getPrefixedText()] = $iw;
689 if ( $this->mConvertTitles
&&
690 count( $wgContLang->getVariants() ) > 1 &&
691 !$titleObj->exists() ) {
692 // Language::findVariantLink will modify titleObj into
693 // the canonical variant if possible
694 $wgContLang->findVariantLink( $title, $titleObj );
695 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
698 if ( $titleObj->getNamespace() < 0 ) {
699 // Handle Special and Media pages
700 $titleObj = $titleObj->fixSpecialName();
701 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
702 $this->mFakePageId
--;
705 $linkBatch->addObj( $titleObj );
709 // Make sure we remember the original title that was
710 // given to us. This way the caller can correlate new
711 // titles with the originally requested when e.g. the
712 // namespace is localized or the capitalization is
714 if ( $titleWasConverted ) {
715 $this->mConvertedTitles
[$title] = $titleObj->getPrefixedText();
716 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
717 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
724 protected function getAllowedParams() {
727 ApiBase
::PARAM_ISMULTI
=> true
730 ApiBase
::PARAM_TYPE
=> 'integer',
731 ApiBase
::PARAM_ISMULTI
=> true
734 ApiBase
::PARAM_TYPE
=> 'integer',
735 ApiBase
::PARAM_ISMULTI
=> true
740 protected function getParamDescription() {
742 'titles' => 'A list of titles to work on',
743 'pageids' => 'A list of page IDs to work on',
744 'revids' => 'A list of revision IDs to work on'
748 public function getPossibleErrors() {
749 return array_merge( parent
::getPossibleErrors(), array(
750 array( 'code' => 'multisource', 'info' => "Cannot use 'pageids' at the same time as 'dataSource'" ),
751 array( 'code' => 'multisource', 'info' => "Cannot use 'revids' at the same time as 'dataSource'" ),
755 public function getVersion() {
756 return __CLASS__
. ': $Id$';