4 * Created on Sep 24, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiQueryBase.php' );
32 * This class contains a list of pages that the client has requested.
33 * Initially, when the client passes in titles=, pageids=, or revisions=
34 * parameter, an instance of the ApiPageSet class will normalize titles,
35 * determine if the pages/revisions exist, and prefetch any additional page
38 * When a generator is used, the result of the generator will become the input
39 * for the second instance of this class, and all subsequent actions will use
40 * the second instance for all their work.
44 class ApiPageSet
extends ApiQueryBase
{
46 private $mAllPages; // [ns][dbkey] => page_id or negative when missing
47 private $mTitles, $mGoodTitles, $mMissingTitles, $mInvalidTitles;
48 private $mMissingPageIDs, $mRedirectTitles, $mSpecialTitles;
49 private $mNormalizedTitles, $mInterwikiTitles;
50 private $mResolveRedirects, $mPendingRedirectIDs;
51 private $mConvertTitles, $mConvertedTitles;
52 private $mGoodRevIDs, $mMissingRevIDs;
55 private $mRequestedPageFields;
59 * @param $query ApiQuery
60 * @param $resolveRedirects bool Whether redirects should be resolved
62 public function __construct( $query, $resolveRedirects = false, $convertTitles = false ) {
63 parent
::__construct( $query, 'query' );
65 $this->mAllPages
= array();
66 $this->mTitles
= array();
67 $this->mGoodTitles
= array();
68 $this->mMissingTitles
= array();
69 $this->mInvalidTitles
= array();
70 $this->mMissingPageIDs
= array();
71 $this->mRedirectTitles
= array();
72 $this->mNormalizedTitles
= array();
73 $this->mInterwikiTitles
= array();
74 $this->mGoodRevIDs
= array();
75 $this->mMissingRevIDs
= array();
76 $this->mSpecialTitles
= array();
78 $this->mRequestedPageFields
= array();
79 $this->mResolveRedirects
= $resolveRedirects;
80 if ( $resolveRedirects ) {
81 $this->mPendingRedirectIDs
= array();
84 $this->mConvertTitles
= $convertTitles;
85 $this->mConvertedTitles
= array();
87 $this->mFakePageId
= - 1;
91 * Check whether this PageSet is resolving redirects
94 public function isResolvingRedirects() {
95 return $this->mResolveRedirects
;
99 * Request an additional field from the page table. Must be called
101 * @param $fieldName string Field name
103 public function requestField( $fieldName ) {
104 $this->mRequestedPageFields
[$fieldName] = null;
108 * Get the value of a custom field previously requested through
110 * @param $fieldName string Field name
111 * @return mixed Field value
113 public function getCustomField( $fieldName ) {
114 return $this->mRequestedPageFields
[$fieldName];
118 * Get the fields that have to be queried from the page table:
119 * the ones requested through requestField() and a few basic ones
121 * @return array of field names
123 public function getPageTableFields() {
124 // Ensure we get minimum required fields
125 // DON'T change this order
127 'page_namespace' => null,
128 'page_title' => null,
132 if ( $this->mResolveRedirects
) {
133 $pageFlds['page_is_redirect'] = null;
136 // only store non-default fields
137 $this->mRequestedPageFields
= array_diff_key( $this->mRequestedPageFields
, $pageFlds );
139 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
140 return array_keys( $pageFlds );
144 * Returns an array [ns][dbkey] => page_id for all requested titles.
145 * page_id is a unique negative number in case title was not found.
146 * Invalid titles will also have negative page IDs and will be in namespace 0
149 public function getAllTitlesByNamespace() {
150 return $this->mAllPages
;
154 * All Title objects provided.
155 * @return array of Title objects
157 public function getTitles() {
158 return $this->mTitles
;
162 * Returns the number of unique pages (not revisions) in the set.
165 public function getTitleCount() {
166 return count( $this->mTitles
);
170 * Title objects that were found in the database.
171 * @return array page_id (int) => Title (obj)
173 public function getGoodTitles() {
174 return $this->mGoodTitles
;
178 * Returns the number of found unique pages (not revisions) in the set.
181 public function getGoodTitleCount() {
182 return count( $this->mGoodTitles
);
186 * Title objects that were NOT found in the database.
187 * The array's index will be negative for each item
188 * @return array of Title objects
190 public function getMissingTitles() {
191 return $this->mMissingTitles
;
195 * Titles that were deemed invalid by Title::newFromText()
196 * The array's index will be unique and negative for each item
197 * @return array of strings (not Title objects)
199 public function getInvalidTitles() {
200 return $this->mInvalidTitles
;
204 * Page IDs that were not found in the database
205 * @return array of page IDs
207 public function getMissingPageIDs() {
208 return $this->mMissingPageIDs
;
212 * Get a list of redirect resolutions - maps a title to its redirect
214 * @return array prefixed_title (string) => prefixed_title (string)
216 public function getRedirectTitles() {
217 return $this->mRedirectTitles
;
221 * Get a list of title normalizations - maps a title to its normalized
223 * @return array raw_prefixed_title (string) => prefixed_title (string)
225 public function getNormalizedTitles() {
226 return $this->mNormalizedTitles
;
230 * Get a list of title conversions - maps a title to its converted
232 * @return array raw_prefixed_title (string) => prefixed_title (string)
234 public function getConvertedTitles() {
235 return $this->mConvertedTitles
;
239 * Get a list of interwiki titles - maps a title to its interwiki
241 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
243 public function getInterwikiTitles() {
244 return $this->mInterwikiTitles
;
248 * Get the list of revision IDs (requested with the revids= parameter)
249 * @return array revID (int) => pageID (int)
251 public function getRevisionIDs() {
252 return $this->mGoodRevIDs
;
256 * Revision IDs that were not found in the database
257 * @return array of revision IDs
259 public function getMissingRevisionIDs() {
260 return $this->mMissingRevIDs
;
264 * Get the list of titles with negative namespace
265 * @return array Title
267 public function getSpecialTitles() {
268 return $this->mSpecialTitles
;
272 * Returns the number of revisions (requested with revids= parameter)\
275 public function getRevisionCount() {
276 return count( $this->getRevisionIDs() );
280 * Populate the PageSet from the request parameters.
282 public function execute() {
284 $params = $this->extractRequestParams();
286 // Only one of the titles/pageids/revids is allowed at the same time
288 if ( isset( $params['titles'] ) ) {
289 $dataSource = 'titles';
291 if ( isset( $params['pageids'] ) ) {
292 if ( isset( $dataSource ) ) {
293 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
295 $dataSource = 'pageids';
297 if ( isset( $params['revids'] ) ) {
298 if ( isset( $dataSource ) ) {
299 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
301 $dataSource = 'revids';
304 switch ( $dataSource ) {
306 $this->initFromTitles( $params['titles'] );
309 $this->initFromPageIds( $params['pageids'] );
312 if ( $this->mResolveRedirects
) {
313 $this->setWarning( 'Redirect resolution cannot be used together with the revids= parameter. ' .
314 'Any redirects the revids= point to have not been resolved.' );
316 $this->mResolveRedirects
= false;
317 $this->initFromRevIDs( $params['revids'] );
320 // Do nothing - some queries do not need any of the data sources.
327 * Populate this PageSet from a list of Titles
328 * @param $titles array of Title objects
330 public function populateFromTitles( $titles ) {
332 $this->initFromTitles( $titles );
337 * Populate this PageSet from a list of page IDs
338 * @param $pageIDs array of page IDs
340 public function populateFromPageIDs( $pageIDs ) {
342 $this->initFromPageIds( $pageIDs );
347 * Populate this PageSet from a rowset returned from the database
348 * @param $db Database object
349 * @param $queryResult Query result object
351 public function populateFromQueryResult( $db, $queryResult ) {
353 $this->initFromQueryResult( $db, $queryResult );
358 * Populate this PageSet from a list of revision IDs
359 * @param $revIDs array of revision IDs
361 public function populateFromRevisionIDs( $revIDs ) {
363 $this->initFromRevIDs( $revIDs );
368 * Extract all requested fields from the row received from the database
369 * @param $row Result row
371 public function processDbRow( $row ) {
372 // Store Title object in various data structures
373 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
375 $pageId = intval( $row->page_id
);
376 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
377 $this->mTitles
[] = $title;
379 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
380 $this->mPendingRedirectIDs
[$pageId] = $title;
382 $this->mGoodTitles
[$pageId] = $title;
385 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
386 $fieldValues[$pageId] = $row-> $fieldName;
391 * Resolve redirects, if applicable
393 public function finishPageSetGeneration() {
395 $this->resolvePendingRedirects();
400 * This method populates internal variables with page information
401 * based on the given array of title strings.
404 * #1 For each title, get data from `page` table
405 * #2 If page was not found in the DB, store it as missing
407 * Additionally, when resolving redirects:
408 * #3 If no more redirects left, stop.
409 * #4 For each redirect, get its target from the `redirect` table.
410 * #5 Substitute the original LinkBatch object with the new list
411 * #6 Repeat from step #1
413 * @param $titles array of Title objects or strings
415 private function initFromTitles( $titles ) {
416 // Get validated and normalized title objects
417 $linkBatch = $this->processTitlesArray( $titles );
418 if ( $linkBatch->isEmpty() ) {
422 $db = $this->getDB();
423 $set = $linkBatch->constructSet( 'page', $db );
425 // Get pageIDs data from the `page` table
426 $this->profileDBIn();
427 $res = $db->select( 'page', $this->getPageTableFields(), $set,
429 $this->profileDBOut();
431 // Hack: get the ns:titles stored in array(ns => array(titles)) format
432 $this->initFromQueryResult( $db, $res, $linkBatch->data
, true ); // process Titles
434 // Resolve any found redirects
435 $this->resolvePendingRedirects();
439 * Does the same as initFromTitles(), but is based on page IDs instead
440 * @param $pageids array of page IDs
442 private function initFromPageIds( $pageids ) {
443 if ( !count( $pageids ) ) {
447 $pageids = array_map( 'intval', $pageids ); // paranoia
449 'page_id' => $pageids
451 $db = $this->getDB();
453 // Get pageIDs data from the `page` table
454 $this->profileDBIn();
455 $res = $db->select( 'page', $this->getPageTableFields(), $set,
457 $this->profileDBOut();
459 $remaining = array_flip( $pageids );
460 $this->initFromQueryResult( $db, $res, $remaining, false ); // process PageIDs
462 // Resolve any found redirects
463 $this->resolvePendingRedirects();
467 * Iterate through the result of the query on 'page' table,
468 * and for each row create and store title object and save any extra fields requested.
469 * @param $db Database
470 * @param $res DB Query result
471 * @param $remaining array of either pageID or ns/title elements (optional).
472 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
473 * @param $processTitles bool Must be provided together with $remaining.
474 * If true, treat $remaining as an array of [ns][title]
475 * If false, treat it as an array of [pageIDs]
477 private function initFromQueryResult( $db, $res, &$remaining = null, $processTitles = null ) {
478 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
479 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
482 foreach ( $res as $row ) {
483 $pageId = intval( $row->page_id
);
485 // Remove found page from the list of remaining items
486 if ( isset( $remaining ) ) {
487 if ( $processTitles ) {
488 unset( $remaining[$row->page_namespace
][$row->page_title
] );
490 unset( $remaining[$pageId] );
494 // Store any extra fields requested by modules
495 $this->processDbRow( $row );
498 if ( isset( $remaining ) ) {
499 // Any items left in the $remaining list are added as missing
500 if ( $processTitles ) {
501 // The remaining titles in $remaining are non-existent pages
502 foreach ( $remaining as $ns => $dbkeys ) {
503 foreach ( $dbkeys as $dbkey => $unused ) {
504 $title = Title
::makeTitle( $ns, $dbkey );
505 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
506 $this->mMissingTitles
[$this->mFakePageId
] = $title;
507 $this->mFakePageId
--;
508 $this->mTitles
[] = $title;
512 // The remaining pageids do not exist
513 if ( !$this->mMissingPageIDs
) {
514 $this->mMissingPageIDs
= array_keys( $remaining );
516 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
523 * Does the same as initFromTitles(), but is based on revision IDs
525 * @param $revids array of revision IDs
527 private function initFromRevIDs( $revids ) {
528 if ( !count( $revids ) ) {
532 $revids = array_map( 'intval', $revids ); // paranoia
533 $db = $this->getDB();
535 $remaining = array_flip( $revids );
537 $tables = array( 'revision', 'page' );
538 $fields = array( 'rev_id', 'rev_page' );
539 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
541 // Get pageIDs data from the `page` table
542 $this->profileDBIn();
543 $res = $db->select( $tables, $fields, $where, __METHOD__
);
544 foreach ( $res as $row ) {
545 $revid = intval( $row->rev_id
);
546 $pageid = intval( $row->rev_page
);
547 $this->mGoodRevIDs
[$revid] = $pageid;
548 $pageids[$pageid] = '';
549 unset( $remaining[$revid] );
551 $this->profileDBOut();
553 $this->mMissingRevIDs
= array_keys( $remaining );
555 // Populate all the page information
556 $this->initFromPageIds( array_keys( $pageids ) );
560 * Resolve any redirects in the result if redirect resolution was
561 * requested. This function is called repeatedly until all redirects
562 * have been resolved.
564 private function resolvePendingRedirects() {
565 if ( $this->mResolveRedirects
) {
566 $db = $this->getDB();
567 $pageFlds = $this->getPageTableFields();
569 // Repeat until all redirects have been resolved
570 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
571 while ( $this->mPendingRedirectIDs
) {
572 // Resolve redirects by querying the pagelinks table, and repeat the process
573 // Create a new linkBatch object for the next pass
574 $linkBatch = $this->getRedirectTargets();
576 if ( $linkBatch->isEmpty() ) {
580 $set = $linkBatch->constructSet( 'page', $db );
581 if ( $set === false ) {
585 // Get pageIDs data from the `page` table
586 $this->profileDBIn();
587 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
588 $this->profileDBOut();
590 // Hack: get the ns:titles stored in array(ns => array(titles)) format
591 $this->initFromQueryResult( $db, $res, $linkBatch->data
, true );
597 * Get the targets of the pending redirects from the database
599 * Also creates entries in the redirect table for redirects that don't
603 private function getRedirectTargets() {
604 $lb = new LinkBatch();
605 $db = $this->getDB();
607 $this->profileDBIn();
614 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ),
617 $this->profileDBOut();
619 foreach ( $res as $row ) {
620 $rdfrom = intval( $row->rd_from
);
621 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
622 $to = Title
::makeTitle( $row->rd_namespace
, $row->rd_title
)->getPrefixedText();
623 unset( $this->mPendingRedirectIDs
[$rdfrom] );
624 if ( !isset( $this->mAllPages
[$row->rd_namespace
][$row->rd_title
] ) ) {
625 $lb->add( $row->rd_namespace
, $row->rd_title
);
627 $this->mRedirectTitles
[$from] = $to;
630 if ( $this->mPendingRedirectIDs
) {
631 // We found pages that aren't in the redirect table
633 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
634 $article = new Article( $title );
635 $rt = $article->insertRedirect();
637 // What the hell. Let's just ignore this
641 $this->mRedirectTitles
[$title->getPrefixedText()] = $rt->getPrefixedText();
642 unset( $this->mPendingRedirectIDs
[$id] );
649 * Given an array of title strings, convert them into Title objects.
650 * Alternativelly, an array of Title objects may be given.
651 * This method validates access rights for the title,
652 * and appends normalization values to the output.
654 * @param $titles array of Title objects or strings
657 private function processTitlesArray( $titles ) {
658 $linkBatch = new LinkBatch();
660 foreach ( $titles as $title ) {
661 $titleObj = is_string( $title ) ? Title
::newFromText( $title ) : $title;
663 // Handle invalid titles gracefully
664 $this->mAllpages
[0][$title] = $this->mFakePageId
;
665 $this->mInvalidTitles
[$this->mFakePageId
] = $title;
666 $this->mFakePageId
--;
667 continue; // There's nothing else we can do
669 $unconvertedTitle = $titleObj->getPrefixedText();
670 $titleWasConverted = false;
671 $iw = $titleObj->getInterwiki();
672 if ( strval( $iw ) !== '' ) {
673 // This title is an interwiki link.
674 $this->mInterwikiTitles
[$titleObj->getPrefixedText()] = $iw;
678 if ( $this->mConvertTitles
&&
679 count( $wgContLang->getVariants() ) > 1 &&
680 !$titleObj->exists() ) {
681 // Language::findVariantLink will modify titleObj into
682 // the canonical variant if possible
683 $wgContLang->findVariantLink( $title, $titleObj );
684 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
688 if ( $titleObj->getNamespace() < 0 ) {
689 // Handle Special and Media pages
690 $titleObj = $titleObj->fixSpecialName();
691 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
692 $this->mFakePageId
--;
695 $linkBatch->addObj( $titleObj );
699 // Make sure we remember the original title that was
700 // given to us. This way the caller can correlate new
701 // titles with the originally requested when e.g. the
702 // namespace is localized or the capitalization is
704 if ( $titleWasConverted ) {
705 $this->mConvertedTitles
[$title] = $titleObj->getPrefixedText();
706 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
707 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
714 protected function getAllowedParams() {
717 ApiBase
::PARAM_ISMULTI
=> true
720 ApiBase
::PARAM_TYPE
=> 'integer',
721 ApiBase
::PARAM_ISMULTI
=> true
724 ApiBase
::PARAM_TYPE
=> 'integer',
725 ApiBase
::PARAM_ISMULTI
=> true
730 protected function getParamDescription() {
732 'titles' => 'A list of titles to work on',
733 'pageids' => 'A list of page IDs to work on',
734 'revids' => 'A list of revision IDs to work on'
738 public function getPossibleErrors() {
739 return array_merge( parent
::getPossibleErrors(), array(
740 array( 'code' => 'multisource', 'info' => "Cannot use 'pageids' at the same time as 'dataSource'" ),
741 array( 'code' => 'multisource', 'info' => "Cannot use 'revids' at the same time as 'dataSource'" ),
745 public function getVersion() {
746 return __CLASS__
. ': $Id$';