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