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