Merge "EditPage: Factor stats collection into private methods"
[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 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
227 '1' :
228 'ug_expiry IS NULL OR ug_expiry >= ' .
229 $this->mDb->addQuotes( $this->mDb->timestamp() )
230 ]
231 ];
232 }
233 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
234 // a timestamp offset far in the past such that there are no edits by users with user_ids in
235 // the range, we would end up scanning all revisions from that offset until start of time.
236 $condition[] = 'rev_timestamp > ' .
237 $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
238 } else {
239 $uid = User::idFromName( $this->target );
240 if ( $uid ) {
241 $condition['rev_user'] = $uid;
242 $index = 'user_timestamp';
243 } else {
244 $condition['rev_user_text'] = $this->target;
245 $index = 'usertext_timestamp';
246 }
247 }
248
249 if ( $this->deletedOnly ) {
250 $condition[] = 'rev_deleted != 0';
251 }
252
253 if ( $this->topOnly ) {
254 $condition[] = 'rev_id = page_latest';
255 }
256
257 if ( $this->newOnly ) {
258 $condition[] = 'rev_parent_id = 0';
259 }
260
261 if ( $this->hideMinor ) {
262 $condition[] = 'rev_minor_edit = 0';
263 }
264
265 return [ $tables, $index, $condition, $join_conds ];
266 }
267
268 function getNamespaceCond() {
269 if ( $this->namespace !== '' ) {
270 $selectedNS = $this->mDb->addQuotes( $this->namespace );
271 $eq_op = $this->nsInvert ? '!=' : '=';
272 $bool_op = $this->nsInvert ? 'AND' : 'OR';
273
274 if ( !$this->associated ) {
275 return [ "page_namespace $eq_op $selectedNS" ];
276 }
277
278 $associatedNS = $this->mDb->addQuotes(
279 MWNamespace::getAssociated( $this->namespace )
280 );
281
282 return [
283 "page_namespace $eq_op $selectedNS " .
284 $bool_op .
285 " page_namespace $eq_op $associatedNS"
286 ];
287 }
288
289 return [];
290 }
291
292 function getIndexField() {
293 return 'rev_timestamp';
294 }
295
296 function doBatchLookups() {
297 # Do a link batch query
298 $this->mResult->seek( 0 );
299 $parentRevIds = [];
300 $this->mParentLens = [];
301 $batch = new LinkBatch();
302 # Give some pointers to make (last) links
303 foreach ( $this->mResult as $row ) {
304 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
305 $parentRevIds[] = $row->rev_parent_id;
306 }
307 if ( isset( $row->rev_id ) ) {
308 $this->mParentLens[$row->rev_id] = $row->rev_len;
309 if ( $this->contribs === 'newbie' ) { // multiple users
310 $batch->add( NS_USER, $row->user_name );
311 $batch->add( NS_USER_TALK, $row->user_name );
312 }
313 $batch->add( $row->page_namespace, $row->page_title );
314 }
315 }
316 # Fetch rev_len for revisions not already scanned above
317 $this->mParentLens += Revision::getParentLengths(
318 $this->mDbSecondary,
319 array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
320 );
321 $batch->execute();
322 $this->mResult->seek( 0 );
323 }
324
325 /**
326 * @return string
327 */
328 function getStartBody() {
329 return "<ul class=\"mw-contributions-list\">\n";
330 }
331
332 /**
333 * @return string
334 */
335 function getEndBody() {
336 return "</ul>\n";
337 }
338
339 /**
340 * Generates each row in the contributions list.
341 *
342 * Contributions which are marked "top" are currently on top of the history.
343 * For these contributions, a [rollback] link is shown for users with roll-
344 * back privileges. The rollback link restores the most recent version that
345 * was not written by the target user.
346 *
347 * @todo This would probably look a lot nicer in a table.
348 * @param object $row
349 * @return string
350 */
351 function formatRow( $row ) {
352
353 $ret = '';
354 $classes = [];
355
356 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
357
358 /*
359 * There may be more than just revision rows. To make sure that we'll only be processing
360 * revisions here, let's _try_ to build a revision out of our row (without displaying
361 * notices though) and then trying to grab data from the built object. If we succeed,
362 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
363 * to extensions to subscribe to the hook to parse the row.
364 */
365 MediaWiki\suppressWarnings();
366 try {
367 $rev = new Revision( $row );
368 $validRevision = (bool)$rev->getId();
369 } catch ( Exception $e ) {
370 $validRevision = false;
371 }
372 MediaWiki\restoreWarnings();
373
374 if ( $validRevision ) {
375 $classes = [];
376
377 $page = Title::newFromRow( $row );
378 $link = $linkRenderer->makeLink(
379 $page,
380 $page->getPrefixedText(),
381 [ 'class' => 'mw-contributions-title' ],
382 $page->isRedirect() ? [ 'redirect' => 'no' ] : []
383 );
384 # Mark current revisions
385 $topmarktext = '';
386 $user = $this->getUser();
387 if ( $row->rev_id === $row->page_latest ) {
388 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
389 $classes[] = 'mw-contributions-current';
390 # Add rollback link
391 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
392 && $page->quickUserCan( 'edit', $user )
393 ) {
394 $this->preventClickjacking();
395 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
396 }
397 }
398 # Is there a visible previous revision?
399 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
400 $difftext = $linkRenderer->makeKnownLink(
401 $page,
402 new HtmlArmor( $this->messages['diff'] ),
403 [],
404 [
405 'diff' => 'prev',
406 'oldid' => $row->rev_id
407 ]
408 );
409 } else {
410 $difftext = $this->messages['diff'];
411 }
412 $histlink = $linkRenderer->makeKnownLink(
413 $page,
414 new HtmlArmor( $this->messages['hist'] ),
415 [],
416 [ 'action' => 'history' ]
417 );
418
419 if ( $row->rev_parent_id === null ) {
420 // For some reason rev_parent_id isn't populated for this row.
421 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
422 // Next best thing is to have the total number of bytes.
423 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
424 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
425 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
426 } else {
427 $parentLen = 0;
428 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
429 $parentLen = $this->mParentLens[$row->rev_parent_id];
430 }
431
432 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
433 $chardiff .= ChangesList::showCharacterDifference(
434 $parentLen,
435 $row->rev_len,
436 $this->getContext()
437 );
438 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
439 }
440
441 $lang = $this->getLanguage();
442 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
443 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
444 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
445 $d = $linkRenderer->makeKnownLink(
446 $page,
447 $date,
448 [ 'class' => 'mw-changeslist-date' ],
449 [ 'oldid' => intval( $row->rev_id ) ]
450 );
451 } else {
452 $d = htmlspecialchars( $date );
453 }
454 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
455 $d = '<span class="history-deleted">' . $d . '</span>';
456 }
457
458 # Show user names for /newbies as there may be different users.
459 # Note that we already excluded rows with hidden user names.
460 if ( $this->contribs == 'newbie' ) {
461 $userlink = ' . . ' . $lang->getDirMark()
462 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
463 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
464 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
465 } else {
466 $userlink = '';
467 }
468
469 $flags = [];
470 if ( $rev->getParentId() === 0 ) {
471 $flags[] = ChangesList::flag( 'newpage' );
472 }
473
474 if ( $rev->isMinor() ) {
475 $flags[] = ChangesList::flag( 'minor' );
476 }
477
478 $del = Linker::getRevDeleteLink( $user, $rev, $page );
479 if ( $del !== '' ) {
480 $del .= ' ';
481 }
482
483 $diffHistLinks = $this->msg( 'parentheses' )
484 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
485 ->escaped();
486
487 # Tags, if any.
488 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
489 $row->ts_tags,
490 'contributions',
491 $this->getContext()
492 );
493 $classes = array_merge( $classes, $newClasses );
494
495 Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
496
497 $templateParams = [
498 'del' => $del,
499 'timestamp' => $d,
500 'diffHistLinks' => $diffHistLinks,
501 'charDifference' => $chardiff,
502 'flags' => $flags,
503 'articleLink' => $link,
504 'userlink' => $userlink,
505 'logText' => $comment,
506 'topmarktext' => $topmarktext,
507 'tagSummary' => $tagSummary,
508 ];
509
510 # Denote if username is redacted for this edit
511 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
512 $templateParams['rev-deleted-user-contribs'] =
513 $this->msg( 'rev-deleted-user-contribs' )->escaped();
514 }
515
516 $templateParser = new TemplateParser();
517 $ret = $templateParser->processTemplate(
518 'SpecialContributionsLine',
519 $templateParams
520 );
521 }
522
523 // Let extensions add data
524 Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes ] );
525
526 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
527 // receiving empty rows?
528
529 if ( $classes === [] && $ret === '' ) {
530 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
531 return "<!-- Could not format Special:Contribution row. -->\n";
532 }
533
534 // FIXME: The signature of the ContributionsLineEnding hook makes it
535 // very awkward to move this LI wrapper into the template.
536 return Html::rawElement( 'li', [ 'class' => $classes ], $ret ) . "\n";
537 }
538
539 /**
540 * Overwrite Pager function and return a helpful comment
541 * @return string
542 */
543 function getSqlComment() {
544 if ( $this->namespace || $this->deletedOnly ) {
545 // potentially slow, see CR r58153
546 return 'contributions page filtered for namespace or RevisionDeleted edits';
547 } else {
548 return 'contributions page unfiltered';
549 }
550 }
551
552 protected function preventClickjacking() {
553 $this->preventClickjacking = true;
554 }
555
556 /**
557 * @return bool
558 */
559 public function getPreventClickjacking() {
560 return $this->preventClickjacking;
561 }
562 }