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