4 * Created on Sep 24, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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= parameter,
34 * an instance of the ApiPageSet class will normalize titles,
35 * determine if the pages/revisions exist, and prefetch any additional data page data requested.
37 * When generator is used, the result of the generator will become the input for the
38 * second instance of this class, and all subsequent actions will go use the second instance
43 class ApiPageSet
extends ApiQueryBase
{
45 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
46 private $mTitles, $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles, $mNormalizedTitles, $mInterwikiTitles;
47 private $mResolveRedirects, $mPendingRedirectIDs;
48 private $mGoodRevIDs, $mMissingRevIDs;
50 private $mRequestedPageFields;
52 public function __construct($query, $resolveRedirects = false) {
53 parent
:: __construct($query, __CLASS__
);
55 $this->mAllPages
= array ();
56 $this->mTitles
= array();
57 $this->mGoodTitles
= array ();
58 $this->mMissingTitles
= array ();
59 $this->mMissingPageIDs
= array ();
60 $this->mRedirectTitles
= array ();
61 $this->mNormalizedTitles
= array ();
62 $this->mInterwikiTitles
= array ();
63 $this->mGoodRevIDs
= array();
64 $this->mMissingRevIDs
= array();
66 $this->mRequestedPageFields
= array ();
67 $this->mResolveRedirects
= $resolveRedirects;
69 $this->mPendingRedirectIDs
= array();
72 public function isResolvingRedirects() {
73 return $this->mResolveRedirects
;
76 public function requestField($fieldName) {
77 $this->mRequestedPageFields
[$fieldName] = null;
80 public function getCustomField($fieldName) {
81 return $this->mRequestedPageFields
[$fieldName];
85 * Get fields that modules have requested from the page table
87 public function getPageTableFields() {
88 // Ensure we get minimum required fields
91 'page_namespace' => null,
95 // only store non-default fields
96 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
98 if ($this->mResolveRedirects
)
99 $pageFlds['page_is_redirect'] = null;
101 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields
);
102 return array_keys($pageFlds);
106 * All Title objects provided.
107 * @return array of Title objects
109 public function getTitles() {
110 return $this->mTitles
;
114 * Returns the number of unique pages (not revisions) in the set.
116 public function getTitleCount() {
117 return count($this->mTitles
);
121 * Title objects that were found in the database.
122 * @return array page_id (int) => Title (obj)
124 public function getGoodTitles() {
125 return $this->mGoodTitles
;
129 * Returns the number of found unique pages (not revisions) in the set.
131 public function getGoodTitleCount() {
132 return count($this->mGoodTitles
);
136 * Title objects that were NOT found in the database.
137 * @return array of Title objects
139 public function getMissingTitles() {
140 return $this->mMissingTitles
;
144 * Page IDs that were not found in the database
145 * @return array of page IDs
147 public function getMissingPageIDs() {
148 return $this->mMissingPageIDs
;
152 * Get a list of redirects when doing redirect resolution
153 * @return array prefixed_title (string) => prefixed_title (string)
155 public function getRedirectTitles() {
156 return $this->mRedirectTitles
;
160 * Get a list of title normalizations - maps the title given
161 * with its normalized version.
162 * @return array raw_prefixed_title (string) => prefixed_title (string)
164 public function getNormalizedTitles() {
165 return $this->mNormalizedTitles
;
169 * Get a list of interwiki titles - maps the title given
170 * with to the interwiki prefix.
171 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
173 public function getInterwikiTitles() {
174 return $this->mInterwikiTitles
;
178 * Get the list of revision IDs (requested with revids= parameter)
179 * @return array revID (int) => pageID (int)
181 public function getRevisionIDs() {
182 return $this->mGoodRevIDs
;
186 * Revision IDs that were not found in the database
187 * @return array of revision IDs
189 public function getMissingRevisionIDs() {
190 return $this->mMissingRevIDs
;
194 * Returns the number of revisions (requested with revids= parameter)
196 public function getRevisionCount() {
197 return count($this->getRevisionIDs());
201 * Populate from the request parameters
203 public function execute() {
205 $titles = $pageids = $revids = null;
206 extract($this->extractRequestParams());
208 // Only one of the titles/pageids/revids is allowed at the same time
211 $dataSource = 'titles';
212 if (isset ($pageids)) {
213 if (isset ($dataSource))
214 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
215 $dataSource = 'pageids';
217 if (isset ($revids)) {
218 if (isset ($dataSource))
219 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
220 $dataSource = 'revids';
223 switch ($dataSource) {
225 $this->initFromTitles($titles);
228 $this->initFromPageIds($pageids);
231 if($this->mResolveRedirects
)
232 $this->dieUsage('revids may not be used with redirect resolution', 'params');
233 $this->initFromRevIDs($revids);
236 // Do nothing - some queries do not need any of the data sources.
243 * Initialize PageSet from a list of Titles
245 public function populateFromTitles($titles) {
247 $this->initFromTitles($titles);
252 * Initialize PageSet from a list of Page IDs
254 public function populateFromPageIDs($pageIDs) {
256 $pageIDs = array_map('intval', $pageIDs); // paranoia
257 $this->initFromPageIds($pageIDs);
262 * Initialize PageSet from a rowset returned from the database
264 public function populateFromQueryResult($db, $queryResult) {
266 $this->initFromQueryResult($db, $queryResult);
271 * Initialize PageSet from a list of Revision IDs
273 public function populateFromRevisionIDs($revIDs) {
275 $revIDs = array_map('intval', $revIDs); // paranoia
276 $this->initFromRevIDs($revIDs);
281 * Extract all requested fields from the row received from the database
283 public function processDbRow($row) {
285 // Store Title object in various data structures
286 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
288 // skip any pages that user has no rights to read
289 if ($title->userCanRead()) {
291 $pageId = intval($row->page_id
);
292 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
293 $this->mTitles
[] = $title;
295 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
296 $this->mPendingRedirectIDs
[$pageId] = $title;
298 $this->mGoodTitles
[$pageId] = $title;
301 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
302 $fieldValues[$pageId] = $row-> $fieldName;
306 public function finishPageSetGeneration() {
308 $this->resolvePendingRedirects();
313 * This method populates internal variables with page information
314 * based on the given array of title strings.
317 * #1 For each title, get data from `page` table
318 * #2 If page was not found in the DB, store it as missing
320 * Additionally, when resolving redirects:
321 * #3 If no more redirects left, stop.
322 * #4 For each redirect, get its links from `pagelinks` table.
323 * #5 Substitute the original LinkBatch object with the new list
324 * #6 Repeat from step #1
326 private function initFromTitles($titles) {
328 // Get validated and normalized title objects
329 $linkBatch = $this->processTitlesArray($titles);
330 if($linkBatch->isEmpty())
333 $db = $this->getDB();
334 $set = $linkBatch->constructSet('page', $db);
336 // Get pageIDs data from the `page` table
337 $this->profileDBIn();
338 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
339 $this->profileDBOut();
341 // Hack: get the ns:titles stored in array(ns => array(titles)) format
342 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
344 // Resolve any found redirects
345 $this->resolvePendingRedirects();
348 private function initFromPageIds($pageids) {
353 'page_id' => $pageids
356 $db = $this->getDB();
358 // Get pageIDs data from the `page` table
359 $this->profileDBIn();
360 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
361 $this->profileDBOut();
363 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
365 // Resolve any found redirects
366 $this->resolvePendingRedirects();
370 * Iterate through the result of the query on 'page' table,
371 * and for each row create and store title object and save any extra fields requested.
372 * @param $db Database
373 * @param $res DB Query result
374 * @param $remaining Array of either pageID or ns/title elements (optional).
375 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
376 * @param $processTitles bool Must be provided together with $remaining.
377 * If true, treat $remaining as an array of [ns][title]
378 * If false, treat it as an array of [pageIDs]
379 * @return Array of redirect IDs (only when resolving redirects)
381 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
382 if (!is_null($remaining) && is_null($processTitles))
383 ApiBase
:: dieDebug(__METHOD__
, 'Missing $processTitles parameter when $remaining is provided');
385 while ($row = $db->fetchObject($res)) {
387 $pageId = intval($row->page_id
);
389 // Remove found page from the list of remaining items
390 if (isset($remaining)) {
392 unset ($remaining[$row->page_namespace
][$row->page_title
]);
394 unset ($remaining[$pageId]);
397 // Store any extra fields requested by modules
398 $this->processDbRow($row);
400 $db->freeResult($res);
402 if(isset($remaining)) {
403 // Any items left in the $remaining list are added as missing
405 // The remaining titles in $remaining are non-existant pages
406 foreach ($remaining as $ns => $dbkeys) {
407 foreach ( $dbkeys as $dbkey => $unused ) {
408 $title = Title
:: makeTitle($ns, $dbkey);
409 $this->mMissingTitles
[] = $title;
410 $this->mAllPages
[$ns][$dbkey] = 0;
411 $this->mTitles
[] = $title;
417 // The remaining pageids do not exist
418 if(empty($this->mMissingPageIDs
))
419 $this->mMissingPageIDs
= array_keys($remaining);
421 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
426 private function initFromRevIDs($revids) {
431 $db = $this->getDB();
433 $remaining = array_flip($revids);
435 $tables = array('revision');
436 $fields = array('rev_id','rev_page');
437 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
439 // Get pageIDs data from the `page` table
440 $this->profileDBIn();
441 $res = $db->select( $tables, $fields, $where, __METHOD__
);
442 while ( $row = $db->fetchObject( $res ) ) {
443 $revid = intval($row->rev_id
);
444 $pageid = intval($row->rev_page
);
445 $this->mGoodRevIDs
[$revid] = $pageid;
446 $pageids[$pageid] = '';
447 unset($remaining[$revid]);
449 $db->freeResult( $res );
450 $this->profileDBOut();
452 $this->mMissingRevIDs
= array_keys($remaining);
454 // Populate all the page information
455 if($this->mResolveRedirects
)
456 ApiBase
:: dieDebug(__METHOD__
, 'revids may not be used with redirect resolution');
457 $this->initFromPageIds(array_keys($pageids));
460 private function resolvePendingRedirects() {
462 if($this->mResolveRedirects
) {
463 $db = $this->getDB();
464 $pageFlds = $this->getPageTableFields();
466 // Repeat until all redirects have been resolved
467 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
468 while (!empty ($this->mPendingRedirectIDs
)) {
470 // Resolve redirects by querying the pagelinks table, and repeat the process
471 // Create a new linkBatch object for the next pass
472 $linkBatch = $this->getRedirectTargets();
474 if ($linkBatch->isEmpty())
477 $set = $linkBatch->constructSet('page', $db);
481 // Get pageIDs data from the `page` table
482 $this->profileDBIn();
483 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
484 $this->profileDBOut();
486 // Hack: get the ns:titles stored in array(ns => array(titles)) format
487 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
492 private function getRedirectTargets() {
494 $linkBatch = new LinkBatch();
495 $db = $this->getDB();
497 // find redirect targets for all redirect pages
498 $this->profileDBIn();
499 $res = $db->select('pagelinks', array (
504 'pl_from' => array_keys($this->mPendingRedirectIDs
506 $this->profileDBOut();
508 while ($row = $db->fetchObject($res)) {
510 $plfrom = intval($row->pl_from
);
512 // Bug 7304 workaround
513 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
514 // A redirect page may have more than one link.
515 // This code will only use the first link returned.
516 if (isset ($this->mPendingRedirectIDs
[$plfrom])) { // remove line when bug 7304 is fixed
518 $titleStrFrom = $this->mPendingRedirectIDs
[$plfrom]->getPrefixedText();
519 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
520 unset ($this->mPendingRedirectIDs
[$plfrom]); // remove line when bug 7304 is fixed
522 // Avoid an infinite loop by checking if we have already processed this target
523 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
524 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
527 // This redirect page has more than one link.
528 // This is very slow, but safer until bug 7304 is resolved
529 $title = Title
:: newFromID($plfrom);
530 $titleStrFrom = $title->getPrefixedText();
532 $article = new Article($title);
533 $text = $article->getContent();
534 $titleTo = Title
:: newFromRedirect($text);
535 $titleStrTo = $titleTo->getPrefixedText();
537 if (is_null($titleStrTo))
538 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
540 // Avoid an infinite loop by checking if we have already processed this target
541 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
542 $linkBatch->addObj($titleTo);
546 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
548 $db->freeResult($res);
550 // All IDs must exist in the page table
551 if (!empty($this->mPendingRedirectIDs
[$plfrom]))
552 ApiBase
:: dieDebug(__METHOD__
, 'Invalid redirect IDs were found');
558 * Given an array of title strings, convert them into Title objects.
559 * Alternativelly, an array of Title objects may be given.
560 * This method validates access rights for the title,
561 * and appends normalization values to the output.
563 * @return LinkBatch of title objects.
565 private function processTitlesArray($titles) {
567 $linkBatch = new LinkBatch();
569 foreach ($titles as $title) {
571 $titleObj = is_string($title) ? Title
:: newFromText($title) : $title;
573 $this->dieUsage("bad title $titleString", 'invalidtitle');
575 $iw = $titleObj->getInterwiki();
577 // This title is an interwiki link.
578 $this->mInterwikiTitles
[$titleObj->getPrefixedText()] = $iw;
582 if ($titleObj->getNamespace() < 0)
583 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
584 if (!$titleObj->userCanRead())
585 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
587 $linkBatch->addObj($titleObj);
590 // Make sure we remember the original title that was given to us
591 // This way the caller can correlate new titles with the originally requested,
592 // i.e. namespace is localized or capitalization is different
593 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
594 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
601 protected function getAllowedParams() {
604 ApiBase
:: PARAM_ISMULTI
=> true
607 ApiBase
:: PARAM_TYPE
=> 'integer',
608 ApiBase
:: PARAM_ISMULTI
=> true
611 ApiBase
:: PARAM_TYPE
=> 'integer',
612 ApiBase
:: PARAM_ISMULTI
=> true
617 protected function getParamDescription() {
619 'titles' => 'A list of titles to work on',
620 'pageids' => 'A list of page IDs to work on',
621 'revids' => 'A list of revision IDs to work on'
625 public function getVersion() {
626 return __CLASS__
. ': $Id$';