* (bug 12584) Don't reset cl_timestamp when auto-updating sort key on move
[mediawiki.git] / includes / api / ApiPageSet.php
blob12da5fa4f584d93911b10f35a36756250e15696d
1 <?php
3 /*
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');
31 /**
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
39 * for all their work.
41 * @addtogroup API
43 class ApiPageSet extends ApiQueryBase {
45 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
46 private $mTitles, $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles;
47 private $mNormalizedTitles, $mInterwikiTitles;
48 private $mResolveRedirects, $mPendingRedirectIDs;
49 private $mGoodRevIDs, $mMissingRevIDs;
50 private $mFakePageId;
52 private $mRequestedPageFields;
54 public function __construct($query, $resolveRedirects = false) {
55 parent :: __construct($query, __CLASS__);
57 $this->mAllPages = array ();
58 $this->mTitles = array();
59 $this->mGoodTitles = array ();
60 $this->mMissingTitles = array ();
61 $this->mMissingPageIDs = array ();
62 $this->mRedirectTitles = array ();
63 $this->mNormalizedTitles = array ();
64 $this->mInterwikiTitles = array ();
65 $this->mGoodRevIDs = array();
66 $this->mMissingRevIDs = array();
68 $this->mRequestedPageFields = array ();
69 $this->mResolveRedirects = $resolveRedirects;
70 if($resolveRedirects)
71 $this->mPendingRedirectIDs = array();
73 $this->mFakePageId = -1;
76 public function isResolvingRedirects() {
77 return $this->mResolveRedirects;
80 public function requestField($fieldName) {
81 $this->mRequestedPageFields[$fieldName] = null;
84 public function getCustomField($fieldName) {
85 return $this->mRequestedPageFields[$fieldName];
88 /**
89 * Get fields that modules have requested from the page table
91 public function getPageTableFields() {
92 // Ensure we get minimum required fields
93 $pageFlds = array (
94 'page_id' => null,
95 'page_namespace' => null,
96 'page_title' => null
99 // only store non-default fields
100 $this->mRequestedPageFields = array_diff_key($this->mRequestedPageFields, $pageFlds);
102 if ($this->mResolveRedirects)
103 $pageFlds['page_is_redirect'] = null;
105 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields);
106 return array_keys($pageFlds);
110 * Returns an array [ns][dbkey] => page_id for all requested titles
111 * page_id is a unique negative number in case title was not found
113 public function getAllTitlesByNamespace() {
114 return $this->mAllPages;
118 * All Title objects provided.
119 * @return array of Title objects
121 public function getTitles() {
122 return $this->mTitles;
126 * Returns the number of unique pages (not revisions) in the set.
128 public function getTitleCount() {
129 return count($this->mTitles);
133 * Title objects that were found in the database.
134 * @return array page_id (int) => Title (obj)
136 public function getGoodTitles() {
137 return $this->mGoodTitles;
141 * Returns the number of found unique pages (not revisions) in the set.
143 public function getGoodTitleCount() {
144 return count($this->mGoodTitles);
148 * Title objects that were NOT found in the database.
149 * The array's index will be negative for each item
150 * @return array of Title objects
152 public function getMissingTitles() {
153 return $this->mMissingTitles;
157 * Page IDs that were not found in the database
158 * @return array of page IDs
160 public function getMissingPageIDs() {
161 return $this->mMissingPageIDs;
165 * Get a list of redirects when doing redirect resolution
166 * @return array prefixed_title (string) => prefixed_title (string)
168 public function getRedirectTitles() {
169 return $this->mRedirectTitles;
173 * Get a list of title normalizations - maps the title given
174 * with its normalized version.
175 * @return array raw_prefixed_title (string) => prefixed_title (string)
177 public function getNormalizedTitles() {
178 return $this->mNormalizedTitles;
182 * Get a list of interwiki titles - maps the title given
183 * with to the interwiki prefix.
184 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
186 public function getInterwikiTitles() {
187 return $this->mInterwikiTitles;
191 * Get the list of revision IDs (requested with revids= parameter)
192 * @return array revID (int) => pageID (int)
194 public function getRevisionIDs() {
195 return $this->mGoodRevIDs;
199 * Revision IDs that were not found in the database
200 * @return array of revision IDs
202 public function getMissingRevisionIDs() {
203 return $this->mMissingRevIDs;
207 * Returns the number of revisions (requested with revids= parameter)
209 public function getRevisionCount() {
210 return count($this->getRevisionIDs());
214 * Populate from the request parameters
216 public function execute() {
217 $this->profileIn();
218 $titles = $pageids = $revids = null;
219 extract($this->extractRequestParams());
221 // Only one of the titles/pageids/revids is allowed at the same time
222 $dataSource = null;
223 if (isset ($titles))
224 $dataSource = 'titles';
225 if (isset ($pageids)) {
226 if (isset ($dataSource))
227 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
228 $dataSource = 'pageids';
230 if (isset ($revids)) {
231 if (isset ($dataSource))
232 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
233 $dataSource = 'revids';
236 switch ($dataSource) {
237 case 'titles' :
238 $this->initFromTitles($titles);
239 break;
240 case 'pageids' :
241 $this->initFromPageIds($pageids);
242 break;
243 case 'revids' :
244 if($this->mResolveRedirects)
245 $this->dieUsage('revids may not be used with redirect resolution', 'params');
246 $this->initFromRevIDs($revids);
247 break;
248 default :
249 // Do nothing - some queries do not need any of the data sources.
250 break;
252 $this->profileOut();
256 * Initialize PageSet from a list of Titles
258 public function populateFromTitles($titles) {
259 $this->profileIn();
260 $this->initFromTitles($titles);
261 $this->profileOut();
265 * Initialize PageSet from a list of Page IDs
267 public function populateFromPageIDs($pageIDs) {
268 $this->profileIn();
269 $this->initFromPageIds($pageIDs);
270 $this->profileOut();
274 * Initialize PageSet from a rowset returned from the database
276 public function populateFromQueryResult($db, $queryResult) {
277 $this->profileIn();
278 $this->initFromQueryResult($db, $queryResult);
279 $this->profileOut();
283 * Initialize PageSet from a list of Revision IDs
285 public function populateFromRevisionIDs($revIDs) {
286 $this->profileIn();
287 $revIDs = array_map('intval', $revIDs); // paranoia
288 $this->initFromRevIDs($revIDs);
289 $this->profileOut();
293 * Extract all requested fields from the row received from the database
295 public function processDbRow($row) {
297 // Store Title object in various data structures
298 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
300 $pageId = intval($row->page_id);
301 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
302 $this->mTitles[] = $title;
304 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
305 $this->mPendingRedirectIDs[$pageId] = $title;
306 } else {
307 $this->mGoodTitles[$pageId] = $title;
310 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
311 $fieldValues[$pageId] = $row-> $fieldName;
314 public function finishPageSetGeneration() {
315 $this->profileIn();
316 $this->resolvePendingRedirects();
317 $this->profileOut();
321 * This method populates internal variables with page information
322 * based on the given array of title strings.
324 * Steps:
325 * #1 For each title, get data from `page` table
326 * #2 If page was not found in the DB, store it as missing
328 * Additionally, when resolving redirects:
329 * #3 If no more redirects left, stop.
330 * #4 For each redirect, get its links from `pagelinks` table.
331 * #5 Substitute the original LinkBatch object with the new list
332 * #6 Repeat from step #1
334 private function initFromTitles($titles) {
336 // Get validated and normalized title objects
337 $linkBatch = $this->processTitlesArray($titles);
338 if($linkBatch->isEmpty())
339 return;
341 $db = $this->getDB();
342 $set = $linkBatch->constructSet('page', $db);
344 // Get pageIDs data from the `page` table
345 $this->profileDBIn();
346 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
347 $this->profileDBOut();
349 // Hack: get the ns:titles stored in array(ns => array(titles)) format
350 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
352 // Resolve any found redirects
353 $this->resolvePendingRedirects();
356 private function initFromPageIds($pageids) {
357 if(empty($pageids))
358 return;
360 $pageids = array_map('intval', $pageids); // paranoia
361 $set = array (
362 'page_id' => $pageids
365 $db = $this->getDB();
367 // Get pageIDs data from the `page` table
368 $this->profileDBIn();
369 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
370 $this->profileDBOut();
372 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
374 // Resolve any found redirects
375 $this->resolvePendingRedirects();
379 * Iterate through the result of the query on 'page' table,
380 * and for each row create and store title object and save any extra fields requested.
381 * @param $db Database
382 * @param $res DB Query result
383 * @param $remaining Array of either pageID or ns/title elements (optional).
384 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
385 * @param $processTitles bool Must be provided together with $remaining.
386 * If true, treat $remaining as an array of [ns][title]
387 * If false, treat it as an array of [pageIDs]
388 * @return Array of redirect IDs (only when resolving redirects)
390 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
391 if (!is_null($remaining) && is_null($processTitles))
392 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
394 while ($row = $db->fetchObject($res)) {
396 $pageId = intval($row->page_id);
398 // Remove found page from the list of remaining items
399 if (isset($remaining)) {
400 if ($processTitles)
401 unset ($remaining[$row->page_namespace][$row->page_title]);
402 else
403 unset ($remaining[$pageId]);
406 // Store any extra fields requested by modules
407 $this->processDbRow($row);
409 $db->freeResult($res);
411 if(isset($remaining)) {
412 // Any items left in the $remaining list are added as missing
413 if($processTitles) {
414 // The remaining titles in $remaining are non-existant pages
415 foreach ($remaining as $ns => $dbkeys) {
416 foreach ( $dbkeys as $dbkey => $unused ) {
417 $title = Title :: makeTitle($ns, $dbkey);
418 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
419 $this->mMissingTitles[$this->mFakePageId] = $title;
420 $this->mFakePageId--;
421 $this->mTitles[] = $title;
425 else
427 // The remaining pageids do not exist
428 if(empty($this->mMissingPageIDs))
429 $this->mMissingPageIDs = array_keys($remaining);
430 else
431 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
436 private function initFromRevIDs($revids) {
438 if(empty($revids))
439 return;
441 $db = $this->getDB();
442 $pageids = array();
443 $remaining = array_flip($revids);
445 $tables = array('revision');
446 $fields = array('rev_id','rev_page');
447 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
449 // Get pageIDs data from the `page` table
450 $this->profileDBIn();
451 $res = $db->select( $tables, $fields, $where, __METHOD__ );
452 while ( $row = $db->fetchObject( $res ) ) {
453 $revid = intval($row->rev_id);
454 $pageid = intval($row->rev_page);
455 $this->mGoodRevIDs[$revid] = $pageid;
456 $pageids[$pageid] = '';
457 unset($remaining[$revid]);
459 $db->freeResult( $res );
460 $this->profileDBOut();
462 $this->mMissingRevIDs = array_keys($remaining);
464 // Populate all the page information
465 if($this->mResolveRedirects)
466 ApiBase :: dieDebug(__METHOD__, 'revids may not be used with redirect resolution');
467 $this->initFromPageIds(array_keys($pageids));
470 private function resolvePendingRedirects() {
472 if($this->mResolveRedirects) {
473 $db = $this->getDB();
474 $pageFlds = $this->getPageTableFields();
476 // Repeat until all redirects have been resolved
477 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
478 while (!empty ($this->mPendingRedirectIDs)) {
480 // Resolve redirects by querying the pagelinks table, and repeat the process
481 // Create a new linkBatch object for the next pass
482 $linkBatch = $this->getRedirectTargets();
484 if ($linkBatch->isEmpty())
485 break;
487 $set = $linkBatch->constructSet('page', $db);
488 if(false === $set)
489 break;
491 // Get pageIDs data from the `page` table
492 $this->profileDBIn();
493 $res = $db->select('page', $pageFlds, $set, __METHOD__);
494 $this->profileDBOut();
496 // Hack: get the ns:titles stored in array(ns => array(titles)) format
497 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
502 private function getRedirectTargets() {
504 $linkBatch = new LinkBatch();
505 $db = $this->getDB();
507 // find redirect targets for all redirect pages
508 $this->profileDBIn();
509 $res = $db->select('pagelinks', array (
510 'pl_from',
511 'pl_namespace',
512 'pl_title'
513 ), array (
514 'pl_from' => array_keys($this->mPendingRedirectIDs
515 )), __METHOD__);
516 $this->profileDBOut();
518 while ($row = $db->fetchObject($res)) {
520 $plfrom = intval($row->pl_from);
522 // Bug 7304 workaround
523 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
524 // A redirect page may have more than one link.
525 // This code will only use the first link returned.
526 if (isset ($this->mPendingRedirectIDs[$plfrom])) { // remove line when bug 7304 is fixed
528 $titleStrFrom = $this->mPendingRedirectIDs[$plfrom]->getPrefixedText();
529 $titleStrTo = Title :: makeTitle($row->pl_namespace, $row->pl_title)->getPrefixedText();
530 unset ($this->mPendingRedirectIDs[$plfrom]); // remove line when bug 7304 is fixed
532 // Avoid an infinite loop by checking if we have already processed this target
533 if (!isset ($this->mAllPages[$row->pl_namespace][$row->pl_title])) {
534 $linkBatch->add($row->pl_namespace, $row->pl_title);
536 } else {
537 // This redirect page has more than one link.
538 // This is very slow, but safer until bug 7304 is resolved
539 $title = Title :: newFromID($plfrom);
540 $titleStrFrom = $title->getPrefixedText();
542 $article = new Article($title);
543 $text = $article->getContent();
544 $titleTo = Title :: newFromRedirect($text);
545 $titleStrTo = $titleTo->getPrefixedText();
547 if (is_null($titleStrTo))
548 ApiBase :: dieDebug(__METHOD__, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
550 // Avoid an infinite loop by checking if we have already processed this target
551 if (!isset ($this->mAllPages[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
552 $linkBatch->addObj($titleTo);
556 $this->mRedirectTitles[$titleStrFrom] = $titleStrTo;
558 $db->freeResult($res);
560 // All IDs must exist in the page table
561 if (!empty($this->mPendingRedirectIDs[$plfrom]))
562 ApiBase :: dieDebug(__METHOD__, 'Invalid redirect IDs were found');
564 return $linkBatch;
568 * Given an array of title strings, convert them into Title objects.
569 * Alternativelly, an array of Title objects may be given.
570 * This method validates access rights for the title,
571 * and appends normalization values to the output.
573 * @return LinkBatch of title objects.
575 private function processTitlesArray($titles) {
577 $linkBatch = new LinkBatch();
579 foreach ($titles as $title) {
581 $titleObj = is_string($title) ? Title :: newFromText($title) : $title;
582 if (!$titleObj)
583 $this->dieUsage("bad title", 'invalidtitle');
585 $iw = $titleObj->getInterwiki();
586 if (!empty($iw)) {
587 // This title is an interwiki link.
588 $this->mInterwikiTitles[$titleObj->getPrefixedText()] = $iw;
589 } else {
591 // Validation
592 if ($titleObj->getNamespace() < 0)
593 $this->dieUsage("No support for special pages has been implemented", 'unsupportednamespace');
595 $linkBatch->addObj($titleObj);
598 // Make sure we remember the original title that was given to us
599 // This way the caller can correlate new titles with the originally requested,
600 // i.e. namespace is localized or capitalization is different
601 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
602 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
606 return $linkBatch;
609 protected function getAllowedParams() {
610 return array (
611 'titles' => array (
612 ApiBase :: PARAM_ISMULTI => true
614 'pageids' => array (
615 ApiBase :: PARAM_TYPE => 'integer',
616 ApiBase :: PARAM_ISMULTI => true
618 'revids' => array (
619 ApiBase :: PARAM_TYPE => 'integer',
620 ApiBase :: PARAM_ISMULTI => true
625 protected function getParamDescription() {
626 return array (
627 'titles' => 'A list of titles to work on',
628 'pageids' => 'A list of page IDs to work on',
629 'revids' => 'A list of revision IDs to work on'
633 public function getVersion() {
634 return __CLASS__ . ': $Id$';