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