3 * Contains classes for formatting log entries
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Niklas Laxström
22 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
27 * Implements the default log formatting.
29 * Can be overridden by subclassing and setting:
31 * $wgLogActionsHandlers['type/subtype'] = 'class'; or
32 * $wgLogActionsHandlers['type/*'] = 'class';
37 // Audience options for viewing usernames, comments, and actions
39 const FOR_THIS_USER
= 2;
44 * Constructs a new formatter suitable for given entry.
45 * @param LogEntry $entry
46 * @return LogFormatter
48 public static function newFromEntry( LogEntry
$entry ) {
49 global $wgLogActionsHandlers;
50 $fulltype = $entry->getFullType();
51 $wildcard = $entry->getType() . '/*';
54 if ( isset( $wgLogActionsHandlers[$fulltype] ) ) {
55 $handler = $wgLogActionsHandlers[$fulltype];
56 } elseif ( isset( $wgLogActionsHandlers[$wildcard] ) ) {
57 $handler = $wgLogActionsHandlers[$wildcard];
60 if ( $handler !== '' && is_string( $handler ) && class_exists( $handler ) ) {
61 return new $handler( $entry );
64 return new LegacyLogFormatter( $entry );
68 * Handy shortcut for constructing a formatter directly from
71 * @see DatabaseLogEntry::getSelectQueryData
72 * @return LogFormatter
74 public static function newFromRow( $row ) {
75 return self
::newFromEntry( DatabaseLogEntry
::newFromRow( $row ) );
80 /** @var LogEntryBase */
83 /** @var int Constant for handling log_deleted */
84 protected $audience = self
::FOR_PUBLIC
;
86 /** @var IContextSource Context for logging */
89 /** @var bool Whether to output user tool links */
90 protected $linkFlood = false;
93 * Set to true if we are constructing a message text that is going to
94 * be included in page history or send to IRC feed. Links are replaced
95 * with plaintext or with [[pagename]] kind of syntax, that is parsed
96 * by page histories and IRC feeds.
99 protected $plaintext = false;
102 protected $irctext = false;
104 protected function __construct( LogEntry
$entry ) {
105 $this->entry
= $entry;
106 $this->context
= RequestContext
::getMain();
110 * Replace the default context
111 * @param IContextSource $context
113 public function setContext( IContextSource
$context ) {
114 $this->context
= $context;
118 * Set the visibility restrictions for displaying content.
119 * If set to public, and an item is deleted, then it will be replaced
120 * with a placeholder even if the context user is allowed to view it.
121 * @param int $audience Const self::FOR_THIS_USER or self::FOR_PUBLIC
123 public function setAudience( $audience ) {
124 $this->audience
= ( $audience == self
::FOR_THIS_USER
)
125 ? self
::FOR_THIS_USER
130 * Check if a log item can be displayed
131 * @param int $field LogPage::DELETED_* constant
134 protected function canView( $field ) {
135 if ( $this->audience
== self
::FOR_THIS_USER
) {
136 return LogEventsList
::userCanBitfield(
137 $this->entry
->getDeleted(), $field, $this->context
->getUser() );
139 return !$this->entry
->isDeleted( $field );
144 * If set to true, will produce user tool links after
145 * the user name. This should be replaced with generic
149 public function setShowUserToolLinks( $value ) {
150 $this->linkFlood
= $value;
154 * Ugly hack to produce plaintext version of the message.
155 * Usually you also want to set extraneous request context
156 * to avoid formatting for any particular user.
157 * @see getActionText()
158 * @return string Plain text
160 public function getPlainActionText() {
161 $this->plaintext
= true;
162 $text = $this->getActionText();
163 $this->plaintext
= false;
169 * Even uglier hack to maintain backwards compatibilty with IRC bots
171 * @see getActionText()
172 * @return string Text
174 public function getIRCActionComment() {
175 $actionComment = $this->getIRCActionText();
176 $comment = $this->entry
->getComment();
178 if ( $comment != '' ) {
179 if ( $actionComment == '' ) {
180 $actionComment = $comment;
182 $actionComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
186 return $actionComment;
190 * Even uglier hack to maintain backwards compatibilty with IRC bots
192 * @see getActionText()
193 * @return string Text
195 public function getIRCActionText() {
198 $this->plaintext
= true;
199 $this->irctext
= true;
201 $entry = $this->entry
;
202 $parameters = $entry->getParameters();
203 // @see LogPage::actionText()
204 // Text of title the action is aimed at.
205 $target = $entry->getTarget()->getPrefixedText();
207 switch ( $entry->getType() ) {
209 switch ( $entry->getSubtype() ) {
211 $movesource = $parameters['4::target'];
212 $text = wfMessage( '1movedto2' )
213 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
216 $movesource = $parameters['4::target'];
217 $text = wfMessage( '1movedto2_redir' )
218 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
220 case 'move-noredirect':
222 case 'move_redir-noredirect':
228 switch ( $entry->getSubtype() ) {
230 $text = wfMessage( 'deletedarticle' )
231 ->rawParams( $target )->inContentLanguage()->escaped();
234 $text = wfMessage( 'undeletedarticle' )
235 ->rawParams( $target )->inContentLanguage()->escaped();
237 // @codingStandardsIgnoreStart Long line
238 //case 'revision': // Revision deletion
239 //case 'event': // Log deletion
240 // see https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/LogPage.php?&pathrev=97044&r1=97043&r2=97044
242 // @codingStandardsIgnoreEnd
247 // @codingStandardsIgnoreStart Long line
248 // https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/PatrolLog.php?&pathrev=97495&r1=97494&r2=97495
249 // @codingStandardsIgnoreEnd
250 // Create a diff link to the patrolled revision
251 if ( $entry->getSubtype() === 'patrol' ) {
252 $diffLink = htmlspecialchars(
253 wfMessage( 'patrol-log-diff', $parameters['4::curid'] )
254 ->inContentLanguage()->text() );
255 $text = wfMessage( 'patrol-log-line', $diffLink, "[[$target]]", "" )
256 ->inContentLanguage()->text();
263 switch ( $entry->getSubtype() ) {
265 $text = wfMessage( 'protectedarticle' )
266 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
269 $text = wfMessage( 'unprotectedarticle' )
270 ->rawParams( $target )->inContentLanguage()->escaped();
273 $text = wfMessage( 'modifiedarticleprotection' )
274 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
280 switch ( $entry->getSubtype() ) {
283 $text = wfMessage( 'newuserlog-create-entry' )
284 ->inContentLanguage()->escaped();
288 $text = wfMessage( 'newuserlog-create2-entry' )
289 ->rawParams( $target )->inContentLanguage()->escaped();
292 $text = wfMessage( 'newuserlog-autocreate-entry' )
293 ->inContentLanguage()->escaped();
299 switch ( $entry->getSubtype() ) {
301 $text = wfMessage( 'uploadedimage' )
302 ->rawParams( $target )->inContentLanguage()->escaped();
305 $text = wfMessage( 'overwroteimage' )
306 ->rawParams( $target )->inContentLanguage()->escaped();
312 if ( count( $parameters['4::oldgroups'] ) ) {
313 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
315 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
317 if ( count( $parameters['5::newgroups'] ) ) {
318 $newgroups = implode( ', ', $parameters['5::newgroups'] );
320 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
322 switch ( $entry->getSubtype() ) {
324 $text = wfMessage( 'rightslogentry' )
325 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
328 $text = wfMessage( 'rightslogentry-autopromote' )
329 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
335 $text = wfMessage( 'pagemerge-logentry' )
336 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
337 ->inContentLanguage()->escaped();
341 switch ( $entry->getSubtype() ) {
343 // Keep compatibility with extensions by checking for
344 // new key (5::duration/6::flags) or old key (0/optional 1)
345 if ( $entry->isLegacy() ) {
346 $rawDuration = $parameters[0];
347 $rawFlags = isset( $parameters[1] ) ?
$parameters[1] : '';
349 $rawDuration = $parameters['5::duration'];
350 $rawFlags = $parameters['6::flags'];
352 $duration = $wgContLang->translateBlockExpiry( $rawDuration );
353 $flags = BlockLogFormatter
::formatBlockFlags( $rawFlags, $wgContLang );
354 $text = wfMessage( 'blocklogentry' )
355 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
358 $text = wfMessage( 'unblocklogentry' )
359 ->rawParams( $target )->inContentLanguage()->escaped();
362 $duration = $wgContLang->translateBlockExpiry( $parameters['5::duration'] );
363 $flags = BlockLogFormatter
::formatBlockFlags( $parameters['6::flags'], $wgContLang );
364 $text = wfMessage( 'reblock-logentry' )
365 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
371 switch ( $entry->getSubtype() ) {
373 $text = wfMessage( 'import-logentry-upload' )
374 ->rawParams( $target )->inContentLanguage()->escaped();
377 $text = wfMessage( 'import-logentry-interwiki' )
378 ->rawParams( $target )->inContentLanguage()->escaped();
382 // case 'suppress' --private log -- aaron (so we know who to blame in a few years :-D)
385 if ( is_null( $text ) ) {
386 $text = $this->getPlainActionText();
389 $this->plaintext
= false;
390 $this->irctext
= false;
396 * Gets the log action, including username.
397 * @return string HTML
399 public function getActionText() {
400 if ( $this->canView( LogPage
::DELETED_ACTION
) ) {
401 $element = $this->getActionMessage();
402 if ( $element instanceof Message
) {
403 $element = $this->plaintext ?
$element->text() : $element->escaped();
405 if ( $this->entry
->isDeleted( LogPage
::DELETED_ACTION
) ) {
406 $element = $this->styleRestricedElement( $element );
409 $sep = $this->msg( 'word-separator' );
410 $sep = $this->plaintext ?
$sep->text() : $sep->escaped();
411 $performer = $this->getPerformerElement();
412 $element = $performer . $sep . $this->getRestrictedElement( 'rev-deleted-event' );
419 * Returns a sentence describing the log action. Usually
420 * a Message object is returned, but old style log types
421 * and entries might return pre-escaped HTML string.
422 * @return Message|string Pre-escaped HTML
424 protected function getActionMessage() {
425 $message = $this->msg( $this->getMessageKey() );
426 $message->params( $this->getMessageParameters() );
432 * Returns a key to be used for formatting the action sentence.
433 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
434 * types will use custom keys, and subclasses can also alter the
435 * key depending on the entry itself.
436 * @return string Message key
438 protected function getMessageKey() {
439 $type = $this->entry
->getType();
440 $subtype = $this->entry
->getSubtype();
442 return "logentry-$type-$subtype";
446 * Returns extra links that comes after the action text, like "revert", etc.
450 public function getActionLinks() {
455 * Extracts the optional extra parameters for use in action messages.
456 * The array indexes start from number 3.
459 protected function extractParameters() {
460 $entry = $this->entry
;
463 if ( $entry->isLegacy() ) {
464 foreach ( $entry->getParameters() as $index => $value ) {
465 $params[$index +
3] = $value;
469 // Filter out parameters which are not in format #:foo
470 foreach ( $entry->getParameters() as $key => $value ) {
471 if ( strpos( $key, ':' ) === false ) {
474 list( $index, $type, ) = explode( ':', $key, 3 );
475 if ( ctype_digit( $index ) ) {
476 $params[$index - 1] = $this->formatParameterValue( $type, $value );
480 /* Message class doesn't like non consecutive numbering.
481 * Fill in missing indexes with empty strings to avoid
482 * incorrect renumbering.
484 if ( count( $params ) ) {
485 $max = max( array_keys( $params ) );
486 // index 0 to 2 are added in getMessageParameters
487 for ( $i = 3; $i < $max; $i++
) {
488 if ( !isset( $params[$i] ) ) {
498 * Formats parameters intented for action message from
499 * array of all parameters. There are three hardcoded
500 * parameters (array is zero-indexed, this list not):
501 * - 1: user name with premade link
502 * - 2: usable for gender magic function
503 * - 3: target page with premade link
506 protected function getMessageParameters() {
507 if ( isset( $this->parsedParameters
) ) {
508 return $this->parsedParameters
;
511 $entry = $this->entry
;
512 $params = $this->extractParameters();
513 $params[0] = Message
::rawParam( $this->getPerformerElement() );
514 $params[1] = $this->canView( LogPage
::DELETED_USER
) ?
$entry->getPerformer()->getName() : '';
515 $params[2] = Message
::rawParam( $this->makePageLink( $entry->getTarget() ) );
517 // Bad things happens if the numbers are not in correct order
520 $this->parsedParameters
= $params;
521 return $this->parsedParameters
;
525 * Formats parameters values dependent to their type
526 * @param string $type The type of the value.
527 * Valid are currently:
528 * * - (empty) or plain: The value is returned as-is
529 * * raw: The value will be added to the log message
530 * as raw parameter (e.g. no escaping)
531 * Use this only if there is no other working
532 * type like user-link or title-link
533 * * msg: The value is a message-key, the output is
534 * the message in user language
535 * * msg-content: The value is a message-key, the output
536 * is the message in content language
537 * * user: The value is a user name, e.g. for GENDER
538 * * user-link: The value is a user name, returns a
540 * * title: The value is a page title,
541 * returns name of page
542 * * title-link: The value is a page title,
543 * returns link to this page
544 * * number: Format value as number
545 * * list: Format value as a comma-separated list
546 * @param mixed $value The parameter value that should be formatted
547 * @return string|array Formated value
550 protected function formatParameterValue( $type, $value ) {
551 $saveLinkFlood = $this->linkFlood
;
553 switch ( strtolower( trim( $type ) ) ) {
555 $value = Message
::rawParam( $value );
558 $value = $this->context
->getLanguage()->commaList( $value );
561 $value = $this->msg( $value )->text();
564 $value = $this->msg( $value )->inContentLanguage()->text();
567 $value = Message
::numParam( $value );
570 $user = User
::newFromName( $value );
571 $value = $user->getName();
574 $this->setShowUserToolLinks( false );
576 $user = User
::newFromName( $value );
577 $value = Message
::rawParam( $this->makeUserLink( $user ) );
579 $this->setShowUserToolLinks( $saveLinkFlood );
582 $title = Title
::newFromText( $value );
583 $value = $title->getPrefixedText();
586 $title = Title
::newFromText( $value );
587 $value = Message
::rawParam( $this->makePageLink( $title ) );
590 // Plain text, nothing to do
592 // Catch other types and use the old behavior (return as-is)
599 * Helper to make a link to the page, taking the plaintext
600 * value in consideration.
601 * @param Title $title The page
602 * @param array $parameters Query parameters
603 * @throws MWException
606 protected function makePageLink( Title
$title = null, $parameters = array() ) {
607 if ( !$this->plaintext
) {
608 $link = Linker
::link( $title, null, array(), $parameters );
610 if ( !$title instanceof Title
) {
611 throw new MWException( "Expected title, got null" );
613 $link = '[[' . $title->getPrefixedText() . ']]';
620 * Provides the name of the user who performed the log action.
621 * Used as part of log action message or standalone, depending
622 * which parts of the log entry has been hidden.
625 public function getPerformerElement() {
626 if ( $this->canView( LogPage
::DELETED_USER
) ) {
627 $performer = $this->entry
->getPerformer();
628 $element = $this->makeUserLink( $performer );
629 if ( $this->entry
->isDeleted( LogPage
::DELETED_USER
) ) {
630 $element = $this->styleRestricedElement( $element );
633 $element = $this->getRestrictedElement( 'rev-deleted-user' );
640 * Gets the user provided comment
641 * @return string HTML
643 public function getComment() {
644 if ( $this->canView( LogPage
::DELETED_COMMENT
) ) {
645 $comment = Linker
::commentBlock( $this->entry
->getComment() );
646 // No hard coded spaces thanx
647 $element = ltrim( $comment );
648 if ( $this->entry
->isDeleted( LogPage
::DELETED_COMMENT
) ) {
649 $element = $this->styleRestricedElement( $element );
652 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
659 * Helper method for displaying restricted element.
660 * @param string $message
661 * @return string HTML or wiki text
663 protected function getRestrictedElement( $message ) {
664 if ( $this->plaintext
) {
665 return $this->msg( $message )->text();
668 $content = $this->msg( $message )->escaped();
669 $attribs = array( 'class' => 'history-deleted' );
671 return Html
::rawElement( 'span', $attribs, $content );
675 * Helper method for styling restricted element.
676 * @param string $content
677 * @return string HTML or wiki text
679 protected function styleRestricedElement( $content ) {
680 if ( $this->plaintext
) {
683 $attribs = array( 'class' => 'history-deleted' );
685 return Html
::rawElement( 'span', $attribs, $content );
689 * Shortcut for wfMessage which honors local context.
693 protected function msg( $key ) {
694 return $this->context
->msg( $key );
697 protected function makeUserLink( User
$user, $toolFlags = 0 ) {
698 if ( $this->plaintext
) {
699 $element = $user->getName();
701 $element = Linker
::userLink(
706 if ( $this->linkFlood
) {
707 $element .= Linker
::userToolLinks(
710 true, // redContribsWhenNoEdits
712 $user->getEditCount()
721 * @return array Array of titles that should be preloaded with LinkBatch
723 public function getPreloadTitles() {
728 * @return array Output of getMessageParameters() for testing
730 public function getMessageParametersForTesting() {
731 // This function was added because getMessageParameters() is
732 // protected and a change from protected to public caused
733 // problems with extensions
734 return $this->getMessageParameters();
738 * Get the array of parameters, converted from legacy format if necessary.
742 protected function getParametersForApi() {
743 return $this->entry
->getParameters();
747 * Format parameters for API output
749 * The result array should generally map named keys to values. Index and
750 * type should be omitted, e.g. "4::foo" should be returned as "foo" in the
751 * output. Values should generally be unformatted.
753 * Renames or removals of keys besides from the legacy numeric format to
754 * modern named style should be avoided. Any renames should be announced to
755 * the mediawiki-api-announce mailing list.
760 public function formatParametersForApi() {
761 $logParams = array();
762 foreach ( $this->getParametersForApi() as $key => $value ) {
763 $vals = explode( ':', $key, 3 );
764 if ( count( $vals ) !== 3 ) {
765 $logParams[$key] = $value;
768 $logParams +
= $this->formatParameterValueForApi( $vals[2], $vals[1], $value );
770 ApiResult
::setIndexedTagName( $logParams, 'param' );
771 ApiResult
::setArrayType( $logParams, 'assoc' );
777 * Format a single parameter value for API output
780 * @param string $name
781 * @param string $type
782 * @param string $value
785 protected function formatParameterValueForApi( $name, $type, $value ) {
786 $type = strtolower( trim( $type ) );
789 $value = (bool)$value;
793 if ( ctype_digit( $value ) ) {
794 $value = (int)$value;
796 $value = (float)$value;
803 if ( is_array( $value ) ) {
804 ApiResult
::setArrayType( $value, $type );
809 $value = wfTimestamp( TS_ISO_8601
, $value );
814 $msg = $this->msg( $value );
815 if ( $type === 'msg-content' ) {
816 $msg->inContentLanguage();
819 $value["{$name}_key"] = $msg->getKey();
820 if ( $msg->getParams() ) {
821 $value["{$name}_params"] = $msg->getParams();
823 $value["{$name}_text"] = $msg->text();
828 $title = Title
::newFromText( $value );
831 ApiQueryBase
::addTitleInfo( $value, $title, "{$name}_" );
837 $user = User
::newFromName( $value );
839 $value = $user->getName();
848 return array( $name => $value );
853 * This class formats all log entries for log types
854 * which have not been converted to the new system.
855 * This is not about old log entries which store
856 * parameters in a different format - the new
857 * LogFormatter classes have code to support formatting
861 class LegacyLogFormatter
extends LogFormatter
{
863 * Backward compatibility for extension changing the comment from
864 * the LogLine hook. This will be set by the first call on getComment(),
865 * then it might be modified by the hook when calling getActionLinks(),
866 * so that the modified value will be returned when calling getComment()
871 private $comment = null;
874 * Cache for the result of getActionLinks() so that it does not need to
875 * run multiple times depending on the order that getComment() and
876 * getActionLinks() are called.
880 private $revert = null;
882 public function getComment() {
883 if ( $this->comment
=== null ) {
884 $this->comment
= parent
::getComment();
887 // Make sure we execute the LogLine hook so that we immediately return
888 // the correct value.
889 if ( $this->revert
=== null ) {
890 $this->getActionLinks();
893 return $this->comment
;
896 protected function getActionMessage() {
897 $entry = $this->entry
;
898 $action = LogPage
::actionText(
900 $entry->getSubtype(),
902 $this->plaintext ?
null : $this->context
->getSkin(),
903 (array)$entry->getParameters(),
904 !$this->plaintext
// whether to filter [[]] links
907 $performer = $this->getPerformerElement();
908 if ( !$this->irctext
) {
909 $sep = $this->msg( 'word-separator' );
910 $sep = $this->plaintext ?
$sep->text() : $sep->escaped();
911 $action = $performer . $sep . $action;
917 public function getActionLinks() {
918 if ( $this->revert
!== null ) {
919 return $this->revert
;
922 if ( $this->entry
->isDeleted( LogPage
::DELETED_ACTION
) ) {
924 return $this->revert
;
927 $title = $this->entry
->getTarget();
928 $type = $this->entry
->getType();
929 $subtype = $this->entry
->getSubtype();
931 if ( $type == 'protect'
932 && ( $subtype == 'protect' ||
$subtype == 'modify' ||
$subtype == 'unprotect' )
935 Linker
::link( $title,
936 $this->msg( 'hist' )->escaped(),
939 'action' => 'history',
940 'offset' => $this->entry
->getTimestamp()
944 if ( $this->context
->getUser()->isAllowed( 'protect' ) ) {
945 $links[] = Linker
::linkKnown(
947 $this->msg( 'protect_change' )->escaped(),
949 array( 'action' => 'protect' )
953 return $this->msg( 'parentheses' )->rawParams(
954 $this->context
->getLanguage()->pipeList( $links ) )->escaped();
957 // Do nothing. The implementation is handled by the hook modifiying the
958 // passed-by-ref parameters. This also changes the default value so that
959 // getComment() and getActionLinks() do not call them indefinitely.
962 // This is to populate the $comment member of this instance so that it
963 // can be modified when calling the hook just below.
964 if ( $this->comment
=== null ) {
968 $params = $this->entry
->getParameters();
970 Hooks
::run( 'LogLine', array( $type, $subtype, $title, $params,
971 &$this->comment
, &$this->revert
, $this->entry
->getTimestamp() ) );
973 return $this->revert
;