Special:Contribs: autofocus to 'target' if target hasn't been specified or in non...
[lhc/web/wiklou.git] / includes / specials / SpecialContributions.php
1 <?php
2 /**
3 * Implements Special:Contributions
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Special:Contributions, show user contributions in a paged list
26 *
27 * @ingroup SpecialPage
28 */
29 class SpecialContributions extends IncludableSpecialPage {
30 protected $opts;
31
32 public function __construct() {
33 parent::__construct( 'Contributions' );
34 }
35
36 public function execute( $par ) {
37 $this->setHeaders();
38 $this->outputHeader();
39 $out = $this->getOutput();
40 $out->addModuleStyles( 'mediawiki.special' );
41 $this->addHelpLink( 'Help:User contributions' );
42
43 $this->opts = array();
44 $request = $this->getRequest();
45
46 if ( $par !== null ) {
47 $target = $par;
48 } else {
49 $target = $request->getVal( 'target' );
50 }
51
52 // check for radiobox
53 if ( $request->getVal( 'contribs' ) == 'newbie' ) {
54 $target = 'newbies';
55 $this->opts['contribs'] = 'newbie';
56 } elseif ( $par === 'newbies' ) { // b/c for WMF
57 $target = 'newbies';
58 $this->opts['contribs'] = 'newbie';
59 } else {
60 $this->opts['contribs'] = 'user';
61 }
62
63 $this->opts['deletedOnly'] = $request->getBool( 'deletedOnly' );
64
65 if ( !strlen( $target ) ) {
66 if ( !$this->including() ) {
67 $out->addHTML( $this->getForm() );
68 }
69
70 return;
71 }
72
73 $user = $this->getUser();
74
75 $this->opts['limit'] = $request->getInt( 'limit', $user->getOption( 'rclimit' ) );
76 $this->opts['target'] = $target;
77 $this->opts['topOnly'] = $request->getBool( 'topOnly' );
78 $this->opts['newOnly'] = $request->getBool( 'newOnly' );
79
80 $nt = Title::makeTitleSafe( NS_USER, $target );
81 if ( !$nt ) {
82 $out->addHTML( $this->getForm() );
83
84 return;
85 }
86 $userObj = User::newFromName( $nt->getText(), false );
87 if ( !$userObj ) {
88 $out->addHTML( $this->getForm() );
89
90 return;
91 }
92 $id = $userObj->getID();
93
94 if ( $this->opts['contribs'] != 'newbie' ) {
95 $target = $nt->getText();
96 $out->addSubtitle( $this->contributionsSub( $userObj ) );
97 $out->setHTMLTitle( $this->msg(
98 'pagetitle',
99 $this->msg( 'contributions-title', $target )->plain()
100 )->inContentLanguage() );
101 $this->getSkin()->setRelevantUser( $userObj );
102 } else {
103 $out->addSubtitle( $this->msg( 'sp-contributions-newbies-sub' ) );
104 $out->setHTMLTitle( $this->msg(
105 'pagetitle',
106 $this->msg( 'sp-contributions-newbies-title' )->plain()
107 )->inContentLanguage() );
108 }
109
110 $ns = $request->getVal( 'namespace', null );
111 if ( $ns !== null && $ns !== '' ) {
112 $this->opts['namespace'] = intval( $ns );
113 } else {
114 $this->opts['namespace'] = '';
115 }
116
117 $this->opts['associated'] = $request->getBool( 'associated' );
118 $this->opts['nsInvert'] = (bool)$request->getVal( 'nsInvert' );
119 $this->opts['tagfilter'] = (string)$request->getVal( 'tagfilter' );
120
121 // Allows reverts to have the bot flag in recent changes. It is just here to
122 // be passed in the form at the top of the page
123 if ( $user->isAllowed( 'markbotedits' ) && $request->getBool( 'bot' ) ) {
124 $this->opts['bot'] = '1';
125 }
126
127 $skip = $request->getText( 'offset' ) || $request->getText( 'dir' ) == 'prev';
128 # Offset overrides year/month selection
129 if ( $skip ) {
130 $this->opts['year'] = '';
131 $this->opts['month'] = '';
132 } else {
133 $this->opts['year'] = $request->getIntOrNull( 'year' );
134 $this->opts['month'] = $request->getIntOrNull( 'month' );
135 }
136
137 $feedType = $request->getVal( 'feed' );
138
139 $feedParams = array(
140 'action' => 'feedcontributions',
141 'user' => $target,
142 );
143 if ( $this->opts['topOnly'] ) {
144 $feedParams['toponly'] = true;
145 }
146 if ( $this->opts['newOnly'] ) {
147 $feedParams['newonly'] = true;
148 }
149 if ( $this->opts['deletedOnly'] ) {
150 $feedParams['deletedonly'] = true;
151 }
152 if ( $this->opts['tagfilter'] !== '' ) {
153 $feedParams['tagfilter'] = $this->opts['tagfilter'];
154 }
155 if ( $this->opts['namespace'] !== '' ) {
156 $feedParams['namespace'] = $this->opts['namespace'];
157 }
158 // Don't use year and month for the feed URL, but pass them on if
159 // we redirect to API (if $feedType is specified)
160 if ( $feedType && $this->opts['year'] !== null ) {
161 $feedParams['year'] = $this->opts['year'];
162 }
163 if ( $feedType && $this->opts['month'] !== null ) {
164 $feedParams['month'] = $this->opts['month'];
165 }
166
167 if ( $feedType ) {
168 // Maintain some level of backwards compatibility
169 // If people request feeds using the old parameters, redirect to API
170 $feedParams['feedformat'] = $feedType;
171 $url = wfAppendQuery( wfScript( 'api' ), $feedParams );
172
173 $out->redirect( $url, '301' );
174
175 return;
176 }
177
178 // Add RSS/atom links
179 $this->addFeedLinks( $feedParams );
180
181 if ( Hooks::run( 'SpecialContributionsBeforeMainOutput', array( $id, $userObj, $this ) ) ) {
182 if ( !$this->including() ) {
183 $out->addHTML( $this->getForm() );
184 }
185 $pager = new ContribsPager( $this->getContext(), array(
186 'target' => $target,
187 'contribs' => $this->opts['contribs'],
188 'namespace' => $this->opts['namespace'],
189 'tagfilter' => $this->opts['tagfilter'],
190 'year' => $this->opts['year'],
191 'month' => $this->opts['month'],
192 'deletedOnly' => $this->opts['deletedOnly'],
193 'topOnly' => $this->opts['topOnly'],
194 'newOnly' => $this->opts['newOnly'],
195 'nsInvert' => $this->opts['nsInvert'],
196 'associated' => $this->opts['associated'],
197 ) );
198
199 if ( !$pager->getNumRows() ) {
200 $out->addWikiMsg( 'nocontribs', $target );
201 } else {
202 # Show a message about slave lag, if applicable
203 $lag = wfGetLB()->safeGetLag( $pager->getDatabase() );
204 if ( $lag > 0 ) {
205 $out->showLagWarning( $lag );
206 }
207
208 $output = $pager->getBody();
209 if ( !$this->including() ) {
210 $output = '<p>' . $pager->getNavigationBar() . '</p>' .
211 $output .
212 '<p>' . $pager->getNavigationBar() . '</p>';
213 }
214 $out->addHTML( $output );
215 }
216 $out->preventClickjacking( $pager->getPreventClickjacking() );
217
218 # Show the appropriate "footer" message - WHOIS tools, etc.
219 if ( $this->opts['contribs'] == 'newbie' ) {
220 $message = 'sp-contributions-footer-newbies';
221 } elseif ( IP::isIPAddress( $target ) ) {
222 $message = 'sp-contributions-footer-anon';
223 } elseif ( $userObj->isAnon() ) {
224 // No message for non-existing users
225 $message = '';
226 } else {
227 $message = 'sp-contributions-footer';
228 }
229
230 if ( $message ) {
231 if ( !$this->including() ) {
232 if ( !$this->msg( $message, $target )->isDisabled() ) {
233 $out->wrapWikiMsg(
234 "<div class='mw-contributions-footer'>\n$1\n</div>",
235 array( $message, $target ) );
236 }
237 }
238 }
239 }
240 }
241
242 /**
243 * Generates the subheading with links
244 * @param User $userObj User object for the target
245 * @return string Appropriately-escaped HTML to be output literally
246 * @todo FIXME: Almost the same as getSubTitle in SpecialDeletedContributions.php.
247 * Could be combined.
248 */
249 protected function contributionsSub( $userObj ) {
250 if ( $userObj->isAnon() ) {
251 // Show a warning message that the user being searched for doesn't exists
252 if ( !User::isIP( $userObj->getName() ) ) {
253 $this->getOutput()->wrapWikiMsg(
254 "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
255 array(
256 'contributions-userdoesnotexist',
257 wfEscapeWikiText( $userObj->getName() ),
258 )
259 );
260 if ( !$this->including() ) {
261 $this->getOutput()->setStatusCode( 404 );
262 }
263 }
264 $user = htmlspecialchars( $userObj->getName() );
265 } else {
266 $user = Linker::link( $userObj->getUserPage(), htmlspecialchars( $userObj->getName() ) );
267 }
268 $nt = $userObj->getUserPage();
269 $talk = $userObj->getTalkPage();
270 $links = '';
271 if ( $talk ) {
272 $tools = $this->getUserLinks( $nt, $talk, $userObj );
273 $links = $this->getLanguage()->pipeList( $tools );
274
275 // Show a note if the user is blocked and display the last block log entry.
276 // Do not expose the autoblocks, since that may lead to a leak of accounts' IPs,
277 // and also this will display a totally irrelevant log entry as a current block.
278 if ( !$this->including() ) {
279 $block = Block::newFromTarget( $userObj, $userObj );
280 if ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
281 if ( $block->getType() == Block::TYPE_RANGE ) {
282 $nt = MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget();
283 }
284
285 $out = $this->getOutput(); // showLogExtract() wants first parameter by reference
286 LogEventsList::showLogExtract(
287 $out,
288 'block',
289 $nt,
290 '',
291 array(
292 'lim' => 1,
293 'showIfEmpty' => false,
294 'msgKey' => array(
295 $userObj->isAnon() ?
296 'sp-contributions-blocked-notice-anon' :
297 'sp-contributions-blocked-notice',
298 $userObj->getName() # Support GENDER in 'sp-contributions-blocked-notice'
299 ),
300 'offset' => '' # don't use WebRequest parameter offset
301 )
302 );
303 }
304 }
305 }
306
307 return $this->msg( 'contribsub2' )->rawParams( $user, $links )->params( $userObj->getName() );
308 }
309
310 /**
311 * Links to different places.
312 * @param Title $userpage Target user page
313 * @param Title $talkpage Talk page
314 * @param User $target Target user object
315 * @return array
316 */
317 public function getUserLinks( Title $userpage, Title $talkpage, User $target ) {
318
319 $id = $target->getId();
320 $username = $target->getName();
321
322 $tools[] = Linker::link( $talkpage, $this->msg( 'sp-contributions-talk' )->escaped() );
323
324 if ( ( $id !== null ) || ( $id === null && IP::isIPAddress( $username ) ) ) {
325 if ( $this->getUser()->isAllowed( 'block' ) ) { # Block / Change block / Unblock links
326 if ( $target->isBlocked() && $target->getBlock()->getType() != Block::TYPE_AUTO ) {
327 $tools[] = Linker::linkKnown( # Change block link
328 SpecialPage::getTitleFor( 'Block', $username ),
329 $this->msg( 'change-blocklink' )->escaped()
330 );
331 $tools[] = Linker::linkKnown( # Unblock link
332 SpecialPage::getTitleFor( 'Unblock', $username ),
333 $this->msg( 'unblocklink' )->escaped()
334 );
335 } else { # User is not blocked
336 $tools[] = Linker::linkKnown( # Block link
337 SpecialPage::getTitleFor( 'Block', $username ),
338 $this->msg( 'blocklink' )->escaped()
339 );
340 }
341 }
342
343 # Block log link
344 $tools[] = Linker::linkKnown(
345 SpecialPage::getTitleFor( 'Log', 'block' ),
346 $this->msg( 'sp-contributions-blocklog' )->escaped(),
347 array(),
348 array( 'page' => $userpage->getPrefixedText() )
349 );
350
351 # Suppression log link (bug 59120)
352 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
353 $tools[] = Linker::linkKnown(
354 SpecialPage::getTitleFor( 'Log', 'suppress' ),
355 $this->msg( 'sp-contributions-suppresslog' )->escaped(),
356 array(),
357 array( 'offender' => $username )
358 );
359 }
360 }
361 # Uploads
362 $tools[] = Linker::linkKnown(
363 SpecialPage::getTitleFor( 'Listfiles', $username ),
364 $this->msg( 'sp-contributions-uploads' )->escaped()
365 );
366
367 # Other logs link
368 $tools[] = Linker::linkKnown(
369 SpecialPage::getTitleFor( 'Log', $username ),
370 $this->msg( 'sp-contributions-logs' )->escaped()
371 );
372
373 # Add link to deleted user contributions for priviledged users
374 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
375 $tools[] = Linker::linkKnown(
376 SpecialPage::getTitleFor( 'DeletedContributions', $username ),
377 $this->msg( 'sp-contributions-deleted' )->escaped()
378 );
379 }
380
381 # Add a link to change user rights for privileged users
382 $userrightsPage = new UserrightsPage();
383 $userrightsPage->setContext( $this->getContext() );
384 if ( $userrightsPage->userCanChangeRights( $target ) ) {
385 $tools[] = Linker::linkKnown(
386 SpecialPage::getTitleFor( 'Userrights', $username ),
387 $this->msg( 'sp-contributions-userrights' )->escaped()
388 );
389 }
390
391 Hooks::run( 'ContributionsToolLinks', array( $id, $userpage, &$tools ) );
392
393 return $tools;
394 }
395
396 /**
397 * Generates the namespace selector form with hidden attributes.
398 * @return string HTML fragment
399 */
400 protected function getForm() {
401 $this->opts['title'] = $this->getPageTitle()->getPrefixedText();
402 if ( !isset( $this->opts['target'] ) ) {
403 $this->opts['target'] = '';
404 } else {
405 $this->opts['target'] = str_replace( '_', ' ', $this->opts['target'] );
406 }
407
408 if ( !isset( $this->opts['namespace'] ) ) {
409 $this->opts['namespace'] = '';
410 }
411
412 if ( !isset( $this->opts['nsInvert'] ) ) {
413 $this->opts['nsInvert'] = '';
414 }
415
416 if ( !isset( $this->opts['associated'] ) ) {
417 $this->opts['associated'] = false;
418 }
419
420 if ( !isset( $this->opts['contribs'] ) ) {
421 $this->opts['contribs'] = 'user';
422 }
423
424 if ( !isset( $this->opts['year'] ) ) {
425 $this->opts['year'] = '';
426 }
427
428 if ( !isset( $this->opts['month'] ) ) {
429 $this->opts['month'] = '';
430 }
431
432 if ( $this->opts['contribs'] == 'newbie' ) {
433 $this->opts['target'] = '';
434 }
435
436 if ( !isset( $this->opts['tagfilter'] ) ) {
437 $this->opts['tagfilter'] = '';
438 }
439
440 if ( !isset( $this->opts['topOnly'] ) ) {
441 $this->opts['topOnly'] = false;
442 }
443
444 if ( !isset( $this->opts['newOnly'] ) ) {
445 $this->opts['newOnly'] = false;
446 }
447
448 $form = Html::openElement(
449 'form',
450 array(
451 'method' => 'get',
452 'action' => wfScript(),
453 'class' => 'mw-contributions-form'
454 )
455 );
456
457 # Add hidden params for tracking except for parameters in $skipParameters
458 $skipParameters = array(
459 'namespace',
460 'nsInvert',
461 'deletedOnly',
462 'target',
463 'contribs',
464 'year',
465 'month',
466 'topOnly',
467 'newOnly',
468 'associated'
469 );
470
471 foreach ( $this->opts as $name => $value ) {
472 if ( in_array( $name, $skipParameters ) ) {
473 continue;
474 }
475 $form .= "\t" . Html::hidden( $name, $value ) . "\n";
476 }
477
478 $tagFilter = ChangeTags::buildTagFilterSelector( $this->opts['tagfilter'] );
479
480 if ( $tagFilter ) {
481 $filterSelection = Html::rawElement(
482 'td',
483 array(),
484 array_shift( $tagFilter ) . implode( '&#160', $tagFilter )
485 );
486 } else {
487 $filterSelection = Html::rawElement( 'td', array( 'colspan' => 2 ), '' );
488 }
489
490 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
491
492 $labelNewbies = Xml::radioLabel(
493 $this->msg( 'sp-contributions-newbies' )->text(),
494 'contribs',
495 'newbie',
496 'newbie',
497 $this->opts['contribs'] == 'newbie',
498 array( 'class' => 'mw-input' )
499 );
500 $labelUsername = Xml::radioLabel(
501 $this->msg( 'sp-contributions-username' )->text(),
502 'contribs',
503 'user',
504 'user',
505 $this->opts['contribs'] == 'user',
506 array( 'class' => 'mw-input' )
507 );
508 $input = Html::input(
509 'target',
510 $this->opts['target'],
511 'text',
512 array(
513 'size' => '40',
514 'required' => '',
515 'class' => array(
516 'mw-input',
517 'mw-ui-input-inline',
518 'mw-autocomplete-user', // used by mediawiki.userSuggest
519 ),
520 ) + (
521 // Only autofocus if target hasn't been specified or in non-newbies mode
522 ( $this->opts['contribs'] === 'newbie' || $this->opts['target'] )
523 ? array() : array( 'autofocus' => true )
524 )
525 );
526
527 $targetSelection = Html::rawElement(
528 'td',
529 array( 'colspan' => 2 ),
530 $labelNewbies . '<br />' . $labelUsername . ' ' . $input . ' '
531 );
532
533 $namespaceSelection = Xml::tags(
534 'td',
535 array(),
536 Xml::label(
537 $this->msg( 'namespace' )->text(),
538 'namespace',
539 ''
540 ) .
541 Html::namespaceSelector(
542 array( 'selected' => $this->opts['namespace'], 'all' => '' ),
543 array(
544 'name' => 'namespace',
545 'id' => 'namespace',
546 'class' => 'namespaceselector',
547 )
548 ) . '&#160;' .
549 Html::rawElement(
550 'span',
551 array( 'class' => 'mw-input-with-label' ),
552 Xml::checkLabel(
553 $this->msg( 'invert' )->text(),
554 'nsInvert',
555 'nsInvert',
556 $this->opts['nsInvert'],
557 array(
558 'title' => $this->msg( 'tooltip-invert' )->text(),
559 'class' => 'mw-input'
560 )
561 ) . '&#160;'
562 ) .
563 Html::rawElement( 'span', array( 'class' => 'mw-input-with-label' ),
564 Xml::checkLabel(
565 $this->msg( 'namespace_association' )->text(),
566 'associated',
567 'associated',
568 $this->opts['associated'],
569 array(
570 'title' => $this->msg( 'tooltip-namespace_association' )->text(),
571 'class' => 'mw-input'
572 )
573 ) . '&#160;'
574 )
575 );
576
577 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
578 $deletedOnlyCheck = Html::rawElement(
579 'span',
580 array( 'class' => 'mw-input-with-label' ),
581 Xml::checkLabel(
582 $this->msg( 'history-show-deleted' )->text(),
583 'deletedOnly',
584 'mw-show-deleted-only',
585 $this->opts['deletedOnly'],
586 array( 'class' => 'mw-input' )
587 )
588 );
589 } else {
590 $deletedOnlyCheck = '';
591 }
592
593 $checkLabelTopOnly = Html::rawElement(
594 'span',
595 array( 'class' => 'mw-input-with-label' ),
596 Xml::checkLabel(
597 $this->msg( 'sp-contributions-toponly' )->text(),
598 'topOnly',
599 'mw-show-top-only',
600 $this->opts['topOnly'],
601 array( 'class' => 'mw-input' )
602 )
603 );
604 $checkLabelNewOnly = Html::rawElement(
605 'span',
606 array( 'class' => 'mw-input-with-label' ),
607 Xml::checkLabel(
608 $this->msg( 'sp-contributions-newonly' )->text(),
609 'newOnly',
610 'mw-show-new-only',
611 $this->opts['newOnly'],
612 array( 'class' => 'mw-input' )
613 )
614 );
615 $extraOptions = Html::rawElement(
616 'td',
617 array( 'colspan' => 2 ),
618 $deletedOnlyCheck . $checkLabelTopOnly . $checkLabelNewOnly
619 );
620
621 $dateSelectionAndSubmit = Xml::tags( 'td', array( 'colspan' => 2 ),
622 Xml::dateMenu(
623 $this->opts['year'] === '' ? MWTimestamp::getInstance()->format( 'Y' ) : $this->opts['year'],
624 $this->opts['month']
625 ) . ' ' .
626 Html::submitButton(
627 $this->msg( 'sp-contributions-submit' )->text(),
628 array( 'class' => 'mw-submit' ), array( 'mw-ui-progressive' )
629 )
630 );
631
632 $form .= Xml::fieldset( $this->msg( 'sp-contributions-search' )->text() );
633 $form .= Html::rawElement( 'table', array( 'class' => 'mw-contributions-table' ), "\n" .
634 Html::rawElement( 'tr', array(), $targetSelection ) . "\n" .
635 Html::rawElement( 'tr', array(), $namespaceSelection ) . "\n" .
636 Html::rawElement( 'tr', array(), $filterSelection ) . "\n" .
637 Html::rawElement( 'tr', array(), $extraOptions ) . "\n" .
638 Html::rawElement( 'tr', array(), $dateSelectionAndSubmit ) . "\n"
639 );
640
641 $explain = $this->msg( 'sp-contributions-explain' );
642 if ( !$explain->isBlank() ) {
643 $form .= "<p id='mw-sp-contributions-explain'>{$explain->parse()}</p>";
644 }
645
646 $form .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' );
647
648 return $form;
649 }
650
651 protected function getGroupName() {
652 return 'users';
653 }
654 }
655
656 /**
657 * Pager for Special:Contributions
658 * @ingroup SpecialPage Pager
659 */
660 class ContribsPager extends ReverseChronologicalPager {
661 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
662 public $messages;
663 public $target;
664 public $namespace = '';
665 public $mDb;
666 public $preventClickjacking = false;
667
668 /** @var IDatabase */
669 public $mDbSecondary;
670
671 /**
672 * @var array
673 */
674 protected $mParentLens;
675
676 function __construct( IContextSource $context, array $options ) {
677 parent::__construct( $context );
678
679 $msgs = array(
680 'diff',
681 'hist',
682 'pipe-separator',
683 'uctop'
684 );
685
686 foreach ( $msgs as $msg ) {
687 $this->messages[$msg] = $this->msg( $msg )->escaped();
688 }
689
690 $this->target = isset( $options['target'] ) ? $options['target'] : '';
691 $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users';
692 $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : '';
693 $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false;
694 $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false;
695 $this->associated = isset( $options['associated'] ) ? $options['associated'] : false;
696
697 $this->deletedOnly = !empty( $options['deletedOnly'] );
698 $this->topOnly = !empty( $options['topOnly'] );
699 $this->newOnly = !empty( $options['newOnly'] );
700
701 $year = isset( $options['year'] ) ? $options['year'] : false;
702 $month = isset( $options['month'] ) ? $options['month'] : false;
703 $this->getDateCond( $year, $month );
704
705 // Most of this code will use the 'contributions' group DB, which can map to slaves
706 // with extra user based indexes or partioning by user. The additional metadata
707 // queries should use a regular slave since the lookup pattern is not all by user.
708 $this->mDbSecondary = wfGetDB( DB_SLAVE ); // any random slave
709 $this->mDb = wfGetDB( DB_SLAVE, 'contributions' );
710 }
711
712 function getDefaultQuery() {
713 $query = parent::getDefaultQuery();
714 $query['target'] = $this->target;
715
716 return $query;
717 }
718
719 /**
720 * This method basically executes the exact same code as the parent class, though with
721 * a hook added, to allow extensions to add additional queries.
722 *
723 * @param string $offset Index offset, inclusive
724 * @param int $limit Exact query limit
725 * @param bool $descending Query direction, false for ascending, true for descending
726 * @return ResultWrapper
727 */
728 function reallyDoQuery( $offset, $limit, $descending ) {
729 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
730 $offset,
731 $limit,
732 $descending
733 );
734
735 /*
736 * This hook will allow extensions to add in additional queries, so they can get their data
737 * in My Contributions as well. Extensions should append their results to the $data array.
738 *
739 * Extension queries have to implement the navbar requirement as well. They should
740 * - have a column aliased as $pager->getIndexField()
741 * - have LIMIT set
742 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
743 * - have the ORDER BY specified based upon the details provided by the navbar
744 *
745 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
746 *
747 * &$data: an array of results of all contribs queries
748 * $pager: the ContribsPager object hooked into
749 * $offset: see phpdoc above
750 * $limit: see phpdoc above
751 * $descending: see phpdoc above
752 */
753 $data = array( $this->mDb->select(
754 $tables, $fields, $conds, $fname, $options, $join_conds
755 ) );
756 Hooks::run(
757 'ContribsPager::reallyDoQuery',
758 array( &$data, $this, $offset, $limit, $descending )
759 );
760
761 $result = array();
762
763 // loop all results and collect them in an array
764 foreach ( $data as $query ) {
765 foreach ( $query as $i => $row ) {
766 // use index column as key, allowing us to easily sort in PHP
767 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
768 }
769 }
770
771 // sort results
772 if ( $descending ) {
773 ksort( $result );
774 } else {
775 krsort( $result );
776 }
777
778 // enforce limit
779 $result = array_slice( $result, 0, $limit );
780
781 // get rid of array keys
782 $result = array_values( $result );
783
784 return new FakeResultWrapper( $result );
785 }
786
787 function getQueryInfo() {
788 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
789
790 $user = $this->getUser();
791 $conds = array_merge( $userCond, $this->getNamespaceCond() );
792
793 // Paranoia: avoid brute force searches (bug 17342)
794 if ( !$user->isAllowed( 'deletedhistory' ) ) {
795 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
796 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
797 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
798 ' != ' . Revision::SUPPRESSED_USER;
799 }
800
801 # Don't include orphaned revisions
802 $join_cond['page'] = Revision::pageJoinCond();
803 # Get the current user name for accounts
804 $join_cond['user'] = Revision::userJoinCond();
805
806 $options = array();
807 if ( $index ) {
808 $options['USE INDEX'] = array( 'revision' => $index );
809 }
810
811 $queryInfo = array(
812 'tables' => $tables,
813 'fields' => array_merge(
814 Revision::selectFields(),
815 Revision::selectUserFields(),
816 array( 'page_namespace', 'page_title', 'page_is_new',
817 'page_latest', 'page_is_redirect', 'page_len' )
818 ),
819 'conds' => $conds,
820 'options' => $options,
821 'join_conds' => $join_cond
822 );
823
824 ChangeTags::modifyDisplayQuery(
825 $queryInfo['tables'],
826 $queryInfo['fields'],
827 $queryInfo['conds'],
828 $queryInfo['join_conds'],
829 $queryInfo['options'],
830 $this->tagFilter
831 );
832
833 Hooks::run( 'ContribsPager::getQueryInfo', array( &$this, &$queryInfo ) );
834
835 return $queryInfo;
836 }
837
838 function getUserCond() {
839 $condition = array();
840 $join_conds = array();
841 $tables = array( 'revision', 'page', 'user' );
842 $index = false;
843 if ( $this->contribs == 'newbie' ) {
844 $max = $this->mDb->selectField( 'user', 'max(user_id)', false, __METHOD__ );
845 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
846 # ignore local groups with the bot right
847 # @todo FIXME: Global groups may have 'bot' rights
848 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
849 if ( count( $groupsWithBotPermission ) ) {
850 $tables[] = 'user_groups';
851 $condition[] = 'ug_group IS NULL';
852 $join_conds['user_groups'] = array(
853 'LEFT JOIN', array(
854 'ug_user = rev_user',
855 'ug_group' => $groupsWithBotPermission
856 )
857 );
858 }
859 } else {
860 $uid = User::idFromName( $this->target );
861 if ( $uid ) {
862 $condition['rev_user'] = $uid;
863 $index = 'user_timestamp';
864 } else {
865 $condition['rev_user_text'] = $this->target;
866 $index = 'usertext_timestamp';
867 }
868 }
869
870 if ( $this->deletedOnly ) {
871 $condition[] = 'rev_deleted != 0';
872 }
873
874 if ( $this->topOnly ) {
875 $condition[] = 'rev_id = page_latest';
876 }
877
878 if ( $this->newOnly ) {
879 $condition[] = 'rev_parent_id = 0';
880 }
881
882 return array( $tables, $index, $condition, $join_conds );
883 }
884
885 function getNamespaceCond() {
886 if ( $this->namespace !== '' ) {
887 $selectedNS = $this->mDb->addQuotes( $this->namespace );
888 $eq_op = $this->nsInvert ? '!=' : '=';
889 $bool_op = $this->nsInvert ? 'AND' : 'OR';
890
891 if ( !$this->associated ) {
892 return array( "page_namespace $eq_op $selectedNS" );
893 }
894
895 $associatedNS = $this->mDb->addQuotes(
896 MWNamespace::getAssociated( $this->namespace )
897 );
898
899 return array(
900 "page_namespace $eq_op $selectedNS " .
901 $bool_op .
902 " page_namespace $eq_op $associatedNS"
903 );
904 }
905
906 return array();
907 }
908
909 function getIndexField() {
910 return 'rev_timestamp';
911 }
912
913 function doBatchLookups() {
914 # Do a link batch query
915 $this->mResult->seek( 0 );
916 $revIds = array();
917 $batch = new LinkBatch();
918 # Give some pointers to make (last) links
919 foreach ( $this->mResult as $row ) {
920 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
921 $revIds[] = $row->rev_parent_id;
922 }
923 if ( isset( $row->rev_id ) ) {
924 if ( $this->contribs === 'newbie' ) { // multiple users
925 $batch->add( NS_USER, $row->user_name );
926 $batch->add( NS_USER_TALK, $row->user_name );
927 }
928 $batch->add( $row->page_namespace, $row->page_title );
929 }
930 }
931 $this->mParentLens = Revision::getParentLengths( $this->mDbSecondary, $revIds );
932 $batch->execute();
933 $this->mResult->seek( 0 );
934 }
935
936 /**
937 * @return string
938 */
939 function getStartBody() {
940 return "<ul class=\"mw-contributions-list\">\n";
941 }
942
943 /**
944 * @return string
945 */
946 function getEndBody() {
947 return "</ul>\n";
948 }
949
950 /**
951 * Generates each row in the contributions list.
952 *
953 * Contributions which are marked "top" are currently on top of the history.
954 * For these contributions, a [rollback] link is shown for users with roll-
955 * back privileges. The rollback link restores the most recent version that
956 * was not written by the target user.
957 *
958 * @todo This would probably look a lot nicer in a table.
959 * @param object $row
960 * @return string
961 */
962 function formatRow( $row ) {
963
964 $ret = '';
965 $classes = array();
966
967 /*
968 * There may be more than just revision rows. To make sure that we'll only be processing
969 * revisions here, let's _try_ to build a revision out of our row (without displaying
970 * notices though) and then trying to grab data from the built object. If we succeed,
971 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
972 * to extensions to subscribe to the hook to parse the row.
973 */
974 MediaWiki\suppressWarnings();
975 try {
976 $rev = new Revision( $row );
977 $validRevision = (bool)$rev->getId();
978 } catch ( Exception $e ) {
979 $validRevision = false;
980 }
981 MediaWiki\restoreWarnings();
982
983 if ( $validRevision ) {
984 $classes = array();
985
986 $page = Title::newFromRow( $row );
987 $link = Linker::link(
988 $page,
989 htmlspecialchars( $page->getPrefixedText() ),
990 array( 'class' => 'mw-contributions-title' ),
991 $page->isRedirect() ? array( 'redirect' => 'no' ) : array()
992 );
993 # Mark current revisions
994 $topmarktext = '';
995 $user = $this->getUser();
996 if ( $row->rev_id == $row->page_latest ) {
997 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
998 # Add rollback link
999 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
1000 && $page->quickUserCan( 'edit', $user )
1001 ) {
1002 $this->preventClickjacking();
1003 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
1004 }
1005 }
1006 # Is there a visible previous revision?
1007 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
1008 $difftext = Linker::linkKnown(
1009 $page,
1010 $this->messages['diff'],
1011 array(),
1012 array(
1013 'diff' => 'prev',
1014 'oldid' => $row->rev_id
1015 )
1016 );
1017 } else {
1018 $difftext = $this->messages['diff'];
1019 }
1020 $histlink = Linker::linkKnown(
1021 $page,
1022 $this->messages['hist'],
1023 array(),
1024 array( 'action' => 'history' )
1025 );
1026
1027 if ( $row->rev_parent_id === null ) {
1028 // For some reason rev_parent_id isn't populated for this row.
1029 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
1030 // Next best thing is to have the total number of bytes.
1031 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
1032 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
1033 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
1034 } else {
1035 $parentLen = 0;
1036 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
1037 $parentLen = $this->mParentLens[$row->rev_parent_id];
1038 }
1039
1040 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
1041 $chardiff .= ChangesList::showCharacterDifference(
1042 $parentLen,
1043 $row->rev_len,
1044 $this->getContext()
1045 );
1046 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
1047 }
1048
1049 $lang = $this->getLanguage();
1050 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
1051 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
1052 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1053 $d = Linker::linkKnown(
1054 $page,
1055 htmlspecialchars( $date ),
1056 array( 'class' => 'mw-changeslist-date' ),
1057 array( 'oldid' => intval( $row->rev_id ) )
1058 );
1059 } else {
1060 $d = htmlspecialchars( $date );
1061 }
1062 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1063 $d = '<span class="history-deleted">' . $d . '</span>';
1064 }
1065
1066 # Show user names for /newbies as there may be different users.
1067 # Note that we already excluded rows with hidden user names.
1068 if ( $this->contribs == 'newbie' ) {
1069 $userlink = ' . . ' . $lang->getDirMark()
1070 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
1071 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
1072 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
1073 } else {
1074 $userlink = '';
1075 }
1076
1077 if ( $rev->getParentId() === 0 ) {
1078 $nflag = ChangesList::flag( 'newpage' );
1079 } else {
1080 $nflag = '';
1081 }
1082
1083 if ( $rev->isMinor() ) {
1084 $mflag = ChangesList::flag( 'minor' );
1085 } else {
1086 $mflag = '';
1087 }
1088
1089 $del = Linker::getRevDeleteLink( $user, $rev, $page );
1090 if ( $del !== '' ) {
1091 $del .= ' ';
1092 }
1093
1094 $diffHistLinks = $this->msg( 'parentheses' )
1095 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
1096 ->escaped();
1097 $ret = "{$del}{$d} {$diffHistLinks}{$chardiff}{$nflag}{$mflag} ";
1098 $ret .= "{$link}{$userlink} {$comment} {$topmarktext}";
1099
1100 # Denote if username is redacted for this edit
1101 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1102 $ret .= " <strong>" .
1103 $this->msg( 'rev-deleted-user-contribs' )->escaped() .
1104 "</strong>";
1105 }
1106
1107 # Tags, if any.
1108 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
1109 $row->ts_tags,
1110 'contributions'
1111 );
1112 $classes = array_merge( $classes, $newClasses );
1113 $ret .= " $tagSummary";
1114 }
1115
1116 // Let extensions add data
1117 Hooks::run( 'ContributionsLineEnding', array( $this, &$ret, $row, &$classes ) );
1118
1119 if ( $classes === array() && $ret === '' ) {
1120 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
1121 $ret = "<!-- Could not format Special:Contribution row. -->\n";
1122 } else {
1123 $ret = Html::rawElement( 'li', array( 'class' => $classes ), $ret ) . "\n";
1124 }
1125
1126 return $ret;
1127 }
1128
1129 /**
1130 * Overwrite Pager function and return a helpful comment
1131 * @return string
1132 */
1133 function getSqlComment() {
1134 if ( $this->namespace || $this->deletedOnly ) {
1135 // potentially slow, see CR r58153
1136 return 'contributions page filtered for namespace or RevisionDeleted edits';
1137 } else {
1138 return 'contributions page unfiltered';
1139 }
1140 }
1141
1142 protected function preventClickjacking() {
1143 $this->preventClickjacking = true;
1144 }
1145
1146 /**
1147 * @return bool
1148 */
1149 public function getPreventClickjacking() {
1150 return $this->preventClickjacking;
1151 }
1152 }