* API query optimizations
[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 $pageIDs = 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 $pageId = intval($row->page_id);
247
248 // Store Title object in various data structures
249 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
250 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
251
252 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
253 $this->mPendingRedirectIDs[$pageId] = $title;
254 } else {
255 $this->mGoodTitles[$pageId] = $title;
256 }
257
258 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
259 $fieldValues[$pageId] = $row-> $fieldName;
260 }
261
262 public function finishPageSetGeneration() {
263 $this->profileIn();
264 $this->resolvePendingRedirects();
265 $this->profileOut();
266 }
267
268 /**
269 * This method populates internal variables with page information
270 * based on the given array of title strings.
271 *
272 * Steps:
273 * #1 For each title, get data from `page` table
274 * #2 If page was not found in the DB, store it as missing
275 *
276 * Additionally, when resolving redirects:
277 * #3 If no more redirects left, stop.
278 * #4 For each redirect, get its links from `pagelinks` table.
279 * #5 Substitute the original LinkBatch object with the new list
280 * #6 Repeat from step #1
281 */
282 private function initFromTitles($titles) {
283 $db = $this->getDB();
284
285 // Get validated and normalized title objects
286 $linkBatch = $this->processTitlesStrArray($titles);
287 if($linkBatch->isEmpty())
288 return;
289
290 $set = $linkBatch->constructSet('page', $db);
291
292 // Get pageIDs data from the `page` table
293 $this->profileDBIn();
294 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
295 $this->profileDBOut();
296
297 // Hack: get the ns:titles stored in array(ns => array(titles)) format
298 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
299
300 // Resolve any found redirects
301 $this->resolvePendingRedirects();
302 }
303
304 private function initFromPageIds($pageids) {
305 if(empty($pageids))
306 return;
307
308 $db = $this->getDB();
309 $set = array (
310 'page_id' => $pageids
311 );
312
313 // Get pageIDs data from the `page` table
314 $this->profileDBIn();
315 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
316 $this->profileDBOut();
317
318 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
319
320 // Resolve any found redirects
321 $this->resolvePendingRedirects();
322 }
323
324 /**
325 * Iterate through the result of the query on 'page' table,
326 * and for each row create and store title object and save any extra fields requested.
327 * @param $db Database
328 * @param $res DB Query result
329 * @param $remaining Array of either pageID or ns/title elements (optional).
330 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
331 * @param $processTitles bool Must be provided together with $remaining.
332 * If true, treat $remaining as an array of [ns][title]
333 * If false, treat it as an array of [pageIDs]
334 * @return Array of redirect IDs (only when resolving redirects)
335 */
336 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
337 if (!is_null($remaining) && is_null($processTitles))
338 $this->dieDebug('Missing $processTitles parameter when $remaining is provided');
339
340 while ($row = $db->fetchObject($res)) {
341
342 $pageId = intval($row->page_id);
343
344 // Remove found page from the list of remaining items
345 if (isset($remaining)) {
346 if ($processTitles)
347 unset ($remaining[$row->page_namespace][$row->page_title]);
348 else
349 unset ($remaining[$pageId]);
350 }
351
352 // Store any extra fields requested by modules
353 $this->processDbRow($row);
354 }
355 $db->freeResult($res);
356
357 if(isset($remaining)) {
358 // Any items left in the $remaining list are added as missing
359 if($processTitles) {
360 // The remaining titles in $remaining are non-existant pages
361 foreach ($remaining as $ns => $dbkeys) {
362 foreach ($dbkeys as $dbkey => $nothing) {
363 $this->mMissingTitles[] = Title :: makeTitle($ns, $dbkey);
364 $this->mAllPages[$ns][$dbkey] = 0;
365 }
366 }
367 }
368 else
369 {
370 // The remaining pageids do not exist
371 if(empty($this->mMissingPageIDs))
372 $this->mMissingPageIDs = array_keys($remaining);
373 else
374 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
375 }
376 }
377 }
378
379 private function initFromRevIDs($revids) {
380
381 if(empty($revids))
382 return;
383
384 $db = $this->getDB();
385 $pageids = array();
386 $remaining = array_flip($revids);
387
388 $tables = array('revision');
389 $fields = array('rev_id','rev_page');
390 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
391
392 // Get pageIDs data from the `page` table
393 $this->profileDBIn();
394 $res = $db->select( $tables, $fields, $where, __METHOD__ );
395 while ( $row = $db->fetchObject( $res ) ) {
396 $revid = intval($row->rev_id);
397 $pageid = intval($row->rev_page);
398 $this->mGoodRevIDs[$revid] = $pageid;
399 $pageids[$pageid] = '';
400 unset($remaining[$revid]);
401 }
402 $db->freeResult( $res );
403 $this->profileDBOut();
404
405 $this->mMissingRevIDs = array_keys($remaining);
406
407 // Populate all the page information
408 if($this->mResolveRedirects)
409 $this->dieDebug('revids may not be used with redirect resolution');
410 $this->initFromPageIds(array_keys($pageids));
411 }
412
413 private function resolvePendingRedirects() {
414
415 if($this->mResolveRedirects) {
416 $db = $this->getDB();
417 $pageFlds = $this->getPageTableFields();
418
419 // Repeat until all redirects have been resolved
420 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
421 while (!empty ($this->mPendingRedirectIDs)) {
422
423 // Resolve redirects by querying the pagelinks table, and repeat the process
424 // Create a new linkBatch object for the next pass
425 $linkBatch = $this->getRedirectTargets();
426
427 if ($linkBatch->isEmpty())
428 break;
429
430 $set = $linkBatch->constructSet('page', $db);
431 if(false === $set)
432 break;
433
434 // Get pageIDs data from the `page` table
435 $this->profileDBIn();
436 $res = $db->select('page', $pageFlds, $set, __METHOD__);
437 $this->profileDBOut();
438
439 // Hack: get the ns:titles stored in array(ns => array(titles)) format
440 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
441 }
442 }
443 }
444
445 private function getRedirectTargets() {
446
447 $linkBatch = new LinkBatch();
448 $db = $this->getDB();
449
450 // find redirect targets for all redirect pages
451 $this->profileDBIn();
452 $res = $db->select('pagelinks', array (
453 'pl_from',
454 'pl_namespace',
455 'pl_title'
456 ), array (
457 'pl_from' => array_keys($this->mPendingRedirectIDs
458 )), __METHOD__);
459 $this->profileDBOut();
460
461 while ($row = $db->fetchObject($res)) {
462
463 $plfrom = intval($row->pl_from);
464
465 // Bug 7304 workaround
466 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
467 // A redirect page may have more than one link.
468 // This code will only use the first link returned.
469 if (isset ($this->mPendingRedirectIDs[$plfrom])) { // remove line when bug 7304 is fixed
470
471 $titleStrFrom = $this->mPendingRedirectIDs[$plfrom]->getPrefixedText();
472 $titleStrTo = Title :: makeTitle($row->pl_namespace, $row->pl_title)->getPrefixedText();
473 unset ($this->mPendingRedirectIDs[$plfrom]); // remove line when bug 7304 is fixed
474
475 // Avoid an infinite loop by checking if we have already processed this target
476 if (!isset ($this->mAllPages[$row->pl_namespace][$row->pl_title])) {
477 $linkBatch->add($row->pl_namespace, $row->pl_title);
478 }
479 } else {
480 // This redirect page has more than one link.
481 // This is very slow, but safer until bug 7304 is resolved
482 $title = Title :: newFromID($plfrom);
483 $titleStrFrom = $title->getPrefixedText();
484
485 $article = new Article($title);
486 $text = $article->getContent();
487 $titleTo = Title :: newFromRedirect($text);
488 $titleStrTo = $titleTo->getPrefixedText();
489
490 if (is_null($titleStrTo))
491 ApiBase :: dieDebug(__METHOD__, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
492
493 // Avoid an infinite loop by checking if we have already processed this target
494 if (!isset ($this->mAllPages[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
495 $linkBatch->addObj($titleTo);
496 }
497 }
498
499 $this->mRedirectTitles[$titleStrFrom] = $titleStrTo;
500 }
501 $db->freeResult($res);
502
503 // All IDs must exist in the page table
504 if (!empty($this->mPendingRedirectIDs[$plfrom]))
505 $this->dieDebug('Invalid redirect IDs were found');
506
507 return $linkBatch;
508 }
509
510 /**
511 * Given an array of title strings, convert them into Title objects.
512 * This method validates access rights for the title,
513 * and appends normalization values to the output.
514 *
515 * @return LinkBatch of title objects.
516 */
517 private function processTitlesStrArray($titles) {
518
519 $linkBatch = new LinkBatch();
520
521 foreach ($titles as $titleString) {
522 $titleObj = Title :: newFromText($titleString);
523
524 // Validation
525 if (!$titleObj)
526 $this->dieUsage("bad title $titleString", 'invalidtitle');
527 if ($titleObj->getNamespace() < 0)
528 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
529 if (!$titleObj->userCanRead())
530 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
531
532 $linkBatch->addObj($titleObj);
533
534 // Make sure we remember the original title that was given to us
535 // This way the caller can correlate new titles with the originally requested,
536 // i.e. namespace is localized or capitalization is different
537 if ($titleString !== $titleObj->getPrefixedText()) {
538 $this->mNormalizedTitles[$titleString] = $titleObj->getPrefixedText();
539 }
540 }
541
542 return $linkBatch;
543 }
544
545 protected function getAllowedParams() {
546 return array (
547 'titles' => array (
548 ApiBase :: PARAM_ISMULTI => true
549 ),
550 'pageids' => array (
551 ApiBase :: PARAM_TYPE => 'integer',
552 ApiBase :: PARAM_ISMULTI => true
553 ),
554 'revids' => array (
555 ApiBase :: PARAM_TYPE => 'integer',
556 ApiBase :: PARAM_ISMULTI => true
557 )
558 );
559 }
560
561 protected function getParamDescription() {
562 return array (
563 'titles' => 'A list of titles to work on',
564 'pageids' => 'A list of page IDs to work on',
565 'revids' => 'A list of revision IDs to work on'
566 );
567 }
568
569 public function getVersion() {
570 return __CLASS__ . ': $Id$';
571 }
572 }
573 ?>