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;
40 protected $mDefaultQuery;
45 protected $showTagEditUI;
50 protected $allowedActions = null;
53 * @var LinkRenderer|null
55 private $linkRenderer;
58 * The first two parameters used to be $skin and $out, but now only a context
59 * is needed, that's why there's a second unused parameter.
61 * @param IContextSource|Skin $context Context to use; formerly it was
62 * a Skin object. Use of Skin is deprecated.
63 * @param LinkRenderer|null $linkRenderer previously unused
64 * @param int $flags Can be a combination of self::NO_ACTION_LINK,
65 * self::NO_EXTRA_USER_LINKS or self::USE_CHECKBOXES.
67 public function __construct( $context, $linkRenderer = null, $flags = 0 ) {
68 if ( $context instanceof IContextSource
) {
69 $this->setContext( $context );
71 // Old parameters, $context should be a Skin object
72 $this->setContext( $context->getContext() );
75 $this->flags
= $flags;
76 $this->showTagEditUI
= ChangeTags
::showTagEditingUI( $this->getUser() );
77 if ( $linkRenderer instanceof LinkRenderer
) {
78 $this->linkRenderer
= $linkRenderer;
84 * @return LinkRenderer
86 protected function getLinkRenderer() {
87 if ( $this->linkRenderer
!== null ) {
88 return $this->linkRenderer
;
90 return MediaWikiServices
::getInstance()->getLinkRenderer();
95 * Show options for the log list
97 * @param array|string $types
100 * @param bool $pattern
101 * @param int|string $year Use 0 to start with no year preselected.
102 * @param int|string $month A month in the 1..12 range. Use 0 to start with no month
104 * @param int|string $day A day in the 1..31 range. Use 0 to start with no month
106 * @param array|null $filter
107 * @param string $tagFilter Tag to select by default
108 * @param string|null $action
110 public function showOptions( $types = [], $user = '', $page = '', $pattern = false, $year = 0,
111 $month = 0, $day = 0, $filter = null, $tagFilter = '', $action = null
113 // For B/C, we take strings, but make sure they are converted...
114 $types = ( $types === '' ) ?
[] : (array)$types;
116 $formDescriptor = [];
119 $formDescriptor['type'] = $this->getTypeMenuDesc( $types );
120 $formDescriptor['user'] = $this->getUserInputDesc( $user );
121 $formDescriptor['page'] = $this->getTitleInputDesc( $page );
123 // Add extra inputs if any
124 // This could either be a form descriptor array or a string with raw HTML.
125 // We need it to work in both cases and show a deprecation warning if it
126 // is a string. See T199495.
127 $extraInputsDescriptor = $this->getExtraInputsDesc( $types );
129 is_array( $extraInputsDescriptor ) &&
130 !empty( $extraInputsDescriptor )
132 $formDescriptor[ 'extra' ] = $extraInputsDescriptor;
133 } elseif ( is_string( $extraInputsDescriptor ) ) {
134 // We'll add this to the footer of the form later
135 $extraInputsString = $extraInputsDescriptor;
136 wfDeprecated( 'Using $input in LogEventsListGetExtraInputs hook', '1.32' );
139 // Title pattern, if allowed
140 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
141 $formDescriptor['pattern'] = $this->getTitlePatternDesc( $pattern );
145 $formDescriptor['date'] = [
147 'label-message' => 'date',
148 'default' => sprintf( "%04d-%02d-%02d", $year, $month, $day ),
152 $formDescriptor['tagfilter'] = [
153 'type' => 'tagfilter',
154 'name' => 'tagfilter',
155 'label-raw' => $this->msg( 'tag-filter' )->parse(),
160 $formDescriptor['filters'] = $this->getFiltersDesc( $filter );
166 $this->allowedActions
!== null &&
167 count( $this->allowedActions
) > 0
169 $formDescriptor['subtype'] = $this->getActionSelectorDesc( $types, $action );
172 $context = new DerivativeContext( $this->getContext() );
173 $context->setTitle( SpecialPage
::getTitleFor( 'Log' ) ); // Remove subpage
174 $htmlForm = new HTMLForm( $formDescriptor, $context );
176 ->setSubmitText( $this->msg( 'logeventslist-submit' )->text() )
178 ->setWrapperLegendMsg( 'log' );
180 // TODO This will should be removed at some point. See T199495.
181 if ( isset( $extraInputsString ) ) {
182 $htmlForm->addFooterText( Html
::rawElement(
189 $htmlForm->prepareForm()->displayForm( false );
193 * @param array $filter
194 * @return array Form descriptor
196 private function getFiltersDesc( $filter ) {
199 foreach ( $filter as $type => $val ) {
200 $message = $this->msg( "logeventslist-{$type}-log" );
201 // FIXME: Remove this check once T199657 is fully resolved.
202 if ( !$message->exists() ) {
203 $message = $this->msg( "log-show-hide-{$type}" )->params( $this->msg( 'show' )->text() );
205 $options[ $message->text() ] = $type;
207 if ( $val === false ) {
212 'class' => 'HTMLMultiSelectField',
213 'label-message' => 'logeventslist-more-filters',
215 'options' => $options,
216 'default' => $default,
220 private function getDefaultQuery() {
221 if ( !isset( $this->mDefaultQuery
) ) {
222 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
223 unset( $this->mDefaultQuery
['title'] );
224 unset( $this->mDefaultQuery
['dir'] );
225 unset( $this->mDefaultQuery
['offset'] );
226 unset( $this->mDefaultQuery
['limit'] );
227 unset( $this->mDefaultQuery
['order'] );
228 unset( $this->mDefaultQuery
['month'] );
229 unset( $this->mDefaultQuery
['year'] );
232 return $this->mDefaultQuery
;
236 * @param array $queryTypes
237 * @return array Form descriptor
239 private function getTypeMenuDesc( $queryTypes ) {
240 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
242 $typesByName = []; // Temporary array
243 // First pass to load the log names
244 foreach ( LogPage
::validTypes() as $type ) {
245 $page = new LogPage( $type );
246 $restriction = $page->getRestriction();
247 if ( $this->getUser()->isAllowed( $restriction ) ) {
248 $typesByName[$type] = $page->getName()->text();
252 // Second pass to sort by name
253 asort( $typesByName );
255 // Always put "All public logs" on top
256 $public = $typesByName[''];
257 unset( $typesByName[''] );
258 $typesByName = [ '' => $public ] +
$typesByName;
261 'class' => 'HTMLSelectField',
263 'options' => array_flip( $typesByName ),
264 'default' => $queryType,
269 * @param string $user
270 * @return array Form descriptor
272 private function getUserInputDesc( $user ) {
274 'class' => 'HTMLUserTextField',
275 'label-message' => 'specialloguserlabel',
282 * @param string $title
283 * @return array Form descriptor
285 private function getTitleInputDesc( $title ) {
287 'class' => 'HTMLTitleTextField',
288 'label-message' => 'speciallogtitlelabel',
295 * @param bool $pattern
296 * @return array Form descriptor
298 private function getTitlePatternDesc( $pattern ) {
301 'label-message' => 'log-title-wildcard',
307 * @param array $types
308 * @return array|string Form descriptor or string with HTML
310 private function getExtraInputsDesc( $types ) {
311 if ( count( $types ) == 1 ) {
312 if ( $types[0] == 'suppress' ) {
315 'label-message' => 'revdelete-offender',
316 'name' => 'offender',
319 // Allow extensions to add their own extra inputs
320 // This could be an array or string. See T199495.
321 $input = ''; // Deprecated
322 $formDescriptor = [];
323 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input, &$formDescriptor ] );
325 return empty( $formDescriptor ) ?
$input : $formDescriptor;
333 * Drop down menu for selection of actions that can be used to filter the log
334 * @param array $types
335 * @param string $action
336 * @return array Form descriptor
338 private function getActionSelectorDesc( $types, $action ) {
340 $actionOptions[ 'log-action-filter-all' ] = '';
342 foreach ( $this->allowedActions
as $value ) {
343 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
344 $actionOptions[ $msgKey ] = $value;
348 'class' => 'HTMLSelectField',
350 'options-messages' => $actionOptions,
351 'default' => $action,
352 'label' => $this->msg( 'log-action-filter-' . $types[0] )->text(),
357 * Sets the action types allowed for log filtering
358 * To one action type may correspond several log_actions
359 * @param array $actions
362 public function setAllowedActions( $actions ) {
363 $this->allowedActions
= $actions;
369 public function beginLogEventsList() {
376 public function endLogEventsList() {
381 * @param stdClass $row A single row from the result set
382 * @return string Formatted HTML list item
384 public function logLine( $row ) {
385 $entry = DatabaseLogEntry
::newFromRow( $row );
386 $formatter = LogFormatter
::newFromEntry( $entry );
387 $formatter->setContext( $this->getContext() );
388 $formatter->setLinkRenderer( $this->getLinkRenderer() );
389 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
391 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
392 $entry->getTimestamp(), $this->getUser() ) );
394 $action = $formatter->getActionText();
396 if ( $this->flags
& self
::NO_ACTION_LINK
) {
399 $revert = $formatter->getActionLinks();
400 if ( $revert != '' ) {
401 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
405 $comment = $formatter->getComment();
407 // Some user can hide log items and have review links
408 $del = $this->getShowHideLinks( $row );
411 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
416 $classes = array_merge(
417 [ 'mw-logline-' . $entry->getType() ],
421 'data-mw-logid' => $entry->getId(),
422 'data-mw-logaction' => $entry->getFullType(),
424 $ret = "$del $time $action $comment $revert $tagDisplay";
426 // Let extensions add data
427 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
428 $attribs = array_filter( $attribs,
429 [ Sanitizer
::class, 'isReservedDataAttribute' ],
432 $attribs['class'] = implode( ' ', $classes );
434 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
438 * @param stdClass $row
441 private function getShowHideLinks( $row ) {
442 // We don't want to see the links and
443 if ( $this->flags
== self
::NO_ACTION_LINK
) {
447 $user = $this->getUser();
449 // If change tag editing is available to this user, return the checkbox
450 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
454 [ 'name' => 'ids[' . $row->log_id
. ']' ]
458 // no one can hide items from the suppress log.
459 if ( $row->log_type
== 'suppress' ) {
464 // Don't show useless checkbox to people who cannot hide log entries
465 if ( $user->isAllowed( 'deletedhistory' ) ) {
466 $canHide = $user->isAllowed( 'deletelogentry' );
467 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
468 !$user->isAllowed( 'suppressrevision' );
469 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
470 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
471 if ( $row->log_deleted ||
$canHide ) {
472 // Show checkboxes instead of links.
473 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
474 // If event was hidden from sysops
475 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
476 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
481 [ 'name' => 'ids[' . $row->log_id
. ']' ]
485 // If event was hidden from sysops
486 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
487 $del = Linker
::revDeleteLinkDisabled( $canHide );
490 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
492 'ids' => $row->log_id
,
494 $del = Linker
::revDeleteLink(
497 $canHide && !$canViewThisSuppressedEntry
508 * @param stdClass $row
509 * @param string|array $type
510 * @param string|array $action
511 * @param string $right
514 public static function typeAction( $row, $type, $action, $right = '' ) {
515 $match = is_array( $type ) ?
516 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
518 $match = is_array( $action ) ?
519 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
520 if ( $match && $right ) {
522 $match = $wgUser->isAllowed( $right );
530 * Determine if the current user is allowed to view a particular
531 * field of this log row, if it's marked as deleted.
533 * @param stdClass $row
535 * @param User|null $user User to check, or null to use $wgUser
538 public static function userCan( $row, $field, User
$user = null ) {
539 return self
::userCanBitfield( $row->log_deleted
, $field, $user );
543 * Determine if the current user is allowed to view a particular
544 * field of this log row, if it's marked as deleted.
546 * @param int $bitfield Current field
548 * @param User|null $user User to check, or null to use $wgUser
551 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
552 if ( $bitfield & $field ) {
553 if ( $user === null ) {
557 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
558 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
560 $permissions = [ 'deletedhistory' ];
562 $permissionlist = implode( ', ', $permissions );
563 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
564 return $user->isAllowedAny( ...$permissions );
570 * @param stdClass $row
571 * @param int $field One of DELETED_* bitfield constants
574 public static function isDeleted( $row, $field ) {
575 return ( $row->log_deleted
& $field ) == $field;
579 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
581 * @param OutputPage|string &$out
582 * @param string|array $types Log types to show
583 * @param string|Title $page The page title to show log entries for
584 * @param string $user The user who made the log entries
585 * @param array $param Associative Array with the following additional options:
586 * - lim Integer Limit of items to show, default is 50
587 * - conds Array Extra conditions for the query
588 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
589 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
590 * if set to true (default), "No matching items in log" is displayed if loglist is empty
591 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
592 * First element is the message key, additional optional elements are parameters for the key
593 * that are processed with wfMessage
594 * - offset Set to overwrite offset parameter in WebRequest
595 * set to '' to unset offset
596 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
597 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
598 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
599 * - useMaster boolean Use master DB
600 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
601 * @return int Number of total log items (not limited by $lim)
603 public static function showLogExtract(
604 &$out, $types = [], $page = '', $user = '', $param = []
606 $defaultParameters = [
609 'showIfEmpty' => true,
613 'useRequestParams' => false,
614 'useMaster' => false,
615 'extraUrlParams' => false,
617 # The + operator appends elements of remaining keys from the right
618 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
619 $param +
= $defaultParameters;
620 # Convert $param array to individual variables
621 $lim = $param['lim'];
622 $conds = $param['conds'];
623 $showIfEmpty = $param['showIfEmpty'];
624 $msgKey = $param['msgKey'];
625 $wrap = $param['wrap'];
626 $flags = $param['flags'];
627 $extraUrlParams = $param['extraUrlParams'];
629 $useRequestParams = $param['useRequestParams'];
630 if ( !is_array( $msgKey ) ) {
631 $msgKey = [ $msgKey ];
634 if ( $out instanceof OutputPage
) {
635 $context = $out->getContext();
637 $context = RequestContext
::getMain();
640 // FIXME: Figure out how to inject this
641 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
643 # Insert list of top 50 (or top $lim) items
644 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
645 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
646 if ( !$useRequestParams ) {
647 # Reset vars that may have been taken from the request
649 $pager->mDefaultLimit
= 50;
650 $pager->mOffset
= "";
651 $pager->mIsBackwards
= false;
654 if ( $param['useMaster'] ) {
655 $pager->mDb
= wfGetDB( DB_MASTER
);
657 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
658 $pager->setOffset( $param['offset'] );
662 $pager->mLimit
= $lim;
664 // Fetch the log rows and build the HTML if needed
665 $logBody = $pager->getBody();
666 $numRows = $pager->getNumRows();
672 $dir = $context->getLanguage()->getDir();
673 $lang = $context->getLanguage()->getHtmlCode();
675 $s = Xml
::openElement( 'div', [
676 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
681 if ( count( $msgKey ) == 1 ) {
682 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
683 } else { // Process additional arguments
685 array_shift( $args );
686 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
689 $s .= $loglist->beginLogEventsList() .
691 $loglist->endLogEventsList();
692 } elseif ( $showIfEmpty ) {
693 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
694 $context->msg( 'logempty' )->parse() );
697 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
699 if ( $page instanceof Title
) {
700 $urlParam['page'] = $page->getPrefixedDBkey();
701 } elseif ( $page != '' ) {
702 $urlParam['page'] = $page;
706 $urlParam['user'] = $user;
709 if ( !is_array( $types ) ) { # Make it an array, if it isn't
713 # If there is exactly one log type, we can link to Special:Log?type=foo
714 if ( count( $types ) == 1 ) {
715 $urlParam['type'] = $types[0];
718 if ( $extraUrlParams !== false ) {
719 $urlParam = array_merge( $urlParam, $extraUrlParams );
722 $s .= $linkRenderer->makeKnownLink(
723 SpecialPage
::getTitleFor( 'Log' ),
724 $context->msg( 'log-fulllog' )->text(),
730 if ( $logBody && $msgKey[0] ) {
734 if ( $wrap != '' ) { // Wrap message in html
735 $s = str_replace( '$1', $s, $wrap );
738 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
739 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
740 // $out can be either an OutputPage object or a String-by-reference
741 if ( $out instanceof OutputPage
) {
752 * SQL clause to skip forbidden log types for this user
754 * @param IDatabase $db
755 * @param string $audience Public/user
756 * @param User|null $user User to check, or null to use $wgUser
757 * @return string|bool String on success, false on failure.
759 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
760 global $wgLogRestrictions;
762 if ( $audience != 'public' && $user === null ) {
767 // Reset the array, clears extra "where" clauses when $par is used
770 // Don't show private logs to unprivileged users
771 foreach ( $wgLogRestrictions as $logType => $right ) {
772 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
773 $hiddenLogs[] = $logType;
776 if ( count( $hiddenLogs ) == 1 ) {
777 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
778 } elseif ( $hiddenLogs ) {
779 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';