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