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