ApiQueryInfo.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. /*
  3. * Created on Sep 25, 2006
  4. *
  5. * API for MediaWiki 1.8+
  6. *
  7. * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, write to the Free Software Foundation, Inc.,
  21. * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. * http://www.gnu.org/copyleft/gpl.html
  23. */
  24. if (!defined('MEDIAWIKI')) {
  25. // Eclipse helper - will be ignored in production
  26. require_once ('ApiQueryBase.php');
  27. }
  28. /**
  29. * A query module to show basic page information.
  30. *
  31. * @ingroup API
  32. */
  33. class ApiQueryInfo extends ApiQueryBase {
  34. private $fld_protection = false, $fld_talkid = false,
  35. $fld_subjectid = false, $fld_url = false,
  36. $fld_readable = false;
  37. public function __construct($query, $moduleName) {
  38. parent :: __construct($query, $moduleName, 'in');
  39. }
  40. public function requestExtraData($pageSet) {
  41. $pageSet->requestField('page_restrictions');
  42. $pageSet->requestField('page_is_redirect');
  43. $pageSet->requestField('page_is_new');
  44. $pageSet->requestField('page_counter');
  45. $pageSet->requestField('page_touched');
  46. $pageSet->requestField('page_latest');
  47. $pageSet->requestField('page_len');
  48. }
  49. /**
  50. * Get an array mapping token names to their handler functions.
  51. * The prototype for a token function is func($pageid, $title)
  52. * it should return a token or false (permission denied)
  53. * @return array(tokenname => function)
  54. */
  55. protected function getTokenFunctions() {
  56. // Don't call the hooks twice
  57. if(isset($this->tokenFunctions))
  58. return $this->tokenFunctions;
  59. // If we're in JSON callback mode, no tokens can be obtained
  60. if(!is_null($this->getMain()->getRequest()->getVal('callback')))
  61. return array();
  62. $this->tokenFunctions = array(
  63. 'edit' => array( 'ApiQueryInfo', 'getEditToken' ),
  64. 'delete' => array( 'ApiQueryInfo', 'getDeleteToken' ),
  65. 'protect' => array( 'ApiQueryInfo', 'getProtectToken' ),
  66. 'move' => array( 'ApiQueryInfo', 'getMoveToken' ),
  67. 'block' => array( 'ApiQueryInfo', 'getBlockToken' ),
  68. 'unblock' => array( 'ApiQueryInfo', 'getUnblockToken' ),
  69. 'email' => array( 'ApiQueryInfo', 'getEmailToken' ),
  70. 'import' => array( 'ApiQueryInfo', 'getImportToken' ),
  71. );
  72. wfRunHooks('APIQueryInfoTokens', array(&$this->tokenFunctions));
  73. return $this->tokenFunctions;
  74. }
  75. public static function getEditToken($pageid, $title)
  76. {
  77. // We could check for $title->userCan('edit') here,
  78. // but that's too expensive for this purpose
  79. // and would break caching
  80. global $wgUser;
  81. if(!$wgUser->isAllowed('edit'))
  82. return false;
  83. // The edit token is always the same, let's exploit that
  84. static $cachedEditToken = null;
  85. if(!is_null($cachedEditToken))
  86. return $cachedEditToken;
  87. $cachedEditToken = $wgUser->editToken();
  88. return $cachedEditToken;
  89. }
  90. public static function getDeleteToken($pageid, $title)
  91. {
  92. global $wgUser;
  93. if(!$wgUser->isAllowed('delete'))
  94. return false;
  95. static $cachedDeleteToken = null;
  96. if(!is_null($cachedDeleteToken))
  97. return $cachedDeleteToken;
  98. $cachedDeleteToken = $wgUser->editToken();
  99. return $cachedDeleteToken;
  100. }
  101. public static function getProtectToken($pageid, $title)
  102. {
  103. global $wgUser;
  104. if(!$wgUser->isAllowed('protect'))
  105. return false;
  106. static $cachedProtectToken = null;
  107. if(!is_null($cachedProtectToken))
  108. return $cachedProtectToken;
  109. $cachedProtectToken = $wgUser->editToken();
  110. return $cachedProtectToken;
  111. }
  112. public static function getMoveToken($pageid, $title)
  113. {
  114. global $wgUser;
  115. if(!$wgUser->isAllowed('move'))
  116. return false;
  117. static $cachedMoveToken = null;
  118. if(!is_null($cachedMoveToken))
  119. return $cachedMoveToken;
  120. $cachedMoveToken = $wgUser->editToken();
  121. return $cachedMoveToken;
  122. }
  123. public static function getBlockToken($pageid, $title)
  124. {
  125. global $wgUser;
  126. if(!$wgUser->isAllowed('block'))
  127. return false;
  128. static $cachedBlockToken = null;
  129. if(!is_null($cachedBlockToken))
  130. return $cachedBlockToken;
  131. $cachedBlockToken = $wgUser->editToken();
  132. return $cachedBlockToken;
  133. }
  134. public static function getUnblockToken($pageid, $title)
  135. {
  136. // Currently, this is exactly the same as the block token
  137. return self::getBlockToken($pageid, $title);
  138. }
  139. public static function getEmailToken($pageid, $title)
  140. {
  141. global $wgUser;
  142. if(!$wgUser->canSendEmail() || $wgUser->isBlockedFromEmailUser())
  143. return false;
  144. static $cachedEmailToken = null;
  145. if(!is_null($cachedEmailToken))
  146. return $cachedEmailToken;
  147. $cachedEmailToken = $wgUser->editToken();
  148. return $cachedEmailToken;
  149. }
  150. public static function getImportToken($pageid, $title)
  151. {
  152. global $wgUser;
  153. if(!$wgUser->isAllowed('import'))
  154. return false;
  155. static $cachedImportToken = null;
  156. if(!is_null($cachedImportToken))
  157. return $cachedImportToken;
  158. $cachedImportToken = $wgUser->editToken();
  159. return $cachedImportToken;
  160. }
  161. public function execute() {
  162. $this->params = $this->extractRequestParams();
  163. if(!is_null($this->params['prop'])) {
  164. $prop = array_flip($this->params['prop']);
  165. $this->fld_protection = isset($prop['protection']);
  166. $this->fld_talkid = isset($prop['talkid']);
  167. $this->fld_subjectid = isset($prop['subjectid']);
  168. $this->fld_url = isset($prop['url']);
  169. $this->fld_readable = isset($prop['readable']);
  170. }
  171. $pageSet = $this->getPageSet();
  172. $this->titles = $pageSet->getGoodTitles();
  173. $this->missing = $pageSet->getMissingTitles();
  174. $this->everything = $this->titles + $this->missing;
  175. $result = $this->getResult();
  176. uasort($this->everything, array('Title', 'compare'));
  177. if(!is_null($this->params['continue']))
  178. {
  179. // Throw away any titles we're gonna skip so they don't
  180. // clutter queries
  181. $cont = explode('|', $this->params['continue']);
  182. if(count($cont) != 2)
  183. $this->dieUsage("Invalid continue param. You should pass the original " .
  184. "value returned by the previous query", "_badcontinue");
  185. $conttitle = Title::makeTitleSafe($cont[0], $cont[1]);
  186. foreach($this->everything as $pageid => $title)
  187. {
  188. if(Title::compare($title, $conttitle) >= 0)
  189. break;
  190. unset($this->titles[$pageid]);
  191. unset($this->missing[$pageid]);
  192. unset($this->everything[$pageid]);
  193. }
  194. }
  195. $this->pageRestrictions = $pageSet->getCustomField('page_restrictions');
  196. $this->pageIsRedir = $pageSet->getCustomField('page_is_redirect');
  197. $this->pageIsNew = $pageSet->getCustomField('page_is_new');
  198. $this->pageCounter = $pageSet->getCustomField('page_counter');
  199. $this->pageTouched = $pageSet->getCustomField('page_touched');
  200. $this->pageLatest = $pageSet->getCustomField('page_latest');
  201. $this->pageLength = $pageSet->getCustomField('page_len');
  202. $db = $this->getDB();
  203. // Get protection info if requested
  204. if ($this->fld_protection)
  205. $this->getProtectionInfo();
  206. // Run the talkid/subjectid query if requested
  207. if($this->fld_talkid || $this->fld_subjectid)
  208. $this->getTSIDs();
  209. foreach($this->everything as $pageid => $title) {
  210. $pageInfo = $this->extractPageInfo($pageid, $title);
  211. $fit = $result->addValue(array (
  212. 'query',
  213. 'pages'
  214. ), $pageid, $pageInfo);
  215. if(!$fit)
  216. {
  217. $this->setContinueEnumParameter('continue',
  218. $title->getNamespace() . '|' .
  219. $title->getText());
  220. break;
  221. }
  222. }
  223. }
  224. /**
  225. * Get a result array with information about a title
  226. * @param $pageid int Page ID (negative for missing titles)
  227. * @param $title Title object
  228. * @return array
  229. */
  230. private function extractPageInfo($pageid, $title)
  231. {
  232. $pageInfo = array();
  233. if($title->exists())
  234. {
  235. $pageInfo['touched'] = wfTimestamp(TS_ISO_8601, $this->pageTouched[$pageid]);
  236. $pageInfo['lastrevid'] = intval($this->pageLatest[$pageid]);
  237. $pageInfo['counter'] = intval($this->pageCounter[$pageid]);
  238. $pageInfo['length'] = intval($this->pageLength[$pageid]);
  239. if ($this->pageIsRedir[$pageid])
  240. $pageInfo['redirect'] = '';
  241. if ($this->pageIsNew[$pageid])
  242. $pageInfo['new'] = '';
  243. }
  244. if (!is_null($this->params['token'])) {
  245. $tokenFunctions = $this->getTokenFunctions();
  246. $pageInfo['starttimestamp'] = wfTimestamp(TS_ISO_8601, time());
  247. foreach($this->params['token'] as $t)
  248. {
  249. $val = call_user_func($tokenFunctions[$t], $pageid, $title);
  250. if($val === false)
  251. $this->setWarning("Action '$t' is not allowed for the current user");
  252. else
  253. $pageInfo[$t . 'token'] = $val;
  254. }
  255. }
  256. if($this->fld_protection) {
  257. $pageInfo['protection'] = array();
  258. if (isset($this->protections[$title->getNamespace()][$title->getDBkey()]))
  259. $pageInfo['protection'] =
  260. $this->protections[$title->getNamespace()][$title->getDBkey()];
  261. $this->getResult()->setIndexedTagName($pageInfo['protection'], 'pr');
  262. }
  263. if($this->fld_talkid && isset($this->talkids[$title->getNamespace()][$title->getDBKey()]))
  264. $pageInfo['talkid'] = $this->talkids[$title->getNamespace()][$title->getDBKey()];
  265. if($this->fld_subjectid && isset($this->subjectids[$title->getNamespace()][$title->getDBKey()]))
  266. $pageInfo['subjectid'] = $this->subjectids[$title->getNamespace()][$title->getDBKey()];
  267. if($this->fld_url) {
  268. $pageInfo['fullurl'] = $title->getFullURL();
  269. $pageInfo['editurl'] = $title->getFullURL('action=edit');
  270. }
  271. if($this->fld_readable)
  272. if($title->userCanRead())
  273. $pageInfo['readable'] = '';
  274. return $pageInfo;
  275. }
  276. /**
  277. * Get information about protections and put it in $protections
  278. */
  279. private function getProtectionInfo()
  280. {
  281. $this->protections = array();
  282. $db = $this->getDB();
  283. // Get normal protections for existing titles
  284. if(count($this->titles))
  285. {
  286. $this->addTables(array('page_restrictions', 'page'));
  287. $this->addWhere('page_id=pr_page');
  288. $this->addFields(array('pr_page', 'pr_type', 'pr_level',
  289. 'pr_expiry', 'pr_cascade', 'page_namespace',
  290. 'page_title'));
  291. $this->addWhereFld('pr_page', array_keys($this->titles));
  292. $res = $this->select(__METHOD__);
  293. while($row = $db->fetchObject($res)) {
  294. $a = array(
  295. 'type' => $row->pr_type,
  296. 'level' => $row->pr_level,
  297. 'expiry' => Block::decodeExpiry($row->pr_expiry, TS_ISO_8601)
  298. );
  299. if($row->pr_cascade)
  300. $a['cascade'] = '';
  301. $this->protections[$row->page_namespace][$row->page_title][] = $a;
  302. # Also check old restrictions
  303. if($this->pageRestrictions[$row->pr_page]) {
  304. $restrictions = explode(':', trim($this->pageRestrictions[$row->pr_page]));
  305. foreach($restrictions as $restrict) {
  306. $temp = explode('=', trim($restrict));
  307. if(count($temp) == 1) {
  308. // old old format should be treated as edit/move restriction
  309. $restriction = trim($temp[0]);
  310. if($restriction == '')
  311. continue;
  312. $this->protections[$row->page_namespace][$row->page_title][] = array(
  313. 'type' => 'edit',
  314. 'level' => $restriction,
  315. 'expiry' => 'infinity',
  316. );
  317. $this->protections[$row->page_namespace][$row->page_title][] = array(
  318. 'type' => 'move',
  319. 'level' => $restriction,
  320. 'expiry' => 'infinity',
  321. );
  322. } else {
  323. $restriction = trim($temp[1]);
  324. if($restriction == '')
  325. continue;
  326. $this->protections[$row->page_namespace][$row->page_title][] = array(
  327. 'type' => $temp[0],
  328. 'level' => $restriction,
  329. 'expiry' => 'infinity',
  330. );
  331. }
  332. }
  333. }
  334. }
  335. $db->freeResult($res);
  336. }
  337. // Get protections for missing titles
  338. if(count($this->missing))
  339. {
  340. $this->resetQueryParams();
  341. $lb = new LinkBatch($this->missing);
  342. $this->addTables('protected_titles');
  343. $this->addFields(array('pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry'));
  344. $this->addWhere($lb->constructSet('pt', $db));
  345. $res = $this->select(__METHOD__);
  346. while($row = $db->fetchObject($res)) {
  347. $this->protections[$row->pt_namespace][$row->pt_title][] = array(
  348. 'type' => 'create',
  349. 'level' => $row->pt_create_perm,
  350. 'expiry' => Block::decodeExpiry($row->pt_expiry, TS_ISO_8601)
  351. );
  352. }
  353. $db->freeResult($res);
  354. }
  355. // Cascading protections
  356. $images = $others = array();
  357. foreach ($this->everything as $title)
  358. if ($title->getNamespace() == NS_FILE)
  359. $images[] = $title->getDBKey();
  360. else
  361. $others[] = $title;
  362. if (count($others)) {
  363. // Non-images: check templatelinks
  364. $lb = new LinkBatch($others);
  365. $this->resetQueryParams();
  366. $this->addTables(array('page_restrictions', 'page', 'templatelinks'));
  367. $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
  368. 'page_title', 'page_namespace',
  369. 'tl_title', 'tl_namespace'));
  370. $this->addWhere($lb->constructSet('tl', $db));
  371. $this->addWhere('pr_page = page_id');
  372. $this->addWhere('pr_page = tl_from');
  373. $this->addWhereFld('pr_cascade', 1);
  374. $res = $this->select(__METHOD__);
  375. while($row = $db->fetchObject($res)) {
  376. $source = Title::makeTitle($row->page_namespace, $row->page_title);
  377. $this->protections[$row->tl_namespace][$row->tl_title][] = array(
  378. 'type' => $row->pr_type,
  379. 'level' => $row->pr_level,
  380. 'expiry' => Block::decodeExpiry($row->pr_expiry, TS_ISO_8601),
  381. 'source' => $source->getPrefixedText()
  382. );
  383. }
  384. $db->freeResult($res);
  385. }
  386. if (count($images)) {
  387. // Images: check imagelinks
  388. $this->resetQueryParams();
  389. $this->addTables(array('page_restrictions', 'page', 'imagelinks'));
  390. $this->addFields(array('pr_type', 'pr_level', 'pr_expiry',
  391. 'page_title', 'page_namespace', 'il_to'));
  392. $this->addWhere('pr_page = page_id');
  393. $this->addWhere('pr_page = il_from');
  394. $this->addWhereFld('pr_cascade', 1);
  395. $this->addWhereFld('il_to', $images);
  396. $res = $this->select(__METHOD__);
  397. while($row = $db->fetchObject($res)) {
  398. $source = Title::makeTitle($row->page_namespace, $row->page_title);
  399. $this->protections[NS_FILE][$row->il_to][] = array(
  400. 'type' => $row->pr_type,
  401. 'level' => $row->pr_level,
  402. 'expiry' => Block::decodeExpiry($row->pr_expiry, TS_ISO_8601),
  403. 'source' => $source->getPrefixedText()
  404. );
  405. }
  406. $db->freeResult($res);
  407. }
  408. }
  409. /**
  410. * Get talk page IDs (if requested) and subject page IDs (if requested)
  411. * and put them in $talkids and $subjectids
  412. */
  413. private function getTSIDs()
  414. {
  415. $getTitles = $this->talkids = $this->subjectids = array();
  416. $db = $this->getDB();
  417. foreach($this->everything as $t)
  418. {
  419. if(MWNamespace::isTalk($t->getNamespace()))
  420. {
  421. if($this->fld_subjectid)
  422. $getTitles[] = $t->getSubjectPage();
  423. }
  424. else if($this->fld_talkid)
  425. $getTitles[] = $t->getTalkPage();
  426. }
  427. if(!count($getTitles))
  428. return;
  429. // Construct a custom WHERE clause that matches
  430. // all titles in $getTitles
  431. $lb = new LinkBatch($getTitles);
  432. $this->resetQueryParams();
  433. $this->addTables('page');
  434. $this->addFields(array('page_title', 'page_namespace', 'page_id'));
  435. $this->addWhere($lb->constructSet('page', $db));
  436. $res = $this->select(__METHOD__);
  437. while($row = $db->fetchObject($res))
  438. {
  439. if(MWNamespace::isTalk($row->page_namespace))
  440. $this->talkids[MWNamespace::getSubject($row->page_namespace)][$row->page_title] =
  441. intval($row->page_id);
  442. else
  443. $this->subjectids[MWNamespace::getTalk($row->page_namespace)][$row->page_title] =
  444. intval($row->page_id);
  445. }
  446. }
  447. public function getAllowedParams() {
  448. return array (
  449. 'prop' => array (
  450. ApiBase :: PARAM_DFLT => NULL,
  451. ApiBase :: PARAM_ISMULTI => true,
  452. ApiBase :: PARAM_TYPE => array (
  453. 'protection',
  454. 'talkid',
  455. 'subjectid',
  456. 'url',
  457. 'readable',
  458. )),
  459. 'token' => array (
  460. ApiBase :: PARAM_DFLT => NULL,
  461. ApiBase :: PARAM_ISMULTI => true,
  462. ApiBase :: PARAM_TYPE => array_keys($this->getTokenFunctions())
  463. ),
  464. 'continue' => null,
  465. );
  466. }
  467. public function getParamDescription() {
  468. return array (
  469. 'prop' => array (
  470. 'Which additional properties to get:',
  471. ' protection - List the protection level of each page',
  472. ' talkid - The page ID of the talk page for each non-talk page',
  473. ' subjectid - The page ID of the parent page for each talk page'
  474. ),
  475. 'token' => 'Request a token to perform a data-modifying action on a page',
  476. 'continue' => 'When more results are available, use this to continue',
  477. );
  478. }
  479. public function getDescription() {
  480. return 'Get basic page information such as namespace, title, last touched date, ...';
  481. }
  482. protected function getExamples() {
  483. return array (
  484. 'api.php?action=query&prop=info&titles=Main%20Page',
  485. 'api.php?action=query&prop=info&inprop=protection&titles=Main%20Page'
  486. );
  487. }
  488. public function getVersion() {
  489. return __CLASS__ . ': $Id: ApiQueryInfo.php 48488 2009-03-17 15:18:26Z catrope $';
  490. }
  491. }