4 * Created on Sep 25, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiQueryBase.php');
32 * A query module to show basic page information.
36 class ApiQueryInfo
extends ApiQueryBase
{
38 public function __construct($query, $moduleName) {
39 parent
:: __construct($query, $moduleName, 'in');
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');
52 protected function getTokenFunctions() {
53 // tokenname => function
54 // function prototype is func($pageid, $title)
55 // should return token or false
57 // Don't call the hooks twice
58 if(isset($this->tokenFunctions
))
59 return $this->tokenFunctions
;
61 // If we're in JSON callback mode, no tokens can be obtained
62 if(!is_null($this->getMain()->getRequest()->getVal('callback')))
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' ),
75 wfRunHooks('APIQueryInfoTokens', array(&$this->tokenFunctions
));
76 return $this->tokenFunctions
;
79 public static function getEditToken($pageid, $title)
81 // We could check for $title->userCan('edit') here,
82 // but that's too expensive for this purpose
84 if(!$wgUser->isAllowed('edit'))
87 // The edit token is always the same, let's exploit that
88 static $cachedEditToken = null;
89 if(!is_null($cachedEditToken))
90 return $cachedEditToken;
92 $cachedEditToken = $wgUser->editToken();
93 return $cachedEditToken;
96 public static function getDeleteToken($pageid, $title)
99 if(!$wgUser->isAllowed('delete'))
102 static $cachedDeleteToken = null;
103 if(!is_null($cachedDeleteToken))
104 return $cachedDeleteToken;
106 $cachedDeleteToken = $wgUser->editToken();
107 return $cachedDeleteToken;
110 public static function getProtectToken($pageid, $title)
113 if(!$wgUser->isAllowed('protect'))
116 static $cachedProtectToken = null;
117 if(!is_null($cachedProtectToken))
118 return $cachedProtectToken;
120 $cachedProtectToken = $wgUser->editToken();
121 return $cachedProtectToken;
124 public static function getMoveToken($pageid, $title)
127 if(!$wgUser->isAllowed('move'))
130 static $cachedMoveToken = null;
131 if(!is_null($cachedMoveToken))
132 return $cachedMoveToken;
134 $cachedMoveToken = $wgUser->editToken();
135 return $cachedMoveToken;
138 public static function getBlockToken($pageid, $title)
141 if(!$wgUser->isAllowed('block'))
144 static $cachedBlockToken = null;
145 if(!is_null($cachedBlockToken))
146 return $cachedBlockToken;
148 $cachedBlockToken = $wgUser->editToken();
149 return $cachedBlockToken;
152 public static function getUnblockToken($pageid, $title)
154 // Currently, this is exactly the same as the block token
155 return self
::getBlockToken($pageid, $title);
158 public static function getEmailToken($pageid, $title)
161 if(!$wgUser->canSendEmail() ||
$wgUser->isBlockedFromEmailUser())
164 static $cachedEmailToken = null;
165 if(!is_null($cachedEmailToken))
166 return $cachedEmailToken;
168 $cachedEmailToken = $wgUser->editToken();
169 return $cachedEmailToken;
172 public static function getImportToken($pageid, $title)
175 if(!$wgUser->isAllowed('import'))
178 static $cachedImportToken = null;
179 if(!is_null($cachedImportToken))
180 return $cachedImportToken;
182 $cachedImportToken = $wgUser->editToken();
183 return $cachedImportToken;
186 public function execute() {
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']);
201 $pageSet = $this->getPageSet();
202 $titles = $pageSet->getGoodTitles();
203 $missing = $pageSet->getMissingTitles();
204 $result = $this->getResult();
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');
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));
220 $res = $this->select(__METHOD__
);
221 while($row = $db->fetchObject($res)) {
223 'type' => $row->pr_type
,
224 'level' => $row->pr_level
,
225 'expiry' => Block
::decodeExpiry( $row->pr_expiry
, TS_ISO_8601
)
229 $protections[$row->pr_page
][] = $a;
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 == '')
240 $protections[$row->pr_page
][] = array(
242 'level' => $restriction,
243 'expiry' => 'infinity',
245 $protections[$row->pr_page
][] = array(
247 'level' => $restriction,
248 'expiry' => 'infinity',
251 $restriction = trim( $temp[1] );
252 if($restriction == '')
254 $protections[$row->pr_page
][] = array(
256 'level' => $restriction,
257 'expiry' => 'infinity',
263 $db->freeResult($res);
266 foreach ($titles as $id => $title)
267 if ($title->getNamespace() == NS_FILE
)
269 // To avoid code duplication
270 $cascadeTypes = array(
273 'table' => 'templatelinks',
274 'ns' => 'tl_namespace',
275 'title' => 'tl_title',
276 'ids' => array_diff(array_keys($titles), $imageIds)
280 'table' => 'imagelinks',
287 foreach ($cascadeTypes as $type)
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'
303 $this->addWhereFld('pr_cascade', 1);
304 $this->addWhereFld('page_target.page_id', $type['ids']);
306 $res = $this->select(__METHOD__
);
307 while($row = $db->fetchObject($res)) {
308 $source = Title
::makeTitle($row->page_source_namespace
, $row->page_source_title
);
310 'type' => $row->pr_type
,
311 'level' => $row->pr_level
,
312 'expiry' => Block
::decodeExpiry( $row->pr_expiry
, TS_ISO_8601
),
313 'source' => $source->getPrefixedText()
315 $protections[$row->page_target_id
][] = $a;
317 $db->freeResult($res);
322 // We don't need to check for pt stuff if there are no nonexistent titles
323 if($fld_protection && count($missing))
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(
336 'level' => $row->pt_create_perm
,
337 'expiry' => Block
::decodeExpiry($row->pt_expiry
, TS_ISO_8601
)
340 $db->freeResult($res);
344 foreach ($missing as $title)
345 if ($title->getNamespace() == NS_FILE
)
346 $images[] = $title->getDBKey();
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);
362 $res = $this->select(__METHOD__
);
363 while($row = $db->fetchObject($res)) {
364 $source = Title
::makeTitle($row->page_namespace
, $row->page_title
);
366 'type' => $row->pr_type
,
367 'level' => $row->pr_level
,
368 'expiry' => Block
::decodeExpiry( $row->pr_expiry
, TS_ISO_8601
),
369 'source' => $source->getPrefixedText()
371 $prottitles[$row->tl_namespace
][$row->tl_title
][] = $a;
373 $db->freeResult($res);
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);
386 $res = $this->select(__METHOD__
);
387 while($row = $db->fetchObject($res)) {
388 $source = Title
::makeTitle($row->page_namespace
, $row->page_title
);
390 'type' => $row->pr_type
,
391 'level' => $row->pr_level
,
392 'expiry' => Block
::decodeExpiry( $row->pr_expiry
, TS_ISO_8601
),
393 'source' => $source->getPrefixedText()
395 $prottitles[NS_FILE
][$row->il_to
][] = $a;
397 $db->freeResult($res);
401 // Run the talkid/subjectid query
402 if($fld_talkid ||
$fld_subjectid)
404 $talktitles = $subjecttitles =
405 $talkids = $subjectids = array();
406 $everything = array_merge($titles, $missing);
407 foreach($everything as $t)
409 if(MWNamespace
::isTalk($t->getNamespace()))
412 $subjecttitles[] = $t->getSubjectPage();
415 $talktitles[] = $t->getTalkPage();
417 if(count($talktitles) ||
count($subjecttitles))
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))
429 if(MWNamespace
::isTalk($row->page_namespace
))
430 $talkids[MWNamespace
::getSubject($row->page_namespace
)][$row->page_title
] = $row->page_id
;
432 $subjectids[MWNamespace
::getTalk($row->page_namespace
)][$row->page_title
] = $row->page_id
;
438 foreach ( $titles as $pageid => $title ) {
440 if(!is_null($params['continue']))
441 if($count < $params['continue'])
444 'touched' => wfTimestamp(TS_ISO_8601
, $pageTouched[$pageid]),
445 'lastrevid' => intval($pageLatest[$pageid]),
446 'counter' => intval($pageCounter[$pageid]),
447 'length' => intval($pageLength[$pageid]),
450 if ($pageIsRedir[$pageid])
451 $pageInfo['redirect'] = '';
453 if ($pageIsNew[$pageid])
454 $pageInfo['new'] = '';
456 if (!is_null($params['token'])) {
457 $tokenFunctions = $this->getTokenFunctions();
458 $pageInfo['starttimestamp'] = wfTimestamp(TS_ISO_8601
, time());
459 foreach($params['token'] as $t)
461 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
463 $this->setWarning("Action '$t' is not allowed for the current user");
465 $pageInfo[$t . 'token'] = $val;
469 if($fld_protection) {
470 $pageInfo['protection'] = array();
471 if (isset($protections[$pageid])) {
472 $pageInfo['protection'] = $protections[$pageid];
473 $result->setIndexedTagName($pageInfo['protection'], 'pr');
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()];
481 $pageInfo['fullurl'] = $title->getFullURL();
482 $pageInfo['editurl'] = $title->getFullURL('action=edit');
485 if($title->userCanRead())
486 $pageInfo['readable'] = '';
488 $fit = $result->addValue(array (
491 ), $pageid, $pageInfo);
494 $this->setContinueEnumParameter('continue', $count);
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)
503 foreach($missing as $pageid => $title) {
505 if(!is_null($params['continue']))
506 if($count < $params['continue'])
509 if(!is_null($params['token']))
511 $tokenFunctions = $this->getTokenFunctions();
512 $res['query']['pages'][$pageid]['starttimestamp'] = wfTimestamp(TS_ISO_8601
, time());
513 foreach($params['token'] as $t)
515 $val = call_user_func($tokenFunctions[$t], $pageid, $title);
517 $this->setWarning("Action '$t' is not allowed for the current user");
519 $fit = $result->addValue(
520 array('query', 'pages', $pageid),
524 if($fld_protection && $fit)
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()];
532 $result->setIndexedTagName($val, 'pr');
533 $fit = $result->addValue(
534 array('query', 'pages', $pageid),
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());
547 $fit = $result->addValue(array('query', 'pages', $pageid), 'editurl',
548 $title->getFullURL('action=edit'));
550 if($fld_readable && $fit)
551 if($title->userCanRead())
552 $fit = $result->addValue(array('query', 'pages', $pageid), 'readable', '');
555 $this->setContinueEnumParameter('continue', $count);
562 public function getAllowedParams() {
565 ApiBase
:: PARAM_DFLT
=> NULL,
566 ApiBase
:: PARAM_ISMULTI
=> true,
567 ApiBase
:: PARAM_TYPE
=> array (
575 ApiBase
:: PARAM_DFLT
=> NULL,
576 ApiBase
:: PARAM_ISMULTI
=> true,
577 ApiBase
:: PARAM_TYPE
=> array_keys($this->getTokenFunctions())
583 public function getParamDescription() {
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'
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',
597 public function getDescription() {
598 return 'Get basic page information such as namespace, title, last touched date, ...';
601 protected function getExamples() {
603 'api.php?action=query&prop=info&titles=Main%20Page',
604 'api.php?action=query&prop=info&inprop=protection&titles=Main%20Page'
608 public function getVersion() {
609 return __CLASS__
. ': $Id$';