3 * Contain classes to list log entries
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz
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\MediaWikiServices
;
27 use Wikimedia\Rdbms\IDatabase
;
29 class LogEventsList
extends ContextSource
{
30 const NO_ACTION_LINK
= 1;
31 const NO_EXTRA_USER_LINKS
= 2;
32 const USE_CHECKBOXES
= 4;
39 protected $mDefaultQuery;
44 protected $showTagEditUI;
49 protected $allowedActions = null;
53 * The first two parameters used to be $skin and $out, but now only a context
54 * is needed, that's why there's a second unused parameter.
56 * @param IContextSource|Skin $context Context to use; formerly it was
57 * a Skin object. Use of Skin is deprecated.
58 * @param null $unused Unused; used to be an OutputPage object.
59 * @param int $flags Can be a combination of self::NO_ACTION_LINK,
60 * self::NO_EXTRA_USER_LINKS or self::USE_CHECKBOXES.
62 public function __construct( $context, $unused = null, $flags = 0 ) {
63 if ( $context instanceof IContextSource
) {
64 $this->setContext( $context );
66 // Old parameters, $context should be a Skin object
67 $this->setContext( $context->getContext() );
70 $this->flags
= $flags;
71 $this->showTagEditUI
= ChangeTags
::showTagEditingUI( $this->getUser() );
75 * Show options for the log list
77 * @param array|string $types
80 * @param string $pattern
81 * @param int $year Year
82 * @param int $month Month
83 * @param array $filter
84 * @param string $tagFilter Tag to select by default
85 * @param string $action
87 public function showOptions( $types = [], $user = '', $page = '', $pattern = '', $year = 0,
88 $month = 0, $filter = null, $tagFilter = '', $action = null
90 global $wgScript, $wgMiserMode;
92 $title = SpecialPage
::getTitleFor( 'Log' );
94 // For B/C, we take strings, but make sure they are converted...
95 $types = ( $types === '' ) ?
[] : (array)$types;
97 $tagSelector = ChangeTags
::buildTagFilterSelector( $tagFilter, false, $this->getContext() );
99 $html = Html
::hidden( 'title', $title->getPrefixedDBkey() );
102 $html .= $this->getTypeMenu( $types ) . "\n";
103 $html .= $this->getUserInput( $user ) . "\n";
104 $html .= $this->getTitleInput( $page ) . "\n";
105 $html .= $this->getExtraInputs( $types ) . "\n";
107 // Title pattern, if allowed
108 if ( !$wgMiserMode ) {
109 $html .= $this->getTitlePattern( $pattern ) . "\n";
113 $html .= Xml
::tags( 'p', null, Xml
::dateMenu( (int)$year, (int)$month ) );
116 if ( $tagSelector ) {
117 $html .= Xml
::tags( 'p', null, implode( ' ', $tagSelector ) );
122 $html .= Xml
::tags( 'p', null, $this->getFilterLinks( $filter ) );
126 if ( $action !== null ) {
127 $html .= Xml
::tags( 'p', null, $this->getActionSelector( $types, $action ) );
131 $html .= Xml
::submitButton( $this->msg( 'logeventslist-submit' )->text() );
134 $html = Xml
::fieldset( $this->msg( 'log' )->text(), $html );
137 $html = Xml
::tags( 'form', [ 'action' => $wgScript, 'method' => 'get' ], $html );
139 $this->getOutput()->addHTML( $html );
143 * @param array $filter
144 * @return string Formatted HTML
146 private function getFilterLinks( $filter ) {
148 $messages = [ $this->msg( 'show' )->text(), $this->msg( 'hide' )->text() ];
149 // Option value -> message mapping
151 $hiddens = ''; // keep track for "go" button
152 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
153 foreach ( $filter as $type => $val ) {
154 // Should the below assignment be outside the foreach?
155 // Then it would have to be copied. Not certain what is more expensive.
156 $query = $this->getDefaultQuery();
157 $queryKey = "hide_{$type}_log";
159 $hideVal = 1 - intval( $val );
160 $query[$queryKey] = $hideVal;
162 $link = $linkRenderer->makeKnownLink(
169 // Message: log-show-hide-patrol
170 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
171 $hiddens .= Html
::hidden( "hide_{$type}_log", $val ) . "\n";
175 return '<small>' . $this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
178 private function getDefaultQuery() {
179 if ( !isset( $this->mDefaultQuery
) ) {
180 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
181 unset( $this->mDefaultQuery
['title'] );
182 unset( $this->mDefaultQuery
['dir'] );
183 unset( $this->mDefaultQuery
['offset'] );
184 unset( $this->mDefaultQuery
['limit'] );
185 unset( $this->mDefaultQuery
['order'] );
186 unset( $this->mDefaultQuery
['month'] );
187 unset( $this->mDefaultQuery
['year'] );
190 return $this->mDefaultQuery
;
194 * @param array $queryTypes
195 * @return string Formatted HTML
197 private function getTypeMenu( $queryTypes ) {
198 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
199 $selector = $this->getTypeSelector();
200 $selector->setDefault( $queryType );
202 return $selector->getHTML();
206 * Returns log page selector.
210 public function getTypeSelector() {
211 $typesByName = []; // Temporary array
212 // First pass to load the log names
213 foreach ( LogPage
::validTypes() as $type ) {
214 $page = new LogPage( $type );
215 $restriction = $page->getRestriction();
216 if ( $this->getUser()->isAllowed( $restriction ) ) {
217 $typesByName[$type] = $page->getName()->text();
221 // Second pass to sort by name
222 asort( $typesByName );
224 // Always put "All public logs" on top
225 $public = $typesByName[''];
226 unset( $typesByName[''] );
227 $typesByName = [ '' => $public ] +
$typesByName;
229 $select = new XmlSelect( 'type' );
230 foreach ( $typesByName as $type => $name ) {
231 $select->addOption( $name, $type );
238 * @param string $user
239 * @return string Formatted HTML
241 private function getUserInput( $user ) {
242 $label = Xml
::inputLabel(
243 $this->msg( 'specialloguserlabel' )->text(),
248 [ 'class' => 'mw-autocomplete-user' ]
251 return '<span class="mw-input-with-label">' . $label . '</span>';
255 * @param string $title
256 * @return string Formatted HTML
258 private function getTitleInput( $title ) {
259 $label = Xml
::inputLabel(
260 $this->msg( 'speciallogtitlelabel' )->text(),
267 return '<span class="mw-input-with-label">' . $label . '</span>';
271 * @param string $pattern
272 * @return string Checkbox
274 private function getTitlePattern( $pattern ) {
275 return '<span class="mw-input-with-label">' .
276 Xml
::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
281 * @param array $types
284 private function getExtraInputs( $types ) {
285 if ( count( $types ) == 1 ) {
286 if ( $types[0] == 'suppress' ) {
287 $offender = $this->getRequest()->getVal( 'offender' );
288 $user = User
::newFromName( $offender, false );
289 if ( !$user ||
( $user->getId() == 0 && !IP
::isIPAddress( $offender ) ) ) {
290 $offender = ''; // Blank field if invalid
292 return Xml
::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
293 'mw-log-offender', 20, $offender );
295 // Allow extensions to add their own extra inputs
297 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input ] );
306 * Drop down menu for selection of actions that can be used to filter the log
307 * @param array $types
308 * @param string $action
312 private function getActionSelector( $types, $action ) {
313 if ( $this->allowedActions
=== null ||
!count( $this->allowedActions
) ) {
317 $html .= Xml
::label( wfMessage( 'log-action-filter-' . $types[0] )->text(),
318 'action-filter-' .$types[0] ) . "\n";
319 $select = new XmlSelect( 'subtype' );
320 $select->addOption( wfMessage( 'log-action-filter-all' )->text(), '' );
321 foreach ( $this->allowedActions
as $value ) {
322 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
323 $select->addOption( wfMessage( $msgKey )->text(), $value );
325 $select->setDefault( $action );
326 $html .= $select->getHTML();
331 * Sets the action types allowed for log filtering
332 * To one action type may correspond several log_actions
333 * @param array $actions
336 public function setAllowedActions( $actions ) {
337 $this->allowedActions
= $actions;
343 public function beginLogEventsList() {
350 public function endLogEventsList() {
355 * @param stdClass $row A single row from the result set
356 * @return string Formatted HTML list item
358 public function logLine( $row ) {
359 $entry = DatabaseLogEntry
::newFromRow( $row );
360 $formatter = LogFormatter
::newFromEntry( $entry );
361 $formatter->setContext( $this->getContext() );
362 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
364 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
365 $entry->getTimestamp(), $this->getUser() ) );
367 $action = $formatter->getActionText();
369 if ( $this->flags
& self
::NO_ACTION_LINK
) {
372 $revert = $formatter->getActionLinks();
373 if ( $revert != '' ) {
374 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
378 $comment = $formatter->getComment();
380 // Some user can hide log items and have review links
381 $del = $this->getShowHideLinks( $row );
384 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
389 $classes = array_merge(
390 [ 'mw-logline-' . $entry->getType() ],
394 'data-mw-logid' => $entry->getId(),
395 'data-mw-logaction' => $entry->getFullType(),
397 $ret = "$del $time $action $comment $revert $tagDisplay";
399 // Let extensions add data
400 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
401 $attribs = wfArrayFilterByKey( $attribs, [ Sanitizer
::class, 'isReservedDataAttribute' ] );
402 $attribs['class'] = implode( ' ', $classes );
404 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
408 * @param stdClass $row Row
411 private function getShowHideLinks( $row ) {
412 // We don't want to see the links and
413 if ( $this->flags
== self
::NO_ACTION_LINK
) {
417 $user = $this->getUser();
419 // If change tag editing is available to this user, return the checkbox
420 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
424 [ 'name' => 'ids[' . $row->log_id
. ']' ]
428 // no one can hide items from the suppress log.
429 if ( $row->log_type
== 'suppress' ) {
434 // Don't show useless checkbox to people who cannot hide log entries
435 if ( $user->isAllowed( 'deletedhistory' ) ) {
436 $canHide = $user->isAllowed( 'deletelogentry' );
437 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
438 !$user->isAllowed( 'suppressrevision' );
439 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
440 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
441 if ( $row->log_deleted ||
$canHide ) {
442 // Show checkboxes instead of links.
443 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
444 // If event was hidden from sysops
445 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
446 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
451 [ 'name' => 'ids[' . $row->log_id
. ']' ]
455 // If event was hidden from sysops
456 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
457 $del = Linker
::revDeleteLinkDisabled( $canHide );
460 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
462 'ids' => $row->log_id
,
464 $del = Linker
::revDeleteLink(
467 $canHide && !$canViewThisSuppressedEntry
478 * @param stdClass $row Row
479 * @param string|array $type
480 * @param string|array $action
481 * @param string $right
484 public static function typeAction( $row, $type, $action, $right = '' ) {
485 $match = is_array( $type ) ?
486 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
488 $match = is_array( $action ) ?
489 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
490 if ( $match && $right ) {
492 $match = $wgUser->isAllowed( $right );
500 * Determine if the current user is allowed to view a particular
501 * field of this log row, if it's marked as deleted.
503 * @param stdClass $row Row
505 * @param User $user User to check, or null to use $wgUser
508 public static function userCan( $row, $field, User
$user = null ) {
509 return self
::userCanBitfield( $row->log_deleted
, $field, $user );
513 * Determine if the current user is allowed to view a particular
514 * field of this log row, if it's marked as deleted.
516 * @param int $bitfield Current field
518 * @param User $user User to check, or null to use $wgUser
521 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
522 if ( $bitfield & $field ) {
523 if ( $user === null ) {
527 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
528 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
530 $permissions = [ 'deletedhistory' ];
532 $permissionlist = implode( ', ', $permissions );
533 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
534 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
540 * @param stdClass $row Row
541 * @param int $field One of DELETED_* bitfield constants
544 public static function isDeleted( $row, $field ) {
545 return ( $row->log_deleted
& $field ) == $field;
549 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
551 * @param OutputPage|string $out By-reference
552 * @param string|array $types Log types to show
553 * @param string|Title $page The page title to show log entries for
554 * @param string $user The user who made the log entries
555 * @param array $param Associative Array with the following additional options:
556 * - lim Integer Limit of items to show, default is 50
557 * - conds Array Extra conditions for the query
558 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
559 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
560 * if set to true (default), "No matching items in log" is displayed if loglist is empty
561 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
562 * First element is the message key, additional optional elements are parameters for the key
563 * that are processed with wfMessage
564 * - offset Set to overwrite offset parameter in WebRequest
565 * set to '' to unset offset
566 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
567 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
568 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
569 * - useMaster boolean Use master DB
570 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
571 * @return int Number of total log items (not limited by $lim)
573 public static function showLogExtract(
574 &$out, $types = [], $page = '', $user = '', $param = []
576 $defaultParameters = [
579 'showIfEmpty' => true,
583 'useRequestParams' => false,
584 'useMaster' => false,
585 'extraUrlParams' => false,
587 # The + operator appends elements of remaining keys from the right
588 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
589 $param +
= $defaultParameters;
590 # Convert $param array to individual variables
591 $lim = $param['lim'];
592 $conds = $param['conds'];
593 $showIfEmpty = $param['showIfEmpty'];
594 $msgKey = $param['msgKey'];
595 $wrap = $param['wrap'];
596 $flags = $param['flags'];
597 $extraUrlParams = $param['extraUrlParams'];
599 $useRequestParams = $param['useRequestParams'];
600 if ( !is_array( $msgKey ) ) {
601 $msgKey = [ $msgKey ];
604 if ( $out instanceof OutputPage
) {
605 $context = $out->getContext();
607 $context = RequestContext
::getMain();
610 # Insert list of top 50 (or top $lim) items
611 $loglist = new LogEventsList( $context, null, $flags );
612 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
613 if ( !$useRequestParams ) {
614 # Reset vars that may have been taken from the request
616 $pager->mDefaultLimit
= 50;
617 $pager->mOffset
= "";
618 $pager->mIsBackwards
= false;
621 if ( $param['useMaster'] ) {
622 $pager->mDb
= wfGetDB( DB_MASTER
);
624 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
625 $pager->setOffset( $param['offset'] );
629 $pager->mLimit
= $lim;
631 // Fetch the log rows and build the HTML if needed
632 $logBody = $pager->getBody();
633 $numRows = $pager->getNumRows();
639 $dir = $context->getLanguage()->getDir();
640 $lang = $context->getLanguage()->getHtmlCode();
642 $s = Xml
::openElement( 'div', [
643 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
648 if ( count( $msgKey ) == 1 ) {
649 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
650 } else { // Process additional arguments
652 array_shift( $args );
653 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
656 $s .= $loglist->beginLogEventsList() .
658 $loglist->endLogEventsList();
659 } elseif ( $showIfEmpty ) {
660 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
661 $context->msg( 'logempty' )->parse() );
664 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
666 if ( $page instanceof Title
) {
667 $urlParam['page'] = $page->getPrefixedDBkey();
668 } elseif ( $page != '' ) {
669 $urlParam['page'] = $page;
673 $urlParam['user'] = $user;
676 if ( !is_array( $types ) ) { # Make it an array, if it isn't
680 # If there is exactly one log type, we can link to Special:Log?type=foo
681 if ( count( $types ) == 1 ) {
682 $urlParam['type'] = $types[0];
685 if ( $extraUrlParams !== false ) {
686 $urlParam = array_merge( $urlParam, $extraUrlParams );
689 $s .= MediaWikiServices
::getInstance()->getLinkRenderer()->makeKnownLink(
690 SpecialPage
::getTitleFor( 'Log' ),
691 $context->msg( 'log-fulllog' )->text(),
697 if ( $logBody && $msgKey[0] ) {
701 if ( $wrap != '' ) { // Wrap message in html
702 $s = str_replace( '$1', $s, $wrap );
705 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
706 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
707 // $out can be either an OutputPage object or a String-by-reference
708 if ( $out instanceof OutputPage
) {
719 * SQL clause to skip forbidden log types for this user
721 * @param IDatabase $db
722 * @param string $audience Public/user
723 * @param User $user User to check, or null to use $wgUser
724 * @return string|bool String on success, false on failure.
726 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
727 global $wgLogRestrictions;
729 if ( $audience != 'public' && $user === null ) {
734 // Reset the array, clears extra "where" clauses when $par is used
737 // Don't show private logs to unprivileged users
738 foreach ( $wgLogRestrictions as $logType => $right ) {
739 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
740 $hiddenLogs[] = $logType;
743 if ( count( $hiddenLogs ) == 1 ) {
744 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
745 } elseif ( $hiddenLogs ) {
746 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';