Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / logging / LogFormatter.php
blob8f60aee16ea6b95d09663805e260536c17109523
1 <?php
2 /**
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
20 * @file
21 * @author Niklas Laxström
22 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
23 * @since 1.19
26 /**
27 * Implements the default log formatting.
28 * Can be overridden by subclassing and setting
29 * $wgLogActionsHandlers['type/subtype'] = 'class'; or
30 * $wgLogActionsHandlers['type/*'] = 'class';
31 * @since 1.19
33 class LogFormatter {
34 // Audience options for viewing usernames, comments, and actions
35 const FOR_PUBLIC = 1;
36 const FOR_THIS_USER = 2;
38 // Static->
40 /**
41 * Constructs a new formatter suitable for given entry.
42 * @param $entry LogEntry
43 * @return LogFormatter
45 public static function newFromEntry( LogEntry $entry ) {
46 global $wgLogActionsHandlers;
47 $fulltype = $entry->getFullType();
48 $wildcard = $entry->getType() . '/*';
49 $handler = '';
51 if ( isset( $wgLogActionsHandlers[$fulltype] ) ) {
52 $handler = $wgLogActionsHandlers[$fulltype];
53 } elseif ( isset( $wgLogActionsHandlers[$wildcard] ) ) {
54 $handler = $wgLogActionsHandlers[$wildcard];
57 if ( $handler !== '' && is_string( $handler ) && class_exists( $handler ) ) {
58 return new $handler( $entry );
61 return new LegacyLogFormatter( $entry );
64 /**
65 * Handy shortcut for constructing a formatter directly from
66 * database row.
67 * @param $row
68 * @see DatabaseLogEntry::getSelectQueryData
69 * @return LogFormatter
71 public static function newFromRow( $row ) {
72 return self::newFromEntry( DatabaseLogEntry::newFromRow( $row ) );
75 // Nonstatic->
77 /// @var LogEntry
78 protected $entry;
80 /// Integer constant for handling log_deleted
81 protected $audience = self::FOR_PUBLIC;
83 /// Whether to output user tool links
84 protected $linkFlood = false;
86 /**
87 * Set to true if we are constructing a message text that is going to
88 * be included in page history or send to IRC feed. Links are replaced
89 * with plaintext or with [[pagename]] kind of syntax, that is parsed
90 * by page histories and IRC feeds.
91 * @var boolean
93 protected $plaintext = false;
95 protected $irctext = false;
97 protected function __construct( LogEntry $entry ) {
98 $this->entry = $entry;
99 $this->context = RequestContext::getMain();
103 * Replace the default context
104 * @param $context IContextSource
106 public function setContext( IContextSource $context ) {
107 $this->context = $context;
111 * Set the visibility restrictions for displaying content.
112 * If set to public, and an item is deleted, then it will be replaced
113 * with a placeholder even if the context user is allowed to view it.
114 * @param $audience integer self::FOR_THIS_USER or self::FOR_PUBLIC
116 public function setAudience( $audience ) {
117 $this->audience = ( $audience == self::FOR_THIS_USER )
118 ? self::FOR_THIS_USER
119 : self::FOR_PUBLIC;
123 * Check if a log item can be displayed
124 * @param $field integer LogPage::DELETED_* constant
125 * @return bool
127 protected function canView( $field ) {
128 if ( $this->audience == self::FOR_THIS_USER ) {
129 return LogEventsList::userCanBitfield(
130 $this->entry->getDeleted(), $field, $this->context->getUser() );
131 } else {
132 return !$this->entry->isDeleted( $field );
137 * If set to true, will produce user tool links after
138 * the user name. This should be replaced with generic
139 * CSS/JS solution.
140 * @param $value boolean
142 public function setShowUserToolLinks( $value ) {
143 $this->linkFlood = $value;
147 * Ugly hack to produce plaintext version of the message.
148 * Usually you also want to set extraneous request context
149 * to avoid formatting for any particular user.
150 * @see getActionText()
151 * @return string text
153 public function getPlainActionText() {
154 $this->plaintext = true;
155 $text = $this->getActionText();
156 $this->plaintext = false;
157 return $text;
161 * Even uglier hack to maintain backwards compatibilty with IRC bots
162 * (bug 34508).
163 * @see getActionText()
164 * @return string text
166 public function getIRCActionComment() {
167 $actionComment = $this->getIRCActionText();
168 $comment = $this->entry->getComment();
170 if ( $comment != '' ) {
171 if ( $actionComment == '' ) {
172 $actionComment = $comment;
173 } else {
174 $actionComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
178 return $actionComment;
182 * Even uglier hack to maintain backwards compatibilty with IRC bots
183 * (bug 34508).
184 * @see getActionText()
185 * @return string text
187 public function getIRCActionText() {
188 $this->plaintext = true;
189 $this->irctext = true;
191 $entry = $this->entry;
192 $parameters = $entry->getParameters();
193 // @see LogPage::actionText()
194 // Text of title the action is aimed at.
195 $target = $entry->getTarget()->getPrefixedText();
196 $text = null;
197 switch ( $entry->getType() ) {
198 case 'move':
199 switch ( $entry->getSubtype() ) {
200 case 'move':
201 $movesource = $parameters['4::target'];
202 $text = wfMessage( '1movedto2' )
203 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
204 break;
205 case 'move_redir':
206 $movesource = $parameters['4::target'];
207 $text = wfMessage( '1movedto2_redir' )
208 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
209 break;
210 case 'move-noredirect':
211 break;
212 case 'move_redir-noredirect':
213 break;
215 break;
217 case 'delete':
218 switch ( $entry->getSubtype() ) {
219 case 'delete':
220 $text = wfMessage( 'deletedarticle' )
221 ->rawParams( $target )->inContentLanguage()->escaped();
222 break;
223 case 'restore':
224 $text = wfMessage( 'undeletedarticle' )
225 ->rawParams( $target )->inContentLanguage()->escaped();
226 break;
227 //case 'revision': // Revision deletion
228 //case 'event': // Log deletion
229 // see https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/LogPage.php?&pathrev=97044&r1=97043&r2=97044
230 //default:
232 break;
234 case 'patrol':
235 // https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/PatrolLog.php?&pathrev=97495&r1=97494&r2=97495
236 // Create a diff link to the patrolled revision
237 if ( $entry->getSubtype() === 'patrol' ) {
238 $diffLink = htmlspecialchars(
239 wfMessage( 'patrol-log-diff', $parameters['4::curid'] )
240 ->inContentLanguage()->text() );
241 $text = wfMessage( 'patrol-log-line', $diffLink, "[[$target]]", "" )
242 ->inContentLanguage()->text();
243 } else {
244 // broken??
246 break;
248 case 'protect':
249 switch ( $entry->getSubtype() ) {
250 case 'protect':
251 $text = wfMessage( 'protectedarticle' )
252 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
253 break;
254 case 'unprotect':
255 $text = wfMessage( 'unprotectedarticle' )
256 ->rawParams( $target )->inContentLanguage()->escaped();
257 break;
258 case 'modify':
259 $text = wfMessage( 'modifiedarticleprotection' )
260 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
261 break;
263 break;
265 case 'newusers':
266 switch ( $entry->getSubtype() ) {
267 case 'newusers':
268 case 'create':
269 $text = wfMessage( 'newuserlog-create-entry' )
270 ->inContentLanguage()->escaped();
271 break;
272 case 'create2':
273 case 'byemail':
274 $text = wfMessage( 'newuserlog-create2-entry' )
275 ->rawParams( $target )->inContentLanguage()->escaped();
276 break;
277 case 'autocreate':
278 $text = wfMessage( 'newuserlog-autocreate-entry' )
279 ->inContentLanguage()->escaped();
280 break;
282 break;
284 case 'upload':
285 switch ( $entry->getSubtype() ) {
286 case 'upload':
287 $text = wfMessage( 'uploadedimage' )
288 ->rawParams( $target )->inContentLanguage()->escaped();
289 break;
290 case 'overwrite':
291 $text = wfMessage( 'overwroteimage' )
292 ->rawParams( $target )->inContentLanguage()->escaped();
293 break;
295 break;
297 case 'rights':
298 if ( count( $parameters['4::oldgroups'] ) ) {
299 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
300 } else {
301 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
303 if ( count( $parameters['5::newgroups'] ) ) {
304 $newgroups = implode( ', ', $parameters['5::newgroups'] );
305 } else {
306 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
308 switch ( $entry->getSubtype() ) {
309 case 'rights':
310 $text = wfMessage( 'rightslogentry' )
311 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
312 break;
313 case 'autopromote':
314 $text = wfMessage( 'rightslogentry-autopromote' )
315 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
316 break;
318 break;
320 // case 'suppress' --private log -- aaron (sign your messages so we know who to blame in a few years :-D)
321 // default:
323 if ( is_null( $text ) ) {
324 $text = $this->getPlainActionText();
327 $this->plaintext = false;
328 $this->irctext = false;
329 return $text;
333 * Gets the log action, including username.
334 * @return string HTML
336 public function getActionText() {
337 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
338 $element = $this->getActionMessage();
339 if ( $element instanceof Message ) {
340 $element = $this->plaintext ? $element->text() : $element->escaped();
342 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
343 $element = $this->styleRestricedElement( $element );
345 } else {
346 $performer = $this->getPerformerElement() . $this->msg( 'word-separator' )->text();
347 $element = $performer . $this->getRestrictedElement( 'rev-deleted-event' );
350 return $element;
354 * Returns a sentence describing the log action. Usually
355 * a Message object is returned, but old style log types
356 * and entries might return pre-escaped html string.
357 * @return Message|string pre-escaped html
359 protected function getActionMessage() {
360 $message = $this->msg( $this->getMessageKey() );
361 $message->params( $this->getMessageParameters() );
362 return $message;
366 * Returns a key to be used for formatting the action sentence.
367 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
368 * types will use custom keys, and subclasses can also alter the
369 * key depending on the entry itself.
370 * @return string message key
372 protected function getMessageKey() {
373 $type = $this->entry->getType();
374 $subtype = $this->entry->getSubtype();
376 return "logentry-$type-$subtype";
380 * Returns extra links that comes after the action text, like "revert", etc.
382 * @return string
384 public function getActionLinks() {
385 return '';
389 * Extracts the optional extra parameters for use in action messages.
390 * The array indexes start from number 3.
391 * @return array
393 protected function extractParameters() {
394 $entry = $this->entry;
395 $params = array();
397 if ( $entry->isLegacy() ) {
398 foreach ( $entry->getParameters() as $index => $value ) {
399 $params[$index + 3] = $value;
403 // Filter out parameters which are not in format #:foo
404 foreach ( $entry->getParameters() as $key => $value ) {
405 if ( strpos( $key, ':' ) === false ) {
406 continue;
408 list( $index, $type, ) = explode( ':', $key, 3 );
409 $params[$index - 1] = $this->formatParameterValue( $type, $value );
412 /* Message class doesn't like non consecutive numbering.
413 * Fill in missing indexes with empty strings to avoid
414 * incorrect renumbering.
416 if ( count( $params ) ) {
417 $max = max( array_keys( $params ) );
418 for ( $i = 4; $i < $max; $i++ ) {
419 if ( !isset( $params[$i] ) ) {
420 $params[$i] = '';
424 return $params;
428 * Formats parameters intented for action message from
429 * array of all parameters. There are three hardcoded
430 * parameters (array is zero-indexed, this list not):
431 * - 1: user name with premade link
432 * - 2: usable for gender magic function
433 * - 3: target page with premade link
434 * @return array
436 protected function getMessageParameters() {
437 if ( isset( $this->parsedParameters ) ) {
438 return $this->parsedParameters;
441 $entry = $this->entry;
442 $params = $this->extractParameters();
443 $params[0] = Message::rawParam( $this->getPerformerElement() );
444 $params[1] = $this->canView( LogPage::DELETED_USER ) ? $entry->getPerformer()->getName() : '';
445 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
447 // Bad things happens if the numbers are not in correct order
448 ksort( $params );
449 return $this->parsedParameters = $params;
453 * Formats parameters values dependent to their type
454 * @param string $type The type of the value.
455 * Valid are currently:
456 * * - (empty) or plain: The value is returned as-is
457 * * raw: The value will be added to the log message
458 * as raw parameter (e.g. no escaping)
459 * Use this only if there is no other working
460 * type like user-link or title-link
461 * * msg: The value is a message-key, the output is
462 * the message in user language
463 * * msg-content: The value is a message-key, the output
464 * is the message in content language
465 * * user: The value is a user name, e.g. for GENDER
466 * * user-link: The value is a user name, returns a
467 * link for the user
468 * * title: The value is a page title,
469 * returns name of page
470 * * title-link: The value is a page title,
471 * returns link to this page
472 * * number: Format value as number
473 * @param string $value The parameter value that should
474 * be formated
475 * @return string or Message::numParam or Message::rawParam
476 * Formated value
477 * @since 1.21
479 protected function formatParameterValue( $type, $value ) {
480 $saveLinkFlood = $this->linkFlood;
482 switch ( strtolower( trim( $type ) ) ) {
483 case 'raw':
484 $value = Message::rawParam( $value );
485 break;
486 case 'msg':
487 $value = $this->msg( $value )->text();
488 break;
489 case 'msg-content':
490 $value = $this->msg( $value )->inContentLanguage()->text();
491 break;
492 case 'number':
493 $value = Message::numParam( $value );
494 break;
495 case 'user':
496 $user = User::newFromName( $value );
497 $value = $user->getName();
498 break;
499 case 'user-link':
500 $this->setShowUserToolLinks( false );
502 $user = User::newFromName( $value );
503 $value = Message::rawParam( $this->makeUserLink( $user ) );
505 $this->setShowUserToolLinks( $saveLinkFlood );
506 break;
507 case 'title':
508 $title = Title::newFromText( $value );
509 $value = $title->getPrefixedText();
510 break;
511 case 'title-link':
512 $title = Title::newFromText( $value );
513 $value = Message::rawParam( $this->makePageLink( $title ) );
514 break;
515 case 'plain':
516 // Plain text, nothing to do
517 default:
518 // Catch other types and use the old behavior (return as-is)
521 return $value;
525 * Helper to make a link to the page, taking the plaintext
526 * value in consideration.
527 * @param $title Title the page
528 * @param array $parameters query parameters
529 * @throws MWException
530 * @return String
532 protected function makePageLink( Title $title = null, $parameters = array() ) {
533 if ( !$this->plaintext ) {
534 $link = Linker::link( $title, null, array(), $parameters );
535 } else {
536 if ( !$title instanceof Title ) {
537 throw new MWException( "Expected title, got null" );
539 $link = '[[' . $title->getPrefixedText() . ']]';
541 return $link;
545 * Provides the name of the user who performed the log action.
546 * Used as part of log action message or standalone, depending
547 * which parts of the log entry has been hidden.
548 * @return String
550 public function getPerformerElement() {
551 if ( $this->canView( LogPage::DELETED_USER ) ) {
552 $performer = $this->entry->getPerformer();
553 $element = $this->makeUserLink( $performer );
554 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
555 $element = $this->styleRestricedElement( $element );
557 } else {
558 $element = $this->getRestrictedElement( 'rev-deleted-user' );
561 return $element;
565 * Gets the luser provided comment
566 * @return string HTML
568 public function getComment() {
569 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
570 $comment = Linker::commentBlock( $this->entry->getComment() );
571 // No hard coded spaces thanx
572 $element = ltrim( $comment );
573 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
574 $element = $this->styleRestricedElement( $element );
576 } else {
577 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
580 return $element;
584 * Helper method for displaying restricted element.
585 * @param $message string
586 * @return string HTML or wikitext
588 protected function getRestrictedElement( $message ) {
589 if ( $this->plaintext ) {
590 return $this->msg( $message )->text();
593 $content = $this->msg( $message )->escaped();
594 $attribs = array( 'class' => 'history-deleted' );
595 return Html::rawElement( 'span', $attribs, $content );
599 * Helper method for styling restricted element.
600 * @param $content string
601 * @return string HTML or wikitext
603 protected function styleRestricedElement( $content ) {
604 if ( $this->plaintext ) {
605 return $content;
607 $attribs = array( 'class' => 'history-deleted' );
608 return Html::rawElement( 'span', $attribs, $content );
612 * Shortcut for wfMessage which honors local context.
613 * @todo Would it be better to require replacing the global context instead?
614 * @param $key string
615 * @return Message
617 protected function msg( $key ) {
618 return $this->context->msg( $key );
621 protected function makeUserLink( User $user ) {
622 if ( $this->plaintext ) {
623 $element = $user->getName();
624 } else {
625 $element = Linker::userLink(
626 $user->getId(),
627 $user->getName()
630 if ( $this->linkFlood ) {
631 $element .= Linker::userToolLinksRedContribs(
632 $user->getId(),
633 $user->getName(),
634 $user->getEditCount()
638 return $element;
642 * @return Array of titles that should be preloaded with LinkBatch.
644 public function getPreloadTitles() {
645 return array();
649 * @return Output of getMessageParameters() for testing
651 public function getMessageParametersForTesting() {
652 // This function was added because getMessageParameters() is
653 // protected and a change from protected to public caused
654 // problems with extensions
655 return $this->getMessageParameters();
661 * This class formats all log entries for log types
662 * which have not been converted to the new system.
663 * This is not about old log entries which store
664 * parameters in a different format - the new
665 * LogFormatter classes have code to support formatting
666 * those too.
667 * @since 1.19
669 class LegacyLogFormatter extends LogFormatter {
672 * Backward compatibility for extension changing the comment from
673 * the LogLine hook. This will be set by the first call on getComment(),
674 * then it might be modified by the hook when calling getActionLinks(),
675 * so that the modified value will be returned when calling getComment()
676 * a second time.
678 * @var string|null
680 private $comment = null;
683 * Cache for the result of getActionLinks() so that it does not need to
684 * run multiple times depending on the order that getComment() and
685 * getActionLinks() are called.
687 * @var string|null
689 private $revert = null;
691 public function getComment() {
692 if ( $this->comment === null ) {
693 $this->comment = parent::getComment();
696 // Make sure we execute the LogLine hook so that we immediately return
697 // the correct value.
698 if ( $this->revert === null ) {
699 $this->getActionLinks();
702 return $this->comment;
705 protected function getActionMessage() {
706 $entry = $this->entry;
707 $action = LogPage::actionText(
708 $entry->getType(),
709 $entry->getSubtype(),
710 $entry->getTarget(),
711 $this->plaintext ? null : $this->context->getSkin(),
712 (array)$entry->getParameters(),
713 !$this->plaintext // whether to filter [[]] links
716 $performer = $this->getPerformerElement();
717 if ( !$this->irctext ) {
718 $action = $performer . $this->msg( 'word-separator' )->text() . $action;
721 return $action;
724 public function getActionLinks() {
725 if ( $this->revert !== null ) {
726 return $this->revert;
729 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
730 return $this->revert = '';
733 $title = $this->entry->getTarget();
734 $type = $this->entry->getType();
735 $subtype = $this->entry->getSubtype();
737 // Show unblock/change block link
738 if ( ( $type == 'block' || $type == 'suppress' ) && ( $subtype == 'block' || $subtype == 'reblock' ) ) {
739 if ( !$this->context->getUser()->isAllowed( 'block' ) ) {
740 return '';
743 $links = array(
744 Linker::linkKnown(
745 SpecialPage::getTitleFor( 'Unblock', $title->getDBkey() ),
746 $this->msg( 'unblocklink' )->escaped()
748 Linker::linkKnown(
749 SpecialPage::getTitleFor( 'Block', $title->getDBkey() ),
750 $this->msg( 'change-blocklink' )->escaped()
753 return $this->msg( 'parentheses' )->rawParams(
754 $this->context->getLanguage()->pipeList( $links ) )->escaped();
755 // Show change protection link
756 } elseif ( $type == 'protect' && ( $subtype == 'protect' || $subtype == 'modify' || $subtype == 'unprotect' ) ) {
757 $links = array(
758 Linker::link( $title,
759 $this->msg( 'hist' )->escaped(),
760 array(),
761 array(
762 'action' => 'history',
763 'offset' => $this->entry->getTimestamp()
767 if ( $this->context->getUser()->isAllowed( 'protect' ) ) {
768 $links[] = Linker::linkKnown(
769 $title,
770 $this->msg( 'protect_change' )->escaped(),
771 array(),
772 array( 'action' => 'protect' )
775 return $this->msg( 'parentheses' )->rawParams(
776 $this->context->getLanguage()->pipeList( $links ) )->escaped();
777 // Show unmerge link
778 } elseif ( $type == 'merge' && $subtype == 'merge' ) {
779 if ( !$this->context->getUser()->isAllowed( 'mergehistory' ) ) {
780 return '';
783 $params = $this->extractParameters();
784 $revert = Linker::linkKnown(
785 SpecialPage::getTitleFor( 'MergeHistory' ),
786 $this->msg( 'revertmerge' )->escaped(),
787 array(),
788 array(
789 'target' => $params[3],
790 'dest' => $title->getPrefixedDBkey(),
791 'mergepoint' => $params[4]
794 return $this->msg( 'parentheses' )->rawParams( $revert )->escaped();
797 // Do nothing. The implementation is handled by the hook modifiying the
798 // passed-by-ref parameters. This also changes the default value so that
799 // getComment() and getActionLinks() do not call them indefinitely.
800 $this->revert = '';
802 // This is to populate the $comment member of this instance so that it
803 // can be modified when calling the hook just below.
804 if ( $this->comment === null ) {
805 $this->getComment();
808 $params = $this->entry->getParameters();
810 wfRunHooks( 'LogLine', array( $type, $subtype, $title, $params,
811 &$this->comment, &$this->revert, $this->entry->getTimestamp() ) );
813 return $this->revert;