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 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 = $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|null $title The page
643 * @param array $parameters Query parameters
644 * @param string|null $html Linktext of the link as raw html
645 * @return string
646 */
647 protected function makePageLink( Title $title = null, $parameters = [], $html = null ) {
648 if ( !$title instanceof Title ) {
649 $msg = $this->msg( 'invalidtitle' )->text();
650 if ( !$this->plaintext ) {
651 return Html::element( 'span', [ 'class' => 'mw-invalidtitle' ], $msg );
652 } else {
653 return $msg;
654 }
655 }
656
657 if ( !$this->plaintext ) {
658 $html = $html !== null ? new HtmlArmor( $html ) : $html;
659 $link = $this->getLinkRenderer()->makeLink( $title, $html, [], $parameters );
660 } else {
661 $link = '[[' . $title->getPrefixedText() . ']]';
662 }
663
664 return $link;
665 }
666
667 /**
668 * Provides the name of the user who performed the log action.
669 * Used as part of log action message or standalone, depending
670 * which parts of the log entry has been hidden.
671 * @return string
672 */
673 public function getPerformerElement() {
674 if ( $this->canView( LogPage::DELETED_USER ) ) {
675 $performer = $this->entry->getPerformer();
676 $element = $this->makeUserLink( $performer );
677 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
678 $element = $this->styleRestricedElement( $element );
679 }
680 } else {
681 $element = $this->getRestrictedElement( 'rev-deleted-user' );
682 }
683
684 return $element;
685 }
686
687 /**
688 * Gets the user provided comment
689 * @return string HTML
690 */
691 public function getComment() {
692 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
693 $comment = Linker::commentBlock( $this->entry->getComment() );
694 // No hard coded spaces thanx
695 $element = ltrim( $comment );
696 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
697 $element = $this->styleRestricedElement( $element );
698 }
699 } else {
700 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
701 }
702
703 return $element;
704 }
705
706 /**
707 * Helper method for displaying restricted element.
708 * @param string $message
709 * @return string HTML or wiki text
710 */
711 protected function getRestrictedElement( $message ) {
712 if ( $this->plaintext ) {
713 return $this->msg( $message )->text();
714 }
715
716 $content = $this->msg( $message )->escaped();
717 $attribs = [ 'class' => 'history-deleted' ];
718
719 return Html::rawElement( 'span', $attribs, $content );
720 }
721
722 /**
723 * Helper method for styling restricted element.
724 * @param string $content
725 * @return string HTML or wiki text
726 */
727 protected function styleRestricedElement( $content ) {
728 if ( $this->plaintext ) {
729 return $content;
730 }
731 $attribs = [ 'class' => 'history-deleted' ];
732
733 return Html::rawElement( 'span', $attribs, $content );
734 }
735
736 /**
737 * Shortcut for wfMessage which honors local context.
738 * @param string $key
739 * @return Message
740 */
741 protected function msg( $key ) {
742 return $this->context->msg( $key );
743 }
744
745 protected function makeUserLink( User $user, $toolFlags = 0 ) {
746 if ( $this->plaintext ) {
747 $element = $user->getName();
748 } else {
749 $element = Linker::userLink(
750 $user->getId(),
751 $user->getName()
752 );
753
754 if ( $this->linkFlood ) {
755 $element .= Linker::userToolLinks(
756 $user->getId(),
757 $user->getName(),
758 true, // redContribsWhenNoEdits
759 $toolFlags,
760 $user->getEditCount()
761 );
762 }
763 }
764
765 return $element;
766 }
767
768 /**
769 * @return array Array of titles that should be preloaded with LinkBatch
770 */
771 public function getPreloadTitles() {
772 return [];
773 }
774
775 /**
776 * @return array Output of getMessageParameters() for testing
777 */
778 public function getMessageParametersForTesting() {
779 // This function was added because getMessageParameters() is
780 // protected and a change from protected to public caused
781 // problems with extensions
782 return $this->getMessageParameters();
783 }
784
785 /**
786 * Get the array of parameters, converted from legacy format if necessary.
787 * @since 1.25
788 * @return array
789 */
790 protected function getParametersForApi() {
791 return $this->entry->getParameters();
792 }
793
794 /**
795 * Format parameters for API output
796 *
797 * The result array should generally map named keys to values. Index and
798 * type should be omitted, e.g. "4::foo" should be returned as "foo" in the
799 * output. Values should generally be unformatted.
800 *
801 * Renames or removals of keys besides from the legacy numeric format to
802 * modern named style should be avoided. Any renames should be announced to
803 * the mediawiki-api-announce mailing list.
804 *
805 * @since 1.25
806 * @return array
807 */
808 public function formatParametersForApi() {
809 $logParams = [];
810 foreach ( $this->getParametersForApi() as $key => $value ) {
811 $vals = explode( ':', $key, 3 );
812 if ( count( $vals ) !== 3 ) {
813 $logParams[$key] = $value;
814 continue;
815 }
816 $logParams += $this->formatParameterValueForApi( $vals[2], $vals[1], $value );
817 }
818 ApiResult::setIndexedTagName( $logParams, 'param' );
819 ApiResult::setArrayType( $logParams, 'assoc' );
820
821 return $logParams;
822 }
823
824 /**
825 * Format a single parameter value for API output
826 *
827 * @since 1.25
828 * @param string $name
829 * @param string $type
830 * @param string $value
831 * @return array
832 */
833 protected function formatParameterValueForApi( $name, $type, $value ) {
834 $type = strtolower( trim( $type ) );
835 switch ( $type ) {
836 case 'bool':
837 $value = (bool)$value;
838 break;
839
840 case 'number':
841 if ( ctype_digit( $value ) || is_int( $value ) ) {
842 $value = (int)$value;
843 } else {
844 $value = (float)$value;
845 }
846 break;
847
848 case 'array':
849 case 'assoc':
850 case 'kvp':
851 if ( is_array( $value ) ) {
852 ApiResult::setArrayType( $value, $type );
853 }
854 break;
855
856 case 'timestamp':
857 $value = wfTimestamp( TS_ISO_8601, $value );
858 break;
859
860 case 'msg':
861 case 'msg-content':
862 $msg = $this->msg( $value );
863 if ( $type === 'msg-content' ) {
864 $msg->inContentLanguage();
865 }
866 $value = [];
867 $value["{$name}_key"] = $msg->getKey();
868 if ( $msg->getParams() ) {
869 $value["{$name}_params"] = $msg->getParams();
870 }
871 $value["{$name}_text"] = $msg->text();
872 return $value;
873
874 case 'title':
875 case 'title-link':
876 $title = Title::newFromText( $value );
877 if ( !$title ) {
878 // Huh? Do something halfway sane.
879 $title = SpecialPage::getTitleFor( 'Badtitle', $value );
880 }
881 $value = [];
882 ApiQueryBase::addTitleInfo( $value, $title, "{$name}_" );
883 return $value;
884
885 case 'user':
886 case 'user-link':
887 $user = User::newFromName( $value );
888 if ( $user ) {
889 $value = $user->getName();
890 }
891 break;
892
893 default:
894 // do nothing
895 break;
896 }
897
898 return [ $name => $value ];
899 }
900 }
901
902 /**
903 * This class formats all log entries for log types
904 * which have not been converted to the new system.
905 * This is not about old log entries which store
906 * parameters in a different format - the new
907 * LogFormatter classes have code to support formatting
908 * those too.
909 * @since 1.19
910 */
911 class LegacyLogFormatter extends LogFormatter {
912 /**
913 * Backward compatibility for extension changing the comment from
914 * the LogLine hook. This will be set by the first call on getComment(),
915 * then it might be modified by the hook when calling getActionLinks(),
916 * so that the modified value will be returned when calling getComment()
917 * a second time.
918 *
919 * @var string|null
920 */
921 private $comment = null;
922
923 /**
924 * Cache for the result of getActionLinks() so that it does not need to
925 * run multiple times depending on the order that getComment() and
926 * getActionLinks() are called.
927 *
928 * @var string|null
929 */
930 private $revert = null;
931
932 public function getComment() {
933 if ( $this->comment === null ) {
934 $this->comment = parent::getComment();
935 }
936
937 // Make sure we execute the LogLine hook so that we immediately return
938 // the correct value.
939 if ( $this->revert === null ) {
940 $this->getActionLinks();
941 }
942
943 return $this->comment;
944 }
945
946 protected function getActionMessage() {
947 $entry = $this->entry;
948 $action = LogPage::actionText(
949 $entry->getType(),
950 $entry->getSubtype(),
951 $entry->getTarget(),
952 $this->plaintext ? null : $this->context->getSkin(),
953 (array)$entry->getParameters(),
954 !$this->plaintext // whether to filter [[]] links
955 );
956
957 $performer = $this->getPerformerElement();
958 if ( !$this->irctext ) {
959 $sep = $this->msg( 'word-separator' );
960 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
961 $action = $performer . $sep . $action;
962 }
963
964 return $action;
965 }
966
967 public function getActionLinks() {
968 if ( $this->revert !== null ) {
969 return $this->revert;
970 }
971
972 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
973 $this->revert = '';
974 return $this->revert;
975 }
976
977 $title = $this->entry->getTarget();
978 $type = $this->entry->getType();
979 $subtype = $this->entry->getSubtype();
980
981 // Do nothing. The implementation is handled by the hook modifiying the
982 // passed-by-ref parameters. This also changes the default value so that
983 // getComment() and getActionLinks() do not call them indefinitely.
984 $this->revert = '';
985
986 // This is to populate the $comment member of this instance so that it
987 // can be modified when calling the hook just below.
988 if ( $this->comment === null ) {
989 $this->getComment();
990 }
991
992 $params = $this->entry->getParameters();
993
994 Hooks::run( 'LogLine', [ $type, $subtype, $title, $params,
995 &$this->comment, &$this->revert, $this->entry->getTimestamp() ] );
996
997 return $this->revert;
998 }
999 }