(no commit message)
[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;
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_talkid = isset($prop['talkid']);
199 $this->fld_subjectid = isset($prop['subjectid']);
200 $this->fld_url = isset($prop['url']);
201 $this->fld_readable = isset($prop['readable']);
202 }
203
204 $pageSet = $this->getPageSet();
205 $this->titles = $pageSet->getGoodTitles();
206 $this->missing = $pageSet->getMissingTitles();
207 $this->everything = array_merge($this->titles, $this->missing);
208 $result = $this->getResult();
209
210 $this->pageRestrictions = $pageSet->getCustomField('page_restrictions');
211 $this->pageIsRedir = $pageSet->getCustomField('page_is_redirect');
212 $this->pageIsNew = $pageSet->getCustomField('page_is_new');
213 $this->pageCounter = $pageSet->getCustomField('page_counter');
214 $this->pageTouched = $pageSet->getCustomField('page_touched');
215 $this->pageLatest = $pageSet->getCustomField('page_latest');
216 $this->pageLength = $pageSet->getCustomField('page_len');
217
218 $db = $this->getDB();
219 // Get protection info if requested
220 if ($this->fld_protection)
221 $this->getProtectionInfo();
222
223 // Run the talkid/subjectid query if requested
224 if($this->fld_talkid || $this->fld_subjectid)
225 $this->getTSIDs();
226
227 $count = 0;
228 ksort($this->everything); // Ensure they're always in the same order
229 foreach($this->everything as $pageid => $title) {
230 $count++;
231 if(!is_null($params['continue']))
232 if($count < $params['continue'])
233 continue;
234 $pageInfo = $this->extractPageInfo($pageid, $title);
235 $fit = $result->addValue(array (
236 'query',
237 'pages'
238 ), $pageid, $pageInfo);
239 if(!$fit)
240 {
241 $this->setContinueEnumParameter('continue', $count);
242 break;
243 }
244 }
245 }
246
247 /**
248 * Get a result array with information about a title
249 * @param $pageid int Page ID (negative for missing titles)
250 * @param $title Title object
251 * @return array
252 */
253 private function extractPageInfo($pageid, $title)
254 {
255 $pageInfo = array();
256 if($title->exists())
257 {
258 $pageInfo['touched'] = wfTimestamp(TS_ISO_8601, $this->pageTouched[$pageid]);
259 $pageInfo['lastrevid'] = intval($this->pageLatest[$pageid]);
260 $pageInfo['counter'] = intval($this->pageCounter[$pageid]);
261 $pageInfo['length'] = intval($this->pageLength[$pageid]);
262 if ($this->pageIsRedir[$pageid])
263 $pageInfo['redirect'] = '';
264 if ($this->pageIsNew[$pageid])
265 $pageInfo['new'] = '';
266 }
267
268 if (!is_null($this->params['token'])) {
269 $tokenFunctions = $this->getTokenFunctions();
270 $pageInfo['starttimestamp'] = wfTimestamp(TS_ISO_8601, time());
271 foreach($this->params['token'] as $t)
272 {
273 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
274 if($val === false)
275 $this->setWarning("Action '$t' is not allowed for the current user");
276 else
277 $pageInfo[$t . 'token'] = $val;
278 }
279 }
280
281 if($this->fld_protection) {
282 $pageInfo['protection'] = array();
283 if (isset($this->protections[$title->getNamespace()][$title->getDBkey()]))
284 $pageInfo['protection'] =
285 $this->protections[$title->getNamespace()][$title->getDBkey()];
286 $result->setIndexedTagName($pageInfo['protection'], 'pr');
287 }
288 if($this->fld_talkid && isset($this->talkids[$title->getNamespace()][$title->getDBKey()]))
289 $pageInfo['talkid'] = $this->talkids[$title->getNamespace()][$title->getDBKey()];
290 if($this->fld_subjectid && isset($this->subjectids[$title->getNamespace()][$title->getDBKey()]))
291 $pageInfo['subjectid'] = $this->subjectids[$title->getNamespace()][$title->getDBKey()];
292 if($this->fld_url) {
293 $pageInfo['fullurl'] = $title->getFullURL();
294 $pageInfo['editurl'] = $title->getFullURL('action=edit');
295 }
296 if($this->fld_readable)
297 if($title->userCanRead())
298 $pageInfo['readable'] = '';
299 return $pageInfo;
300 }
301
302 /**
303 * Get information about protections and put it in $protections
304 */
305 private function getProtectionInfo()
306 {
307 $this->protections = array();
308 $db = $this->getDB();
309
310 // Get normal protections for existing titles
311 $this->addTables('page_restrictions', 'page');
312 $this->addWhere('page_id=pr_page');
313 $this->addFields(array('pr_page', 'pr_type', 'pr_level',
314 'pr_expiry', 'pr_cascade', 'page_namespace',
315 'page_title'));
316 $this->addWhereFld('pr_page', array_keys($this->titles));
317
318 $res = $this->select(__METHOD__);
319 while($row = $db->fetchObject($res)) {
320 $a = array(
321 'type' => $row->pr_type,
322 'level' => $row->pr_level,
323 'expiry' => Block::decodeExpiry($row->pr_expiry, TS_ISO_8601)
324 );
325 if($row->pr_cascade)
326 $a['cascade'] = '';
327 $this->protections[$row->page_namespace][$row->page_title][] = $a;
328
329 # Also check old restrictions
330 if($pageRestrictions[$row->pr_page]) {
331 foreach(explode(':', trim($this->pageRestrictions[$row->pr_page])) as $restrict) {
332 $temp = explode('=', trim($restrict));
333 if(count($temp) == 1) {
334 // old old format should be treated as edit/move restriction
335 $restriction = trim( $temp[0] );
336
337 if($restriction == '')
338 continue;
339 $this->protections[$row->page_namespace][$row->page_title][] = array(
340 'type' => 'edit',
341 'level' => $restriction,
342 'expiry' => 'infinity',
343 );
344 $this->protections[$row->page_namespace][$row->page_title][] = array(
345 'type' => 'move',
346 'level' => $restriction,
347 'expiry' => 'infinity',
348 );
349 } else {
350 $restriction = trim($temp[1]);
351 if($restriction == '')
352 continue;
353 $this->protections[$row->page_namespace][$row->page_title][] = array(
354 'type' => $temp[0],
355 'level' => $restriction,
356 'expiry' => 'infinity',
357 );
358 }
359 }
360 }
361 }
362 $db->freeResult($res);
363
364 // Get protections for missing titles
365 $this->resetQueryParams();
366 $lb = new LinkBatch($this->missing);
367 $this->addTables('protected_titles');
368 $this->addFields(array('pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry'));
369 $this->addWhere($lb->constructSet('pt', $db));
370 $res = $this->select(__METHOD__);
371 while($row = $db->fetchObject($res)) {
372 $this->protections[$row->pt_namespace][$row->pt_title][] = array(
373 'type' => 'create',
374 'level' => $row->pt_create_perm,
375 'expiry' => Block::decodeExpiry($row->pt_expiry, TS_ISO_8601)
376 );
377 }
378 $db->freeResult($res);
379
380 // Cascading protections
381 $images = $others = array();
382 foreach ($this->everything as $title)
383 if ($title->getNamespace() == NS_FILE)
384 $images[] = $title->getDBKey();
385 else
386 $others[] = $title;
387
388 if (count($others)) {
389 // Non-images: check templatelinks
390 $lb = new LinkBatch($others);
391 $this->resetQueryParams();
392 $this->addTables(array('page_restrictions', 'page', 'templatelinks'));
393 $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
394 'page_title', 'page_namespace',
395 'tl_title', 'tl_namespace'));
396 $this->addWhere($lb->constructSet('tl', $db));
397 $this->addWhere('pr_page = page_id');
398 $this->addWhere('pr_page = tl_from');
399 $this->addWhereFld('pr_cascade', 1);
400
401 $res = $this->select(__METHOD__);
402 while($row = $db->fetchObject($res)) {
403 $source = Title::makeTitle($row->page_namespace, $row->page_title);
404 $this->protections[$row->pt_namespace][$row->pt_title][] = array(
405 'type' => $row->pr_type,
406 'level' => $row->pr_level,
407 'expiry' => Block::decodeExpiry($row->pr_expiry, TS_ISO_8601),
408 'source' => $source->getPrefixedText()
409 );
410 }
411 $db->freeResult($res);
412 }
413
414 if (count($images)) {
415 // Images: check imagelinks
416 $this->resetQueryParams();
417 $this->addTables(array('page_restrictions', 'page', 'imagelinks'));
418 $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
419 'page_title', 'page_namespace', 'il_to'));
420 $this->addWhere('pr_page = page_id');
421 $this->addWhere('pr_page = il_from');
422 $this->addWhereFld('pr_cascade', 1);
423 $this->addWhereFld('il_to', $images);
424
425 $res = $this->select(__METHOD__);
426 while($row = $db->fetchObject($res)) {
427 $source = Title::makeTitle($row->page_namespace, $row->page_title);
428 $this->protections[NS_FILE][$row->il_to][] = array(
429 'type' => $row->pr_type,
430 'level' => $row->pr_level,
431 'expiry' => Block::decodeExpiry($row->pr_expiry, TS_ISO_8601),
432 'source' => $source->getPrefixedText()
433 );
434 }
435 $db->freeResult($res);
436 }
437 }
438
439 /**
440 * Get talk page IDs (if requested) and subject page IDs (if requested)
441 * and put them in $talkids and $subjectids
442 */
443 private function getTSIDs()
444 {
445 $getTitles = $this->talkids = $this->subjectids = array();
446 $db = $this->getDB();
447 foreach($this->everything as $t)
448 {
449 if(MWNamespace::isTalk($t->getNamespace()))
450 {
451 if($this->fld_subjectid)
452 $getTitles[] = $t->getSubjectPage();
453 }
454 else if($this->fld_talkid)
455 $getTitles[] = $t->getTalkPage();
456 }
457 if(!count($getTitles))
458 return;
459
460 // Construct a custom WHERE clause that matches
461 // all titles in $getTitles
462 $lb = new LinkBatch($getTitles);
463 $this->resetQueryParams();
464 $this->addTables('page');
465 $this->addFields(array('page_title', 'page_namespace', 'page_id'));
466 $this->addWhere($lb->constructSet('page', $db));
467 $res = $this->select(__METHOD__);
468 while($row = $db->fetchObject($res))
469 {
470 if(MWNamespace::isTalk($row->page_namespace))
471 $this->talkids[MWNamespace::getSubject($row->page_namespace)][$row->page_title] =
472 $row->page_id;
473 else
474 $this->subjectids[MWNamespace::getTalk($row->page_namespace)][$row->page_title] =
475 $row->page_id;
476 }
477 }
478
479 public function getAllowedParams() {
480 return array (
481 'prop' => array (
482 ApiBase :: PARAM_DFLT => NULL,
483 ApiBase :: PARAM_ISMULTI => true,
484 ApiBase :: PARAM_TYPE => array (
485 'protection',
486 'talkid',
487 'subjectid',
488 'url',
489 'readable',
490 )),
491 'token' => array (
492 ApiBase :: PARAM_DFLT => NULL,
493 ApiBase :: PARAM_ISMULTI => true,
494 ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions())
495 ),
496 'continue' => null,
497 );
498 }
499
500 public function getParamDescription() {
501 return array (
502 'prop' => array (
503 'Which additional properties to get:',
504 ' protection - List the protection level of each page',
505 ' talkid - The page ID of the talk page for each non-talk page',
506 ' subjectid - The page ID of the parent page for each talk page'
507 ),
508 'token' => 'Request a token to perform a data-modifying action on a page',
509 'continue' => 'When more results are available, use this to continue',
510 );
511 }
512
513 public function getDescription() {
514 return 'Get basic page information such as namespace, title, last touched date, ...';
515 }
516
517 protected function getExamples() {
518 return array (
519 'api.php?action=query&prop=info&titles=Main%20Page',
520 'api.php?action=query&prop=info&inprop=protection&titles=Main%20Page'
521 );
522 }
523
524 public function getVersion() {
525 return __CLASS__ . ': $Id$';
526 }
527 }