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