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