Merge "Change "slave" => "replica DB" in /includes"
[lhc/web/wiklou.git] / includes / api / ApiQueryUserContributions.php
1 <?php
2 /**
3 *
4 *
5 * Created on Oct 16, 2006
6 *
7 * Copyright © 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * This query action adds a list of a specified user's contributions to the output.
29 *
30 * @ingroup API
31 */
32 class ApiQueryContributions extends ApiQueryBase {
33
34 public function __construct( ApiQuery $query, $moduleName ) {
35 parent::__construct( $query, $moduleName, 'uc' );
36 }
37
38 private $params, $prefixMode, $userprefix, $multiUserMode, $idMode, $usernames, $userids,
39 $parentLens;
40 private $fld_ids = false, $fld_title = false, $fld_timestamp = false,
41 $fld_comment = false, $fld_parsedcomment = false, $fld_flags = false,
42 $fld_patrolled = false, $fld_tags = false, $fld_size = false, $fld_sizediff = false;
43
44 public function execute() {
45 // Parse some parameters
46 $this->params = $this->extractRequestParams();
47
48 $prop = array_flip( $this->params['prop'] );
49 $this->fld_ids = isset( $prop['ids'] );
50 $this->fld_title = isset( $prop['title'] );
51 $this->fld_comment = isset( $prop['comment'] );
52 $this->fld_parsedcomment = isset( $prop['parsedcomment'] );
53 $this->fld_size = isset( $prop['size'] );
54 $this->fld_sizediff = isset( $prop['sizediff'] );
55 $this->fld_flags = isset( $prop['flags'] );
56 $this->fld_timestamp = isset( $prop['timestamp'] );
57 $this->fld_patrolled = isset( $prop['patrolled'] );
58 $this->fld_tags = isset( $prop['tags'] );
59
60 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
61 // with extra user based indexes or partioning by user. The additional metadata
62 // queries should use a regular replica DB since the lookup pattern is not all by user.
63 $dbSecondary = $this->getDB(); // any random replica DB
64
65 // TODO: if the query is going only against the revision table, should this be done?
66 $this->selectNamedDB( 'contributions', DB_SLAVE, 'contributions' );
67
68 $this->idMode = false;
69 if ( isset( $this->params['userprefix'] ) ) {
70 $this->prefixMode = true;
71 $this->multiUserMode = true;
72 $this->userprefix = $this->params['userprefix'];
73 } else {
74 $anyIPs = false;
75 $this->userids = [];
76 $this->usernames = [];
77 if ( !is_array( $this->params['user'] ) ) {
78 $this->params['user'] = [ $this->params['user'] ];
79 }
80 if ( !count( $this->params['user'] ) ) {
81 $this->dieUsage( 'User parameter may not be empty.', 'param_user' );
82 }
83 foreach ( $this->params['user'] as $u ) {
84 if ( is_null( $u ) || $u === '' ) {
85 $this->dieUsage( 'User parameter may not be empty', 'param_user' );
86 }
87
88 if ( User::isIP( $u ) ) {
89 $anyIPs = true;
90 $this->usernames[] = $u;
91 } else {
92 $name = User::getCanonicalName( $u, 'valid' );
93 if ( $name === false ) {
94 $this->dieUsage( "User name {$u} is not valid", 'param_user' );
95 }
96 $this->usernames[] = $name;
97 }
98 }
99 $this->prefixMode = false;
100 $this->multiUserMode = ( count( $this->params['user'] ) > 1 );
101
102 if ( !$anyIPs ) {
103 $dbr = $this->getDB();
104 $res = $dbr->select( 'user', 'user_id', [ 'user_name' => $this->usernames ], __METHOD__ );
105 foreach ( $res as $row ) {
106 $this->userids[] = $row->user_id;
107 }
108 $this->idMode = count( $this->userids ) === count( $this->usernames );
109 }
110 }
111
112 $this->prepareQuery();
113
114 // Do the actual query.
115 $res = $this->select( __METHOD__ );
116
117 if ( $this->fld_sizediff ) {
118 $revIds = [];
119 foreach ( $res as $row ) {
120 if ( $row->rev_parent_id ) {
121 $revIds[] = $row->rev_parent_id;
122 }
123 }
124 $this->parentLens = Revision::getParentLengths( $dbSecondary, $revIds );
125 $res->rewind(); // reset
126 }
127
128 // Initialise some variables
129 $count = 0;
130 $limit = $this->params['limit'];
131
132 // Fetch each row
133 foreach ( $res as $row ) {
134 if ( ++$count > $limit ) {
135 // We've reached the one extra which shows that there are
136 // additional pages to be had. Stop here...
137 $this->setContinueEnumParameter( 'continue', $this->continueStr( $row ) );
138 break;
139 }
140
141 $vals = $this->extractRowInfo( $row );
142 $fit = $this->getResult()->addValue( [ 'query', $this->getModuleName() ], null, $vals );
143 if ( !$fit ) {
144 $this->setContinueEnumParameter( 'continue', $this->continueStr( $row ) );
145 break;
146 }
147 }
148
149 $this->getResult()->addIndexedTagName(
150 [ 'query', $this->getModuleName() ],
151 'item'
152 );
153 }
154
155 /**
156 * Prepares the query and returns the limit of rows requested
157 */
158 private function prepareQuery() {
159 // We're after the revision table, and the corresponding page
160 // row for anything we retrieve. We may also need the
161 // recentchanges row and/or tag summary row.
162 $user = $this->getUser();
163 $tables = [ 'page', 'revision' ]; // Order may change
164 $this->addWhere( 'page_id=rev_page' );
165
166 // Handle continue parameter
167 if ( !is_null( $this->params['continue'] ) ) {
168 $continue = explode( '|', $this->params['continue'] );
169 $db = $this->getDB();
170 if ( $this->multiUserMode ) {
171 $this->dieContinueUsageIf( count( $continue ) != 4 );
172 $modeFlag = array_shift( $continue );
173 $this->dieContinueUsageIf( !in_array( $modeFlag, [ 'id', 'name' ] ) );
174 if ( $this->idMode && $modeFlag === 'name' ) {
175 // The users were created since this query started, but we
176 // can't go back and change modes now. So just keep on with
177 // name mode.
178 $this->idMode = false;
179 }
180 $this->dieContinueUsageIf( ( $modeFlag === 'id' ) !== $this->idMode );
181 $userField = $this->idMode ? 'rev_user' : 'rev_user_text';
182 $encUser = $db->addQuotes( array_shift( $continue ) );
183 } else {
184 $this->dieContinueUsageIf( count( $continue ) != 2 );
185 }
186 $encTS = $db->addQuotes( $db->timestamp( $continue[0] ) );
187 $encId = (int)$continue[1];
188 $this->dieContinueUsageIf( $encId != $continue[1] );
189 $op = ( $this->params['dir'] == 'older' ? '<' : '>' );
190 if ( $this->multiUserMode ) {
191 $this->addWhere(
192 "$userField $op $encUser OR " .
193 "($userField = $encUser AND " .
194 "(rev_timestamp $op $encTS OR " .
195 "(rev_timestamp = $encTS AND " .
196 "rev_id $op= $encId)))"
197 );
198 } else {
199 $this->addWhere(
200 "rev_timestamp $op $encTS OR " .
201 "(rev_timestamp = $encTS AND " .
202 "rev_id $op= $encId)"
203 );
204 }
205 }
206
207 // Don't include any revisions where we're not supposed to be able to
208 // see the username.
209 if ( !$user->isAllowed( 'deletedhistory' ) ) {
210 $bitmask = Revision::DELETED_USER;
211 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
212 $bitmask = Revision::DELETED_USER | Revision::DELETED_RESTRICTED;
213 } else {
214 $bitmask = 0;
215 }
216 if ( $bitmask ) {
217 $this->addWhere( $this->getDB()->bitAnd( 'rev_deleted', $bitmask ) . " != $bitmask" );
218 }
219
220 // We only want pages by the specified users.
221 if ( $this->prefixMode ) {
222 $this->addWhere( 'rev_user_text' .
223 $this->getDB()->buildLike( $this->userprefix, $this->getDB()->anyString() ) );
224 } elseif ( $this->idMode ) {
225 $this->addWhereFld( 'rev_user', $this->userids );
226 } else {
227 $this->addWhereFld( 'rev_user_text', $this->usernames );
228 }
229 // ... and in the specified timeframe.
230 // Ensure the same sort order for rev_user/rev_user_text and rev_timestamp
231 // so our query is indexed
232 if ( $this->multiUserMode ) {
233 $this->addWhereRange( $this->idMode ? 'rev_user' : 'rev_user_text',
234 $this->params['dir'], null, null );
235 }
236 $this->addTimestampWhereRange( 'rev_timestamp',
237 $this->params['dir'], $this->params['start'], $this->params['end'] );
238 // Include in ORDER BY for uniqueness
239 $this->addWhereRange( 'rev_id', $this->params['dir'], null, null );
240
241 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
242
243 $show = $this->params['show'];
244 if ( $this->params['toponly'] ) { // deprecated/old param
245 $show[] = 'top';
246 }
247 if ( !is_null( $show ) ) {
248 $show = array_flip( $show );
249
250 if ( ( isset( $show['minor'] ) && isset( $show['!minor'] ) )
251 || ( isset( $show['patrolled'] ) && isset( $show['!patrolled'] ) )
252 || ( isset( $show['top'] ) && isset( $show['!top'] ) )
253 || ( isset( $show['new'] ) && isset( $show['!new'] ) )
254 ) {
255 $this->dieUsageMsg( 'show' );
256 }
257
258 $this->addWhereIf( 'rev_minor_edit = 0', isset( $show['!minor'] ) );
259 $this->addWhereIf( 'rev_minor_edit != 0', isset( $show['minor'] ) );
260 $this->addWhereIf( 'rc_patrolled = 0', isset( $show['!patrolled'] ) );
261 $this->addWhereIf( 'rc_patrolled != 0', isset( $show['patrolled'] ) );
262 $this->addWhereIf( 'rev_id != page_latest', isset( $show['!top'] ) );
263 $this->addWhereIf( 'rev_id = page_latest', isset( $show['top'] ) );
264 $this->addWhereIf( 'rev_parent_id != 0', isset( $show['!new'] ) );
265 $this->addWhereIf( 'rev_parent_id = 0', isset( $show['new'] ) );
266 }
267 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
268
269 // Mandatory fields: timestamp allows request continuation
270 // ns+title checks if the user has access rights for this page
271 // user_text is necessary if multiple users were specified
272 $this->addFields( [
273 'rev_id',
274 'rev_timestamp',
275 'page_namespace',
276 'page_title',
277 'rev_user',
278 'rev_user_text',
279 'rev_deleted'
280 ] );
281
282 if ( isset( $show['patrolled'] ) || isset( $show['!patrolled'] ) ||
283 $this->fld_patrolled
284 ) {
285 if ( !$user->useRCPatrol() && !$user->useNPPatrol() ) {
286 $this->dieUsage(
287 'You need the patrol right to request the patrolled flag',
288 'permissiondenied'
289 );
290 }
291
292 // Use a redundant join condition on both
293 // timestamp and ID so we can use the timestamp
294 // index
295 $index['recentchanges'] = 'rc_user_text';
296 if ( isset( $show['patrolled'] ) || isset( $show['!patrolled'] ) ) {
297 // Put the tables in the right order for
298 // STRAIGHT_JOIN
299 $tables = [ 'revision', 'recentchanges', 'page' ];
300 $this->addOption( 'STRAIGHT_JOIN' );
301 $this->addWhere( 'rc_user_text=rev_user_text' );
302 $this->addWhere( 'rc_timestamp=rev_timestamp' );
303 $this->addWhere( 'rc_this_oldid=rev_id' );
304 } else {
305 $tables[] = 'recentchanges';
306 $this->addJoinConds( [ 'recentchanges' => [
307 'LEFT JOIN', [
308 'rc_user_text=rev_user_text',
309 'rc_timestamp=rev_timestamp',
310 'rc_this_oldid=rev_id' ] ] ] );
311 }
312 }
313
314 $this->addTables( $tables );
315 $this->addFieldsIf( 'rev_page', $this->fld_ids );
316 $this->addFieldsIf( 'page_latest', $this->fld_flags );
317 // $this->addFieldsIf( 'rev_text_id', $this->fld_ids ); // Should this field be exposed?
318 $this->addFieldsIf( 'rev_comment', $this->fld_comment || $this->fld_parsedcomment );
319 $this->addFieldsIf( 'rev_len', $this->fld_size || $this->fld_sizediff );
320 $this->addFieldsIf( 'rev_minor_edit', $this->fld_flags );
321 $this->addFieldsIf( 'rev_parent_id', $this->fld_flags || $this->fld_sizediff || $this->fld_ids );
322 $this->addFieldsIf( 'rc_patrolled', $this->fld_patrolled );
323
324 if ( $this->fld_tags ) {
325 $this->addTables( 'tag_summary' );
326 $this->addJoinConds(
327 [ 'tag_summary' => [ 'LEFT JOIN', [ 'rev_id=ts_rev_id' ] ] ]
328 );
329 $this->addFields( 'ts_tags' );
330 }
331
332 if ( isset( $this->params['tag'] ) ) {
333 $this->addTables( 'change_tag' );
334 $this->addJoinConds(
335 [ 'change_tag' => [ 'INNER JOIN', [ 'rev_id=ct_rev_id' ] ] ]
336 );
337 $this->addWhereFld( 'ct_tag', $this->params['tag'] );
338 }
339
340 if ( isset( $index ) ) {
341 $this->addOption( 'USE INDEX', $index );
342 }
343 }
344
345 /**
346 * Extract fields from the database row and append them to a result array
347 *
348 * @param stdClass $row
349 * @return array
350 */
351 private function extractRowInfo( $row ) {
352 $vals = [];
353 $anyHidden = false;
354
355 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
356 $vals['texthidden'] = true;
357 $anyHidden = true;
358 }
359
360 // Any rows where we can't view the user were filtered out in the query.
361 $vals['userid'] = (int)$row->rev_user;
362 $vals['user'] = $row->rev_user_text;
363 if ( $row->rev_deleted & Revision::DELETED_USER ) {
364 $vals['userhidden'] = true;
365 $anyHidden = true;
366 }
367 if ( $this->fld_ids ) {
368 $vals['pageid'] = intval( $row->rev_page );
369 $vals['revid'] = intval( $row->rev_id );
370 // $vals['textid'] = intval( $row->rev_text_id ); // todo: Should this field be exposed?
371
372 if ( !is_null( $row->rev_parent_id ) ) {
373 $vals['parentid'] = intval( $row->rev_parent_id );
374 }
375 }
376
377 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
378
379 if ( $this->fld_title ) {
380 ApiQueryBase::addTitleInfo( $vals, $title );
381 }
382
383 if ( $this->fld_timestamp ) {
384 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->rev_timestamp );
385 }
386
387 if ( $this->fld_flags ) {
388 $vals['new'] = $row->rev_parent_id == 0 && !is_null( $row->rev_parent_id );
389 $vals['minor'] = (bool)$row->rev_minor_edit;
390 $vals['top'] = $row->page_latest == $row->rev_id;
391 }
392
393 if ( ( $this->fld_comment || $this->fld_parsedcomment ) && isset( $row->rev_comment ) ) {
394 if ( $row->rev_deleted & Revision::DELETED_COMMENT ) {
395 $vals['commenthidden'] = true;
396 $anyHidden = true;
397 }
398
399 $userCanView = Revision::userCanBitfield(
400 $row->rev_deleted,
401 Revision::DELETED_COMMENT, $this->getUser()
402 );
403
404 if ( $userCanView ) {
405 if ( $this->fld_comment ) {
406 $vals['comment'] = $row->rev_comment;
407 }
408
409 if ( $this->fld_parsedcomment ) {
410 $vals['parsedcomment'] = Linker::formatComment( $row->rev_comment, $title );
411 }
412 }
413 }
414
415 if ( $this->fld_patrolled ) {
416 $vals['patrolled'] = (bool)$row->rc_patrolled;
417 }
418
419 if ( $this->fld_size && !is_null( $row->rev_len ) ) {
420 $vals['size'] = intval( $row->rev_len );
421 }
422
423 if ( $this->fld_sizediff
424 && !is_null( $row->rev_len )
425 && !is_null( $row->rev_parent_id )
426 ) {
427 $parentLen = isset( $this->parentLens[$row->rev_parent_id] )
428 ? $this->parentLens[$row->rev_parent_id]
429 : 0;
430 $vals['sizediff'] = intval( $row->rev_len - $parentLen );
431 }
432
433 if ( $this->fld_tags ) {
434 if ( $row->ts_tags ) {
435 $tags = explode( ',', $row->ts_tags );
436 ApiResult::setIndexedTagName( $tags, 'tag' );
437 $vals['tags'] = $tags;
438 } else {
439 $vals['tags'] = [];
440 }
441 }
442
443 if ( $anyHidden && $row->rev_deleted & Revision::DELETED_RESTRICTED ) {
444 $vals['suppressed'] = true;
445 }
446
447 return $vals;
448 }
449
450 private function continueStr( $row ) {
451 if ( $this->multiUserMode ) {
452 if ( $this->idMode ) {
453 return "id|$row->rev_user|$row->rev_timestamp|$row->rev_id";
454 } else {
455 return "name|$row->rev_user_text|$row->rev_timestamp|$row->rev_id";
456 }
457 } else {
458 return "$row->rev_timestamp|$row->rev_id";
459 }
460 }
461
462 public function getCacheMode( $params ) {
463 // This module provides access to deleted revisions and patrol flags if
464 // the requester is logged in
465 return 'anon-public-user-private';
466 }
467
468 public function getAllowedParams() {
469 return [
470 'limit' => [
471 ApiBase::PARAM_DFLT => 10,
472 ApiBase::PARAM_TYPE => 'limit',
473 ApiBase::PARAM_MIN => 1,
474 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
475 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
476 ],
477 'start' => [
478 ApiBase::PARAM_TYPE => 'timestamp'
479 ],
480 'end' => [
481 ApiBase::PARAM_TYPE => 'timestamp'
482 ],
483 'continue' => [
484 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
485 ],
486 'user' => [
487 ApiBase::PARAM_TYPE => 'user',
488 ApiBase::PARAM_ISMULTI => true
489 ],
490 'userprefix' => null,
491 'dir' => [
492 ApiBase::PARAM_DFLT => 'older',
493 ApiBase::PARAM_TYPE => [
494 'newer',
495 'older'
496 ],
497 ApiBase::PARAM_HELP_MSG => 'api-help-param-direction',
498 ],
499 'namespace' => [
500 ApiBase::PARAM_ISMULTI => true,
501 ApiBase::PARAM_TYPE => 'namespace'
502 ],
503 'prop' => [
504 ApiBase::PARAM_ISMULTI => true,
505 ApiBase::PARAM_DFLT => 'ids|title|timestamp|comment|size|flags',
506 ApiBase::PARAM_TYPE => [
507 'ids',
508 'title',
509 'timestamp',
510 'comment',
511 'parsedcomment',
512 'size',
513 'sizediff',
514 'flags',
515 'patrolled',
516 'tags'
517 ],
518 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
519 ],
520 'show' => [
521 ApiBase::PARAM_ISMULTI => true,
522 ApiBase::PARAM_TYPE => [
523 'minor',
524 '!minor',
525 'patrolled',
526 '!patrolled',
527 'top',
528 '!top',
529 'new',
530 '!new',
531 ],
532 ApiBase::PARAM_HELP_MSG => [
533 'apihelp-query+usercontribs-param-show',
534 $this->getConfig()->get( 'RCMaxAge' )
535 ],
536 ],
537 'tag' => null,
538 'toponly' => [
539 ApiBase::PARAM_DFLT => false,
540 ApiBase::PARAM_DEPRECATED => true,
541 ],
542 ];
543 }
544
545 protected function getExamplesMessages() {
546 return [
547 'action=query&list=usercontribs&ucuser=Example'
548 => 'apihelp-query+usercontribs-example-user',
549 'action=query&list=usercontribs&ucuserprefix=192.0.2.'
550 => 'apihelp-query+usercontribs-example-ipprefix',
551 ];
552 }
553
554 public function getHelpUrls() {
555 return 'https://www.mediawiki.org/wiki/API:Usercontribs';
556 }
557 }