e846f30e2ff636aca24619638a9cd8bfaaa3288c
[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 $titles = $pageids = $revids = null;
232 extract($this->extractRequestParams());
233
234 // Only one of the titles/pageids/revids is allowed at the same time
235 $dataSource = null;
236 if (isset ($titles))
237 $dataSource = 'titles';
238 if (isset ($pageids)) {
239 if (isset ($dataSource))
240 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
241 $dataSource = 'pageids';
242 }
243 if (isset ($revids)) {
244 if (isset ($dataSource))
245 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
246 $dataSource = 'revids';
247 }
248
249 switch ($dataSource) {
250 case 'titles' :
251 $this->initFromTitles($titles);
252 break;
253 case 'pageids' :
254 $this->initFromPageIds($pageids);
255 break;
256 case 'revids' :
257 if($this->mResolveRedirects)
258 $this->setWarning('Redirect resolution cannot be used together with the revids= parameter. '.
259 'Any redirects the revids= point to have not been resolved.');
260 $this->mResolveRedirects = false;
261 $this->initFromRevIDs($revids);
262 break;
263 default :
264 // Do nothing - some queries do not need any of the data sources.
265 break;
266 }
267 $this->profileOut();
268 }
269
270 /**
271 * Initialize PageSet from a list of Titles
272 */
273 public function populateFromTitles($titles) {
274 $this->profileIn();
275 $this->initFromTitles($titles);
276 $this->profileOut();
277 }
278
279 /**
280 * Initialize PageSet from a list of Page IDs
281 */
282 public function populateFromPageIDs($pageIDs) {
283 $this->profileIn();
284 $this->initFromPageIds($pageIDs);
285 $this->profileOut();
286 }
287
288 /**
289 * Initialize PageSet from a rowset returned from the database
290 */
291 public function populateFromQueryResult($db, $queryResult) {
292 $this->profileIn();
293 $this->initFromQueryResult($db, $queryResult);
294 $this->profileOut();
295 }
296
297 /**
298 * Initialize PageSet from a list of Revision IDs
299 */
300 public function populateFromRevisionIDs($revIDs) {
301 $this->profileIn();
302 $revIDs = array_map('intval', $revIDs); // paranoia
303 $this->initFromRevIDs($revIDs);
304 $this->profileOut();
305 }
306
307 /**
308 * Extract all requested fields from the row received from the database
309 */
310 public function processDbRow($row) {
311
312 // Store Title object in various data structures
313 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
314
315 $pageId = intval($row->page_id);
316 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
317 $this->mTitles[] = $title;
318
319 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
320 $this->mPendingRedirectIDs[$pageId] = $title;
321 } else {
322 $this->mGoodTitles[$pageId] = $title;
323 }
324
325 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
326 $fieldValues[$pageId] = $row-> $fieldName;
327 }
328
329 public function finishPageSetGeneration() {
330 $this->profileIn();
331 $this->resolvePendingRedirects();
332 $this->profileOut();
333 }
334
335 /**
336 * This method populates internal variables with page information
337 * based on the given array of title strings.
338 *
339 * Steps:
340 * #1 For each title, get data from `page` table
341 * #2 If page was not found in the DB, store it as missing
342 *
343 * Additionally, when resolving redirects:
344 * #3 If no more redirects left, stop.
345 * #4 For each redirect, get its links from `pagelinks` table.
346 * #5 Substitute the original LinkBatch object with the new list
347 * #6 Repeat from step #1
348 */
349 private function initFromTitles($titles) {
350
351 // Get validated and normalized title objects
352 $linkBatch = $this->processTitlesArray($titles);
353 if($linkBatch->isEmpty())
354 return;
355
356 $db = $this->getDB();
357 $set = $linkBatch->constructSet('page', $db);
358
359 // Get pageIDs data from the `page` table
360 $this->profileDBIn();
361 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
362 $this->profileDBOut();
363
364 // Hack: get the ns:titles stored in array(ns => array(titles)) format
365 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
366
367 // Resolve any found redirects
368 $this->resolvePendingRedirects();
369 }
370
371 private function initFromPageIds($pageids) {
372 if(!count($pageids))
373 return;
374
375 $pageids = array_map('intval', $pageids); // paranoia
376 $set = array (
377 'page_id' => $pageids
378 );
379
380 $db = $this->getDB();
381
382 // Get pageIDs data from the `page` table
383 $this->profileDBIn();
384 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
385 $this->profileDBOut();
386
387 $remaining = array_flip($pageids);
388 $this->initFromQueryResult($db, $res, $remaining, false); // process PageIDs
389
390 // Resolve any found redirects
391 $this->resolvePendingRedirects();
392 }
393
394 /**
395 * Iterate through the result of the query on 'page' table,
396 * and for each row create and store title object and save any extra fields requested.
397 * @param $db Database
398 * @param $res DB Query result
399 * @param $remaining Array of either pageID or ns/title elements (optional).
400 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
401 * @param $processTitles bool Must be provided together with $remaining.
402 * If true, treat $remaining as an array of [ns][title]
403 * If false, treat it as an array of [pageIDs]
404 * @return Array of redirect IDs (only when resolving redirects)
405 */
406 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
407 if (!is_null($remaining) && is_null($processTitles))
408 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
409
410 while ($row = $db->fetchObject($res)) {
411
412 $pageId = intval($row->page_id);
413
414 // Remove found page from the list of remaining items
415 if (isset($remaining)) {
416 if ($processTitles)
417 unset ($remaining[$row->page_namespace][$row->page_title]);
418 else
419 unset ($remaining[$pageId]);
420 }
421
422 // Store any extra fields requested by modules
423 $this->processDbRow($row);
424 }
425 $db->freeResult($res);
426
427 if(isset($remaining)) {
428 // Any items left in the $remaining list are added as missing
429 if($processTitles) {
430 // The remaining titles in $remaining are non-existant pages
431 foreach ($remaining as $ns => $dbkeys) {
432 foreach ( $dbkeys as $dbkey => $unused ) {
433 $title = Title :: makeTitle($ns, $dbkey);
434 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
435 $this->mMissingTitles[$this->mFakePageId] = $title;
436 $this->mFakePageId--;
437 $this->mTitles[] = $title;
438 }
439 }
440 }
441 else
442 {
443 // The remaining pageids do not exist
444 if(!$this->mMissingPageIDs)
445 $this->mMissingPageIDs = array_keys($remaining);
446 else
447 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
448 }
449 }
450 }
451
452 private function initFromRevIDs($revids) {
453
454 if(!count($revids))
455 return;
456
457 $db = $this->getDB();
458 $pageids = array();
459 $remaining = array_flip($revids);
460
461 $tables = array('revision','page');
462 $fields = array('rev_id','rev_page');
463 $where = array('rev_deleted' => 0, 'rev_id' => $revids,'rev_page = page_id');
464
465 // Get pageIDs data from the `page` table
466 $this->profileDBIn();
467 $res = $db->select( $tables, $fields, $where, __METHOD__ );
468 while ( $row = $db->fetchObject( $res ) ) {
469 $revid = intval($row->rev_id);
470 $pageid = intval($row->rev_page);
471 $this->mGoodRevIDs[$revid] = $pageid;
472 $pageids[$pageid] = '';
473 unset($remaining[$revid]);
474 }
475 $db->freeResult( $res );
476 $this->profileDBOut();
477
478 $this->mMissingRevIDs = array_keys($remaining);
479
480 // Populate all the page information
481 $this->initFromPageIds(array_keys($pageids));
482 }
483
484 private function resolvePendingRedirects() {
485
486 if($this->mResolveRedirects) {
487 $db = $this->getDB();
488 $pageFlds = $this->getPageTableFields();
489
490 // Repeat until all redirects have been resolved
491 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
492 while ($this->mPendingRedirectIDs) {
493
494 // Resolve redirects by querying the pagelinks table, and repeat the process
495 // Create a new linkBatch object for the next pass
496 $linkBatch = $this->getRedirectTargets();
497
498 if ($linkBatch->isEmpty())
499 break;
500
501 $set = $linkBatch->constructSet('page', $db);
502 if(false === $set)
503 break;
504
505 // Get pageIDs data from the `page` table
506 $this->profileDBIn();
507 $res = $db->select('page', $pageFlds, $set, __METHOD__);
508 $this->profileDBOut();
509
510 // Hack: get the ns:titles stored in array(ns => array(titles)) format
511 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
512 }
513 }
514 }
515
516 private function getRedirectTargets() {
517 $lb = new LinkBatch();
518 $db = $this->getDB();
519
520 $this->profileDBIn();
521 $res = $db->select('redirect', array(
522 'rd_from',
523 'rd_namespace',
524 'rd_title'
525 ), array('rd_from' => array_keys($this->mPendingRedirectIDs)),
526 __METHOD__
527 );
528 $this->profileDBOut();
529
530 while($row = $db->fetchObject($res))
531 {
532 $rdfrom = intval($row->rd_from);
533 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
534 $to = Title::makeTitle($row->rd_namespace, $row->rd_title)->getPrefixedText();
535 unset($this->mPendingRedirectIDs[$rdfrom]);
536 if(!isset($this->mAllPages[$row->rd_namespace][$row->rd_title]))
537 $lb->add($row->rd_namespace, $row->rd_title);
538 $this->mRedirectTitles[$from] = $to;
539 }
540 $db->freeResult($res);
541 if($this->mPendingRedirectIDs)
542 {
543 # We found pages that aren't in the redirect table
544 # Add them
545 foreach($this->mPendingRedirectIDs as $id => $title)
546 {
547 $article = new Article($title);
548 $rt = $article->insertRedirect();
549 if(!$rt)
550 # What the hell. Let's just ignore this
551 continue;
552 $lb->addObj($rt);
553 $this->mRedirectTitles[$title->getPrefixedText()] = $rt->getPrefixedText();
554 unset($this->mPendingRedirectIDs[$id]);
555 }
556 }
557 return $lb;
558 }
559
560 /**
561 * Given an array of title strings, convert them into Title objects.
562 * Alternativelly, an array of Title objects may be given.
563 * This method validates access rights for the title,
564 * and appends normalization values to the output.
565 *
566 * @return LinkBatch of title objects.
567 */
568 private function processTitlesArray($titles) {
569
570 $linkBatch = new LinkBatch();
571
572 foreach ($titles as $title) {
573
574 $titleObj = is_string($title) ? Title :: newFromText($title) : $title;
575 if (!$titleObj)
576 {
577 # Handle invalid titles gracefully
578 $this->mAllpages[0][$title] = $this->mFakePageId;
579 $this->mInvalidTitles[$this->mFakePageId] = $title;
580 $this->mFakePageId--;
581 continue; // There's nothing else we can do
582 }
583 $iw = $titleObj->getInterwiki();
584 if (strval($iw) !== '') {
585 // This title is an interwiki link.
586 $this->mInterwikiTitles[$titleObj->getPrefixedText()] = $iw;
587 } else {
588
589 // Validation
590 if ($titleObj->getNamespace() < 0)
591 $this->setWarning("No support for special pages has been implemented");
592 else
593 $linkBatch->addObj($titleObj);
594 }
595
596 // Make sure we remember the original title that was given to us
597 // This way the caller can correlate new titles with the originally requested,
598 // i.e. namespace is localized or capitalization is different
599 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
600 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
601 }
602 }
603
604 return $linkBatch;
605 }
606
607 protected function getAllowedParams() {
608 return array (
609 'titles' => array (
610 ApiBase :: PARAM_ISMULTI => true
611 ),
612 'pageids' => array (
613 ApiBase :: PARAM_TYPE => 'integer',
614 ApiBase :: PARAM_ISMULTI => true
615 ),
616 'revids' => array (
617 ApiBase :: PARAM_TYPE => 'integer',
618 ApiBase :: PARAM_ISMULTI => true
619 )
620 );
621 }
622
623 protected function getParamDescription() {
624 return array (
625 'titles' => 'A list of titles to work on',
626 'pageids' => 'A list of page IDs to work on',
627 'revids' => 'A list of revision IDs to work on'
628 );
629 }
630
631 public function getVersion() {
632 return __CLASS__ . ': $Id$';
633 }
634 }