Fix MediaWiki.Commenting.LicenseComment.InvalidLicenseTag errors
[lhc/web/wiklou.git] / includes / logging / LogFormatter.php
1 <?php
2 /**
3 * Contains classes for formatting log entries
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Niklas Laxström
22 * @license GPL-2.0-or-later
23 * @since 1.19
24 */
25 use MediaWiki\Linker\LinkRenderer;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Implements the default log formatting.
30 *
31 * Can be overridden by subclassing and setting:
32 *
33 * $wgLogActionsHandlers['type/subtype'] = 'class'; or
34 * $wgLogActionsHandlers['type/*'] = 'class';
35 *
36 * @since 1.19
37 */
38 class LogFormatter {
39 // Audience options for viewing usernames, comments, and actions
40 const FOR_PUBLIC = 1;
41 const FOR_THIS_USER = 2;
42
43 // Static->
44
45 /**
46 * Constructs a new formatter suitable for given entry.
47 * @param LogEntry $entry
48 * @return LogFormatter
49 */
50 public static function newFromEntry( LogEntry $entry ) {
51 global $wgLogActionsHandlers;
52 $fulltype = $entry->getFullType();
53 $wildcard = $entry->getType() . '/*';
54 $handler = '';
55
56 if ( isset( $wgLogActionsHandlers[$fulltype] ) ) {
57 $handler = $wgLogActionsHandlers[$fulltype];
58 } elseif ( isset( $wgLogActionsHandlers[$wildcard] ) ) {
59 $handler = $wgLogActionsHandlers[$wildcard];
60 }
61
62 if ( $handler !== '' && is_string( $handler ) && class_exists( $handler ) ) {
63 return new $handler( $entry );
64 }
65
66 return new LegacyLogFormatter( $entry );
67 }
68
69 /**
70 * Handy shortcut for constructing a formatter directly from
71 * database row.
72 * @param stdClass|array $row
73 * @see DatabaseLogEntry::getSelectQueryData
74 * @return LogFormatter
75 */
76 public static function newFromRow( $row ) {
77 return self::newFromEntry( DatabaseLogEntry::newFromRow( $row ) );
78 }
79
80 // Nonstatic->
81
82 /** @var LogEntryBase */
83 protected $entry;
84
85 /** @var int Constant for handling log_deleted */
86 protected $audience = self::FOR_PUBLIC;
87
88 /** @var IContextSource Context for logging */
89 public $context;
90
91 /** @var bool Whether to output user tool links */
92 protected $linkFlood = false;
93
94 /**
95 * Set to true if we are constructing a message text that is going to
96 * be included in page history or send to IRC feed. Links are replaced
97 * with plaintext or with [[pagename]] kind of syntax, that is parsed
98 * by page histories and IRC feeds.
99 * @var string
100 */
101 protected $plaintext = false;
102
103 /** @var string */
104 protected $irctext = false;
105
106 /**
107 * @var LinkRenderer|null
108 */
109 private $linkRenderer;
110
111 /**
112 * @see LogFormatter::getMessageParameters
113 * @var array
114 */
115 protected $parsedParameters;
116
117 protected function __construct( LogEntry $entry ) {
118 $this->entry = $entry;
119 $this->context = RequestContext::getMain();
120 }
121
122 /**
123 * Replace the default context
124 * @param IContextSource $context
125 */
126 public function setContext( IContextSource $context ) {
127 $this->context = $context;
128 }
129
130 /**
131 * @since 1.30
132 * @param LinkRenderer $linkRenderer
133 */
134 public function setLinkRenderer( LinkRenderer $linkRenderer ) {
135 $this->linkRenderer = $linkRenderer;
136 }
137
138 /**
139 * @since 1.30
140 * @return LinkRenderer
141 */
142 public function getLinkRenderer() {
143 if ( $this->linkRenderer !== null ) {
144 return $this->linkRenderer;
145 } else {
146 return MediaWikiServices::getInstance()->getLinkRenderer();
147 }
148 }
149
150 /**
151 * Set the visibility restrictions for displaying content.
152 * If set to public, and an item is deleted, then it will be replaced
153 * with a placeholder even if the context user is allowed to view it.
154 * @param int $audience Const self::FOR_THIS_USER or self::FOR_PUBLIC
155 */
156 public function setAudience( $audience ) {
157 $this->audience = ( $audience == self::FOR_THIS_USER )
158 ? self::FOR_THIS_USER
159 : self::FOR_PUBLIC;
160 }
161
162 /**
163 * Check if a log item can be displayed
164 * @param int $field LogPage::DELETED_* constant
165 * @return bool
166 */
167 protected function canView( $field ) {
168 if ( $this->audience == self::FOR_THIS_USER ) {
169 return LogEventsList::userCanBitfield(
170 $this->entry->getDeleted(), $field, $this->context->getUser() );
171 } else {
172 return !$this->entry->isDeleted( $field );
173 }
174 }
175
176 /**
177 * If set to true, will produce user tool links after
178 * the user name. This should be replaced with generic
179 * CSS/JS solution.
180 * @param bool $value
181 */
182 public function setShowUserToolLinks( $value ) {
183 $this->linkFlood = $value;
184 }
185
186 /**
187 * Ugly hack to produce plaintext version of the message.
188 * Usually you also want to set extraneous request context
189 * to avoid formatting for any particular user.
190 * @see getActionText()
191 * @return string Plain text
192 */
193 public function getPlainActionText() {
194 $this->plaintext = true;
195 $text = $this->getActionText();
196 $this->plaintext = false;
197
198 return $text;
199 }
200
201 /**
202 * Even uglier hack to maintain backwards compatibility with IRC bots
203 * (T36508).
204 * @see getActionText()
205 * @return string Text
206 */
207 public function getIRCActionComment() {
208 $actionComment = $this->getIRCActionText();
209 $comment = $this->entry->getComment();
210
211 if ( $comment != '' ) {
212 if ( $actionComment == '' ) {
213 $actionComment = $comment;
214 } else {
215 $actionComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
216 }
217 }
218
219 return $actionComment;
220 }
221
222 /**
223 * Even uglier hack to maintain backwards compatibility with IRC bots
224 * (T36508).
225 * @see getActionText()
226 * @return string Text
227 */
228 public function getIRCActionText() {
229 global $wgContLang;
230
231 $this->plaintext = true;
232 $this->irctext = true;
233
234 $entry = $this->entry;
235 $parameters = $entry->getParameters();
236 // @see LogPage::actionText()
237 // Text of title the action is aimed at.
238 $target = $entry->getTarget()->getPrefixedText();
239 $text = null;
240 switch ( $entry->getType() ) {
241 case 'move':
242 switch ( $entry->getSubtype() ) {
243 case 'move':
244 $movesource = $parameters['4::target'];
245 $text = wfMessage( '1movedto2' )
246 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
247 break;
248 case 'move_redir':
249 $movesource = $parameters['4::target'];
250 $text = wfMessage( '1movedto2_redir' )
251 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
252 break;
253 case 'move-noredirect':
254 break;
255 case 'move_redir-noredirect':
256 break;
257 }
258 break;
259
260 case 'delete':
261 switch ( $entry->getSubtype() ) {
262 case 'delete':
263 $text = wfMessage( 'deletedarticle' )
264 ->rawParams( $target )->inContentLanguage()->escaped();
265 break;
266 case 'restore':
267 $text = wfMessage( 'undeletedarticle' )
268 ->rawParams( $target )->inContentLanguage()->escaped();
269 break;
270 //case 'revision': // Revision deletion
271 //case 'event': // Log deletion
272 // see https://github.com/wikimedia/mediawiki/commit/a9c243b7b5289dad204278dbe7ed571fd914e395
273 //default:
274 }
275 break;
276
277 case 'patrol':
278 // https://github.com/wikimedia/mediawiki/commit/1a05f8faf78675dc85984f27f355b8825b43efff
279 // Create a diff link to the patrolled revision
280 if ( $entry->getSubtype() === 'patrol' ) {
281 $diffLink = htmlspecialchars(
282 wfMessage( 'patrol-log-diff', $parameters['4::curid'] )
283 ->inContentLanguage()->text() );
284 $text = wfMessage( 'patrol-log-line', $diffLink, "[[$target]]", "" )
285 ->inContentLanguage()->text();
286 } else {
287 // broken??
288 }
289 break;
290
291 case 'protect':
292 switch ( $entry->getSubtype() ) {
293 case 'protect':
294 $text = wfMessage( 'protectedarticle' )
295 ->rawParams( $target . ' ' . $parameters['4::description'] )->inContentLanguage()->escaped();
296 break;
297 case 'unprotect':
298 $text = wfMessage( 'unprotectedarticle' )
299 ->rawParams( $target )->inContentLanguage()->escaped();
300 break;
301 case 'modify':
302 $text = wfMessage( 'modifiedarticleprotection' )
303 ->rawParams( $target . ' ' . $parameters['4::description'] )->inContentLanguage()->escaped();
304 break;
305 case 'move_prot':
306 $text = wfMessage( 'movedarticleprotection' )
307 ->rawParams( $target, $parameters['4::oldtitle'] )->inContentLanguage()->escaped();
308 break;
309 }
310 break;
311
312 case 'newusers':
313 switch ( $entry->getSubtype() ) {
314 case 'newusers':
315 case 'create':
316 $text = wfMessage( 'newuserlog-create-entry' )
317 ->inContentLanguage()->escaped();
318 break;
319 case 'create2':
320 case 'byemail':
321 $text = wfMessage( 'newuserlog-create2-entry' )
322 ->rawParams( $target )->inContentLanguage()->escaped();
323 break;
324 case 'autocreate':
325 $text = wfMessage( 'newuserlog-autocreate-entry' )
326 ->inContentLanguage()->escaped();
327 break;
328 }
329 break;
330
331 case 'upload':
332 switch ( $entry->getSubtype() ) {
333 case 'upload':
334 $text = wfMessage( 'uploadedimage' )
335 ->rawParams( $target )->inContentLanguage()->escaped();
336 break;
337 case 'overwrite':
338 $text = wfMessage( 'overwroteimage' )
339 ->rawParams( $target )->inContentLanguage()->escaped();
340 break;
341 }
342 break;
343
344 case 'rights':
345 if ( count( $parameters['4::oldgroups'] ) ) {
346 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
347 } else {
348 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
349 }
350 if ( count( $parameters['5::newgroups'] ) ) {
351 $newgroups = implode( ', ', $parameters['5::newgroups'] );
352 } else {
353 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
354 }
355 switch ( $entry->getSubtype() ) {
356 case 'rights':
357 $text = wfMessage( 'rightslogentry' )
358 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
359 break;
360 case 'autopromote':
361 $text = wfMessage( 'rightslogentry-autopromote' )
362 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
363 break;
364 }
365 break;
366
367 case 'merge':
368 $text = wfMessage( 'pagemerge-logentry' )
369 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
370 ->inContentLanguage()->escaped();
371 break;
372
373 case 'block':
374 switch ( $entry->getSubtype() ) {
375 case 'block':
376 // Keep compatibility with extensions by checking for
377 // new key (5::duration/6::flags) or old key (0/optional 1)
378 if ( $entry->isLegacy() ) {
379 $rawDuration = $parameters[0];
380 $rawFlags = isset( $parameters[1] ) ? $parameters[1] : '';
381 } else {
382 $rawDuration = $parameters['5::duration'];
383 $rawFlags = $parameters['6::flags'];
384 }
385 $duration = $wgContLang->translateBlockExpiry(
386 $rawDuration,
387 null,
388 wfTimestamp( TS_UNIX, $entry->getTimestamp() )
389 );
390 $flags = BlockLogFormatter::formatBlockFlags( $rawFlags, $wgContLang );
391 $text = wfMessage( 'blocklogentry' )
392 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
393 break;
394 case 'unblock':
395 $text = wfMessage( 'unblocklogentry' )
396 ->rawParams( $target )->inContentLanguage()->escaped();
397 break;
398 case 'reblock':
399 $duration = $wgContLang->translateBlockExpiry(
400 $parameters['5::duration'],
401 null,
402 wfTimestamp( TS_UNIX, $entry->getTimestamp() )
403 );
404 $flags = BlockLogFormatter::formatBlockFlags( $parameters['6::flags'], $wgContLang );
405 $text = wfMessage( 'reblock-logentry' )
406 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
407 break;
408 }
409 break;
410
411 case 'import':
412 switch ( $entry->getSubtype() ) {
413 case 'upload':
414 $text = wfMessage( 'import-logentry-upload' )
415 ->rawParams( $target )->inContentLanguage()->escaped();
416 break;
417 case 'interwiki':
418 $text = wfMessage( 'import-logentry-interwiki' )
419 ->rawParams( $target )->inContentLanguage()->escaped();
420 break;
421 }
422 break;
423 // case 'suppress' --private log -- aaron (so we know who to blame in a few years :-D)
424 // default:
425 }
426 if ( is_null( $text ) ) {
427 $text = $this->getPlainActionText();
428 }
429
430 $this->plaintext = false;
431 $this->irctext = false;
432
433 return $text;
434 }
435
436 /**
437 * Gets the log action, including username.
438 * @return string HTML
439 */
440 public function getActionText() {
441 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
442 $element = $this->getActionMessage();
443 if ( $element instanceof Message ) {
444 $element = $this->plaintext ? $element->text() : $element->escaped();
445 }
446 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
447 $element = $this->styleRestricedElement( $element );
448 }
449 } else {
450 $sep = $this->msg( 'word-separator' );
451 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
452 $performer = $this->getPerformerElement();
453 $element = $performer . $sep . $this->getRestrictedElement( 'rev-deleted-event' );
454 }
455
456 return $element;
457 }
458
459 /**
460 * Returns a sentence describing the log action. Usually
461 * a Message object is returned, but old style log types
462 * and entries might return pre-escaped HTML string.
463 * @return Message|string Pre-escaped HTML
464 */
465 protected function getActionMessage() {
466 $message = $this->msg( $this->getMessageKey() );
467 $message->params( $this->getMessageParameters() );
468
469 return $message;
470 }
471
472 /**
473 * Returns a key to be used for formatting the action sentence.
474 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
475 * types will use custom keys, and subclasses can also alter the
476 * key depending on the entry itself.
477 * @return string Message key
478 */
479 protected function getMessageKey() {
480 $type = $this->entry->getType();
481 $subtype = $this->entry->getSubtype();
482
483 return "logentry-$type-$subtype";
484 }
485
486 /**
487 * Returns extra links that comes after the action text, like "revert", etc.
488 *
489 * @return string
490 */
491 public function getActionLinks() {
492 return '';
493 }
494
495 /**
496 * Extracts the optional extra parameters for use in action messages.
497 * The array indexes start from number 3.
498 * @return array
499 */
500 protected function extractParameters() {
501 $entry = $this->entry;
502 $params = [];
503
504 if ( $entry->isLegacy() ) {
505 foreach ( $entry->getParameters() as $index => $value ) {
506 $params[$index + 3] = $value;
507 }
508 }
509
510 // Filter out parameters which are not in format #:foo
511 foreach ( $entry->getParameters() as $key => $value ) {
512 if ( strpos( $key, ':' ) === false ) {
513 continue;
514 }
515 list( $index, $type, ) = explode( ':', $key, 3 );
516 if ( ctype_digit( $index ) ) {
517 $params[$index - 1] = $this->formatParameterValue( $type, $value );
518 }
519 }
520
521 /* Message class doesn't like non consecutive numbering.
522 * Fill in missing indexes with empty strings to avoid
523 * incorrect renumbering.
524 */
525 if ( count( $params ) ) {
526 $max = max( array_keys( $params ) );
527 // index 0 to 2 are added in getMessageParameters
528 for ( $i = 3; $i < $max; $i++ ) {
529 if ( !isset( $params[$i] ) ) {
530 $params[$i] = '';
531 }
532 }
533 }
534
535 return $params;
536 }
537
538 /**
539 * Formats parameters intented for action message from
540 * array of all parameters. There are three hardcoded
541 * parameters (array is zero-indexed, this list not):
542 * - 1: user name with premade link
543 * - 2: usable for gender magic function
544 * - 3: target page with premade link
545 * @return array
546 */
547 protected function getMessageParameters() {
548 if ( isset( $this->parsedParameters ) ) {
549 return $this->parsedParameters;
550 }
551
552 $entry = $this->entry;
553 $params = $this->extractParameters();
554 $params[0] = Message::rawParam( $this->getPerformerElement() );
555 $params[1] = $this->canView( LogPage::DELETED_USER ) ? $entry->getPerformer()->getName() : '';
556 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
557
558 // Bad things happens if the numbers are not in correct order
559 ksort( $params );
560
561 $this->parsedParameters = $params;
562 return $this->parsedParameters;
563 }
564
565 /**
566 * Formats parameters values dependent to their type
567 * @param string $type The type of the value.
568 * Valid are currently:
569 * * - (empty) or plain: The value is returned as-is
570 * * raw: The value will be added to the log message
571 * as raw parameter (e.g. no escaping)
572 * Use this only if there is no other working
573 * type like user-link or title-link
574 * * msg: The value is a message-key, the output is
575 * the message in user language
576 * * msg-content: The value is a message-key, the output
577 * is the message in content language
578 * * user: The value is a user name, e.g. for GENDER
579 * * user-link: The value is a user name, returns a
580 * link for the user
581 * * title: The value is a page title,
582 * returns name of page
583 * * title-link: The value is a page title,
584 * returns link to this page
585 * * number: Format value as number
586 * * list: Format value as a comma-separated list
587 * @param mixed $value The parameter value that should be formatted
588 * @return string|array Formated value
589 * @since 1.21
590 */
591 protected function formatParameterValue( $type, $value ) {
592 $saveLinkFlood = $this->linkFlood;
593
594 switch ( strtolower( trim( $type ) ) ) {
595 case 'raw':
596 $value = Message::rawParam( $value );
597 break;
598 case 'list':
599 $value = $this->context->getLanguage()->commaList( $value );
600 break;
601 case 'msg':
602 $value = $this->msg( $value )->text();
603 break;
604 case 'msg-content':
605 $value = $this->msg( $value )->inContentLanguage()->text();
606 break;
607 case 'number':
608 $value = Message::numParam( $value );
609 break;
610 case 'user':
611 $user = User::newFromName( $value );
612 $value = $user->getName();
613 break;
614 case 'user-link':
615 $this->setShowUserToolLinks( false );
616
617 $user = User::newFromName( $value );
618 $value = Message::rawParam( $this->makeUserLink( $user ) );
619
620 $this->setShowUserToolLinks( $saveLinkFlood );
621 break;
622 case 'title':
623 $title = Title::newFromText( $value );
624 $value = $title->getPrefixedText();
625 break;
626 case 'title-link':
627 $title = Title::newFromText( $value );
628 $value = Message::rawParam( $this->makePageLink( $title ) );
629 break;
630 case 'plain':
631 // Plain text, nothing to do
632 default:
633 // Catch other types and use the old behavior (return as-is)
634 }
635
636 return $value;
637 }
638
639 /**
640 * Helper to make a link to the page, taking the plaintext
641 * value in consideration.
642 * @param Title $title The page
643 * @param array $parameters Query parameters
644 * @param string|null $html Linktext of the link as raw html
645 * @throws MWException
646 * @return string
647 */
648 protected function makePageLink( Title $title = null, $parameters = [], $html = null ) {
649 if ( !$title instanceof Title ) {
650 throw new MWException( 'Expected title, got null' );
651 }
652 if ( !$this->plaintext ) {
653 $html = $html !== null ? new HtmlArmor( $html ) : $html;
654 $link = $this->getLinkRenderer()->makeLink( $title, $html, [], $parameters );
655 } else {
656 $link = '[[' . $title->getPrefixedText() . ']]';
657 }
658
659 return $link;
660 }
661
662 /**
663 * Provides the name of the user who performed the log action.
664 * Used as part of log action message or standalone, depending
665 * which parts of the log entry has been hidden.
666 * @return string
667 */
668 public function getPerformerElement() {
669 if ( $this->canView( LogPage::DELETED_USER ) ) {
670 $performer = $this->entry->getPerformer();
671 $element = $this->makeUserLink( $performer );
672 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
673 $element = $this->styleRestricedElement( $element );
674 }
675 } else {
676 $element = $this->getRestrictedElement( 'rev-deleted-user' );
677 }
678
679 return $element;
680 }
681
682 /**
683 * Gets the user provided comment
684 * @return string HTML
685 */
686 public function getComment() {
687 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
688 $comment = Linker::commentBlock( $this->entry->getComment() );
689 // No hard coded spaces thanx
690 $element = ltrim( $comment );
691 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
692 $element = $this->styleRestricedElement( $element );
693 }
694 } else {
695 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
696 }
697
698 return $element;
699 }
700
701 /**
702 * Helper method for displaying restricted element.
703 * @param string $message
704 * @return string HTML or wiki text
705 */
706 protected function getRestrictedElement( $message ) {
707 if ( $this->plaintext ) {
708 return $this->msg( $message )->text();
709 }
710
711 $content = $this->msg( $message )->escaped();
712 $attribs = [ 'class' => 'history-deleted' ];
713
714 return Html::rawElement( 'span', $attribs, $content );
715 }
716
717 /**
718 * Helper method for styling restricted element.
719 * @param string $content
720 * @return string HTML or wiki text
721 */
722 protected function styleRestricedElement( $content ) {
723 if ( $this->plaintext ) {
724 return $content;
725 }
726 $attribs = [ 'class' => 'history-deleted' ];
727
728 return Html::rawElement( 'span', $attribs, $content );
729 }
730
731 /**
732 * Shortcut for wfMessage which honors local context.
733 * @param string $key
734 * @return Message
735 */
736 protected function msg( $key ) {
737 return $this->context->msg( $key );
738 }
739
740 protected function makeUserLink( User $user, $toolFlags = 0 ) {
741 if ( $this->plaintext ) {
742 $element = $user->getName();
743 } else {
744 $element = Linker::userLink(
745 $user->getId(),
746 $user->getName()
747 );
748
749 if ( $this->linkFlood ) {
750 $element .= Linker::userToolLinks(
751 $user->getId(),
752 $user->getName(),
753 true, // redContribsWhenNoEdits
754 $toolFlags,
755 $user->getEditCount()
756 );
757 }
758 }
759
760 return $element;
761 }
762
763 /**
764 * @return array Array of titles that should be preloaded with LinkBatch
765 */
766 public function getPreloadTitles() {
767 return [];
768 }
769
770 /**
771 * @return array Output of getMessageParameters() for testing
772 */
773 public function getMessageParametersForTesting() {
774 // This function was added because getMessageParameters() is
775 // protected and a change from protected to public caused
776 // problems with extensions
777 return $this->getMessageParameters();
778 }
779
780 /**
781 * Get the array of parameters, converted from legacy format if necessary.
782 * @since 1.25
783 * @return array
784 */
785 protected function getParametersForApi() {
786 return $this->entry->getParameters();
787 }
788
789 /**
790 * Format parameters for API output
791 *
792 * The result array should generally map named keys to values. Index and
793 * type should be omitted, e.g. "4::foo" should be returned as "foo" in the
794 * output. Values should generally be unformatted.
795 *
796 * Renames or removals of keys besides from the legacy numeric format to
797 * modern named style should be avoided. Any renames should be announced to
798 * the mediawiki-api-announce mailing list.
799 *
800 * @since 1.25
801 * @return array
802 */
803 public function formatParametersForApi() {
804 $logParams = [];
805 foreach ( $this->getParametersForApi() as $key => $value ) {
806 $vals = explode( ':', $key, 3 );
807 if ( count( $vals ) !== 3 ) {
808 $logParams[$key] = $value;
809 continue;
810 }
811 $logParams += $this->formatParameterValueForApi( $vals[2], $vals[1], $value );
812 }
813 ApiResult::setIndexedTagName( $logParams, 'param' );
814 ApiResult::setArrayType( $logParams, 'assoc' );
815
816 return $logParams;
817 }
818
819 /**
820 * Format a single parameter value for API output
821 *
822 * @since 1.25
823 * @param string $name
824 * @param string $type
825 * @param string $value
826 * @return array
827 */
828 protected function formatParameterValueForApi( $name, $type, $value ) {
829 $type = strtolower( trim( $type ) );
830 switch ( $type ) {
831 case 'bool':
832 $value = (bool)$value;
833 break;
834
835 case 'number':
836 if ( ctype_digit( $value ) || is_int( $value ) ) {
837 $value = (int)$value;
838 } else {
839 $value = (float)$value;
840 }
841 break;
842
843 case 'array':
844 case 'assoc':
845 case 'kvp':
846 if ( is_array( $value ) ) {
847 ApiResult::setArrayType( $value, $type );
848 }
849 break;
850
851 case 'timestamp':
852 $value = wfTimestamp( TS_ISO_8601, $value );
853 break;
854
855 case 'msg':
856 case 'msg-content':
857 $msg = $this->msg( $value );
858 if ( $type === 'msg-content' ) {
859 $msg->inContentLanguage();
860 }
861 $value = [];
862 $value["{$name}_key"] = $msg->getKey();
863 if ( $msg->getParams() ) {
864 $value["{$name}_params"] = $msg->getParams();
865 }
866 $value["{$name}_text"] = $msg->text();
867 return $value;
868
869 case 'title':
870 case 'title-link':
871 $title = Title::newFromText( $value );
872 if ( !$title ) {
873 // Huh? Do something halfway sane.
874 $title = SpecialPage::getTitleFor( 'Badtitle', $value );
875 }
876 $value = [];
877 ApiQueryBase::addTitleInfo( $value, $title, "{$name}_" );
878 return $value;
879
880 case 'user':
881 case 'user-link':
882 $user = User::newFromName( $value );
883 if ( $user ) {
884 $value = $user->getName();
885 }
886 break;
887
888 default:
889 // do nothing
890 break;
891 }
892
893 return [ $name => $value ];
894 }
895 }
896
897 /**
898 * This class formats all log entries for log types
899 * which have not been converted to the new system.
900 * This is not about old log entries which store
901 * parameters in a different format - the new
902 * LogFormatter classes have code to support formatting
903 * those too.
904 * @since 1.19
905 */
906 class LegacyLogFormatter extends LogFormatter {
907 /**
908 * Backward compatibility for extension changing the comment from
909 * the LogLine hook. This will be set by the first call on getComment(),
910 * then it might be modified by the hook when calling getActionLinks(),
911 * so that the modified value will be returned when calling getComment()
912 * a second time.
913 *
914 * @var string|null
915 */
916 private $comment = null;
917
918 /**
919 * Cache for the result of getActionLinks() so that it does not need to
920 * run multiple times depending on the order that getComment() and
921 * getActionLinks() are called.
922 *
923 * @var string|null
924 */
925 private $revert = null;
926
927 public function getComment() {
928 if ( $this->comment === null ) {
929 $this->comment = parent::getComment();
930 }
931
932 // Make sure we execute the LogLine hook so that we immediately return
933 // the correct value.
934 if ( $this->revert === null ) {
935 $this->getActionLinks();
936 }
937
938 return $this->comment;
939 }
940
941 protected function getActionMessage() {
942 $entry = $this->entry;
943 $action = LogPage::actionText(
944 $entry->getType(),
945 $entry->getSubtype(),
946 $entry->getTarget(),
947 $this->plaintext ? null : $this->context->getSkin(),
948 (array)$entry->getParameters(),
949 !$this->plaintext // whether to filter [[]] links
950 );
951
952 $performer = $this->getPerformerElement();
953 if ( !$this->irctext ) {
954 $sep = $this->msg( 'word-separator' );
955 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
956 $action = $performer . $sep . $action;
957 }
958
959 return $action;
960 }
961
962 public function getActionLinks() {
963 if ( $this->revert !== null ) {
964 return $this->revert;
965 }
966
967 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
968 $this->revert = '';
969 return $this->revert;
970 }
971
972 $title = $this->entry->getTarget();
973 $type = $this->entry->getType();
974 $subtype = $this->entry->getSubtype();
975
976 // Do nothing. The implementation is handled by the hook modifiying the
977 // passed-by-ref parameters. This also changes the default value so that
978 // getComment() and getActionLinks() do not call them indefinitely.
979 $this->revert = '';
980
981 // This is to populate the $comment member of this instance so that it
982 // can be modified when calling the hook just below.
983 if ( $this->comment === null ) {
984 $this->getComment();
985 }
986
987 $params = $this->entry->getParameters();
988
989 Hooks::run( 'LogLine', [ $type, $subtype, $title, $params,
990 &$this->comment, &$this->revert, $this->entry->getTimestamp() ] );
991
992 return $this->revert;
993 }
994 }