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 ( MediaWikiServices
::getInstance()
237 ->getPermissionManager()
238 ->userHasRight( $this->getUser(), $restriction )
240 $typesByName[$type] = $page->getName()->text();
244 // Second pass to sort by name
245 asort( $typesByName );
247 // Always put "All public logs" on top
248 $public = $typesByName[''];
249 unset( $typesByName[''] );
250 $typesByName = [ '' => $public ] +
$typesByName;
253 'class' => 'HTMLSelectField',
255 'options' => array_flip( $typesByName ),
256 'default' => $queryType,
261 * @param string $user
262 * @return array Form descriptor
264 private function getUserInputDesc( $user ) {
266 'class' => 'HTMLUserTextField',
267 'label-message' => 'specialloguserlabel',
274 * @param string $title
275 * @return array Form descriptor
277 private function getTitleInputDesc( $title ) {
279 'class' => 'HTMLTitleTextField',
280 'label-message' => 'speciallogtitlelabel',
287 * @param bool $pattern
288 * @return array Form descriptor
290 private function getTitlePatternDesc( $pattern ) {
293 'label-message' => 'log-title-wildcard',
299 * @param array $types
300 * @return array|string Form descriptor or string with HTML
302 private function getExtraInputsDesc( $types ) {
303 if ( count( $types ) == 1 ) {
304 if ( $types[0] == 'suppress' ) {
307 'label-message' => 'revdelete-offender',
308 'name' => 'offender',
311 // Allow extensions to add their own extra inputs
312 // This could be an array or string. See T199495.
313 $input = ''; // Deprecated
314 $formDescriptor = [];
315 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input, &$formDescriptor ] );
317 return empty( $formDescriptor ) ?
$input : $formDescriptor;
325 * Drop down menu for selection of actions that can be used to filter the log
326 * @param array $types
327 * @param string $action
328 * @return array Form descriptor
330 private function getActionSelectorDesc( $types, $action ) {
332 $actionOptions[ 'log-action-filter-all' ] = '';
334 foreach ( $this->allowedActions
as $value ) {
335 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
336 $actionOptions[ $msgKey ] = $value;
340 'class' => 'HTMLSelectField',
342 'options-messages' => $actionOptions,
343 'default' => $action,
344 'label' => $this->msg( 'log-action-filter-' . $types[0] )->text(),
349 * Sets the action types allowed for log filtering
350 * To one action type may correspond several log_actions
351 * @param array $actions
354 public function setAllowedActions( $actions ) {
355 $this->allowedActions
= $actions;
361 public function beginLogEventsList() {
368 public function endLogEventsList() {
373 * @param stdClass $row A single row from the result set
374 * @return string Formatted HTML list item
376 public function logLine( $row ) {
377 $entry = DatabaseLogEntry
::newFromRow( $row );
378 $formatter = LogFormatter
::newFromEntry( $entry );
379 $formatter->setContext( $this->getContext() );
380 $formatter->setLinkRenderer( $this->getLinkRenderer() );
381 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
383 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
384 $entry->getTimestamp(), $this->getUser() ) );
386 $action = $formatter->getActionText();
388 if ( $this->flags
& self
::NO_ACTION_LINK
) {
391 $revert = $formatter->getActionLinks();
392 if ( $revert != '' ) {
393 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
397 $comment = $formatter->getComment();
399 // Some user can hide log items and have review links
400 $del = $this->getShowHideLinks( $row );
403 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
408 $classes = array_merge(
409 [ 'mw-logline-' . $entry->getType() ],
413 'data-mw-logid' => $entry->getId(),
414 'data-mw-logaction' => $entry->getFullType(),
416 $ret = "$del $time $action $comment $revert $tagDisplay";
418 // Let extensions add data
419 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
420 $attribs = array_filter( $attribs,
421 [ Sanitizer
::class, 'isReservedDataAttribute' ],
424 $attribs['class'] = implode( ' ', $classes );
426 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
430 * @param stdClass $row
433 private function getShowHideLinks( $row ) {
434 // We don't want to see the links and
435 if ( $this->flags
== self
::NO_ACTION_LINK
) {
439 $user = $this->getUser();
441 // If change tag editing is available to this user, return the checkbox
442 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
446 [ 'name' => 'ids[' . $row->log_id
. ']' ]
450 // no one can hide items from the suppress log.
451 if ( $row->log_type
== 'suppress' ) {
456 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
457 // Don't show useless checkbox to people who cannot hide log entries
458 if ( $permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
459 $canHide = $permissionManager->userHasRight( $user, 'deletelogentry' );
460 $canViewSuppressedOnly = $permissionManager->userHasRight( $user, 'viewsuppressed' ) &&
461 !$permissionManager->userHasRight( $user, 'suppressrevision' );
462 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
463 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
464 if ( $row->log_deleted ||
$canHide ) {
465 // Show checkboxes instead of links.
466 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
467 // If event was hidden from sysops
468 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
469 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
474 [ 'name' => 'ids[' . $row->log_id
. ']' ]
478 // If event was hidden from sysops
479 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
480 $del = Linker
::revDeleteLinkDisabled( $canHide );
483 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
485 'ids' => $row->log_id
,
487 $del = Linker
::revDeleteLink(
490 $canHide && !$canViewThisSuppressedEntry
501 * @param stdClass $row
502 * @param string|array $type
503 * @param string|array $action
504 * @param string $right
507 public static function typeAction( $row, $type, $action, $right = '' ) {
508 $match = is_array( $type ) ?
509 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
511 $match = is_array( $action ) ?
512 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
513 if ( $match && $right ) {
515 $match = MediaWikiServices
::getInstance()
516 ->getPermissionManager()
517 ->userHasRight( $wgUser, $right );
525 * Determine if the current user is allowed to view a particular
526 * field of this log row, if it's marked as deleted and/or restricted log type.
528 * @param stdClass $row
530 * @param User|null $user User to check, or null to use $wgUser
533 public static function userCan( $row, $field, User
$user = null ) {
534 return self
::userCanBitfield( $row->log_deleted
, $field, $user ) &&
535 self
::userCanViewLogType( $row->log_type
, $user );
539 * Determine if the current user is allowed to view a particular
540 * field of this log row, if it's marked as deleted.
542 * @param int $bitfield Current field
544 * @param User|null $user User to check, or null to use $wgUser
547 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
548 if ( $bitfield & $field ) {
549 if ( $user === null ) {
553 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
554 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
556 $permissions = [ 'deletedhistory' ];
558 $permissionlist = implode( ', ', $permissions );
559 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
560 return MediaWikiServices
::getInstance()
561 ->getPermissionManager()
562 ->userHasAnyRight( $user, ...$permissions );
568 * Determine if the current user is allowed to view a particular
569 * field of this log row, if it's marked as restricted log type.
571 * @param stdClass $type
572 * @param User|null $user User to check, or null to use $wgUser
575 public static function userCanViewLogType( $type, User
$user = null ) {
576 if ( $user === null ) {
580 $logRestrictions = MediaWikiServices
::getInstance()->getMainConfig()->get( 'LogRestrictions' );
581 if ( isset( $logRestrictions[$type] ) && !MediaWikiServices
::getInstance()
582 ->getPermissionManager()
583 ->userHasRight( $user, $logRestrictions[$type] )
591 * @param stdClass $row
592 * @param int $field One of DELETED_* bitfield constants
595 public static function isDeleted( $row, $field ) {
596 return ( $row->log_deleted
& $field ) == $field;
600 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
602 * @param OutputPage|string &$out
603 * @param string|array $types Log types to show
604 * @param string|Title $page The page title to show log entries for
605 * @param string $user The user who made the log entries
606 * @param array $param Associative Array with the following additional options:
607 * - lim Integer Limit of items to show, default is 50
608 * - conds Array Extra conditions for the query
609 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
610 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
611 * if set to true (default), "No matching items in log" is displayed if loglist is empty
612 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
613 * First element is the message key, additional optional elements are parameters for the key
614 * that are processed with wfMessage
615 * - offset Set to overwrite offset parameter in WebRequest
616 * set to '' to unset offset
617 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
618 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
619 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
620 * - useMaster boolean Use master DB
621 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
622 * @return int Number of total log items (not limited by $lim)
624 public static function showLogExtract(
625 &$out, $types = [], $page = '', $user = '', $param = []
627 $defaultParameters = [
630 'showIfEmpty' => true,
634 'useRequestParams' => false,
635 'useMaster' => false,
636 'extraUrlParams' => false,
638 # The + operator appends elements of remaining keys from the right
639 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
640 $param +
= $defaultParameters;
641 # Convert $param array to individual variables
642 $lim = $param['lim'];
643 $conds = $param['conds'];
644 $showIfEmpty = $param['showIfEmpty'];
645 $msgKey = $param['msgKey'];
646 $wrap = $param['wrap'];
647 $flags = $param['flags'];
648 $extraUrlParams = $param['extraUrlParams'];
650 $useRequestParams = $param['useRequestParams'];
651 if ( !is_array( $msgKey ) ) {
652 $msgKey = [ $msgKey ];
655 if ( $out instanceof OutputPage
) {
656 $context = $out->getContext();
658 $context = RequestContext
::getMain();
661 // FIXME: Figure out how to inject this
662 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
664 # Insert list of top 50 (or top $lim) items
665 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
666 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
667 if ( !$useRequestParams ) {
668 # Reset vars that may have been taken from the request
670 $pager->mDefaultLimit
= 50;
671 $pager->mOffset
= "";
672 $pager->mIsBackwards
= false;
675 if ( $param['useMaster'] ) {
676 $pager->mDb
= wfGetDB( DB_MASTER
);
678 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
679 $pager->setOffset( $param['offset'] );
683 $pager->mLimit
= $lim;
685 // Fetch the log rows and build the HTML if needed
686 $logBody = $pager->getBody();
687 $numRows = $pager->getNumRows();
693 $dir = $context->getLanguage()->getDir();
694 $lang = $context->getLanguage()->getHtmlCode();
696 $s = Xml
::openElement( 'div', [
697 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
702 if ( count( $msgKey ) == 1 ) {
703 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
704 } else { // Process additional arguments
706 array_shift( $args );
707 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
710 $s .= $loglist->beginLogEventsList() .
712 $loglist->endLogEventsList();
713 // add styles for change tags
714 $context->getOutput()->addModuleStyles( 'mediawiki.interface.helpers.styles' );
715 } elseif ( $showIfEmpty ) {
716 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
717 $context->msg( 'logempty' )->parse() );
720 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
722 if ( $page instanceof Title
) {
723 $urlParam['page'] = $page->getPrefixedDBkey();
724 } elseif ( $page != '' ) {
725 $urlParam['page'] = $page;
729 $urlParam['user'] = $user;
732 if ( !is_array( $types ) ) { # Make it an array, if it isn't
736 # If there is exactly one log type, we can link to Special:Log?type=foo
737 if ( count( $types ) == 1 ) {
738 $urlParam['type'] = $types[0];
741 if ( $extraUrlParams !== false ) {
742 $urlParam = array_merge( $urlParam, $extraUrlParams );
745 $s .= $linkRenderer->makeKnownLink(
746 SpecialPage
::getTitleFor( 'Log' ),
747 $context->msg( 'log-fulllog' )->text(),
753 if ( $logBody && $msgKey[0] ) {
757 if ( $wrap != '' ) { // Wrap message in html
758 $s = str_replace( '$1', $s, $wrap );
761 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
762 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
763 // $out can be either an OutputPage object or a String-by-reference
764 if ( $out instanceof OutputPage
) {
775 * SQL clause to skip forbidden log types for this user
777 * @param IDatabase $db
778 * @param string $audience Public/user
779 * @param User|null $user User to check, or null to use $wgUser
780 * @return string|bool String on success, false on failure.
782 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
783 global $wgLogRestrictions;
785 if ( $audience != 'public' && $user === null ) {
790 // Reset the array, clears extra "where" clauses when $par is used
793 // Don't show private logs to unprivileged users
794 foreach ( $wgLogRestrictions as $logType => $right ) {
795 if ( $audience == 'public' ||
!MediaWikiServices
::getInstance()
796 ->getPermissionManager()
797 ->userHasRight( $user, $right )
799 $hiddenLogs[] = $logType;
802 if ( count( $hiddenLogs ) == 1 ) {
803 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
804 } elseif ( $hiddenLogs ) {
805 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';