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