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 $title = SpecialPage
::getTitleFor( 'Log' );
115 // For B/C, we take strings, but make sure they are converted...
116 $types = ( $types === '' ) ?
[] : (array)$types;
118 $formDescriptor = [];
121 $formDescriptor['type'] = $this->getTypeMenuDesc( $types );
122 $formDescriptor['user'] = $this->getUserInputDesc( $user );
123 $formDescriptor['page'] = $this->getTitleInputDesc( $title );
125 // Add extra inputs if any
126 // This could either be a form descriptor array or a string with raw HTML.
127 // We need it to work in both cases and show a deprecation warning if it
128 // is a string. See T199495.
129 $extraInputsDescriptor = $this->getExtraInputsDesc( $types );
131 is_array( $extraInputsDescriptor ) &&
132 !empty( $extraInputsDescriptor )
134 $formDescriptor[ 'extra' ] = $extraInputsDescriptor;
135 } elseif ( is_string( $extraInputsDescriptor ) ) {
136 // We'll add this to the footer of the form later
137 $extraInputsString = $extraInputsDescriptor;
138 wfDeprecated( 'Using $input in LogEventsListGetExtraInputs hook', '1.32' );
141 // Title pattern, if allowed
142 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
143 $formDescriptor['pattern'] = $this->getTitlePatternDesc( $pattern );
147 $formDescriptor['date'] = [
149 'label-message' => 'date'
153 $formDescriptor['tagfilter'] = [
154 'type' => 'tagfilter',
155 'name' => 'tagfilter',
156 'label-raw' => $this->msg( 'tag-filter' )->parse(),
161 $formDescriptor['filters'] = $this->getFiltersDesc( $filter );
167 $this->allowedActions
!== null &&
168 count( $this->allowedActions
) > 0
170 $formDescriptor['subtype'] = $this->getActionSelectorDesc( $types, $action );
173 $htmlForm = new HTMLForm( $formDescriptor, $this->getContext() );
175 ->setSubmitText( $this->msg( 'logeventslist-submit' )->text() )
176 ->setWrapperLegendMsg( 'log' );
178 // TODO This will should be removed at some point. See T199495.
179 if ( isset( $extraInputsString ) ) {
180 $htmlForm->addFooterText( Html
::rawElement(
187 $htmlForm->prepareForm()->displayForm( false );
191 * @param array $filter
192 * @return array Form descriptor
194 private function getFiltersDesc( $filter ) {
197 foreach ( $filter as $type => $val ) {
198 $options[ $this->msg( "logeventslist-{$type}-log" )->text() ] = $type;
205 'class' => 'HTMLMultiSelectField',
206 'label-message' => 'logeventslist-more-filters',
208 'options' => $options,
209 'default' => $default,
213 private function getDefaultQuery() {
214 if ( !isset( $this->mDefaultQuery
) ) {
215 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
216 unset( $this->mDefaultQuery
['title'] );
217 unset( $this->mDefaultQuery
['dir'] );
218 unset( $this->mDefaultQuery
['offset'] );
219 unset( $this->mDefaultQuery
['limit'] );
220 unset( $this->mDefaultQuery
['order'] );
221 unset( $this->mDefaultQuery
['month'] );
222 unset( $this->mDefaultQuery
['year'] );
225 return $this->mDefaultQuery
;
229 * @param array $queryTypes
230 * @return array Form descriptor
232 private function getTypeMenuDesc( $queryTypes ) {
233 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
235 $typesByName = []; // Temporary array
236 // First pass to load the log names
237 foreach ( LogPage
::validTypes() as $type ) {
238 $page = new LogPage( $type );
239 $restriction = $page->getRestriction();
240 if ( $this->getUser()->isAllowed( $restriction ) ) {
241 $typesByName[$type] = $page->getName()->text();
245 // Second pass to sort by name
246 asort( $typesByName );
248 // Always put "All public logs" on top
249 $public = $typesByName[''];
250 unset( $typesByName[''] );
251 $typesByName = [ '' => $public ] +
$typesByName;
254 'class' => 'HTMLSelectField',
256 'options' => array_flip( $typesByName ),
257 'default' => $queryType,
262 * @param string $user
263 * @return array Form descriptor
265 private function getUserInputDesc( $user ) {
267 'class' => 'HTMLUserTextField',
268 'label-message' => 'specialloguserlabel',
274 * @param string $title
275 * @return array Form descriptor
277 private function getTitleInputDesc( $title ) {
279 'class' => 'HTMLTitleTextField',
280 'label-message' => 'speciallogtitlelabel',
288 * @param bool $pattern
289 * @return array Form descriptor
291 private function getTitlePatternDesc( $pattern ) {
294 'label-message' => 'log-title-wildcard',
300 * @param array $types
301 * @return array|string Form descriptor or string with HTML
303 private function getExtraInputsDesc( $types ) {
304 if ( count( $types ) == 1 ) {
305 if ( $types[0] == 'suppress' ) {
306 $offender = $this->getRequest()->getVal( 'offender' );
307 $user = User
::newFromName( $offender, false );
308 if ( !$user ||
( $user->getId() == 0 && !IP
::isIPAddress( $offender ) ) ) {
309 $offender = ''; // Blank field if invalid
313 'label-message' => 'revdelete-offender',
314 'name' => 'offender',
315 'value' => $offender,
318 // Allow extensions to add their own extra inputs
319 // This could be an array or string. See T199495.
320 $input = ''; // Deprecated
321 $formDescriptor = [];
322 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input, &$formDescriptor ] );
324 return empty( $formDescriptor ) ?
$input : $formDescriptor;
332 * Drop down menu for selection of actions that can be used to filter the log
333 * @param array $types
334 * @param string $action
335 * @return array Form descriptor
337 private function getActionSelectorDesc( $types, $action ) {
339 $actionOptions[ 'log-action-filter-all' ] = '';
341 foreach ( $this->allowedActions
as $value ) {
342 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
343 $actionOptions[ $msgKey ] = $value;
347 'class' => 'HTMLSelectField',
349 'options-messages' => $actionOptions,
350 'default' => $action,
351 'label' => $this->msg( 'log-action-filter-' . $types[0] )->text(),
356 * Sets the action types allowed for log filtering
357 * To one action type may correspond several log_actions
358 * @param array $actions
361 public function setAllowedActions( $actions ) {
362 $this->allowedActions
= $actions;
368 public function beginLogEventsList() {
375 public function endLogEventsList() {
380 * @param stdClass $row A single row from the result set
381 * @return string Formatted HTML list item
383 public function logLine( $row ) {
384 $entry = DatabaseLogEntry
::newFromRow( $row );
385 $formatter = LogFormatter
::newFromEntry( $entry );
386 $formatter->setContext( $this->getContext() );
387 $formatter->setLinkRenderer( $this->getLinkRenderer() );
388 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
390 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
391 $entry->getTimestamp(), $this->getUser() ) );
393 $action = $formatter->getActionText();
395 if ( $this->flags
& self
::NO_ACTION_LINK
) {
398 $revert = $formatter->getActionLinks();
399 if ( $revert != '' ) {
400 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
404 $comment = $formatter->getComment();
406 // Some user can hide log items and have review links
407 $del = $this->getShowHideLinks( $row );
410 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
415 $classes = array_merge(
416 [ 'mw-logline-' . $entry->getType() ],
420 'data-mw-logid' => $entry->getId(),
421 'data-mw-logaction' => $entry->getFullType(),
423 $ret = "$del $time $action $comment $revert $tagDisplay";
425 // Let extensions add data
426 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
427 $attribs = wfArrayFilterByKey( $attribs, [ Sanitizer
::class, 'isReservedDataAttribute' ] );
428 $attribs['class'] = implode( ' ', $classes );
430 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
434 * @param stdClass $row
437 private function getShowHideLinks( $row ) {
438 // We don't want to see the links and
439 if ( $this->flags
== self
::NO_ACTION_LINK
) {
443 $user = $this->getUser();
445 // If change tag editing is available to this user, return the checkbox
446 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
450 [ 'name' => 'ids[' . $row->log_id
. ']' ]
454 // no one can hide items from the suppress log.
455 if ( $row->log_type
== 'suppress' ) {
460 // Don't show useless checkbox to people who cannot hide log entries
461 if ( $user->isAllowed( 'deletedhistory' ) ) {
462 $canHide = $user->isAllowed( 'deletelogentry' );
463 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
464 !$user->isAllowed( 'suppressrevision' );
465 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
466 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
467 if ( $row->log_deleted ||
$canHide ) {
468 // Show checkboxes instead of links.
469 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
470 // If event was hidden from sysops
471 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
472 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
477 [ 'name' => 'ids[' . $row->log_id
. ']' ]
481 // If event was hidden from sysops
482 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
483 $del = Linker
::revDeleteLinkDisabled( $canHide );
486 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
488 'ids' => $row->log_id
,
490 $del = Linker
::revDeleteLink(
493 $canHide && !$canViewThisSuppressedEntry
504 * @param stdClass $row
505 * @param string|array $type
506 * @param string|array $action
507 * @param string $right
510 public static function typeAction( $row, $type, $action, $right = '' ) {
511 $match = is_array( $type ) ?
512 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
514 $match = is_array( $action ) ?
515 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
516 if ( $match && $right ) {
518 $match = $wgUser->isAllowed( $right );
526 * Determine if the current user is allowed to view a particular
527 * field of this log row, if it's marked as deleted.
529 * @param stdClass $row
531 * @param User|null $user User to check, or null to use $wgUser
534 public static function userCan( $row, $field, User
$user = null ) {
535 return self
::userCanBitfield( $row->log_deleted
, $field, $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 $user->isAllowedAny( ...$permissions );
566 * @param stdClass $row
567 * @param int $field One of DELETED_* bitfield constants
570 public static function isDeleted( $row, $field ) {
571 return ( $row->log_deleted
& $field ) == $field;
575 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
577 * @param OutputPage|string &$out
578 * @param string|array $types Log types to show
579 * @param string|Title $page The page title to show log entries for
580 * @param string $user The user who made the log entries
581 * @param array $param Associative Array with the following additional options:
582 * - lim Integer Limit of items to show, default is 50
583 * - conds Array Extra conditions for the query
584 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
585 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
586 * if set to true (default), "No matching items in log" is displayed if loglist is empty
587 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
588 * First element is the message key, additional optional elements are parameters for the key
589 * that are processed with wfMessage
590 * - offset Set to overwrite offset parameter in WebRequest
591 * set to '' to unset offset
592 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
593 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
594 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
595 * - useMaster boolean Use master DB
596 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
597 * @return int Number of total log items (not limited by $lim)
599 public static function showLogExtract(
600 &$out, $types = [], $page = '', $user = '', $param = []
602 $defaultParameters = [
605 'showIfEmpty' => true,
609 'useRequestParams' => false,
610 'useMaster' => false,
611 'extraUrlParams' => false,
613 # The + operator appends elements of remaining keys from the right
614 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
615 $param +
= $defaultParameters;
616 # Convert $param array to individual variables
617 $lim = $param['lim'];
618 $conds = $param['conds'];
619 $showIfEmpty = $param['showIfEmpty'];
620 $msgKey = $param['msgKey'];
621 $wrap = $param['wrap'];
622 $flags = $param['flags'];
623 $extraUrlParams = $param['extraUrlParams'];
625 $useRequestParams = $param['useRequestParams'];
626 if ( !is_array( $msgKey ) ) {
627 $msgKey = [ $msgKey ];
630 if ( $out instanceof OutputPage
) {
631 $context = $out->getContext();
633 $context = RequestContext
::getMain();
636 // FIXME: Figure out how to inject this
637 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
639 # Insert list of top 50 (or top $lim) items
640 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
641 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
642 if ( !$useRequestParams ) {
643 # Reset vars that may have been taken from the request
645 $pager->mDefaultLimit
= 50;
646 $pager->mOffset
= "";
647 $pager->mIsBackwards
= false;
650 if ( $param['useMaster'] ) {
651 $pager->mDb
= wfGetDB( DB_MASTER
);
653 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
654 $pager->setOffset( $param['offset'] );
658 $pager->mLimit
= $lim;
660 // Fetch the log rows and build the HTML if needed
661 $logBody = $pager->getBody();
662 $numRows = $pager->getNumRows();
668 $dir = $context->getLanguage()->getDir();
669 $lang = $context->getLanguage()->getHtmlCode();
671 $s = Xml
::openElement( 'div', [
672 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
677 if ( count( $msgKey ) == 1 ) {
678 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
679 } else { // Process additional arguments
681 array_shift( $args );
682 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
685 $s .= $loglist->beginLogEventsList() .
687 $loglist->endLogEventsList();
688 } elseif ( $showIfEmpty ) {
689 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
690 $context->msg( 'logempty' )->parse() );
693 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
695 if ( $page instanceof Title
) {
696 $urlParam['page'] = $page->getPrefixedDBkey();
697 } elseif ( $page != '' ) {
698 $urlParam['page'] = $page;
702 $urlParam['user'] = $user;
705 if ( !is_array( $types ) ) { # Make it an array, if it isn't
709 # If there is exactly one log type, we can link to Special:Log?type=foo
710 if ( count( $types ) == 1 ) {
711 $urlParam['type'] = $types[0];
714 if ( $extraUrlParams !== false ) {
715 $urlParam = array_merge( $urlParam, $extraUrlParams );
718 $s .= $linkRenderer->makeKnownLink(
719 SpecialPage
::getTitleFor( 'Log' ),
720 $context->msg( 'log-fulllog' )->text(),
726 if ( $logBody && $msgKey[0] ) {
730 if ( $wrap != '' ) { // Wrap message in html
731 $s = str_replace( '$1', $s, $wrap );
734 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
735 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
736 // $out can be either an OutputPage object or a String-by-reference
737 if ( $out instanceof OutputPage
) {
748 * SQL clause to skip forbidden log types for this user
750 * @param IDatabase $db
751 * @param string $audience Public/user
752 * @param User|null $user User to check, or null to use $wgUser
753 * @return string|bool String on success, false on failure.
755 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
756 global $wgLogRestrictions;
758 if ( $audience != 'public' && $user === null ) {
763 // Reset the array, clears extra "where" clauses when $par is used
766 // Don't show private logs to unprivileged users
767 foreach ( $wgLogRestrictions as $logType => $right ) {
768 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
769 $hiddenLogs[] = $logType;
772 if ( count( $hiddenLogs ) == 1 ) {
773 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
774 } elseif ( $hiddenLogs ) {
775 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';