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 $year Year
102 * @param int $month Month
103 * @param array $filter
104 * @param string $tagFilter Tag to select by default
105 * @param string $action
107 public function showOptions( $types = [], $user = '', $page = '', $pattern = '', $year = 0,
108 $month = 0, $filter = null, $tagFilter = '', $action = null
110 global $wgScript, $wgMiserMode;
112 $title = SpecialPage
::getTitleFor( 'Log' );
114 // For B/C, we take strings, but make sure they are converted...
115 $types = ( $types === '' ) ?
[] : (array)$types;
117 $tagSelector = ChangeTags
::buildTagFilterSelector( $tagFilter, false, $this->getContext() );
119 $html = Html
::hidden( 'title', $title->getPrefixedDBkey() );
122 $html .= $this->getTypeMenu( $types ) . "\n";
123 $html .= $this->getUserInput( $user ) . "\n";
124 $html .= $this->getTitleInput( $page ) . "\n";
125 $html .= $this->getExtraInputs( $types ) . "\n";
127 // Title pattern, if allowed
128 if ( !$wgMiserMode ) {
129 $html .= $this->getTitlePattern( $pattern ) . "\n";
133 $html .= Xml
::tags( 'p', null, Xml
::dateMenu( (int)$year, (int)$month ) );
136 if ( $tagSelector ) {
137 $html .= Xml
::tags( 'p', null, implode( ' ', $tagSelector ) );
142 $html .= Xml
::tags( 'p', null, $this->getFilterLinks( $filter ) );
146 if ( $action !== null ) {
147 $html .= Xml
::tags( 'p', null, $this->getActionSelector( $types, $action ) );
151 $html .= Xml
::submitButton( $this->msg( 'logeventslist-submit' )->text() );
154 $html = Xml
::fieldset( $this->msg( 'log' )->text(), $html );
157 $html = Xml
::tags( 'form', [ 'action' => $wgScript, 'method' => 'get' ], $html );
159 $this->getOutput()->addHTML( $html );
163 * @param array $filter
164 * @return string Formatted HTML
166 private function getFilterLinks( $filter ) {
168 $messages = [ $this->msg( 'show' )->text(), $this->msg( 'hide' )->text() ];
169 // Option value -> message mapping
171 $hiddens = ''; // keep track for "go" button
172 $linkRenderer = $this->getLinkRenderer();
173 foreach ( $filter as $type => $val ) {
174 // Should the below assignment be outside the foreach?
175 // Then it would have to be copied. Not certain what is more expensive.
176 $query = $this->getDefaultQuery();
177 $queryKey = "hide_{$type}_log";
179 $hideVal = 1 - intval( $val );
180 $query[$queryKey] = $hideVal;
182 $link = $linkRenderer->makeKnownLink(
189 // Message: log-show-hide-patrol
190 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
191 $hiddens .= Html
::hidden( "hide_{$type}_log", $val ) . "\n";
195 return '<small>' . $this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
198 private function getDefaultQuery() {
199 if ( !isset( $this->mDefaultQuery
) ) {
200 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
201 unset( $this->mDefaultQuery
['title'] );
202 unset( $this->mDefaultQuery
['dir'] );
203 unset( $this->mDefaultQuery
['offset'] );
204 unset( $this->mDefaultQuery
['limit'] );
205 unset( $this->mDefaultQuery
['order'] );
206 unset( $this->mDefaultQuery
['month'] );
207 unset( $this->mDefaultQuery
['year'] );
210 return $this->mDefaultQuery
;
214 * @param array $queryTypes
215 * @return string Formatted HTML
217 private function getTypeMenu( $queryTypes ) {
218 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
219 $selector = $this->getTypeSelector();
220 $selector->setDefault( $queryType );
222 return $selector->getHTML();
226 * Returns log page selector.
230 public function getTypeSelector() {
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 ( $this->getUser()->isAllowed( $restriction ) ) {
237 $typesByName[$type] = $page->getName()->text();
241 // Second pass to sort by name
242 asort( $typesByName );
244 // Always put "All public logs" on top
245 $public = $typesByName[''];
246 unset( $typesByName[''] );
247 $typesByName = [ '' => $public ] +
$typesByName;
249 $select = new XmlSelect( 'type' );
250 foreach ( $typesByName as $type => $name ) {
251 $select->addOption( $name, $type );
258 * @param string $user
259 * @return string Formatted HTML
261 private function getUserInput( $user ) {
262 $label = Xml
::inputLabel(
263 $this->msg( 'specialloguserlabel' )->text(),
268 [ 'class' => 'mw-autocomplete-user' ]
271 return '<span class="mw-input-with-label">' . $label . '</span>';
275 * @param string $title
276 * @return string Formatted HTML
278 private function getTitleInput( $title ) {
279 $label = Xml
::inputLabel(
280 $this->msg( 'speciallogtitlelabel' )->text(),
287 return '<span class="mw-input-with-label">' . $label . '</span>';
291 * @param string $pattern
292 * @return string Checkbox
294 private function getTitlePattern( $pattern ) {
295 return '<span class="mw-input-with-label">' .
296 Xml
::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
301 * @param array $types
304 private function getExtraInputs( $types ) {
305 if ( count( $types ) == 1 ) {
306 if ( $types[0] == 'suppress' ) {
307 $offender = $this->getRequest()->getVal( 'offender' );
308 $user = User
::newFromName( $offender, false );
309 if ( !$user ||
( $user->getId() == 0 && !IP
::isIPAddress( $offender ) ) ) {
310 $offender = ''; // Blank field if invalid
312 return Xml
::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
313 'mw-log-offender', 20, $offender );
315 // Allow extensions to add their own extra inputs
317 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input ] );
326 * Drop down menu for selection of actions that can be used to filter the log
327 * @param array $types
328 * @param string $action
332 private function getActionSelector( $types, $action ) {
333 if ( $this->allowedActions
=== null ||
!count( $this->allowedActions
) ) {
337 $html .= Xml
::label( wfMessage( 'log-action-filter-' . $types[0] )->text(),
338 'action-filter-' .$types[0] ) . "\n";
339 $select = new XmlSelect( 'subtype' );
340 $select->addOption( wfMessage( 'log-action-filter-all' )->text(), '' );
341 foreach ( $this->allowedActions
as $value ) {
342 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
343 $select->addOption( wfMessage( $msgKey )->text(), $value );
345 $select->setDefault( $action );
346 $html .= $select->getHTML();
351 * Sets the action types allowed for log filtering
352 * To one action type may correspond several log_actions
353 * @param array $actions
356 public function setAllowedActions( $actions ) {
357 $this->allowedActions
= $actions;
363 public function beginLogEventsList() {
370 public function endLogEventsList() {
375 * @param stdClass $row A single row from the result set
376 * @return string Formatted HTML list item
378 public function logLine( $row ) {
379 $entry = DatabaseLogEntry
::newFromRow( $row );
380 $formatter = LogFormatter
::newFromEntry( $entry );
381 $formatter->setContext( $this->getContext() );
382 $formatter->setLinkRenderer( $this->getLinkRenderer() );
383 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
385 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
386 $entry->getTimestamp(), $this->getUser() ) );
388 $action = $formatter->getActionText();
390 if ( $this->flags
& self
::NO_ACTION_LINK
) {
393 $revert = $formatter->getActionLinks();
394 if ( $revert != '' ) {
395 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
399 $comment = $formatter->getComment();
401 // Some user can hide log items and have review links
402 $del = $this->getShowHideLinks( $row );
405 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
410 $classes = array_merge(
411 [ 'mw-logline-' . $entry->getType() ],
415 'data-mw-logid' => $entry->getId(),
416 'data-mw-logaction' => $entry->getFullType(),
418 $ret = "$del $time $action $comment $revert $tagDisplay";
420 // Let extensions add data
421 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
422 $attribs = wfArrayFilterByKey( $attribs, [ Sanitizer
::class, 'isReservedDataAttribute' ] );
423 $attribs['class'] = implode( ' ', $classes );
425 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
429 * @param stdClass $row Row
432 private function getShowHideLinks( $row ) {
433 // We don't want to see the links and
434 if ( $this->flags
== self
::NO_ACTION_LINK
) {
438 $user = $this->getUser();
440 // If change tag editing is available to this user, return the checkbox
441 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
445 [ 'name' => 'ids[' . $row->log_id
. ']' ]
449 // no one can hide items from the suppress log.
450 if ( $row->log_type
== 'suppress' ) {
455 // Don't show useless checkbox to people who cannot hide log entries
456 if ( $user->isAllowed( 'deletedhistory' ) ) {
457 $canHide = $user->isAllowed( 'deletelogentry' );
458 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
459 !$user->isAllowed( 'suppressrevision' );
460 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
461 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
462 if ( $row->log_deleted ||
$canHide ) {
463 // Show checkboxes instead of links.
464 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
465 // If event was hidden from sysops
466 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
467 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
472 [ 'name' => 'ids[' . $row->log_id
. ']' ]
476 // If event was hidden from sysops
477 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
478 $del = Linker
::revDeleteLinkDisabled( $canHide );
481 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
483 'ids' => $row->log_id
,
485 $del = Linker
::revDeleteLink(
488 $canHide && !$canViewThisSuppressedEntry
499 * @param stdClass $row Row
500 * @param string|array $type
501 * @param string|array $action
502 * @param string $right
505 public static function typeAction( $row, $type, $action, $right = '' ) {
506 $match = is_array( $type ) ?
507 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
509 $match = is_array( $action ) ?
510 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
511 if ( $match && $right ) {
513 $match = $wgUser->isAllowed( $right );
521 * Determine if the current user is allowed to view a particular
522 * field of this log row, if it's marked as deleted.
524 * @param stdClass $row Row
526 * @param User $user User to check, or null to use $wgUser
529 public static function userCan( $row, $field, User
$user = null ) {
530 return self
::userCanBitfield( $row->log_deleted
, $field, $user );
534 * Determine if the current user is allowed to view a particular
535 * field of this log row, if it's marked as deleted.
537 * @param int $bitfield Current field
539 * @param User $user User to check, or null to use $wgUser
542 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
543 if ( $bitfield & $field ) {
544 if ( $user === null ) {
548 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
549 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
551 $permissions = [ 'deletedhistory' ];
553 $permissionlist = implode( ', ', $permissions );
554 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
555 return call_user_func_array( [ $user, 'isAllowedAny' ], $permissions );
561 * @param stdClass $row Row
562 * @param int $field One of DELETED_* bitfield constants
565 public static function isDeleted( $row, $field ) {
566 return ( $row->log_deleted
& $field ) == $field;
570 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
572 * @param OutputPage|string &$out
573 * @param string|array $types Log types to show
574 * @param string|Title $page The page title to show log entries for
575 * @param string $user The user who made the log entries
576 * @param array $param Associative Array with the following additional options:
577 * - lim Integer Limit of items to show, default is 50
578 * - conds Array Extra conditions for the query
579 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
580 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
581 * if set to true (default), "No matching items in log" is displayed if loglist is empty
582 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
583 * First element is the message key, additional optional elements are parameters for the key
584 * that are processed with wfMessage
585 * - offset Set to overwrite offset parameter in WebRequest
586 * set to '' to unset offset
587 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
588 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
589 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
590 * - useMaster boolean Use master DB
591 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
592 * @return int Number of total log items (not limited by $lim)
594 public static function showLogExtract(
595 &$out, $types = [], $page = '', $user = '', $param = []
597 $defaultParameters = [
600 'showIfEmpty' => true,
604 'useRequestParams' => false,
605 'useMaster' => false,
606 'extraUrlParams' => false,
608 # The + operator appends elements of remaining keys from the right
609 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
610 $param +
= $defaultParameters;
611 # Convert $param array to individual variables
612 $lim = $param['lim'];
613 $conds = $param['conds'];
614 $showIfEmpty = $param['showIfEmpty'];
615 $msgKey = $param['msgKey'];
616 $wrap = $param['wrap'];
617 $flags = $param['flags'];
618 $extraUrlParams = $param['extraUrlParams'];
620 $useRequestParams = $param['useRequestParams'];
621 if ( !is_array( $msgKey ) ) {
622 $msgKey = [ $msgKey ];
625 if ( $out instanceof OutputPage
) {
626 $context = $out->getContext();
628 $context = RequestContext
::getMain();
631 // FIXME: Figure out how to inject this
632 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
634 # Insert list of top 50 (or top $lim) items
635 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
636 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
637 if ( !$useRequestParams ) {
638 # Reset vars that may have been taken from the request
640 $pager->mDefaultLimit
= 50;
641 $pager->mOffset
= "";
642 $pager->mIsBackwards
= false;
645 if ( $param['useMaster'] ) {
646 $pager->mDb
= wfGetDB( DB_MASTER
);
648 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
649 $pager->setOffset( $param['offset'] );
653 $pager->mLimit
= $lim;
655 // Fetch the log rows and build the HTML if needed
656 $logBody = $pager->getBody();
657 $numRows = $pager->getNumRows();
663 $dir = $context->getLanguage()->getDir();
664 $lang = $context->getLanguage()->getHtmlCode();
666 $s = Xml
::openElement( 'div', [
667 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
672 if ( count( $msgKey ) == 1 ) {
673 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
674 } else { // Process additional arguments
676 array_shift( $args );
677 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
680 $s .= $loglist->beginLogEventsList() .
682 $loglist->endLogEventsList();
683 } elseif ( $showIfEmpty ) {
684 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
685 $context->msg( 'logempty' )->parse() );
688 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
690 if ( $page instanceof Title
) {
691 $urlParam['page'] = $page->getPrefixedDBkey();
692 } elseif ( $page != '' ) {
693 $urlParam['page'] = $page;
697 $urlParam['user'] = $user;
700 if ( !is_array( $types ) ) { # Make it an array, if it isn't
704 # If there is exactly one log type, we can link to Special:Log?type=foo
705 if ( count( $types ) == 1 ) {
706 $urlParam['type'] = $types[0];
709 if ( $extraUrlParams !== false ) {
710 $urlParam = array_merge( $urlParam, $extraUrlParams );
713 $s .= $linkRenderer->makeKnownLink(
714 SpecialPage
::getTitleFor( 'Log' ),
715 $context->msg( 'log-fulllog' )->text(),
721 if ( $logBody && $msgKey[0] ) {
725 if ( $wrap != '' ) { // Wrap message in html
726 $s = str_replace( '$1', $s, $wrap );
729 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
730 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
731 // $out can be either an OutputPage object or a String-by-reference
732 if ( $out instanceof OutputPage
) {
743 * SQL clause to skip forbidden log types for this user
745 * @param IDatabase $db
746 * @param string $audience Public/user
747 * @param User $user User to check, or null to use $wgUser
748 * @return string|bool String on success, false on failure.
750 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
751 global $wgLogRestrictions;
753 if ( $audience != 'public' && $user === null ) {
758 // Reset the array, clears extra "where" clauses when $par is used
761 // Don't show private logs to unprivileged users
762 foreach ( $wgLogRestrictions as $logType => $right ) {
763 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
764 $hiddenLogs[] = $logType;
767 if ( count( $hiddenLogs ) == 1 ) {
768 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
769 } elseif ( $hiddenLogs ) {
770 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';