Profiler: Call getContentType() only once in logData()
[mediawiki.git] / includes / logging / LogFormatter.php
blobbbe2f429753ea86406eff3b22eeaf15720e0fb58
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 LogEntry $entry
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 object $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 LogEntryBase */
78 protected $entry;
80 /** @var int Constant for handling log_deleted */
81 protected $audience = self::FOR_PUBLIC;
83 /** @var bool 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 string
93 protected $plaintext = false;
95 /** @var string */
96 protected $irctext = false;
98 protected function __construct( LogEntry $entry ) {
99 $this->entry = $entry;
100 $this->context = RequestContext::getMain();
104 * Replace the default context
105 * @param IContextSource $context
107 public function setContext( IContextSource $context ) {
108 $this->context = $context;
112 * Set the visibility restrictions for displaying content.
113 * If set to public, and an item is deleted, then it will be replaced
114 * with a placeholder even if the context user is allowed to view it.
115 * @param int $audience Const self::FOR_THIS_USER or self::FOR_PUBLIC
117 public function setAudience( $audience ) {
118 $this->audience = ( $audience == self::FOR_THIS_USER )
119 ? self::FOR_THIS_USER
120 : self::FOR_PUBLIC;
124 * Check if a log item can be displayed
125 * @param int $field LogPage::DELETED_* constant
126 * @return bool
128 protected function canView( $field ) {
129 if ( $this->audience == self::FOR_THIS_USER ) {
130 return LogEventsList::userCanBitfield(
131 $this->entry->getDeleted(), $field, $this->context->getUser() );
132 } else {
133 return !$this->entry->isDeleted( $field );
138 * If set to true, will produce user tool links after
139 * the user name. This should be replaced with generic
140 * CSS/JS solution.
141 * @param bool $value
143 public function setShowUserToolLinks( $value ) {
144 $this->linkFlood = $value;
148 * Ugly hack to produce plaintext version of the message.
149 * Usually you also want to set extraneous request context
150 * to avoid formatting for any particular user.
151 * @see getActionText()
152 * @return string Plain text
154 public function getPlainActionText() {
155 $this->plaintext = true;
156 $text = $this->getActionText();
157 $this->plaintext = false;
159 return $text;
163 * Even uglier hack to maintain backwards compatibilty with IRC bots
164 * (bug 34508).
165 * @see getActionText()
166 * @return string Text
168 public function getIRCActionComment() {
169 $actionComment = $this->getIRCActionText();
170 $comment = $this->entry->getComment();
172 if ( $comment != '' ) {
173 if ( $actionComment == '' ) {
174 $actionComment = $comment;
175 } else {
176 $actionComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
180 return $actionComment;
184 * Even uglier hack to maintain backwards compatibilty with IRC bots
185 * (bug 34508).
186 * @see getActionText()
187 * @return string Text
189 public function getIRCActionText() {
190 $this->plaintext = true;
191 $this->irctext = true;
193 $entry = $this->entry;
194 $parameters = $entry->getParameters();
195 // @see LogPage::actionText()
196 // Text of title the action is aimed at.
197 $target = $entry->getTarget()->getPrefixedText();
198 $text = null;
199 switch ( $entry->getType() ) {
200 case 'move':
201 switch ( $entry->getSubtype() ) {
202 case 'move':
203 $movesource = $parameters['4::target'];
204 $text = wfMessage( '1movedto2' )
205 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
206 break;
207 case 'move_redir':
208 $movesource = $parameters['4::target'];
209 $text = wfMessage( '1movedto2_redir' )
210 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
211 break;
212 case 'move-noredirect':
213 break;
214 case 'move_redir-noredirect':
215 break;
217 break;
219 case 'delete':
220 switch ( $entry->getSubtype() ) {
221 case 'delete':
222 $text = wfMessage( 'deletedarticle' )
223 ->rawParams( $target )->inContentLanguage()->escaped();
224 break;
225 case 'restore':
226 $text = wfMessage( 'undeletedarticle' )
227 ->rawParams( $target )->inContentLanguage()->escaped();
228 break;
229 // @codingStandardsIgnoreStart Long line
230 //case 'revision': // Revision deletion
231 //case 'event': // Log deletion
232 // see https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/LogPage.php?&pathrev=97044&r1=97043&r2=97044
233 //default:
234 // @codingStandardsIgnoreEnd
236 break;
238 case 'patrol':
239 // @codingStandardsIgnoreStart Long line
240 // https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/PatrolLog.php?&pathrev=97495&r1=97494&r2=97495
241 // @codingStandardsIgnoreEnd
242 // Create a diff link to the patrolled revision
243 if ( $entry->getSubtype() === 'patrol' ) {
244 $diffLink = htmlspecialchars(
245 wfMessage( 'patrol-log-diff', $parameters['4::curid'] )
246 ->inContentLanguage()->text() );
247 $text = wfMessage( 'patrol-log-line', $diffLink, "[[$target]]", "" )
248 ->inContentLanguage()->text();
249 } else {
250 // broken??
252 break;
254 case 'protect':
255 switch ( $entry->getSubtype() ) {
256 case 'protect':
257 $text = wfMessage( 'protectedarticle' )
258 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
259 break;
260 case 'unprotect':
261 $text = wfMessage( 'unprotectedarticle' )
262 ->rawParams( $target )->inContentLanguage()->escaped();
263 break;
264 case 'modify':
265 $text = wfMessage( 'modifiedarticleprotection' )
266 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
267 break;
269 break;
271 case 'newusers':
272 switch ( $entry->getSubtype() ) {
273 case 'newusers':
274 case 'create':
275 $text = wfMessage( 'newuserlog-create-entry' )
276 ->inContentLanguage()->escaped();
277 break;
278 case 'create2':
279 case 'byemail':
280 $text = wfMessage( 'newuserlog-create2-entry' )
281 ->rawParams( $target )->inContentLanguage()->escaped();
282 break;
283 case 'autocreate':
284 $text = wfMessage( 'newuserlog-autocreate-entry' )
285 ->inContentLanguage()->escaped();
286 break;
288 break;
290 case 'upload':
291 switch ( $entry->getSubtype() ) {
292 case 'upload':
293 $text = wfMessage( 'uploadedimage' )
294 ->rawParams( $target )->inContentLanguage()->escaped();
295 break;
296 case 'overwrite':
297 $text = wfMessage( 'overwroteimage' )
298 ->rawParams( $target )->inContentLanguage()->escaped();
299 break;
301 break;
303 case 'rights':
304 if ( count( $parameters['4::oldgroups'] ) ) {
305 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
306 } else {
307 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
309 if ( count( $parameters['5::newgroups'] ) ) {
310 $newgroups = implode( ', ', $parameters['5::newgroups'] );
311 } else {
312 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
314 switch ( $entry->getSubtype() ) {
315 case 'rights':
316 $text = wfMessage( 'rightslogentry' )
317 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
318 break;
319 case 'autopromote':
320 $text = wfMessage( 'rightslogentry-autopromote' )
321 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
322 break;
324 break;
326 case 'merge':
327 $text = wfMessage( 'pagemerge-logentry' )
328 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
329 ->inContentLanguage()->escaped();
330 break;
331 // case 'suppress' --private log -- aaron (so we know who to blame in a few years :-D)
332 // default:
334 if ( is_null( $text ) ) {
335 $text = $this->getPlainActionText();
338 $this->plaintext = false;
339 $this->irctext = false;
341 return $text;
345 * Gets the log action, including username.
346 * @return string HTML
348 public function getActionText() {
349 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
350 $element = $this->getActionMessage();
351 if ( $element instanceof Message ) {
352 $element = $this->plaintext ? $element->text() : $element->escaped();
354 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
355 $element = $this->styleRestricedElement( $element );
357 } else {
358 $performer = $this->getPerformerElement() . $this->msg( 'word-separator' )->text();
359 $element = $performer . $this->getRestrictedElement( 'rev-deleted-event' );
362 return $element;
366 * Returns a sentence describing the log action. Usually
367 * a Message object is returned, but old style log types
368 * and entries might return pre-escaped HTML string.
369 * @return Message|string Pre-escaped HTML
371 protected function getActionMessage() {
372 $message = $this->msg( $this->getMessageKey() );
373 $message->params( $this->getMessageParameters() );
375 return $message;
379 * Returns a key to be used for formatting the action sentence.
380 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
381 * types will use custom keys, and subclasses can also alter the
382 * key depending on the entry itself.
383 * @return string Message key
385 protected function getMessageKey() {
386 $type = $this->entry->getType();
387 $subtype = $this->entry->getSubtype();
389 return "logentry-$type-$subtype";
393 * Returns extra links that comes after the action text, like "revert", etc.
395 * @return string
397 public function getActionLinks() {
398 return '';
402 * Extracts the optional extra parameters for use in action messages.
403 * The array indexes start from number 3.
404 * @return array
406 protected function extractParameters() {
407 $entry = $this->entry;
408 $params = array();
410 if ( $entry->isLegacy() ) {
411 foreach ( $entry->getParameters() as $index => $value ) {
412 $params[$index + 3] = $value;
416 // Filter out parameters which are not in format #:foo
417 foreach ( $entry->getParameters() as $key => $value ) {
418 if ( strpos( $key, ':' ) === false ) {
419 continue;
421 list( $index, $type, ) = explode( ':', $key, 3 );
422 $params[$index - 1] = $this->formatParameterValue( $type, $value );
425 /* Message class doesn't like non consecutive numbering.
426 * Fill in missing indexes with empty strings to avoid
427 * incorrect renumbering.
429 if ( count( $params ) ) {
430 $max = max( array_keys( $params ) );
431 for ( $i = 4; $i < $max; $i++ ) {
432 if ( !isset( $params[$i] ) ) {
433 $params[$i] = '';
438 return $params;
442 * Formats parameters intented for action message from
443 * array of all parameters. There are three hardcoded
444 * parameters (array is zero-indexed, this list not):
445 * - 1: user name with premade link
446 * - 2: usable for gender magic function
447 * - 3: target page with premade link
448 * @return array
450 protected function getMessageParameters() {
451 if ( isset( $this->parsedParameters ) ) {
452 return $this->parsedParameters;
455 $entry = $this->entry;
456 $params = $this->extractParameters();
457 $params[0] = Message::rawParam( $this->getPerformerElement() );
458 $params[1] = $this->canView( LogPage::DELETED_USER ) ? $entry->getPerformer()->getName() : '';
459 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
461 // Bad things happens if the numbers are not in correct order
462 ksort( $params );
464 $this->parsedParameters = $params;
465 return $this->parsedParameters;
469 * Formats parameters values dependent to their type
470 * @param string $type The type of the value.
471 * Valid are currently:
472 * * - (empty) or plain: The value is returned as-is
473 * * raw: The value will be added to the log message
474 * as raw parameter (e.g. no escaping)
475 * Use this only if there is no other working
476 * type like user-link or title-link
477 * * msg: The value is a message-key, the output is
478 * the message in user language
479 * * msg-content: The value is a message-key, the output
480 * is the message in content language
481 * * user: The value is a user name, e.g. for GENDER
482 * * user-link: The value is a user name, returns a
483 * link for the user
484 * * title: The value is a page title,
485 * returns name of page
486 * * title-link: The value is a page title,
487 * returns link to this page
488 * * number: Format value as number
489 * @param string $value The parameter value that should
490 * be formated
491 * @return string|array Formated value
492 * @since 1.21
494 protected function formatParameterValue( $type, $value ) {
495 $saveLinkFlood = $this->linkFlood;
497 switch ( strtolower( trim( $type ) ) ) {
498 case 'raw':
499 $value = Message::rawParam( $value );
500 break;
501 case 'msg':
502 $value = $this->msg( $value )->text();
503 break;
504 case 'msg-content':
505 $value = $this->msg( $value )->inContentLanguage()->text();
506 break;
507 case 'number':
508 $value = Message::numParam( $value );
509 break;
510 case 'user':
511 $user = User::newFromName( $value );
512 $value = $user->getName();
513 break;
514 case 'user-link':
515 $this->setShowUserToolLinks( false );
517 $user = User::newFromName( $value );
518 $value = Message::rawParam( $this->makeUserLink( $user ) );
520 $this->setShowUserToolLinks( $saveLinkFlood );
521 break;
522 case 'title':
523 $title = Title::newFromText( $value );
524 $value = $title->getPrefixedText();
525 break;
526 case 'title-link':
527 $title = Title::newFromText( $value );
528 $value = Message::rawParam( $this->makePageLink( $title ) );
529 break;
530 case 'plain':
531 // Plain text, nothing to do
532 default:
533 // Catch other types and use the old behavior (return as-is)
536 return $value;
540 * Helper to make a link to the page, taking the plaintext
541 * value in consideration.
542 * @param Title $title The page
543 * @param array $parameters Query parameters
544 * @throws MWException
545 * @return string
547 protected function makePageLink( Title $title = null, $parameters = array() ) {
548 if ( !$this->plaintext ) {
549 $link = Linker::link( $title, null, array(), $parameters );
550 } else {
551 if ( !$title instanceof Title ) {
552 throw new MWException( "Expected title, got null" );
554 $link = '[[' . $title->getPrefixedText() . ']]';
557 return $link;
561 * Provides the name of the user who performed the log action.
562 * Used as part of log action message or standalone, depending
563 * which parts of the log entry has been hidden.
564 * @return string
566 public function getPerformerElement() {
567 if ( $this->canView( LogPage::DELETED_USER ) ) {
568 $performer = $this->entry->getPerformer();
569 $element = $this->makeUserLink( $performer );
570 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
571 $element = $this->styleRestricedElement( $element );
573 } else {
574 $element = $this->getRestrictedElement( 'rev-deleted-user' );
577 return $element;
581 * Gets the user provided comment
582 * @return string HTML
584 public function getComment() {
585 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
586 $comment = Linker::commentBlock( $this->entry->getComment() );
587 // No hard coded spaces thanx
588 $element = ltrim( $comment );
589 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
590 $element = $this->styleRestricedElement( $element );
592 } else {
593 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
596 return $element;
600 * Helper method for displaying restricted element.
601 * @param string $message
602 * @return string HTML or wiki text
604 protected function getRestrictedElement( $message ) {
605 if ( $this->plaintext ) {
606 return $this->msg( $message )->text();
609 $content = $this->msg( $message )->escaped();
610 $attribs = array( 'class' => 'history-deleted' );
612 return Html::rawElement( 'span', $attribs, $content );
616 * Helper method for styling restricted element.
617 * @param string $content
618 * @return string HTML or wiki text
620 protected function styleRestricedElement( $content ) {
621 if ( $this->plaintext ) {
622 return $content;
624 $attribs = array( 'class' => 'history-deleted' );
626 return Html::rawElement( 'span', $attribs, $content );
630 * Shortcut for wfMessage which honors local context.
631 * @param string $key
632 * @return Message
634 protected function msg( $key ) {
635 return $this->context->msg( $key );
638 protected function makeUserLink( User $user ) {
639 if ( $this->plaintext ) {
640 $element = $user->getName();
641 } else {
642 $element = Linker::userLink(
643 $user->getId(),
644 $user->getName()
647 if ( $this->linkFlood ) {
648 $element .= Linker::userToolLinksRedContribs(
649 $user->getId(),
650 $user->getName(),
651 $user->getEditCount()
656 return $element;
660 * @return array Array of titles that should be preloaded with LinkBatch
662 public function getPreloadTitles() {
663 return array();
667 * @return array Output of getMessageParameters() for testing
669 public function getMessageParametersForTesting() {
670 // This function was added because getMessageParameters() is
671 // protected and a change from protected to public caused
672 // problems with extensions
673 return $this->getMessageParameters();
678 * This class formats all log entries for log types
679 * which have not been converted to the new system.
680 * This is not about old log entries which store
681 * parameters in a different format - the new
682 * LogFormatter classes have code to support formatting
683 * those too.
684 * @since 1.19
686 class LegacyLogFormatter extends LogFormatter {
688 * Backward compatibility for extension changing the comment from
689 * the LogLine hook. This will be set by the first call on getComment(),
690 * then it might be modified by the hook when calling getActionLinks(),
691 * so that the modified value will be returned when calling getComment()
692 * a second time.
694 * @var string|null
696 private $comment = null;
699 * Cache for the result of getActionLinks() so that it does not need to
700 * run multiple times depending on the order that getComment() and
701 * getActionLinks() are called.
703 * @var string|null
705 private $revert = null;
707 public function getComment() {
708 if ( $this->comment === null ) {
709 $this->comment = parent::getComment();
712 // Make sure we execute the LogLine hook so that we immediately return
713 // the correct value.
714 if ( $this->revert === null ) {
715 $this->getActionLinks();
718 return $this->comment;
721 protected function getActionMessage() {
722 $entry = $this->entry;
723 $action = LogPage::actionText(
724 $entry->getType(),
725 $entry->getSubtype(),
726 $entry->getTarget(),
727 $this->plaintext ? null : $this->context->getSkin(),
728 (array)$entry->getParameters(),
729 !$this->plaintext // whether to filter [[]] links
732 $performer = $this->getPerformerElement();
733 if ( !$this->irctext ) {
734 $action = $performer . $this->msg( 'word-separator' )->text() . $action;
737 return $action;
740 public function getActionLinks() {
741 if ( $this->revert !== null ) {
742 return $this->revert;
745 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
746 $this->revert = '';
747 return $this->revert;
750 $title = $this->entry->getTarget();
751 $type = $this->entry->getType();
752 $subtype = $this->entry->getSubtype();
754 // Show unblock/change block link
755 if ( ( $type == 'block' || $type == 'suppress' )
756 && ( $subtype == 'block' || $subtype == 'reblock' )
758 if ( !$this->context->getUser()->isAllowed( 'block' ) ) {
759 return '';
762 $links = array(
763 Linker::linkKnown(
764 SpecialPage::getTitleFor( 'Unblock', $title->getDBkey() ),
765 $this->msg( 'unblocklink' )->escaped()
767 Linker::linkKnown(
768 SpecialPage::getTitleFor( 'Block', $title->getDBkey() ),
769 $this->msg( 'change-blocklink' )->escaped()
773 return $this->msg( 'parentheses' )->rawParams(
774 $this->context->getLanguage()->pipeList( $links ) )->escaped();
775 // Show change protection link
776 } elseif ( $type == 'protect'
777 && ( $subtype == 'protect' || $subtype == 'modify' || $subtype == 'unprotect' )
779 $links = array(
780 Linker::link( $title,
781 $this->msg( 'hist' )->escaped(),
782 array(),
783 array(
784 'action' => 'history',
785 'offset' => $this->entry->getTimestamp()
789 if ( $this->context->getUser()->isAllowed( 'protect' ) ) {
790 $links[] = Linker::linkKnown(
791 $title,
792 $this->msg( 'protect_change' )->escaped(),
793 array(),
794 array( 'action' => 'protect' )
798 return $this->msg( 'parentheses' )->rawParams(
799 $this->context->getLanguage()->pipeList( $links ) )->escaped();
802 // Do nothing. The implementation is handled by the hook modifiying the
803 // passed-by-ref parameters. This also changes the default value so that
804 // getComment() and getActionLinks() do not call them indefinitely.
805 $this->revert = '';
807 // This is to populate the $comment member of this instance so that it
808 // can be modified when calling the hook just below.
809 if ( $this->comment === null ) {
810 $this->getComment();
813 $params = $this->entry->getParameters();
815 wfRunHooks( 'LogLine', array( $type, $subtype, $title, $params,
816 &$this->comment, &$this->revert, $this->entry->getTimestamp() ) );
818 return $this->revert;