ApiQueryLogEvents.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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\Storage\NameTableAccessException;
  24. /**
  25. * Query action to List the log events, with optional filtering by various parameters.
  26. *
  27. * @ingroup API
  28. */
  29. class ApiQueryLogEvents extends ApiQueryBase {
  30. private $commentStore;
  31. public function __construct( ApiQuery $query, $moduleName ) {
  32. parent::__construct( $query, $moduleName, 'le' );
  33. }
  34. private $fld_ids = false, $fld_title = false, $fld_type = false,
  35. $fld_user = false, $fld_userid = false,
  36. $fld_timestamp = false, $fld_comment = false, $fld_parsedcomment = false,
  37. $fld_details = false, $fld_tags = false;
  38. public function execute() {
  39. $params = $this->extractRequestParams();
  40. $db = $this->getDB();
  41. $this->commentStore = CommentStore::getStore();
  42. $this->requireMaxOneParameter( $params, 'title', 'prefix', 'namespace' );
  43. $prop = array_flip( $params['prop'] );
  44. $this->fld_ids = isset( $prop['ids'] );
  45. $this->fld_title = isset( $prop['title'] );
  46. $this->fld_type = isset( $prop['type'] );
  47. $this->fld_user = isset( $prop['user'] );
  48. $this->fld_userid = isset( $prop['userid'] );
  49. $this->fld_timestamp = isset( $prop['timestamp'] );
  50. $this->fld_comment = isset( $prop['comment'] );
  51. $this->fld_parsedcomment = isset( $prop['parsedcomment'] );
  52. $this->fld_details = isset( $prop['details'] );
  53. $this->fld_tags = isset( $prop['tags'] );
  54. $hideLogs = LogEventsList::getExcludeClause( $db, 'user', $this->getUser() );
  55. if ( $hideLogs !== false ) {
  56. $this->addWhere( $hideLogs );
  57. }
  58. $actorMigration = ActorMigration::newMigration();
  59. $actorQuery = $actorMigration->getJoin( 'log_user' );
  60. $this->addTables( 'logging' );
  61. $this->addTables( $actorQuery['tables'] );
  62. $this->addTables( [ 'user', 'page' ] );
  63. $this->addJoinConds( $actorQuery['joins'] );
  64. $this->addJoinConds( [
  65. 'user' => [ 'LEFT JOIN',
  66. 'user_id=' . $actorQuery['fields']['log_user'] ],
  67. 'page' => [ 'LEFT JOIN',
  68. [ 'log_namespace=page_namespace',
  69. 'log_title=page_title' ] ] ] );
  70. $this->addFields( [
  71. 'log_id',
  72. 'log_type',
  73. 'log_action',
  74. 'log_timestamp',
  75. 'log_deleted',
  76. ] );
  77. $this->addFieldsIf( 'page_id', $this->fld_ids );
  78. // log_page is the page_id saved at log time, whereas page_id is from a
  79. // join at query time. This leads to different results in various
  80. // scenarios, e.g. deletion, recreation.
  81. $this->addFieldsIf( 'log_page', $this->fld_ids );
  82. $this->addFieldsIf( $actorQuery['fields'] + [ 'user_name' ], $this->fld_user );
  83. $this->addFieldsIf( $actorQuery['fields'], $this->fld_userid );
  84. $this->addFieldsIf(
  85. [ 'log_namespace', 'log_title' ],
  86. $this->fld_title || $this->fld_parsedcomment
  87. );
  88. $this->addFieldsIf( 'log_params', $this->fld_details );
  89. if ( $this->fld_comment || $this->fld_parsedcomment ) {
  90. $commentQuery = $this->commentStore->getJoin( 'log_comment' );
  91. $this->addTables( $commentQuery['tables'] );
  92. $this->addFields( $commentQuery['fields'] );
  93. $this->addJoinConds( $commentQuery['joins'] );
  94. }
  95. if ( $this->fld_tags ) {
  96. $this->addFields( [ 'ts_tags' => ChangeTags::makeTagSummarySubquery( 'logging' ) ] );
  97. }
  98. if ( !is_null( $params['tag'] ) ) {
  99. $this->addTables( 'change_tag' );
  100. $this->addJoinConds( [ 'change_tag' => [ 'JOIN',
  101. [ 'log_id=ct_log_id' ] ] ] );
  102. $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
  103. try {
  104. $this->addWhereFld( 'ct_tag_id', $changeTagDefStore->getId( $params['tag'] ) );
  105. } catch ( NameTableAccessException $exception ) {
  106. // Return nothing.
  107. $this->addWhere( '1=0' );
  108. }
  109. }
  110. if ( !is_null( $params['action'] ) ) {
  111. // Do validation of action param, list of allowed actions can contains wildcards
  112. // Allow the param, when the actions is in the list or a wildcard version is listed.
  113. $logAction = $params['action'];
  114. if ( strpos( $logAction, '/' ) === false ) {
  115. // all items in the list have a slash
  116. $valid = false;
  117. } else {
  118. $logActions = array_flip( $this->getAllowedLogActions() );
  119. list( $type, $action ) = explode( '/', $logAction, 2 );
  120. $valid = isset( $logActions[$logAction] ) || isset( $logActions[$type . '/*'] );
  121. }
  122. if ( !$valid ) {
  123. $encParamName = $this->encodeParamName( 'action' );
  124. $this->dieWithError(
  125. [ 'apierror-unrecognizedvalue', $encParamName, wfEscapeWikiText( $logAction ) ],
  126. "unknown_$encParamName"
  127. );
  128. }
  129. $this->addWhereFld( 'log_type', $type );
  130. $this->addWhereFld( 'log_action', $action );
  131. } elseif ( !is_null( $params['type'] ) ) {
  132. $this->addWhereFld( 'log_type', $params['type'] );
  133. }
  134. $this->addTimestampWhereRange(
  135. 'log_timestamp',
  136. $params['dir'],
  137. $params['start'],
  138. $params['end']
  139. );
  140. // Include in ORDER BY for uniqueness
  141. $this->addWhereRange( 'log_id', $params['dir'], null, null );
  142. if ( !is_null( $params['continue'] ) ) {
  143. $cont = explode( '|', $params['continue'] );
  144. $this->dieContinueUsageIf( count( $cont ) != 2 );
  145. $op = ( $params['dir'] === 'newer' ? '>' : '<' );
  146. $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
  147. $continueId = (int)$cont[1];
  148. $this->dieContinueUsageIf( $continueId != $cont[1] );
  149. $this->addWhere( "log_timestamp $op $continueTimestamp OR " .
  150. "(log_timestamp = $continueTimestamp AND " .
  151. "log_id $op= $continueId)"
  152. );
  153. }
  154. $limit = $params['limit'];
  155. $this->addOption( 'LIMIT', $limit + 1 );
  156. $user = $params['user'];
  157. if ( !is_null( $user ) ) {
  158. // Note the joins in $q are the same as those from ->getJoin() above
  159. // so we only need to add 'conds' here.
  160. $q = $actorMigration->getWhere(
  161. $db, 'log_user', User::newFromName( $params['user'], false )
  162. );
  163. $this->addWhere( $q['conds'] );
  164. // T71222: MariaDB's optimizer, at least 10.1.37 and .38, likes to choose a wildly bad plan for
  165. // some reason for this code path. Tell it not to use the wrong index it wants to pick.
  166. // @phan-suppress-next-line PhanTypeMismatchArgument
  167. $this->addOption( 'IGNORE INDEX', [ 'logging' => [ 'times' ] ] );
  168. }
  169. $title = $params['title'];
  170. if ( !is_null( $title ) ) {
  171. $titleObj = Title::newFromText( $title );
  172. if ( is_null( $titleObj ) ) {
  173. $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $title ) ] );
  174. }
  175. $this->addWhereFld( 'log_namespace', $titleObj->getNamespace() );
  176. $this->addWhereFld( 'log_title', $titleObj->getDBkey() );
  177. }
  178. if ( $params['namespace'] !== null ) {
  179. $this->addWhereFld( 'log_namespace', $params['namespace'] );
  180. }
  181. $prefix = $params['prefix'];
  182. if ( !is_null( $prefix ) ) {
  183. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  184. $this->dieWithError( 'apierror-prefixsearchdisabled' );
  185. }
  186. $title = Title::newFromText( $prefix );
  187. if ( is_null( $title ) ) {
  188. $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $prefix ) ] );
  189. }
  190. $this->addWhereFld( 'log_namespace', $title->getNamespace() );
  191. $this->addWhere( 'log_title ' . $db->buildLike( $title->getDBkey(), $db->anyString() ) );
  192. }
  193. // Paranoia: avoid brute force searches (T19342)
  194. if ( $params['namespace'] !== null || !is_null( $title ) || !is_null( $user ) ) {
  195. if ( !$this->getPermissionManager()->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
  196. $titleBits = LogPage::DELETED_ACTION;
  197. $userBits = LogPage::DELETED_USER;
  198. } elseif ( !$this->getPermissionManager()
  199. ->userHasAnyRight( $this->getUser(), 'suppressrevision', 'viewsuppressed' )
  200. ) {
  201. $titleBits = LogPage::DELETED_ACTION | LogPage::DELETED_RESTRICTED;
  202. $userBits = LogPage::DELETED_USER | LogPage::DELETED_RESTRICTED;
  203. } else {
  204. $titleBits = 0;
  205. $userBits = 0;
  206. }
  207. if ( ( $params['namespace'] !== null || !is_null( $title ) ) && $titleBits ) {
  208. $this->addWhere( $db->bitAnd( 'log_deleted', $titleBits ) . " != $titleBits" );
  209. }
  210. if ( !is_null( $user ) && $userBits ) {
  211. $this->addWhere( $db->bitAnd( 'log_deleted', $userBits ) . " != $userBits" );
  212. }
  213. }
  214. // T220999: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` before
  215. // `logging` and filesorting is somehow better than querying $limit+1 rows from `logging`.
  216. // Tell it not to reorder the query. But not when `letag` was used, as it seems as likely
  217. // to be harmed as helped in that case.
  218. if ( $params['tag'] === null ) {
  219. $this->addOption( 'STRAIGHT_JOIN' );
  220. }
  221. $count = 0;
  222. $res = $this->select( __METHOD__ );
  223. $result = $this->getResult();
  224. foreach ( $res as $row ) {
  225. if ( ++$count > $limit ) {
  226. // We've reached the one extra which shows that there are
  227. // additional pages to be had. Stop here...
  228. $this->setContinueEnumParameter( 'continue', "$row->log_timestamp|$row->log_id" );
  229. break;
  230. }
  231. $vals = $this->extractRowInfo( $row );
  232. $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
  233. if ( !$fit ) {
  234. $this->setContinueEnumParameter( 'continue', "$row->log_timestamp|$row->log_id" );
  235. break;
  236. }
  237. }
  238. $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'item' );
  239. }
  240. private function extractRowInfo( $row ) {
  241. $logEntry = DatabaseLogEntry::newFromRow( $row );
  242. $vals = [
  243. ApiResult::META_TYPE => 'assoc',
  244. ];
  245. $anyHidden = false;
  246. $user = $this->getUser();
  247. if ( $this->fld_ids ) {
  248. $vals['logid'] = (int)$row->log_id;
  249. }
  250. if ( $this->fld_title || $this->fld_parsedcomment ) {
  251. $title = Title::makeTitle( $row->log_namespace, $row->log_title );
  252. }
  253. if ( $this->fld_title || $this->fld_ids || $this->fld_details && $row->log_params !== '' ) {
  254. if ( LogEventsList::isDeleted( $row, LogPage::DELETED_ACTION ) ) {
  255. $vals['actionhidden'] = true;
  256. $anyHidden = true;
  257. }
  258. if ( LogEventsList::userCan( $row, LogPage::DELETED_ACTION, $user ) ) {
  259. if ( $this->fld_title ) {
  260. ApiQueryBase::addTitleInfo( $vals, $title );
  261. }
  262. if ( $this->fld_ids ) {
  263. $vals['pageid'] = (int)$row->page_id;
  264. $vals['logpage'] = (int)$row->log_page;
  265. }
  266. if ( $this->fld_details ) {
  267. $vals['params'] = LogFormatter::newFromEntry( $logEntry )->formatParametersForApi();
  268. }
  269. }
  270. }
  271. if ( $this->fld_type ) {
  272. $vals['type'] = $row->log_type;
  273. $vals['action'] = $row->log_action;
  274. }
  275. if ( $this->fld_user || $this->fld_userid ) {
  276. if ( LogEventsList::isDeleted( $row, LogPage::DELETED_USER ) ) {
  277. $vals['userhidden'] = true;
  278. $anyHidden = true;
  279. }
  280. if ( LogEventsList::userCan( $row, LogPage::DELETED_USER, $user ) ) {
  281. if ( $this->fld_user ) {
  282. $vals['user'] = $row->user_name ?? $row->log_user_text;
  283. }
  284. if ( $this->fld_userid ) {
  285. $vals['userid'] = (int)$row->log_user;
  286. }
  287. if ( !$row->log_user ) {
  288. $vals['anon'] = true;
  289. }
  290. }
  291. }
  292. if ( $this->fld_timestamp ) {
  293. $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->log_timestamp );
  294. }
  295. if ( $this->fld_comment || $this->fld_parsedcomment ) {
  296. if ( LogEventsList::isDeleted( $row, LogPage::DELETED_COMMENT ) ) {
  297. $vals['commenthidden'] = true;
  298. $anyHidden = true;
  299. }
  300. if ( LogEventsList::userCan( $row, LogPage::DELETED_COMMENT, $user ) ) {
  301. $comment = $this->commentStore->getComment( 'log_comment', $row )->text;
  302. if ( $this->fld_comment ) {
  303. $vals['comment'] = $comment;
  304. }
  305. if ( $this->fld_parsedcomment ) {
  306. $vals['parsedcomment'] = Linker::formatComment( $comment, $title );
  307. }
  308. }
  309. }
  310. if ( $this->fld_tags ) {
  311. if ( $row->ts_tags ) {
  312. $tags = explode( ',', $row->ts_tags );
  313. ApiResult::setIndexedTagName( $tags, 'tag' );
  314. $vals['tags'] = $tags;
  315. } else {
  316. $vals['tags'] = [];
  317. }
  318. }
  319. if ( $anyHidden && LogEventsList::isDeleted( $row, LogPage::DELETED_RESTRICTED ) ) {
  320. $vals['suppressed'] = true;
  321. }
  322. return $vals;
  323. }
  324. /**
  325. * @return array
  326. */
  327. private function getAllowedLogActions() {
  328. $config = $this->getConfig();
  329. return array_keys( array_merge(
  330. $config->get( 'LogActions' ),
  331. $config->get( 'LogActionsHandlers' )
  332. ) );
  333. }
  334. public function getCacheMode( $params ) {
  335. if ( $this->userCanSeeRevDel() ) {
  336. return 'private';
  337. }
  338. if ( !is_null( $params['prop'] ) && in_array( 'parsedcomment', $params['prop'] ) ) {
  339. // formatComment() calls wfMessage() among other things
  340. return 'anon-public-user-private';
  341. } elseif ( LogEventsList::getExcludeClause( $this->getDB(), 'user', $this->getUser() )
  342. === LogEventsList::getExcludeClause( $this->getDB(), 'public' )
  343. ) { // Output can only contain public data.
  344. return 'public';
  345. } else {
  346. return 'anon-public-user-private';
  347. }
  348. }
  349. public function getAllowedParams( $flags = 0 ) {
  350. $config = $this->getConfig();
  351. if ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
  352. $logActions = $this->getAllowedLogActions();
  353. sort( $logActions );
  354. } else {
  355. $logActions = null;
  356. }
  357. $ret = [
  358. 'prop' => [
  359. ApiBase::PARAM_ISMULTI => true,
  360. ApiBase::PARAM_DFLT => 'ids|title|type|user|timestamp|comment|details',
  361. ApiBase::PARAM_TYPE => [
  362. 'ids',
  363. 'title',
  364. 'type',
  365. 'user',
  366. 'userid',
  367. 'timestamp',
  368. 'comment',
  369. 'parsedcomment',
  370. 'details',
  371. 'tags'
  372. ],
  373. ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
  374. ],
  375. 'type' => [
  376. ApiBase::PARAM_TYPE => LogPage::validTypes(),
  377. ],
  378. 'action' => [
  379. // validation on request is done in execute()
  380. ApiBase::PARAM_TYPE => $logActions
  381. ],
  382. 'start' => [
  383. ApiBase::PARAM_TYPE => 'timestamp'
  384. ],
  385. 'end' => [
  386. ApiBase::PARAM_TYPE => 'timestamp'
  387. ],
  388. 'dir' => [
  389. ApiBase::PARAM_DFLT => 'older',
  390. ApiBase::PARAM_TYPE => [
  391. 'newer',
  392. 'older'
  393. ],
  394. ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
  395. ],
  396. 'user' => [
  397. ApiBase::PARAM_TYPE => 'user',
  398. ],
  399. 'title' => null,
  400. 'namespace' => [
  401. ApiBase::PARAM_TYPE => 'namespace',
  402. ApiBase::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
  403. ],
  404. 'prefix' => [],
  405. 'tag' => null,
  406. 'limit' => [
  407. ApiBase::PARAM_DFLT => 10,
  408. ApiBase::PARAM_TYPE => 'limit',
  409. ApiBase::PARAM_MIN => 1,
  410. ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
  411. ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
  412. ],
  413. 'continue' => [
  414. ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
  415. ],
  416. ];
  417. if ( $config->get( 'MiserMode' ) ) {
  418. $ret['prefix'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
  419. }
  420. return $ret;
  421. }
  422. protected function getExamplesMessages() {
  423. return [
  424. 'action=query&list=logevents'
  425. => 'apihelp-query+logevents-example-simple',
  426. ];
  427. }
  428. public function getHelpUrls() {
  429. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Logevents';
  430. }
  431. }