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