Merge "Add tests for SkinTemplate::setupSkinUserCss"
[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
28 class ContribsPager extends ReverseChronologicalPager {
29
30 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
31 public $messages;
32 public $target;
33 public $namespace = '';
34 public $mDb;
35 public $preventClickjacking = false;
36
37 /** @var IDatabase */
38 public $mDbSecondary;
39
40 /**
41 * @var array
42 */
43 protected $mParentLens;
44
45 function __construct( IContextSource $context, array $options ) {
46 parent::__construct( $context );
47
48 $msgs = [
49 'diff',
50 'hist',
51 'pipe-separator',
52 'uctop'
53 ];
54
55 foreach ( $msgs as $msg ) {
56 $this->messages[$msg] = $this->msg( $msg )->escaped();
57 }
58
59 $this->target = isset( $options['target'] ) ? $options['target'] : '';
60 $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users';
61 $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : '';
62 $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false;
63 $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false;
64 $this->associated = isset( $options['associated'] ) ? $options['associated'] : false;
65
66 $this->deletedOnly = !empty( $options['deletedOnly'] );
67 $this->topOnly = !empty( $options['topOnly'] );
68 $this->newOnly = !empty( $options['newOnly'] );
69 $this->hideMinor = !empty( $options['hideMinor'] );
70
71 $year = isset( $options['year'] ) ? $options['year'] : false;
72 $month = isset( $options['month'] ) ? $options['month'] : false;
73 $this->getDateCond( $year, $month );
74
75 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
76 // with extra user based indexes or partioning by user. The additional metadata
77 // queries should use a regular replica DB since the lookup pattern is not all by user.
78 $this->mDbSecondary = wfGetDB( DB_REPLICA ); // any random replica DB
79 $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
80 }
81
82 function getDefaultQuery() {
83 $query = parent::getDefaultQuery();
84 $query['target'] = $this->target;
85
86 return $query;
87 }
88
89 /**
90 * This method basically executes the exact same code as the parent class, though with
91 * a hook added, to allow extensions to add additional queries.
92 *
93 * @param string $offset Index offset, inclusive
94 * @param int $limit Exact query limit
95 * @param bool $descending Query direction, false for ascending, true for descending
96 * @return ResultWrapper
97 */
98 function reallyDoQuery( $offset, $limit, $descending ) {
99 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
100 $offset,
101 $limit,
102 $descending
103 );
104
105 /*
106 * This hook will allow extensions to add in additional queries, so they can get their data
107 * in My Contributions as well. Extensions should append their results to the $data array.
108 *
109 * Extension queries have to implement the navbar requirement as well. They should
110 * - have a column aliased as $pager->getIndexField()
111 * - have LIMIT set
112 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
113 * - have the ORDER BY specified based upon the details provided by the navbar
114 *
115 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
116 *
117 * &$data: an array of results of all contribs queries
118 * $pager: the ContribsPager object hooked into
119 * $offset: see phpdoc above
120 * $limit: see phpdoc above
121 * $descending: see phpdoc above
122 */
123 $data = [ $this->mDb->select(
124 $tables, $fields, $conds, $fname, $options, $join_conds
125 ) ];
126 Hooks::run(
127 'ContribsPager::reallyDoQuery',
128 [ &$data, $this, $offset, $limit, $descending ]
129 );
130
131 $result = [];
132
133 // loop all results and collect them in an array
134 foreach ( $data as $query ) {
135 foreach ( $query as $i => $row ) {
136 // use index column as key, allowing us to easily sort in PHP
137 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
138 }
139 }
140
141 // sort results
142 if ( $descending ) {
143 ksort( $result );
144 } else {
145 krsort( $result );
146 }
147
148 // enforce limit
149 $result = array_slice( $result, 0, $limit );
150
151 // get rid of array keys
152 $result = array_values( $result );
153
154 return new FakeResultWrapper( $result );
155 }
156
157 function getQueryInfo() {
158 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
159
160 $user = $this->getUser();
161 $conds = array_merge( $userCond, $this->getNamespaceCond() );
162
163 // Paranoia: avoid brute force searches (bug 17342)
164 if ( !$user->isAllowed( 'deletedhistory' ) ) {
165 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
166 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
167 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
168 ' != ' . Revision::SUPPRESSED_USER;
169 }
170
171 # Don't include orphaned revisions
172 $join_cond['page'] = Revision::pageJoinCond();
173 # Get the current user name for accounts
174 $join_cond['user'] = Revision::userJoinCond();
175
176 $options = [];
177 if ( $index ) {
178 $options['USE INDEX'] = [ 'revision' => $index ];
179 }
180
181 $queryInfo = [
182 'tables' => $tables,
183 'fields' => array_merge(
184 Revision::selectFields(),
185 Revision::selectUserFields(),
186 [ 'page_namespace', 'page_title', 'page_is_new',
187 'page_latest', 'page_is_redirect', 'page_len' ]
188 ),
189 'conds' => $conds,
190 'options' => $options,
191 'join_conds' => $join_cond
192 ];
193
194 ChangeTags::modifyDisplayQuery(
195 $queryInfo['tables'],
196 $queryInfo['fields'],
197 $queryInfo['conds'],
198 $queryInfo['join_conds'],
199 $queryInfo['options'],
200 $this->tagFilter
201 );
202
203 Hooks::run( 'ContribsPager::getQueryInfo', [ &$this, &$queryInfo ] );
204
205 return $queryInfo;
206 }
207
208 function getUserCond() {
209 $condition = [];
210 $join_conds = [];
211 $tables = [ 'revision', 'page', 'user' ];
212 $index = false;
213 if ( $this->contribs == 'newbie' ) {
214 $max = $this->mDb->selectField( 'user', 'max(user_id)', false, __METHOD__ );
215 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
216 # ignore local groups with the bot right
217 # @todo FIXME: Global groups may have 'bot' rights
218 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
219 if ( count( $groupsWithBotPermission ) ) {
220 $tables[] = 'user_groups';
221 $condition[] = 'ug_group IS NULL';
222 $join_conds['user_groups'] = [
223 'LEFT JOIN', [
224 'ug_user = rev_user',
225 'ug_group' => $groupsWithBotPermission,
226 'ug_expiry IS NULL OR ug_expiry >= ' . $this->mDb->addQuotes( $this->mDb->timestamp() )
227 ]
228 ];
229 }
230 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
231 // a timestamp offset far in the past such that there are no edits by users with user_ids in
232 // the range, we would end up scanning all revisions from that offset until start of time.
233 $condition[] = 'rev_timestamp > ' .
234 $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
235 } else {
236 $uid = User::idFromName( $this->target );
237 if ( $uid ) {
238 $condition['rev_user'] = $uid;
239 $index = 'user_timestamp';
240 } else {
241 $condition['rev_user_text'] = $this->target;
242 $index = 'usertext_timestamp';
243 }
244 }
245
246 if ( $this->deletedOnly ) {
247 $condition[] = 'rev_deleted != 0';
248 }
249
250 if ( $this->topOnly ) {
251 $condition[] = 'rev_id = page_latest';
252 }
253
254 if ( $this->newOnly ) {
255 $condition[] = 'rev_parent_id = 0';
256 }
257
258 if ( $this->hideMinor ) {
259 $condition[] = 'rev_minor_edit = 0';
260 }
261
262 return [ $tables, $index, $condition, $join_conds ];
263 }
264
265 function getNamespaceCond() {
266 if ( $this->namespace !== '' ) {
267 $selectedNS = $this->mDb->addQuotes( $this->namespace );
268 $eq_op = $this->nsInvert ? '!=' : '=';
269 $bool_op = $this->nsInvert ? 'AND' : 'OR';
270
271 if ( !$this->associated ) {
272 return [ "page_namespace $eq_op $selectedNS" ];
273 }
274
275 $associatedNS = $this->mDb->addQuotes(
276 MWNamespace::getAssociated( $this->namespace )
277 );
278
279 return [
280 "page_namespace $eq_op $selectedNS " .
281 $bool_op .
282 " page_namespace $eq_op $associatedNS"
283 ];
284 }
285
286 return [];
287 }
288
289 function getIndexField() {
290 return 'rev_timestamp';
291 }
292
293 function doBatchLookups() {
294 # Do a link batch query
295 $this->mResult->seek( 0 );
296 $parentRevIds = [];
297 $this->mParentLens = [];
298 $batch = new LinkBatch();
299 # Give some pointers to make (last) links
300 foreach ( $this->mResult as $row ) {
301 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
302 $parentRevIds[] = $row->rev_parent_id;
303 }
304 if ( isset( $row->rev_id ) ) {
305 $this->mParentLens[$row->rev_id] = $row->rev_len;
306 if ( $this->contribs === 'newbie' ) { // multiple users
307 $batch->add( NS_USER, $row->user_name );
308 $batch->add( NS_USER_TALK, $row->user_name );
309 }
310 $batch->add( $row->page_namespace, $row->page_title );
311 }
312 }
313 # Fetch rev_len for revisions not already scanned above
314 $this->mParentLens += Revision::getParentLengths(
315 $this->mDbSecondary,
316 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
317 );
318 $batch->execute();
319 $this->mResult->seek( 0 );
320 }
321
322 /**
323 * @return string
324 */
325 function getStartBody() {
326 return "<ul class=\"mw-contributions-list\">\n";
327 }
328
329 /**
330 * @return string
331 */
332 function getEndBody() {
333 return "</ul>\n";
334 }
335
336 /**
337 * Generates each row in the contributions list.
338 *
339 * Contributions which are marked "top" are currently on top of the history.
340 * For these contributions, a [rollback] link is shown for users with roll-
341 * back privileges. The rollback link restores the most recent version that
342 * was not written by the target user.
343 *
344 * @todo This would probably look a lot nicer in a table.
345 * @param object $row
346 * @return string
347 */
348 function formatRow( $row ) {
349
350 $ret = '';
351 $classes = [];
352
353 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
354
355 /*
356 * There may be more than just revision rows. To make sure that we'll only be processing
357 * revisions here, let's _try_ to build a revision out of our row (without displaying
358 * notices though) and then trying to grab data from the built object. If we succeed,
359 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
360 * to extensions to subscribe to the hook to parse the row.
361 */
362 MediaWiki\suppressWarnings();
363 try {
364 $rev = new Revision( $row );
365 $validRevision = (bool)$rev->getId();
366 } catch ( Exception $e ) {
367 $validRevision = false;
368 }
369 MediaWiki\restoreWarnings();
370
371 if ( $validRevision ) {
372 $classes = [];
373
374 $page = Title::newFromRow( $row );
375 $link = $linkRenderer->makeLink(
376 $page,
377 $page->getPrefixedText(),
378 [ 'class' => 'mw-contributions-title' ],
379 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
380 );
381 # Mark current revisions
382 $topmarktext = '';
383 $user = $this->getUser();
384 if ( $row->rev_id === $row->page_latest ) {
385 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
386 $classes[] = 'mw-contributions-current';
387 # Add rollback link
388 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
389 && $page->quickUserCan( 'edit', $user )
390 ) {
391 $this->preventClickjacking();
392 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
393 }
394 }
395 # Is there a visible previous revision?
396 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
397 $difftext = $linkRenderer->makeKnownLink(
398 $page,
399 new HtmlArmor( $this->messages['diff'] ),
400 [],
401 [
402 'diff' => 'prev',
403 'oldid' => $row->rev_id
404 ]
405 );
406 } else {
407 $difftext = $this->messages['diff'];
408 }
409 $histlink = $linkRenderer->makeKnownLink(
410 $page,
411 new HtmlArmor( $this->messages['hist'] ),
412 [],
413 [ 'action' => 'history' ]
414 );
415
416 if ( $row->rev_parent_id === null ) {
417 // For some reason rev_parent_id isn't populated for this row.
418 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
419 // Next best thing is to have the total number of bytes.
420 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
421 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
422 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
423 } else {
424 $parentLen = 0;
425 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
426 $parentLen = $this->mParentLens[$row->rev_parent_id];
427 }
428
429 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
430 $chardiff .= ChangesList::showCharacterDifference(
431 $parentLen,
432 $row->rev_len,
433 $this->getContext()
434 );
435 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
436 }
437
438 $lang = $this->getLanguage();
439 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
440 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
441 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
442 $d = $linkRenderer->makeKnownLink(
443 $page,
444 $date,
445 [ 'class' => 'mw-changeslist-date' ],
446 [ 'oldid' => intval( $row->rev_id ) ]
447 );
448 } else {
449 $d = htmlspecialchars( $date );
450 }
451 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
452 $d = '<span class="history-deleted">' . $d . '</span>';
453 }
454
455 # Show user names for /newbies as there may be different users.
456 # Note that we already excluded rows with hidden user names.
457 if ( $this->contribs == 'newbie' ) {
458 $userlink = ' . . ' . $lang->getDirMark()
459 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
460 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
461 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
462 } else {
463 $userlink = '';
464 }
465
466 $flags = [];
467 if ( $rev->getParentId() === 0 ) {
468 $flags[] = ChangesList::flag( 'newpage' );
469 }
470
471 if ( $rev->isMinor() ) {
472 $flags[] = ChangesList::flag( 'minor' );
473 }
474
475 $del = Linker::getRevDeleteLink( $user, $rev, $page );
476 if ( $del !== '' ) {
477 $del .= ' ';
478 }
479
480 $diffHistLinks = $this->msg( 'parentheses' )
481 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
482 ->escaped();
483
484 # Tags, if any.
485 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
486 $row->ts_tags,
487 'contributions',
488 $this->getContext()
489 );
490 $classes = array_merge( $classes, $newClasses );
491
492 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
493
494 $templateParams = [
495 'del' => $del,
496 'timestamp' => $d,
497 'diffHistLinks' => $diffHistLinks,
498 'charDifference' => $chardiff,
499 'flags' => $flags,
500 'articleLink' => $link,
501 'userlink' => $userlink,
502 'logText' => $comment,
503 'topmarktext' => $topmarktext,
504 'tagSummary' => $tagSummary,
505 ];
506
507 # Denote if username is redacted for this edit
508 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
509 $templateParams['rev-deleted-user-contribs'] =
510 $this->msg( 'rev-deleted-user-contribs' )->escaped();
511 }
512
513 $templateParser = new TemplateParser();
514 $ret = $templateParser->processTemplate(
515 'SpecialContributionsLine',
516 $templateParams
517 );
518 }
519
520 // Let extensions add data
521 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
522
523 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
524 // receiving empty rows?
525
526 if ( $classes === [] && $ret === '' ) {
527 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
528 return "<!-- Could not format Special:Contribution row. -->\n";
529 }
530
531 // FIXME: The signature of the ContributionsLineEnding hook makes it
532 // very awkward to move this LI wrapper into the template.
533 return Html::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
534 }
535
536 /**
537 * Overwrite Pager function and return a helpful comment
538 * @return string
539 */
540 function getSqlComment() {
541 if ( $this->namespace || $this->deletedOnly ) {
542 // potentially slow, see CR r58153
543 return 'contributions page filtered for namespace or RevisionDeleted edits';
544 } else {
545 return 'contributions page unfiltered';
546 }
547 }
548
549 protected function preventClickjacking() {
550 $this->preventClickjacking = true;
551 }
552
553 /**
554 * @return bool
555 */
556 public function getPreventClickjacking() {
557 return $this->preventClickjacking;
558 }
559 }