ApiQueryRevisions.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <?php
  2. /**
  3. * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\MediaWikiServices;
  23. use MediaWiki\Revision\RevisionRecord;
  24. use MediaWiki\Storage\NameTableAccessException;
  25. /**
  26. * A query action to enumerate revisions of a given page, or show top revisions
  27. * of multiple pages. Various pieces of information may be shown - flags,
  28. * comments, and the actual wiki markup of the rev. In the enumeration mode,
  29. * ranges of revisions may be requested and filtered.
  30. *
  31. * @ingroup API
  32. */
  33. class ApiQueryRevisions extends ApiQueryRevisionsBase {
  34. private $token = null;
  35. public function __construct( ApiQuery $query, $moduleName ) {
  36. parent::__construct( $query, $moduleName, 'rv' );
  37. }
  38. private $tokenFunctions;
  39. /** @deprecated since 1.24 */
  40. protected function getTokenFunctions() {
  41. // tokenname => function
  42. // function prototype is func($pageid, $title, $rev)
  43. // should return token or false
  44. // Don't call the hooks twice
  45. if ( isset( $this->tokenFunctions ) ) {
  46. return $this->tokenFunctions;
  47. }
  48. // If we're in a mode that breaks the same-origin policy, no tokens can
  49. // be obtained
  50. if ( $this->lacksSameOriginSecurity() ) {
  51. return [];
  52. }
  53. $this->tokenFunctions = [
  54. 'rollback' => [ self::class, 'getRollbackToken' ]
  55. ];
  56. Hooks::run( 'APIQueryRevisionsTokens', [ &$this->tokenFunctions ] );
  57. return $this->tokenFunctions;
  58. }
  59. /**
  60. * @deprecated since 1.24
  61. * @param int $pageid
  62. * @param Title $title
  63. * @param Revision $rev
  64. * @return bool|string
  65. */
  66. public static function getRollbackToken( $pageid, $title, $rev ) {
  67. global $wgUser;
  68. if ( !MediaWikiServices::getInstance()->getPermissionManager()
  69. ->userHasRight( $wgUser, 'rollback' ) ) {
  70. return false;
  71. }
  72. return $wgUser->getEditToken( 'rollback' );
  73. }
  74. protected function run( ApiPageSet $resultPageSet = null ) {
  75. $params = $this->extractRequestParams( false );
  76. $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
  77. // If any of those parameters are used, work in 'enumeration' mode.
  78. // Enum mode can only be used when exactly one page is provided.
  79. // Enumerating revisions on multiple pages make it extremely
  80. // difficult to manage continuations and require additional SQL indexes
  81. $enumRevMode = ( $params['user'] !== null || $params['excludeuser'] !== null ||
  82. $params['limit'] !== null || $params['startid'] !== null ||
  83. $params['endid'] !== null || $params['dir'] === 'newer' ||
  84. $params['start'] !== null || $params['end'] !== null );
  85. $pageSet = $this->getPageSet();
  86. $pageCount = $pageSet->getGoodTitleCount();
  87. $revCount = $pageSet->getRevisionCount();
  88. // Optimization -- nothing to do
  89. if ( $revCount === 0 && $pageCount === 0 ) {
  90. // Nothing to do
  91. return;
  92. }
  93. if ( $revCount > 0 && count( $pageSet->getLiveRevisionIDs() ) === 0 ) {
  94. // We're in revisions mode but all given revisions are deleted
  95. return;
  96. }
  97. if ( $revCount > 0 && $enumRevMode ) {
  98. $this->dieWithError(
  99. [ 'apierror-revisions-norevids', $this->getModulePrefix() ], 'invalidparammix'
  100. );
  101. }
  102. if ( $pageCount > 1 && $enumRevMode ) {
  103. $this->dieWithError(
  104. [ 'apierror-revisions-singlepage', $this->getModulePrefix() ], 'invalidparammix'
  105. );
  106. }
  107. // In non-enum mode, rvlimit can't be directly used. Use the maximum
  108. // allowed value.
  109. if ( !$enumRevMode ) {
  110. $this->setParsedLimit = false;
  111. $params['limit'] = 'max';
  112. }
  113. $db = $this->getDB();
  114. $idField = 'rev_id';
  115. $tsField = 'rev_timestamp';
  116. $pageField = 'rev_page';
  117. if ( $params['user'] !== null ) {
  118. // We're going to want to use the page_actor_timestamp index (on revision_actor_temp)
  119. // so use that table's denormalized fields.
  120. $idField = 'revactor_rev';
  121. $tsField = 'revactor_timestamp';
  122. $pageField = 'revactor_page';
  123. }
  124. if ( $resultPageSet === null ) {
  125. $this->parseParameters( $params );
  126. $this->token = $params['token'];
  127. $opts = [];
  128. if ( $this->token !== null || $pageCount > 0 ) {
  129. $opts[] = 'page';
  130. }
  131. if ( $this->fld_user ) {
  132. $opts[] = 'user';
  133. }
  134. $revQuery = $revisionStore->getQueryInfo( $opts );
  135. if ( $idField !== 'rev_id' ) {
  136. $aliasFields = [ 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField ];
  137. $revQuery['fields'] = array_merge(
  138. $aliasFields,
  139. array_diff( $revQuery['fields'], array_keys( $aliasFields ) )
  140. );
  141. }
  142. $this->addTables( $revQuery['tables'] );
  143. $this->addFields( $revQuery['fields'] );
  144. $this->addJoinConds( $revQuery['joins'] );
  145. } else {
  146. $this->limit = $this->getParameter( 'limit' ) ?: 10;
  147. // Always join 'page' so orphaned revisions are filtered out
  148. $this->addTables( [ 'revision', 'page' ] );
  149. $this->addJoinConds(
  150. [ 'page' => [ 'JOIN', [ 'page_id = rev_page' ] ] ]
  151. );
  152. $this->addFields( [
  153. 'rev_id' => $idField, 'rev_timestamp' => $tsField, 'rev_page' => $pageField
  154. ] );
  155. }
  156. if ( $this->fld_tags ) {
  157. $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'revision' ) ] );
  158. }
  159. if ( $params['tag'] !== null ) {
  160. $this->addTables( 'change_tag' );
  161. $this->addJoinConds(
  162. [ 'change_tag' => [ 'JOIN', [ 'rev_id=ct_rev_id' ] ] ]
  163. );
  164. $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
  165. try {
  166. $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
  167. } catch ( NameTableAccessException $exception ) {
  168. // Return nothing.
  169. $this->addWhere( '1=0' );
  170. }
  171. }
  172. if ( $resultPageSet === null && $this->fetchContent ) {
  173. // For each page we will request, the user must have read rights for that page
  174. $status = Status::newGood();
  175. $user = $this->getUser();
  176. /** @var Title $title */
  177. foreach ( $pageSet->getGoodTitles() as $title ) {
  178. if ( !$this->getPermissionManager()->userCan( 'read', $user, $title ) ) {
  179. $status->fatal( ApiMessage::create(
  180. [ 'apierror-cannotviewtitle', wfEscapeWikiText( $title->getPrefixedText() ) ],
  181. 'accessdenied'
  182. ) );
  183. }
  184. }
  185. if ( !$status->isGood() ) {
  186. $this->dieStatus( $status );
  187. }
  188. }
  189. if ( $enumRevMode ) {
  190. // Indexes targeted:
  191. // page_timestamp if we don't have rvuser
  192. // page_actor_timestamp (on revision_actor_temp) if we have rvuser in READ_NEW mode
  193. // page_user_timestamp if we have a logged-in rvuser
  194. // page_timestamp or usertext_timestamp if we have an IP rvuser
  195. // This is mostly to prevent parameter errors (and optimize SQL?)
  196. $this->requireMaxOneParameter( $params, 'startid', 'start' );
  197. $this->requireMaxOneParameter( $params, 'endid', 'end' );
  198. $this->requireMaxOneParameter( $params, 'user', 'excludeuser' );
  199. if ( $params['continue'] !== null ) {
  200. $cont = explode( '|', $params['continue'] );
  201. $this->dieContinueUsageIf( count( $cont ) != 2 );
  202. $op = ( $params['dir'] === 'newer' ? '>' : '<' );
  203. $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
  204. $continueId = (int)$cont[1];
  205. $this->dieContinueUsageIf( $continueId != $cont[1] );
  206. $this->addWhere( "$tsField $op $continueTimestamp OR " .
  207. "($tsField = $continueTimestamp AND " .
  208. "$idField $op= $continueId)"
  209. );
  210. }
  211. // Convert startid/endid to timestamps (T163532)
  212. $revids = [];
  213. if ( $params['startid'] !== null ) {
  214. $revids[] = (int)$params['startid'];
  215. }
  216. if ( $params['endid'] !== null ) {
  217. $revids[] = (int)$params['endid'];
  218. }
  219. if ( $revids ) {
  220. $db = $this->getDB();
  221. $sql = $db->unionQueries( [
  222. $db->selectSQLText(
  223. 'revision',
  224. [ 'id' => 'rev_id', 'ts' => 'rev_timestamp' ],
  225. [ 'rev_id' => $revids ],
  226. __METHOD__
  227. ),
  228. $db->selectSQLText(
  229. 'archive',
  230. [ 'id' => 'ar_rev_id', 'ts' => 'ar_timestamp' ],
  231. [ 'ar_rev_id' => $revids ],
  232. __METHOD__
  233. ),
  234. ], $db::UNION_DISTINCT );
  235. $res = $db->query( $sql, __METHOD__ );
  236. foreach ( $res as $row ) {
  237. if ( (int)$row->id === (int)$params['startid'] ) {
  238. $params['start'] = $row->ts;
  239. }
  240. if ( (int)$row->id === (int)$params['endid'] ) {
  241. $params['end'] = $row->ts;
  242. }
  243. }
  244. if ( $params['startid'] !== null && $params['start'] === null ) {
  245. $p = $this->encodeParamName( 'startid' );
  246. $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
  247. }
  248. if ( $params['endid'] !== null && $params['end'] === null ) {
  249. $p = $this->encodeParamName( 'endid' );
  250. $this->dieWithError( [ 'apierror-revisions-badid', $p ], "badid_$p" );
  251. }
  252. if ( $params['start'] !== null ) {
  253. $op = ( $params['dir'] === 'newer' ? '>' : '<' );
  254. $ts = $db->addQuotes( $db->timestampOrNull( $params['start'] ) );
  255. if ( $params['startid'] !== null ) {
  256. $this->addWhere( "$tsField $op $ts OR "
  257. . "$tsField = $ts AND $idField $op= " . (int)$params['startid'] );
  258. } else {
  259. $this->addWhere( "$tsField $op= $ts" );
  260. }
  261. }
  262. if ( $params['end'] !== null ) {
  263. $op = ( $params['dir'] === 'newer' ? '<' : '>' ); // Yes, opposite of the above
  264. $ts = $db->addQuotes( $db->timestampOrNull( $params['end'] ) );
  265. if ( $params['endid'] !== null ) {
  266. $this->addWhere( "$tsField $op $ts OR "
  267. . "$tsField = $ts AND $idField $op= " . (int)$params['endid'] );
  268. } else {
  269. $this->addWhere( "$tsField $op= $ts" );
  270. }
  271. }
  272. } else {
  273. $this->addTimestampWhereRange( $tsField, $params['dir'],
  274. $params['start'], $params['end'] );
  275. }
  276. $sort = ( $params['dir'] === 'newer' ? '' : 'DESC' );
  277. $this->addOption( 'ORDER BY', [ "rev_timestamp $sort", "rev_id $sort" ] );
  278. // There is only one ID, use it
  279. $ids = array_keys( $pageSet->getGoodTitles() );
  280. $this->addWhereFld( $pageField, reset( $ids ) );
  281. if ( $params['user'] !== null ) {
  282. $actorQuery = ActorMigration::newMigration()
  283. ->getWhere( $db, 'rev_user', User::newFromName( $params['user'], false ) );
  284. $this->addTables( $actorQuery['tables'] );
  285. $this->addJoinConds( $actorQuery['joins'] );
  286. $this->addWhere( $actorQuery['conds'] );
  287. } elseif ( $params['excludeuser'] !== null ) {
  288. $actorQuery = ActorMigration::newMigration()
  289. ->getWhere( $db, 'rev_user', User::newFromName( $params['excludeuser'], false ) );
  290. $this->addTables( $actorQuery['tables'] );
  291. $this->addJoinConds( $actorQuery['joins'] );
  292. $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
  293. }
  294. if ( $params['user'] !== null || $params['excludeuser'] !== null ) {
  295. // Paranoia: avoid brute force searches (T19342)
  296. if ( !$this->getPermissionManager()->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
  297. $bitmask = RevisionRecord::DELETED_USER;
  298. } elseif ( !$this->getPermissionManager()
  299. ->userHasAnyRight( $this->getUser(), 'suppressrevision', 'viewsuppressed' )
  300. ) {
  301. $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
  302. } else {
  303. $bitmask = 0;
  304. }
  305. if ( $bitmask ) {
  306. $this->addWhere( $db->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
  307. }
  308. }
  309. } elseif ( $revCount > 0 ) {
  310. // Always targets the PRIMARY index
  311. $revs = $pageSet->getLiveRevisionIDs();
  312. // Get all revision IDs
  313. $this->addWhereFld( 'rev_id', array_keys( $revs ) );
  314. if ( $params['continue'] !== null ) {
  315. $this->addWhere( 'rev_id >= ' . (int)$params['continue'] );
  316. }
  317. $this->addOption( 'ORDER BY', 'rev_id' );
  318. } elseif ( $pageCount > 0 ) {
  319. // Always targets the rev_page_id index
  320. $titles = $pageSet->getGoodTitles();
  321. // When working in multi-page non-enumeration mode,
  322. // limit to the latest revision only
  323. $this->addWhere( 'page_latest=rev_id' );
  324. // Get all page IDs
  325. $this->addWhereFld( 'page_id', array_keys( $titles ) );
  326. // Every time someone relies on equality propagation, god kills a kitten :)
  327. $this->addWhereFld( 'rev_page', array_keys( $titles ) );
  328. if ( $params['continue'] !== null ) {
  329. $cont = explode( '|', $params['continue'] );
  330. $this->dieContinueUsageIf( count( $cont ) != 2 );
  331. $pageid = (int)$cont[0];
  332. $revid = (int)$cont[1];
  333. $this->addWhere(
  334. "rev_page > $pageid OR " .
  335. "(rev_page = $pageid AND " .
  336. "rev_id >= $revid)"
  337. );
  338. }
  339. $this->addOption( 'ORDER BY', [
  340. 'rev_page',
  341. 'rev_id'
  342. ] );
  343. } else {
  344. ApiBase::dieDebug( __METHOD__, 'param validation?' );
  345. }
  346. $this->addOption( 'LIMIT', $this->limit + 1 );
  347. // T224017: `rev_timestamp` is never the correct index to use for this module, but
  348. // MariaDB (10.1.37-39) sometimes insists on trying to use it anyway. Tell it not to.
  349. $this->addOption( 'IGNORE INDEX', [ 'revision' => 'rev_timestamp' ] );
  350. $count = 0;
  351. $generated = [];
  352. $hookData = [];
  353. $res = $this->select( __METHOD__, [], $hookData );
  354. foreach ( $res as $row ) {
  355. if ( ++$count > $this->limit ) {
  356. // We've reached the one extra which shows that there are
  357. // additional pages to be had. Stop here...
  358. if ( $enumRevMode ) {
  359. $this->setContinueEnumParameter( 'continue',
  360. $row->rev_timestamp . '|' . (int)$row->rev_id );
  361. } elseif ( $revCount > 0 ) {
  362. $this->setContinueEnumParameter( 'continue', (int)$row->rev_id );
  363. } else {
  364. $this->setContinueEnumParameter( 'continue', (int)$row->rev_page .
  365. '|' . (int)$row->rev_id );
  366. }
  367. break;
  368. }
  369. if ( $resultPageSet !== null ) {
  370. $generated[] = $row->rev_id;
  371. } else {
  372. $revision = $revisionStore->newRevisionFromRow( $row );
  373. $rev = $this->extractRevisionInfo( $revision, $row );
  374. if ( $this->token !== null ) {
  375. $title = Title::newFromLinkTarget( $revision->getPageAsLinkTarget() );
  376. $revisionCompat = new Revision( $revision );
  377. $tokenFunctions = $this->getTokenFunctions();
  378. foreach ( $this->token as $t ) {
  379. $val = call_user_func( $tokenFunctions[$t], $title->getArticleID(), $title, $revisionCompat );
  380. if ( $val === false ) {
  381. $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
  382. } else {
  383. $rev[$t . 'token'] = $val;
  384. }
  385. }
  386. }
  387. $fit = $this->processRow( $row, $rev, $hookData ) &&
  388. $this->addPageSubItem( $row->rev_page, $rev, 'rev' );
  389. if ( !$fit ) {
  390. if ( $enumRevMode ) {
  391. $this->setContinueEnumParameter( 'continue',
  392. $row->rev_timestamp . '|' . (int)$row->rev_id );
  393. } elseif ( $revCount > 0 ) {
  394. $this->setContinueEnumParameter( 'continue', (int)$row->rev_id );
  395. } else {
  396. $this->setContinueEnumParameter( 'continue', (int)$row->rev_page .
  397. '|' . (int)$row->rev_id );
  398. }
  399. break;
  400. }
  401. }
  402. }
  403. if ( $resultPageSet !== null ) {
  404. $resultPageSet->populateFromRevisionIDs( $generated );
  405. }
  406. }
  407. public function getCacheMode( $params ) {
  408. if ( isset( $params['token'] ) ) {
  409. return 'private';
  410. }
  411. return parent::getCacheMode( $params );
  412. }
  413. public function getAllowedParams() {
  414. $ret = parent::getAllowedParams() + [
  415. 'startid' => [
  416. ApiBase::PARAM_TYPE => 'integer',
  417. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  418. ],
  419. 'endid' => [
  420. ApiBase::PARAM_TYPE => 'integer',
  421. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  422. ],
  423. 'start' => [
  424. ApiBase::PARAM_TYPE => 'timestamp',
  425. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  426. ],
  427. 'end' => [
  428. ApiBase::PARAM_TYPE => 'timestamp',
  429. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  430. ],
  431. 'dir' => [
  432. ApiBase::PARAM_DFLT => 'older',
  433. ApiBase::PARAM_TYPE => [
  434. 'newer',
  435. 'older'
  436. ],
  437. ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
  438. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  439. ],
  440. 'user' => [
  441. ApiBase::PARAM_TYPE => 'user',
  442. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  443. ],
  444. 'excludeuser' => [
  445. ApiBase::PARAM_TYPE => 'user',
  446. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'singlepageonly' ] ],
  447. ],
  448. 'tag' => null,
  449. 'token' => [
  450. ApiBase::PARAM_DEPRECATED => true,
  451. ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() ),
  452. ApiBase::PARAM_ISMULTI => true
  453. ],
  454. 'continue' => [
  455. ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
  456. ],
  457. ];
  458. $ret['limit'][ApiBase::PARAM_HELP_MSG_INFO] = [ [ 'singlepageonly' ] ];
  459. return $ret;
  460. }
  461. protected function getExamplesMessages() {
  462. return [
  463. 'action=query&prop=revisions&titles=API|Main%20Page&' .
  464. 'rvslots=*&rvprop=timestamp|user|comment|content'
  465. => 'apihelp-query+revisions-example-content',
  466. 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
  467. 'rvprop=timestamp|user|comment'
  468. => 'apihelp-query+revisions-example-last5',
  469. 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
  470. 'rvprop=timestamp|user|comment&rvdir=newer'
  471. => 'apihelp-query+revisions-example-first5',
  472. 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
  473. 'rvprop=timestamp|user|comment&rvdir=newer&rvstart=2006-05-01T00:00:00Z'
  474. => 'apihelp-query+revisions-example-first5-after',
  475. 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
  476. 'rvprop=timestamp|user|comment&rvexcludeuser=127.0.0.1'
  477. => 'apihelp-query+revisions-example-first5-not-localhost',
  478. 'action=query&prop=revisions&titles=Main%20Page&rvlimit=5&' .
  479. 'rvprop=timestamp|user|comment&rvuser=MediaWiki%20default'
  480. => 'apihelp-query+revisions-example-first5-user',
  481. ];
  482. }
  483. public function getHelpUrls() {
  484. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Revisions';
  485. }
  486. }