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