E_STRICT
[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 $remaining = array_flip($pageids);
385 $this->initFromQueryResult($db, $res, $remaining, false); // process PageIDs
386
387 // Resolve any found redirects
388 $this->resolvePendingRedirects();
389 }
390
391 /**
392 * Iterate through the result of the query on 'page' table,
393 * and for each row create and store title object and save any extra fields requested.
394 * @param $db Database
395 * @param $res DB Query result
396 * @param $remaining Array of either pageID or ns/title elements (optional).
397 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
398 * @param $processTitles bool Must be provided together with $remaining.
399 * If true, treat $remaining as an array of [ns][title]
400 * If false, treat it as an array of [pageIDs]
401 * @return Array of redirect IDs (only when resolving redirects)
402 */
403 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
404 if (!is_null($remaining) && is_null($processTitles))
405 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
406
407 while ($row = $db->fetchObject($res)) {
408
409 $pageId = intval($row->page_id);
410
411 // Remove found page from the list of remaining items
412 if (isset($remaining)) {
413 if ($processTitles)
414 unset ($remaining[$row->page_namespace][$row->page_title]);
415 else
416 unset ($remaining[$pageId]);
417 }
418
419 // Store any extra fields requested by modules
420 $this->processDbRow($row);
421 }
422 $db->freeResult($res);
423
424 if(isset($remaining)) {
425 // Any items left in the $remaining list are added as missing
426 if($processTitles) {
427 // The remaining titles in $remaining are non-existant pages
428 foreach ($remaining as $ns => $dbkeys) {
429 foreach ( $dbkeys as $dbkey => $unused ) {
430 $title = Title :: makeTitle($ns, $dbkey);
431 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
432 $this->mMissingTitles[$this->mFakePageId] = $title;
433 $this->mFakePageId--;
434 $this->mTitles[] = $title;
435 }
436 }
437 }
438 else
439 {
440 // The remaining pageids do not exist
441 if(empty($this->mMissingPageIDs))
442 $this->mMissingPageIDs = array_keys($remaining);
443 else
444 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
445 }
446 }
447 }
448
449 private function initFromRevIDs($revids) {
450
451 if(empty($revids))
452 return;
453
454 $db = $this->getDB();
455 $pageids = array();
456 $remaining = array_flip($revids);
457
458 $tables = array('revision');
459 $fields = array('rev_id','rev_page');
460 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
461
462 // Get pageIDs data from the `page` table
463 $this->profileDBIn();
464 $res = $db->select( $tables, $fields, $where, __METHOD__ );
465 while ( $row = $db->fetchObject( $res ) ) {
466 $revid = intval($row->rev_id);
467 $pageid = intval($row->rev_page);
468 $this->mGoodRevIDs[$revid] = $pageid;
469 $pageids[$pageid] = '';
470 unset($remaining[$revid]);
471 }
472 $db->freeResult( $res );
473 $this->profileDBOut();
474
475 $this->mMissingRevIDs = array_keys($remaining);
476
477 // Populate all the page information
478 if($this->mResolveRedirects)
479 ApiBase :: dieDebug(__METHOD__, 'revids may not be used with redirect resolution');
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 (!empty ($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(!empty($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 $this->getMain()->scheduleCommit();
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 (!empty($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->dieUsage("No support for special pages has been implemented", 'unsupportednamespace');
592
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 }