Live Preview: Cope with the edit summary being an OOjs UI widget
[lhc/web/wiklou.git] / includes / specials / pagers / ContribsPager.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Pager
20 */
21
22 /**
23 * Pager for Special:Contributions
24 * @ingroup Pager
25 */
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\ResultWrapper;
28 use Wikimedia\Rdbms\FakeResultWrapper;
29 use Wikimedia\Rdbms\IDatabase;
30
31 class ContribsPager extends RangeChronologicalPager {
32
33 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
34 public $messages;
35 public $target;
36 public $namespace = '';
37 public $mDb;
38 public $preventClickjacking = false;
39
40 /** @var IDatabase */
41 public $mDbSecondary;
42
43 /**
44 * @var array
45 */
46 protected $mParentLens;
47
48 /**
49 * @var TemplateParser
50 */
51 protected $templateParser;
52
53 function __construct( IContextSource $context, array $options ) {
54 parent::__construct( $context );
55
56 $msgs = [
57 'diff',
58 'hist',
59 'pipe-separator',
60 'uctop'
61 ];
62
63 foreach ( $msgs as $msg ) {
64 $this->messages[$msg] = $this->msg( $msg )->escaped();
65 }
66
67 $this->target = isset( $options['target'] ) ? $options['target'] : '';
68 $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users';
69 $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : '';
70 $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false;
71 $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false;
72 $this->associated = isset( $options['associated'] ) ? $options['associated'] : false;
73
74 $this->deletedOnly = !empty( $options['deletedOnly'] );
75 $this->topOnly = !empty( $options['topOnly'] );
76 $this->newOnly = !empty( $options['newOnly'] );
77 $this->hideMinor = !empty( $options['hideMinor'] );
78
79 // Date filtering: use timestamp if available
80 $startTimestamp = '';
81 $endTimestamp = '';
82 if ( $options['start'] ) {
83 $startTimestamp = $options['start'] . ' 00:00:00';
84 }
85 if ( $options['end'] ) {
86 $endTimestamp = $options['end'] . ' 23:59:59';
87 }
88 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
89
90 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
91 // with extra user based indexes or partioning by user. The additional metadata
92 // queries should use a regular replica DB since the lookup pattern is not all by user.
93 $this->mDbSecondary = wfGetDB( DB_REPLICA ); // any random replica DB
94 $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
95 $this->templateParser = new TemplateParser();
96 }
97
98 function getDefaultQuery() {
99 $query = parent::getDefaultQuery();
100 $query['target'] = $this->target;
101
102 return $query;
103 }
104
105 /**
106 * This method basically executes the exact same code as the parent class, though with
107 * a hook added, to allow extensions to add additional queries.
108 *
109 * @param string $offset Index offset, inclusive
110 * @param int $limit Exact query limit
111 * @param bool $descending Query direction, false for ascending, true for descending
112 * @return ResultWrapper
113 */
114 function reallyDoQuery( $offset, $limit, $descending ) {
115 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
116 $offset,
117 $limit,
118 $descending
119 );
120
121 /*
122 * This hook will allow extensions to add in additional queries, so they can get their data
123 * in My Contributions as well. Extensions should append their results to the $data array.
124 *
125 * Extension queries have to implement the navbar requirement as well. They should
126 * - have a column aliased as $pager->getIndexField()
127 * - have LIMIT set
128 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
129 * - have the ORDER BY specified based upon the details provided by the navbar
130 *
131 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
132 *
133 * &$data: an array of results of all contribs queries
134 * $pager: the ContribsPager object hooked into
135 * $offset: see phpdoc above
136 * $limit: see phpdoc above
137 * $descending: see phpdoc above
138 */
139 $data = [ $this->mDb->select(
140 $tables, $fields, $conds, $fname, $options, $join_conds
141 ) ];
142 Hooks::run(
143 'ContribsPager::reallyDoQuery',
144 [ &$data, $this, $offset, $limit, $descending ]
145 );
146
147 $result = [];
148
149 // loop all results and collect them in an array
150 foreach ( $data as $query ) {
151 foreach ( $query as $i => $row ) {
152 // use index column as key, allowing us to easily sort in PHP
153 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
154 }
155 }
156
157 // sort results
158 if ( $descending ) {
159 ksort( $result );
160 } else {
161 krsort( $result );
162 }
163
164 // enforce limit
165 $result = array_slice( $result, 0, $limit );
166
167 // get rid of array keys
168 $result = array_values( $result );
169
170 return new FakeResultWrapper( $result );
171 }
172
173 function getQueryInfo() {
174 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
175
176 $user = $this->getUser();
177 $conds = array_merge( $userCond, $this->getNamespaceCond() );
178
179 // Paranoia: avoid brute force searches (T19342)
180 if ( !$user->isAllowed( 'deletedhistory' ) ) {
181 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
182 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
183 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
184 ' != ' . Revision::SUPPRESSED_USER;
185 }
186
187 # Don't include orphaned revisions
188 $join_cond['page'] = Revision::pageJoinCond();
189 # Get the current user name for accounts
190 $join_cond['user'] = Revision::userJoinCond();
191
192 $options = [];
193 if ( $index ) {
194 $options['USE INDEX'] = [ 'revision' => $index ];
195 }
196
197 $queryInfo = [
198 'tables' => $tables,
199 'fields' => array_merge(
200 Revision::selectFields(),
201 Revision::selectUserFields(),
202 [ 'page_namespace', 'page_title', 'page_is_new',
203 'page_latest', 'page_is_redirect', 'page_len' ]
204 ),
205 'conds' => $conds,
206 'options' => $options,
207 'join_conds' => $join_cond
208 ];
209
210 ChangeTags::modifyDisplayQuery(
211 $queryInfo['tables'],
212 $queryInfo['fields'],
213 $queryInfo['conds'],
214 $queryInfo['join_conds'],
215 $queryInfo['options'],
216 $this->tagFilter
217 );
218
219 // Avoid PHP 7.1 warning from passing $this by reference
220 $pager = $this;
221 Hooks::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
222
223 return $queryInfo;
224 }
225
226 function getUserCond() {
227 $condition = [];
228 $join_conds = [];
229 $tables = [ 'revision', 'page', 'user' ];
230 $index = false;
231 if ( $this->contribs == 'newbie' ) {
232 $max = $this->mDb->selectField( 'user', 'max(user_id)', false, __METHOD__ );
233 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
234 # ignore local groups with the bot right
235 # @todo FIXME: Global groups may have 'bot' rights
236 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
237 if ( count( $groupsWithBotPermission ) ) {
238 $tables[] = 'user_groups';
239 $condition[] = 'ug_group IS NULL';
240 $join_conds['user_groups'] = [
241 'LEFT JOIN', [
242 'ug_user = rev_user',
243 'ug_group' => $groupsWithBotPermission,
244 'ug_expiry IS NULL OR ug_expiry >= ' .
245 $this->mDb->addQuotes( $this->mDb->timestamp() )
246 ]
247 ];
248 }
249 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
250 // a timestamp offset far in the past such that there are no edits by users with user_ids in
251 // the range, we would end up scanning all revisions from that offset until start of time.
252 $condition[] = 'rev_timestamp > ' .
253 $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
254 } else {
255 $uid = User::idFromName( $this->target );
256 if ( $uid ) {
257 $condition['rev_user'] = $uid;
258 $index = 'user_timestamp';
259 } else {
260 $condition['rev_user_text'] = $this->target;
261 $index = 'usertext_timestamp';
262 }
263 }
264
265 if ( $this->deletedOnly ) {
266 $condition[] = 'rev_deleted != 0';
267 }
268
269 if ( $this->topOnly ) {
270 $condition[] = 'rev_id = page_latest';
271 }
272
273 if ( $this->newOnly ) {
274 $condition[] = 'rev_parent_id = 0';
275 }
276
277 if ( $this->hideMinor ) {
278 $condition[] = 'rev_minor_edit = 0';
279 }
280
281 return [ $tables, $index, $condition, $join_conds ];
282 }
283
284 function getNamespaceCond() {
285 if ( $this->namespace !== '' ) {
286 $selectedNS = $this->mDb->addQuotes( $this->namespace );
287 $eq_op = $this->nsInvert ? '!=' : '=';
288 $bool_op = $this->nsInvert ? 'AND' : 'OR';
289
290 if ( !$this->associated ) {
291 return [ "page_namespace $eq_op $selectedNS" ];
292 }
293
294 $associatedNS = $this->mDb->addQuotes(
295 MWNamespace::getAssociated( $this->namespace )
296 );
297
298 return [
299 "page_namespace $eq_op $selectedNS " .
300 $bool_op .
301 " page_namespace $eq_op $associatedNS"
302 ];
303 }
304
305 return [];
306 }
307
308 function getIndexField() {
309 return 'rev_timestamp';
310 }
311
312 function doBatchLookups() {
313 # Do a link batch query
314 $this->mResult->seek( 0 );
315 $parentRevIds = [];
316 $this->mParentLens = [];
317 $batch = new LinkBatch();
318 # Give some pointers to make (last) links
319 foreach ( $this->mResult as $row ) {
320 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
321 $parentRevIds[] = $row->rev_parent_id;
322 }
323 if ( isset( $row->rev_id ) ) {
324 $this->mParentLens[$row->rev_id] = $row->rev_len;
325 if ( $this->contribs === 'newbie' ) { // multiple users
326 $batch->add( NS_USER, $row->user_name );
327 $batch->add( NS_USER_TALK, $row->user_name );
328 }
329 $batch->add( $row->page_namespace, $row->page_title );
330 }
331 }
332 # Fetch rev_len for revisions not already scanned above
333 $this->mParentLens += Revision::getParentLengths(
334 $this->mDbSecondary,
335 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
336 );
337 $batch->execute();
338 $this->mResult->seek( 0 );
339 }
340
341 /**
342 * @return string
343 */
344 function getStartBody() {
345 return "<ul class=\"mw-contributions-list\">\n";
346 }
347
348 /**
349 * @return string
350 */
351 function getEndBody() {
352 return "</ul>\n";
353 }
354
355 /**
356 * Generates each row in the contributions list.
357 *
358 * Contributions which are marked "top" are currently on top of the history.
359 * For these contributions, a [rollback] link is shown for users with roll-
360 * back privileges. The rollback link restores the most recent version that
361 * was not written by the target user.
362 *
363 * @todo This would probably look a lot nicer in a table.
364 * @param object $row
365 * @return string
366 */
367 function formatRow( $row ) {
368 $ret = '';
369 $classes = [];
370 $attribs = [];
371
372 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
373
374 /*
375 * There may be more than just revision rows. To make sure that we'll only be processing
376 * revisions here, let's _try_ to build a revision out of our row (without displaying
377 * notices though) and then trying to grab data from the built object. If we succeed,
378 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
379 * to extensions to subscribe to the hook to parse the row.
380 */
381 MediaWiki\suppressWarnings();
382 try {
383 $rev = new Revision( $row );
384 $validRevision = (bool)$rev->getId();
385 } catch ( Exception $e ) {
386 $validRevision = false;
387 }
388 MediaWiki\restoreWarnings();
389
390 if ( $validRevision ) {
391 $attribs['data-mw-revid'] = $rev->getId();
392
393 $page = Title::newFromRow( $row );
394 $link = $linkRenderer->makeLink(
395 $page,
396 $page->getPrefixedText(),
397 [ 'class' => 'mw-contributions-title' ],
398 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
399 );
400 # Mark current revisions
401 $topmarktext = '';
402 $user = $this->getUser();
403 if ( $row->rev_id === $row->page_latest ) {
404 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
405 $classes[] = 'mw-contributions-current';
406 # Add rollback link
407 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
408 && $page->quickUserCan( 'edit', $user )
409 ) {
410 $this->preventClickjacking();
411 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
412 }
413 }
414 # Is there a visible previous revision?
415 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
416 $difftext = $linkRenderer->makeKnownLink(
417 $page,
418 new HtmlArmor( $this->messages['diff'] ),
419 [ 'class' => 'mw-changeslist-diff' ],
420 [
421 'diff' => 'prev',
422 'oldid' => $row->rev_id
423 ]
424 );
425 } else {
426 $difftext = $this->messages['diff'];
427 }
428 $histlink = $linkRenderer->makeKnownLink(
429 $page,
430 new HtmlArmor( $this->messages['hist'] ),
431 [ 'class' => 'mw-changeslist-history' ],
432 [ 'action' => 'history' ]
433 );
434
435 if ( $row->rev_parent_id === null ) {
436 // For some reason rev_parent_id isn't populated for this row.
437 // Its rumoured this is true on wikipedia for some revisions (T36922).
438 // Next best thing is to have the total number of bytes.
439 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
440 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
441 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
442 } else {
443 $parentLen = 0;
444 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
445 $parentLen = $this->mParentLens[$row->rev_parent_id];
446 }
447
448 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
449 $chardiff .= ChangesList::showCharacterDifference(
450 $parentLen,
451 $row->rev_len,
452 $this->getContext()
453 );
454 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
455 }
456
457 $lang = $this->getLanguage();
458 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
459 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
460 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
461 $d = $linkRenderer->makeKnownLink(
462 $page,
463 $date,
464 [ 'class' => 'mw-changeslist-date' ],
465 [ 'oldid' => intval( $row->rev_id ) ]
466 );
467 } else {
468 $d = htmlspecialchars( $date );
469 }
470 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
471 $d = '<span class="history-deleted">' . $d . '</span>';
472 }
473
474 # Show user names for /newbies as there may be different users.
475 # Note that only unprivileged users have rows with hidden user names excluded.
476 $userlink = '';
477 if ( $this->contribs == 'newbie' && !$rev->isDeleted( Revision::DELETED_USER ) ) {
478 $userlink = ' . . ' . $lang->getDirMark()
479 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
480 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
481 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
482 }
483
484 $flags = [];
485 if ( $rev->getParentId() === 0 ) {
486 $flags[] = ChangesList::flag( 'newpage' );
487 }
488
489 if ( $rev->isMinor() ) {
490 $flags[] = ChangesList::flag( 'minor' );
491 }
492
493 $del = Linker::getRevDeleteLink( $user, $rev, $page );
494 if ( $del !== '' ) {
495 $del .= ' ';
496 }
497
498 $diffHistLinks = $this->msg( 'parentheses' )
499 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
500 ->escaped();
501
502 # Tags, if any.
503 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
504 $row->ts_tags,
505 'contributions',
506 $this->getContext()
507 );
508 $classes = array_merge( $classes, $newClasses );
509
510 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
511
512 $templateParams = [
513 'del' => $del,
514 'timestamp' => $d,
515 'diffHistLinks' => $diffHistLinks,
516 'charDifference' => $chardiff,
517 'flags' => $flags,
518 'articleLink' => $link,
519 'userlink' => $userlink,
520 'logText' => $comment,
521 'topmarktext' => $topmarktext,
522 'tagSummary' => $tagSummary,
523 ];
524
525 # Denote if username is redacted for this edit
526 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
527 $templateParams['rev-deleted-user-contribs'] =
528 $this->msg( 'rev-deleted-user-contribs' )->escaped();
529 }
530
531 $ret = $this->templateParser->processTemplate(
532 'SpecialContributionsLine',
533 $templateParams
534 );
535 }
536
537 // Let extensions add data
538 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
539 $attribs = wfArrayFilterByKey( $attribs, [ Sanitizer::class, 'isReservedDataAttribute' ] );
540
541 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
542 // receiving empty rows?
543
544 if ( $classes === [] && $attribs === [] && $ret === '' ) {
545 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
546 return "<!-- Could not format Special:Contribution row. -->\n";
547 }
548 $attribs['class'] = $classes;
549
550 // FIXME: The signature of the ContributionsLineEnding hook makes it
551 // very awkward to move this LI wrapper into the template.
552 return Html::rawElement( 'li', $attribs, $ret ) . "\n";
553 }
554
555 /**
556 * Overwrite Pager function and return a helpful comment
557 * @return string
558 */
559 function getSqlComment() {
560 if ( $this->namespace || $this->deletedOnly ) {
561 // potentially slow, see CR r58153
562 return 'contributions page filtered for namespace or RevisionDeleted edits';
563 } else {
564 return 'contributions page unfiltered';
565 }
566 }
567
568 protected function preventClickjacking() {
569 $this->preventClickjacking = true;
570 }
571
572 /**
573 * @return bool
574 */
575 public function getPreventClickjacking() {
576 return $this->preventClickjacking;
577 }
578
579 /**
580 * Set up date filter options, given request data.
581 *
582 * @param array $opts Options array
583 * @return array Options array with processed start and end date filter options
584 */
585 public static function processDateFilter( $opts ) {
586 $start = $opts['start'] ?: '';
587 $end = $opts['end'] ?: '';
588 $year = $opts['year'] ?: '';
589 $month = $opts['month'] ?: '';
590
591 if ( $start !== '' && $end !== '' && $start > $end ) {
592 $temp = $start;
593 $start = $end;
594 $end = $temp;
595 }
596
597 // If year/month legacy filtering options are set, convert them to display the new stamp
598 if ( $year !== '' || $month !== '' ) {
599 // Reuse getDateCond logic, but subtract a day because
600 // the endpoints of our date range appear inclusive
601 // but the internal end offsets are always exclusive
602 $legacyTimestamp = ReverseChronologicalPager::getOffsetDate( $year, $month );
603 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601 ) );
604 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
605
606 // Clear the new timestamp range options if used and
607 // replace with the converted legacy timestamp
608 $start = '';
609 $end = $legacyDateTime->format( 'Y-m-d' );
610 }
611
612 $opts['start'] = $start;
613 $opts['end'] = $end;
614
615 return $opts;
616 }
617 }