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;
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->mGoodRevIDs
= array();
63 $this->mMissingRevIDs
= array();
65 $this->mRequestedPageFields
= array ();
66 $this->mResolveRedirects
= $resolveRedirects;
68 $this->mPendingRedirectIDs
= array();
71 public function isResolvingRedirects() {
72 return $this->mResolveRedirects
;
75 public function requestField($fieldName) {
76 $this->mRequestedPageFields
[$fieldName] = null;
79 public function getCustomField($fieldName) {
80 return $this->mRequestedPageFields
[$fieldName];
84 * Get fields that modules have requested from the page table
86 public function getPageTableFields() {
87 // Ensure we get minimum required fields
90 'page_namespace' => null,
94 // only store non-default fields
95 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
97 if ($this->mResolveRedirects
)
98 $pageFlds['page_is_redirect'] = null;
100 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields
);
101 return array_keys($pageFlds);
105 * All Title objects provided.
106 * @return array of Title objects
108 public function getTitles() {
109 return $this->mTitles
;
113 * Returns the number of unique pages (not revisions) in the set.
115 public function getTitleCount() {
116 return count($this->mTitles
);
120 * Title objects that were found in the database.
121 * @return array page_id (int) => Title (obj)
123 public function getGoodTitles() {
124 return $this->mGoodTitles
;
128 * Returns the number of found unique pages (not revisions) in the set.
130 public function getGoodTitleCount() {
131 return count($this->mGoodTitles
);
135 * Title objects that were NOT found in the database.
136 * @return array of Title objects
138 public function getMissingTitles() {
139 return $this->mMissingTitles
;
143 * Page IDs that were not found in the database
144 * @return array of page IDs
146 public function getMissingPageIDs() {
147 return $this->mMissingPageIDs
;
151 * Get a list of redirects when doing redirect resolution
152 * @return array prefixed_title (string) => prefixed_title (string)
154 public function getRedirectTitles() {
155 return $this->mRedirectTitles
;
159 * Get a list of title normalizations - maps the title given
160 * with its normalized version.
161 * @return array raw_prefixed_title (string) => prefixed_title (string)
163 public function getNormalizedTitles() {
164 return $this->mNormalizedTitles
;
168 * Get the list of revision IDs (requested with revids= parameter)
169 * @return array revID (int) => pageID (int)
171 public function getRevisionIDs() {
172 return $this->mGoodRevIDs
;
176 * Revision IDs that were not found in the database
177 * @return array of revision IDs
179 public function getMissingRevisionIDs() {
180 return $this->mMissingRevIDs
;
184 * Returns the number of revisions (requested with revids= parameter)
186 public function getRevisionCount() {
187 return count($this->getRevisionIDs());
191 * Populate from the request parameters
193 public function execute() {
195 $titles = $pageids = $revids = null;
196 extract($this->extractRequestParams());
198 // Only one of the titles/pageids/revids is allowed at the same time
201 $dataSource = 'titles';
202 if (isset ($pageids)) {
203 if (isset ($dataSource))
204 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
205 $dataSource = 'pageids';
207 if (isset ($revids)) {
208 if (isset ($dataSource))
209 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
210 $dataSource = 'revids';
213 switch ($dataSource) {
215 $this->initFromTitles($titles);
218 $this->initFromPageIds($pageids);
221 if($this->mResolveRedirects
)
222 $this->dieUsage('revids may not be used with redirect resolution', 'params');
223 $this->initFromRevIDs($revids);
226 // Do nothing - some queries do not need any of the data sources.
233 * Initialize PageSet from a list of Titles
235 public function populateFromTitles($titles) {
237 $this->initFromTitles($titles);
242 * Initialize PageSet from a list of Page IDs
244 public function populateFromPageIDs($pageIDs) {
246 $pageIDs = array_map('intval', $pageIDs); // paranoia
247 $this->initFromPageIds($pageIDs);
252 * Initialize PageSet from a rowset returned from the database
254 public function populateFromQueryResult($db, $queryResult) {
256 $this->initFromQueryResult($db, $queryResult);
261 * Initialize PageSet from a list of Revision IDs
263 public function populateFromRevisionIDs($revIDs) {
265 $revIDs = array_map('intval', $revIDs); // paranoia
266 $this->initFromRevIDs($revIDs);
271 * Extract all requested fields from the row received from the database
273 public function processDbRow($row) {
275 // Store Title object in various data structures
276 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
278 // skip any pages that user has no rights to read
279 if ($title->userCanRead()) {
281 $pageId = intval($row->page_id
);
282 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
283 $this->mTitles
[] = $title;
285 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
286 $this->mPendingRedirectIDs
[$pageId] = $title;
288 $this->mGoodTitles
[$pageId] = $title;
291 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
292 $fieldValues[$pageId] = $row-> $fieldName;
296 public function finishPageSetGeneration() {
298 $this->resolvePendingRedirects();
303 * This method populates internal variables with page information
304 * based on the given array of title strings.
307 * #1 For each title, get data from `page` table
308 * #2 If page was not found in the DB, store it as missing
310 * Additionally, when resolving redirects:
311 * #3 If no more redirects left, stop.
312 * #4 For each redirect, get its links from `pagelinks` table.
313 * #5 Substitute the original LinkBatch object with the new list
314 * #6 Repeat from step #1
316 private function initFromTitles($titles) {
318 // Get validated and normalized title objects
319 $linkBatch = $this->processTitlesArray($titles);
320 if($linkBatch->isEmpty())
323 $db = $this->getDB();
324 $set = $linkBatch->constructSet('page', $db);
326 // Get pageIDs data from the `page` table
327 $this->profileDBIn();
328 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
329 $this->profileDBOut();
331 // Hack: get the ns:titles stored in array(ns => array(titles)) format
332 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
334 // Resolve any found redirects
335 $this->resolvePendingRedirects();
338 private function initFromPageIds($pageids) {
343 'page_id' => $pageids
346 $db = $this->getDB();
348 // Get pageIDs data from the `page` table
349 $this->profileDBIn();
350 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
351 $this->profileDBOut();
353 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
355 // Resolve any found redirects
356 $this->resolvePendingRedirects();
360 * Iterate through the result of the query on 'page' table,
361 * and for each row create and store title object and save any extra fields requested.
362 * @param $db Database
363 * @param $res DB Query result
364 * @param $remaining Array of either pageID or ns/title elements (optional).
365 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
366 * @param $processTitles bool Must be provided together with $remaining.
367 * If true, treat $remaining as an array of [ns][title]
368 * If false, treat it as an array of [pageIDs]
369 * @return Array of redirect IDs (only when resolving redirects)
371 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
372 if (!is_null($remaining) && is_null($processTitles))
373 ApiBase
:: dieDebug(__METHOD__
, 'Missing $processTitles parameter when $remaining is provided');
375 while ($row = $db->fetchObject($res)) {
377 $pageId = intval($row->page_id
);
379 // Remove found page from the list of remaining items
380 if (isset($remaining)) {
382 unset ($remaining[$row->page_namespace
][$row->page_title
]);
384 unset ($remaining[$pageId]);
387 // Store any extra fields requested by modules
388 $this->processDbRow($row);
390 $db->freeResult($res);
392 if(isset($remaining)) {
393 // Any items left in the $remaining list are added as missing
395 // The remaining titles in $remaining are non-existant pages
396 foreach ($remaining as $ns => $dbkeys) {
397 foreach ( $dbkeys as $dbkey => $unused ) {
398 $title = Title
:: makeTitle($ns, $dbkey);
399 $this->mMissingTitles
[] = $title;
400 $this->mAllPages
[$ns][$dbkey] = 0;
401 $this->mTitles
[] = $title;
407 // The remaining pageids do not exist
408 if(empty($this->mMissingPageIDs
))
409 $this->mMissingPageIDs
= array_keys($remaining);
411 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
416 private function initFromRevIDs($revids) {
421 $db = $this->getDB();
423 $remaining = array_flip($revids);
425 $tables = array('revision');
426 $fields = array('rev_id','rev_page');
427 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
429 // Get pageIDs data from the `page` table
430 $this->profileDBIn();
431 $res = $db->select( $tables, $fields, $where, __METHOD__
);
432 while ( $row = $db->fetchObject( $res ) ) {
433 $revid = intval($row->rev_id
);
434 $pageid = intval($row->rev_page
);
435 $this->mGoodRevIDs
[$revid] = $pageid;
436 $pageids[$pageid] = '';
437 unset($remaining[$revid]);
439 $db->freeResult( $res );
440 $this->profileDBOut();
442 $this->mMissingRevIDs
= array_keys($remaining);
444 // Populate all the page information
445 if($this->mResolveRedirects
)
446 ApiBase
:: dieDebug(__METHOD__
, 'revids may not be used with redirect resolution');
447 $this->initFromPageIds(array_keys($pageids));
450 private function resolvePendingRedirects() {
452 if($this->mResolveRedirects
) {
453 $db = $this->getDB();
454 $pageFlds = $this->getPageTableFields();
456 // Repeat until all redirects have been resolved
457 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
458 while (!empty ($this->mPendingRedirectIDs
)) {
460 // Resolve redirects by querying the pagelinks table, and repeat the process
461 // Create a new linkBatch object for the next pass
462 $linkBatch = $this->getRedirectTargets();
464 if ($linkBatch->isEmpty())
467 $set = $linkBatch->constructSet('page', $db);
471 // Get pageIDs data from the `page` table
472 $this->profileDBIn();
473 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
474 $this->profileDBOut();
476 // Hack: get the ns:titles stored in array(ns => array(titles)) format
477 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
482 private function getRedirectTargets() {
484 $linkBatch = new LinkBatch();
485 $db = $this->getDB();
487 // find redirect targets for all redirect pages
488 $this->profileDBIn();
489 $res = $db->select('pagelinks', array (
494 'pl_from' => array_keys($this->mPendingRedirectIDs
496 $this->profileDBOut();
498 while ($row = $db->fetchObject($res)) {
500 $plfrom = intval($row->pl_from
);
502 // Bug 7304 workaround
503 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
504 // A redirect page may have more than one link.
505 // This code will only use the first link returned.
506 if (isset ($this->mPendingRedirectIDs
[$plfrom])) { // remove line when bug 7304 is fixed
508 $titleStrFrom = $this->mPendingRedirectIDs
[$plfrom]->getPrefixedText();
509 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
510 unset ($this->mPendingRedirectIDs
[$plfrom]); // remove line when bug 7304 is fixed
512 // Avoid an infinite loop by checking if we have already processed this target
513 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
514 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
517 // This redirect page has more than one link.
518 // This is very slow, but safer until bug 7304 is resolved
519 $title = Title
:: newFromID($plfrom);
520 $titleStrFrom = $title->getPrefixedText();
522 $article = new Article($title);
523 $text = $article->getContent();
524 $titleTo = Title
:: newFromRedirect($text);
525 $titleStrTo = $titleTo->getPrefixedText();
527 if (is_null($titleStrTo))
528 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
530 // Avoid an infinite loop by checking if we have already processed this target
531 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
532 $linkBatch->addObj($titleTo);
536 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
538 $db->freeResult($res);
540 // All IDs must exist in the page table
541 if (!empty($this->mPendingRedirectIDs
[$plfrom]))
542 ApiBase
:: dieDebug(__METHOD__
, 'Invalid redirect IDs were found');
548 * Given an array of title strings, convert them into Title objects.
549 * This method validates access rights for the title,
550 * and appends normalization values to the output.
552 * @return LinkBatch of title objects.
554 private function processTitlesArray($titles) {
556 $linkBatch = new LinkBatch();
558 foreach ($titles as $title) {
560 $titleObj = is_string($title) ? Title
:: newFromText($title) : $title;
564 $this->dieUsage("bad title $titleString", 'invalidtitle');
565 if ($titleObj->getNamespace() < 0)
566 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
567 if (!$titleObj->userCanRead())
568 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
570 $linkBatch->addObj($titleObj);
572 // Make sure we remember the original title that was given to us
573 // This way the caller can correlate new titles with the originally requested,
574 // i.e. namespace is localized or capitalization is different
575 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
576 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
583 protected function getAllowedParams() {
586 ApiBase
:: PARAM_ISMULTI
=> true
589 ApiBase
:: PARAM_TYPE
=> 'integer',
590 ApiBase
:: PARAM_ISMULTI
=> true
593 ApiBase
:: PARAM_TYPE
=> 'integer',
594 ApiBase
:: PARAM_ISMULTI
=> true
599 protected function getParamDescription() {
601 'titles' => 'A list of titles to work on',
602 'pageids' => 'A list of page IDs to work on',
603 'revids' => 'A list of revision IDs to work on'
607 public function getVersion() {
608 return __CLASS__
. ': $Id$';