Merge "Make thumbnail image decoding async"
[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\IResultWrapper;
28 use Wikimedia\Rdbms\FakeResultWrapper;
29 use Wikimedia\Rdbms\IDatabase;
30
31 class ContribsPager extends RangeChronologicalPager {
32
33 /**
34 * @var string[] Local cache for escaped messages
35 */
36 private $messages;
37
38 /**
39 * @var string User name, or a string describing an IP address range
40 */
41 private $target;
42
43 /**
44 * @var string Set to "newbie" to list contributions from the most recent 1% registered users.
45 * $this->target is ignored then. Defaults to "users".
46 */
47 private $contribs;
48
49 /**
50 * @var string|int A single namespace number, or an empty string for all namespaces
51 */
52 private $namespace = '';
53
54 /**
55 * @var string|false Name of tag to filter, or false to ignore tags
56 */
57 private $tagFilter;
58
59 /**
60 * @var bool Set to true to invert the namespace selection
61 */
62 private $nsInvert;
63
64 /**
65 * @var bool Set to true to show both the subject and talk namespace, no matter which got
66 * selected
67 */
68 private $associated;
69
70 /**
71 * @var bool Set to true to show only deleted revisions
72 */
73 private $deletedOnly;
74
75 /**
76 * @var bool Set to true to show only latest (a.k.a. current) revisions
77 */
78 private $topOnly;
79
80 /**
81 * @var bool Set to true to show only new pages
82 */
83 private $newOnly;
84
85 /**
86 * @var bool Set to true to hide edits marked as minor by the user
87 */
88 private $hideMinor;
89
90 private $preventClickjacking = false;
91
92 /** @var IDatabase */
93 private $mDbSecondary;
94
95 /**
96 * @var array
97 */
98 private $mParentLens;
99
100 /**
101 * @var TemplateParser
102 */
103 private $templateParser;
104
105 public function __construct( IContextSource $context, array $options ) {
106 parent::__construct( $context );
107
108 $msgs = [
109 'diff',
110 'hist',
111 'pipe-separator',
112 'uctop'
113 ];
114
115 foreach ( $msgs as $msg ) {
116 $this->messages[$msg] = $this->msg( $msg )->escaped();
117 }
118
119 $this->target = $options['target'] ?? '';
120 $this->contribs = $options['contribs'] ?? 'users';
121 $this->namespace = $options['namespace'] ?? '';
122 $this->tagFilter = $options['tagfilter'] ?? false;
123 $this->nsInvert = $options['nsInvert'] ?? false;
124 $this->associated = $options['associated'] ?? false;
125
126 $this->deletedOnly = !empty( $options['deletedOnly'] );
127 $this->topOnly = !empty( $options['topOnly'] );
128 $this->newOnly = !empty( $options['newOnly'] );
129 $this->hideMinor = !empty( $options['hideMinor'] );
130
131 // Date filtering: use timestamp if available
132 $startTimestamp = '';
133 $endTimestamp = '';
134 if ( $options['start'] ) {
135 $startTimestamp = $options['start'] . ' 00:00:00';
136 }
137 if ( $options['end'] ) {
138 $endTimestamp = $options['end'] . ' 23:59:59';
139 }
140 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
141
142 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
143 // with extra user based indexes or partioning by user. The additional metadata
144 // queries should use a regular replica DB since the lookup pattern is not all by user.
145 $this->mDbSecondary = wfGetDB( DB_REPLICA ); // any random replica DB
146 $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
147 $this->templateParser = new TemplateParser();
148 }
149
150 function getDefaultQuery() {
151 $query = parent::getDefaultQuery();
152 $query['target'] = $this->target;
153
154 return $query;
155 }
156
157 /**
158 * This method basically executes the exact same code as the parent class, though with
159 * a hook added, to allow extensions to add additional queries.
160 *
161 * @param string $offset Index offset, inclusive
162 * @param int $limit Exact query limit
163 * @param bool $descending Query direction, false for ascending, true for descending
164 * @return IResultWrapper
165 */
166 function reallyDoQuery( $offset, $limit, $descending ) {
167 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
168 $offset,
169 $limit,
170 $descending
171 );
172
173 /*
174 * This hook will allow extensions to add in additional queries, so they can get their data
175 * in My Contributions as well. Extensions should append their results to the $data array.
176 *
177 * Extension queries have to implement the navbar requirement as well. They should
178 * - have a column aliased as $pager->getIndexField()
179 * - have LIMIT set
180 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
181 * - have the ORDER BY specified based upon the details provided by the navbar
182 *
183 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
184 *
185 * &$data: an array of results of all contribs queries
186 * $pager: the ContribsPager object hooked into
187 * $offset: see phpdoc above
188 * $limit: see phpdoc above
189 * $descending: see phpdoc above
190 */
191 $data = [ $this->mDb->select(
192 $tables, $fields, $conds, $fname, $options, $join_conds
193 ) ];
194 Hooks::run(
195 'ContribsPager::reallyDoQuery',
196 [ &$data, $this, $offset, $limit, $descending ]
197 );
198
199 $result = [];
200
201 // loop all results and collect them in an array
202 foreach ( $data as $query ) {
203 foreach ( $query as $i => $row ) {
204 // use index column as key, allowing us to easily sort in PHP
205 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
206 }
207 }
208
209 // sort results
210 if ( $descending ) {
211 ksort( $result );
212 } else {
213 krsort( $result );
214 }
215
216 // enforce limit
217 $result = array_slice( $result, 0, $limit );
218
219 // get rid of array keys
220 $result = array_values( $result );
221
222 return new FakeResultWrapper( $result );
223 }
224
225 function getQueryInfo() {
226 $revQuery = Revision::getQueryInfo( [ 'page', 'user' ] );
227 $queryInfo = [
228 'tables' => $revQuery['tables'],
229 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
230 'conds' => [],
231 'options' => [],
232 'join_conds' => $revQuery['joins'],
233 ];
234
235 if ( $this->contribs == 'newbie' ) {
236 $max = $this->mDb->selectField( 'user', 'max(user_id)', '', __METHOD__ );
237 $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
238 # ignore local groups with the bot right
239 # @todo FIXME: Global groups may have 'bot' rights
240 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
241 if ( count( $groupsWithBotPermission ) ) {
242 $queryInfo['tables'][] = 'user_groups';
243 $queryInfo['conds'][] = 'ug_group IS NULL';
244 $queryInfo['join_conds']['user_groups'] = [
245 'LEFT JOIN', [
246 'ug_user = ' . $revQuery['fields']['rev_user'],
247 'ug_group' => $groupsWithBotPermission,
248 'ug_expiry IS NULL OR ug_expiry >= ' .
249 $this->mDb->addQuotes( $this->mDb->timestamp() )
250 ]
251 ];
252 }
253 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
254 // a timestamp offset far in the past such that there are no edits by users with user_ids in
255 // the range, we would end up scanning all revisions from that offset until start of time.
256 $queryInfo['conds'][] = 'rev_timestamp > ' .
257 $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
258 } else {
259 $user = User::newFromName( $this->target, false );
260 $ipRangeConds = $user->isAnon() ? $this->getIpRangeConds( $this->mDb, $this->target ) : null;
261 if ( $ipRangeConds ) {
262 $queryInfo['tables'][] = 'ip_changes';
263 /**
264 * These aliases make `ORDER BY rev_timestamp, rev_id` from {@see getIndexField} and
265 * {@see getExtraSortFields} use the replicated `ipc_rev_timestamp` and `ipc_rev_id`
266 * columns from the `ip_changes` table, for more efficient queries.
267 * @see https://phabricator.wikimedia.org/T200259#4832318
268 */
269 $queryInfo['fields'] = array_merge(
270 [
271 'rev_timestamp' => 'ipc_rev_timestamp',
272 'rev_id' => 'ipc_rev_id',
273 ],
274 array_diff( $queryInfo['fields'], [
275 'rev_timestamp',
276 'rev_id',
277 ] )
278 );
279 $queryInfo['join_conds']['ip_changes'] = [
280 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
281 ];
282 $queryInfo['conds'][] = $ipRangeConds;
283 } else {
284 // tables and joins are already handled by Revision::getQueryInfo()
285 $conds = ActorMigration::newMigration()->getWhere( $this->mDb, 'rev_user', $user );
286 $queryInfo['conds'][] = $conds['conds'];
287 // Force the appropriate index to avoid bad query plans (T189026)
288 if ( isset( $conds['orconds']['actor'] ) ) {
289 // @todo: This will need changing when revision_comment_temp goes away
290 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
291 // Alias 'rev_timestamp' => 'revactor_timestamp' so "ORDER BY rev_timestamp" is interpreted to
292 // use revactor_timestamp instead.
293 $queryInfo['fields'] = array_merge(
294 array_diff( $queryInfo['fields'], [ 'rev_timestamp' ] ),
295 [ 'rev_timestamp' => 'revactor_timestamp' ]
296 );
297 } else {
298 $queryInfo['options']['USE INDEX']['revision'] =
299 isset( $conds['orconds']['userid'] ) ? 'user_timestamp' : 'usertext_timestamp';
300 }
301 }
302 }
303
304 if ( $this->deletedOnly ) {
305 $queryInfo['conds'][] = 'rev_deleted != 0';
306 }
307
308 if ( $this->topOnly ) {
309 $queryInfo['conds'][] = 'rev_id = page_latest';
310 }
311
312 if ( $this->newOnly ) {
313 $queryInfo['conds'][] = 'rev_parent_id = 0';
314 }
315
316 if ( $this->hideMinor ) {
317 $queryInfo['conds'][] = 'rev_minor_edit = 0';
318 }
319
320 $user = $this->getUser();
321 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
322
323 // Paranoia: avoid brute force searches (T19342)
324 if ( !$user->isAllowed( 'deletedhistory' ) ) {
325 $queryInfo['conds'][] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
326 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
327 $queryInfo['conds'][] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
328 ' != ' . Revision::SUPPRESSED_USER;
329 }
330
331 // For IPv6, we use ipc_rev_timestamp on ip_changes as the index field,
332 // which will be referenced when parsing the results of a query.
333 if ( self::isQueryableRange( $this->target ) ) {
334 $queryInfo['fields'][] = 'ipc_rev_timestamp';
335 }
336
337 ChangeTags::modifyDisplayQuery(
338 $queryInfo['tables'],
339 $queryInfo['fields'],
340 $queryInfo['conds'],
341 $queryInfo['join_conds'],
342 $queryInfo['options'],
343 $this->tagFilter
344 );
345
346 // Avoid PHP 7.1 warning from passing $this by reference
347 $pager = $this;
348 Hooks::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
349
350 return $queryInfo;
351 }
352
353 function getNamespaceCond() {
354 if ( $this->namespace !== '' ) {
355 $selectedNS = $this->mDb->addQuotes( $this->namespace );
356 $eq_op = $this->nsInvert ? '!=' : '=';
357 $bool_op = $this->nsInvert ? 'AND' : 'OR';
358
359 if ( !$this->associated ) {
360 return [ "page_namespace $eq_op $selectedNS" ];
361 }
362
363 $associatedNS = $this->mDb->addQuotes(
364 MWNamespace::getAssociated( $this->namespace )
365 );
366
367 return [
368 "page_namespace $eq_op $selectedNS " .
369 $bool_op .
370 " page_namespace $eq_op $associatedNS"
371 ];
372 }
373
374 return [];
375 }
376
377 /**
378 * Get SQL conditions for an IP range, if applicable
379 * @param IDatabase $db
380 * @param string $ip The IP address or CIDR
381 * @return string|false SQL for valid IP ranges, false if invalid
382 */
383 private function getIpRangeConds( $db, $ip ) {
384 // First make sure it is a valid range and they are not outside the CIDR limit
385 if ( !$this->isQueryableRange( $ip ) ) {
386 return false;
387 }
388
389 list( $start, $end ) = IP::parseRange( $ip );
390
391 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
392 }
393
394 /**
395 * Is the given IP a range and within the CIDR limit?
396 *
397 * @param string $ipRange
398 * @return bool True if it is valid
399 * @since 1.30
400 */
401 public function isQueryableRange( $ipRange ) {
402 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
403
404 $bits = IP::parseCIDR( $ipRange )[1];
405 if (
406 ( $bits === false ) ||
407 ( IP::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
408 ( IP::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
409 ) {
410 return false;
411 }
412
413 return true;
414 }
415
416 /**
417 * @return string
418 */
419 public function getIndexField() {
420 // Note this is run via parent::__construct() *before* $this->target is set!
421 return 'rev_timestamp';
422 }
423
424 /**
425 * @return string[]
426 */
427 protected function getExtraSortFields() {
428 // Note this is run via parent::__construct() *before* $this->target is set!
429 return [ 'rev_id' ];
430 }
431
432 function doBatchLookups() {
433 # Do a link batch query
434 $this->mResult->seek( 0 );
435 $parentRevIds = [];
436 $this->mParentLens = [];
437 $batch = new LinkBatch();
438 $isIpRange = $this->isQueryableRange( $this->target );
439 # Give some pointers to make (last) links
440 foreach ( $this->mResult as $row ) {
441 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
442 $parentRevIds[] = $row->rev_parent_id;
443 }
444 if ( isset( $row->rev_id ) ) {
445 $this->mParentLens[$row->rev_id] = $row->rev_len;
446 if ( $this->contribs === 'newbie' ) { // multiple users
447 $batch->add( NS_USER, $row->user_name );
448 $batch->add( NS_USER_TALK, $row->user_name );
449 } elseif ( $isIpRange ) {
450 // If this is an IP range, batch the IP's talk page
451 $batch->add( NS_USER_TALK, $row->rev_user_text );
452 }
453 $batch->add( $row->page_namespace, $row->page_title );
454 }
455 }
456 # Fetch rev_len for revisions not already scanned above
457 $this->mParentLens += Revision::getParentLengths(
458 $this->mDbSecondary,
459 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
460 );
461 $batch->execute();
462 $this->mResult->seek( 0 );
463 }
464
465 /**
466 * @return string
467 */
468 function getStartBody() {
469 return "<ul class=\"mw-contributions-list\">\n";
470 }
471
472 /**
473 * @return string
474 */
475 function getEndBody() {
476 return "</ul>\n";
477 }
478
479 /**
480 * Check whether the revision associated is valid for formatting. If has no associated revision
481 * id then null is returned.
482 *
483 * @param object $row
484 * @param Title|null $title
485 * @return Revision|null
486 */
487 public function tryToCreateValidRevision( $row, $title = null ) {
488 /*
489 * There may be more than just revision rows. To make sure that we'll only be processing
490 * revisions here, let's _try_ to build a revision out of our row (without displaying
491 * notices though) and then trying to grab data from the built object. If we succeed,
492 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
493 * to extensions to subscribe to the hook to parse the row.
494 */
495 Wikimedia\suppressWarnings();
496 try {
497 $rev = new Revision( $row, 0, $title );
498 $validRevision = (bool)$rev->getId();
499 } catch ( Exception $e ) {
500 $validRevision = false;
501 }
502 Wikimedia\restoreWarnings();
503 return $validRevision ? $rev : null;
504 }
505
506 /**
507 * Generates each row in the contributions list.
508 *
509 * Contributions which are marked "top" are currently on top of the history.
510 * For these contributions, a [rollback] link is shown for users with roll-
511 * back privileges. The rollback link restores the most recent version that
512 * was not written by the target user.
513 *
514 * @todo This would probably look a lot nicer in a table.
515 * @param object $row
516 * @return string
517 */
518 function formatRow( $row ) {
519 $ret = '';
520 $classes = [];
521 $attribs = [];
522
523 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
524
525 $page = null;
526 // Create a title for the revision if possible
527 // Rows from the hook may not include title information
528 if ( isset( $row->page_namespace ) && isset( $row->page_title ) ) {
529 $page = Title::newFromRow( $row );
530 }
531 $rev = $this->tryToCreateValidRevision( $row, $page );
532 if ( $rev ) {
533 $attribs['data-mw-revid'] = $rev->getId();
534
535 $link = $linkRenderer->makeLink(
536 $page,
537 $page->getPrefixedText(),
538 [ 'class' => 'mw-contributions-title' ],
539 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
540 );
541 # Mark current revisions
542 $topmarktext = '';
543 $user = $this->getUser();
544
545 if ( $row->rev_id === $row->page_latest ) {
546 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
547 $classes[] = 'mw-contributions-current';
548 # Add rollback link
549 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
550 && $page->quickUserCan( 'edit', $user )
551 ) {
552 $this->preventClickjacking();
553 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
554 }
555 }
556 # Is there a visible previous revision?
557 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
558 $difftext = $linkRenderer->makeKnownLink(
559 $page,
560 new HtmlArmor( $this->messages['diff'] ),
561 [ 'class' => 'mw-changeslist-diff' ],
562 [
563 'diff' => 'prev',
564 'oldid' => $row->rev_id
565 ]
566 );
567 } else {
568 $difftext = $this->messages['diff'];
569 }
570 $histlink = $linkRenderer->makeKnownLink(
571 $page,
572 new HtmlArmor( $this->messages['hist'] ),
573 [ 'class' => 'mw-changeslist-history' ],
574 [ 'action' => 'history' ]
575 );
576
577 if ( $row->rev_parent_id === null ) {
578 // For some reason rev_parent_id isn't populated for this row.
579 // Its rumoured this is true on wikipedia for some revisions (T36922).
580 // Next best thing is to have the total number of bytes.
581 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
582 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
583 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
584 } else {
585 $parentLen = 0;
586 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
587 $parentLen = $this->mParentLens[$row->rev_parent_id];
588 }
589
590 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
591 $chardiff .= ChangesList::showCharacterDifference(
592 $parentLen,
593 $row->rev_len,
594 $this->getContext()
595 );
596 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
597 }
598
599 $lang = $this->getLanguage();
600 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true, false );
601 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
602 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
603 $d = $linkRenderer->makeKnownLink(
604 $page,
605 $date,
606 [ 'class' => 'mw-changeslist-date' ],
607 [ 'oldid' => intval( $row->rev_id ) ]
608 );
609 } else {
610 $d = htmlspecialchars( $date );
611 }
612 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
613 $d = '<span class="history-deleted">' . $d . '</span>';
614 }
615
616 # Show user names for /newbies as there may be different users.
617 # Note that only unprivileged users have rows with hidden user names excluded.
618 # When querying for an IP range, we want to always show user and user talk links.
619 $userlink = '';
620 if ( ( $this->contribs == 'newbie' && !$rev->isDeleted( Revision::DELETED_USER ) )
621 || $this->isQueryableRange( $this->target ) ) {
622 $userlink = ' <span class="mw-changeslist-separator"></span> '
623 . $lang->getDirMark()
624 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
625 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
626 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
627 }
628
629 $flags = [];
630 if ( $rev->getParentId() === 0 ) {
631 $flags[] = ChangesList::flag( 'newpage' );
632 }
633
634 if ( $rev->isMinor() ) {
635 $flags[] = ChangesList::flag( 'minor' );
636 }
637
638 $del = Linker::getRevDeleteLink( $user, $rev, $page );
639 if ( $del !== '' ) {
640 $del .= ' ';
641 }
642
643 // While it might be tempting to use a list here
644 // this would result in clutter and slows down navigating the content
645 // in assistive technology.
646 // See https://phabricator.wikimedia.org/T205581#4734812
647 $diffHistLinks = Html::rawElement( 'span',
648 [ 'class' => 'mw-changeslist-links' ],
649 // The spans are needed to ensure the dividing '|' elements are not
650 // themselves styled as links.
651 Html::rawElement( 'span', [], $difftext ) .
652 ' ' . // Space needed for separating two words.
653 Html::rawElement( 'span', [], $histlink )
654 );
655
656 # Tags, if any.
657 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
658 $row->ts_tags,
659 'contributions',
660 $this->getContext()
661 );
662 $classes = array_merge( $classes, $newClasses );
663
664 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
665
666 $templateParams = [
667 'del' => $del,
668 'timestamp' => $d,
669 'diffHistLinks' => $diffHistLinks,
670 'charDifference' => $chardiff,
671 'flags' => $flags,
672 'articleLink' => $link,
673 'userlink' => $userlink,
674 'logText' => $comment,
675 'topmarktext' => $topmarktext,
676 'tagSummary' => $tagSummary,
677 ];
678
679 # Denote if username is redacted for this edit
680 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
681 $templateParams['rev-deleted-user-contribs'] =
682 $this->msg( 'rev-deleted-user-contribs' )->escaped();
683 }
684
685 $ret = $this->templateParser->processTemplate(
686 'SpecialContributionsLine',
687 $templateParams
688 );
689 }
690
691 // Let extensions add data
692 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
693 $attribs = array_filter( $attribs,
694 [ Sanitizer::class, 'isReservedDataAttribute' ],
695 ARRAY_FILTER_USE_KEY
696 );
697
698 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
699 // receiving empty rows?
700
701 if ( $classes === [] && $attribs === [] && $ret === '' ) {
702 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
703 return "<!-- Could not format Special:Contribution row. -->\n";
704 }
705 $attribs['class'] = $classes;
706
707 // FIXME: The signature of the ContributionsLineEnding hook makes it
708 // very awkward to move this LI wrapper into the template.
709 return Html::rawElement( 'li', $attribs, $ret ) . "\n";
710 }
711
712 /**
713 * Overwrite Pager function and return a helpful comment
714 * @return string
715 */
716 function getSqlComment() {
717 if ( $this->namespace || $this->deletedOnly ) {
718 // potentially slow, see CR r58153
719 return 'contributions page filtered for namespace or RevisionDeleted edits';
720 } else {
721 return 'contributions page unfiltered';
722 }
723 }
724
725 protected function preventClickjacking() {
726 $this->preventClickjacking = true;
727 }
728
729 /**
730 * @return bool
731 */
732 public function getPreventClickjacking() {
733 return $this->preventClickjacking;
734 }
735
736 /**
737 * Set up date filter options, given request data.
738 *
739 * @param array $opts Options array
740 * @return array Options array with processed start and end date filter options
741 */
742 public static function processDateFilter( array $opts ) {
743 $start = $opts['start'] ?? '';
744 $end = $opts['end'] ?? '';
745 $year = $opts['year'] ?? '';
746 $month = $opts['month'] ?? '';
747
748 if ( $start !== '' && $end !== '' && $start > $end ) {
749 $temp = $start;
750 $start = $end;
751 $end = $temp;
752 }
753
754 // If year/month legacy filtering options are set, convert them to display the new stamp
755 if ( $year !== '' || $month !== '' ) {
756 // Reuse getDateCond logic, but subtract a day because
757 // the endpoints of our date range appear inclusive
758 // but the internal end offsets are always exclusive
759 $legacyTimestamp = ReverseChronologicalPager::getOffsetDate( $year, $month );
760 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601 ) );
761 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
762
763 // Clear the new timestamp range options if used and
764 // replace with the converted legacy timestamp
765 $start = '';
766 $end = $legacyDateTime->format( 'Y-m-d' );
767 }
768
769 $opts['start'] = $start;
770 $opts['end'] = $end;
771
772 return $opts;
773 }
774 }