3 * Contain classes to list log entries
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
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
26 use MediaWiki\Linker\LinkRenderer
;
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\Rdbms\IDatabase
;
30 class LogEventsList
extends ContextSource
{
31 const NO_ACTION_LINK
= 1;
32 const NO_EXTRA_USER_LINKS
= 2;
33 const USE_CHECKBOXES
= 4;
39 * @deprecated since 1.34, no longer used.
41 protected $mDefaultQuery;
46 protected $showTagEditUI;
51 protected $allowedActions = null;
54 * @var LinkRenderer|null
56 private $linkRenderer;
59 * The first two parameters used to be $skin and $out, but now only a context
60 * is needed, that's why there's a second unused parameter.
62 * @param IContextSource|Skin $context Context to use; formerly it was
63 * a Skin object. Use of Skin is deprecated.
64 * @param LinkRenderer|null $linkRenderer previously unused
65 * @param int $flags Can be a combination of self::NO_ACTION_LINK,
66 * self::NO_EXTRA_USER_LINKS or self::USE_CHECKBOXES.
68 public function __construct( $context, $linkRenderer = null, $flags = 0 ) {
69 if ( $context instanceof IContextSource
) {
70 $this->setContext( $context );
72 // Old parameters, $context should be a Skin object
73 $this->setContext( $context->getContext() );
76 $this->flags
= $flags;
77 $this->showTagEditUI
= ChangeTags
::showTagEditingUI( $this->getUser() );
78 if ( $linkRenderer instanceof LinkRenderer
) {
79 $this->linkRenderer
= $linkRenderer;
85 * @return LinkRenderer
87 protected function getLinkRenderer() {
88 if ( $this->linkRenderer
!== null ) {
89 return $this->linkRenderer
;
91 return MediaWikiServices
::getInstance()->getLinkRenderer();
96 * Show options for the log list
98 * @param array|string $types
100 * @param string $page
101 * @param bool $pattern
102 * @param int|string $year Use 0 to start with no year preselected.
103 * @param int|string $month A month in the 1..12 range. Use 0 to start with no month
105 * @param int|string $day A day in the 1..31 range. Use 0 to start with no month
107 * @param array|null $filter
108 * @param string $tagFilter Tag to select by default
109 * @param string|null $action
111 public function showOptions( $types = [], $user = '', $page = '', $pattern = false, $year = 0,
112 $month = 0, $day = 0, $filter = null, $tagFilter = '', $action = null
114 // For B/C, we take strings, but make sure they are converted...
115 $types = ( $types === '' ) ?
[] : (array)$types;
117 $formDescriptor = [];
120 $formDescriptor['type'] = $this->getTypeMenuDesc( $types );
121 $formDescriptor['user'] = $this->getUserInputDesc( $user );
122 $formDescriptor['page'] = $this->getTitleInputDesc( $page );
124 // Add extra inputs if any
125 // This could either be a form descriptor array or a string with raw HTML.
126 // We need it to work in both cases and show a deprecation warning if it
127 // is a string. See T199495.
128 $extraInputsDescriptor = $this->getExtraInputsDesc( $types );
130 is_array( $extraInputsDescriptor ) &&
131 !empty( $extraInputsDescriptor )
133 $formDescriptor[ 'extra' ] = $extraInputsDescriptor;
135 is_string( $extraInputsDescriptor ) &&
136 $extraInputsDescriptor !== ''
138 // We'll add this to the footer of the form later
139 $extraInputsString = $extraInputsDescriptor;
140 wfDeprecated( '$input in LogEventsListGetExtraInputs hook', '1.32' );
143 // Title pattern, if allowed
144 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
145 $formDescriptor['pattern'] = $this->getTitlePatternDesc( $pattern );
149 $formDescriptor['date'] = [
151 'label-message' => 'date',
152 'default' => $year && $month && $day ?
sprintf( "%04d-%02d-%02d", $year, $month, $day ) : '',
156 $formDescriptor['tagfilter'] = [
157 'type' => 'tagfilter',
158 'name' => 'tagfilter',
159 'label-raw' => $this->msg( 'tag-filter' )->parse(),
164 $formDescriptor['filters'] = $this->getFiltersDesc( $filter );
170 $this->allowedActions
!== null &&
171 count( $this->allowedActions
) > 0
173 $formDescriptor['subtype'] = $this->getActionSelectorDesc( $types, $action );
176 $context = new DerivativeContext( $this->getContext() );
177 $context->setTitle( SpecialPage
::getTitleFor( 'Log' ) ); // Remove subpage
178 $htmlForm = HTMLForm
::factory( 'ooui', $formDescriptor, $context );
180 ->setSubmitText( $this->msg( 'logeventslist-submit' )->text() )
182 ->setWrapperLegendMsg( 'log' );
184 // TODO This will should be removed at some point. See T199495.
185 if ( isset( $extraInputsString ) ) {
186 $htmlForm->addFooterText( Html
::rawElement(
193 $htmlForm->prepareForm()->displayForm( false );
197 * @param array $filter
198 * @return array Form descriptor
200 private function getFiltersDesc( $filter ) {
203 foreach ( $filter as $type => $val ) {
204 $message = $this->msg( "logeventslist-{$type}-log" );
205 // FIXME: Remove this check once T199657 is fully resolved.
206 if ( !$message->exists() ) {
207 $message = $this->msg( "log-show-hide-{$type}" )->params( $this->msg( 'show' )->text() );
209 $options[ $message->text() ] = $type;
211 if ( $val === false ) {
216 'class' => 'HTMLMultiSelectField',
217 'label-message' => 'logeventslist-more-filters',
219 'options' => $options,
220 'default' => $default,
225 * @param array $queryTypes
226 * @return array Form descriptor
228 private function getTypeMenuDesc( $queryTypes ) {
229 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
231 $typesByName = []; // Temporary array
232 // First pass to load the log names
233 foreach ( LogPage
::validTypes() as $type ) {
234 $page = new LogPage( $type );
235 $restriction = $page->getRestriction();
236 if ( $this->getUser()->isAllowed( $restriction ) ) {
237 $typesByName[$type] = $page->getName()->text();
241 // Second pass to sort by name
242 asort( $typesByName );
244 // Always put "All public logs" on top
245 $public = $typesByName[''];
246 unset( $typesByName[''] );
247 $typesByName = [ '' => $public ] +
$typesByName;
250 'class' => 'HTMLSelectField',
252 'options' => array_flip( $typesByName ),
253 'default' => $queryType,
258 * @param string $user
259 * @return array Form descriptor
261 private function getUserInputDesc( $user ) {
263 'class' => 'HTMLUserTextField',
264 'label-message' => 'specialloguserlabel',
271 * @param string $title
272 * @return array Form descriptor
274 private function getTitleInputDesc( $title ) {
276 'class' => 'HTMLTitleTextField',
277 'label-message' => 'speciallogtitlelabel',
284 * @param bool $pattern
285 * @return array Form descriptor
287 private function getTitlePatternDesc( $pattern ) {
290 'label-message' => 'log-title-wildcard',
296 * @param array $types
297 * @return array|string Form descriptor or string with HTML
299 private function getExtraInputsDesc( $types ) {
300 if ( count( $types ) == 1 ) {
301 if ( $types[0] == 'suppress' ) {
304 'label-message' => 'revdelete-offender',
305 'name' => 'offender',
308 // Allow extensions to add their own extra inputs
309 // This could be an array or string. See T199495.
310 $input = ''; // Deprecated
311 $formDescriptor = [];
312 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input, &$formDescriptor ] );
314 return empty( $formDescriptor ) ?
$input : $formDescriptor;
322 * Drop down menu for selection of actions that can be used to filter the log
323 * @param array $types
324 * @param string $action
325 * @return array Form descriptor
327 private function getActionSelectorDesc( $types, $action ) {
329 $actionOptions[ 'log-action-filter-all' ] = '';
331 foreach ( $this->allowedActions
as $value ) {
332 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
333 $actionOptions[ $msgKey ] = $value;
337 'class' => 'HTMLSelectField',
339 'options-messages' => $actionOptions,
340 'default' => $action,
341 'label' => $this->msg( 'log-action-filter-' . $types[0] )->text(),
346 * Sets the action types allowed for log filtering
347 * To one action type may correspond several log_actions
348 * @param array $actions
351 public function setAllowedActions( $actions ) {
352 $this->allowedActions
= $actions;
358 public function beginLogEventsList() {
365 public function endLogEventsList() {
370 * @param stdClass $row A single row from the result set
371 * @return string Formatted HTML list item
373 public function logLine( $row ) {
374 $entry = DatabaseLogEntry
::newFromRow( $row );
375 $formatter = LogFormatter
::newFromEntry( $entry );
376 $formatter->setContext( $this->getContext() );
377 $formatter->setLinkRenderer( $this->getLinkRenderer() );
378 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
380 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
381 $entry->getTimestamp(), $this->getUser() ) );
383 $action = $formatter->getActionText();
385 if ( $this->flags
& self
::NO_ACTION_LINK
) {
388 $revert = $formatter->getActionLinks();
389 if ( $revert != '' ) {
390 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
394 $comment = $formatter->getComment();
396 // Some user can hide log items and have review links
397 $del = $this->getShowHideLinks( $row );
400 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
405 $classes = array_merge(
406 [ 'mw-logline-' . $entry->getType() ],
410 'data-mw-logid' => $entry->getId(),
411 'data-mw-logaction' => $entry->getFullType(),
413 $ret = "$del $time $action $comment $revert $tagDisplay";
415 // Let extensions add data
416 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
417 $attribs = array_filter( $attribs,
418 [ Sanitizer
::class, 'isReservedDataAttribute' ],
421 $attribs['class'] = implode( ' ', $classes );
423 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
427 * @param stdClass $row
430 private function getShowHideLinks( $row ) {
431 // We don't want to see the links and
432 if ( $this->flags
== self
::NO_ACTION_LINK
) {
436 $user = $this->getUser();
438 // If change tag editing is available to this user, return the checkbox
439 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
443 [ 'name' => 'ids[' . $row->log_id
. ']' ]
447 // no one can hide items from the suppress log.
448 if ( $row->log_type
== 'suppress' ) {
453 // Don't show useless checkbox to people who cannot hide log entries
454 if ( $user->isAllowed( 'deletedhistory' ) ) {
455 $canHide = $user->isAllowed( 'deletelogentry' );
456 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
457 !$user->isAllowed( 'suppressrevision' );
458 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
459 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
460 if ( $row->log_deleted ||
$canHide ) {
461 // Show checkboxes instead of links.
462 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
463 // If event was hidden from sysops
464 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
465 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
470 [ 'name' => 'ids[' . $row->log_id
. ']' ]
474 // If event was hidden from sysops
475 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
476 $del = Linker
::revDeleteLinkDisabled( $canHide );
479 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
481 'ids' => $row->log_id
,
483 $del = Linker
::revDeleteLink(
486 $canHide && !$canViewThisSuppressedEntry
497 * @param stdClass $row
498 * @param string|array $type
499 * @param string|array $action
500 * @param string $right
503 public static function typeAction( $row, $type, $action, $right = '' ) {
504 $match = is_array( $type ) ?
505 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
507 $match = is_array( $action ) ?
508 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
509 if ( $match && $right ) {
511 $match = $wgUser->isAllowed( $right );
519 * Determine if the current user is allowed to view a particular
520 * field of this log row, if it's marked as deleted and/or restricted log type.
522 * @param stdClass $row
524 * @param User|null $user User to check, or null to use $wgUser
527 public static function userCan( $row, $field, User
$user = null ) {
528 return self
::userCanBitfield( $row->log_deleted
, $field, $user ) &&
529 self
::userCanViewLogType( $row->log_type
, $user );
533 * Determine if the current user is allowed to view a particular
534 * field of this log row, if it's marked as deleted.
536 * @param int $bitfield Current field
538 * @param User|null $user User to check, or null to use $wgUser
541 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
542 if ( $bitfield & $field ) {
543 if ( $user === null ) {
547 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
548 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
550 $permissions = [ 'deletedhistory' ];
552 $permissionlist = implode( ', ', $permissions );
553 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
554 return MediaWikiServices
::getInstance()
555 ->getPermissionManager()
556 ->userHasAnyRight( $user, ...$permissions );
562 * Determine if the current user is allowed to view a particular
563 * field of this log row, if it's marked as restricted log type.
565 * @param stdClass $type
566 * @param User|null $user User to check, or null to use $wgUser
569 public static function userCanViewLogType( $type, User
$user = null ) {
570 if ( $user === null ) {
574 $logRestrictions = MediaWikiServices
::getInstance()->getMainConfig()->get( 'LogRestrictions' );
575 if ( isset( $logRestrictions[$type] ) && !$user->isAllowed( $logRestrictions[$type] ) ) {
582 * @param stdClass $row
583 * @param int $field One of DELETED_* bitfield constants
586 public static function isDeleted( $row, $field ) {
587 return ( $row->log_deleted
& $field ) == $field;
591 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
593 * @param OutputPage|string &$out
594 * @param string|array $types Log types to show
595 * @param string|Title $page The page title to show log entries for
596 * @param string $user The user who made the log entries
597 * @param array $param Associative Array with the following additional options:
598 * - lim Integer Limit of items to show, default is 50
599 * - conds Array Extra conditions for the query
600 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
601 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
602 * if set to true (default), "No matching items in log" is displayed if loglist is empty
603 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
604 * First element is the message key, additional optional elements are parameters for the key
605 * that are processed with wfMessage
606 * - offset Set to overwrite offset parameter in WebRequest
607 * set to '' to unset offset
608 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
609 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
610 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
611 * - useMaster boolean Use master DB
612 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
613 * @return int Number of total log items (not limited by $lim)
615 public static function showLogExtract(
616 &$out, $types = [], $page = '', $user = '', $param = []
618 $defaultParameters = [
621 'showIfEmpty' => true,
625 'useRequestParams' => false,
626 'useMaster' => false,
627 'extraUrlParams' => false,
629 # The + operator appends elements of remaining keys from the right
630 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
631 $param +
= $defaultParameters;
632 # Convert $param array to individual variables
633 $lim = $param['lim'];
634 $conds = $param['conds'];
635 $showIfEmpty = $param['showIfEmpty'];
636 $msgKey = $param['msgKey'];
637 $wrap = $param['wrap'];
638 $flags = $param['flags'];
639 $extraUrlParams = $param['extraUrlParams'];
641 $useRequestParams = $param['useRequestParams'];
642 if ( !is_array( $msgKey ) ) {
643 $msgKey = [ $msgKey ];
646 if ( $out instanceof OutputPage
) {
647 $context = $out->getContext();
649 $context = RequestContext
::getMain();
652 // FIXME: Figure out how to inject this
653 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
655 # Insert list of top 50 (or top $lim) items
656 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
657 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
658 if ( !$useRequestParams ) {
659 # Reset vars that may have been taken from the request
661 $pager->mDefaultLimit
= 50;
662 $pager->mOffset
= "";
663 $pager->mIsBackwards
= false;
666 if ( $param['useMaster'] ) {
667 $pager->mDb
= wfGetDB( DB_MASTER
);
669 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
670 $pager->setOffset( $param['offset'] );
674 $pager->mLimit
= $lim;
676 // Fetch the log rows and build the HTML if needed
677 $logBody = $pager->getBody();
678 $numRows = $pager->getNumRows();
684 $dir = $context->getLanguage()->getDir();
685 $lang = $context->getLanguage()->getHtmlCode();
687 $s = Xml
::openElement( 'div', [
688 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
693 if ( count( $msgKey ) == 1 ) {
694 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
695 } else { // Process additional arguments
697 array_shift( $args );
698 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
701 $s .= $loglist->beginLogEventsList() .
703 $loglist->endLogEventsList();
704 // add styles for change tags
705 $context->getOutput()->addModuleStyles( 'mediawiki.interface.helpers.styles' );
706 } elseif ( $showIfEmpty ) {
707 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
708 $context->msg( 'logempty' )->parse() );
711 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
713 if ( $page instanceof Title
) {
714 $urlParam['page'] = $page->getPrefixedDBkey();
715 } elseif ( $page != '' ) {
716 $urlParam['page'] = $page;
720 $urlParam['user'] = $user;
723 if ( !is_array( $types ) ) { # Make it an array, if it isn't
727 # If there is exactly one log type, we can link to Special:Log?type=foo
728 if ( count( $types ) == 1 ) {
729 $urlParam['type'] = $types[0];
732 if ( $extraUrlParams !== false ) {
733 $urlParam = array_merge( $urlParam, $extraUrlParams );
736 $s .= $linkRenderer->makeKnownLink(
737 SpecialPage
::getTitleFor( 'Log' ),
738 $context->msg( 'log-fulllog' )->text(),
744 if ( $logBody && $msgKey[0] ) {
748 if ( $wrap != '' ) { // Wrap message in html
749 $s = str_replace( '$1', $s, $wrap );
752 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
753 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
754 // $out can be either an OutputPage object or a String-by-reference
755 if ( $out instanceof OutputPage
) {
766 * SQL clause to skip forbidden log types for this user
768 * @param IDatabase $db
769 * @param string $audience Public/user
770 * @param User|null $user User to check, or null to use $wgUser
771 * @return string|bool String on success, false on failure.
773 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
774 global $wgLogRestrictions;
776 if ( $audience != 'public' && $user === null ) {
781 // Reset the array, clears extra "where" clauses when $par is used
784 // Don't show private logs to unprivileged users
785 foreach ( $wgLogRestrictions as $logType => $right ) {
786 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
787 $hiddenLogs[] = $logType;
790 if ( count( $hiddenLogs ) == 1 ) {
791 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
792 } elseif ( $hiddenLogs ) {
793 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';