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 string $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 array $filter
105 * @param string $tagFilter Tag to select by default
106 * @param string $action
108 public function showOptions( $types = [], $user = '', $page = '', $pattern = '', $year = 0,
109 $month = 0, $filter = null, $tagFilter = '', $action = null
111 global $wgScript, $wgMiserMode;
113 $title = SpecialPage
::getTitleFor( 'Log' );
115 // For B/C, we take strings, but make sure they are converted...
116 $types = ( $types === '' ) ?
[] : (array)$types;
118 $tagSelector = ChangeTags
::buildTagFilterSelector( $tagFilter, false, $this->getContext() );
120 $html = Html
::hidden( 'title', $title->getPrefixedDBkey() );
123 $html .= $this->getTypeMenu( $types ) . "\n";
124 $html .= $this->getUserInput( $user ) . "\n";
125 $html .= $this->getTitleInput( $page ) . "\n";
126 $html .= $this->getExtraInputs( $types ) . "\n";
128 // Title pattern, if allowed
129 if ( !$wgMiserMode ) {
130 $html .= $this->getTitlePattern( $pattern ) . "\n";
134 $html .= Xml
::tags( 'p', null, Xml
::dateMenu( (int)$year, (int)$month ) );
137 if ( $tagSelector ) {
138 $html .= Xml
::tags( 'p', null, implode( ' ', $tagSelector ) );
143 $html .= Xml
::tags( 'p', null, $this->getFilterLinks( $filter ) );
147 if ( $action !== null ) {
148 $html .= Xml
::tags( 'p', null, $this->getActionSelector( $types, $action ) );
152 $html .= Xml
::submitButton( $this->msg( 'logeventslist-submit' )->text() );
155 $html = Xml
::fieldset( $this->msg( 'log' )->text(), $html );
158 $html = Xml
::tags( 'form', [ 'action' => $wgScript, 'method' => 'get' ], $html );
160 $this->getOutput()->addHTML( $html );
164 * @param array $filter
165 * @return string Formatted HTML
167 private function getFilterLinks( $filter ) {
169 $messages = [ $this->msg( 'show' )->text(), $this->msg( 'hide' )->text() ];
170 // Option value -> message mapping
172 $hiddens = ''; // keep track for "go" button
173 $linkRenderer = $this->getLinkRenderer();
174 foreach ( $filter as $type => $val ) {
175 // Should the below assignment be outside the foreach?
176 // Then it would have to be copied. Not certain what is more expensive.
177 $query = $this->getDefaultQuery();
178 $queryKey = "hide_{$type}_log";
180 $hideVal = 1 - intval( $val );
181 $query[$queryKey] = $hideVal;
183 $link = $linkRenderer->makeKnownLink(
190 // Message: log-show-hide-patrol
191 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
192 $hiddens .= Html
::hidden( "hide_{$type}_log", $val ) . "\n";
196 return '<small>' . $this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
199 private function getDefaultQuery() {
200 if ( !isset( $this->mDefaultQuery
) ) {
201 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
202 unset( $this->mDefaultQuery
['title'] );
203 unset( $this->mDefaultQuery
['dir'] );
204 unset( $this->mDefaultQuery
['offset'] );
205 unset( $this->mDefaultQuery
['limit'] );
206 unset( $this->mDefaultQuery
['order'] );
207 unset( $this->mDefaultQuery
['month'] );
208 unset( $this->mDefaultQuery
['year'] );
211 return $this->mDefaultQuery
;
215 * @param array $queryTypes
216 * @return string Formatted HTML
218 private function getTypeMenu( $queryTypes ) {
219 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
220 $selector = $this->getTypeSelector();
221 $selector->setDefault( $queryType );
223 return $selector->getHTML();
227 * Returns log page selector.
231 public function getTypeSelector() {
232 $typesByName = []; // Temporary array
233 // First pass to load the log names
234 foreach ( LogPage
::validTypes() as $type ) {
235 $page = new LogPage( $type );
236 $restriction = $page->getRestriction();
237 if ( $this->getUser()->isAllowed( $restriction ) ) {
238 $typesByName[$type] = $page->getName()->text();
242 // Second pass to sort by name
243 asort( $typesByName );
245 // Always put "All public logs" on top
246 $public = $typesByName[''];
247 unset( $typesByName[''] );
248 $typesByName = [ '' => $public ] +
$typesByName;
250 $select = new XmlSelect( 'type' );
251 foreach ( $typesByName as $type => $name ) {
252 $select->addOption( $name, $type );
259 * @param string $user
260 * @return string Formatted HTML
262 private function getUserInput( $user ) {
263 $label = Xml
::inputLabel(
264 $this->msg( 'specialloguserlabel' )->text(),
269 [ 'class' => 'mw-autocomplete-user' ]
272 return '<span class="mw-input-with-label">' . $label . '</span>';
276 * @param string $title
277 * @return string Formatted HTML
279 private function getTitleInput( $title ) {
280 $label = Xml
::inputLabel(
281 $this->msg( 'speciallogtitlelabel' )->text(),
288 return '<span class="mw-input-with-label">' . $label . '</span>';
292 * @param string $pattern
293 * @return string Checkbox
295 private function getTitlePattern( $pattern ) {
296 return '<span class="mw-input-with-label">' .
297 Xml
::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
302 * @param array $types
305 private function getExtraInputs( $types ) {
306 if ( count( $types ) == 1 ) {
307 if ( $types[0] == 'suppress' ) {
308 $offender = $this->getRequest()->getVal( 'offender' );
309 $user = User
::newFromName( $offender, false );
310 if ( !$user ||
( $user->getId() == 0 && !IP
::isIPAddress( $offender ) ) ) {
311 $offender = ''; // Blank field if invalid
313 return Xml
::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
314 'mw-log-offender', 20, $offender );
316 // Allow extensions to add their own extra inputs
318 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input ] );
327 * Drop down menu for selection of actions that can be used to filter the log
328 * @param array $types
329 * @param string $action
333 private function getActionSelector( $types, $action ) {
334 if ( $this->allowedActions
=== null ||
!count( $this->allowedActions
) ) {
338 $html .= Xml
::label( wfMessage( 'log-action-filter-' . $types[0] )->text(),
339 'action-filter-' .$types[0] ) . "\n";
340 $select = new XmlSelect( 'subtype' );
341 $select->addOption( wfMessage( 'log-action-filter-all' )->text(), '' );
342 foreach ( $this->allowedActions
as $value ) {
343 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
344 $select->addOption( wfMessage( $msgKey )->text(), $value );
346 $select->setDefault( $action );
347 $html .= $select->getHTML();
352 * Sets the action types allowed for log filtering
353 * To one action type may correspond several log_actions
354 * @param array $actions
357 public function setAllowedActions( $actions ) {
358 $this->allowedActions
= $actions;
364 public function beginLogEventsList() {
371 public function endLogEventsList() {
376 * @param stdClass $row A single row from the result set
377 * @return string Formatted HTML list item
379 public function logLine( $row ) {
380 $entry = DatabaseLogEntry
::newFromRow( $row );
381 $formatter = LogFormatter
::newFromEntry( $entry );
382 $formatter->setContext( $this->getContext() );
383 $formatter->setLinkRenderer( $this->getLinkRenderer() );
384 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
386 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
387 $entry->getTimestamp(), $this->getUser() ) );
389 $action = $formatter->getActionText();
391 if ( $this->flags
& self
::NO_ACTION_LINK
) {
394 $revert = $formatter->getActionLinks();
395 if ( $revert != '' ) {
396 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
400 $comment = $formatter->getComment();
402 // Some user can hide log items and have review links
403 $del = $this->getShowHideLinks( $row );
406 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
411 $classes = array_merge(
412 [ 'mw-logline-' . $entry->getType() ],
416 'data-mw-logid' => $entry->getId(),
417 'data-mw-logaction' => $entry->getFullType(),
419 $ret = "$del $time $action $comment $revert $tagDisplay";
421 // Let extensions add data
422 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
423 $attribs = wfArrayFilterByKey( $attribs, [ 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 // Don't show useless checkbox to people who cannot hide log entries
457 if ( $user->isAllowed( 'deletedhistory' ) ) {
458 $canHide = $user->isAllowed( 'deletelogentry' );
459 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
460 !$user->isAllowed( 'suppressrevision' );
461 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
462 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
463 if ( $row->log_deleted ||
$canHide ) {
464 // Show checkboxes instead of links.
465 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
466 // If event was hidden from sysops
467 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
468 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
473 [ 'name' => 'ids[' . $row->log_id
. ']' ]
477 // If event was hidden from sysops
478 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
479 $del = Linker
::revDeleteLinkDisabled( $canHide );
482 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
484 'ids' => $row->log_id
,
486 $del = Linker
::revDeleteLink(
489 $canHide && !$canViewThisSuppressedEntry
500 * @param stdClass $row
501 * @param string|array $type
502 * @param string|array $action
503 * @param string $right
506 public static function typeAction( $row, $type, $action, $right = '' ) {
507 $match = is_array( $type ) ?
508 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
510 $match = is_array( $action ) ?
511 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
512 if ( $match && $right ) {
514 $match = $wgUser->isAllowed( $right );
522 * Determine if the current user is allowed to view a particular
523 * field of this log row, if it's marked as deleted and/or restricted log type.
525 * @param stdClass $row
527 * @param User $user User to check, or null to use $wgUser
530 public static function userCan( $row, $field, User
$user = null ) {
531 return self
::userCanBitfield( $row->log_deleted
, $field, $user ) &&
532 self
::userCanViewLogType( $row->log_type
, $user );
536 * Determine if the current user is allowed to view a particular
537 * field of this log row, if it's marked as deleted.
539 * @param int $bitfield Current field
541 * @param User $user User to check, or null to use $wgUser
544 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
545 if ( $bitfield & $field ) {
546 if ( $user === null ) {
550 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
551 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
553 $permissions = [ 'deletedhistory' ];
555 $permissionlist = implode( ', ', $permissions );
556 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
557 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
563 * Determine if the current user is allowed to view a particular
564 * field of this log row, if it's marked as restricted log type.
566 * @param stdClass $type
567 * @param User|null $user User to check, or null to use $wgUser
570 public static function userCanViewLogType( $type, User
$user = null ) {
571 if ( $user === null ) {
575 $logRestrictions = MediaWikiServices
::getInstance()->getMainConfig()->get( 'LogRestrictions' );
576 if ( isset( $logRestrictions[$type] ) && !$user->isAllowed( $logRestrictions[$type] ) ) {
583 * @param stdClass $row
584 * @param int $field One of DELETED_* bitfield constants
587 public static function isDeleted( $row, $field ) {
588 return ( $row->log_deleted
& $field ) == $field;
592 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
594 * @param OutputPage|string &$out
595 * @param string|array $types Log types to show
596 * @param string|Title $page The page title to show log entries for
597 * @param string $user The user who made the log entries
598 * @param array $param Associative Array with the following additional options:
599 * - lim Integer Limit of items to show, default is 50
600 * - conds Array Extra conditions for the query
601 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
602 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
603 * if set to true (default), "No matching items in log" is displayed if loglist is empty
604 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
605 * First element is the message key, additional optional elements are parameters for the key
606 * that are processed with wfMessage
607 * - offset Set to overwrite offset parameter in WebRequest
608 * set to '' to unset offset
609 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
610 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
611 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
612 * - useMaster boolean Use master DB
613 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
614 * @return int Number of total log items (not limited by $lim)
616 public static function showLogExtract(
617 &$out, $types = [], $page = '', $user = '', $param = []
619 $defaultParameters = [
622 'showIfEmpty' => true,
626 'useRequestParams' => false,
627 'useMaster' => false,
628 'extraUrlParams' => false,
630 # The + operator appends elements of remaining keys from the right
631 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
632 $param +
= $defaultParameters;
633 # Convert $param array to individual variables
634 $lim = $param['lim'];
635 $conds = $param['conds'];
636 $showIfEmpty = $param['showIfEmpty'];
637 $msgKey = $param['msgKey'];
638 $wrap = $param['wrap'];
639 $flags = $param['flags'];
640 $extraUrlParams = $param['extraUrlParams'];
642 $useRequestParams = $param['useRequestParams'];
643 if ( !is_array( $msgKey ) ) {
644 $msgKey = [ $msgKey ];
647 if ( $out instanceof OutputPage
) {
648 $context = $out->getContext();
650 $context = RequestContext
::getMain();
653 // FIXME: Figure out how to inject this
654 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
656 # Insert list of top 50 (or top $lim) items
657 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
658 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
659 if ( !$useRequestParams ) {
660 # Reset vars that may have been taken from the request
662 $pager->mDefaultLimit
= 50;
663 $pager->mOffset
= "";
664 $pager->mIsBackwards
= false;
667 if ( $param['useMaster'] ) {
668 $pager->mDb
= wfGetDB( DB_MASTER
);
670 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
671 $pager->setOffset( $param['offset'] );
675 $pager->mLimit
= $lim;
677 // Fetch the log rows and build the HTML if needed
678 $logBody = $pager->getBody();
679 $numRows = $pager->getNumRows();
685 $dir = $context->getLanguage()->getDir();
686 $lang = $context->getLanguage()->getHtmlCode();
688 $s = Xml
::openElement( 'div', [
689 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
694 if ( count( $msgKey ) == 1 ) {
695 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
696 } else { // Process additional arguments
698 array_shift( $args );
699 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
702 $s .= $loglist->beginLogEventsList() .
704 $loglist->endLogEventsList();
705 } elseif ( $showIfEmpty ) {
706 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
707 $context->msg( 'logempty' )->parse() );
710 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
712 if ( $page instanceof Title
) {
713 $urlParam['page'] = $page->getPrefixedDBkey();
714 } elseif ( $page != '' ) {
715 $urlParam['page'] = $page;
719 $urlParam['user'] = $user;
722 if ( !is_array( $types ) ) { # Make it an array, if it isn't
726 # If there is exactly one log type, we can link to Special:Log?type=foo
727 if ( count( $types ) == 1 ) {
728 $urlParam['type'] = $types[0];
731 if ( $extraUrlParams !== false ) {
732 $urlParam = array_merge( $urlParam, $extraUrlParams );
735 $s .= $linkRenderer->makeKnownLink(
736 SpecialPage
::getTitleFor( 'Log' ),
737 $context->msg( 'log-fulllog' )->text(),
743 if ( $logBody && $msgKey[0] ) {
747 if ( $wrap != '' ) { // Wrap message in html
748 $s = str_replace( '$1', $s, $wrap );
751 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
752 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
753 // $out can be either an OutputPage object or a String-by-reference
754 if ( $out instanceof OutputPage
) {
765 * SQL clause to skip forbidden log types for this user
767 * @param IDatabase $db
768 * @param string $audience Public/user
769 * @param User $user User to check, or null to use $wgUser
770 * @return string|bool String on success, false on failure.
772 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
773 global $wgLogRestrictions;
775 if ( $audience != 'public' && $user === null ) {
780 // Reset the array, clears extra "where" clauses when $par is used
783 // Don't show private logs to unprivileged users
784 foreach ( $wgLogRestrictions as $logType => $right ) {
785 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
786 $hiddenLogs[] = $logType;
789 if ( count( $hiddenLogs ) == 1 ) {
790 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
791 } elseif ( $hiddenLogs ) {
792 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';