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