5 * Created on Sep 24, 2006
7 * API for MediaWiki 1.8+
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
27 if (!defined('MEDIAWIKI')) {
28 // Eclipse helper - will be ignored in production
29 require_once ('ApiQueryBase.php');
32 class ApiPageSet
extends ApiQueryBase
{
34 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
35 private $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles, $mNormalizedTitles;
36 private $mResolveRedirects, $mPendingRedirectIDs;
37 private $mGoodRevIDs, $mMissingRevIDs;
39 private $mRequestedPageFields;
41 public function __construct($query, $resolveRedirects = false) {
42 parent
:: __construct($query, __CLASS__
);
44 $this->mAllPages
= array ();
45 $this->mGoodTitles
= array ();
46 $this->mMissingTitles
= array ();
47 $this->mMissingPageIDs
= array ();
48 $this->mRedirectTitles
= array ();
49 $this->mNormalizedTitles
= array ();
50 $this->mGoodRevIDs
= array();
51 $this->mMissingRevIDs
= array();
53 $this->mRequestedPageFields
= array ();
54 $this->mResolveRedirects
= $resolveRedirects;
56 $this->mPendingRedirectIDs
= array();
59 public function isResolvingRedirects() {
60 return $this->mResolveRedirects
;
63 public function requestField($fieldName) {
64 $this->mRequestedPageFields
[$fieldName] = null;
67 public function getCustomField($fieldName) {
68 return $this->mRequestedPageFields
[$fieldName];
72 * Get fields that modules have requested from the page table
74 public function getPageTableFields() {
75 // Ensure we get minimum required fields
78 'page_namespace' => null,
82 // only store non-default fields
83 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
85 if ($this->mResolveRedirects
)
86 $pageFlds['page_is_redirect'] = null;
88 return array_keys(array_merge($pageFlds, $this->mRequestedPageFields
));
92 * Title objects that were found in the database.
93 * @return array page_id (int) => Title (obj)
95 public function getGoodTitles() {
96 return $this->mGoodTitles
;
100 * Returns the number of unique pages (not revisions) in the set.
102 public function getGoodTitleCount() {
103 return count($this->getGoodTitles());
107 * Title objects that were NOT found in the database.
108 * @return array of Title objects
110 public function getMissingTitles() {
111 return $this->mMissingTitles
;
115 * Page IDs that were not found in the database
116 * @return array of page IDs
118 public function getMissingPageIDs() {
119 return $this->mMissingPageIDs
;
123 * Get a list of redirects when doing redirect resolution
124 * @return array prefixed_title (string) => prefixed_title (string)
126 public function getRedirectTitles() {
127 return $this->mRedirectTitles
;
131 * Get a list of title normalizations - maps the title given
132 * with its normalized version.
133 * @return array raw_prefixed_title (string) => prefixed_title (string)
135 public function getNormalizedTitles() {
136 return $this->mNormalizedTitles
;
140 * Get the list of revision IDs (requested with revids= parameter)
141 * @return array revID (int) => pageID (int)
143 public function getRevisionIDs() {
144 return $this->mGoodRevIDs
;
148 * Revision IDs that were not found in the database
149 * @return array of revision IDs
151 public function getMissingRevisionIDs() {
152 return $this->mMissingRevIDs
;
156 * Returns the number of revisions (requested with revids= parameter)
158 public function getRevisionCount() {
159 return count($this->getRevisionIDs());
163 * Populate from the request parameters
165 public function execute() {
167 $titles = $pageids = $revids = null;
168 extract($this->extractRequestParams());
170 // Only one of the titles/pageids/revids is allowed at the same time
173 $dataSource = 'titles';
174 if (isset ($pageids)) {
175 if (isset ($dataSource))
176 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
177 $dataSource = 'pageids';
179 if (isset ($revids)) {
180 if (isset ($dataSource))
181 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
182 $dataSource = 'revids';
185 switch ($dataSource) {
187 $this->initFromTitles($titles);
190 $this->initFromPageIds($pageids);
193 if($this->mResolveRedirects
)
194 $this->dieUsage('revids may not be used with redirect resolution', 'params');
195 $this->initFromRevIDs($revids);
198 // Do nothing - some queries do not need any of the data sources.
205 * Initialize PageSet from a list of Titles
207 public function populateFromTitles($titles) {
209 $this->initFromTitles($titles);
214 * Initialize PageSet from a list of Page IDs
216 public function populateFromPageIDs($pageIDs) {
218 $pageIDs = array_map('intval', $pageIDs); // paranoia
219 $this->initFromPageIds($pageIDs);
224 * Initialize PageSet from a rowset returned from the database
226 public function populateFromQueryResult($db, $queryResult) {
228 $this->initFromQueryResult($db, $queryResult);
233 * Extract all requested fields from the row received from the database
235 public function processDbRow($row) {
236 $pageId = intval($row->page_id
);
238 // Store Title object in various data structures
239 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
240 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
242 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
243 $this->mPendingRedirectIDs
[$pageId] = $title;
245 $this->mGoodTitles
[$pageId] = $title;
248 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
249 $fieldValues[$pageId] = $row-> $fieldName;
252 public function finishPageSetGeneration() {
254 $this->resolvePendingRedirects();
259 * This method populates internal variables with page information
260 * based on the given array of title strings.
263 * #1 For each title, get data from `page` table
264 * #2 If page was not found in the DB, store it as missing
266 * Additionally, when resolving redirects:
267 * #3 If no more redirects left, stop.
268 * #4 For each redirect, get its links from `pagelinks` table.
269 * #5 Substitute the original LinkBatch object with the new list
270 * #6 Repeat from step #1
272 private function initFromTitles($titles) {
273 $db = $this->getDB();
275 // Get validated and normalized title objects
276 $linkBatch = $this->processTitlesStrArray($titles);
277 if($linkBatch->isEmpty())
280 $set = $linkBatch->constructSet('page', $db);
282 // Get pageIDs data from the `page` table
283 $this->profileDBIn();
284 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
285 $this->profileDBOut();
287 // Hack: get the ns:titles stored in array(ns => array(titles)) format
288 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
290 // Resolve any found redirects
291 $this->resolvePendingRedirects();
294 private function initFromPageIds($pageids) {
298 $db = $this->getDB();
300 'page_id' => $pageids
303 // Get pageIDs data from the `page` table
304 $this->profileDBIn();
305 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
306 $this->profileDBOut();
308 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
310 // Resolve any found redirects
311 $this->resolvePendingRedirects();
315 * Iterate through the result of the query on 'page' table,
316 * and for each row create and store title object and save any extra fields requested.
317 * @param $db Database
318 * @param $res DB Query result
319 * @param $remaining Array of either pageID or ns/title elements (optional).
320 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
321 * @param $processTitles bool Must be provided together with $remaining.
322 * If true, treat $remaining as an array of [ns][title]
323 * If false, treat it as an array of [pageIDs]
324 * @return Array of redirect IDs (only when resolving redirects)
326 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
327 if (!is_null($remaining) && is_null($processTitles))
328 $this->dieDebug('Missing $processTitles parameter when $remaining is provided');
330 while ($row = $db->fetchObject($res)) {
332 $pageId = intval($row->page_id
);
334 // Remove found page from the list of remaining items
335 if (isset($remaining)) {
337 unset ($remaining[$row->page_namespace
][$row->page_title
]);
339 unset ($remaining[$pageId]);
342 // Store any extra fields requested by modules
343 $this->processDbRow($row);
345 $db->freeResult($res);
347 if(isset($remaining)) {
348 // Any items left in the $remaining list are added as missing
350 // The remaining titles in $remaining are non-existant pages
351 foreach ($remaining as $ns => $dbkeys) {
352 foreach ($dbkeys as $dbkey => $nothing) {
353 $this->mMissingTitles
[] = Title
:: makeTitle($ns, $dbkey);
354 $this->mAllPages
[$ns][$dbkey] = 0;
360 // The remaining pageids do not exist
361 if(empty($this->mMissingPageIDs
))
362 $this->mMissingPageIDs
= array_keys($remaining);
364 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
369 private function initFromRevIDs($revids) {
374 $db = $this->getDB();
376 $remaining = array_flip($revids);
378 $tables = array('page', 'revision');
379 $fields = array('rev_id','rev_page');
380 $where = array( 'rev_deleted' => 0, 'rev_id' => $revids );
382 // Get pageIDs data from the `page` table
383 $this->profileDBIn();
384 $res = $db->select( $tables, $fields, $where, __METHOD__
);
385 while ( $row = $db->fetchObject( $res ) ) {
386 $revid = intval($row->rev_id
);
387 $pageid = intval($row->rev_page
);
388 $this->mGoodRevIDs
[$revid] = $pageid;
389 $pageids[$pageid] = '';
390 unset($remaining[$revid]);
392 $db->freeResult( $res );
393 $this->profileDBOut();
395 $this->mMissingRevIDs
= array_keys($remaining);
397 // Populate all the page information
398 if($this->mResolveRedirects
)
399 $this->dieDebug('revids may not be used with redirect resolution');
400 $this->initFromPageIds(array_keys($pageids));
403 private function resolvePendingRedirects() {
405 if($this->mResolveRedirects
) {
406 $db = $this->getDB();
407 $pageFlds = $this->getPageTableFields();
409 // Repeat until all redirects have been resolved
410 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
411 while (!empty ($this->mPendingRedirectIDs
)) {
413 // Resolve redirects by querying the pagelinks table, and repeat the process
414 // Create a new linkBatch object for the next pass
415 $linkBatch = $this->getRedirectTargets();
417 if ($linkBatch->isEmpty())
420 $set = $linkBatch->constructSet('page', $db);
424 // Get pageIDs data from the `page` table
425 $this->profileDBIn();
426 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
427 $this->profileDBOut();
429 // Hack: get the ns:titles stored in array(ns => array(titles)) format
430 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
435 private function getRedirectTargets() {
437 $linkBatch = new LinkBatch();
438 $db = $this->getDB();
440 // find redirect targets for all redirect pages
441 $this->profileDBIn();
442 $res = $db->select('pagelinks', array (
447 'pl_from' => array_keys($this->mPendingRedirectIDs
449 $this->profileDBOut();
451 while ($row = $db->fetchObject($res)) {
453 $plfrom = intval($row->pl_from
);
455 // Bug 7304 workaround
456 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
457 // A redirect page may have more than one link.
458 // This code will only use the first link returned.
459 if (isset ($this->mPendingRedirectIDs
[$plfrom])) { // remove line when bug 7304 is fixed
461 $titleStrFrom = $this->mPendingRedirectIDs
[$plfrom]->getPrefixedText();
462 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
463 unset ($this->mPendingRedirectIDs
[$plfrom]); // remove line when bug 7304 is fixed
465 // Avoid an infinite loop by checking if we have already processed this target
466 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
467 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
470 // This redirect page has more than one link.
471 // This is very slow, but safer until bug 7304 is resolved
472 $title = Title
:: newFromID($plfrom);
473 $titleStrFrom = $title->getPrefixedText();
475 $article = new Article($title);
476 $text = $article->getContent();
477 $titleTo = Title
:: newFromRedirect($text);
478 $titleStrTo = $titleTo->getPrefixedText();
480 if (is_null($titleStrTo))
481 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
483 // Avoid an infinite loop by checking if we have already processed this target
484 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
485 $linkBatch->addObj($titleTo);
489 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
491 $db->freeResult($res);
493 // All IDs must exist in the page table
494 if (!empty($this->mPendingRedirectIDs
[$plfrom]))
495 $this->dieDebug('Invalid redirect IDs were found');
501 * Given an array of title strings, convert them into Title objects.
502 * This method validates access rights for the title,
503 * and appends normalization values to the output.
505 * @return LinkBatch of title objects.
507 private function processTitlesStrArray($titles) {
509 $linkBatch = new LinkBatch();
511 foreach ($titles as $titleString) {
512 $titleObj = Title
:: newFromText($titleString);
516 $this->dieUsage("bad title $titleString", 'invalidtitle');
517 if ($titleObj->getNamespace() < 0)
518 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
519 if (!$titleObj->userCanRead())
520 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
522 $linkBatch->addObj($titleObj);
524 // Make sure we remember the original title that was given to us
525 // This way the caller can correlate new titles with the originally requested,
526 // i.e. namespace is localized or capitalization is different
527 if ($titleString !== $titleObj->getPrefixedText()) {
528 $this->mNormalizedTitles
[$titleString] = $titleObj->getPrefixedText();
535 protected function getAllowedParams() {
538 ApiBase
:: PARAM_ISMULTI
=> true
541 ApiBase
:: PARAM_TYPE
=> 'integer',
542 ApiBase
:: PARAM_ISMULTI
=> true
545 ApiBase
:: PARAM_TYPE
=> 'integer',
546 ApiBase
:: PARAM_ISMULTI
=> true
551 protected function getParamDescription() {
553 'titles' => 'A list of titles to work on',
554 'pageids' => 'A list of page IDs to work on',
555 'revids' => 'A list of revision IDs to work on'
559 public function getVersion() {
560 return __CLASS__
. ': $Id$';