Introduce mediawiki.RegExp module
[mediawiki.git] / includes / specials / SpecialContributions.php
blob9672580d8c563ff8b1ba5828da856ab4c515ddc8
1 <?php
2 /**
3 * Implements Special:Contributions
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
24 /**
25 * Special:Contributions, show user contributions in a paged list
27 * @ingroup SpecialPage
29 class SpecialContributions extends IncludableSpecialPage {
30 protected $opts;
32 public function __construct() {
33 parent::__construct( 'Contributions' );
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' );
43 $this->opts = array();
44 $request = $this->getRequest();
46 if ( $par !== null ) {
47 $target = $par;
48 } else {
49 $target = $request->getVal( 'target' );
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';
63 $this->opts['deletedOnly'] = $request->getBool( 'deletedOnly' );
65 if ( !strlen( $target ) ) {
66 if ( !$this->including() ) {
67 $out->addHTML( $this->getForm() );
70 return;
73 $user = $this->getUser();
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' );
80 $nt = Title::makeTitleSafe( NS_USER, $target );
81 if ( !$nt ) {
82 $out->addHTML( $this->getForm() );
84 return;
86 $userObj = User::newFromName( $nt->getText(), false );
87 if ( !$userObj ) {
88 $out->addHTML( $this->getForm() );
90 return;
92 $id = $userObj->getID();
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() );
110 if ( ( $ns = $request->getVal( 'namespace', null ) ) !== null && $ns !== '' ) {
111 $this->opts['namespace'] = intval( $ns );
112 } else {
113 $this->opts['namespace'] = '';
116 $this->opts['associated'] = $request->getBool( 'associated' );
117 $this->opts['nsInvert'] = (bool)$request->getVal( 'nsInvert' );
118 $this->opts['tagfilter'] = (string)$request->getVal( 'tagfilter' );
120 // Allows reverts to have the bot flag in recent changes. It is just here to
121 // be passed in the form at the top of the page
122 if ( $user->isAllowed( 'markbotedits' ) && $request->getBool( 'bot' ) ) {
123 $this->opts['bot'] = '1';
126 $skip = $request->getText( 'offset' ) || $request->getText( 'dir' ) == 'prev';
127 # Offset overrides year/month selection
128 if ( $skip ) {
129 $this->opts['year'] = '';
130 $this->opts['month'] = '';
131 } else {
132 $this->opts['year'] = $request->getIntOrNull( 'year' );
133 $this->opts['month'] = $request->getIntOrNull( 'month' );
136 $feedType = $request->getVal( 'feed' );
138 $feedParams = array(
139 'action' => 'feedcontributions',
140 'user' => $target,
142 if ( $this->opts['topOnly'] ) {
143 $feedParams['toponly'] = true;
145 if ( $this->opts['newOnly'] ) {
146 $feedParams['newonly'] = true;
148 if ( $this->opts['deletedOnly'] ) {
149 $feedParams['deletedonly'] = true;
151 if ( $this->opts['tagfilter'] !== '' ) {
152 $feedParams['tagfilter'] = $this->opts['tagfilter'];
154 if ( $this->opts['namespace'] !== '' ) {
155 $feedParams['namespace'] = $this->opts['namespace'];
157 // Don't use year and month for the feed URL, but pass them on if
158 // we redirect to API (if $feedType is specified)
159 if ( $feedType && $this->opts['year'] !== null ) {
160 $feedParams['year'] = $this->opts['year'];
162 if ( $feedType && $this->opts['month'] !== null ) {
163 $feedParams['month'] = $this->opts['month'];
166 if ( $feedType ) {
167 // Maintain some level of backwards compatibility
168 // If people request feeds using the old parameters, redirect to API
169 $feedParams['feedformat'] = $feedType;
170 $url = wfAppendQuery( wfScript( 'api' ), $feedParams );
172 $out->redirect( $url, '301' );
174 return;
177 // Add RSS/atom links
178 $this->addFeedLinks( $feedParams );
180 if ( Hooks::run( 'SpecialContributionsBeforeMainOutput', array( $id, $userObj, $this ) ) ) {
181 if ( !$this->including() ) {
182 $out->addHTML( $this->getForm() );
184 $pager = new ContribsPager( $this->getContext(), array(
185 'target' => $target,
186 'contribs' => $this->opts['contribs'],
187 'namespace' => $this->opts['namespace'],
188 'tagfilter' => $this->opts['tagfilter'],
189 'year' => $this->opts['year'],
190 'month' => $this->opts['month'],
191 'deletedOnly' => $this->opts['deletedOnly'],
192 'topOnly' => $this->opts['topOnly'],
193 'newOnly' => $this->opts['newOnly'],
194 'nsInvert' => $this->opts['nsInvert'],
195 'associated' => $this->opts['associated'],
196 ) );
198 if ( !$pager->getNumRows() ) {
199 $out->addWikiMsg( 'nocontribs', $target );
200 } else {
201 # Show a message about slave lag, if applicable
202 $lag = wfGetLB()->safeGetLag( $pager->getDatabase() );
203 if ( $lag > 0 ) {
204 $out->showLagWarning( $lag );
207 $output = $pager->getBody();
208 if ( !$this->including() ) {
209 $output = '<p>' . $pager->getNavigationBar() . '</p>' .
210 $output .
211 '<p>' . $pager->getNavigationBar() . '</p>';
213 $out->addHTML( $output );
215 $out->preventClickjacking( $pager->getPreventClickjacking() );
217 # Show the appropriate "footer" message - WHOIS tools, etc.
218 if ( $this->opts['contribs'] == 'newbie' ) {
219 $message = 'sp-contributions-footer-newbies';
220 } elseif ( IP::isIPAddress( $target ) ) {
221 $message = 'sp-contributions-footer-anon';
222 } elseif ( $userObj->isAnon() ) {
223 // No message for non-existing users
224 $message = '';
225 } else {
226 $message = 'sp-contributions-footer';
229 if ( $message ) {
230 if ( !$this->including() ) {
231 if ( !$this->msg( $message, $target )->isDisabled() ) {
232 $out->wrapWikiMsg(
233 "<div class='mw-contributions-footer'>\n$1\n</div>",
234 array( $message, $target ) );
242 * Generates the subheading with links
243 * @param User $userObj User object for the target
244 * @return string Appropriately-escaped HTML to be output literally
245 * @todo FIXME: Almost the same as getSubTitle in SpecialDeletedContributions.php.
246 * Could be combined.
248 protected function contributionsSub( $userObj ) {
249 if ( $userObj->isAnon() ) {
250 // Show a warning message that the user being searched for doesn't exists
251 if ( !User::isIP( $userObj->getName() ) ) {
252 $this->getOutput()->wrapWikiMsg(
253 "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
254 array(
255 'contributions-userdoesnotexist',
256 wfEscapeWikiText( $userObj->getName() ),
259 if ( !$this->including() ) {
260 $this->getOutput()->setStatusCode( 404 );
263 $user = htmlspecialchars( $userObj->getName() );
264 } else {
265 $user = Linker::link( $userObj->getUserPage(), htmlspecialchars( $userObj->getName() ) );
267 $nt = $userObj->getUserPage();
268 $talk = $userObj->getTalkPage();
269 $links = '';
270 if ( $talk ) {
271 $tools = $this->getUserLinks( $nt, $talk, $userObj );
272 $links = $this->getLanguage()->pipeList( $tools );
274 // Show a note if the user is blocked and display the last block log entry.
275 // Do not expose the autoblocks, since that may lead to a leak of accounts' IPs,
276 // and also this will display a totally irrelevant log entry as a current block.
277 if ( !$this->including() ) {
278 $block = Block::newFromTarget( $userObj, $userObj );
279 if ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
280 if ( $block->getType() == Block::TYPE_RANGE ) {
281 $nt = MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget();
284 $out = $this->getOutput(); // showLogExtract() wants first parameter by reference
285 LogEventsList::showLogExtract(
286 $out,
287 'block',
288 $nt,
290 array(
291 'lim' => 1,
292 'showIfEmpty' => false,
293 'msgKey' => array(
294 $userObj->isAnon() ?
295 'sp-contributions-blocked-notice-anon' :
296 'sp-contributions-blocked-notice',
297 $userObj->getName() # Support GENDER in 'sp-contributions-blocked-notice'
299 'offset' => '' # don't use WebRequest parameter offset
306 return $this->msg( 'contribsub2' )->rawParams( $user, $links )->params( $userObj->getName() );
310 * Links to different places.
311 * @param Title $userpage Target user page
312 * @param Title $talkpage Talk page
313 * @param User $target Target user object
314 * @return array
316 public function getUserLinks( Title $userpage, Title $talkpage, User $target ) {
318 $id = $target->getId();
319 $username = $target->getName();
321 $tools[] = Linker::link( $talkpage, $this->msg( 'sp-contributions-talk' )->escaped() );
323 if ( ( $id !== null ) || ( $id === null && IP::isIPAddress( $username ) ) ) {
324 if ( $this->getUser()->isAllowed( 'block' ) ) { # Block / Change block / Unblock links
325 if ( $target->isBlocked() && $target->getBlock()->getType() != Block::TYPE_AUTO ) {
326 $tools[] = Linker::linkKnown( # Change block link
327 SpecialPage::getTitleFor( 'Block', $username ),
328 $this->msg( 'change-blocklink' )->escaped()
330 $tools[] = Linker::linkKnown( # Unblock link
331 SpecialPage::getTitleFor( 'Unblock', $username ),
332 $this->msg( 'unblocklink' )->escaped()
334 } else { # User is not blocked
335 $tools[] = Linker::linkKnown( # Block link
336 SpecialPage::getTitleFor( 'Block', $username ),
337 $this->msg( 'blocklink' )->escaped()
342 # Block log link
343 $tools[] = Linker::linkKnown(
344 SpecialPage::getTitleFor( 'Log', 'block' ),
345 $this->msg( 'sp-contributions-blocklog' )->escaped(),
346 array(),
347 array( 'page' => $userpage->getPrefixedText() )
350 # Suppression log link (bug 59120)
351 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
352 $tools[] = Linker::linkKnown(
353 SpecialPage::getTitleFor( 'Log', 'suppress' ),
354 $this->msg( 'sp-contributions-suppresslog' )->escaped(),
355 array(),
356 array( 'offender' => $username )
360 # Uploads
361 $tools[] = Linker::linkKnown(
362 SpecialPage::getTitleFor( 'Listfiles', $username ),
363 $this->msg( 'sp-contributions-uploads' )->escaped()
366 # Other logs link
367 $tools[] = Linker::linkKnown(
368 SpecialPage::getTitleFor( 'Log', $username ),
369 $this->msg( 'sp-contributions-logs' )->escaped()
372 # Add link to deleted user contributions for priviledged users
373 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
374 $tools[] = Linker::linkKnown(
375 SpecialPage::getTitleFor( 'DeletedContributions', $username ),
376 $this->msg( 'sp-contributions-deleted' )->escaped()
380 # Add a link to change user rights for privileged users
381 $userrightsPage = new UserrightsPage();
382 $userrightsPage->setContext( $this->getContext() );
383 if ( $userrightsPage->userCanChangeRights( $target ) ) {
384 $tools[] = Linker::linkKnown(
385 SpecialPage::getTitleFor( 'Userrights', $username ),
386 $this->msg( 'sp-contributions-userrights' )->escaped()
390 Hooks::run( 'ContributionsToolLinks', array( $id, $userpage, &$tools ) );
392 return $tools;
396 * Generates the namespace selector form with hidden attributes.
397 * @return string HTML fragment
399 protected function getForm() {
400 $this->opts['title'] = $this->getPageTitle()->getPrefixedText();
401 if ( !isset( $this->opts['target'] ) ) {
402 $this->opts['target'] = '';
403 } else {
404 $this->opts['target'] = str_replace( '_', ' ', $this->opts['target'] );
407 if ( !isset( $this->opts['namespace'] ) ) {
408 $this->opts['namespace'] = '';
411 if ( !isset( $this->opts['nsInvert'] ) ) {
412 $this->opts['nsInvert'] = '';
415 if ( !isset( $this->opts['associated'] ) ) {
416 $this->opts['associated'] = false;
419 if ( !isset( $this->opts['contribs'] ) ) {
420 $this->opts['contribs'] = 'user';
423 if ( !isset( $this->opts['year'] ) ) {
424 $this->opts['year'] = '';
427 if ( !isset( $this->opts['month'] ) ) {
428 $this->opts['month'] = '';
431 if ( $this->opts['contribs'] == 'newbie' ) {
432 $this->opts['target'] = '';
435 if ( !isset( $this->opts['tagfilter'] ) ) {
436 $this->opts['tagfilter'] = '';
439 if ( !isset( $this->opts['topOnly'] ) ) {
440 $this->opts['topOnly'] = false;
443 if ( !isset( $this->opts['newOnly'] ) ) {
444 $this->opts['newOnly'] = false;
447 $form = Html::openElement(
448 'form',
449 array(
450 'method' => 'get',
451 'action' => wfScript(),
452 'class' => 'mw-contributions-form'
456 # Add hidden params for tracking except for parameters in $skipParameters
457 $skipParameters = array(
458 'namespace',
459 'nsInvert',
460 'deletedOnly',
461 'target',
462 'contribs',
463 'year',
464 'month',
465 'topOnly',
466 'newOnly',
467 'associated'
470 foreach ( $this->opts as $name => $value ) {
471 if ( in_array( $name, $skipParameters ) ) {
472 continue;
474 $form .= "\t" . Html::hidden( $name, $value ) . "\n";
477 $tagFilter = ChangeTags::buildTagFilterSelector( $this->opts['tagfilter'] );
479 if ( $tagFilter ) {
480 $filterSelection = Html::rawElement(
481 'td',
482 array(),
483 array_shift( $tagFilter ) . implode( '&#160', $tagFilter )
485 } else {
486 $filterSelection = Html::rawElement( 'td', array( 'colspan' => 2 ), '' );
489 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
491 $labelNewbies = Xml::radioLabel(
492 $this->msg( 'sp-contributions-newbies' )->text(),
493 'contribs',
494 'newbie',
495 'newbie',
496 $this->opts['contribs'] == 'newbie',
497 array( 'class' => 'mw-input' )
499 $labelUsername = Xml::radioLabel(
500 $this->msg( 'sp-contributions-username' )->text(),
501 'contribs',
502 'user',
503 'user',
504 $this->opts['contribs'] == 'user',
505 array( 'class' => 'mw-input' )
507 $input = Html::input(
508 'target',
509 $this->opts['target'],
510 'text',
511 array(
512 'size' => '40',
513 'required' => '',
514 'class' => array(
515 'mw-input',
516 'mw-ui-input-inline',
517 'mw-autocomplete-user', // used by mediawiki.userSuggest
519 ) + ( $this->opts['target'] ? array() : array( 'autofocus' ) )
521 $targetSelection = Html::rawElement(
522 'td',
523 array( 'colspan' => 2 ),
524 $labelNewbies . '<br />' . $labelUsername . ' ' . $input . ' '
527 $namespaceSelection = Xml::tags(
528 'td',
529 array(),
530 Xml::label(
531 $this->msg( 'namespace' )->text(),
532 'namespace',
535 Html::namespaceSelector(
536 array( 'selected' => $this->opts['namespace'], 'all' => '' ),
537 array(
538 'name' => 'namespace',
539 'id' => 'namespace',
540 'class' => 'namespaceselector',
542 ) . '&#160;' .
543 Html::rawElement(
544 'span',
545 array( 'style' => 'white-space: nowrap' ),
546 Xml::checkLabel(
547 $this->msg( 'invert' )->text(),
548 'nsInvert',
549 'nsInvert',
550 $this->opts['nsInvert'],
551 array(
552 'title' => $this->msg( 'tooltip-invert' )->text(),
553 'class' => 'mw-input'
555 ) . '&#160;'
557 Html::rawElement( 'span', array( 'style' => 'white-space: nowrap' ),
558 Xml::checkLabel(
559 $this->msg( 'namespace_association' )->text(),
560 'associated',
561 'associated',
562 $this->opts['associated'],
563 array(
564 'title' => $this->msg( 'tooltip-namespace_association' )->text(),
565 'class' => 'mw-input'
567 ) . '&#160;'
571 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
572 $deletedOnlyCheck = Html::rawElement(
573 'span',
574 array( 'style' => 'white-space: nowrap' ),
575 Xml::checkLabel(
576 $this->msg( 'history-show-deleted' )->text(),
577 'deletedOnly',
578 'mw-show-deleted-only',
579 $this->opts['deletedOnly'],
580 array( 'class' => 'mw-input' )
583 } else {
584 $deletedOnlyCheck = '';
587 $checkLabelTopOnly = Html::rawElement(
588 'span',
589 array( 'style' => 'white-space: nowrap' ),
590 Xml::checkLabel(
591 $this->msg( 'sp-contributions-toponly' )->text(),
592 'topOnly',
593 'mw-show-top-only',
594 $this->opts['topOnly'],
595 array( 'class' => 'mw-input' )
598 $checkLabelNewOnly = Html::rawElement(
599 'span',
600 array( 'style' => 'white-space: nowrap' ),
601 Xml::checkLabel(
602 $this->msg( 'sp-contributions-newonly' )->text(),
603 'newOnly',
604 'mw-show-new-only',
605 $this->opts['newOnly'],
606 array( 'class' => 'mw-input' )
609 $extraOptions = Html::rawElement(
610 'td',
611 array( 'colspan' => 2 ),
612 $deletedOnlyCheck . $checkLabelTopOnly . $checkLabelNewOnly
615 $dateSelectionAndSubmit = Xml::tags( 'td', array( 'colspan' => 2 ),
616 Xml::dateMenu(
617 $this->opts['year'] === '' ? MWTimestamp::getInstance()->format( 'Y' ) : $this->opts['year'],
618 $this->opts['month']
619 ) . ' ' .
620 Html::submitButton(
621 $this->msg( 'sp-contributions-submit' )->text(),
622 array( 'class' => 'mw-submit' ), array( 'mw-ui-progressive' )
626 $form .= Xml::fieldset( $this->msg( 'sp-contributions-search' )->text() );
627 $form .= Html::rawElement( 'table', array( 'class' => 'mw-contributions-table' ), "\n" .
628 Html::rawElement( 'tr', array(), $targetSelection ) . "\n" .
629 Html::rawElement( 'tr', array(), $namespaceSelection ) . "\n" .
630 Html::rawElement( 'tr', array(), $filterSelection ) . "\n" .
631 Html::rawElement( 'tr', array(), $extraOptions ) . "\n" .
632 Html::rawElement( 'tr', array(), $dateSelectionAndSubmit ) . "\n"
635 $explain = $this->msg( 'sp-contributions-explain' );
636 if ( !$explain->isBlank() ) {
637 $form .= "<p id='mw-sp-contributions-explain'>{$explain->parse()}</p>";
640 $form .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' );
642 return $form;
645 protected function getGroupName() {
646 return 'users';
651 * Pager for Special:Contributions
652 * @ingroup SpecialPage Pager
654 class ContribsPager extends ReverseChronologicalPager {
655 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
656 public $messages;
657 public $target;
658 public $namespace = '';
659 public $mDb;
660 public $preventClickjacking = false;
662 /** @var IDatabase */
663 public $mDbSecondary;
666 * @var array
668 protected $mParentLens;
670 function __construct( IContextSource $context, array $options ) {
671 parent::__construct( $context );
673 $msgs = array(
674 'diff',
675 'hist',
676 'pipe-separator',
677 'uctop'
680 foreach ( $msgs as $msg ) {
681 $this->messages[$msg] = $this->msg( $msg )->escaped();
684 $this->target = isset( $options['target'] ) ? $options['target'] : '';
685 $this->contribs = isset( $options['contribs'] ) ? $options['contribs'] : 'users';
686 $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : '';
687 $this->tagFilter = isset( $options['tagfilter'] ) ? $options['tagfilter'] : false;
688 $this->nsInvert = isset( $options['nsInvert'] ) ? $options['nsInvert'] : false;
689 $this->associated = isset( $options['associated'] ) ? $options['associated'] : false;
691 $this->deletedOnly = !empty( $options['deletedOnly'] );
692 $this->topOnly = !empty( $options['topOnly'] );
693 $this->newOnly = !empty( $options['newOnly'] );
695 $year = isset( $options['year'] ) ? $options['year'] : false;
696 $month = isset( $options['month'] ) ? $options['month'] : false;
697 $this->getDateCond( $year, $month );
699 // Most of this code will use the 'contributions' group DB, which can map to slaves
700 // with extra user based indexes or partioning by user. The additional metadata
701 // queries should use a regular slave since the lookup pattern is not all by user.
702 $this->mDbSecondary = wfGetDB( DB_SLAVE ); // any random slave
703 $this->mDb = wfGetDB( DB_SLAVE, 'contributions' );
706 function getDefaultQuery() {
707 $query = parent::getDefaultQuery();
708 $query['target'] = $this->target;
710 return $query;
714 * This method basically executes the exact same code as the parent class, though with
715 * a hook added, to allow extensions to add additional queries.
717 * @param string $offset Index offset, inclusive
718 * @param int $limit Exact query limit
719 * @param bool $descending Query direction, false for ascending, true for descending
720 * @return ResultWrapper
722 function reallyDoQuery( $offset, $limit, $descending ) {
723 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
724 $offset,
725 $limit,
726 $descending
730 * This hook will allow extensions to add in additional queries, so they can get their data
731 * in My Contributions as well. Extensions should append their results to the $data array.
733 * Extension queries have to implement the navbar requirement as well. They should
734 * - have a column aliased as $pager->getIndexField()
735 * - have LIMIT set
736 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
737 * - have the ORDER BY specified based upon the details provided by the navbar
739 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
741 * &$data: an array of results of all contribs queries
742 * $pager: the ContribsPager object hooked into
743 * $offset: see phpdoc above
744 * $limit: see phpdoc above
745 * $descending: see phpdoc above
747 $data = array( $this->mDb->select(
748 $tables, $fields, $conds, $fname, $options, $join_conds
749 ) );
750 Hooks::run(
751 'ContribsPager::reallyDoQuery',
752 array( &$data, $this, $offset, $limit, $descending )
755 $result = array();
757 // loop all results and collect them in an array
758 foreach ( $data as $query ) {
759 foreach ( $query as $i => $row ) {
760 // use index column as key, allowing us to easily sort in PHP
761 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
765 // sort results
766 if ( $descending ) {
767 ksort( $result );
768 } else {
769 krsort( $result );
772 // enforce limit
773 $result = array_slice( $result, 0, $limit );
775 // get rid of array keys
776 $result = array_values( $result );
778 return new FakeResultWrapper( $result );
781 function getQueryInfo() {
782 list( $tables, $index, $userCond, $join_cond ) = $this->getUserCond();
784 $user = $this->getUser();
785 $conds = array_merge( $userCond, $this->getNamespaceCond() );
787 // Paranoia: avoid brute force searches (bug 17342)
788 if ( !$user->isAllowed( 'deletedhistory' ) ) {
789 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0';
790 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
791 $conds[] = $this->mDb->bitAnd( 'rev_deleted', Revision::SUPPRESSED_USER ) .
792 ' != ' . Revision::SUPPRESSED_USER;
795 # Don't include orphaned revisions
796 $join_cond['page'] = Revision::pageJoinCond();
797 # Get the current user name for accounts
798 $join_cond['user'] = Revision::userJoinCond();
800 $options = array();
801 if ( $index ) {
802 $options['USE INDEX'] = array( 'revision' => $index );
805 $queryInfo = array(
806 'tables' => $tables,
807 'fields' => array_merge(
808 Revision::selectFields(),
809 Revision::selectUserFields(),
810 array( 'page_namespace', 'page_title', 'page_is_new',
811 'page_latest', 'page_is_redirect', 'page_len' )
813 'conds' => $conds,
814 'options' => $options,
815 'join_conds' => $join_cond
818 ChangeTags::modifyDisplayQuery(
819 $queryInfo['tables'],
820 $queryInfo['fields'],
821 $queryInfo['conds'],
822 $queryInfo['join_conds'],
823 $queryInfo['options'],
824 $this->tagFilter
827 Hooks::run( 'ContribsPager::getQueryInfo', array( &$this, &$queryInfo ) );
829 return $queryInfo;
832 function getUserCond() {
833 $condition = array();
834 $join_conds = array();
835 $tables = array( 'revision', 'page', 'user' );
836 $index = false;
837 if ( $this->contribs == 'newbie' ) {
838 $max = $this->mDb->selectField( 'user', 'max(user_id)', false, __METHOD__ );
839 $condition[] = 'rev_user >' . (int)( $max - $max / 100 );
840 # ignore local groups with the bot right
841 # @todo FIXME: Global groups may have 'bot' rights
842 $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
843 if ( count( $groupsWithBotPermission ) ) {
844 $tables[] = 'user_groups';
845 $condition[] = 'ug_group IS NULL';
846 $join_conds['user_groups'] = array(
847 'LEFT JOIN', array(
848 'ug_user = rev_user',
849 'ug_group' => $groupsWithBotPermission
853 } else {
854 $uid = User::idFromName( $this->target );
855 if ( $uid ) {
856 $condition['rev_user'] = $uid;
857 $index = 'user_timestamp';
858 } else {
859 $condition['rev_user_text'] = $this->target;
860 $index = 'usertext_timestamp';
864 if ( $this->deletedOnly ) {
865 $condition[] = 'rev_deleted != 0';
868 if ( $this->topOnly ) {
869 $condition[] = 'rev_id = page_latest';
872 if ( $this->newOnly ) {
873 $condition[] = 'rev_parent_id = 0';
876 return array( $tables, $index, $condition, $join_conds );
879 function getNamespaceCond() {
880 if ( $this->namespace !== '' ) {
881 $selectedNS = $this->mDb->addQuotes( $this->namespace );
882 $eq_op = $this->nsInvert ? '!=' : '=';
883 $bool_op = $this->nsInvert ? 'AND' : 'OR';
885 if ( !$this->associated ) {
886 return array( "page_namespace $eq_op $selectedNS" );
889 $associatedNS = $this->mDb->addQuotes(
890 MWNamespace::getAssociated( $this->namespace )
893 return array(
894 "page_namespace $eq_op $selectedNS " .
895 $bool_op .
896 " page_namespace $eq_op $associatedNS"
900 return array();
903 function getIndexField() {
904 return 'rev_timestamp';
907 function doBatchLookups() {
908 # Do a link batch query
909 $this->mResult->seek( 0 );
910 $revIds = array();
911 $batch = new LinkBatch();
912 # Give some pointers to make (last) links
913 foreach ( $this->mResult as $row ) {
914 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
915 $revIds[] = $row->rev_parent_id;
917 if ( isset( $row->rev_id ) ) {
918 if ( $this->contribs === 'newbie' ) { // multiple users
919 $batch->add( NS_USER, $row->user_name );
920 $batch->add( NS_USER_TALK, $row->user_name );
922 $batch->add( $row->page_namespace, $row->page_title );
925 $this->mParentLens = Revision::getParentLengths( $this->mDbSecondary, $revIds );
926 $batch->execute();
927 $this->mResult->seek( 0 );
931 * @return string
933 function getStartBody() {
934 return "<ul class=\"mw-contributions-list\">\n";
938 * @return string
940 function getEndBody() {
941 return "</ul>\n";
945 * Generates each row in the contributions list.
947 * Contributions which are marked "top" are currently on top of the history.
948 * For these contributions, a [rollback] link is shown for users with roll-
949 * back privileges. The rollback link restores the most recent version that
950 * was not written by the target user.
952 * @todo This would probably look a lot nicer in a table.
953 * @param object $row
954 * @return string
956 function formatRow( $row ) {
958 $ret = '';
959 $classes = array();
962 * There may be more than just revision rows. To make sure that we'll only be processing
963 * revisions here, let's _try_ to build a revision out of our row (without displaying
964 * notices though) and then trying to grab data from the built object. If we succeed,
965 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
966 * to extensions to subscribe to the hook to parse the row.
968 MediaWiki\suppressWarnings();
969 try {
970 $rev = new Revision( $row );
971 $validRevision = (bool)$rev->getId();
972 } catch ( Exception $e ) {
973 $validRevision = false;
975 MediaWiki\restoreWarnings();
977 if ( $validRevision ) {
978 $classes = array();
980 $page = Title::newFromRow( $row );
981 $link = Linker::link(
982 $page,
983 htmlspecialchars( $page->getPrefixedText() ),
984 array( 'class' => 'mw-contributions-title' ),
985 $page->isRedirect() ? array( 'redirect' => 'no' ) : array()
987 # Mark current revisions
988 $topmarktext = '';
989 $user = $this->getUser();
990 if ( $row->rev_id == $row->page_latest ) {
991 $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
992 # Add rollback link
993 if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
994 && $page->quickUserCan( 'edit', $user )
996 $this->preventClickjacking();
997 $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
1000 # Is there a visible previous revision?
1001 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
1002 $difftext = Linker::linkKnown(
1003 $page,
1004 $this->messages['diff'],
1005 array(),
1006 array(
1007 'diff' => 'prev',
1008 'oldid' => $row->rev_id
1011 } else {
1012 $difftext = $this->messages['diff'];
1014 $histlink = Linker::linkKnown(
1015 $page,
1016 $this->messages['hist'],
1017 array(),
1018 array( 'action' => 'history' )
1021 if ( $row->rev_parent_id === null ) {
1022 // For some reason rev_parent_id isn't populated for this row.
1023 // Its rumoured this is true on wikipedia for some revisions (bug 34922).
1024 // Next best thing is to have the total number of bytes.
1025 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
1026 $chardiff .= Linker::formatRevisionSize( $row->rev_len );
1027 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
1028 } else {
1029 $parentLen = 0;
1030 if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
1031 $parentLen = $this->mParentLens[$row->rev_parent_id];
1034 $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
1035 $chardiff .= ChangesList::showCharacterDifference(
1036 $parentLen,
1037 $row->rev_len,
1038 $this->getContext()
1040 $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
1043 $lang = $this->getLanguage();
1044 $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true );
1045 $date = $lang->userTimeAndDate( $row->rev_timestamp, $user );
1046 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1047 $d = Linker::linkKnown(
1048 $page,
1049 htmlspecialchars( $date ),
1050 array( 'class' => 'mw-changeslist-date' ),
1051 array( 'oldid' => intval( $row->rev_id ) )
1053 } else {
1054 $d = htmlspecialchars( $date );
1056 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1057 $d = '<span class="history-deleted">' . $d . '</span>';
1060 # Show user names for /newbies as there may be different users.
1061 # Note that we already excluded rows with hidden user names.
1062 if ( $this->contribs == 'newbie' ) {
1063 $userlink = ' . . ' . $lang->getDirMark()
1064 . Linker::userLink( $rev->getUser(), $rev->getUserText() );
1065 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
1066 Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
1067 } else {
1068 $userlink = '';
1071 if ( $rev->getParentId() === 0 ) {
1072 $nflag = ChangesList::flag( 'newpage' );
1073 } else {
1074 $nflag = '';
1077 if ( $rev->isMinor() ) {
1078 $mflag = ChangesList::flag( 'minor' );
1079 } else {
1080 $mflag = '';
1083 $del = Linker::getRevDeleteLink( $user, $rev, $page );
1084 if ( $del !== '' ) {
1085 $del .= ' ';
1088 $diffHistLinks = $this->msg( 'parentheses' )
1089 ->rawParams( $difftext . $this->messages['pipe-separator'] . $histlink )
1090 ->escaped();
1091 $ret = "{$del}{$d} {$diffHistLinks}{$chardiff}{$nflag}{$mflag} ";
1092 $ret .= "{$link}{$userlink} {$comment} {$topmarktext}";
1094 # Denote if username is redacted for this edit
1095 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1096 $ret .= " <strong>" .
1097 $this->msg( 'rev-deleted-user-contribs' )->escaped() .
1098 "</strong>";
1101 # Tags, if any.
1102 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
1103 $row->ts_tags,
1104 'contributions'
1106 $classes = array_merge( $classes, $newClasses );
1107 $ret .= " $tagSummary";
1110 // Let extensions add data
1111 Hooks::run( 'ContributionsLineEnding', array( $this, &$ret, $row, &$classes ) );
1113 if ( $classes === array() && $ret === '' ) {
1114 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
1115 $ret = "<!-- Could not format Special:Contribution row. -->\n";
1116 } else {
1117 $ret = Html::rawElement( 'li', array( 'class' => $classes ), $ret ) . "\n";
1120 return $ret;
1124 * Overwrite Pager function and return a helpful comment
1125 * @return string
1127 function getSqlComment() {
1128 if ( $this->namespace || $this->deletedOnly ) {
1129 // potentially slow, see CR r58153
1130 return 'contributions page filtered for namespace or RevisionDeleted edits';
1131 } else {
1132 return 'contributions page unfiltered';
1136 protected function preventClickjacking() {
1137 $this->preventClickjacking = true;
1141 * @return bool
1143 public function getPreventClickjacking() {
1144 return $this->preventClickjacking;