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