Merge "Fix positioning of jQuery.tipsy tooltip arrows"
[mediawiki.git] / includes / logging / LogEventsList.php
blobdcd7a45215f648163d6ca94c2e21ef112d801b97
1 <?php
2 /**
3 * Contain classes to list log entries
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
26 class LogEventsList extends ContextSource {
27 const NO_ACTION_LINK = 1;
28 const NO_EXTRA_USER_LINKS = 2;
29 const USE_CHECKBOXES = 4;
31 public $flags;
33 /**
34 * @var array
36 protected $mDefaultQuery;
38 /**
39 * @var bool
41 protected $showTagEditUI;
43 /**
44 * Constructor.
45 * The first two parameters used to be $skin and $out, but now only a context
46 * is needed, that's why there's a second unused parameter.
48 * @param IContextSource|Skin $context Context to use; formerly it was
49 * a Skin object. Use of Skin is deprecated.
50 * @param null $unused Unused; used to be an OutputPage object.
51 * @param int $flags Can be a combination of self::NO_ACTION_LINK,
52 * self::NO_EXTRA_USER_LINKS or self::USE_CHECKBOXES.
54 public function __construct( $context, $unused = null, $flags = 0 ) {
55 if ( $context instanceof IContextSource ) {
56 $this->setContext( $context );
57 } else {
58 // Old parameters, $context should be a Skin object
59 $this->setContext( $context->getContext() );
62 $this->flags = $flags;
63 $this->showTagEditUI = ChangeTags::showTagEditingUI( $this->getUser() );
66 /**
67 * Show options for the log list
69 * @param array|string $types
70 * @param string $user
71 * @param string $page
72 * @param string $pattern
73 * @param int $year Year
74 * @param int $month Month
75 * @param array $filter
76 * @param string $tagFilter Tag to select by default
78 public function showOptions( $types = array(), $user = '', $page = '', $pattern = '', $year = 0,
79 $month = 0, $filter = null, $tagFilter = ''
80 ) {
81 global $wgScript, $wgMiserMode;
83 $title = SpecialPage::getTitleFor( 'Log' );
85 // For B/C, we take strings, but make sure they are converted...
86 $types = ( $types === '' ) ? array() : (array)$types;
88 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
90 $html = Html::hidden( 'title', $title->getPrefixedDBkey() );
92 // Basic selectors
93 $html .= $this->getTypeMenu( $types ) . "\n";
94 $html .= $this->getUserInput( $user ) . "\n";
95 $html .= $this->getTitleInput( $page ) . "\n";
96 $html .= $this->getExtraInputs( $types ) . "\n";
98 // Title pattern, if allowed
99 if ( !$wgMiserMode ) {
100 $html .= $this->getTitlePattern( $pattern ) . "\n";
103 // date menu
104 $html .= Xml::tags( 'p', null, Xml::dateMenu( (int)$year, (int)$month ) );
106 // Tag filter
107 if ( $tagSelector ) {
108 $html .= Xml::tags( 'p', null, implode( '&#160;', $tagSelector ) );
111 // Filter links
112 if ( $filter ) {
113 $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) );
116 // Submit button
117 $html .= Xml::submitButton( $this->msg( 'logeventslist-submit' )->text() );
119 // Fieldset
120 $html = Xml::fieldset( $this->msg( 'log' )->text(), $html );
122 // Form wrapping
123 $html = Xml::tags( 'form', array( 'action' => $wgScript, 'method' => 'get' ), $html );
125 $this->getOutput()->addHTML( $html );
129 * @param array $filter
130 * @return string Formatted HTML
132 private function getFilterLinks( $filter ) {
133 // show/hide links
134 $messages = array( $this->msg( 'show' )->escaped(), $this->msg( 'hide' )->escaped() );
135 // Option value -> message mapping
136 $links = array();
137 $hiddens = ''; // keep track for "go" button
138 foreach ( $filter as $type => $val ) {
139 // Should the below assignment be outside the foreach?
140 // Then it would have to be copied. Not certain what is more expensive.
141 $query = $this->getDefaultQuery();
142 $queryKey = "hide_{$type}_log";
144 $hideVal = 1 - intval( $val );
145 $query[$queryKey] = $hideVal;
147 $link = Linker::linkKnown(
148 $this->getTitle(),
149 $messages[$hideVal],
150 array(),
151 $query
154 // Message: log-show-hide-patrol
155 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
156 $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n";
159 // Build links
160 return '<small>' . $this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
163 private function getDefaultQuery() {
164 if ( !isset( $this->mDefaultQuery ) ) {
165 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
166 unset( $this->mDefaultQuery['title'] );
167 unset( $this->mDefaultQuery['dir'] );
168 unset( $this->mDefaultQuery['offset'] );
169 unset( $this->mDefaultQuery['limit'] );
170 unset( $this->mDefaultQuery['order'] );
171 unset( $this->mDefaultQuery['month'] );
172 unset( $this->mDefaultQuery['year'] );
175 return $this->mDefaultQuery;
179 * @param array $queryTypes
180 * @return string Formatted HTML
182 private function getTypeMenu( $queryTypes ) {
183 $queryType = count( $queryTypes ) == 1 ? $queryTypes[0] : '';
184 $selector = $this->getTypeSelector();
185 $selector->setDefault( $queryType );
187 return $selector->getHtml();
191 * Returns log page selector.
192 * @return XmlSelect
193 * @since 1.19
195 public function getTypeSelector() {
196 $typesByName = array(); // Temporary array
197 // First pass to load the log names
198 foreach ( LogPage::validTypes() as $type ) {
199 $page = new LogPage( $type );
200 $restriction = $page->getRestriction();
201 if ( $this->getUser()->isAllowed( $restriction ) ) {
202 $typesByName[$type] = $page->getName()->text();
206 // Second pass to sort by name
207 asort( $typesByName );
209 // Always put "All public logs" on top
210 $public = $typesByName[''];
211 unset( $typesByName[''] );
212 $typesByName = array( '' => $public ) + $typesByName;
214 $select = new XmlSelect( 'type' );
215 foreach ( $typesByName as $type => $name ) {
216 $select->addOption( $name, $type );
219 return $select;
223 * @param string $user
224 * @return string Formatted HTML
226 private function getUserInput( $user ) {
227 $label = Xml::inputLabel(
228 $this->msg( 'specialloguserlabel' )->text(),
229 'user',
230 'mw-log-user',
232 $user,
233 array( 'class' => 'mw-autocomplete-user' )
236 return '<span class="mw-input-with-label">' . $label . '</span>';
240 * @param string $title
241 * @return string Formatted HTML
243 private function getTitleInput( $title ) {
244 $label = Xml::inputLabel(
245 $this->msg( 'speciallogtitlelabel' )->text(),
246 'page',
247 'mw-log-page',
249 $title
252 return '<span class="mw-input-with-label">' . $label . '</span>';
256 * @param string $pattern
257 * @return string Checkbox
259 private function getTitlePattern( $pattern ) {
260 return '<span class="mw-input-with-label">' .
261 Xml::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
262 '</span>';
266 * @param array $types
267 * @return string
269 private function getExtraInputs( $types ) {
270 if ( count( $types ) == 1 ) {
271 if ( $types[0] == 'suppress' ) {
272 $offender = $this->getRequest()->getVal( 'offender' );
273 $user = User::newFromName( $offender, false );
274 if ( !$user || ( $user->getId() == 0 && !IP::isIPAddress( $offender ) ) ) {
275 $offender = ''; // Blank field if invalid
277 return Xml::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
278 'mw-log-offender', 20, $offender );
279 } else {
280 // Allow extensions to add their own extra inputs
281 $input = '';
282 Hooks::run( 'LogEventsListGetExtraInputs', array( $types[0], $this, &$input ) );
283 return $input;
287 return '';
291 * @return string
293 public function beginLogEventsList() {
294 return "<ul>\n";
298 * @return string
300 public function endLogEventsList() {
301 return "</ul>\n";
305 * @param stdClass $row A single row from the result set
306 * @return string Formatted HTML list item
308 public function logLine( $row ) {
309 $entry = DatabaseLogEntry::newFromRow( $row );
310 $formatter = LogFormatter::newFromEntry( $entry );
311 $formatter->setContext( $this->getContext() );
312 $formatter->setShowUserToolLinks( !( $this->flags & self::NO_EXTRA_USER_LINKS ) );
314 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
315 $entry->getTimestamp(), $this->getUser() ) );
317 $action = $formatter->getActionText();
319 if ( $this->flags & self::NO_ACTION_LINK ) {
320 $revert = '';
321 } else {
322 $revert = $formatter->getActionLinks();
323 if ( $revert != '' ) {
324 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
328 $comment = $formatter->getComment();
330 // Some user can hide log items and have review links
331 $del = $this->getShowHideLinks( $row );
333 // Any tags...
334 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
335 $classes = array_merge(
336 array( 'mw-logline-' . $entry->getType() ),
337 $newClasses
340 return Html::rawElement( 'li', array( 'class' => $classes ),
341 "$del $time $action $comment $revert $tagDisplay" ) . "\n";
345 * @param stdClass $row Row
346 * @return string
348 private function getShowHideLinks( $row ) {
349 // We don't want to see the links and
350 if ( $this->flags == self::NO_ACTION_LINK ) {
351 return '';
354 $user = $this->getUser();
356 // If change tag editing is available to this user, return the checkbox
357 if ( $this->flags & self::USE_CHECKBOXES && $this->showTagEditUI ) {
358 return Xml::check(
359 'showhiderevisions',
360 false,
361 array( 'name' => 'ids[' . $row->log_id . ']' )
365 // no one can hide items from the suppress log.
366 if ( $row->log_type == 'suppress' ) {
367 return '';
370 $del = '';
371 // Don't show useless checkbox to people who cannot hide log entries
372 if ( $user->isAllowed( 'deletedhistory' ) ) {
373 $canHide = $user->isAllowed( 'deletelogentry' );
374 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
375 !$user->isAllowed( 'suppressrevision' );
376 $entryIsSuppressed = self::isDeleted( $row, LogPage::DELETED_RESTRICTED );
377 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
378 if ( $row->log_deleted || $canHide ) {
379 // Show checkboxes instead of links.
380 if ( $canHide && $this->flags & self::USE_CHECKBOXES && !$canViewThisSuppressedEntry ) {
381 // If event was hidden from sysops
382 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
383 $del = Xml::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
384 } else {
385 $del = Xml::check(
386 'showhiderevisions',
387 false,
388 array( 'name' => 'ids[' . $row->log_id . ']' )
391 } else {
392 // If event was hidden from sysops
393 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
394 $del = Linker::revDeleteLinkDisabled( $canHide );
395 } else {
396 $query = array(
397 'target' => SpecialPage::getTitleFor( 'Log', $row->log_type )->getPrefixedDBkey(),
398 'type' => 'logging',
399 'ids' => $row->log_id,
401 $del = Linker::revDeleteLink(
402 $query,
403 $entryIsSuppressed,
404 $canHide && !$canViewThisSuppressedEntry
411 return $del;
415 * @param stdClass $row Row
416 * @param string|array $type
417 * @param string|array $action
418 * @param string $right
419 * @return bool
421 public static function typeAction( $row, $type, $action, $right = '' ) {
422 $match = is_array( $type ) ?
423 in_array( $row->log_type, $type ) : $row->log_type == $type;
424 if ( $match ) {
425 $match = is_array( $action ) ?
426 in_array( $row->log_action, $action ) : $row->log_action == $action;
427 if ( $match && $right ) {
428 global $wgUser;
429 $match = $wgUser->isAllowed( $right );
433 return $match;
437 * Determine if the current user is allowed to view a particular
438 * field of this log row, if it's marked as deleted.
440 * @param stdClass $row Row
441 * @param int $field
442 * @param User $user User to check, or null to use $wgUser
443 * @return bool
445 public static function userCan( $row, $field, User $user = null ) {
446 return self::userCanBitfield( $row->log_deleted, $field, $user );
450 * Determine if the current user is allowed to view a particular
451 * field of this log row, if it's marked as deleted.
453 * @param int $bitfield Current field
454 * @param int $field
455 * @param User $user User to check, or null to use $wgUser
456 * @return bool
458 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
459 if ( $bitfield & $field ) {
460 if ( $user === null ) {
461 global $wgUser;
462 $user = $wgUser;
464 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
465 $permissions = array( 'suppressrevision', 'viewsuppressed' );
466 } else {
467 $permissions = array( 'deletedhistory' );
469 $permissionlist = implode( ', ', $permissions );
470 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
471 return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions );
473 return true;
477 * @param stdClass $row Row
478 * @param int $field One of DELETED_* bitfield constants
479 * @return bool
481 public static function isDeleted( $row, $field ) {
482 return ( $row->log_deleted & $field ) == $field;
486 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
488 * @param OutputPage|string $out By-reference
489 * @param string|array $types Log types to show
490 * @param string|Title $page The page title to show log entries for
491 * @param string $user The user who made the log entries
492 * @param array $param Associative Array with the following additional options:
493 * - lim Integer Limit of items to show, default is 50
494 * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'")
495 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
496 * if set to true (default), "No matching items in log" is displayed if loglist is empty
497 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
498 * First element is the message key, additional optional elements are parameters for the key
499 * that are processed with wfMessage
500 * - offset Set to overwrite offset parameter in WebRequest
501 * set to '' to unset offset
502 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
503 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
504 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
505 * - useMaster boolean Use master DB
506 * @return int Number of total log items (not limited by $lim)
508 public static function showLogExtract(
509 &$out, $types = array(), $page = '', $user = '', $param = array()
511 $defaultParameters = array(
512 'lim' => 25,
513 'conds' => array(),
514 'showIfEmpty' => true,
515 'msgKey' => array( '' ),
516 'wrap' => "$1",
517 'flags' => 0,
518 'useRequestParams' => false,
519 'useMaster' => false,
521 # The + operator appends elements of remaining keys from the right
522 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
523 $param += $defaultParameters;
524 # Convert $param array to individual variables
525 $lim = $param['lim'];
526 $conds = $param['conds'];
527 $showIfEmpty = $param['showIfEmpty'];
528 $msgKey = $param['msgKey'];
529 $wrap = $param['wrap'];
530 $flags = $param['flags'];
531 $useRequestParams = $param['useRequestParams'];
532 if ( !is_array( $msgKey ) ) {
533 $msgKey = array( $msgKey );
536 if ( $out instanceof OutputPage ) {
537 $context = $out->getContext();
538 } else {
539 $context = RequestContext::getMain();
542 # Insert list of top 50 (or top $lim) items
543 $loglist = new LogEventsList( $context, null, $flags );
544 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
545 if ( !$useRequestParams ) {
546 # Reset vars that may have been taken from the request
547 $pager->mLimit = 50;
548 $pager->mDefaultLimit = 50;
549 $pager->mOffset = "";
550 $pager->mIsBackwards = false;
553 if ( $param['useMaster'] ) {
554 $pager->mDb = wfGetDB( DB_MASTER );
556 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
557 $pager->setOffset( $param['offset'] );
560 if ( $lim > 0 ) {
561 $pager->mLimit = $lim;
563 // Fetch the log rows and build the HTML if needed
564 $logBody = $pager->getBody();
565 $numRows = $pager->getNumRows();
567 $s = '';
569 if ( $logBody ) {
570 if ( $msgKey[0] ) {
571 $dir = $context->getLanguage()->getDir();
572 $lang = $context->getLanguage()->getHtmlCode();
574 $s = Xml::openElement( 'div', array(
575 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
576 'dir' => $dir,
577 'lang' => $lang,
578 ) );
580 if ( count( $msgKey ) == 1 ) {
581 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
582 } else { // Process additional arguments
583 $args = $msgKey;
584 array_shift( $args );
585 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
588 $s .= $loglist->beginLogEventsList() .
589 $logBody .
590 $loglist->endLogEventsList();
591 } elseif ( $showIfEmpty ) {
592 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
593 $context->msg( 'logempty' )->parse() );
596 if ( $numRows > $pager->mLimit ) { # Show "Full log" link
597 $urlParam = array();
598 if ( $page instanceof Title ) {
599 $urlParam['page'] = $page->getPrefixedDBkey();
600 } elseif ( $page != '' ) {
601 $urlParam['page'] = $page;
604 if ( $user != '' ) {
605 $urlParam['user'] = $user;
608 if ( !is_array( $types ) ) { # Make it an array, if it isn't
609 $types = array( $types );
612 # If there is exactly one log type, we can link to Special:Log?type=foo
613 if ( count( $types ) == 1 ) {
614 $urlParam['type'] = $types[0];
617 $s .= Linker::link(
618 SpecialPage::getTitleFor( 'Log' ),
619 $context->msg( 'log-fulllog' )->escaped(),
620 array(),
621 $urlParam
625 if ( $logBody && $msgKey[0] ) {
626 $s .= '</div>';
629 if ( $wrap != '' ) { // Wrap message in html
630 $s = str_replace( '$1', $s, $wrap );
633 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
634 if ( Hooks::run( 'LogEventsListShowLogExtract', array( &$s, $types, $page, $user, $param ) ) ) {
635 // $out can be either an OutputPage object or a String-by-reference
636 if ( $out instanceof OutputPage ) {
637 $out->addHTML( $s );
638 } else {
639 $out = $s;
643 return $numRows;
647 * SQL clause to skip forbidden log types for this user
649 * @param IDatabase $db
650 * @param string $audience Public/user
651 * @param User $user User to check, or null to use $wgUser
652 * @return string|bool String on success, false on failure.
654 public static function getExcludeClause( $db, $audience = 'public', User $user = null ) {
655 global $wgLogRestrictions;
657 if ( $audience != 'public' && $user === null ) {
658 global $wgUser;
659 $user = $wgUser;
662 // Reset the array, clears extra "where" clauses when $par is used
663 $hiddenLogs = array();
665 // Don't show private logs to unprivileged users
666 foreach ( $wgLogRestrictions as $logType => $right ) {
667 if ( $audience == 'public' || !$user->isAllowed( $right ) ) {
668 $hiddenLogs[] = $logType;
671 if ( count( $hiddenLogs ) == 1 ) {
672 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
673 } elseif ( $hiddenLogs ) {
674 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';
677 return false;