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();
277 $text = wfMessage( 'movedarticleprotection' )
278 ->rawParams( $target, $parameters['4::oldtitle'] )->inContentLanguage()->escaped();
284 switch ( $entry->getSubtype() ) {
287 $text = wfMessage( 'newuserlog-create-entry' )
288 ->inContentLanguage()->escaped();
292 $text = wfMessage( 'newuserlog-create2-entry' )
293 ->rawParams( $target )->inContentLanguage()->escaped();
296 $text = wfMessage( 'newuserlog-autocreate-entry' )
297 ->inContentLanguage()->escaped();
303 switch ( $entry->getSubtype() ) {
305 $text = wfMessage( 'uploadedimage' )
306 ->rawParams( $target )->inContentLanguage()->escaped();
309 $text = wfMessage( 'overwroteimage' )
310 ->rawParams( $target )->inContentLanguage()->escaped();
316 if ( count( $parameters['4::oldgroups'] ) ) {
317 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
319 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
321 if ( count( $parameters['5::newgroups'] ) ) {
322 $newgroups = implode( ', ', $parameters['5::newgroups'] );
324 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
326 switch ( $entry->getSubtype() ) {
328 $text = wfMessage( 'rightslogentry' )
329 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
332 $text = wfMessage( 'rightslogentry-autopromote' )
333 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
339 $text = wfMessage( 'pagemerge-logentry' )
340 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
341 ->inContentLanguage()->escaped();
345 switch ( $entry->getSubtype() ) {
347 // Keep compatibility with extensions by checking for
348 // new key (5::duration/6::flags) or old key (0/optional 1)
349 if ( $entry->isLegacy() ) {
350 $rawDuration = $parameters[0];
351 $rawFlags = isset( $parameters[1] ) ?
$parameters[1] : '';
353 $rawDuration = $parameters['5::duration'];
354 $rawFlags = $parameters['6::flags'];
356 $duration = $wgContLang->translateBlockExpiry( $rawDuration );
357 $flags = BlockLogFormatter
::formatBlockFlags( $rawFlags, $wgContLang );
358 $text = wfMessage( 'blocklogentry' )
359 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
362 $text = wfMessage( 'unblocklogentry' )
363 ->rawParams( $target )->inContentLanguage()->escaped();
366 $duration = $wgContLang->translateBlockExpiry( $parameters['5::duration'] );
367 $flags = BlockLogFormatter
::formatBlockFlags( $parameters['6::flags'], $wgContLang );
368 $text = wfMessage( 'reblock-logentry' )
369 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
375 switch ( $entry->getSubtype() ) {
377 $text = wfMessage( 'import-logentry-upload' )
378 ->rawParams( $target )->inContentLanguage()->escaped();
381 $text = wfMessage( 'import-logentry-interwiki' )
382 ->rawParams( $target )->inContentLanguage()->escaped();
386 // case 'suppress' --private log -- aaron (so we know who to blame in a few years :-D)
389 if ( is_null( $text ) ) {
390 $text = $this->getPlainActionText();
393 $this->plaintext
= false;
394 $this->irctext
= false;
400 * Gets the log action, including username.
401 * @return string HTML
403 public function getActionText() {
404 if ( $this->canView( LogPage
::DELETED_ACTION
) ) {
405 $element = $this->getActionMessage();
406 if ( $element instanceof Message
) {
407 $element = $this->plaintext ?
$element->text() : $element->escaped();
409 if ( $this->entry
->isDeleted( LogPage
::DELETED_ACTION
) ) {
410 $element = $this->styleRestricedElement( $element );
413 $sep = $this->msg( 'word-separator' );
414 $sep = $this->plaintext ?
$sep->text() : $sep->escaped();
415 $performer = $this->getPerformerElement();
416 $element = $performer . $sep . $this->getRestrictedElement( 'rev-deleted-event' );
423 * Returns a sentence describing the log action. Usually
424 * a Message object is returned, but old style log types
425 * and entries might return pre-escaped HTML string.
426 * @return Message|string Pre-escaped HTML
428 protected function getActionMessage() {
429 $message = $this->msg( $this->getMessageKey() );
430 $message->params( $this->getMessageParameters() );
436 * Returns a key to be used for formatting the action sentence.
437 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
438 * types will use custom keys, and subclasses can also alter the
439 * key depending on the entry itself.
440 * @return string Message key
442 protected function getMessageKey() {
443 $type = $this->entry
->getType();
444 $subtype = $this->entry
->getSubtype();
446 return "logentry-$type-$subtype";
450 * Returns extra links that comes after the action text, like "revert", etc.
454 public function getActionLinks() {
459 * Extracts the optional extra parameters for use in action messages.
460 * The array indexes start from number 3.
463 protected function extractParameters() {
464 $entry = $this->entry
;
467 if ( $entry->isLegacy() ) {
468 foreach ( $entry->getParameters() as $index => $value ) {
469 $params[$index +
3] = $value;
473 // Filter out parameters which are not in format #:foo
474 foreach ( $entry->getParameters() as $key => $value ) {
475 if ( strpos( $key, ':' ) === false ) {
478 list( $index, $type, ) = explode( ':', $key, 3 );
479 if ( ctype_digit( $index ) ) {
480 $params[$index - 1] = $this->formatParameterValue( $type, $value );
484 /* Message class doesn't like non consecutive numbering.
485 * Fill in missing indexes with empty strings to avoid
486 * incorrect renumbering.
488 if ( count( $params ) ) {
489 $max = max( array_keys( $params ) );
490 // index 0 to 2 are added in getMessageParameters
491 for ( $i = 3; $i < $max; $i++
) {
492 if ( !isset( $params[$i] ) ) {
502 * Formats parameters intented for action message from
503 * array of all parameters. There are three hardcoded
504 * parameters (array is zero-indexed, this list not):
505 * - 1: user name with premade link
506 * - 2: usable for gender magic function
507 * - 3: target page with premade link
510 protected function getMessageParameters() {
511 if ( isset( $this->parsedParameters
) ) {
512 return $this->parsedParameters
;
515 $entry = $this->entry
;
516 $params = $this->extractParameters();
517 $params[0] = Message
::rawParam( $this->getPerformerElement() );
518 $params[1] = $this->canView( LogPage
::DELETED_USER
) ?
$entry->getPerformer()->getName() : '';
519 $params[2] = Message
::rawParam( $this->makePageLink( $entry->getTarget() ) );
521 // Bad things happens if the numbers are not in correct order
524 $this->parsedParameters
= $params;
525 return $this->parsedParameters
;
529 * Formats parameters values dependent to their type
530 * @param string $type The type of the value.
531 * Valid are currently:
532 * * - (empty) or plain: The value is returned as-is
533 * * raw: The value will be added to the log message
534 * as raw parameter (e.g. no escaping)
535 * Use this only if there is no other working
536 * type like user-link or title-link
537 * * msg: The value is a message-key, the output is
538 * the message in user language
539 * * msg-content: The value is a message-key, the output
540 * is the message in content language
541 * * user: The value is a user name, e.g. for GENDER
542 * * user-link: The value is a user name, returns a
544 * * title: The value is a page title,
545 * returns name of page
546 * * title-link: The value is a page title,
547 * returns link to this page
548 * * number: Format value as number
549 * * list: Format value as a comma-separated list
550 * @param mixed $value The parameter value that should be formatted
551 * @return string|array Formated value
554 protected function formatParameterValue( $type, $value ) {
555 $saveLinkFlood = $this->linkFlood
;
557 switch ( strtolower( trim( $type ) ) ) {
559 $value = Message
::rawParam( $value );
562 $value = $this->context
->getLanguage()->commaList( $value );
565 $value = $this->msg( $value )->text();
568 $value = $this->msg( $value )->inContentLanguage()->text();
571 $value = Message
::numParam( $value );
574 $user = User
::newFromName( $value );
575 $value = $user->getName();
578 $this->setShowUserToolLinks( false );
580 $user = User
::newFromName( $value );
581 $value = Message
::rawParam( $this->makeUserLink( $user ) );
583 $this->setShowUserToolLinks( $saveLinkFlood );
586 $title = Title
::newFromText( $value );
587 $value = $title->getPrefixedText();
590 $title = Title
::newFromText( $value );
591 $value = Message
::rawParam( $this->makePageLink( $title ) );
594 // Plain text, nothing to do
596 // Catch other types and use the old behavior (return as-is)
603 * Helper to make a link to the page, taking the plaintext
604 * value in consideration.
605 * @param Title $title The page
606 * @param array $parameters Query parameters
607 * @throws MWException
610 protected function makePageLink( Title
$title = null, $parameters = array() ) {
611 if ( !$this->plaintext
) {
612 $link = Linker
::link( $title, null, array(), $parameters );
614 if ( !$title instanceof Title
) {
615 throw new MWException( "Expected title, got null" );
617 $link = '[[' . $title->getPrefixedText() . ']]';
624 * Provides the name of the user who performed the log action.
625 * Used as part of log action message or standalone, depending
626 * which parts of the log entry has been hidden.
629 public function getPerformerElement() {
630 if ( $this->canView( LogPage
::DELETED_USER
) ) {
631 $performer = $this->entry
->getPerformer();
632 $element = $this->makeUserLink( $performer );
633 if ( $this->entry
->isDeleted( LogPage
::DELETED_USER
) ) {
634 $element = $this->styleRestricedElement( $element );
637 $element = $this->getRestrictedElement( 'rev-deleted-user' );
644 * Gets the user provided comment
645 * @return string HTML
647 public function getComment() {
648 if ( $this->canView( LogPage
::DELETED_COMMENT
) ) {
649 $comment = Linker
::commentBlock( $this->entry
->getComment() );
650 // No hard coded spaces thanx
651 $element = ltrim( $comment );
652 if ( $this->entry
->isDeleted( LogPage
::DELETED_COMMENT
) ) {
653 $element = $this->styleRestricedElement( $element );
656 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
663 * Helper method for displaying restricted element.
664 * @param string $message
665 * @return string HTML or wiki text
667 protected function getRestrictedElement( $message ) {
668 if ( $this->plaintext
) {
669 return $this->msg( $message )->text();
672 $content = $this->msg( $message )->escaped();
673 $attribs = array( 'class' => 'history-deleted' );
675 return Html
::rawElement( 'span', $attribs, $content );
679 * Helper method for styling restricted element.
680 * @param string $content
681 * @return string HTML or wiki text
683 protected function styleRestricedElement( $content ) {
684 if ( $this->plaintext
) {
687 $attribs = array( 'class' => 'history-deleted' );
689 return Html
::rawElement( 'span', $attribs, $content );
693 * Shortcut for wfMessage which honors local context.
697 protected function msg( $key ) {
698 return $this->context
->msg( $key );
701 protected function makeUserLink( User
$user, $toolFlags = 0 ) {
702 if ( $this->plaintext
) {
703 $element = $user->getName();
705 $element = Linker
::userLink(
710 if ( $this->linkFlood
) {
711 $element .= Linker
::userToolLinks(
714 true, // redContribsWhenNoEdits
716 $user->getEditCount()
725 * @return array Array of titles that should be preloaded with LinkBatch
727 public function getPreloadTitles() {
732 * @return array Output of getMessageParameters() for testing
734 public function getMessageParametersForTesting() {
735 // This function was added because getMessageParameters() is
736 // protected and a change from protected to public caused
737 // problems with extensions
738 return $this->getMessageParameters();
742 * Get the array of parameters, converted from legacy format if necessary.
746 protected function getParametersForApi() {
747 return $this->entry
->getParameters();
751 * Format parameters for API output
753 * The result array should generally map named keys to values. Index and
754 * type should be omitted, e.g. "4::foo" should be returned as "foo" in the
755 * output. Values should generally be unformatted.
757 * Renames or removals of keys besides from the legacy numeric format to
758 * modern named style should be avoided. Any renames should be announced to
759 * the mediawiki-api-announce mailing list.
764 public function formatParametersForApi() {
765 $logParams = array();
766 foreach ( $this->getParametersForApi() as $key => $value ) {
767 $vals = explode( ':', $key, 3 );
768 if ( count( $vals ) !== 3 ) {
769 $logParams[$key] = $value;
772 $logParams +
= $this->formatParameterValueForApi( $vals[2], $vals[1], $value );
774 ApiResult
::setIndexedTagName( $logParams, 'param' );
775 ApiResult
::setArrayType( $logParams, 'assoc' );
781 * Format a single parameter value for API output
784 * @param string $name
785 * @param string $type
786 * @param string $value
789 protected function formatParameterValueForApi( $name, $type, $value ) {
790 $type = strtolower( trim( $type ) );
793 $value = (bool)$value;
797 if ( ctype_digit( $value ) ||
is_int( $value ) ) {
798 $value = (int)$value;
800 $value = (float)$value;
807 if ( is_array( $value ) ) {
808 ApiResult
::setArrayType( $value, $type );
813 $value = wfTimestamp( TS_ISO_8601
, $value );
818 $msg = $this->msg( $value );
819 if ( $type === 'msg-content' ) {
820 $msg->inContentLanguage();
823 $value["{$name}_key"] = $msg->getKey();
824 if ( $msg->getParams() ) {
825 $value["{$name}_params"] = $msg->getParams();
827 $value["{$name}_text"] = $msg->text();
832 $title = Title
::newFromText( $value );
835 ApiQueryBase
::addTitleInfo( $value, $title, "{$name}_" );
841 $user = User
::newFromName( $value );
843 $value = $user->getName();
852 return array( $name => $value );
857 * This class formats all log entries for log types
858 * which have not been converted to the new system.
859 * This is not about old log entries which store
860 * parameters in a different format - the new
861 * LogFormatter classes have code to support formatting
865 class LegacyLogFormatter
extends LogFormatter
{
867 * Backward compatibility for extension changing the comment from
868 * the LogLine hook. This will be set by the first call on getComment(),
869 * then it might be modified by the hook when calling getActionLinks(),
870 * so that the modified value will be returned when calling getComment()
875 private $comment = null;
878 * Cache for the result of getActionLinks() so that it does not need to
879 * run multiple times depending on the order that getComment() and
880 * getActionLinks() are called.
884 private $revert = null;
886 public function getComment() {
887 if ( $this->comment
=== null ) {
888 $this->comment
= parent
::getComment();
891 // Make sure we execute the LogLine hook so that we immediately return
892 // the correct value.
893 if ( $this->revert
=== null ) {
894 $this->getActionLinks();
897 return $this->comment
;
900 protected function getActionMessage() {
901 $entry = $this->entry
;
902 $action = LogPage
::actionText(
904 $entry->getSubtype(),
906 $this->plaintext ?
null : $this->context
->getSkin(),
907 (array)$entry->getParameters(),
908 !$this->plaintext
// whether to filter [[]] links
911 $performer = $this->getPerformerElement();
912 if ( !$this->irctext
) {
913 $sep = $this->msg( 'word-separator' );
914 $sep = $this->plaintext ?
$sep->text() : $sep->escaped();
915 $action = $performer . $sep . $action;
921 public function getActionLinks() {
922 if ( $this->revert
!== null ) {
923 return $this->revert
;
926 if ( $this->entry
->isDeleted( LogPage
::DELETED_ACTION
) ) {
928 return $this->revert
;
931 $title = $this->entry
->getTarget();
932 $type = $this->entry
->getType();
933 $subtype = $this->entry
->getSubtype();
935 if ( $type == 'protect'
936 && ( $subtype == 'protect' ||
$subtype == 'modify' ||
$subtype == 'unprotect' )
939 Linker
::link( $title,
940 $this->msg( 'hist' )->escaped(),
943 'action' => 'history',
944 'offset' => $this->entry
->getTimestamp()
948 if ( $this->context
->getUser()->isAllowed( 'protect' ) ) {
949 $links[] = Linker
::linkKnown(
951 $this->msg( 'protect_change' )->escaped(),
953 array( 'action' => 'protect' )
957 return $this->msg( 'parentheses' )->rawParams(
958 $this->context
->getLanguage()->pipeList( $links ) )->escaped();
961 // Do nothing. The implementation is handled by the hook modifiying the
962 // passed-by-ref parameters. This also changes the default value so that
963 // getComment() and getActionLinks() do not call them indefinitely.
966 // This is to populate the $comment member of this instance so that it
967 // can be modified when calling the hook just below.
968 if ( $this->comment
=== null ) {
972 $params = $this->entry
->getParameters();
974 Hooks
::run( 'LogLine', array( $type, $subtype, $title, $params,
975 &$this->comment
, &$this->revert
, $this->entry
->getTimestamp() ) );
977 return $this->revert
;