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 negative when missing
46 private $mTitles, $mGoodTitles, $mMissingTitles, $mInvalidTitles;
47 private $mMissingPageIDs, $mRedirectTitles;
48 private $mNormalizedTitles, $mInterwikiTitles;
49 private $mResolveRedirects, $mPendingRedirectIDs;
50 private $mGoodRevIDs, $mMissingRevIDs;
53 private $mRequestedPageFields;
55 public function __construct($query, $resolveRedirects = false) {
56 parent
:: __construct($query, __CLASS__
);
58 $this->mAllPages
= array ();
59 $this->mTitles
= array();
60 $this->mGoodTitles
= array ();
61 $this->mMissingTitles
= array ();
62 $this->mInvalidTitles
= array ();
63 $this->mMissingPageIDs
= array ();
64 $this->mRedirectTitles
= array ();
65 $this->mNormalizedTitles
= array ();
66 $this->mInterwikiTitles
= array ();
67 $this->mGoodRevIDs
= array();
68 $this->mMissingRevIDs
= array();
70 $this->mRequestedPageFields
= array ();
71 $this->mResolveRedirects
= $resolveRedirects;
73 $this->mPendingRedirectIDs
= array();
75 $this->mFakePageId
= -1;
78 public function isResolvingRedirects() {
79 return $this->mResolveRedirects
;
82 public function requestField($fieldName) {
83 $this->mRequestedPageFields
[$fieldName] = null;
86 public function getCustomField($fieldName) {
87 return $this->mRequestedPageFields
[$fieldName];
91 * Get fields that modules have requested from the page table
93 public function getPageTableFields() {
94 // Ensure we get minimum required fields
97 'page_namespace' => null,
101 // only store non-default fields
102 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
104 if ($this->mResolveRedirects
)
105 $pageFlds['page_is_redirect'] = null;
107 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields
);
108 return array_keys($pageFlds);
112 * Returns an array [ns][dbkey] => page_id for all requested titles.
113 * page_id is a unique negative number in case title was not found.
114 * Invalid titles will also have negative page IDs and will be in namespace 0
116 public function getAllTitlesByNamespace() {
117 return $this->mAllPages
;
121 * All Title objects provided.
122 * @return array of Title objects
124 public function getTitles() {
125 return $this->mTitles
;
129 * Returns the number of unique pages (not revisions) in the set.
131 public function getTitleCount() {
132 return count($this->mTitles
);
136 * Title objects that were found in the database.
137 * @return array page_id (int) => Title (obj)
139 public function getGoodTitles() {
140 return $this->mGoodTitles
;
144 * Returns the number of found unique pages (not revisions) in the set.
146 public function getGoodTitleCount() {
147 return count($this->mGoodTitles
);
151 * Title objects that were NOT found in the database.
152 * The array's index will be negative for each item
153 * @return array of Title objects
155 public function getMissingTitles() {
156 return $this->mMissingTitles
;
160 * Titles that were deemed invalid by Title::newFromText()
161 * The array's index will be unique and negative for each item
162 * @return array of strings (not Title objects)
164 public function getInvalidTitles() {
165 return $this->mInvalidTitles
;
169 * Page IDs that were not found in the database
170 * @return array of page IDs
172 public function getMissingPageIDs() {
173 return $this->mMissingPageIDs
;
177 * Get a list of redirects when doing redirect resolution
178 * @return array prefixed_title (string) => prefixed_title (string)
180 public function getRedirectTitles() {
181 return $this->mRedirectTitles
;
185 * Get a list of title normalizations - maps the title given
186 * with its normalized version.
187 * @return array raw_prefixed_title (string) => prefixed_title (string)
189 public function getNormalizedTitles() {
190 return $this->mNormalizedTitles
;
194 * Get a list of interwiki titles - maps the title given
195 * with to the interwiki prefix.
196 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
198 public function getInterwikiTitles() {
199 return $this->mInterwikiTitles
;
203 * Get the list of revision IDs (requested with revids= parameter)
204 * @return array revID (int) => pageID (int)
206 public function getRevisionIDs() {
207 return $this->mGoodRevIDs
;
211 * Revision IDs that were not found in the database
212 * @return array of revision IDs
214 public function getMissingRevisionIDs() {
215 return $this->mMissingRevIDs
;
219 * Returns the number of revisions (requested with revids= parameter)
221 public function getRevisionCount() {
222 return count($this->getRevisionIDs());
226 * Populate from the request parameters
228 public function execute() {
230 $titles = $pageids = $revids = null;
231 extract($this->extractRequestParams());
233 // Only one of the titles/pageids/revids is allowed at the same time
236 $dataSource = 'titles';
237 if (isset ($pageids)) {
238 if (isset ($dataSource))
239 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
240 $dataSource = 'pageids';
242 if (isset ($revids)) {
243 if (isset ($dataSource))
244 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
245 $dataSource = 'revids';
248 switch ($dataSource) {
250 $this->initFromTitles($titles);
253 $this->initFromPageIds($pageids);
256 if($this->mResolveRedirects
)
257 $this->dieUsage('revids may not be used with redirect resolution', 'params');
258 $this->initFromRevIDs($revids);
261 // Do nothing - some queries do not need any of the data sources.
268 * Initialize PageSet from a list of Titles
270 public function populateFromTitles($titles) {
272 $this->initFromTitles($titles);
277 * Initialize PageSet from a list of Page IDs
279 public function populateFromPageIDs($pageIDs) {
281 $this->initFromPageIds($pageIDs);
286 * Initialize PageSet from a rowset returned from the database
288 public function populateFromQueryResult($db, $queryResult) {
290 $this->initFromQueryResult($db, $queryResult);
295 * Initialize PageSet from a list of Revision IDs
297 public function populateFromRevisionIDs($revIDs) {
299 $revIDs = array_map('intval', $revIDs); // paranoia
300 $this->initFromRevIDs($revIDs);
305 * Extract all requested fields from the row received from the database
307 public function processDbRow($row) {
309 // Store Title object in various data structures
310 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
312 $pageId = intval($row->page_id
);
313 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
314 $this->mTitles
[] = $title;
316 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
317 $this->mPendingRedirectIDs
[$pageId] = $title;
319 $this->mGoodTitles
[$pageId] = $title;
322 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
323 $fieldValues[$pageId] = $row-> $fieldName;
326 public function finishPageSetGeneration() {
328 $this->resolvePendingRedirects();
333 * This method populates internal variables with page information
334 * based on the given array of title strings.
337 * #1 For each title, get data from `page` table
338 * #2 If page was not found in the DB, store it as missing
340 * Additionally, when resolving redirects:
341 * #3 If no more redirects left, stop.
342 * #4 For each redirect, get its links from `pagelinks` table.
343 * #5 Substitute the original LinkBatch object with the new list
344 * #6 Repeat from step #1
346 private function initFromTitles($titles) {
348 // Get validated and normalized title objects
349 $linkBatch = $this->processTitlesArray($titles);
350 if($linkBatch->isEmpty())
353 $db = $this->getDB();
354 $set = $linkBatch->constructSet('page', $db);
356 // Get pageIDs data from the `page` table
357 $this->profileDBIn();
358 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
359 $this->profileDBOut();
361 // Hack: get the ns:titles stored in array(ns => array(titles)) format
362 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
364 // Resolve any found redirects
365 $this->resolvePendingRedirects();
368 private function initFromPageIds($pageids) {
372 $pageids = array_map('intval', $pageids); // paranoia
374 'page_id' => $pageids
377 $db = $this->getDB();
379 // Get pageIDs data from the `page` table
380 $this->profileDBIn();
381 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
382 $this->profileDBOut();
384 $remaining = array_flip($pageids);
385 $this->initFromQueryResult($db, $res, $remaining, false); // process PageIDs
387 // Resolve any found redirects
388 $this->resolvePendingRedirects();
392 * Iterate through the result of the query on 'page' table,
393 * and for each row create and store title object and save any extra fields requested.
394 * @param $db Database
395 * @param $res DB Query result
396 * @param $remaining Array of either pageID or ns/title elements (optional).
397 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
398 * @param $processTitles bool Must be provided together with $remaining.
399 * If true, treat $remaining as an array of [ns][title]
400 * If false, treat it as an array of [pageIDs]
401 * @return Array of redirect IDs (only when resolving redirects)
403 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
404 if (!is_null($remaining) && is_null($processTitles))
405 ApiBase
:: dieDebug(__METHOD__
, 'Missing $processTitles parameter when $remaining is provided');
407 while ($row = $db->fetchObject($res)) {
409 $pageId = intval($row->page_id
);
411 // Remove found page from the list of remaining items
412 if (isset($remaining)) {
414 unset ($remaining[$row->page_namespace
][$row->page_title
]);
416 unset ($remaining[$pageId]);
419 // Store any extra fields requested by modules
420 $this->processDbRow($row);
422 $db->freeResult($res);
424 if(isset($remaining)) {
425 // Any items left in the $remaining list are added as missing
427 // The remaining titles in $remaining are non-existant pages
428 foreach ($remaining as $ns => $dbkeys) {
429 foreach ( $dbkeys as $dbkey => $unused ) {
430 $title = Title
:: makeTitle($ns, $dbkey);
431 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
432 $this->mMissingTitles
[$this->mFakePageId
] = $title;
433 $this->mFakePageId
--;
434 $this->mTitles
[] = $title;
440 // The remaining pageids do not exist
441 if(empty($this->mMissingPageIDs
))
442 $this->mMissingPageIDs
= array_keys($remaining);
444 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
449 private function initFromRevIDs($revids) {
454 $db = $this->getDB();
456 $remaining = array_flip($revids);
458 $tables = array('revision');
459 $fields = array('rev_id','rev_page');
460 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
462 // Get pageIDs data from the `page` table
463 $this->profileDBIn();
464 $res = $db->select( $tables, $fields, $where, __METHOD__
);
465 while ( $row = $db->fetchObject( $res ) ) {
466 $revid = intval($row->rev_id
);
467 $pageid = intval($row->rev_page
);
468 $this->mGoodRevIDs
[$revid] = $pageid;
469 $pageids[$pageid] = '';
470 unset($remaining[$revid]);
472 $db->freeResult( $res );
473 $this->profileDBOut();
475 $this->mMissingRevIDs
= array_keys($remaining);
477 // Populate all the page information
478 if($this->mResolveRedirects
)
479 ApiBase
:: dieDebug(__METHOD__
, 'revids may not be used with redirect resolution');
480 $this->initFromPageIds(array_keys($pageids));
483 private function resolvePendingRedirects() {
485 if($this->mResolveRedirects
) {
486 $db = $this->getDB();
487 $pageFlds = $this->getPageTableFields();
489 // Repeat until all redirects have been resolved
490 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
491 while (!empty ($this->mPendingRedirectIDs
)) {
493 // Resolve redirects by querying the pagelinks table, and repeat the process
494 // Create a new linkBatch object for the next pass
495 $linkBatch = $this->getRedirectTargets();
497 if ($linkBatch->isEmpty())
500 $set = $linkBatch->constructSet('page', $db);
504 // Get pageIDs data from the `page` table
505 $this->profileDBIn();
506 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
507 $this->profileDBOut();
509 // Hack: get the ns:titles stored in array(ns => array(titles)) format
510 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
515 private function getRedirectTargets() {
516 $lb = new LinkBatch();
517 $db = $this->getDB();
519 $this->profileDBIn();
520 $res = $db->select('redirect', array(
524 ), array('rd_from' => array_keys($this->mPendingRedirectIDs
)),
527 $this->profileDBOut();
529 while($row = $db->fetchObject($res))
531 $rdfrom = intval($row->rd_from
);
532 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
533 $to = Title
::makeTitle($row->rd_namespace
, $row->rd_title
)->getPrefixedText();
534 unset($this->mPendingRedirectIDs
[$rdfrom]);
535 if(!isset($this->mAllPages
[$row->rd_namespace
][$row->rd_title
]))
536 $lb->add($row->rd_namespace
, $row->rd_title
);
537 $this->mRedirectTitles
[$from] = $to;
539 $db->freeResult($res);
540 if(!empty($this->mPendingRedirectIDs
))
542 # We found pages that aren't in the redirect table
544 foreach($this->mPendingRedirectIDs
as $id => $title)
546 $article = new Article($title);
547 $rt = $article->insertRedirect();
549 # What the hell. Let's just ignore this
552 $this->mRedirectTitles
[$title->getPrefixedText()] = $rt->getPrefixedText();
553 unset($this->mPendingRedirectIDs
[$id]);
560 * Given an array of title strings, convert them into Title objects.
561 * Alternativelly, an array of Title objects may be given.
562 * This method validates access rights for the title,
563 * and appends normalization values to the output.
565 * @return LinkBatch of title objects.
567 private function processTitlesArray($titles) {
569 $linkBatch = new LinkBatch();
571 foreach ($titles as $title) {
573 $titleObj = is_string($title) ? Title
:: newFromText($title) : $title;
576 # Handle invalid titles gracefully
577 $this->mAllpages
[0][$title] = $this->mFakePageId
;
578 $this->mInvalidTitles
[$this->mFakePageId
] = $title;
579 $this->mFakePageId
--;
580 continue; // There's nothing else we can do
582 $iw = $titleObj->getInterwiki();
584 // This title is an interwiki link.
585 $this->mInterwikiTitles
[$titleObj->getPrefixedText()] = $iw;
589 if ($titleObj->getNamespace() < 0)
590 $this->dieUsage("No support for special pages has been implemented", 'unsupportednamespace');
592 $linkBatch->addObj($titleObj);
595 // Make sure we remember the original title that was given to us
596 // This way the caller can correlate new titles with the originally requested,
597 // i.e. namespace is localized or capitalization is different
598 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
599 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
606 protected function getAllowedParams() {
609 ApiBase
:: PARAM_ISMULTI
=> true
612 ApiBase
:: PARAM_TYPE
=> 'integer',
613 ApiBase
:: PARAM_ISMULTI
=> true
616 ApiBase
:: PARAM_TYPE
=> 'integer',
617 ApiBase
:: PARAM_ISMULTI
=> true
622 protected function getParamDescription() {
624 'titles' => 'A list of titles to work on',
625 'pageids' => 'A list of page IDs to work on',
626 'revids' => 'A list of revision IDs to work on'
630 public function getVersion() {
631 return __CLASS__
. ': $Id$';