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