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 $mTitles, $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->mTitles
= array();
46 $this->mGoodTitles
= array ();
47 $this->mMissingTitles
= array ();
48 $this->mMissingPageIDs
= array ();
49 $this->mRedirectTitles
= array ();
50 $this->mNormalizedTitles
= array ();
51 $this->mGoodRevIDs
= array();
52 $this->mMissingRevIDs
= array();
54 $this->mRequestedPageFields
= array ();
55 $this->mResolveRedirects
= $resolveRedirects;
57 $this->mPendingRedirectIDs
= array();
60 public function isResolvingRedirects() {
61 return $this->mResolveRedirects
;
64 public function requestField($fieldName) {
65 $this->mRequestedPageFields
[$fieldName] = null;
68 public function getCustomField($fieldName) {
69 return $this->mRequestedPageFields
[$fieldName];
73 * Get fields that modules have requested from the page table
75 public function getPageTableFields() {
76 // Ensure we get minimum required fields
79 'page_namespace' => null,
83 // only store non-default fields
84 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
86 if ($this->mResolveRedirects
)
87 $pageFlds['page_is_redirect'] = null;
89 return array_keys(array_merge($pageFlds, $this->mRequestedPageFields
));
93 * All Title objects provided.
94 * @return array of Title objects
96 public function getTitles() {
97 return $this->mTitles
;
101 * Returns the number of unique pages (not revisions) in the set.
103 public function getTitleCount() {
104 return count($this->mTitles
);
108 * Title objects that were found in the database.
109 * @return array page_id (int) => Title (obj)
111 public function getGoodTitles() {
112 return $this->mGoodTitles
;
116 * Returns the number of found unique pages (not revisions) in the set.
118 public function getGoodTitleCount() {
119 return count($this->mGoodTitles
);
123 * Title objects that were NOT found in the database.
124 * @return array of Title objects
126 public function getMissingTitles() {
127 return $this->mMissingTitles
;
131 * Page IDs that were not found in the database
132 * @return array of page IDs
134 public function getMissingPageIDs() {
135 return $this->mMissingPageIDs
;
139 * Get a list of redirects when doing redirect resolution
140 * @return array prefixed_title (string) => prefixed_title (string)
142 public function getRedirectTitles() {
143 return $this->mRedirectTitles
;
147 * Get a list of title normalizations - maps the title given
148 * with its normalized version.
149 * @return array raw_prefixed_title (string) => prefixed_title (string)
151 public function getNormalizedTitles() {
152 return $this->mNormalizedTitles
;
156 * Get the list of revision IDs (requested with revids= parameter)
157 * @return array revID (int) => pageID (int)
159 public function getRevisionIDs() {
160 return $this->mGoodRevIDs
;
164 * Revision IDs that were not found in the database
165 * @return array of revision IDs
167 public function getMissingRevisionIDs() {
168 return $this->mMissingRevIDs
;
172 * Returns the number of revisions (requested with revids= parameter)
174 public function getRevisionCount() {
175 return count($this->getRevisionIDs());
179 * Populate from the request parameters
181 public function execute() {
183 $titles = $pageids = $revids = null;
184 extract($this->extractRequestParams());
186 // Only one of the titles/pageids/revids is allowed at the same time
189 $dataSource = 'titles';
190 if (isset ($pageids)) {
191 if (isset ($dataSource))
192 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
193 $dataSource = 'pageids';
195 if (isset ($revids)) {
196 if (isset ($dataSource))
197 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
198 $dataSource = 'revids';
201 switch ($dataSource) {
203 $this->initFromTitles($titles);
206 $this->initFromPageIds($pageids);
209 if($this->mResolveRedirects
)
210 $this->dieUsage('revids may not be used with redirect resolution', 'params');
211 $this->initFromRevIDs($revids);
214 // Do nothing - some queries do not need any of the data sources.
221 * Initialize PageSet from a list of Titles
223 public function populateFromTitles($titles) {
225 $this->initFromTitles($titles);
230 * Initialize PageSet from a list of Page IDs
232 public function populateFromPageIDs($pageIDs) {
234 $pageIDs = array_map('intval', $pageIDs); // paranoia
235 $this->initFromPageIds($pageIDs);
240 * Initialize PageSet from a rowset returned from the database
242 public function populateFromQueryResult($db, $queryResult) {
244 $this->initFromQueryResult($db, $queryResult);
249 * Initialize PageSet from a list of Revision IDs
251 public function populateFromRevisionIDs($revIDs) {
253 $revIDs = array_map('intval', $revIDs); // paranoia
254 $this->initFromRevIDs($revIDs);
259 * Extract all requested fields from the row received from the database
261 public function processDbRow($row) {
263 // Store Title object in various data structures
264 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
266 // skip any pages that user has no rights to read
267 if ($title->userCanRead()) {
269 $pageId = intval($row->page_id
);
270 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
271 $this->mTitles
[] = $title;
273 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
274 $this->mPendingRedirectIDs
[$pageId] = $title;
276 $this->mGoodTitles
[$pageId] = $title;
279 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
280 $fieldValues[$pageId] = $row-> $fieldName;
284 public function finishPageSetGeneration() {
286 $this->resolvePendingRedirects();
291 * This method populates internal variables with page information
292 * based on the given array of title strings.
295 * #1 For each title, get data from `page` table
296 * #2 If page was not found in the DB, store it as missing
298 * Additionally, when resolving redirects:
299 * #3 If no more redirects left, stop.
300 * #4 For each redirect, get its links from `pagelinks` table.
301 * #5 Substitute the original LinkBatch object with the new list
302 * #6 Repeat from step #1
304 private function initFromTitles($titles) {
306 // Get validated and normalized title objects
307 $linkBatch = $this->processTitlesStrArray($titles);
308 if($linkBatch->isEmpty())
311 $db = $this->getDB();
312 $set = $linkBatch->constructSet('page', $db);
314 // Get pageIDs data from the `page` table
315 $this->profileDBIn();
316 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
317 $this->profileDBOut();
319 // Hack: get the ns:titles stored in array(ns => array(titles)) format
320 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
322 // Resolve any found redirects
323 $this->resolvePendingRedirects();
326 private function initFromPageIds($pageids) {
331 'page_id' => $pageids
334 $db = $this->getDB();
336 // Get pageIDs data from the `page` table
337 $this->profileDBIn();
338 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
339 $this->profileDBOut();
341 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
343 // Resolve any found redirects
344 $this->resolvePendingRedirects();
348 * Iterate through the result of the query on 'page' table,
349 * and for each row create and store title object and save any extra fields requested.
350 * @param $db Database
351 * @param $res DB Query result
352 * @param $remaining Array of either pageID or ns/title elements (optional).
353 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
354 * @param $processTitles bool Must be provided together with $remaining.
355 * If true, treat $remaining as an array of [ns][title]
356 * If false, treat it as an array of [pageIDs]
357 * @return Array of redirect IDs (only when resolving redirects)
359 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
360 if (!is_null($remaining) && is_null($processTitles))
361 ApiBase
:: dieDebug(__METHOD__
, 'Missing $processTitles parameter when $remaining is provided');
363 while ($row = $db->fetchObject($res)) {
365 $pageId = intval($row->page_id
);
367 // Remove found page from the list of remaining items
368 if (isset($remaining)) {
370 unset ($remaining[$row->page_namespace
][$row->page_title
]);
372 unset ($remaining[$pageId]);
375 // Store any extra fields requested by modules
376 $this->processDbRow($row);
378 $db->freeResult($res);
380 if(isset($remaining)) {
381 // Any items left in the $remaining list are added as missing
383 // The remaining titles in $remaining are non-existant pages
384 foreach ($remaining as $ns => $dbkeys) {
385 foreach ( $dbkeys as $dbkey => $unused ) {
386 $title = Title
:: makeTitle($ns, $dbkey);
387 $this->mMissingTitles
[] = $title;
388 $this->mAllPages
[$ns][$dbkey] = 0;
389 $this->mTitles
[] = $title;
395 // The remaining pageids do not exist
396 if(empty($this->mMissingPageIDs
))
397 $this->mMissingPageIDs
= array_keys($remaining);
399 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
404 private function initFromRevIDs($revids) {
409 $db = $this->getDB();
411 $remaining = array_flip($revids);
413 $tables = array('revision');
414 $fields = array('rev_id','rev_page');
415 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
417 // Get pageIDs data from the `page` table
418 $this->profileDBIn();
419 $res = $db->select( $tables, $fields, $where, __METHOD__
);
420 while ( $row = $db->fetchObject( $res ) ) {
421 $revid = intval($row->rev_id
);
422 $pageid = intval($row->rev_page
);
423 $this->mGoodRevIDs
[$revid] = $pageid;
424 $pageids[$pageid] = '';
425 unset($remaining[$revid]);
427 $db->freeResult( $res );
428 $this->profileDBOut();
430 $this->mMissingRevIDs
= array_keys($remaining);
432 // Populate all the page information
433 if($this->mResolveRedirects
)
434 ApiBase
:: dieDebug(__METHOD__
, 'revids may not be used with redirect resolution');
435 $this->initFromPageIds(array_keys($pageids));
438 private function resolvePendingRedirects() {
440 if($this->mResolveRedirects
) {
441 $db = $this->getDB();
442 $pageFlds = $this->getPageTableFields();
444 // Repeat until all redirects have been resolved
445 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
446 while (!empty ($this->mPendingRedirectIDs
)) {
448 // Resolve redirects by querying the pagelinks table, and repeat the process
449 // Create a new linkBatch object for the next pass
450 $linkBatch = $this->getRedirectTargets();
452 if ($linkBatch->isEmpty())
455 $set = $linkBatch->constructSet('page', $db);
459 // Get pageIDs data from the `page` table
460 $this->profileDBIn();
461 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
462 $this->profileDBOut();
464 // Hack: get the ns:titles stored in array(ns => array(titles)) format
465 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
470 private function getRedirectTargets() {
472 $linkBatch = new LinkBatch();
473 $db = $this->getDB();
475 // find redirect targets for all redirect pages
476 $this->profileDBIn();
477 $res = $db->select('pagelinks', array (
482 'pl_from' => array_keys($this->mPendingRedirectIDs
484 $this->profileDBOut();
486 while ($row = $db->fetchObject($res)) {
488 $plfrom = intval($row->pl_from
);
490 // Bug 7304 workaround
491 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
492 // A redirect page may have more than one link.
493 // This code will only use the first link returned.
494 if (isset ($this->mPendingRedirectIDs
[$plfrom])) { // remove line when bug 7304 is fixed
496 $titleStrFrom = $this->mPendingRedirectIDs
[$plfrom]->getPrefixedText();
497 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
498 unset ($this->mPendingRedirectIDs
[$plfrom]); // remove line when bug 7304 is fixed
500 // Avoid an infinite loop by checking if we have already processed this target
501 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
502 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
505 // This redirect page has more than one link.
506 // This is very slow, but safer until bug 7304 is resolved
507 $title = Title
:: newFromID($plfrom);
508 $titleStrFrom = $title->getPrefixedText();
510 $article = new Article($title);
511 $text = $article->getContent();
512 $titleTo = Title
:: newFromRedirect($text);
513 $titleStrTo = $titleTo->getPrefixedText();
515 if (is_null($titleStrTo))
516 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
518 // Avoid an infinite loop by checking if we have already processed this target
519 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
520 $linkBatch->addObj($titleTo);
524 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
526 $db->freeResult($res);
528 // All IDs must exist in the page table
529 if (!empty($this->mPendingRedirectIDs
[$plfrom]))
530 ApiBase
:: dieDebug(__METHOD__
, 'Invalid redirect IDs were found');
536 * Given an array of title strings, convert them into Title objects.
537 * This method validates access rights for the title,
538 * and appends normalization values to the output.
540 * @return LinkBatch of title objects.
542 private function processTitlesStrArray($titles) {
544 $linkBatch = new LinkBatch();
546 foreach ($titles as $titleString) {
547 $titleObj = Title
:: newFromText($titleString);
551 $this->dieUsage("bad title $titleString", 'invalidtitle');
552 if ($titleObj->getNamespace() < 0)
553 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
554 if (!$titleObj->userCanRead())
555 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
557 $linkBatch->addObj($titleObj);
559 // Make sure we remember the original title that was given to us
560 // This way the caller can correlate new titles with the originally requested,
561 // i.e. namespace is localized or capitalization is different
562 if ($titleString !== $titleObj->getPrefixedText()) {
563 $this->mNormalizedTitles
[$titleString] = $titleObj->getPrefixedText();
570 protected function getAllowedParams() {
573 ApiBase
:: PARAM_ISMULTI
=> true
576 ApiBase
:: PARAM_TYPE
=> 'integer',
577 ApiBase
:: PARAM_ISMULTI
=> true
580 ApiBase
:: PARAM_TYPE
=> 'integer',
581 ApiBase
:: PARAM_ISMULTI
=> true
586 protected function getParamDescription() {
588 'titles' => 'A list of titles to work on',
589 'pageids' => 'A list of page IDs to work on',
590 'revids' => 'A list of revision IDs to work on'
594 public function getVersion() {
595 return __CLASS__
. ': $Id$';