Implement extension registration from an extension.json file
[mediawiki.git] / includes / logging / LogFormatter.php
blobc6fcdb0d4acec54ccba3f44a94c3837b02b8dcd1
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 $sep = $this->msg( 'word-separator' );
359 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
360 $performer = $this->getPerformerElement();
361 $element = $performer . $sep . $this->getRestrictedElement( 'rev-deleted-event' );
364 return $element;
368 * Returns a sentence describing the log action. Usually
369 * a Message object is returned, but old style log types
370 * and entries might return pre-escaped HTML string.
371 * @return Message|string Pre-escaped HTML
373 protected function getActionMessage() {
374 $message = $this->msg( $this->getMessageKey() );
375 $message->params( $this->getMessageParameters() );
377 return $message;
381 * Returns a key to be used for formatting the action sentence.
382 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
383 * types will use custom keys, and subclasses can also alter the
384 * key depending on the entry itself.
385 * @return string Message key
387 protected function getMessageKey() {
388 $type = $this->entry->getType();
389 $subtype = $this->entry->getSubtype();
391 return "logentry-$type-$subtype";
395 * Returns extra links that comes after the action text, like "revert", etc.
397 * @return string
399 public function getActionLinks() {
400 return '';
404 * Extracts the optional extra parameters for use in action messages.
405 * The array indexes start from number 3.
406 * @return array
408 protected function extractParameters() {
409 $entry = $this->entry;
410 $params = array();
412 if ( $entry->isLegacy() ) {
413 foreach ( $entry->getParameters() as $index => $value ) {
414 $params[$index + 3] = $value;
418 // Filter out parameters which are not in format #:foo
419 foreach ( $entry->getParameters() as $key => $value ) {
420 if ( strpos( $key, ':' ) === false ) {
421 continue;
423 list( $index, $type, ) = explode( ':', $key, 3 );
424 $params[$index - 1] = $this->formatParameterValue( $type, $value );
427 /* Message class doesn't like non consecutive numbering.
428 * Fill in missing indexes with empty strings to avoid
429 * incorrect renumbering.
431 if ( count( $params ) ) {
432 $max = max( array_keys( $params ) );
433 for ( $i = 4; $i < $max; $i++ ) {
434 if ( !isset( $params[$i] ) ) {
435 $params[$i] = '';
440 return $params;
444 * Formats parameters intented for action message from
445 * array of all parameters. There are three hardcoded
446 * parameters (array is zero-indexed, this list not):
447 * - 1: user name with premade link
448 * - 2: usable for gender magic function
449 * - 3: target page with premade link
450 * @return array
452 protected function getMessageParameters() {
453 if ( isset( $this->parsedParameters ) ) {
454 return $this->parsedParameters;
457 $entry = $this->entry;
458 $params = $this->extractParameters();
459 $params[0] = Message::rawParam( $this->getPerformerElement() );
460 $params[1] = $this->canView( LogPage::DELETED_USER ) ? $entry->getPerformer()->getName() : '';
461 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
463 // Bad things happens if the numbers are not in correct order
464 ksort( $params );
466 $this->parsedParameters = $params;
467 return $this->parsedParameters;
471 * Formats parameters values dependent to their type
472 * @param string $type The type of the value.
473 * Valid are currently:
474 * * - (empty) or plain: The value is returned as-is
475 * * raw: The value will be added to the log message
476 * as raw parameter (e.g. no escaping)
477 * Use this only if there is no other working
478 * type like user-link or title-link
479 * * msg: The value is a message-key, the output is
480 * the message in user language
481 * * msg-content: The value is a message-key, the output
482 * is the message in content language
483 * * user: The value is a user name, e.g. for GENDER
484 * * user-link: The value is a user name, returns a
485 * link for the user
486 * * title: The value is a page title,
487 * returns name of page
488 * * title-link: The value is a page title,
489 * returns link to this page
490 * * number: Format value as number
491 * @param string $value The parameter value that should
492 * be formated
493 * @return string|array Formated value
494 * @since 1.21
496 protected function formatParameterValue( $type, $value ) {
497 $saveLinkFlood = $this->linkFlood;
499 switch ( strtolower( trim( $type ) ) ) {
500 case 'raw':
501 $value = Message::rawParam( $value );
502 break;
503 case 'msg':
504 $value = $this->msg( $value )->text();
505 break;
506 case 'msg-content':
507 $value = $this->msg( $value )->inContentLanguage()->text();
508 break;
509 case 'number':
510 $value = Message::numParam( $value );
511 break;
512 case 'user':
513 $user = User::newFromName( $value );
514 $value = $user->getName();
515 break;
516 case 'user-link':
517 $this->setShowUserToolLinks( false );
519 $user = User::newFromName( $value );
520 $value = Message::rawParam( $this->makeUserLink( $user ) );
522 $this->setShowUserToolLinks( $saveLinkFlood );
523 break;
524 case 'title':
525 $title = Title::newFromText( $value );
526 $value = $title->getPrefixedText();
527 break;
528 case 'title-link':
529 $title = Title::newFromText( $value );
530 $value = Message::rawParam( $this->makePageLink( $title ) );
531 break;
532 case 'plain':
533 // Plain text, nothing to do
534 default:
535 // Catch other types and use the old behavior (return as-is)
538 return $value;
542 * Helper to make a link to the page, taking the plaintext
543 * value in consideration.
544 * @param Title $title The page
545 * @param array $parameters Query parameters
546 * @throws MWException
547 * @return string
549 protected function makePageLink( Title $title = null, $parameters = array() ) {
550 if ( !$this->plaintext ) {
551 $link = Linker::link( $title, null, array(), $parameters );
552 } else {
553 if ( !$title instanceof Title ) {
554 throw new MWException( "Expected title, got null" );
556 $link = '[[' . $title->getPrefixedText() . ']]';
559 return $link;
563 * Provides the name of the user who performed the log action.
564 * Used as part of log action message or standalone, depending
565 * which parts of the log entry has been hidden.
566 * @return string
568 public function getPerformerElement() {
569 if ( $this->canView( LogPage::DELETED_USER ) ) {
570 $performer = $this->entry->getPerformer();
571 $element = $this->makeUserLink( $performer );
572 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
573 $element = $this->styleRestricedElement( $element );
575 } else {
576 $element = $this->getRestrictedElement( 'rev-deleted-user' );
579 return $element;
583 * Gets the user provided comment
584 * @return string HTML
586 public function getComment() {
587 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
588 $comment = Linker::commentBlock( $this->entry->getComment() );
589 // No hard coded spaces thanx
590 $element = ltrim( $comment );
591 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
592 $element = $this->styleRestricedElement( $element );
594 } else {
595 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
598 return $element;
602 * Helper method for displaying restricted element.
603 * @param string $message
604 * @return string HTML or wiki text
606 protected function getRestrictedElement( $message ) {
607 if ( $this->plaintext ) {
608 return $this->msg( $message )->text();
611 $content = $this->msg( $message )->escaped();
612 $attribs = array( 'class' => 'history-deleted' );
614 return Html::rawElement( 'span', $attribs, $content );
618 * Helper method for styling restricted element.
619 * @param string $content
620 * @return string HTML or wiki text
622 protected function styleRestricedElement( $content ) {
623 if ( $this->plaintext ) {
624 return $content;
626 $attribs = array( 'class' => 'history-deleted' );
628 return Html::rawElement( 'span', $attribs, $content );
632 * Shortcut for wfMessage which honors local context.
633 * @param string $key
634 * @return Message
636 protected function msg( $key ) {
637 return $this->context->msg( $key );
640 protected function makeUserLink( User $user ) {
641 if ( $this->plaintext ) {
642 $element = $user->getName();
643 } else {
644 $element = Linker::userLink(
645 $user->getId(),
646 $user->getName()
649 if ( $this->linkFlood ) {
650 $element .= Linker::userToolLinksRedContribs(
651 $user->getId(),
652 $user->getName(),
653 $user->getEditCount()
658 return $element;
662 * @return array Array of titles that should be preloaded with LinkBatch
664 public function getPreloadTitles() {
665 return array();
669 * @return array Output of getMessageParameters() for testing
671 public function getMessageParametersForTesting() {
672 // This function was added because getMessageParameters() is
673 // protected and a change from protected to public caused
674 // problems with extensions
675 return $this->getMessageParameters();
680 * This class formats all log entries for log types
681 * which have not been converted to the new system.
682 * This is not about old log entries which store
683 * parameters in a different format - the new
684 * LogFormatter classes have code to support formatting
685 * those too.
686 * @since 1.19
688 class LegacyLogFormatter extends LogFormatter {
690 * Backward compatibility for extension changing the comment from
691 * the LogLine hook. This will be set by the first call on getComment(),
692 * then it might be modified by the hook when calling getActionLinks(),
693 * so that the modified value will be returned when calling getComment()
694 * a second time.
696 * @var string|null
698 private $comment = null;
701 * Cache for the result of getActionLinks() so that it does not need to
702 * run multiple times depending on the order that getComment() and
703 * getActionLinks() are called.
705 * @var string|null
707 private $revert = null;
709 public function getComment() {
710 if ( $this->comment === null ) {
711 $this->comment = parent::getComment();
714 // Make sure we execute the LogLine hook so that we immediately return
715 // the correct value.
716 if ( $this->revert === null ) {
717 $this->getActionLinks();
720 return $this->comment;
723 protected function getActionMessage() {
724 $entry = $this->entry;
725 $action = LogPage::actionText(
726 $entry->getType(),
727 $entry->getSubtype(),
728 $entry->getTarget(),
729 $this->plaintext ? null : $this->context->getSkin(),
730 (array)$entry->getParameters(),
731 !$this->plaintext // whether to filter [[]] links
734 $performer = $this->getPerformerElement();
735 if ( !$this->irctext ) {
736 $sep = $this->msg( 'word-separator' );
737 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
738 $action = $performer . $sep . $action;
741 return $action;
744 public function getActionLinks() {
745 if ( $this->revert !== null ) {
746 return $this->revert;
749 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
750 $this->revert = '';
751 return $this->revert;
754 $title = $this->entry->getTarget();
755 $type = $this->entry->getType();
756 $subtype = $this->entry->getSubtype();
758 // Show unblock/change block link
759 if ( ( $type == 'block' || $type == 'suppress' )
760 && ( $subtype == 'block' || $subtype == 'reblock' )
762 if ( !$this->context->getUser()->isAllowed( 'block' ) ) {
763 return '';
766 $links = array(
767 Linker::linkKnown(
768 SpecialPage::getTitleFor( 'Unblock', $title->getDBkey() ),
769 $this->msg( 'unblocklink' )->escaped()
771 Linker::linkKnown(
772 SpecialPage::getTitleFor( 'Block', $title->getDBkey() ),
773 $this->msg( 'change-blocklink' )->escaped()
777 return $this->msg( 'parentheses' )->rawParams(
778 $this->context->getLanguage()->pipeList( $links ) )->escaped();
779 // Show change protection link
780 } elseif ( $type == 'protect'
781 && ( $subtype == 'protect' || $subtype == 'modify' || $subtype == 'unprotect' )
783 $links = array(
784 Linker::link( $title,
785 $this->msg( 'hist' )->escaped(),
786 array(),
787 array(
788 'action' => 'history',
789 'offset' => $this->entry->getTimestamp()
793 if ( $this->context->getUser()->isAllowed( 'protect' ) ) {
794 $links[] = Linker::linkKnown(
795 $title,
796 $this->msg( 'protect_change' )->escaped(),
797 array(),
798 array( 'action' => 'protect' )
802 return $this->msg( 'parentheses' )->rawParams(
803 $this->context->getLanguage()->pipeList( $links ) )->escaped();
806 // Do nothing. The implementation is handled by the hook modifiying the
807 // passed-by-ref parameters. This also changes the default value so that
808 // getComment() and getActionLinks() do not call them indefinitely.
809 $this->revert = '';
811 // This is to populate the $comment member of this instance so that it
812 // can be modified when calling the hook just below.
813 if ( $this->comment === null ) {
814 $this->getComment();
817 $params = $this->entry->getParameters();
819 Hooks::run( 'LogLine', array( $type, $subtype, $title, $params,
820 &$this->comment, &$this->revert, $this->entry->getTimestamp() ) );
822 return $this->revert;