* API: implemented generator function
[lhc/web/wiklou.git] / includes / api / ApiPageSet.php
1 <?php
2
3
4 /*
5 * Created on Sep 24, 2006
6 *
7 * API for MediaWiki 1.8+
8 *
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
10 *
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.
15 *
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.
20 *
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
25 */
26
27 if (!defined('MEDIAWIKI')) {
28 // Eclipse helper - will be ignored in production
29 require_once ('ApiQueryBase.php');
30 }
31
32 class ApiPageSet extends ApiQueryBase {
33
34 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
35 private $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles, $mNormalizedTitles;
36
37 private $mRequestedFields;
38
39 public function __construct($query) {
40 parent :: __construct($query, __CLASS__);
41
42 $this->mAllPages = array ();
43 $this->mGoodTitles = array ();
44 $this->mMissingTitles = array ();
45 $this->mMissingPageIDs = array ();
46 $this->mRedirectTitles = array ();
47 $this->mNormalizedTitles = array ();
48
49 $this->mRequestedFields = array ();
50 }
51
52 public function requestField($fieldName) {
53 $this->mRequestedFields[$fieldName] = null;
54 }
55
56 public function getCustomField($fieldName) {
57 return $this->mRequestedFields[$fieldName];
58 }
59
60 /**
61 * Title objects that were found in the database.
62 * @return array page_id (int) => Title (obj)
63 */
64 public function getGoodTitles() {
65 return $this->mGoodTitles;
66 }
67
68 /**
69 * Title objects that were NOT found in the database.
70 * @return array of Title objects
71 */
72 public function getMissingTitles() {
73 return $this->mMissingTitles;
74 }
75
76 /**
77 * Page IDs that were not found in the database
78 * @return array of page IDs
79 */
80 public function getMissingPageIDs() {
81 return $this->mMissingPageIDs;
82 }
83
84 /**
85 * Get a list of redirects when doing redirect resolution
86 * @return array prefixed_title (string) => prefixed_title (string)
87 */
88 public function getRedirectTitles() {
89 return $this->mRedirectTitles;
90 }
91
92 /**
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)
96 */
97 public function getNormalizedTitles() {
98 return $this->mNormalizedTitles;
99 }
100
101 /**
102 * Returns the number of unique pages (not revisions) in the set.
103 */
104 public function getGoodTitleCount() {
105 return count($this->getGoodTitles());
106 }
107
108 /**
109 * Get the list of revision IDs (requested with revids= parameter)
110 */
111 public function getRevisionIDs() {
112 $this->dieUsage(__METHOD__ . ' is not implemented', 'notimplemented');
113 }
114
115 /**
116 * Returns the number of revisions (requested with revids= parameter)
117 */
118 public function getRevisionCount() {
119 return 0; // TODO: implement
120 }
121
122 /**
123 * This method populates internal variables with page information
124 * based on the given array of title strings.
125 *
126 * Steps:
127 * #1 For each title, get data from `page` table
128 * #2 If page was not found in the DB, store it as missing
129 *
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
135 */
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);
140
141 // Ensure we get minimum required fields
142 $pageFlds = array (
143 'page_id' => null,
144 'page_namespace' => null,
145 'page_title' => null
146 );
147
148 // only store non-default fields
149 $this->mRequestedFields = array_diff_key($this->mRequestedFields, $pageFlds);
150
151 if ($redirects)
152 $pageFlds['page_is_redirect'] = null;
153
154 $pageFlds = array_keys(array_merge($pageFlds, $this->mRequestedFields));
155
156 $db = $this->getDB();
157
158 if ($processTitles) {
159
160 // Get validated and normalized title objects
161 $linkBatch = $this->processTitlesStrArray($titles);
162
163 $set = $linkBatch->constructSet('page', $db);
164 } else {
165 $set = array (
166 'page_id' => $pageids
167 );
168 }
169
170 //
171 // Repeat until all redirects have been resolved
172 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
173 //
174 do {
175 if ($processTitles) {
176 // Hack: get the ns:titles stored in array(ns => array(titles)) format
177 $remaining = $linkBatch->data;
178 } else {
179 $remaining = array_flip($pageids); // turn pageids into keys
180 }
181
182 $redirectIds = array ();
183
184 //
185 // Get data about $linkBatch from `page` table
186 //
187 $this->profileDBIn();
188 $res = $db->select('page', $pageFlds, $set, __METHOD__);
189 $this->profileDBOut();
190 while ($row = $db->fetchObject($res)) {
191
192 $pageId = intval($row->page_id);
193
194 if ($processTitles)
195 unset ($remaining[$row->page_namespace][$row->page_title]);
196 else
197 unset ($remaining[$pageId]);
198
199 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
200 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
201
202 if ($redirects && $row->page_is_redirect == '1') {
203 $redirectIds[$pageId] = $title;
204 } else {
205 $this->mGoodTitles[$pageId] = $title;
206 }
207
208 foreach ($this->mRequestedFields as $fieldName => & $fieldValues) {
209 $fieldValues[$pageId] = $row-> $fieldName;
210 }
211 }
212 $db->freeResult($res);
213
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;
220 }
221 }
222 } else {
223 // The remaining pageids in $remaining do not exist
224 foreach ($remaining as $pageid => $ignore) {
225 $this->mMissingPageIDs[] = $pageid;
226 }
227 }
228
229 if (!$redirects || empty ($redirectIds))
230 break;
231
232 //
233 // Resolve redirects by querying the pagelinks table, and repeat the process
234 // Create a new linkBatch object for the next pass
235 //
236 $linkBatch = $this->resolveRedirectList($redirectIds);
237
238 // Redirects are always titles
239 $processTitles = true;
240 }
241 while (false !== ($set = $linkBatch->constructSet('page', $db)));
242 }
243
244 private function resolveRedirectList($redirectIds) {
245
246 $linkBatch = new LinkBatch();
247 $db = $this->getDB();
248
249 // find redirect targets for all redirect pages
250 $this->profileDBIn();
251 $res = $db->select('pagelinks', array (
252 'pl_from',
253 'pl_namespace',
254 'pl_title'
255 ), array (
256 'pl_from' => array_keys($redirectIds
257 )), __METHOD__);
258 $this->profileDBOut();
259
260 while ($row = $db->fetchObject($res)) {
261
262 $plfrom = intval($row->pl_from);
263
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
269
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
273
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);
277 }
278 } else {
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();
283
284 $article = new Article($title);
285 $text = $article->getContent();
286 $titleTo = Title :: newFromRedirect($text);
287 $titleStrTo = $titleTo->getPrefixedText();
288
289 if (is_null($titleStrTo))
290 ApiBase :: dieDebug(__METHOD__, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
291
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);
295 }
296 }
297
298 $this->mRedirectTitles[$titleStrFrom] = $titleStrTo;
299 }
300 $db->freeResult($res);
301
302 return $linkBatch;
303 }
304
305 /**
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.
309 *
310 * @return LinkBatch of title objects.
311 */
312 private function processTitlesStrArray($titles) {
313
314 $linkBatch = new LinkBatch();
315
316 foreach ($titles as $titleString) {
317 $titleObj = Title :: newFromText($titleString);
318
319 // Validation
320 if (!$titleObj)
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');
326
327 $linkBatch->addObj($titleObj);
328
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();
334 }
335 }
336
337 return $linkBatch;
338 }
339
340 private function populateRevIDs($revids) {
341 $this->dieUsage(__METHOD__ . ' is not implemented', 'notimplemented');
342 }
343
344 public function execute() {
345 $this->profileIn();
346 $titles = $pageids = $revids = $redirects = null;
347 extract($this->extractRequestParams());
348
349 // Only one of the titles/pageids/revids is allowed at the same time
350 $dataSource = null;
351 if (isset ($titles))
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';
357 }
358 if (isset ($revids)) {
359 if (isset ($dataSource))
360 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
361 $dataSource = 'revids';
362 }
363
364 switch ($dataSource) {
365 case 'titles' :
366 case 'pageids' :
367 $this->populatePages($titles, $pageids, $redirects);
368 break;
369 case 'revids' :
370 $this->populateRevIDs($revids);
371 break;
372 default :
373 // Do nothing - some queries do not need any of the data sources.
374 break;
375 }
376 $this->profileOut();
377 }
378
379 /**
380 * This method is used by generators to pass the list of pageIDs internaly
381 */
382 public function executeForPageIDs($pageIDs) {
383 $this->profileIn();
384 $pageIDs = array_map( 'intval', $pageIDs ); // paranoia
385 $this->populatePages(null, $pageIDs, $this->getParameter('redirects'));
386 $this->profileOut();
387 }
388
389 protected function getAllowedParams() {
390 return array (
391 'titles' => array (
392 ApiBase :: PARAM_ISMULTI => true
393 ),
394 'pageids' => array (
395 ApiBase :: PARAM_TYPE => 'integer',
396 ApiBase :: PARAM_ISMULTI => true
397 ),
398 'revids' => array (
399 ApiBase :: PARAM_TYPE => 'integer',
400 ApiBase :: PARAM_ISMULTI => true
401 ),
402 'redirects' => false
403 );
404 }
405
406 protected function getParamDescription() {
407 return array (
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'
412 );
413 }
414
415 public function getVersion() {
416 return __CLASS__ . ': $Id$';
417 }
418 }
419 ?>