* Removed inconsistent hard coding of colons
[mediawiki.git] / includes / api / ApiPageSet.php
bloba99ec218e2fef91625fc8a9023c9c7281d2c46f8
1 <?php
3 /*
4 * Created on Sep 24, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@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');
31 /**
32 * @addtogroup API
34 class ApiPageSet extends ApiQueryBase {
36 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
37 private $mTitles, $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles, $mNormalizedTitles;
38 private $mResolveRedirects, $mPendingRedirectIDs;
39 private $mGoodRevIDs, $mMissingRevIDs;
41 private $mRequestedPageFields;
43 public function __construct($query, $resolveRedirects = false) {
44 parent :: __construct($query, __CLASS__);
46 $this->mAllPages = array ();
47 $this->mTitles = array();
48 $this->mGoodTitles = array ();
49 $this->mMissingTitles = array ();
50 $this->mMissingPageIDs = array ();
51 $this->mRedirectTitles = array ();
52 $this->mNormalizedTitles = array ();
53 $this->mGoodRevIDs = array();
54 $this->mMissingRevIDs = array();
56 $this->mRequestedPageFields = array ();
57 $this->mResolveRedirects = $resolveRedirects;
58 if($resolveRedirects)
59 $this->mPendingRedirectIDs = array();
62 public function isResolvingRedirects() {
63 return $this->mResolveRedirects;
66 public function requestField($fieldName) {
67 $this->mRequestedPageFields[$fieldName] = null;
70 public function getCustomField($fieldName) {
71 return $this->mRequestedPageFields[$fieldName];
74 /**
75 * Get fields that modules have requested from the page table
77 public function getPageTableFields() {
78 // Ensure we get minimum required fields
79 $pageFlds = array (
80 'page_id' => null,
81 'page_namespace' => null,
82 'page_title' => null
85 // only store non-default fields
86 $this->mRequestedPageFields = array_diff_key($this->mRequestedPageFields, $pageFlds);
88 if ($this->mResolveRedirects)
89 $pageFlds['page_is_redirect'] = null;
91 return array_keys(array_merge($pageFlds, $this->mRequestedPageFields));
94 /**
95 * All Title objects provided.
96 * @return array of Title objects
98 public function getTitles() {
99 return $this->mTitles;
103 * Returns the number of unique pages (not revisions) in the set.
105 public function getTitleCount() {
106 return count($this->mTitles);
110 * Title objects that were found in the database.
111 * @return array page_id (int) => Title (obj)
113 public function getGoodTitles() {
114 return $this->mGoodTitles;
118 * Returns the number of found unique pages (not revisions) in the set.
120 public function getGoodTitleCount() {
121 return count($this->mGoodTitles);
125 * Title objects that were NOT found in the database.
126 * @return array of Title objects
128 public function getMissingTitles() {
129 return $this->mMissingTitles;
133 * Page IDs that were not found in the database
134 * @return array of page IDs
136 public function getMissingPageIDs() {
137 return $this->mMissingPageIDs;
141 * Get a list of redirects when doing redirect resolution
142 * @return array prefixed_title (string) => prefixed_title (string)
144 public function getRedirectTitles() {
145 return $this->mRedirectTitles;
149 * Get a list of title normalizations - maps the title given
150 * with its normalized version.
151 * @return array raw_prefixed_title (string) => prefixed_title (string)
153 public function getNormalizedTitles() {
154 return $this->mNormalizedTitles;
158 * Get the list of revision IDs (requested with revids= parameter)
159 * @return array revID (int) => pageID (int)
161 public function getRevisionIDs() {
162 return $this->mGoodRevIDs;
166 * Revision IDs that were not found in the database
167 * @return array of revision IDs
169 public function getMissingRevisionIDs() {
170 return $this->mMissingRevIDs;
174 * Returns the number of revisions (requested with revids= parameter)
176 public function getRevisionCount() {
177 return count($this->getRevisionIDs());
181 * Populate from the request parameters
183 public function execute() {
184 $this->profileIn();
185 $titles = $pageids = $revids = null;
186 extract($this->extractRequestParams());
188 // Only one of the titles/pageids/revids is allowed at the same time
189 $dataSource = null;
190 if (isset ($titles))
191 $dataSource = 'titles';
192 if (isset ($pageids)) {
193 if (isset ($dataSource))
194 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
195 $dataSource = 'pageids';
197 if (isset ($revids)) {
198 if (isset ($dataSource))
199 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
200 $dataSource = 'revids';
203 switch ($dataSource) {
204 case 'titles' :
205 $this->initFromTitles($titles);
206 break;
207 case 'pageids' :
208 $this->initFromPageIds($pageids);
209 break;
210 case 'revids' :
211 if($this->mResolveRedirects)
212 $this->dieUsage('revids may not be used with redirect resolution', 'params');
213 $this->initFromRevIDs($revids);
214 break;
215 default :
216 // Do nothing - some queries do not need any of the data sources.
217 break;
219 $this->profileOut();
223 * Initialize PageSet from a list of Titles
225 public function populateFromTitles($titles) {
226 $this->profileIn();
227 $this->initFromTitles($titles);
228 $this->profileOut();
232 * Initialize PageSet from a list of Page IDs
234 public function populateFromPageIDs($pageIDs) {
235 $this->profileIn();
236 $pageIDs = array_map('intval', $pageIDs); // paranoia
237 $this->initFromPageIds($pageIDs);
238 $this->profileOut();
242 * Initialize PageSet from a rowset returned from the database
244 public function populateFromQueryResult($db, $queryResult) {
245 $this->profileIn();
246 $this->initFromQueryResult($db, $queryResult);
247 $this->profileOut();
251 * Initialize PageSet from a list of Revision IDs
253 public function populateFromRevisionIDs($revIDs) {
254 $this->profileIn();
255 $revIDs = array_map('intval', $revIDs); // paranoia
256 $this->initFromRevIDs($revIDs);
257 $this->profileOut();
261 * Extract all requested fields from the row received from the database
263 public function processDbRow($row) {
265 // Store Title object in various data structures
266 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
268 // skip any pages that user has no rights to read
269 if ($title->userCanRead()) {
271 $pageId = intval($row->page_id);
272 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
273 $this->mTitles[] = $title;
275 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
276 $this->mPendingRedirectIDs[$pageId] = $title;
277 } else {
278 $this->mGoodTitles[$pageId] = $title;
281 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
282 $fieldValues[$pageId] = $row-> $fieldName;
286 public function finishPageSetGeneration() {
287 $this->profileIn();
288 $this->resolvePendingRedirects();
289 $this->profileOut();
293 * This method populates internal variables with page information
294 * based on the given array of title strings.
296 * Steps:
297 * #1 For each title, get data from `page` table
298 * #2 If page was not found in the DB, store it as missing
300 * Additionally, when resolving redirects:
301 * #3 If no more redirects left, stop.
302 * #4 For each redirect, get its links from `pagelinks` table.
303 * #5 Substitute the original LinkBatch object with the new list
304 * #6 Repeat from step #1
306 private function initFromTitles($titles) {
308 // Get validated and normalized title objects
309 $linkBatch = $this->processTitlesStrArray($titles);
310 if($linkBatch->isEmpty())
311 return;
313 $db = $this->getDB();
314 $set = $linkBatch->constructSet('page', $db);
316 // Get pageIDs data from the `page` table
317 $this->profileDBIn();
318 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
319 $this->profileDBOut();
321 // Hack: get the ns:titles stored in array(ns => array(titles)) format
322 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
324 // Resolve any found redirects
325 $this->resolvePendingRedirects();
328 private function initFromPageIds($pageids) {
329 if(empty($pageids))
330 return;
332 $set = array (
333 'page_id' => $pageids
336 $db = $this->getDB();
338 // Get pageIDs data from the `page` table
339 $this->profileDBIn();
340 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
341 $this->profileDBOut();
343 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
345 // Resolve any found redirects
346 $this->resolvePendingRedirects();
350 * Iterate through the result of the query on 'page' table,
351 * and for each row create and store title object and save any extra fields requested.
352 * @param $db Database
353 * @param $res DB Query result
354 * @param $remaining Array of either pageID or ns/title elements (optional).
355 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
356 * @param $processTitles bool Must be provided together with $remaining.
357 * If true, treat $remaining as an array of [ns][title]
358 * If false, treat it as an array of [pageIDs]
359 * @return Array of redirect IDs (only when resolving redirects)
361 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
362 if (!is_null($remaining) && is_null($processTitles))
363 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
365 while ($row = $db->fetchObject($res)) {
367 $pageId = intval($row->page_id);
369 // Remove found page from the list of remaining items
370 if (isset($remaining)) {
371 if ($processTitles)
372 unset ($remaining[$row->page_namespace][$row->page_title]);
373 else
374 unset ($remaining[$pageId]);
377 // Store any extra fields requested by modules
378 $this->processDbRow($row);
380 $db->freeResult($res);
382 if(isset($remaining)) {
383 // Any items left in the $remaining list are added as missing
384 if($processTitles) {
385 // The remaining titles in $remaining are non-existant pages
386 foreach ($remaining as $ns => $dbkeys) {
387 foreach ( $dbkeys as $dbkey => $unused ) {
388 $title = Title :: makeTitle($ns, $dbkey);
389 $this->mMissingTitles[] = $title;
390 $this->mAllPages[$ns][$dbkey] = 0;
391 $this->mTitles[] = $title;
395 else
397 // The remaining pageids do not exist
398 if(empty($this->mMissingPageIDs))
399 $this->mMissingPageIDs = array_keys($remaining);
400 else
401 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
406 private function initFromRevIDs($revids) {
408 if(empty($revids))
409 return;
411 $db = $this->getDB();
412 $pageids = array();
413 $remaining = array_flip($revids);
415 $tables = array('revision');
416 $fields = array('rev_id','rev_page');
417 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
419 // Get pageIDs data from the `page` table
420 $this->profileDBIn();
421 $res = $db->select( $tables, $fields, $where, __METHOD__ );
422 while ( $row = $db->fetchObject( $res ) ) {
423 $revid = intval($row->rev_id);
424 $pageid = intval($row->rev_page);
425 $this->mGoodRevIDs[$revid] = $pageid;
426 $pageids[$pageid] = '';
427 unset($remaining[$revid]);
429 $db->freeResult( $res );
430 $this->profileDBOut();
432 $this->mMissingRevIDs = array_keys($remaining);
434 // Populate all the page information
435 if($this->mResolveRedirects)
436 ApiBase :: dieDebug(__METHOD__, 'revids may not be used with redirect resolution');
437 $this->initFromPageIds(array_keys($pageids));
440 private function resolvePendingRedirects() {
442 if($this->mResolveRedirects) {
443 $db = $this->getDB();
444 $pageFlds = $this->getPageTableFields();
446 // Repeat until all redirects have been resolved
447 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
448 while (!empty ($this->mPendingRedirectIDs)) {
450 // Resolve redirects by querying the pagelinks table, and repeat the process
451 // Create a new linkBatch object for the next pass
452 $linkBatch = $this->getRedirectTargets();
454 if ($linkBatch->isEmpty())
455 break;
457 $set = $linkBatch->constructSet('page', $db);
458 if(false === $set)
459 break;
461 // Get pageIDs data from the `page` table
462 $this->profileDBIn();
463 $res = $db->select('page', $pageFlds, $set, __METHOD__);
464 $this->profileDBOut();
466 // Hack: get the ns:titles stored in array(ns => array(titles)) format
467 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
472 private function getRedirectTargets() {
474 $linkBatch = new LinkBatch();
475 $db = $this->getDB();
477 // find redirect targets for all redirect pages
478 $this->profileDBIn();
479 $res = $db->select('pagelinks', array (
480 'pl_from',
481 'pl_namespace',
482 'pl_title'
483 ), array (
484 'pl_from' => array_keys($this->mPendingRedirectIDs
485 )), __METHOD__);
486 $this->profileDBOut();
488 while ($row = $db->fetchObject($res)) {
490 $plfrom = intval($row->pl_from);
492 // Bug 7304 workaround
493 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
494 // A redirect page may have more than one link.
495 // This code will only use the first link returned.
496 if (isset ($this->mPendingRedirectIDs[$plfrom])) { // remove line when bug 7304 is fixed
498 $titleStrFrom = $this->mPendingRedirectIDs[$plfrom]->getPrefixedText();
499 $titleStrTo = Title :: makeTitle($row->pl_namespace, $row->pl_title)->getPrefixedText();
500 unset ($this->mPendingRedirectIDs[$plfrom]); // remove line when bug 7304 is fixed
502 // Avoid an infinite loop by checking if we have already processed this target
503 if (!isset ($this->mAllPages[$row->pl_namespace][$row->pl_title])) {
504 $linkBatch->add($row->pl_namespace, $row->pl_title);
506 } else {
507 // This redirect page has more than one link.
508 // This is very slow, but safer until bug 7304 is resolved
509 $title = Title :: newFromID($plfrom);
510 $titleStrFrom = $title->getPrefixedText();
512 $article = new Article($title);
513 $text = $article->getContent();
514 $titleTo = Title :: newFromRedirect($text);
515 $titleStrTo = $titleTo->getPrefixedText();
517 if (is_null($titleStrTo))
518 ApiBase :: dieDebug(__METHOD__, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
520 // Avoid an infinite loop by checking if we have already processed this target
521 if (!isset ($this->mAllPages[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
522 $linkBatch->addObj($titleTo);
526 $this->mRedirectTitles[$titleStrFrom] = $titleStrTo;
528 $db->freeResult($res);
530 // All IDs must exist in the page table
531 if (!empty($this->mPendingRedirectIDs[$plfrom]))
532 ApiBase :: dieDebug(__METHOD__, 'Invalid redirect IDs were found');
534 return $linkBatch;
538 * Given an array of title strings, convert them into Title objects.
539 * This method validates access rights for the title,
540 * and appends normalization values to the output.
542 * @return LinkBatch of title objects.
544 private function processTitlesStrArray($titles) {
546 $linkBatch = new LinkBatch();
548 foreach ($titles as $titleString) {
549 $titleObj = Title :: newFromText($titleString);
551 // Validation
552 if (!$titleObj)
553 $this->dieUsage("bad title $titleString", 'invalidtitle');
554 if ($titleObj->getNamespace() < 0)
555 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
556 if (!$titleObj->userCanRead())
557 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
559 $linkBatch->addObj($titleObj);
561 // Make sure we remember the original title that was given to us
562 // This way the caller can correlate new titles with the originally requested,
563 // i.e. namespace is localized or capitalization is different
564 if ($titleString !== $titleObj->getPrefixedText()) {
565 $this->mNormalizedTitles[$titleString] = $titleObj->getPrefixedText();
569 return $linkBatch;
572 protected function getAllowedParams() {
573 return array (
574 'titles' => array (
575 ApiBase :: PARAM_ISMULTI => true
577 'pageids' => array (
578 ApiBase :: PARAM_TYPE => 'integer',
579 ApiBase :: PARAM_ISMULTI => true
581 'revids' => array (
582 ApiBase :: PARAM_TYPE => 'integer',
583 ApiBase :: PARAM_ISMULTI => true
588 protected function getParamDescription() {
589 return array (
590 'titles' => 'A list of titles to work on',
591 'pageids' => 'A list of page IDs to work on',
592 'revids' => 'A list of revision IDs to work on'
596 public function getVersion() {
597 return __CLASS__ . ': $Id$';