d2f561040a043ed7c5277e8977cf777062524885
4 * Created on Sep 24, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@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');
34 class ApiPageSet
extends ApiQueryBase
{
36 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
37 private $mTitles, $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles, $mNormalizedTitles;
38 private $mResolveRedirects, $mPendingRedirectIDs;
39 private $mGoodRevIDs, $mMissingRevIDs;
41 private $mRequestedPageFields;
43 public function __construct($query, $resolveRedirects = false) {
44 parent
:: __construct($query, __CLASS__
);
46 $this->mAllPages
= array ();
47 $this->mTitles
= array();
48 $this->mGoodTitles
= array ();
49 $this->mMissingTitles
= array ();
50 $this->mMissingPageIDs
= array ();
51 $this->mRedirectTitles
= array ();
52 $this->mNormalizedTitles
= array ();
53 $this->mGoodRevIDs
= array();
54 $this->mMissingRevIDs
= array();
56 $this->mRequestedPageFields
= array ();
57 $this->mResolveRedirects
= $resolveRedirects;
59 $this->mPendingRedirectIDs
= array();
62 public function isResolvingRedirects() {
63 return $this->mResolveRedirects
;
66 public function requestField($fieldName) {
67 $this->mRequestedPageFields
[$fieldName] = null;
70 public function getCustomField($fieldName) {
71 return $this->mRequestedPageFields
[$fieldName];
75 * Get fields that modules have requested from the page table
77 public function getPageTableFields() {
78 // Ensure we get minimum required fields
81 'page_namespace' => null,
85 // only store non-default fields
86 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
88 if ($this->mResolveRedirects
)
89 $pageFlds['page_is_redirect'] = null;
91 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields
);
92 return array_keys($pageFlds);
96 * All Title objects provided.
97 * @return array of Title objects
99 public function getTitles() {
100 return $this->mTitles
;
104 * Returns the number of unique pages (not revisions) in the set.
106 public function getTitleCount() {
107 return count($this->mTitles
);
111 * Title objects that were found in the database.
112 * @return array page_id (int) => Title (obj)
114 public function getGoodTitles() {
115 return $this->mGoodTitles
;
119 * Returns the number of found unique pages (not revisions) in the set.
121 public function getGoodTitleCount() {
122 return count($this->mGoodTitles
);
126 * Title objects that were NOT found in the database.
127 * @return array of Title objects
129 public function getMissingTitles() {
130 return $this->mMissingTitles
;
134 * Page IDs that were not found in the database
135 * @return array of page IDs
137 public function getMissingPageIDs() {
138 return $this->mMissingPageIDs
;
142 * Get a list of redirects when doing redirect resolution
143 * @return array prefixed_title (string) => prefixed_title (string)
145 public function getRedirectTitles() {
146 return $this->mRedirectTitles
;
150 * Get a list of title normalizations - maps the title given
151 * with its normalized version.
152 * @return array raw_prefixed_title (string) => prefixed_title (string)
154 public function getNormalizedTitles() {
155 return $this->mNormalizedTitles
;
159 * Get the list of revision IDs (requested with revids= parameter)
160 * @return array revID (int) => pageID (int)
162 public function getRevisionIDs() {
163 return $this->mGoodRevIDs
;
167 * Revision IDs that were not found in the database
168 * @return array of revision IDs
170 public function getMissingRevisionIDs() {
171 return $this->mMissingRevIDs
;
175 * Returns the number of revisions (requested with revids= parameter)
177 public function getRevisionCount() {
178 return count($this->getRevisionIDs());
182 * Populate from the request parameters
184 public function execute() {
186 $titles = $pageids = $revids = null;
187 extract($this->extractRequestParams());
189 // Only one of the titles/pageids/revids is allowed at the same time
192 $dataSource = 'titles';
193 if (isset ($pageids)) {
194 if (isset ($dataSource))
195 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
196 $dataSource = 'pageids';
198 if (isset ($revids)) {
199 if (isset ($dataSource))
200 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
201 $dataSource = 'revids';
204 switch ($dataSource) {
206 $this->initFromTitles($titles);
209 $this->initFromPageIds($pageids);
212 if($this->mResolveRedirects
)
213 $this->dieUsage('revids may not be used with redirect resolution', 'params');
214 $this->initFromRevIDs($revids);
217 // Do nothing - some queries do not need any of the data sources.
224 * Initialize PageSet from a list of Titles
226 public function populateFromTitles($titles) {
228 $this->initFromTitles($titles);
233 * Initialize PageSet from a list of Page IDs
235 public function populateFromPageIDs($pageIDs) {
237 $pageIDs = array_map('intval', $pageIDs); // paranoia
238 $this->initFromPageIds($pageIDs);
243 * Initialize PageSet from a rowset returned from the database
245 public function populateFromQueryResult($db, $queryResult) {
247 $this->initFromQueryResult($db, $queryResult);
252 * Initialize PageSet from a list of Revision IDs
254 public function populateFromRevisionIDs($revIDs) {
256 $revIDs = array_map('intval', $revIDs); // paranoia
257 $this->initFromRevIDs($revIDs);
262 * Extract all requested fields from the row received from the database
264 public function processDbRow($row) {
266 // Store Title object in various data structures
267 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
269 // skip any pages that user has no rights to read
270 if ($title->userCanRead()) {
272 $pageId = intval($row->page_id
);
273 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
274 $this->mTitles
[] = $title;
276 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
277 $this->mPendingRedirectIDs
[$pageId] = $title;
279 $this->mGoodTitles
[$pageId] = $title;
282 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
283 $fieldValues[$pageId] = $row-> $fieldName;
287 public function finishPageSetGeneration() {
289 $this->resolvePendingRedirects();
294 * This method populates internal variables with page information
295 * based on the given array of title strings.
298 * #1 For each title, get data from `page` table
299 * #2 If page was not found in the DB, store it as missing
301 * Additionally, when resolving redirects:
302 * #3 If no more redirects left, stop.
303 * #4 For each redirect, get its links from `pagelinks` table.
304 * #5 Substitute the original LinkBatch object with the new list
305 * #6 Repeat from step #1
307 private function initFromTitles($titles) {
309 // Get validated and normalized title objects
310 $linkBatch = $this->processTitlesArray($titles);
311 if($linkBatch->isEmpty())
314 $db = $this->getDB();
315 $set = $linkBatch->constructSet('page', $db);
317 // Get pageIDs data from the `page` table
318 $this->profileDBIn();
319 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
320 $this->profileDBOut();
322 // Hack: get the ns:titles stored in array(ns => array(titles)) format
323 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
325 // Resolve any found redirects
326 $this->resolvePendingRedirects();
329 private function initFromPageIds($pageids) {
334 'page_id' => $pageids
337 $db = $this->getDB();
339 // Get pageIDs data from the `page` table
340 $this->profileDBIn();
341 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
342 $this->profileDBOut();
344 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
346 // Resolve any found redirects
347 $this->resolvePendingRedirects();
351 * Iterate through the result of the query on 'page' table,
352 * and for each row create and store title object and save any extra fields requested.
353 * @param $db Database
354 * @param $res DB Query result
355 * @param $remaining Array of either pageID or ns/title elements (optional).
356 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
357 * @param $processTitles bool Must be provided together with $remaining.
358 * If true, treat $remaining as an array of [ns][title]
359 * If false, treat it as an array of [pageIDs]
360 * @return Array of redirect IDs (only when resolving redirects)
362 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
363 if (!is_null($remaining) && is_null($processTitles))
364 ApiBase
:: dieDebug(__METHOD__
, 'Missing $processTitles parameter when $remaining is provided');
366 while ($row = $db->fetchObject($res)) {
368 $pageId = intval($row->page_id
);
370 // Remove found page from the list of remaining items
371 if (isset($remaining)) {
373 unset ($remaining[$row->page_namespace
][$row->page_title
]);
375 unset ($remaining[$pageId]);
378 // Store any extra fields requested by modules
379 $this->processDbRow($row);
381 $db->freeResult($res);
383 if(isset($remaining)) {
384 // Any items left in the $remaining list are added as missing
386 // The remaining titles in $remaining are non-existant pages
387 foreach ($remaining as $ns => $dbkeys) {
388 foreach ( $dbkeys as $dbkey => $unused ) {
389 $title = Title
:: makeTitle($ns, $dbkey);
390 $this->mMissingTitles
[] = $title;
391 $this->mAllPages
[$ns][$dbkey] = 0;
392 $this->mTitles
[] = $title;
398 // The remaining pageids do not exist
399 if(empty($this->mMissingPageIDs
))
400 $this->mMissingPageIDs
= array_keys($remaining);
402 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
407 private function initFromRevIDs($revids) {
412 $db = $this->getDB();
414 $remaining = array_flip($revids);
416 $tables = array('revision');
417 $fields = array('rev_id','rev_page');
418 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
420 // Get pageIDs data from the `page` table
421 $this->profileDBIn();
422 $res = $db->select( $tables, $fields, $where, __METHOD__
);
423 while ( $row = $db->fetchObject( $res ) ) {
424 $revid = intval($row->rev_id
);
425 $pageid = intval($row->rev_page
);
426 $this->mGoodRevIDs
[$revid] = $pageid;
427 $pageids[$pageid] = '';
428 unset($remaining[$revid]);
430 $db->freeResult( $res );
431 $this->profileDBOut();
433 $this->mMissingRevIDs
= array_keys($remaining);
435 // Populate all the page information
436 if($this->mResolveRedirects
)
437 ApiBase
:: dieDebug(__METHOD__
, 'revids may not be used with redirect resolution');
438 $this->initFromPageIds(array_keys($pageids));
441 private function resolvePendingRedirects() {
443 if($this->mResolveRedirects
) {
444 $db = $this->getDB();
445 $pageFlds = $this->getPageTableFields();
447 // Repeat until all redirects have been resolved
448 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
449 while (!empty ($this->mPendingRedirectIDs
)) {
451 // Resolve redirects by querying the pagelinks table, and repeat the process
452 // Create a new linkBatch object for the next pass
453 $linkBatch = $this->getRedirectTargets();
455 if ($linkBatch->isEmpty())
458 $set = $linkBatch->constructSet('page', $db);
462 // Get pageIDs data from the `page` table
463 $this->profileDBIn();
464 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
465 $this->profileDBOut();
467 // Hack: get the ns:titles stored in array(ns => array(titles)) format
468 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
473 private function getRedirectTargets() {
475 $linkBatch = new LinkBatch();
476 $db = $this->getDB();
478 // find redirect targets for all redirect pages
479 $this->profileDBIn();
480 $res = $db->select('pagelinks', array (
485 'pl_from' => array_keys($this->mPendingRedirectIDs
487 $this->profileDBOut();
489 while ($row = $db->fetchObject($res)) {
491 $plfrom = intval($row->pl_from
);
493 // Bug 7304 workaround
494 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
495 // A redirect page may have more than one link.
496 // This code will only use the first link returned.
497 if (isset ($this->mPendingRedirectIDs
[$plfrom])) { // remove line when bug 7304 is fixed
499 $titleStrFrom = $this->mPendingRedirectIDs
[$plfrom]->getPrefixedText();
500 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
501 unset ($this->mPendingRedirectIDs
[$plfrom]); // remove line when bug 7304 is fixed
503 // Avoid an infinite loop by checking if we have already processed this target
504 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
505 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
508 // This redirect page has more than one link.
509 // This is very slow, but safer until bug 7304 is resolved
510 $title = Title
:: newFromID($plfrom);
511 $titleStrFrom = $title->getPrefixedText();
513 $article = new Article($title);
514 $text = $article->getContent();
515 $titleTo = Title
:: newFromRedirect($text);
516 $titleStrTo = $titleTo->getPrefixedText();
518 if (is_null($titleStrTo))
519 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
521 // Avoid an infinite loop by checking if we have already processed this target
522 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
523 $linkBatch->addObj($titleTo);
527 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
529 $db->freeResult($res);
531 // All IDs must exist in the page table
532 if (!empty($this->mPendingRedirectIDs
[$plfrom]))
533 ApiBase
:: dieDebug(__METHOD__
, 'Invalid redirect IDs were found');
539 * Given an array of title strings, convert them into Title objects.
540 * This method validates access rights for the title,
541 * and appends normalization values to the output.
543 * @return LinkBatch of title objects.
545 private function processTitlesArray($titles) {
547 $linkBatch = new LinkBatch();
549 foreach ($titles as $title) {
551 $titleObj = is_string($title) ? Title
:: newFromText($title) : $title;
555 $this->dieUsage("bad title $titleString", 'invalidtitle');
556 if ($titleObj->getNamespace() < 0)
557 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
558 if (!$titleObj->userCanRead())
559 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
561 $linkBatch->addObj($titleObj);
563 // Make sure we remember the original title that was given to us
564 // This way the caller can correlate new titles with the originally requested,
565 // i.e. namespace is localized or capitalization is different
566 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
567 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
574 protected function getAllowedParams() {
577 ApiBase
:: PARAM_ISMULTI
=> true
580 ApiBase
:: PARAM_TYPE
=> 'integer',
581 ApiBase
:: PARAM_ISMULTI
=> true
584 ApiBase
:: PARAM_TYPE
=> 'integer',
585 ApiBase
:: PARAM_ISMULTI
=> true
590 protected function getParamDescription() {
592 'titles' => 'A list of titles to work on',
593 'pageids' => 'A list of page IDs to work on',
594 'revids' => 'A list of revision IDs to work on'
598 public function getVersion() {
599 return __CLASS__
. ': $Id$';