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