API: Prevent ApiQueryInfo from trying to set a continue value twice (which will fail...
[lhc/web/wiklou.git] / includes / api / ApiQueryInfo.php
1 <?php
2
3 /*
4 * Created on Sep 25, 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 * A query module to show basic page information.
33 *
34 * @ingroup API
35 */
36 class ApiQueryInfo extends ApiQueryBase {
37
38 public function __construct($query, $moduleName) {
39 parent :: __construct($query, $moduleName, 'in');
40 }
41
42 public function requestExtraData($pageSet) {
43 $pageSet->requestField('page_restrictions');
44 $pageSet->requestField('page_is_redirect');
45 $pageSet->requestField('page_is_new');
46 $pageSet->requestField('page_counter');
47 $pageSet->requestField('page_touched');
48 $pageSet->requestField('page_latest');
49 $pageSet->requestField('page_len');
50 }
51
52 protected function getTokenFunctions() {
53 // tokenname => function
54 // function prototype is func($pageid, $title)
55 // should return token or false
56
57 // Don't call the hooks twice
58 if(isset($this->tokenFunctions))
59 return $this->tokenFunctions;
60
61 // If we're in JSON callback mode, no tokens can be obtained
62 if(!is_null($this->getMain()->getRequest()->getVal('callback')))
63 return array();
64
65 $this->tokenFunctions = array(
66 'edit' => array( 'ApiQueryInfo', 'getEditToken' ),
67 'delete' => array( 'ApiQueryInfo', 'getDeleteToken' ),
68 'protect' => array( 'ApiQueryInfo', 'getProtectToken' ),
69 'move' => array( 'ApiQueryInfo', 'getMoveToken' ),
70 'block' => array( 'ApiQueryInfo', 'getBlockToken' ),
71 'unblock' => array( 'ApiQueryInfo', 'getUnblockToken' ),
72 'email' => array( 'ApiQueryInfo', 'getEmailToken' ),
73 'import' => array( 'ApiQueryInfo', 'getImportToken' ),
74 );
75 wfRunHooks('APIQueryInfoTokens', array(&$this->tokenFunctions));
76 return $this->tokenFunctions;
77 }
78
79 public static function getEditToken($pageid, $title)
80 {
81 // We could check for $title->userCan('edit') here,
82 // but that's too expensive for this purpose
83 global $wgUser;
84 if(!$wgUser->isAllowed('edit'))
85 return false;
86
87 // The edit token is always the same, let's exploit that
88 static $cachedEditToken = null;
89 if(!is_null($cachedEditToken))
90 return $cachedEditToken;
91
92 $cachedEditToken = $wgUser->editToken();
93 return $cachedEditToken;
94 }
95
96 public static function getDeleteToken($pageid, $title)
97 {
98 global $wgUser;
99 if(!$wgUser->isAllowed('delete'))
100 return false;
101
102 static $cachedDeleteToken = null;
103 if(!is_null($cachedDeleteToken))
104 return $cachedDeleteToken;
105
106 $cachedDeleteToken = $wgUser->editToken();
107 return $cachedDeleteToken;
108 }
109
110 public static function getProtectToken($pageid, $title)
111 {
112 global $wgUser;
113 if(!$wgUser->isAllowed('protect'))
114 return false;
115
116 static $cachedProtectToken = null;
117 if(!is_null($cachedProtectToken))
118 return $cachedProtectToken;
119
120 $cachedProtectToken = $wgUser->editToken();
121 return $cachedProtectToken;
122 }
123
124 public static function getMoveToken($pageid, $title)
125 {
126 global $wgUser;
127 if(!$wgUser->isAllowed('move'))
128 return false;
129
130 static $cachedMoveToken = null;
131 if(!is_null($cachedMoveToken))
132 return $cachedMoveToken;
133
134 $cachedMoveToken = $wgUser->editToken();
135 return $cachedMoveToken;
136 }
137
138 public static function getBlockToken($pageid, $title)
139 {
140 global $wgUser;
141 if(!$wgUser->isAllowed('block'))
142 return false;
143
144 static $cachedBlockToken = null;
145 if(!is_null($cachedBlockToken))
146 return $cachedBlockToken;
147
148 $cachedBlockToken = $wgUser->editToken();
149 return $cachedBlockToken;
150 }
151
152 public static function getUnblockToken($pageid, $title)
153 {
154 // Currently, this is exactly the same as the block token
155 return self::getBlockToken($pageid, $title);
156 }
157
158 public static function getEmailToken($pageid, $title)
159 {
160 global $wgUser;
161 if(!$wgUser->canSendEmail() || $wgUser->isBlockedFromEmailUser())
162 return false;
163
164 static $cachedEmailToken = null;
165 if(!is_null($cachedEmailToken))
166 return $cachedEmailToken;
167
168 $cachedEmailToken = $wgUser->editToken();
169 return $cachedEmailToken;
170 }
171
172 public static function getImportToken($pageid, $title)
173 {
174 global $wgUser;
175 if(!$wgUser->isAllowed('import'))
176 return false;
177
178 static $cachedImportToken = null;
179 if(!is_null($cachedImportToken))
180 return $cachedImportToken;
181
182 $cachedImportToken = $wgUser->editToken();
183 return $cachedImportToken;
184 }
185
186 public function execute() {
187
188 global $wgUser;
189
190 $params = $this->extractRequestParams();
191 $fld_protection = $fld_talkid = $fld_subjectid = $fld_url = $fld_readable = false;
192 if(!is_null($params['prop'])) {
193 $prop = array_flip($params['prop']);
194 $fld_protection = isset($prop['protection']);
195 $fld_talkid = isset($prop['talkid']);
196 $fld_subjectid = isset($prop['subjectid']);
197 $fld_url = isset($prop['url']);
198 $fld_readable = isset($prop['readable']);
199 }
200
201 $pageSet = $this->getPageSet();
202 $titles = $pageSet->getGoodTitles();
203 $missing = $pageSet->getMissingTitles();
204 $result = $this->getResult();
205
206 $pageRestrictions = $pageSet->getCustomField('page_restrictions');
207 $pageIsRedir = $pageSet->getCustomField('page_is_redirect');
208 $pageIsNew = $pageSet->getCustomField('page_is_new');
209 $pageCounter = $pageSet->getCustomField('page_counter');
210 $pageTouched = $pageSet->getCustomField('page_touched');
211 $pageLatest = $pageSet->getCustomField('page_latest');
212 $pageLength = $pageSet->getCustomField('page_len');
213
214 $db = $this->getDB();
215 if ($fld_protection && count($titles)) {
216 $this->addTables('page_restrictions');
217 $this->addFields(array('pr_page', 'pr_type', 'pr_level', 'pr_expiry', 'pr_cascade'));
218 $this->addWhereFld('pr_page', array_keys($titles));
219
220 $res = $this->select(__METHOD__);
221 while($row = $db->fetchObject($res)) {
222 $a = array(
223 'type' => $row->pr_type,
224 'level' => $row->pr_level,
225 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 )
226 );
227 if($row->pr_cascade)
228 $a['cascade'] = '';
229 $protections[$row->pr_page][] = $a;
230
231 # Also check old restrictions
232 if($pageRestrictions[$row->pr_page]) {
233 foreach(explode(':', trim($pageRestrictions[$pageid])) as $restrict) {
234 $temp = explode('=', trim($restrict));
235 if(count($temp) == 1) {
236 // old old format should be treated as edit/move restriction
237 $restriction = trim( $temp[0] );
238 if($restriction == '')
239 continue;
240 $protections[$row->pr_page][] = array(
241 'type' => 'edit',
242 'level' => $restriction,
243 'expiry' => 'infinity',
244 );
245 $protections[$row->pr_page][] = array(
246 'type' => 'move',
247 'level' => $restriction,
248 'expiry' => 'infinity',
249 );
250 } else {
251 $restriction = trim( $temp[1] );
252 if($restriction == '')
253 continue;
254 $protections[$row->pr_page][] = array(
255 'type' => $temp[0],
256 'level' => $restriction,
257 'expiry' => 'infinity',
258 );
259 }
260 }
261 }
262 }
263 $db->freeResult($res);
264
265 $imageIds = array();
266 foreach ($titles as $id => $title)
267 if ($title->getNamespace() == NS_FILE)
268 $imageIds[] = $id;
269 // To avoid code duplication
270 $cascadeTypes = array(
271 array(
272 'prefix' => 'tl',
273 'table' => 'templatelinks',
274 'ns' => 'tl_namespace',
275 'title' => 'tl_title',
276 'ids' => array_diff(array_keys($titles), $imageIds)
277 ),
278 array(
279 'prefix' => 'il',
280 'table' => 'imagelinks',
281 'ns' => NS_FILE,
282 'title' => 'il_to',
283 'ids' => $imageIds
284 )
285 );
286
287 foreach ($cascadeTypes as $type)
288 {
289 if (count($type['ids']) != 0) {
290 $this->resetQueryParams();
291 $this->addTables(array('page_restrictions', $type['table']));
292 $this->addTables('page', 'page_source');
293 $this->addTables('page', 'page_target');
294 $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
295 'page_target.page_id AS page_target_id',
296 'page_source.page_namespace AS page_source_namespace',
297 'page_source.page_title AS page_source_title'));
298 $this->addWhere(array("{$type['prefix']}_from = pr_page",
299 'page_target.page_namespace = '.$type['ns'],
300 'page_target.page_title = '.$type['title'],
301 'page_source.page_id = pr_page'
302 ));
303 $this->addWhereFld('pr_cascade', 1);
304 $this->addWhereFld('page_target.page_id', $type['ids']);
305
306 $res = $this->select(__METHOD__);
307 while($row = $db->fetchObject($res)) {
308 $source = Title::makeTitle($row->page_source_namespace, $row->page_source_title);
309 $a = array(
310 'type' => $row->pr_type,
311 'level' => $row->pr_level,
312 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 ),
313 'source' => $source->getPrefixedText()
314 );
315 $protections[$row->page_target_id][] = $a;
316 }
317 $db->freeResult($res);
318 }
319 }
320 }
321
322 // We don't need to check for pt stuff if there are no nonexistent titles
323 if($fld_protection && count($missing))
324 {
325 $this->resetQueryParams();
326 // Construct a custom WHERE clause that matches all titles in $missing
327 $lb = new LinkBatch($missing);
328 $this->addTables('protected_titles');
329 $this->addFields(array('pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry'));
330 $this->addWhere($lb->constructSet('pt', $db));
331 $res = $this->select(__METHOD__);
332 $prottitles = array();
333 while($row = $db->fetchObject($res)) {
334 $prottitles[$row->pt_namespace][$row->pt_title][] = array(
335 'type' => 'create',
336 'level' => $row->pt_create_perm,
337 'expiry' => Block::decodeExpiry($row->pt_expiry, TS_ISO_8601)
338 );
339 }
340 $db->freeResult($res);
341
342 $images = array();
343 $others = array();
344 foreach ($missing as $title)
345 if ($title->getNamespace() == NS_FILE)
346 $images[] = $title->getDBKey();
347 else
348 $others[] = $title;
349
350 if (count($others) != 0) {
351 $lb = new LinkBatch($others);
352 $this->resetQueryParams();
353 $this->addTables(array('page_restrictions', 'page', 'templatelinks'));
354 $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
355 'page_title', 'page_namespace',
356 'tl_title', 'tl_namespace'));
357 $this->addWhere($lb->constructSet('tl', $db));
358 $this->addWhere('pr_page = page_id');
359 $this->addWhere('pr_page = tl_from');
360 $this->addWhereFld('pr_cascade', 1);
361
362 $res = $this->select(__METHOD__);
363 while($row = $db->fetchObject($res)) {
364 $source = Title::makeTitle($row->page_namespace, $row->page_title);
365 $a = array(
366 'type' => $row->pr_type,
367 'level' => $row->pr_level,
368 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 ),
369 'source' => $source->getPrefixedText()
370 );
371 $prottitles[$row->tl_namespace][$row->tl_title][] = $a;
372 }
373 $db->freeResult($res);
374 }
375
376 if (count($images) != 0) {
377 $this->resetQueryParams();
378 $this->addTables(array('page_restrictions', 'page', 'imagelinks'));
379 $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
380 'page_title', 'page_namespace', 'il_to'));
381 $this->addWhere('pr_page = page_id');
382 $this->addWhere('pr_page = il_from');
383 $this->addWhereFld('pr_cascade', 1);
384 $this->addWhereFld('il_to', $images);
385
386 $res = $this->select(__METHOD__);
387 while($row = $db->fetchObject($res)) {
388 $source = Title::makeTitle($row->page_namespace, $row->page_title);
389 $a = array(
390 'type' => $row->pr_type,
391 'level' => $row->pr_level,
392 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 ),
393 'source' => $source->getPrefixedText()
394 );
395 $prottitles[NS_FILE][$row->il_to][] = $a;
396 }
397 $db->freeResult($res);
398 }
399 }
400
401 // Run the talkid/subjectid query
402 if($fld_talkid || $fld_subjectid)
403 {
404 $talktitles = $subjecttitles =
405 $talkids = $subjectids = array();
406 $everything = array_merge($titles, $missing);
407 foreach($everything as $t)
408 {
409 if(MWNamespace::isTalk($t->getNamespace()))
410 {
411 if($fld_subjectid)
412 $subjecttitles[] = $t->getSubjectPage();
413 }
414 else if($fld_talkid)
415 $talktitles[] = $t->getTalkPage();
416 }
417 if(count($talktitles) || count($subjecttitles))
418 {
419 // Construct a custom WHERE clause that matches
420 // all titles in $talktitles and $subjecttitles
421 $lb = new LinkBatch(array_merge($talktitles, $subjecttitles));
422 $this->resetQueryParams();
423 $this->addTables('page');
424 $this->addFields(array('page_title', 'page_namespace', 'page_id'));
425 $this->addWhere($lb->constructSet('page', $db));
426 $res = $this->select(__METHOD__);
427 while($row = $db->fetchObject($res))
428 {
429 if(MWNamespace::isTalk($row->page_namespace))
430 $talkids[MWNamespace::getSubject($row->page_namespace)][$row->page_title] = $row->page_id;
431 else
432 $subjectids[MWNamespace::getTalk($row->page_namespace)][$row->page_title] = $row->page_id;
433 }
434 }
435 }
436
437 $count = 0;
438 $fit = true;
439 ksort($titles); // Ensure they're always in the same order
440 foreach ( $titles as $pageid => $title ) {
441 $count++;
442 if(!is_null($params['continue']))
443 if($count < $params['continue'])
444 continue;
445 $pageInfo = array (
446 'touched' => wfTimestamp(TS_ISO_8601, $pageTouched[$pageid]),
447 'lastrevid' => intval($pageLatest[$pageid]),
448 'counter' => intval($pageCounter[$pageid]),
449 'length' => intval($pageLength[$pageid]),
450 );
451
452 if ($pageIsRedir[$pageid])
453 $pageInfo['redirect'] = '';
454
455 if ($pageIsNew[$pageid])
456 $pageInfo['new'] = '';
457
458 if (!is_null($params['token'])) {
459 $tokenFunctions = $this->getTokenFunctions();
460 $pageInfo['starttimestamp'] = wfTimestamp(TS_ISO_8601, time());
461 foreach($params['token'] as $t)
462 {
463 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
464 if($val === false)
465 $this->setWarning("Action '$t' is not allowed for the current user");
466 else
467 $pageInfo[$t . 'token'] = $val;
468 }
469 }
470
471 if($fld_protection) {
472 $pageInfo['protection'] = array();
473 if (isset($protections[$pageid])) {
474 $pageInfo['protection'] = $protections[$pageid];
475 $result->setIndexedTagName($pageInfo['protection'], 'pr');
476 }
477 }
478 if($fld_talkid && isset($talkids[$title->getNamespace()][$title->getDBKey()]))
479 $pageInfo['talkid'] = $talkids[$title->getNamespace()][$title->getDBKey()];
480 if($fld_subjectid && isset($subjectids[$title->getNamespace()][$title->getDBKey()]))
481 $pageInfo['subjectid'] = $subjectids[$title->getNamespace()][$title->getDBKey()];
482 if($fld_url) {
483 $pageInfo['fullurl'] = $title->getFullURL();
484 $pageInfo['editurl'] = $title->getFullURL('action=edit');
485 }
486 if($fld_readable)
487 if($title->userCanRead())
488 $pageInfo['readable'] = '';
489
490 $fit = $result->addValue(array (
491 'query',
492 'pages'
493 ), $pageid, $pageInfo);
494 if(!$fit)
495 {
496 $this->setContinueEnumParameter('continue', $count);
497 break;
498 }
499 }
500
501 // Get properties for missing titles if requested
502 if($fit && (!is_null($params['token']) || $fld_protection ||
503 $fld_talkid || $fld_subjectid || $fld_url ||
504 $fld_readable))
505 {
506 foreach($missing as $pageid => $title) {
507 $count++;
508 if(!is_null($params['continue']))
509 if($count < $params['continue'])
510 continue;
511 $r = array();
512 if(!is_null($params['token']))
513 {
514 $tokenFunctions = $this->getTokenFunctions();
515 $res['query']['pages'][$pageid]['starttimestamp'] = wfTimestamp(TS_ISO_8601, time());
516 foreach($params['token'] as $t)
517 {
518 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
519 if($val === false)
520 $this->setWarning("Action '$t' is not allowed for the current user");
521 else
522 $r[$t . 'token'] = $val;
523 }
524 }
525 if($fld_protection)
526 {
527 // Apparently the XML formatting code doesn't like array(null)
528 // This is painful to fix, so we'll just work around it
529 if(isset($prottitles[$title->getNamespace()][$title->getDBkey()]))
530 $val = $prottitles[$title->getNamespace()][$title->getDBkey()];
531 else
532 $val = array();
533 $result->setIndexedTagName($val, 'pr');
534 $r['protection'] = $val;
535 }
536 if($fld_talkid && isset($talkids[$title->getNamespace()][$title->getDbKey()]))
537 $r['talkid'] = $talkids[$title->getNamespace()][$title->getDbKey()];
538 if($fld_subjectid && isset($subjectids[$title->getNamespace()][$title->getDbKey()]))
539 $r['subjectid'] = $subjectids[$title->getNamespace()][$title->getDbKey()];
540 if($fld_url)
541 {
542 $r['fullurl'] = $title->getFullURL();
543 $r['editurl'] = $title->getFullURL('action=edit');
544 }
545 if($fld_readable)
546 if($title->userCanRead())
547 $r['readable'] = '';
548 $fit = $result->addValue(array('query', 'pages'), $pageid, $r);
549 if(!$fit)
550 {
551 $this->setContinueEnumParameter('continue', $count);
552 break;
553 }
554 }
555 }
556 }
557
558 public function getAllowedParams() {
559 return array (
560 'prop' => array (
561 ApiBase :: PARAM_DFLT => NULL,
562 ApiBase :: PARAM_ISMULTI => true,
563 ApiBase :: PARAM_TYPE => array (
564 'protection',
565 'talkid',
566 'subjectid',
567 'url',
568 'readable',
569 )),
570 'token' => array (
571 ApiBase :: PARAM_DFLT => NULL,
572 ApiBase :: PARAM_ISMULTI => true,
573 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions())
574 ),
575 'continue' => null,
576 );
577 }
578
579 public function getParamDescription() {
580 return array (
581 'prop' => array (
582 'Which additional properties to get:',
583 ' protection - List the protection level of each page',
584 ' talkid - The page ID of the talk page for each non-talk page',
585 ' subjectid - The page ID of the parent page for each talk page'
586 ),
587 'token' => 'Request a token to perform a data-modifying action on a page',
588 'continue' => 'When more results are available, use this to continue',
589 );
590 }
591
592
593 public function getDescription() {
594 return 'Get basic page information such as namespace, title, last touched date, ...';
595 }
596
597 protected function getExamples() {
598 return array (
599 'api.php?action=query&prop=info&titles=Main%20Page',
600 'api.php?action=query&prop=info&inprop=protection&titles=Main%20Page'
601 );
602 }
603
604 public function getVersion() {
605 return __CLASS__ . ': $Id$';
606 }
607 }