Merge "Type hint against LinkTarget in WatchedItemStore"
[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 ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
355 $queryInfo['conds'][] = $this->mDb->bitAnd(
356 'rev_deleted', RevisionRecord::SUPPRESSED_USER
357 ) . ' != ' . RevisionRecord::SUPPRESSED_USER;
358 }
359
360 // $this->getIndexField() must be in the result rows, as reallyDoQuery() tries to access it.
361 $indexField = $this->getIndexField();
362 if ( $indexField !== 'rev_timestamp' ) {
363 $queryInfo['fields'][] = $indexField;
364 }
365
366 ChangeTags::modifyDisplayQuery(
367 $queryInfo['tables'],
368 $queryInfo['fields'],
369 $queryInfo['conds'],
370 $queryInfo['join_conds'],
371 $queryInfo['options'],
372 $this->tagFilter
373 );
374
375 // Avoid PHP 7.1 warning from passing $this by reference
376 $pager = $this;
377 Hooks::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
378
379 return $queryInfo;
380 }
381
382 function getNamespaceCond() {
383 if ( $this->namespace !== '' ) {
384 $selectedNS = $this->mDb->addQuotes( $this->namespace );
385 $eq_op = $this->nsInvert ? '!=' : '=';
386 $bool_op = $this->nsInvert ? 'AND' : 'OR';
387
388 if ( !$this->associated ) {
389 return [ "page_namespace $eq_op $selectedNS" ];
390 }
391
392 $associatedNS = $this->mDb->addQuotes(
393 MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociated( $this->namespace )
394 );
395
396 return [
397 "page_namespace $eq_op $selectedNS " .
398 $bool_op .
399 " page_namespace $eq_op $associatedNS"
400 ];
401 }
402
403 return [];
404 }
405
406 /**
407 * Get SQL conditions for an IP range, if applicable
408 * @param IDatabase $db
409 * @param string $ip The IP address or CIDR
410 * @return string|false SQL for valid IP ranges, false if invalid
411 */
412 private function getIpRangeConds( $db, $ip ) {
413 // First make sure it is a valid range and they are not outside the CIDR limit
414 if ( !$this->isQueryableRange( $ip ) ) {
415 return false;
416 }
417
418 list( $start, $end ) = IP::parseRange( $ip );
419
420 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
421 }
422
423 /**
424 * Is the given IP a range and within the CIDR limit?
425 *
426 * @param string $ipRange
427 * @return bool True if it is valid
428 * @since 1.30
429 */
430 public function isQueryableRange( $ipRange ) {
431 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
432
433 $bits = IP::parseCIDR( $ipRange )[1];
434 if (
435 ( $bits === false ) ||
436 ( IP::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
437 ( IP::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
438 ) {
439 return false;
440 }
441
442 return true;
443 }
444
445 /**
446 * @return string
447 */
448 public function getIndexField() {
449 // The returned column is used for sorting and continuation, so we need to
450 // make sure to use the right denormalized column depending on which table is
451 // being targeted by the query to avoid bad query plans.
452 // See T200259, T204669, T220991, and T221380.
453 $target = $this->getTargetTable();
454 switch ( $target ) {
455 case 'revision':
456 return 'rev_timestamp';
457 case 'ip_changes':
458 return 'ipc_rev_timestamp';
459 case 'revision_actor_temp':
460 return 'revactor_timestamp';
461 default:
462 wfWarn(
463 __METHOD__ . ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
464 );
465 return 'rev_timestamp';
466 }
467 }
468
469 /**
470 * @return false|string
471 */
472 public function getTagFilter() {
473 return $this->tagFilter;
474 }
475
476 /**
477 * @return string
478 */
479 public function getContribs() {
480 return $this->contribs;
481 }
482
483 /**
484 * @return string
485 */
486 public function getTarget() {
487 return $this->target;
488 }
489
490 /**
491 * @return bool
492 */
493 public function isNewOnly() {
494 return $this->newOnly;
495 }
496
497 /**
498 * @return int|string
499 */
500 public function getNamespace() {
501 return $this->namespace;
502 }
503
504 /**
505 * @return string[]
506 */
507 protected function getExtraSortFields() {
508 // The returned columns are used for sorting, so we need to make sure
509 // to use the right denormalized column depending on which table is
510 // being targeted by the query to avoid bad query plans.
511 // See T200259, T204669, T220991, and T221380.
512 $target = $this->getTargetTable();
513 switch ( $target ) {
514 case 'revision':
515 return [ 'rev_id' ];
516 case 'ip_changes':
517 return [ 'ipc_rev_id' ];
518 case 'revision_actor_temp':
519 return [ 'revactor_rev' ];
520 default:
521 wfWarn(
522 __METHOD__ . ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
523 );
524 return [ 'rev_id' ];
525 }
526 }
527
528 protected function doBatchLookups() {
529 # Do a link batch query
530 $this->mResult->seek( 0 );
531 $parentRevIds = [];
532 $this->mParentLens = [];
533 $batch = new LinkBatch();
534 $isIpRange = $this->isQueryableRange( $this->target );
535 # Give some pointers to make (last) links
536 foreach ( $this->mResult as $row ) {
537 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
538 $parentRevIds[] = $row->rev_parent_id;
539 }
540 if ( isset( $row->rev_id ) ) {
541 $this->mParentLens[$row->rev_id] = $row->rev_len;
542 if ( $this->contribs === 'newbie' ) { // multiple users
543 $batch->add( NS_USER, $row->user_name );
544 $batch->add( NS_USER_TALK, $row->user_name );
545 } elseif ( $isIpRange ) {
546 // If this is an IP range, batch the IP's talk page
547 $batch->add( NS_USER_TALK, $row->rev_user_text );
548 }
549 $batch->add( $row->page_namespace, $row->page_title );
550 }
551 }
552 # Fetch rev_len for revisions not already scanned above
553 $this->mParentLens += Revision::getParentLengths(
554 $this->mDbSecondary,
555 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
556 );
557 $batch->execute();
558 $this->mResult->seek( 0 );
559 }
560
561 /**
562 * @return string
563 */
564 protected function getStartBody() {
565 return "<ul class=\"mw-contributions-list\">\n";
566 }
567
568 /**
569 * @return string
570 */
571 protected function getEndBody() {
572 return "</ul>\n";
573 }
574
575 /**
576 * Check whether the revision associated is valid for formatting. If has no associated revision
577 * id then null is returned.
578 *
579 * @param object $row
580 * @param Title|null $title
581 * @return Revision|null
582 */
583 public function tryToCreateValidRevision( $row, $title = null ) {
584 /*
585 * There may be more than just revision rows. To make sure that we'll only be processing
586 * revisions here, let's _try_ to build a revision out of our row (without displaying
587 * notices though) and then trying to grab data from the built object. If we succeed,
588 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
589 * to extensions to subscribe to the hook to parse the row.
590 */
591 Wikimedia\suppressWarnings();
592 try {
593 $rev = new Revision( $row, 0, $title );
594 $validRevision = (bool)$rev->getId();
595 } catch ( Exception $e ) {
596 $validRevision = false;
597 }
598 Wikimedia\restoreWarnings();
599 return $validRevision ? $rev : null;
600 }
601
602 /**
603 * Generates each row in the contributions list.
604 *
605 * Contributions which are marked "top" are currently on top of the history.
606 * For these contributions, a [rollback] link is shown for users with roll-
607 * back privileges. The rollback link restores the most recent version that
608 * was not written by the target user.
609 *
610 * @todo This would probably look a lot nicer in a table.
611 * @param object $row
612 * @return string
613 */
614 function formatRow( $row ) {
615 $ret = '';
616 $classes = [];
617 $attribs = [];
618
619 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
620
621 $page = null;
622 // Create a title for the revision if possible
623 // Rows from the hook may not include title information
624 if ( isset( $row->page_namespace ) && isset( $row->page_title ) ) {
625 $page = Title::newFromRow( $row );
626 }
627 $rev = $this->tryToCreateValidRevision( $row, $page );
628 if ( $rev ) {
629 $attribs['data-mw-revid'] = $rev->getId();
630
631 $link = $linkRenderer->makeLink(
632 $page,
633 $page->getPrefixedText(),
634 [ 'class' => 'mw-contributions-title' ],
635 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
636 );
637 # Mark current revisions
638 $topmarktext = '';
639 $user = $this->getUser();
640
641 if ( $row->rev_id === $row->page_latest ) {
642 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
643 $classes[] = 'mw-contributions-current';
644 # Add rollback link
645 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
646 && $page->quickUserCan( 'edit', $user )
647 ) {
648 $this->preventClickjacking();
649 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext(),
650 [ 'noBrackets' ] );
651 }
652 }
653 # Is there a visible previous revision?
654 if ( $rev->userCan( RevisionRecord::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
655 $difftext = $linkRenderer->makeKnownLink(
656 $page,
657 new HtmlArmor( $this->messages['diff'] ),
658 [ 'class' => 'mw-changeslist-diff' ],
659 [
660 'diff' => 'prev',
661 'oldid' => $row->rev_id
662 ]
663 );
664 } else {
665 $difftext = $this->messages['diff'];
666 }
667 $histlink = $linkRenderer->makeKnownLink(
668 $page,
669 new HtmlArmor( $this->messages['hist'] ),
670 [ 'class' => 'mw-changeslist-history' ],
671 [ 'action' => 'history' ]
672 );
673
674 if ( $row->rev_parent_id === null ) {
675 // For some reason rev_parent_id isn't populated for this row.
676 // Its rumoured this is true on wikipedia for some revisions (T36922).
677 // Next best thing is to have the total number of bytes.
678 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
679 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
680 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
681 } else {
682 $parentLen = 0;
683 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
684 $parentLen = $this->mParentLens[$row->rev_parent_id];
685 }
686
687 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
688 $chardiff .= ChangesList::showCharacterDifference(
689 $parentLen,
690 $row->rev_len,
691 $this->getContext()
692 );
693 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
694 }
695
696 $lang = $this->getLanguage();
697 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true, false );
698 $d = ChangesList::revDateLink( $rev, $user, $lang, $page );
699
700 # Show user names for /newbies as there may be different users.
701 # Note that only unprivileged users have rows with hidden user names excluded.
702 # When querying for an IP range, we want to always show user and user talk links.
703 $userlink = '';
704 if ( ( $this->contribs == 'newbie' && !$rev->isDeleted( RevisionRecord::DELETED_USER ) )
705 || $this->isQueryableRange( $this->target ) ) {
706 $userlink = ' <span class="mw-changeslist-separator"></span> '
707 . $lang->getDirMark()
708 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
709 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
710 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
711 }
712
713 $flags = [];
714 if ( $rev->getParentId() === 0 ) {
715 $flags[] = ChangesList::flag( 'newpage' );
716 }
717
718 if ( $rev->isMinor() ) {
719 $flags[] = ChangesList::flag( 'minor' );
720 }
721
722 $del = Linker::getRevDeleteLink( $user, $rev, $page );
723 if ( $del !== '' ) {
724 $del .= ' ';
725 }
726
727 // While it might be tempting to use a list here
728 // this would result in clutter and slows down navigating the content
729 // in assistive technology.
730 // See https://phabricator.wikimedia.org/T205581#4734812
731 $diffHistLinks = Html::rawElement( 'span',
732 [ 'class' => 'mw-changeslist-links' ],
733 // The spans are needed to ensure the dividing '|' elements are not
734 // themselves styled as links.
735 Html::rawElement( 'span', [], $difftext ) .
736 ' ' . // Space needed for separating two words.
737 Html::rawElement( 'span', [], $histlink )
738 );
739
740 # Tags, if any.
741 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
742 $row->ts_tags,
743 'contributions',
744 $this->getContext()
745 );
746 $classes = array_merge( $classes, $newClasses );
747
748 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
749
750 $templateParams = [
751 'del' => $del,
752 'timestamp' => $d,
753 'diffHistLinks' => $diffHistLinks,
754 'charDifference' => $chardiff,
755 'flags' => $flags,
756 'articleLink' => $link,
757 'userlink' => $userlink,
758 'logText' => $comment,
759 'topmarktext' => $topmarktext,
760 'tagSummary' => $tagSummary,
761 ];
762
763 # Denote if username is redacted for this edit
764 if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
765 $templateParams['rev-deleted-user-contribs'] =
766 $this->msg( 'rev-deleted-user-contribs' )->escaped();
767 }
768
769 $ret = $this->templateParser->processTemplate(
770 'SpecialContributionsLine',
771 $templateParams
772 );
773 }
774
775 // Let extensions add data
776 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
777 $attribs = array_filter( $attribs,
778 [ Sanitizer::class, 'isReservedDataAttribute' ],
779 ARRAY_FILTER_USE_KEY
780 );
781
782 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
783 // receiving empty rows?
784
785 if ( $classes === [] && $attribs === [] && $ret === '' ) {
786 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
787 return "<!-- Could not format Special:Contribution row. -->\n";
788 }
789 $attribs['class'] = $classes;
790
791 // FIXME: The signature of the ContributionsLineEnding hook makes it
792 // very awkward to move this LI wrapper into the template.
793 return Html::rawElement( 'li', $attribs, $ret ) . "\n";
794 }
795
796 /**
797 * Overwrite Pager function and return a helpful comment
798 * @return string
799 */
800 function getSqlComment() {
801 if ( $this->namespace || $this->deletedOnly ) {
802 // potentially slow, see CR r58153
803 return 'contributions page filtered for namespace or RevisionDeleted edits';
804 } else {
805 return 'contributions page unfiltered';
806 }
807 }
808
809 protected function preventClickjacking() {
810 $this->preventClickjacking = true;
811 }
812
813 /**
814 * @return bool
815 */
816 public function getPreventClickjacking() {
817 return $this->preventClickjacking;
818 }
819
820 /**
821 * Set up date filter options, given request data.
822 *
823 * @param array $opts Options array
824 * @return array Options array with processed start and end date filter options
825 */
826 public static function processDateFilter( array $opts ) {
827 $start = $opts['start'] ?? '';
828 $end = $opts['end'] ?? '';
829 $year = $opts['year'] ?? '';
830 $month = $opts['month'] ?? '';
831
832 if ( $start !== '' && $end !== '' && $start > $end ) {
833 $temp = $start;
834 $start = $end;
835 $end = $temp;
836 }
837
838 // If year/month legacy filtering options are set, convert them to display the new stamp
839 if ( $year !== '' || $month !== '' ) {
840 // Reuse getDateCond logic, but subtract a day because
841 // the endpoints of our date range appear inclusive
842 // but the internal end offsets are always exclusive
843 $legacyTimestamp = ReverseChronologicalPager::getOffsetDate( $year, $month );
844 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601 ) );
845 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
846
847 // Clear the new timestamp range options if used and
848 // replace with the converted legacy timestamp
849 $start = '';
850 $end = $legacyDateTime->format( 'Y-m-d' );
851 }
852
853 $opts['start'] = $start;
854 $opts['end'] = $end;
855
856 return $opts;
857 }
858 }