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;
37 private $mRequestedFields;
39 public function __construct($query) {
40 parent
:: __construct($query, __CLASS__
);
42 $this->mAllPages
= array ();
43 $this->mGoodTitles
= array ();
44 $this->mMissingTitles
= array ();
45 $this->mMissingPageIDs
= array ();
46 $this->mRedirectTitles
= array ();
47 $this->mNormalizedTitles
= array ();
49 $this->mRequestedFields
= array ();
52 public function requestField($fieldName) {
53 $this->mRequestedFields
[$fieldName] = null;
56 public function getCustomField($fieldName) {
57 return $this->mRequestedFields
[$fieldName];
61 * Title objects that were found in the database.
62 * @return array page_id (int) => Title (obj)
64 public function getGoodTitles() {
65 return $this->mGoodTitles
;
69 * Title objects that were NOT found in the database.
70 * @return array of Title objects
72 public function getMissingTitles() {
73 return $this->mMissingTitles
;
77 * Page IDs that were not found in the database
78 * @return array of page IDs
80 public function getMissingPageIDs() {
81 return $this->mMissingPageIDs
;
85 * Get a list of redirects when doing redirect resolution
86 * @return array prefixed_title (string) => prefixed_title (string)
88 public function getRedirectTitles() {
89 return $this->mRedirectTitles
;
93 * Get a list of title normalizations - maps the title given
94 * with its normalized version.
95 * @return array raw_prefixed_title (string) => prefixed_title (string)
97 public function getNormalizedTitles() {
98 return $this->mNormalizedTitles
;
102 * Returns the number of unique pages (not revisions) in the set.
104 public function getGoodTitleCount() {
105 return count($this->getGoodTitles());
109 * Get the list of revision IDs (requested with revids= parameter)
111 public function getRevisionIDs() {
112 $this->dieUsage(__METHOD__
. ' is not implemented', 'notimplemented');
116 * Returns the number of revisions (requested with revids= parameter)
118 public function getRevisionCount() {
119 return 0; // TODO: implement
123 * This method populates internal variables with page information
124 * based on the given array of title strings.
127 * #1 For each title, get data from `page` table
128 * #2 If page was not found in the DB, store it as missing
130 * Additionally, when resolving redirects:
131 * #3 If no more redirects left, stop.
132 * #4 For each redirect, get its links from `pagelinks` table.
133 * #5 Substitute the original LinkBatch object with the new list
134 * #6 Repeat from step #1
136 private function populatePages($titles, $pageids, $redirects) {
137 if (!is_null($titles) && !is_null($pageids))
138 ApiBase
:: dieDebug(__METHOD__
, 'bad parameters');
139 $processTitles = !is_null($titles);
141 // Ensure we get minimum required fields
144 'page_namespace' => null,
148 // only store non-default fields
149 $this->mRequestedFields
= array_diff_key($this->mRequestedFields
, $pageFlds);
152 $pageFlds['page_is_redirect'] = null;
154 $pageFlds = array_keys(array_merge($pageFlds, $this->mRequestedFields
));
156 $db = $this->getDB();
158 if ($processTitles) {
160 // Get validated and normalized title objects
161 $linkBatch = $this->processTitlesStrArray($titles);
163 $set = $linkBatch->constructSet('page', $db);
166 'page_id' => $pageids
171 // Repeat until all redirects have been resolved
172 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
175 if ($processTitles) {
176 // Hack: get the ns:titles stored in array(ns => array(titles)) format
177 $remaining = $linkBatch->data
;
179 $remaining = array_flip($pageids); // turn pageids into keys
182 $redirectIds = array ();
185 // Get data about $linkBatch from `page` table
187 $this->profileDBIn();
188 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
189 $this->profileDBOut();
190 while ($row = $db->fetchObject($res)) {
192 $pageId = intval($row->page_id
);
195 unset ($remaining[$row->page_namespace
][$row->page_title
]);
197 unset ($remaining[$pageId]);
199 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
200 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
202 if ($redirects && $row->page_is_redirect
== '1') {
203 $redirectIds[$pageId] = $title;
205 $this->mGoodTitles
[$pageId] = $title;
208 foreach ($this->mRequestedFields
as $fieldName => & $fieldValues) {
209 $fieldValues[$pageId] = $row-> $fieldName;
212 $db->freeResult($res);
214 if ($processTitles) {
215 // The remaining titles in $remaining are non-existant pages
216 foreach ($remaining as $ns => $dbkeys) {
217 foreach ($dbkeys as $dbkey => $nothing) {
218 $this->mMissingTitles
[] = Title
:: makeTitle($ns, $dbkey);
219 $this->mAllPages
[$ns][$dbkey] = 0;
223 // The remaining pageids in $remaining do not exist
224 foreach ($remaining as $pageid => $ignore) {
225 $this->mMissingPageIDs
[] = $pageid;
229 if (!$redirects ||
empty ($redirectIds))
233 // Resolve redirects by querying the pagelinks table, and repeat the process
234 // Create a new linkBatch object for the next pass
236 $linkBatch = $this->resolveRedirectList($redirectIds);
238 // Redirects are always titles
239 $processTitles = true;
241 while (false !== ($set = $linkBatch->constructSet('page', $db)));
244 private function resolveRedirectList($redirectIds) {
246 $linkBatch = new LinkBatch();
247 $db = $this->getDB();
249 // find redirect targets for all redirect pages
250 $this->profileDBIn();
251 $res = $db->select('pagelinks', array (
256 'pl_from' => array_keys($redirectIds
258 $this->profileDBOut();
260 while ($row = $db->fetchObject($res)) {
262 $plfrom = intval($row->pl_from
);
264 // Bug 7304 workaround
265 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
266 // A redirect page may have more than one link.
267 // This code will only use the first link returned.
268 if (isset ($redirectIds[$plfrom])) { // remove line when bug 7304 is fixed
270 $titleStrFrom = $redirectIds[$plfrom]->getPrefixedText();
271 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
272 unset ($redirectIds[$plfrom]); // remove line when bug 7304 is fixed
274 // Avoid an infinite loop by checking if we have already processed this target
275 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
276 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
279 // This redirect page has more than one link.
280 // This is very slow, but safer until bug 7304 is resolved
281 $title = Title
:: newFromID($plfrom);
282 $titleStrFrom = $title->getPrefixedText();
284 $article = new Article($title);
285 $text = $article->getContent();
286 $titleTo = Title
:: newFromRedirect($text);
287 $titleStrTo = $titleTo->getPrefixedText();
289 if (is_null($titleStrTo))
290 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
292 // Avoid an infinite loop by checking if we have already processed this target
293 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
294 $linkBatch->addObj($titleTo);
298 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
300 $db->freeResult($res);
306 * Given an array of title strings, convert them into Title objects.
307 * This method validates access rights for the title,
308 * and appends normalization values to the output.
310 * @return LinkBatch of title objects.
312 private function processTitlesStrArray($titles) {
314 $linkBatch = new LinkBatch();
316 foreach ($titles as $titleString) {
317 $titleObj = Title
:: newFromText($titleString);
321 $this->dieUsage("bad title $titleString", 'invalidtitle');
322 if ($titleObj->getNamespace() < 0)
323 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
324 if (!$titleObj->userCanRead())
325 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
327 $linkBatch->addObj($titleObj);
329 // Make sure we remember the original title that was given to us
330 // This way the caller can correlate new titles with the originally requested,
331 // i.e. namespace is localized or capitalization is different
332 if ($titleString !== $titleObj->getPrefixedText()) {
333 $this->mNormalizedTitles
[$titleString] = $titleObj->getPrefixedText();
340 private function populateRevIDs($revids) {
341 $this->dieUsage(__METHOD__
. ' is not implemented', 'notimplemented');
344 public function execute() {
346 $titles = $pageids = $revids = $redirects = null;
347 extract($this->extractRequestParams());
349 // Only one of the titles/pageids/revids is allowed at the same time
352 $dataSource = 'titles';
353 if (isset ($pageids)) {
354 if (isset ($dataSource))
355 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
356 $dataSource = 'pageids';
358 if (isset ($revids)) {
359 if (isset ($dataSource))
360 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
361 $dataSource = 'revids';
364 switch ($dataSource) {
367 $this->populatePages($titles, $pageids, $redirects);
370 $this->populateRevIDs($revids);
373 // Do nothing - some queries do not need any of the data sources.
380 * This method is used by generators to pass the list of pageIDs internaly
382 public function executeForPageIDs($pageIDs) {
384 $pageIDs = array_map( 'intval', $pageIDs ); // paranoia
385 $this->populatePages(null, $pageIDs, $this->getParameter('redirects'));
389 protected function getAllowedParams() {
392 ApiBase
:: PARAM_ISMULTI
=> true
395 ApiBase
:: PARAM_TYPE
=> 'integer',
396 ApiBase
:: PARAM_ISMULTI
=> true
399 ApiBase
:: PARAM_TYPE
=> 'integer',
400 ApiBase
:: PARAM_ISMULTI
=> true
406 protected function getParamDescription() {
408 'titles' => 'A list of titles to work on',
409 'pageids' => 'A list of page IDs to work on',
410 'revids' => 'A list of revision IDs to work on',
411 'redirects' => 'Automatically resolve redirects'
415 public function getVersion() {
416 return __CLASS__
. ': $Id$';