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