API: Fix up r46825:
[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 foreach ( $titles as $pageid => $title ) {
439 $count++;
440 if(!is_null($params['continue']))
441 if($count < $params['continue'])
442 continue;
443 $pageInfo = array (
444 'touched' => wfTimestamp(TS_ISO_8601, $pageTouched[$pageid]),
445 'lastrevid' => intval($pageLatest[$pageid]),
446 'counter' => intval($pageCounter[$pageid]),
447 'length' => intval($pageLength[$pageid]),
448 );
449
450 if ($pageIsRedir[$pageid])
451 $pageInfo['redirect'] = '';
452
453 if ($pageIsNew[$pageid])
454 $pageInfo['new'] = '';
455
456 if (!is_null($params['token'])) {
457 $tokenFunctions = $this->getTokenFunctions();
458 $pageInfo['starttimestamp'] = wfTimestamp(TS_ISO_8601, time());
459 foreach($params['token'] as $t)
460 {
461 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
462 if($val === false)
463 $this->setWarning("Action '$t' is not allowed for the current user");
464 else
465 $pageInfo[$t . 'token'] = $val;
466 }
467 }
468
469 if($fld_protection) {
470 $pageInfo['protection'] = array();
471 if (isset($protections[$pageid])) {
472 $pageInfo['protection'] = $protections[$pageid];
473 $result->setIndexedTagName($pageInfo['protection'], 'pr');
474 }
475 }
476 if($fld_talkid && isset($talkids[$title->getNamespace()][$title->getDBKey()]))
477 $pageInfo['talkid'] = $talkids[$title->getNamespace()][$title->getDBKey()];
478 if($fld_subjectid && isset($subjectids[$title->getNamespace()][$title->getDBKey()]))
479 $pageInfo['subjectid'] = $subjectids[$title->getNamespace()][$title->getDBKey()];
480 if($fld_url) {
481 $pageInfo['fullurl'] = $title->getFullURL();
482 $pageInfo['editurl'] = $title->getFullURL('action=edit');
483 }
484 if($fld_readable)
485 if($title->userCanRead())
486 $pageInfo['readable'] = '';
487
488 $fit = $result->addValue(array (
489 'query',
490 'pages'
491 ), $pageid, $pageInfo);
492 if(!$fit)
493 {
494 $this->setContinueEnumParameter('continue', $count);
495 break;
496 }
497 }
498
499 // Get properties for missing titles if requested
500 if(!is_null($params['token']) || $fld_protection || $fld_talkid || $fld_subjectid ||
501 $fld_url || $fld_readable)
502 {
503 foreach($missing as $pageid => $title) {
504 $count++;
505 if(!is_null($params['continue']))
506 if($count < $params['continue'])
507 continue;
508 $fit = true;
509 if(!is_null($params['token']))
510 {
511 $tokenFunctions = $this->getTokenFunctions();
512 $res['query']['pages'][$pageid]['starttimestamp'] = wfTimestamp(TS_ISO_8601, time());
513 foreach($params['token'] as $t)
514 {
515 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
516 if($val === false)
517 $this->setWarning("Action '$t' is not allowed for the current user");
518 else
519 $fit = $result->addValue(
520 array('query', 'pages', $pageid),
521 $t . 'token', $val);
522 }
523 }
524 if($fld_protection && $fit)
525 {
526 // Apparently the XML formatting code doesn't like array(null)
527 // This is painful to fix, so we'll just work around it
528 if(isset($prottitles[$title->getNamespace()][$title->getDBkey()]))
529 $val = $prottitles[$title->getNamespace()][$title->getDBkey()];
530 else
531 $val = array();
532 $result->setIndexedTagName($val, 'pr');
533 $fit = $result->addValue(
534 array('query', 'pages', $pageid),
535 'protection', $val);
536 }
537 if($fld_talkid && isset($talkids[$title->getNamespace()][$title->getDbKey()]) && $fit)
538 $fit = $result->addValue(array('query', 'pages', $pageid), 'talkid',
539 $talkids[$title->getNamespace()][$title->getDbKey()]);
540 if($fld_subjectid && isset($subjectids[$title->getNamespace()][$title->getDbKey()]) && $fit)
541 $fit = $result->addValue(array('query', 'pages', $pageid), 'subjectid',
542 $subjectids[$title->getNamespace()][$title->getDbKey()]);
543 if($fld_url && $fit) {
544 $fit = $result->addValue(array('query', 'pages', $pageid), 'fullurl',
545 $title->getFullURL());
546 if($fit)
547 $fit = $result->addValue(array('query', 'pages', $pageid), 'editurl',
548 $title->getFullURL('action=edit'));
549 }
550 if($fld_readable && $fit)
551 if($title->userCanRead())
552 $fit = $result->addValue(array('query', 'pages', $pageid), 'readable', '');
553 if(!$fit)
554 {
555 $this->setContinueEnumParameter('continue', $count);
556 break;
557 }
558 }
559 }
560 }
561
562 public function getAllowedParams() {
563 return array (
564 'prop' => array (
565 ApiBase :: PARAM_DFLT => NULL,
566 ApiBase :: PARAM_ISMULTI => true,
567 ApiBase :: PARAM_TYPE => array (
568 'protection',
569 'talkid',
570 'subjectid',
571 'url',
572 'readable',
573 )),
574 'token' => array (
575 ApiBase :: PARAM_DFLT => NULL,
576 ApiBase :: PARAM_ISMULTI => true,
577 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions())
578 ),
579 'continue' => null,
580 );
581 }
582
583 public function getParamDescription() {
584 return array (
585 'prop' => array (
586 'Which additional properties to get:',
587 ' protection - List the protection level of each page',
588 ' talkid - The page ID of the talk page for each non-talk page',
589 ' subjectid - The page ID of the parent page for each talk page'
590 ),
591 'token' => 'Request a token to perform a data-modifying action on a page',
592 'continue' => 'When more results are available, use this to continue',
593 );
594 }
595
596
597 public function getDescription() {
598 return 'Get basic page information such as namespace, title, last touched date, ...';
599 }
600
601 protected function getExamples() {
602 return array (
603 'api.php?action=query&prop=info&titles=Main%20Page',
604 'api.php?action=query&prop=info&inprop=protection&titles=Main%20Page'
605 );
606 }
607
608 public function getVersion() {
609 return __CLASS__ . ': $Id$';
610 }
611 }