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