Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / logging / LogFormatter.php
blob4487fec6e4085c84d35d694a3b96abbe442646f2
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 IContextSource Context for logging */
84 public $context;
86 /** @var bool Whether to output user tool links */
87 protected $linkFlood = false;
89 /**
90 * Set to true if we are constructing a message text that is going to
91 * be included in page history or send to IRC feed. Links are replaced
92 * with plaintext or with [[pagename]] kind of syntax, that is parsed
93 * by page histories and IRC feeds.
94 * @var string
96 protected $plaintext = false;
98 /** @var string */
99 protected $irctext = false;
101 protected function __construct( LogEntry $entry ) {
102 $this->entry = $entry;
103 $this->context = RequestContext::getMain();
107 * Replace the default context
108 * @param IContextSource $context
110 public function setContext( IContextSource $context ) {
111 $this->context = $context;
115 * Set the visibility restrictions for displaying content.
116 * If set to public, and an item is deleted, then it will be replaced
117 * with a placeholder even if the context user is allowed to view it.
118 * @param int $audience Const self::FOR_THIS_USER or self::FOR_PUBLIC
120 public function setAudience( $audience ) {
121 $this->audience = ( $audience == self::FOR_THIS_USER )
122 ? self::FOR_THIS_USER
123 : self::FOR_PUBLIC;
127 * Check if a log item can be displayed
128 * @param int $field LogPage::DELETED_* constant
129 * @return bool
131 protected function canView( $field ) {
132 if ( $this->audience == self::FOR_THIS_USER ) {
133 return LogEventsList::userCanBitfield(
134 $this->entry->getDeleted(), $field, $this->context->getUser() );
135 } else {
136 return !$this->entry->isDeleted( $field );
141 * If set to true, will produce user tool links after
142 * the user name. This should be replaced with generic
143 * CSS/JS solution.
144 * @param bool $value
146 public function setShowUserToolLinks( $value ) {
147 $this->linkFlood = $value;
151 * Ugly hack to produce plaintext version of the message.
152 * Usually you also want to set extraneous request context
153 * to avoid formatting for any particular user.
154 * @see getActionText()
155 * @return string Plain text
157 public function getPlainActionText() {
158 $this->plaintext = true;
159 $text = $this->getActionText();
160 $this->plaintext = false;
162 return $text;
166 * Even uglier hack to maintain backwards compatibilty with IRC bots
167 * (bug 34508).
168 * @see getActionText()
169 * @return string Text
171 public function getIRCActionComment() {
172 $actionComment = $this->getIRCActionText();
173 $comment = $this->entry->getComment();
175 if ( $comment != '' ) {
176 if ( $actionComment == '' ) {
177 $actionComment = $comment;
178 } else {
179 $actionComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
183 return $actionComment;
187 * Even uglier hack to maintain backwards compatibilty with IRC bots
188 * (bug 34508).
189 * @see getActionText()
190 * @return string Text
192 public function getIRCActionText() {
193 $this->plaintext = true;
194 $this->irctext = true;
196 $entry = $this->entry;
197 $parameters = $entry->getParameters();
198 // @see LogPage::actionText()
199 // Text of title the action is aimed at.
200 $target = $entry->getTarget()->getPrefixedText();
201 $text = null;
202 switch ( $entry->getType() ) {
203 case 'move':
204 switch ( $entry->getSubtype() ) {
205 case 'move':
206 $movesource = $parameters['4::target'];
207 $text = wfMessage( '1movedto2' )
208 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
209 break;
210 case 'move_redir':
211 $movesource = $parameters['4::target'];
212 $text = wfMessage( '1movedto2_redir' )
213 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
214 break;
215 case 'move-noredirect':
216 break;
217 case 'move_redir-noredirect':
218 break;
220 break;
222 case 'delete':
223 switch ( $entry->getSubtype() ) {
224 case 'delete':
225 $text = wfMessage( 'deletedarticle' )
226 ->rawParams( $target )->inContentLanguage()->escaped();
227 break;
228 case 'restore':
229 $text = wfMessage( 'undeletedarticle' )
230 ->rawParams( $target )->inContentLanguage()->escaped();
231 break;
232 // @codingStandardsIgnoreStart Long line
233 //case 'revision': // Revision deletion
234 //case 'event': // Log deletion
235 // see https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/LogPage.php?&pathrev=97044&r1=97043&r2=97044
236 //default:
237 // @codingStandardsIgnoreEnd
239 break;
241 case 'patrol':
242 // @codingStandardsIgnoreStart Long line
243 // https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/PatrolLog.php?&pathrev=97495&r1=97494&r2=97495
244 // @codingStandardsIgnoreEnd
245 // Create a diff link to the patrolled revision
246 if ( $entry->getSubtype() === 'patrol' ) {
247 $diffLink = htmlspecialchars(
248 wfMessage( 'patrol-log-diff', $parameters['4::curid'] )
249 ->inContentLanguage()->text() );
250 $text = wfMessage( 'patrol-log-line', $diffLink, "[[$target]]", "" )
251 ->inContentLanguage()->text();
252 } else {
253 // broken??
255 break;
257 case 'protect':
258 switch ( $entry->getSubtype() ) {
259 case 'protect':
260 $text = wfMessage( 'protectedarticle' )
261 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
262 break;
263 case 'unprotect':
264 $text = wfMessage( 'unprotectedarticle' )
265 ->rawParams( $target )->inContentLanguage()->escaped();
266 break;
267 case 'modify':
268 $text = wfMessage( 'modifiedarticleprotection' )
269 ->rawParams( $target . ' ' . $parameters[0] )->inContentLanguage()->escaped();
270 break;
272 break;
274 case 'newusers':
275 switch ( $entry->getSubtype() ) {
276 case 'newusers':
277 case 'create':
278 $text = wfMessage( 'newuserlog-create-entry' )
279 ->inContentLanguage()->escaped();
280 break;
281 case 'create2':
282 case 'byemail':
283 $text = wfMessage( 'newuserlog-create2-entry' )
284 ->rawParams( $target )->inContentLanguage()->escaped();
285 break;
286 case 'autocreate':
287 $text = wfMessage( 'newuserlog-autocreate-entry' )
288 ->inContentLanguage()->escaped();
289 break;
291 break;
293 case 'upload':
294 switch ( $entry->getSubtype() ) {
295 case 'upload':
296 $text = wfMessage( 'uploadedimage' )
297 ->rawParams( $target )->inContentLanguage()->escaped();
298 break;
299 case 'overwrite':
300 $text = wfMessage( 'overwroteimage' )
301 ->rawParams( $target )->inContentLanguage()->escaped();
302 break;
304 break;
306 case 'rights':
307 if ( count( $parameters['4::oldgroups'] ) ) {
308 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
309 } else {
310 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
312 if ( count( $parameters['5::newgroups'] ) ) {
313 $newgroups = implode( ', ', $parameters['5::newgroups'] );
314 } else {
315 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
317 switch ( $entry->getSubtype() ) {
318 case 'rights':
319 $text = wfMessage( 'rightslogentry' )
320 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
321 break;
322 case 'autopromote':
323 $text = wfMessage( 'rightslogentry-autopromote' )
324 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
325 break;
327 break;
329 case 'merge':
330 $text = wfMessage( 'pagemerge-logentry' )
331 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
332 ->inContentLanguage()->escaped();
333 break;
334 // case 'suppress' --private log -- aaron (so we know who to blame in a few years :-D)
335 // default:
337 if ( is_null( $text ) ) {
338 $text = $this->getPlainActionText();
341 $this->plaintext = false;
342 $this->irctext = false;
344 return $text;
348 * Gets the log action, including username.
349 * @return string HTML
351 public function getActionText() {
352 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
353 $element = $this->getActionMessage();
354 if ( $element instanceof Message ) {
355 $element = $this->plaintext ? $element->text() : $element->escaped();
357 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
358 $element = $this->styleRestricedElement( $element );
360 } else {
361 $sep = $this->msg( 'word-separator' );
362 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
363 $performer = $this->getPerformerElement();
364 $element = $performer . $sep . $this->getRestrictedElement( 'rev-deleted-event' );
367 return $element;
371 * Returns a sentence describing the log action. Usually
372 * a Message object is returned, but old style log types
373 * and entries might return pre-escaped HTML string.
374 * @return Message|string Pre-escaped HTML
376 protected function getActionMessage() {
377 $message = $this->msg( $this->getMessageKey() );
378 $message->params( $this->getMessageParameters() );
380 return $message;
384 * Returns a key to be used for formatting the action sentence.
385 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
386 * types will use custom keys, and subclasses can also alter the
387 * key depending on the entry itself.
388 * @return string Message key
390 protected function getMessageKey() {
391 $type = $this->entry->getType();
392 $subtype = $this->entry->getSubtype();
394 return "logentry-$type-$subtype";
398 * Returns extra links that comes after the action text, like "revert", etc.
400 * @return string
402 public function getActionLinks() {
403 return '';
407 * Extracts the optional extra parameters for use in action messages.
408 * The array indexes start from number 3.
409 * @return array
411 protected function extractParameters() {
412 $entry = $this->entry;
413 $params = array();
415 if ( $entry->isLegacy() ) {
416 foreach ( $entry->getParameters() as $index => $value ) {
417 $params[$index + 3] = $value;
421 // Filter out parameters which are not in format #:foo
422 foreach ( $entry->getParameters() as $key => $value ) {
423 if ( strpos( $key, ':' ) === false ) {
424 continue;
426 list( $index, $type, ) = explode( ':', $key, 3 );
427 $params[$index - 1] = $this->formatParameterValue( $type, $value );
430 /* Message class doesn't like non consecutive numbering.
431 * Fill in missing indexes with empty strings to avoid
432 * incorrect renumbering.
434 if ( count( $params ) ) {
435 $max = max( array_keys( $params ) );
436 for ( $i = 4; $i < $max; $i++ ) {
437 if ( !isset( $params[$i] ) ) {
438 $params[$i] = '';
443 return $params;
447 * Formats parameters intented for action message from
448 * array of all parameters. There are three hardcoded
449 * parameters (array is zero-indexed, this list not):
450 * - 1: user name with premade link
451 * - 2: usable for gender magic function
452 * - 3: target page with premade link
453 * @return array
455 protected function getMessageParameters() {
456 if ( isset( $this->parsedParameters ) ) {
457 return $this->parsedParameters;
460 $entry = $this->entry;
461 $params = $this->extractParameters();
462 $params[0] = Message::rawParam( $this->getPerformerElement() );
463 $params[1] = $this->canView( LogPage::DELETED_USER ) ? $entry->getPerformer()->getName() : '';
464 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
466 // Bad things happens if the numbers are not in correct order
467 ksort( $params );
469 $this->parsedParameters = $params;
470 return $this->parsedParameters;
474 * Formats parameters values dependent to their type
475 * @param string $type The type of the value.
476 * Valid are currently:
477 * * - (empty) or plain: The value is returned as-is
478 * * raw: The value will be added to the log message
479 * as raw parameter (e.g. no escaping)
480 * Use this only if there is no other working
481 * type like user-link or title-link
482 * * msg: The value is a message-key, the output is
483 * the message in user language
484 * * msg-content: The value is a message-key, the output
485 * is the message in content language
486 * * user: The value is a user name, e.g. for GENDER
487 * * user-link: The value is a user name, returns a
488 * link for the user
489 * * title: The value is a page title,
490 * returns name of page
491 * * title-link: The value is a page title,
492 * returns link to this page
493 * * number: Format value as number
494 * @param string $value The parameter value that should
495 * be formated
496 * @return string|array Formated value
497 * @since 1.21
499 protected function formatParameterValue( $type, $value ) {
500 $saveLinkFlood = $this->linkFlood;
502 switch ( strtolower( trim( $type ) ) ) {
503 case 'raw':
504 $value = Message::rawParam( $value );
505 break;
506 case 'msg':
507 $value = $this->msg( $value )->text();
508 break;
509 case 'msg-content':
510 $value = $this->msg( $value )->inContentLanguage()->text();
511 break;
512 case 'number':
513 $value = Message::numParam( $value );
514 break;
515 case 'user':
516 $user = User::newFromName( $value );
517 $value = $user->getName();
518 break;
519 case 'user-link':
520 $this->setShowUserToolLinks( false );
522 $user = User::newFromName( $value );
523 $value = Message::rawParam( $this->makeUserLink( $user ) );
525 $this->setShowUserToolLinks( $saveLinkFlood );
526 break;
527 case 'title':
528 $title = Title::newFromText( $value );
529 $value = $title->getPrefixedText();
530 break;
531 case 'title-link':
532 $title = Title::newFromText( $value );
533 $value = Message::rawParam( $this->makePageLink( $title ) );
534 break;
535 case 'plain':
536 // Plain text, nothing to do
537 default:
538 // Catch other types and use the old behavior (return as-is)
541 return $value;
545 * Helper to make a link to the page, taking the plaintext
546 * value in consideration.
547 * @param Title $title The page
548 * @param array $parameters Query parameters
549 * @throws MWException
550 * @return string
552 protected function makePageLink( Title $title = null, $parameters = array() ) {
553 if ( !$this->plaintext ) {
554 $link = Linker::link( $title, null, array(), $parameters );
555 } else {
556 if ( !$title instanceof Title ) {
557 throw new MWException( "Expected title, got null" );
559 $link = '[[' . $title->getPrefixedText() . ']]';
562 return $link;
566 * Provides the name of the user who performed the log action.
567 * Used as part of log action message or standalone, depending
568 * which parts of the log entry has been hidden.
569 * @return string
571 public function getPerformerElement() {
572 if ( $this->canView( LogPage::DELETED_USER ) ) {
573 $performer = $this->entry->getPerformer();
574 $element = $this->makeUserLink( $performer );
575 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
576 $element = $this->styleRestricedElement( $element );
578 } else {
579 $element = $this->getRestrictedElement( 'rev-deleted-user' );
582 return $element;
586 * Gets the user provided comment
587 * @return string HTML
589 public function getComment() {
590 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
591 $comment = Linker::commentBlock( $this->entry->getComment() );
592 // No hard coded spaces thanx
593 $element = ltrim( $comment );
594 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
595 $element = $this->styleRestricedElement( $element );
597 } else {
598 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
601 return $element;
605 * Helper method for displaying restricted element.
606 * @param string $message
607 * @return string HTML or wiki text
609 protected function getRestrictedElement( $message ) {
610 if ( $this->plaintext ) {
611 return $this->msg( $message )->text();
614 $content = $this->msg( $message )->escaped();
615 $attribs = array( 'class' => 'history-deleted' );
617 return Html::rawElement( 'span', $attribs, $content );
621 * Helper method for styling restricted element.
622 * @param string $content
623 * @return string HTML or wiki text
625 protected function styleRestricedElement( $content ) {
626 if ( $this->plaintext ) {
627 return $content;
629 $attribs = array( 'class' => 'history-deleted' );
631 return Html::rawElement( 'span', $attribs, $content );
635 * Shortcut for wfMessage which honors local context.
636 * @param string $key
637 * @return Message
639 protected function msg( $key ) {
640 return $this->context->msg( $key );
643 protected function makeUserLink( User $user ) {
644 if ( $this->plaintext ) {
645 $element = $user->getName();
646 } else {
647 $element = Linker::userLink(
648 $user->getId(),
649 $user->getName()
652 if ( $this->linkFlood ) {
653 $element .= Linker::userToolLinksRedContribs(
654 $user->getId(),
655 $user->getName(),
656 $user->getEditCount()
661 return $element;
665 * @return array Array of titles that should be preloaded with LinkBatch
667 public function getPreloadTitles() {
668 return array();
672 * @return array Output of getMessageParameters() for testing
674 public function getMessageParametersForTesting() {
675 // This function was added because getMessageParameters() is
676 // protected and a change from protected to public caused
677 // problems with extensions
678 return $this->getMessageParameters();
683 * This class formats all log entries for log types
684 * which have not been converted to the new system.
685 * This is not about old log entries which store
686 * parameters in a different format - the new
687 * LogFormatter classes have code to support formatting
688 * those too.
689 * @since 1.19
691 class LegacyLogFormatter extends LogFormatter {
693 * Backward compatibility for extension changing the comment from
694 * the LogLine hook. This will be set by the first call on getComment(),
695 * then it might be modified by the hook when calling getActionLinks(),
696 * so that the modified value will be returned when calling getComment()
697 * a second time.
699 * @var string|null
701 private $comment = null;
704 * Cache for the result of getActionLinks() so that it does not need to
705 * run multiple times depending on the order that getComment() and
706 * getActionLinks() are called.
708 * @var string|null
710 private $revert = null;
712 public function getComment() {
713 if ( $this->comment === null ) {
714 $this->comment = parent::getComment();
717 // Make sure we execute the LogLine hook so that we immediately return
718 // the correct value.
719 if ( $this->revert === null ) {
720 $this->getActionLinks();
723 return $this->comment;
726 protected function getActionMessage() {
727 $entry = $this->entry;
728 $action = LogPage::actionText(
729 $entry->getType(),
730 $entry->getSubtype(),
731 $entry->getTarget(),
732 $this->plaintext ? null : $this->context->getSkin(),
733 (array)$entry->getParameters(),
734 !$this->plaintext // whether to filter [[]] links
737 $performer = $this->getPerformerElement();
738 if ( !$this->irctext ) {
739 $sep = $this->msg( 'word-separator' );
740 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
741 $action = $performer . $sep . $action;
744 return $action;
747 public function getActionLinks() {
748 if ( $this->revert !== null ) {
749 return $this->revert;
752 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
753 $this->revert = '';
754 return $this->revert;
757 $title = $this->entry->getTarget();
758 $type = $this->entry->getType();
759 $subtype = $this->entry->getSubtype();
761 // Show unblock/change block link
762 if ( ( $type == 'block' || $type == 'suppress' )
763 && ( $subtype == 'block' || $subtype == 'reblock' )
765 if ( !$this->context->getUser()->isAllowed( 'block' ) ) {
766 return '';
769 $links = array(
770 Linker::linkKnown(
771 SpecialPage::getTitleFor( 'Unblock', $title->getDBkey() ),
772 $this->msg( 'unblocklink' )->escaped()
774 Linker::linkKnown(
775 SpecialPage::getTitleFor( 'Block', $title->getDBkey() ),
776 $this->msg( 'change-blocklink' )->escaped()
780 return $this->msg( 'parentheses' )->rawParams(
781 $this->context->getLanguage()->pipeList( $links ) )->escaped();
782 // Show change protection link
783 } elseif ( $type == 'protect'
784 && ( $subtype == 'protect' || $subtype == 'modify' || $subtype == 'unprotect' )
786 $links = array(
787 Linker::link( $title,
788 $this->msg( 'hist' )->escaped(),
789 array(),
790 array(
791 'action' => 'history',
792 'offset' => $this->entry->getTimestamp()
796 if ( $this->context->getUser()->isAllowed( 'protect' ) ) {
797 $links[] = Linker::linkKnown(
798 $title,
799 $this->msg( 'protect_change' )->escaped(),
800 array(),
801 array( 'action' => 'protect' )
805 return $this->msg( 'parentheses' )->rawParams(
806 $this->context->getLanguage()->pipeList( $links ) )->escaped();
809 // Do nothing. The implementation is handled by the hook modifiying the
810 // passed-by-ref parameters. This also changes the default value so that
811 // getComment() and getActionLinks() do not call them indefinitely.
812 $this->revert = '';
814 // This is to populate the $comment member of this instance so that it
815 // can be modified when calling the hook just below.
816 if ( $this->comment === null ) {
817 $this->getComment();
820 $params = $this->entry->getParameters();
822 Hooks::run( 'LogLine', array( $type, $subtype, $title, $params,
823 &$this->comment, &$this->revert, $this->entry->getTimestamp() ) );
825 return $this->revert;