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