API: disabled login module until it is more secure. added performance comment in...
[lhc/web/wiklou.git] / includes / api / ApiPageSet.php
1 <?php
2
3 /*
4 * Created on Sep 24, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiQueryBase.php');
29 }
30
31 /**
32 * @addtogroup API
33 */
34 class ApiPageSet extends ApiQueryBase {
35
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;
40
41 private $mRequestedPageFields;
42
43 public function __construct($query, $resolveRedirects = false) {
44 parent :: __construct($query, __CLASS__);
45
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();
55
56 $this->mRequestedPageFields = array ();
57 $this->mResolveRedirects = $resolveRedirects;
58 if($resolveRedirects)
59 $this->mPendingRedirectIDs = array();
60 }
61
62 public function isResolvingRedirects() {
63 return $this->mResolveRedirects;
64 }
65
66 public function requestField($fieldName) {
67 $this->mRequestedPageFields[$fieldName] = null;
68 }
69
70 public function getCustomField($fieldName) {
71 return $this->mRequestedPageFields[$fieldName];
72 }
73
74 /**
75 * Get fields that modules have requested from the page table
76 */
77 public function getPageTableFields() {
78 // Ensure we get minimum required fields
79 $pageFlds = array (
80 'page_id' => null,
81 'page_namespace' => null,
82 'page_title' => null
83 );
84
85 // only store non-default fields
86 $this->mRequestedPageFields = array_diff_key($this->mRequestedPageFields, $pageFlds);
87
88 if ($this->mResolveRedirects)
89 $pageFlds['page_is_redirect'] = null;
90
91 return array_keys(array_merge($pageFlds, $this->mRequestedPageFields));
92 }
93
94 /**
95 * All Title objects provided.
96 * @return array of Title objects
97 */
98 public function getTitles() {
99 return $this->mTitles;
100 }
101
102 /**
103 * Returns the number of unique pages (not revisions) in the set.
104 */
105 public function getTitleCount() {
106 return count($this->mTitles);
107 }
108
109 /**
110 * Title objects that were found in the database.
111 * @return array page_id (int) => Title (obj)
112 */
113 public function getGoodTitles() {
114 return $this->mGoodTitles;
115 }
116
117 /**
118 * Returns the number of found unique pages (not revisions) in the set.
119 */
120 public function getGoodTitleCount() {
121 return count($this->mGoodTitles);
122 }
123
124 /**
125 * Title objects that were NOT found in the database.
126 * @return array of Title objects
127 */
128 public function getMissingTitles() {
129 return $this->mMissingTitles;
130 }
131
132 /**
133 * Page IDs that were not found in the database
134 * @return array of page IDs
135 */
136 public function getMissingPageIDs() {
137 return $this->mMissingPageIDs;
138 }
139
140 /**
141 * Get a list of redirects when doing redirect resolution
142 * @return array prefixed_title (string) => prefixed_title (string)
143 */
144 public function getRedirectTitles() {
145 return $this->mRedirectTitles;
146 }
147
148 /**
149 * Get a list of title normalizations - maps the title given
150 * with its normalized version.
151 * @return array raw_prefixed_title (string) => prefixed_title (string)
152 */
153 public function getNormalizedTitles() {
154 return $this->mNormalizedTitles;
155 }
156
157 /**
158 * Get the list of revision IDs (requested with revids= parameter)
159 * @return array revID (int) => pageID (int)
160 */
161 public function getRevisionIDs() {
162 return $this->mGoodRevIDs;
163 }
164
165 /**
166 * Revision IDs that were not found in the database
167 * @return array of revision IDs
168 */
169 public function getMissingRevisionIDs() {
170 return $this->mMissingRevIDs;
171 }
172
173 /**
174 * Returns the number of revisions (requested with revids= parameter)
175 */
176 public function getRevisionCount() {
177 return count($this->getRevisionIDs());
178 }
179
180 /**
181 * Populate from the request parameters
182 */
183 public function execute() {
184 $this->profileIn();
185 $titles = $pageids = $revids = null;
186 extract($this->extractRequestParams());
187
188 // Only one of the titles/pageids/revids is allowed at the same time
189 $dataSource = null;
190 if (isset ($titles))
191 $dataSource = 'titles';
192 if (isset ($pageids)) {
193 if (isset ($dataSource))
194 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
195 $dataSource = 'pageids';
196 }
197 if (isset ($revids)) {
198 if (isset ($dataSource))
199 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
200 $dataSource = 'revids';
201 }
202
203 switch ($dataSource) {
204 case 'titles' :
205 $this->initFromTitles($titles);
206 break;
207 case 'pageids' :
208 $this->initFromPageIds($pageids);
209 break;
210 case 'revids' :
211 if($this->mResolveRedirects)
212 $this->dieUsage('revids may not be used with redirect resolution', 'params');
213 $this->initFromRevIDs($revids);
214 break;
215 default :
216 // Do nothing - some queries do not need any of the data sources.
217 break;
218 }
219 $this->profileOut();
220 }
221
222 /**
223 * Initialize PageSet from a list of Titles
224 */
225 public function populateFromTitles($titles) {
226 $this->profileIn();
227 $this->initFromTitles($titles);
228 $this->profileOut();
229 }
230
231 /**
232 * Initialize PageSet from a list of Page IDs
233 */
234 public function populateFromPageIDs($pageIDs) {
235 $this->profileIn();
236 $pageIDs = array_map('intval', $pageIDs); // paranoia
237 $this->initFromPageIds($pageIDs);
238 $this->profileOut();
239 }
240
241 /**
242 * Initialize PageSet from a rowset returned from the database
243 */
244 public function populateFromQueryResult($db, $queryResult) {
245 $this->profileIn();
246 $this->initFromQueryResult($db, $queryResult);
247 $this->profileOut();
248 }
249
250 /**
251 * Initialize PageSet from a list of Revision IDs
252 */
253 public function populateFromRevisionIDs($revIDs) {
254 $this->profileIn();
255 $revIDs = array_map('intval', $revIDs); // paranoia
256 $this->initFromRevIDs($revIDs);
257 $this->profileOut();
258 }
259
260 /**
261 * Extract all requested fields from the row received from the database
262 */
263 public function processDbRow($row) {
264
265 // Store Title object in various data structures
266 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
267
268 // skip any pages that user has no rights to read
269 if ($title->userCanRead()) {
270
271 $pageId = intval($row->page_id);
272 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
273 $this->mTitles[] = $title;
274
275 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
276 $this->mPendingRedirectIDs[$pageId] = $title;
277 } else {
278 $this->mGoodTitles[$pageId] = $title;
279 }
280
281 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
282 $fieldValues[$pageId] = $row-> $fieldName;
283 }
284 }
285
286 public function finishPageSetGeneration() {
287 $this->profileIn();
288 $this->resolvePendingRedirects();
289 $this->profileOut();
290 }
291
292 /**
293 * This method populates internal variables with page information
294 * based on the given array of title strings.
295 *
296 * Steps:
297 * #1 For each title, get data from `page` table
298 * #2 If page was not found in the DB, store it as missing
299 *
300 * Additionally, when resolving redirects:
301 * #3 If no more redirects left, stop.
302 * #4 For each redirect, get its links from `pagelinks` table.
303 * #5 Substitute the original LinkBatch object with the new list
304 * #6 Repeat from step #1
305 */
306 private function initFromTitles($titles) {
307
308 // Get validated and normalized title objects
309 $linkBatch = $this->processTitlesArray($titles);
310 if($linkBatch->isEmpty())
311 return;
312
313 $db = $this->getDB();
314 $set = $linkBatch->constructSet('page', $db);
315
316 // Get pageIDs data from the `page` table
317 $this->profileDBIn();
318 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
319 $this->profileDBOut();
320
321 // Hack: get the ns:titles stored in array(ns => array(titles)) format
322 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
323
324 // Resolve any found redirects
325 $this->resolvePendingRedirects();
326 }
327
328 private function initFromPageIds($pageids) {
329 if(empty($pageids))
330 return;
331
332 $set = array (
333 'page_id' => $pageids
334 );
335
336 $db = $this->getDB();
337
338 // Get pageIDs data from the `page` table
339 $this->profileDBIn();
340 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
341 $this->profileDBOut();
342
343 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
344
345 // Resolve any found redirects
346 $this->resolvePendingRedirects();
347 }
348
349 /**
350 * Iterate through the result of the query on 'page' table,
351 * and for each row create and store title object and save any extra fields requested.
352 * @param $db Database
353 * @param $res DB Query result
354 * @param $remaining Array of either pageID or ns/title elements (optional).
355 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
356 * @param $processTitles bool Must be provided together with $remaining.
357 * If true, treat $remaining as an array of [ns][title]
358 * If false, treat it as an array of [pageIDs]
359 * @return Array of redirect IDs (only when resolving redirects)
360 */
361 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
362 if (!is_null($remaining) && is_null($processTitles))
363 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
364
365 while ($row = $db->fetchObject($res)) {
366
367 $pageId = intval($row->page_id);
368
369 // Remove found page from the list of remaining items
370 if (isset($remaining)) {
371 if ($processTitles)
372 unset ($remaining[$row->page_namespace][$row->page_title]);
373 else
374 unset ($remaining[$pageId]);
375 }
376
377 // Store any extra fields requested by modules
378 $this->processDbRow($row);
379 }
380 $db->freeResult($res);
381
382 if(isset($remaining)) {
383 // Any items left in the $remaining list are added as missing
384 if($processTitles) {
385 // The remaining titles in $remaining are non-existant pages
386 foreach ($remaining as $ns => $dbkeys) {
387 foreach ( $dbkeys as $dbkey => $unused ) {
388 $title = Title :: makeTitle($ns, $dbkey);
389 $this->mMissingTitles[] = $title;
390 $this->mAllPages[$ns][$dbkey] = 0;
391 $this->mTitles[] = $title;
392 }
393 }
394 }
395 else
396 {
397 // The remaining pageids do not exist
398 if(empty($this->mMissingPageIDs))
399 $this->mMissingPageIDs = array_keys($remaining);
400 else
401 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
402 }
403 }
404 }
405
406 private function initFromRevIDs($revids) {
407
408 if(empty($revids))
409 return;
410
411 $db = $this->getDB();
412 $pageids = array();
413 $remaining = array_flip($revids);
414
415 $tables = array('revision');
416 $fields = array('rev_id','rev_page');
417 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
418
419 // Get pageIDs data from the `page` table
420 $this->profileDBIn();
421 $res = $db->select( $tables, $fields, $where, __METHOD__ );
422 while ( $row = $db->fetchObject( $res ) ) {
423 $revid = intval($row->rev_id);
424 $pageid = intval($row->rev_page);
425 $this->mGoodRevIDs[$revid] = $pageid;
426 $pageids[$pageid] = '';
427 unset($remaining[$revid]);
428 }
429 $db->freeResult( $res );
430 $this->profileDBOut();
431
432 $this->mMissingRevIDs = array_keys($remaining);
433
434 // Populate all the page information
435 if($this->mResolveRedirects)
436 ApiBase :: dieDebug(__METHOD__, 'revids may not be used with redirect resolution');
437 $this->initFromPageIds(array_keys($pageids));
438 }
439
440 private function resolvePendingRedirects() {
441
442 if($this->mResolveRedirects) {
443 $db = $this->getDB();
444 $pageFlds = $this->getPageTableFields();
445
446 // Repeat until all redirects have been resolved
447 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
448 while (!empty ($this->mPendingRedirectIDs)) {
449
450 // Resolve redirects by querying the pagelinks table, and repeat the process
451 // Create a new linkBatch object for the next pass
452 $linkBatch = $this->getRedirectTargets();
453
454 if ($linkBatch->isEmpty())
455 break;
456
457 $set = $linkBatch->constructSet('page', $db);
458 if(false === $set)
459 break;
460
461 // Get pageIDs data from the `page` table
462 $this->profileDBIn();
463 $res = $db->select('page', $pageFlds, $set, __METHOD__);
464 $this->profileDBOut();
465
466 // Hack: get the ns:titles stored in array(ns => array(titles)) format
467 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
468 }
469 }
470 }
471
472 private function getRedirectTargets() {
473
474 $linkBatch = new LinkBatch();
475 $db = $this->getDB();
476
477 // find redirect targets for all redirect pages
478 $this->profileDBIn();
479 $res = $db->select('pagelinks', array (
480 'pl_from',
481 'pl_namespace',
482 'pl_title'
483 ), array (
484 'pl_from' => array_keys($this->mPendingRedirectIDs
485 )), __METHOD__);
486 $this->profileDBOut();
487
488 while ($row = $db->fetchObject($res)) {
489
490 $plfrom = intval($row->pl_from);
491
492 // Bug 7304 workaround
493 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
494 // A redirect page may have more than one link.
495 // This code will only use the first link returned.
496 if (isset ($this->mPendingRedirectIDs[$plfrom])) { // remove line when bug 7304 is fixed
497
498 $titleStrFrom = $this->mPendingRedirectIDs[$plfrom]->getPrefixedText();
499 $titleStrTo = Title :: makeTitle($row->pl_namespace, $row->pl_title)->getPrefixedText();
500 unset ($this->mPendingRedirectIDs[$plfrom]); // remove line when bug 7304 is fixed
501
502 // Avoid an infinite loop by checking if we have already processed this target
503 if (!isset ($this->mAllPages[$row->pl_namespace][$row->pl_title])) {
504 $linkBatch->add($row->pl_namespace, $row->pl_title);
505 }
506 } else {
507 // This redirect page has more than one link.
508 // This is very slow, but safer until bug 7304 is resolved
509 $title = Title :: newFromID($plfrom);
510 $titleStrFrom = $title->getPrefixedText();
511
512 $article = new Article($title);
513 $text = $article->getContent();
514 $titleTo = Title :: newFromRedirect($text);
515 $titleStrTo = $titleTo->getPrefixedText();
516
517 if (is_null($titleStrTo))
518 ApiBase :: dieDebug(__METHOD__, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
519
520 // Avoid an infinite loop by checking if we have already processed this target
521 if (!isset ($this->mAllPages[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
522 $linkBatch->addObj($titleTo);
523 }
524 }
525
526 $this->mRedirectTitles[$titleStrFrom] = $titleStrTo;
527 }
528 $db->freeResult($res);
529
530 // All IDs must exist in the page table
531 if (!empty($this->mPendingRedirectIDs[$plfrom]))
532 ApiBase :: dieDebug(__METHOD__, 'Invalid redirect IDs were found');
533
534 return $linkBatch;
535 }
536
537 /**
538 * Given an array of title strings, convert them into Title objects.
539 * This method validates access rights for the title,
540 * and appends normalization values to the output.
541 *
542 * @return LinkBatch of title objects.
543 */
544 private function processTitlesArray($titles) {
545
546 $linkBatch = new LinkBatch();
547
548 foreach ($titles as $title) {
549
550 $titleObj = is_string($title) ? Title :: newFromText($title) : $title;
551
552 // Validation
553 if (!$titleObj)
554 $this->dieUsage("bad title $titleString", 'invalidtitle');
555 if ($titleObj->getNamespace() < 0)
556 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
557 if (!$titleObj->userCanRead())
558 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
559
560 $linkBatch->addObj($titleObj);
561
562 // Make sure we remember the original title that was given to us
563 // This way the caller can correlate new titles with the originally requested,
564 // i.e. namespace is localized or capitalization is different
565 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
566 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
567 }
568 }
569
570 return $linkBatch;
571 }
572
573 public static function debugPrint($name = 'unknown') {
574 ApiBase::debugPrint($this->mAllPages, $name);
575 }
576
577 protected function getAllowedParams() {
578 return array (
579 'titles' => array (
580 ApiBase :: PARAM_ISMULTI => true
581 ),
582 'pageids' => array (
583 ApiBase :: PARAM_TYPE => 'integer',
584 ApiBase :: PARAM_ISMULTI => true
585 ),
586 'revids' => array (
587 ApiBase :: PARAM_TYPE => 'integer',
588 ApiBase :: PARAM_ISMULTI => true
589 )
590 );
591 }
592
593 protected function getParamDescription() {
594 return array (
595 'titles' => 'A list of titles to work on',
596 'pageids' => 'A list of page IDs to work on',
597 'revids' => 'A list of revision IDs to work on'
598 );
599 }
600
601 public function getVersion() {
602 return __CLASS__ . ': $Id$';
603 }
604 }
605 ?>