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