ApiQueryAllDeletedRevisions.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <?php
  2. /**
  3. * Copyright © 2014 Wikimedia Foundation and contributors
  4. *
  5. * Heavily based on ApiQueryDeletedrevs,
  6. * Copyright © 2007 Roan Kattouw "<Firstname>.<Lastname>@gmail.com"
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. * http://www.gnu.org/copyleft/gpl.html
  22. *
  23. * @file
  24. */
  25. use MediaWiki\MediaWikiServices;
  26. use MediaWiki\Revision\RevisionRecord;
  27. use MediaWiki\Storage\NameTableAccessException;
  28. /**
  29. * Query module to enumerate all deleted revisions.
  30. *
  31. * @ingroup API
  32. */
  33. class ApiQueryAllDeletedRevisions extends ApiQueryRevisionsBase {
  34. public function __construct( ApiQuery $query, $moduleName ) {
  35. parent::__construct( $query, $moduleName, 'adr' );
  36. }
  37. /**
  38. * @param ApiPageSet|null $resultPageSet
  39. * @return void
  40. */
  41. protected function run( ApiPageSet $resultPageSet = null ) {
  42. $user = $this->getUser();
  43. $db = $this->getDB();
  44. $params = $this->extractRequestParams( false );
  45. $services = MediaWikiServices::getInstance();
  46. $revisionStore = $services->getRevisionStore();
  47. $result = $this->getResult();
  48. // If the user wants no namespaces, they get no pages.
  49. if ( $params['namespace'] === [] ) {
  50. if ( $resultPageSet === null ) {
  51. $result->addValue( 'query', $this->getModuleName(), [] );
  52. }
  53. return;
  54. }
  55. // This module operates in two modes:
  56. // 'user': List deleted revs by a certain user
  57. // 'all': List all deleted revs in NS
  58. $mode = 'all';
  59. if ( !is_null( $params['user'] ) ) {
  60. $mode = 'user';
  61. }
  62. if ( $mode == 'user' ) {
  63. foreach ( [ 'from', 'to', 'prefix', 'excludeuser' ] as $param ) {
  64. if ( !is_null( $params[$param] ) ) {
  65. $p = $this->getModulePrefix();
  66. $this->dieWithError(
  67. [ 'apierror-invalidparammix-cannotusewith', $p . $param, "{$p}user" ],
  68. 'invalidparammix'
  69. );
  70. }
  71. }
  72. } else {
  73. foreach ( [ 'start', 'end' ] as $param ) {
  74. if ( !is_null( $params[$param] ) ) {
  75. $p = $this->getModulePrefix();
  76. $this->dieWithError(
  77. [ 'apierror-invalidparammix-mustusewith', $p . $param, "{$p}user" ],
  78. 'invalidparammix'
  79. );
  80. }
  81. }
  82. }
  83. // If we're generating titles only, we can use DISTINCT for a better
  84. // query. But we can't do that in 'user' mode (wrong index), and we can
  85. // only do it when sorting ASC (because MySQL apparently can't use an
  86. // index backwards for grouping even though it can for ORDER BY, WTF?)
  87. $dir = $params['dir'];
  88. $optimizeGenerateTitles = false;
  89. if ( $mode === 'all' && $params['generatetitles'] && $resultPageSet !== null ) {
  90. if ( $dir === 'newer' ) {
  91. $optimizeGenerateTitles = true;
  92. } else {
  93. $p = $this->getModulePrefix();
  94. $this->addWarning( [ 'apiwarn-alldeletedrevisions-performance', $p ], 'performance' );
  95. }
  96. }
  97. if ( $resultPageSet === null ) {
  98. $this->parseParameters( $params );
  99. $arQuery = $revisionStore->getArchiveQueryInfo();
  100. $this->addTables( $arQuery['tables'] );
  101. $this->addJoinConds( $arQuery['joins'] );
  102. $this->addFields( $arQuery['fields'] );
  103. $this->addFields( [ 'ar_title', 'ar_namespace' ] );
  104. } else {
  105. $this->limit = $this->getParameter( 'limit' ) ?: 10;
  106. $this->addTables( 'archive' );
  107. $this->addFields( [ 'ar_title', 'ar_namespace' ] );
  108. if ( $optimizeGenerateTitles ) {
  109. $this->addOption( 'DISTINCT' );
  110. } else {
  111. $this->addFields( [ 'ar_timestamp', 'ar_rev_id', 'ar_id' ] );
  112. }
  113. }
  114. if ( $this->fld_tags ) {
  115. $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'archive' ) ] );
  116. }
  117. if ( !is_null( $params['tag'] ) ) {
  118. $this->addTables( 'change_tag' );
  119. $this->addJoinConds(
  120. [ 'change_tag' => [ 'JOIN', [ 'ar_rev_id=ct_rev_id' ] ] ]
  121. );
  122. $changeTagDefStore = $services->getChangeTagDefStore();
  123. try {
  124. $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
  125. } catch ( NameTableAccessException $exception ) {
  126. // Return nothing.
  127. $this->addWhere( '1=0' );
  128. }
  129. }
  130. // This means stricter restrictions
  131. if ( ( $this->fld_comment || $this->fld_parsedcomment ) &&
  132. !$this->getPermissionManager()->userHasRight( $user, 'deletedhistory' )
  133. ) {
  134. $this->dieWithError( 'apierror-cantview-deleted-comment', 'permissiondenied' );
  135. }
  136. if ( $this->fetchContent &&
  137. !$this->getPermissionManager()->userHasAnyRight( $user, 'deletedtext', 'undelete' )
  138. ) {
  139. $this->dieWithError( 'apierror-cantview-deleted-revision-content', 'permissiondenied' );
  140. }
  141. $miser_ns = null;
  142. if ( $mode == 'all' ) {
  143. $namespaces = $params['namespace'] ??
  144. $services->getNamespaceInfo()->getValidNamespaces();
  145. $this->addWhereFld( 'ar_namespace', $namespaces );
  146. // For from/to/prefix, we have to consider the potential
  147. // transformations of the title in all specified namespaces.
  148. // Generally there will be only one transformation, but wikis with
  149. // some namespaces case-sensitive could have two.
  150. if ( $params['from'] !== null || $params['to'] !== null ) {
  151. $isDirNewer = ( $dir === 'newer' );
  152. $after = ( $isDirNewer ? '>=' : '<=' );
  153. $before = ( $isDirNewer ? '<=' : '>=' );
  154. $where = [];
  155. foreach ( $namespaces as $ns ) {
  156. $w = [];
  157. if ( $params['from'] !== null ) {
  158. $w[] = 'ar_title' . $after .
  159. $db->addQuotes( $this->titlePartToKey( $params['from'], $ns ) );
  160. }
  161. if ( $params['to'] !== null ) {
  162. $w[] = 'ar_title' . $before .
  163. $db->addQuotes( $this->titlePartToKey( $params['to'], $ns ) );
  164. }
  165. $w = $db->makeList( $w, LIST_AND );
  166. $where[$w][] = $ns;
  167. }
  168. if ( count( $where ) == 1 ) {
  169. $where = key( $where );
  170. $this->addWhere( $where );
  171. } else {
  172. $where2 = [];
  173. foreach ( $where as $w => $ns ) {
  174. $where2[] = $db->makeList( [ $w, 'ar_namespace' => $ns ], LIST_AND );
  175. }
  176. $this->addWhere( $db->makeList( $where2, LIST_OR ) );
  177. }
  178. }
  179. if ( isset( $params['prefix'] ) ) {
  180. $where = [];
  181. foreach ( $namespaces as $ns ) {
  182. $w = 'ar_title' . $db->buildLike(
  183. $this->titlePartToKey( $params['prefix'], $ns ),
  184. $db->anyString() );
  185. $where[$w][] = $ns;
  186. }
  187. if ( count( $where ) == 1 ) {
  188. $where = key( $where );
  189. $this->addWhere( $where );
  190. } else {
  191. $where2 = [];
  192. foreach ( $where as $w => $ns ) {
  193. $where2[] = $db->makeList( [ $w, 'ar_namespace' => $ns ], LIST_AND );
  194. }
  195. $this->addWhere( $db->makeList( $where2, LIST_OR ) );
  196. }
  197. }
  198. } else {
  199. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  200. $miser_ns = $params['namespace'];
  201. } else {
  202. $this->addWhereFld( 'ar_namespace', $params['namespace'] );
  203. }
  204. $this->addTimestampWhereRange( 'ar_timestamp', $dir, $params['start'], $params['end'] );
  205. }
  206. if ( !is_null( $params['user'] ) ) {
  207. // Don't query by user ID here, it might be able to use the ar_usertext_timestamp index.
  208. $actorQuery = ActorMigration::newMigration()
  209. ->getWhere( $db, 'ar_user', User::newFromName( $params['user'], false ), false );
  210. $this->addTables( $actorQuery['tables'] );
  211. $this->addJoinConds( $actorQuery['joins'] );
  212. $this->addWhere( $actorQuery['conds'] );
  213. } elseif ( !is_null( $params['excludeuser'] ) ) {
  214. // Here there's no chance of using ar_usertext_timestamp.
  215. $actorQuery = ActorMigration::newMigration()
  216. ->getWhere( $db, 'ar_user', User::newFromName( $params['excludeuser'], false ) );
  217. $this->addTables( $actorQuery['tables'] );
  218. $this->addJoinConds( $actorQuery['joins'] );
  219. $this->addWhere( 'NOT(' . $actorQuery['conds'] . ')' );
  220. }
  221. if ( !is_null( $params['user'] ) || !is_null( $params['excludeuser'] ) ) {
  222. // Paranoia: avoid brute force searches (T19342)
  223. if ( !$this->getPermissionManager()->userHasRight( $user, 'deletedhistory' ) ) {
  224. $bitmask = RevisionRecord::DELETED_USER;
  225. } elseif ( !$this->getPermissionManager()
  226. ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
  227. ) {
  228. $bitmask = RevisionRecord::DELETED_USER | RevisionRecord::DELETED_RESTRICTED;
  229. } else {
  230. $bitmask = 0;
  231. }
  232. if ( $bitmask ) {
  233. $this->addWhere( $db->bitAnd( 'ar_deleted', $bitmask ) . " != $bitmask" );
  234. }
  235. }
  236. if ( !is_null( $params['continue'] ) ) {
  237. $cont = explode( '|', $params['continue'] );
  238. $op = ( $dir == 'newer' ? '>' : '<' );
  239. if ( $optimizeGenerateTitles ) {
  240. $this->dieContinueUsageIf( count( $cont ) != 2 );
  241. $ns = (int)$cont[0];
  242. $this->dieContinueUsageIf( strval( $ns ) !== $cont[0] );
  243. $title = $db->addQuotes( $cont[1] );
  244. $this->addWhere( "ar_namespace $op $ns OR " .
  245. "(ar_namespace = $ns AND ar_title $op= $title)" );
  246. } elseif ( $mode == 'all' ) {
  247. $this->dieContinueUsageIf( count( $cont ) != 4 );
  248. $ns = (int)$cont[0];
  249. $this->dieContinueUsageIf( strval( $ns ) !== $cont[0] );
  250. $title = $db->addQuotes( $cont[1] );
  251. $ts = $db->addQuotes( $db->timestamp( $cont[2] ) );
  252. $ar_id = (int)$cont[3];
  253. $this->dieContinueUsageIf( strval( $ar_id ) !== $cont[3] );
  254. $this->addWhere( "ar_namespace $op $ns OR " .
  255. "(ar_namespace = $ns AND " .
  256. "(ar_title $op $title OR " .
  257. "(ar_title = $title AND " .
  258. "(ar_timestamp $op $ts OR " .
  259. "(ar_timestamp = $ts AND " .
  260. "ar_id $op= $ar_id)))))" );
  261. } else {
  262. $this->dieContinueUsageIf( count( $cont ) != 2 );
  263. $ts = $db->addQuotes( $db->timestamp( $cont[0] ) );
  264. $ar_id = (int)$cont[1];
  265. $this->dieContinueUsageIf( strval( $ar_id ) !== $cont[1] );
  266. $this->addWhere( "ar_timestamp $op $ts OR " .
  267. "(ar_timestamp = $ts AND " .
  268. "ar_id $op= $ar_id)" );
  269. }
  270. }
  271. $this->addOption( 'LIMIT', $this->limit + 1 );
  272. $sort = ( $dir == 'newer' ? '' : ' DESC' );
  273. $orderby = [];
  274. if ( $optimizeGenerateTitles ) {
  275. // Targeting index name_title_timestamp
  276. if ( $params['namespace'] === null || count( array_unique( $params['namespace'] ) ) > 1 ) {
  277. $orderby[] = "ar_namespace $sort";
  278. }
  279. $orderby[] = "ar_title $sort";
  280. } elseif ( $mode == 'all' ) {
  281. // Targeting index name_title_timestamp
  282. if ( $params['namespace'] === null || count( array_unique( $params['namespace'] ) ) > 1 ) {
  283. $orderby[] = "ar_namespace $sort";
  284. }
  285. $orderby[] = "ar_title $sort";
  286. $orderby[] = "ar_timestamp $sort";
  287. $orderby[] = "ar_id $sort";
  288. } else {
  289. // Targeting index usertext_timestamp
  290. // 'user' is always constant.
  291. $orderby[] = "ar_timestamp $sort";
  292. $orderby[] = "ar_id $sort";
  293. }
  294. $this->addOption( 'ORDER BY', $orderby );
  295. $res = $this->select( __METHOD__ );
  296. $pageMap = []; // Maps ns&title to array index
  297. $count = 0;
  298. $nextIndex = 0;
  299. $generated = [];
  300. foreach ( $res as $row ) {
  301. if ( ++$count > $this->limit ) {
  302. // We've had enough
  303. if ( $optimizeGenerateTitles ) {
  304. $this->setContinueEnumParameter( 'continue', "$row->ar_namespace|$row->ar_title" );
  305. } elseif ( $mode == 'all' ) {
  306. $this->setContinueEnumParameter( 'continue',
  307. "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
  308. );
  309. } else {
  310. $this->setContinueEnumParameter( 'continue', "$row->ar_timestamp|$row->ar_id" );
  311. }
  312. break;
  313. }
  314. // Miser mode namespace check
  315. if ( $miser_ns !== null && !in_array( $row->ar_namespace, $miser_ns ) ) {
  316. continue;
  317. }
  318. if ( $resultPageSet !== null ) {
  319. if ( $params['generatetitles'] ) {
  320. $key = "{$row->ar_namespace}:{$row->ar_title}";
  321. if ( !isset( $generated[$key] ) ) {
  322. $generated[$key] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
  323. }
  324. } else {
  325. $generated[] = $row->ar_rev_id;
  326. }
  327. } else {
  328. $revision = $revisionStore->newRevisionFromArchiveRow( $row );
  329. $rev = $this->extractRevisionInfo( $revision, $row );
  330. if ( !isset( $pageMap[$row->ar_namespace][$row->ar_title] ) ) {
  331. $index = $nextIndex++;
  332. $pageMap[$row->ar_namespace][$row->ar_title] = $index;
  333. $title = Title::newFromLinkTarget( $revision->getPageAsLinkTarget() );
  334. $a = [
  335. 'pageid' => $title->getArticleID(),
  336. 'revisions' => [ $rev ],
  337. ];
  338. ApiResult::setIndexedTagName( $a['revisions'], 'rev' );
  339. ApiQueryBase::addTitleInfo( $a, $title );
  340. $fit = $result->addValue( [ 'query', $this->getModuleName() ], $index, $a );
  341. } else {
  342. $index = $pageMap[$row->ar_namespace][$row->ar_title];
  343. $fit = $result->addValue(
  344. [ 'query', $this->getModuleName(), $index, 'revisions' ],
  345. null, $rev );
  346. }
  347. if ( !$fit ) {
  348. if ( $mode == 'all' ) {
  349. $this->setContinueEnumParameter( 'continue',
  350. "$row->ar_namespace|$row->ar_title|$row->ar_timestamp|$row->ar_id"
  351. );
  352. } else {
  353. $this->setContinueEnumParameter( 'continue', "$row->ar_timestamp|$row->ar_id" );
  354. }
  355. break;
  356. }
  357. }
  358. }
  359. if ( $resultPageSet !== null ) {
  360. if ( $params['generatetitles'] ) {
  361. $resultPageSet->populateFromTitles( $generated );
  362. } else {
  363. $resultPageSet->populateFromRevisionIDs( $generated );
  364. }
  365. } else {
  366. $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'page' );
  367. }
  368. }
  369. public function getAllowedParams() {
  370. $ret = parent::getAllowedParams() + [
  371. 'user' => [
  372. ApiBase::PARAM_TYPE => 'user'
  373. ],
  374. 'namespace' => [
  375. ApiBase::PARAM_ISMULTI => true,
  376. ApiBase::PARAM_TYPE => 'namespace',
  377. ],
  378. 'start' => [
  379. ApiBase::PARAM_TYPE => 'timestamp',
  380. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'useronly' ] ],
  381. ],
  382. 'end' => [
  383. ApiBase::PARAM_TYPE => 'timestamp',
  384. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'useronly' ] ],
  385. ],
  386. 'dir' => [
  387. ApiBase::PARAM_TYPE => [
  388. 'newer',
  389. 'older'
  390. ],
  391. ApiBase::PARAM_DFLT => 'older',
  392. ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
  393. ],
  394. 'from' => [
  395. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
  396. ],
  397. 'to' => [
  398. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
  399. ],
  400. 'prefix' => [
  401. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
  402. ],
  403. 'excludeuser' => [
  404. ApiBase::PARAM_TYPE => 'user',
  405. ApiBase::PARAM_HELP_MSG_INFO => [ [ 'nonuseronly' ] ],
  406. ],
  407. 'tag' => null,
  408. 'continue' => [
  409. ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
  410. ],
  411. 'generatetitles' => [
  412. ApiBase::PARAM_DFLT => false
  413. ],
  414. ];
  415. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  416. $ret['user'][ApiBase::PARAM_HELP_MSG_APPEND] = [
  417. 'apihelp-query+alldeletedrevisions-param-miser-user-namespace',
  418. ];
  419. $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
  420. 'apihelp-query+alldeletedrevisions-param-miser-user-namespace',
  421. ];
  422. }
  423. return $ret;
  424. }
  425. protected function getExamplesMessages() {
  426. return [
  427. 'action=query&list=alldeletedrevisions&adruser=Example&adrlimit=50'
  428. => 'apihelp-query+alldeletedrevisions-example-user',
  429. 'action=query&list=alldeletedrevisions&adrdir=newer&adrnamespace=0&adrlimit=50'
  430. => 'apihelp-query+alldeletedrevisions-example-ns-main',
  431. ];
  432. }
  433. public function getHelpUrls() {
  434. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Alldeletedrevisions';
  435. }
  436. }