Committing patch for bug 10931, which also fixes bug 13651. For a detailed explanatio...
[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 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, __CLASS__);
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 $pageFlds = array (
96 'page_id' => null,
97 'page_namespace' => null,
98 'page_title' => null
99 );
100
101 // only store non-default fields
102 $this->mRequestedPageFields = array_diff_key($this->mRequestedPageFields, $pageFlds);
103
104 if ($this->mResolveRedirects)
105 $pageFlds['page_is_redirect'] = null;
106
107 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields);
108 return array_keys($pageFlds);
109 }
110
111 /**
112 * Returns an array [ns][dbkey] => page_id for all requested titles.
113 * page_id is a unique negative number in case title was not found.
114 * Invalid titles will also have negative page IDs and will be in namespace 0
115 */
116 public function getAllTitlesByNamespace() {
117 return $this->mAllPages;
118 }
119
120 /**
121 * All Title objects provided.
122 * @return array of Title objects
123 */
124 public function getTitles() {
125 return $this->mTitles;
126 }
127
128 /**
129 * Returns the number of unique pages (not revisions) in the set.
130 */
131 public function getTitleCount() {
132 return count($this->mTitles);
133 }
134
135 /**
136 * Title objects that were found in the database.
137 * @return array page_id (int) => Title (obj)
138 */
139 public function getGoodTitles() {
140 return $this->mGoodTitles;
141 }
142
143 /**
144 * Returns the number of found unique pages (not revisions) in the set.
145 */
146 public function getGoodTitleCount() {
147 return count($this->mGoodTitles);
148 }
149
150 /**
151 * Title objects that were NOT found in the database.
152 * The array's index will be negative for each item
153 * @return array of Title objects
154 */
155 public function getMissingTitles() {
156 return $this->mMissingTitles;
157 }
158
159 /**
160 * Titles that were deemed invalid by Title::newFromText()
161 * The array's index will be unique and negative for each item
162 * @return array of strings (not Title objects)
163 */
164 public function getInvalidTitles() {
165 return $this->mInvalidTitles;
166 }
167
168 /**
169 * Page IDs that were not found in the database
170 * @return array of page IDs
171 */
172 public function getMissingPageIDs() {
173 return $this->mMissingPageIDs;
174 }
175
176 /**
177 * Get a list of redirects when doing redirect resolution
178 * @return array prefixed_title (string) => prefixed_title (string)
179 */
180 public function getRedirectTitles() {
181 return $this->mRedirectTitles;
182 }
183
184 /**
185 * Get a list of title normalizations - maps the title given
186 * with its normalized version.
187 * @return array raw_prefixed_title (string) => prefixed_title (string)
188 */
189 public function getNormalizedTitles() {
190 return $this->mNormalizedTitles;
191 }
192
193 /**
194 * Get a list of interwiki titles - maps the title given
195 * with to the interwiki prefix.
196 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
197 */
198 public function getInterwikiTitles() {
199 return $this->mInterwikiTitles;
200 }
201
202 /**
203 * Get the list of revision IDs (requested with revids= parameter)
204 * @return array revID (int) => pageID (int)
205 */
206 public function getRevisionIDs() {
207 return $this->mGoodRevIDs;
208 }
209
210 /**
211 * Revision IDs that were not found in the database
212 * @return array of revision IDs
213 */
214 public function getMissingRevisionIDs() {
215 return $this->mMissingRevIDs;
216 }
217
218 /**
219 * Returns the number of revisions (requested with revids= parameter)
220 */
221 public function getRevisionCount() {
222 return count($this->getRevisionIDs());
223 }
224
225 /**
226 * Populate from the request parameters
227 */
228 public function execute() {
229 $this->profileIn();
230 $titles = $pageids = $revids = null;
231 extract($this->extractRequestParams());
232
233 // Only one of the titles/pageids/revids is allowed at the same time
234 $dataSource = null;
235 if (isset ($titles))
236 $dataSource = 'titles';
237 if (isset ($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 ($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($titles);
251 break;
252 case 'pageids' :
253 $this->initFromPageIds($pageids);
254 break;
255 case 'revids' :
256 if($this->mResolveRedirects)
257 $this->dieUsage('revids may not be used with redirect resolution', 'params');
258 $this->initFromRevIDs($revids);
259 break;
260 default :
261 // Do nothing - some queries do not need any of the data sources.
262 break;
263 }
264 $this->profileOut();
265 }
266
267 /**
268 * Initialize PageSet from a list of Titles
269 */
270 public function populateFromTitles($titles) {
271 $this->profileIn();
272 $this->initFromTitles($titles);
273 $this->profileOut();
274 }
275
276 /**
277 * Initialize PageSet from a list of Page IDs
278 */
279 public function populateFromPageIDs($pageIDs) {
280 $this->profileIn();
281 $this->initFromPageIds($pageIDs);
282 $this->profileOut();
283 }
284
285 /**
286 * Initialize PageSet from a rowset returned from the database
287 */
288 public function populateFromQueryResult($db, $queryResult) {
289 $this->profileIn();
290 $this->initFromQueryResult($db, $queryResult);
291 $this->profileOut();
292 }
293
294 /**
295 * Initialize PageSet from a list of Revision IDs
296 */
297 public function populateFromRevisionIDs($revIDs) {
298 $this->profileIn();
299 $revIDs = array_map('intval', $revIDs); // paranoia
300 $this->initFromRevIDs($revIDs);
301 $this->profileOut();
302 }
303
304 /**
305 * Extract all requested fields from the row received from the database
306 */
307 public function processDbRow($row) {
308
309 // Store Title object in various data structures
310 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
311
312 $pageId = intval($row->page_id);
313 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
314 $this->mTitles[] = $title;
315
316 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
317 $this->mPendingRedirectIDs[$pageId] = $title;
318 } else {
319 $this->mGoodTitles[$pageId] = $title;
320 }
321
322 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
323 $fieldValues[$pageId] = $row-> $fieldName;
324 }
325
326 public function finishPageSetGeneration() {
327 $this->profileIn();
328 $this->resolvePendingRedirects();
329 $this->profileOut();
330 }
331
332 /**
333 * This method populates internal variables with page information
334 * based on the given array of title strings.
335 *
336 * Steps:
337 * #1 For each title, get data from `page` table
338 * #2 If page was not found in the DB, store it as missing
339 *
340 * Additionally, when resolving redirects:
341 * #3 If no more redirects left, stop.
342 * #4 For each redirect, get its links from `pagelinks` table.
343 * #5 Substitute the original LinkBatch object with the new list
344 * #6 Repeat from step #1
345 */
346 private function initFromTitles($titles) {
347
348 // Get validated and normalized title objects
349 $linkBatch = $this->processTitlesArray($titles);
350 if($linkBatch->isEmpty())
351 return;
352
353 $db = $this->getDB();
354 $set = $linkBatch->constructSet('page', $db);
355
356 // Get pageIDs data from the `page` table
357 $this->profileDBIn();
358 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
359 $this->profileDBOut();
360
361 // Hack: get the ns:titles stored in array(ns => array(titles)) format
362 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
363
364 // Resolve any found redirects
365 $this->resolvePendingRedirects();
366 }
367
368 private function initFromPageIds($pageids) {
369 if(empty($pageids))
370 return;
371
372 $pageids = array_map('intval', $pageids); // paranoia
373 $set = array (
374 'page_id' => $pageids
375 );
376
377 $db = $this->getDB();
378
379 // Get pageIDs data from the `page` table
380 $this->profileDBIn();
381 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
382 $this->profileDBOut();
383
384 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
385
386 // Resolve any found redirects
387 $this->resolvePendingRedirects();
388 }
389
390 /**
391 * Iterate through the result of the query on 'page' table,
392 * and for each row create and store title object and save any extra fields requested.
393 * @param $db Database
394 * @param $res DB Query result
395 * @param $remaining Array of either pageID or ns/title elements (optional).
396 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
397 * @param $processTitles bool Must be provided together with $remaining.
398 * If true, treat $remaining as an array of [ns][title]
399 * If false, treat it as an array of [pageIDs]
400 * @return Array of redirect IDs (only when resolving redirects)
401 */
402 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
403 if (!is_null($remaining) && is_null($processTitles))
404 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
405
406 while ($row = $db->fetchObject($res)) {
407
408 $pageId = intval($row->page_id);
409
410 // Remove found page from the list of remaining items
411 if (isset($remaining)) {
412 if ($processTitles)
413 unset ($remaining[$row->page_namespace][$row->page_title]);
414 else
415 unset ($remaining[$pageId]);
416 }
417
418 // Store any extra fields requested by modules
419 $this->processDbRow($row);
420 }
421 $db->freeResult($res);
422
423 if(isset($remaining)) {
424 // Any items left in the $remaining list are added as missing
425 if($processTitles) {
426 // The remaining titles in $remaining are non-existant pages
427 foreach ($remaining as $ns => $dbkeys) {
428 foreach ( $dbkeys as $dbkey => $unused ) {
429 $title = Title :: makeTitle($ns, $dbkey);
430 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
431 $this->mMissingTitles[$this->mFakePageId] = $title;
432 $this->mFakePageId--;
433 $this->mTitles[] = $title;
434 }
435 }
436 }
437 else
438 {
439 // The remaining pageids do not exist
440 if(empty($this->mMissingPageIDs))
441 $this->mMissingPageIDs = array_keys($remaining);
442 else
443 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
444 }
445 }
446 }
447
448 private function initFromRevIDs($revids) {
449
450 if(empty($revids))
451 return;
452
453 $db = $this->getDB();
454 $pageids = array();
455 $remaining = array_flip($revids);
456
457 $tables = array('revision');
458 $fields = array('rev_id','rev_page');
459 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
460
461 // Get pageIDs data from the `page` table
462 $this->profileDBIn();
463 $res = $db->select( $tables, $fields, $where, __METHOD__ );
464 while ( $row = $db->fetchObject( $res ) ) {
465 $revid = intval($row->rev_id);
466 $pageid = intval($row->rev_page);
467 $this->mGoodRevIDs[$revid] = $pageid;
468 $pageids[$pageid] = '';
469 unset($remaining[$revid]);
470 }
471 $db->freeResult( $res );
472 $this->profileDBOut();
473
474 $this->mMissingRevIDs = array_keys($remaining);
475
476 // Populate all the page information
477 if($this->mResolveRedirects)
478 ApiBase :: dieDebug(__METHOD__, 'revids may not be used with redirect resolution');
479 $this->initFromPageIds(array_keys($pageids));
480 }
481
482 private function resolvePendingRedirects() {
483
484 if($this->mResolveRedirects) {
485 $db = $this->getDB();
486 $pageFlds = $this->getPageTableFields();
487
488 // Repeat until all redirects have been resolved
489 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
490 while (!empty ($this->mPendingRedirectIDs)) {
491
492 // Resolve redirects by querying the pagelinks table, and repeat the process
493 // Create a new linkBatch object for the next pass
494 $linkBatch = $this->getRedirectTargets();
495
496 if ($linkBatch->isEmpty())
497 break;
498
499 $set = $linkBatch->constructSet('page', $db);
500 if(false === $set)
501 break;
502
503 // Get pageIDs data from the `page` table
504 $this->profileDBIn();
505 $res = $db->select('page', $pageFlds, $set, __METHOD__);
506 $this->profileDBOut();
507
508 // Hack: get the ns:titles stored in array(ns => array(titles)) format
509 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
510 }
511 }
512 }
513
514 private function getRedirectTargets() {
515 $lb = new LinkBatch();
516 $db = $this->getDB();
517
518 $this->profileDBIn();
519 $res = $db->select('redirect', array(
520 'rd_from',
521 'rd_namespace',
522 'rd_title'
523 ), array('rd_from' => array_keys($this->mPendingRedirectIDs)),
524 __METHOD__
525 );
526 $this->profileDBOut();
527
528 while($row = $db->fetchObject($res))
529 {
530 $rdfrom = intval($row->rd_from);
531 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
532 $to = Title::makeTitle($row->rd_namespace, $row->rd_title)->getPrefixedText();
533 unset($this->mPendingRedirectIDs[$rdfrom]);
534 if(!isset($this->mAllPages[$row->rd_namespace][$row->rd_title]))
535 $lb->add($row->rd_namespace, $row->rd_title);
536 $this->mRedirectTitles[$from] = $to;
537 }
538 $db->freeResult($res);
539 if(!empty($this->mPendingRedirectIDs))
540 {
541 # We found pages that aren't in the redirect table
542 # Add them
543 foreach($this->mPendingRedirectIDs as $id => $title)
544 {
545 $article = new Article($title);
546 $rt = $article->insertRedirect();
547 if(!$rt)
548 # What the hell. Let's just ignore this
549 continue;
550 $lb->addObj($rt);
551 $this->mRedirectTitles[$title->getPrefixedText()] = $rt->getPrefixedText();
552 unset($this->mPendingRedirectIDs[$id]);
553 }
554 $this->getMain()->scheduleCommit();
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 (!empty($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->dieUsage("No support for special pages has been implemented", 'unsupportednamespace');
591
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 }
634
635