Merge "Check normalization rules of usernames during signup"
[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 = $wgLogActionsHandlers[$fulltype] ?? $wgLogActionsHandlers[$wildcard] ?? '';
55
56 if ( $handler !== '' && is_string( $handler ) && class_exists( $handler ) ) {
57 return new $handler( $entry );
58 }
59
60 return new LegacyLogFormatter( $entry );
61 }
62
63 /**
64 * Handy shortcut for constructing a formatter directly from
65 * database row.
66 * @param stdClass|array $row
67 * @see DatabaseLogEntry::getSelectQueryData
68 * @return LogFormatter
69 */
70 public static function newFromRow( $row ) {
71 return self::newFromEntry( DatabaseLogEntry::newFromRow( $row ) );
72 }
73
74 // Nonstatic->
75
76 /** @var LogEntryBase */
77 protected $entry;
78
79 /** @var int Constant for handling log_deleted */
80 protected $audience = self::FOR_PUBLIC;
81
82 /** @var IContextSource Context for logging */
83 public $context;
84
85 /** @var bool Whether to output user tool links */
86 protected $linkFlood = false;
87
88 /**
89 * Set to true if we are constructing a message text that is going to
90 * be included in page history or send to IRC feed. Links are replaced
91 * with plaintext or with [[pagename]] kind of syntax, that is parsed
92 * by page histories and IRC feeds.
93 * @var string
94 */
95 protected $plaintext = false;
96
97 /** @var string */
98 protected $irctext = false;
99
100 /**
101 * @var LinkRenderer|null
102 */
103 private $linkRenderer;
104
105 /**
106 * @see LogFormatter::getMessageParameters
107 * @var array
108 */
109 protected $parsedParameters;
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 * @return-taint tainted
187 */
188 public function getPlainActionText() {
189 $this->plaintext = true;
190 $text = $this->getActionText();
191 $this->plaintext = false;
192
193 return $text;
194 }
195
196 /**
197 * Even uglier hack to maintain backwards compatibility with IRC bots
198 * (T36508).
199 * @see getActionText()
200 * @return string Text
201 */
202 public function getIRCActionComment() {
203 $actionComment = $this->getIRCActionText();
204 $comment = $this->entry->getComment();
205
206 if ( $comment != '' ) {
207 if ( $actionComment == '' ) {
208 $actionComment = $comment;
209 } else {
210 $actionComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
211 }
212 }
213
214 return $actionComment;
215 }
216
217 /**
218 * Even uglier hack to maintain backwards compatibility with IRC bots
219 * (T36508).
220 * @see getActionText()
221 * @return string Text
222 */
223 public function getIRCActionText() {
224 $this->plaintext = true;
225 $this->irctext = true;
226
227 $entry = $this->entry;
228 $parameters = $entry->getParameters();
229 // @see LogPage::actionText()
230 // Text of title the action is aimed at.
231 $target = $entry->getTarget()->getPrefixedText();
232 $text = null;
233 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
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 case 'revert':
333 $text = wfMessage( 'overwroteimage' )
334 ->rawParams( $target )->inContentLanguage()->escaped();
335 break;
336 }
337 break;
338
339 case 'rights':
340 if ( count( $parameters['4::oldgroups'] ) ) {
341 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
342 } else {
343 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
344 }
345 if ( count( $parameters['5::newgroups'] ) ) {
346 $newgroups = implode( ', ', $parameters['5::newgroups'] );
347 } else {
348 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
349 }
350 switch ( $entry->getSubtype() ) {
351 case 'rights':
352 $text = wfMessage( 'rightslogentry' )
353 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
354 break;
355 case 'autopromote':
356 $text = wfMessage( 'rightslogentry-autopromote' )
357 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
358 break;
359 }
360 break;
361
362 case 'merge':
363 $text = wfMessage( 'pagemerge-logentry' )
364 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
365 ->inContentLanguage()->escaped();
366 break;
367
368 case 'block':
369 switch ( $entry->getSubtype() ) {
370 case 'block':
371 // Keep compatibility with extensions by checking for
372 // new key (5::duration/6::flags) or old key (0/optional 1)
373 if ( $entry->isLegacy() ) {
374 $rawDuration = $parameters[0];
375 $rawFlags = $parameters[1] ?? '';
376 } else {
377 $rawDuration = $parameters['5::duration'];
378 $rawFlags = $parameters['6::flags'];
379 }
380 $duration = $contLang->translateBlockExpiry(
381 $rawDuration,
382 null,
383 wfTimestamp( TS_UNIX, $entry->getTimestamp() )
384 );
385 $flags = BlockLogFormatter::formatBlockFlags( $rawFlags, $contLang );
386 $text = wfMessage( 'blocklogentry' )
387 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
388 break;
389 case 'unblock':
390 $text = wfMessage( 'unblocklogentry' )
391 ->rawParams( $target )->inContentLanguage()->escaped();
392 break;
393 case 'reblock':
394 $duration = $contLang->translateBlockExpiry(
395 $parameters['5::duration'],
396 null,
397 wfTimestamp( TS_UNIX, $entry->getTimestamp() )
398 );
399 $flags = BlockLogFormatter::formatBlockFlags( $parameters['6::flags'],
400 $contLang );
401 $text = wfMessage( 'reblock-logentry' )
402 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
403 break;
404 }
405 break;
406
407 case 'import':
408 switch ( $entry->getSubtype() ) {
409 case 'upload':
410 $text = wfMessage( 'import-logentry-upload' )
411 ->rawParams( $target )->inContentLanguage()->escaped();
412 break;
413 case 'interwiki':
414 $text = wfMessage( 'import-logentry-interwiki' )
415 ->rawParams( $target )->inContentLanguage()->escaped();
416 break;
417 }
418 break;
419 // case 'suppress' --private log -- aaron (so we know who to blame in a few years :-D)
420 // default:
421 }
422 if ( is_null( $text ) ) {
423 $text = $this->getPlainActionText();
424 }
425
426 $this->plaintext = false;
427 $this->irctext = false;
428
429 return $text;
430 }
431
432 /**
433 * Gets the log action, including username.
434 * @return string HTML
435 * phan-taint-check gets very confused by $this->plaintext, so disable.
436 * @return-taint onlysafefor_html
437 */
438 public function getActionText() {
439 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
440 $element = $this->getActionMessage();
441 if ( $element instanceof Message ) {
442 $element = $this->plaintext ? $element->text() : $element->escaped();
443 }
444 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
445 $element = $this->styleRestricedElement( $element );
446 }
447 } else {
448 $sep = $this->msg( 'word-separator' );
449 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
450 $performer = $this->getPerformerElement();
451 $element = $performer . $sep . $this->getRestrictedElement( 'rev-deleted-event' );
452 }
453
454 return $element;
455 }
456
457 /**
458 * Returns a sentence describing the log action. Usually
459 * a Message object is returned, but old style log types
460 * and entries might return pre-escaped HTML string.
461 * @return Message|string Pre-escaped HTML
462 */
463 protected function getActionMessage() {
464 $message = $this->msg( $this->getMessageKey() );
465 $message->params( $this->getMessageParameters() );
466
467 return $message;
468 }
469
470 /**
471 * Returns a key to be used for formatting the action sentence.
472 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
473 * types will use custom keys, and subclasses can also alter the
474 * key depending on the entry itself.
475 * @return string Message key
476 */
477 protected function getMessageKey() {
478 $type = $this->entry->getType();
479 $subtype = $this->entry->getSubtype();
480
481 return "logentry-$type-$subtype";
482 }
483
484 /**
485 * Returns extra links that comes after the action text, like "revert", etc.
486 *
487 * @return string
488 */
489 public function getActionLinks() {
490 return '';
491 }
492
493 /**
494 * Extracts the optional extra parameters for use in action messages.
495 * The array indexes start from number 3.
496 * @return array
497 */
498 protected function extractParameters() {
499 $entry = $this->entry;
500 $params = [];
501
502 if ( $entry->isLegacy() ) {
503 foreach ( $entry->getParameters() as $index => $value ) {
504 $params[$index + 3] = $value;
505 }
506 }
507
508 // Filter out parameters which are not in format #:foo
509 foreach ( $entry->getParameters() as $key => $value ) {
510 if ( strpos( $key, ':' ) === false ) {
511 continue;
512 }
513 list( $index, $type, ) = explode( ':', $key, 3 );
514 if ( ctype_digit( $index ) ) {
515 $params[$index - 1] = $this->formatParameterValue( $type, $value );
516 }
517 }
518
519 /* Message class doesn't like non consecutive numbering.
520 * Fill in missing indexes with empty strings to avoid
521 * incorrect renumbering.
522 */
523 if ( count( $params ) ) {
524 $max = max( array_keys( $params ) );
525 // index 0 to 2 are added in getMessageParameters
526 for ( $i = 3; $i < $max; $i++ ) {
527 if ( !isset( $params[$i] ) ) {
528 $params[$i] = '';
529 }
530 }
531 }
532
533 return $params;
534 }
535
536 /**
537 * Formats parameters intented for action message from
538 * array of all parameters. There are three hardcoded
539 * parameters (array is zero-indexed, this list not):
540 * - 1: user name with premade link
541 * - 2: usable for gender magic function
542 * - 3: target page with premade link
543 * @return array
544 */
545 protected function getMessageParameters() {
546 if ( isset( $this->parsedParameters ) ) {
547 return $this->parsedParameters;
548 }
549
550 $entry = $this->entry;
551 $params = $this->extractParameters();
552 $params[0] = Message::rawParam( $this->getPerformerElement() );
553 $params[1] = $this->canView( LogPage::DELETED_USER ) ? $entry->getPerformer()->getName() : '';
554 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
555
556 // Bad things happens if the numbers are not in correct order
557 ksort( $params );
558
559 $this->parsedParameters = $params;
560 return $this->parsedParameters;
561 }
562
563 /**
564 * Formats parameters values dependent to their type
565 * @param string $type The type of the value.
566 * Valid are currently:
567 * * - (empty) or plain: The value is returned as-is
568 * * raw: The value will be added to the log message
569 * as raw parameter (e.g. no escaping)
570 * Use this only if there is no other working
571 * type like user-link or title-link
572 * * msg: The value is a message-key, the output is
573 * the message in user language
574 * * msg-content: The value is a message-key, the output
575 * is the message in content language
576 * * user: The value is a user name, e.g. for GENDER
577 * * user-link: The value is a user name, returns a
578 * link for the user
579 * * title: The value is a page title,
580 * returns name of page
581 * * title-link: The value is a page title,
582 * returns link to this page
583 * * number: Format value as number
584 * * list: Format value as a comma-separated list
585 * @param mixed $value The parameter value that should be formatted
586 * @return string|array Formated value
587 * @since 1.21
588 */
589 protected function formatParameterValue( $type, $value ) {
590 $saveLinkFlood = $this->linkFlood;
591
592 switch ( strtolower( trim( $type ) ) ) {
593 case 'raw':
594 $value = Message::rawParam( $value );
595 break;
596 case 'list':
597 $value = $this->context->getLanguage()->commaList( $value );
598 break;
599 case 'msg':
600 $value = $this->msg( $value )->text();
601 break;
602 case 'msg-content':
603 $value = $this->msg( $value )->inContentLanguage()->text();
604 break;
605 case 'number':
606 $value = Message::numParam( $value );
607 break;
608 case 'user':
609 $user = User::newFromName( $value );
610 $value = $user->getName();
611 break;
612 case 'user-link':
613 $this->setShowUserToolLinks( false );
614
615 $user = User::newFromName( $value );
616 $value = Message::rawParam( $this->makeUserLink( $user ) );
617
618 $this->setShowUserToolLinks( $saveLinkFlood );
619 break;
620 case 'title':
621 $title = Title::newFromText( $value );
622 $value = $title->getPrefixedText();
623 break;
624 case 'title-link':
625 $title = Title::newFromText( $value );
626 $value = Message::rawParam( $this->makePageLink( $title ) );
627 break;
628 case 'plain':
629 // Plain text, nothing to do
630 default:
631 // Catch other types and use the old behavior (return as-is)
632 }
633
634 return $value;
635 }
636
637 /**
638 * Helper to make a link to the page, taking the plaintext
639 * value in consideration.
640 * @param Title|null $title The page
641 * @param array $parameters Query parameters
642 * @param string|null $html Linktext of the link as raw html
643 * @return string
644 */
645 protected function makePageLink( Title $title = null, $parameters = [], $html = null ) {
646 if ( !$title instanceof Title ) {
647 $msg = $this->msg( 'invalidtitle' )->text();
648 if ( $this->plaintext ) {
649 return $msg;
650 } else {
651 return Html::element( 'span', [ 'class' => 'mw-invalidtitle' ], $msg );
652 }
653 }
654
655 if ( $this->plaintext ) {
656 $link = '[[' . $title->getPrefixedText() . ']]';
657 } else {
658 $html = $html !== null ? new HtmlArmor( $html ) : $html;
659 $link = $this->getLinkRenderer()->makeLink( $title, $html, [], $parameters );
660 }
661
662 return $link;
663 }
664
665 /**
666 * Provides the name of the user who performed the log action.
667 * Used as part of log action message or standalone, depending
668 * which parts of the log entry has been hidden.
669 * @return string
670 */
671 public function getPerformerElement() {
672 if ( $this->canView( LogPage::DELETED_USER ) ) {
673 $performer = $this->entry->getPerformer();
674 $element = $this->makeUserLink( $performer );
675 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
676 $element = $this->styleRestricedElement( $element );
677 }
678 } else {
679 $element = $this->getRestrictedElement( 'rev-deleted-user' );
680 }
681
682 return $element;
683 }
684
685 /**
686 * Gets the user provided comment
687 * @return string HTML
688 */
689 public function getComment() {
690 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
691 $comment = Linker::commentBlock( $this->entry->getComment() );
692 // No hard coded spaces thanx
693 $element = ltrim( $comment );
694 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
695 $element = $this->styleRestricedElement( $element );
696 }
697 } else {
698 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
699 }
700
701 return $element;
702 }
703
704 /**
705 * Helper method for displaying restricted element.
706 * @param string $message
707 * @return string HTML or wiki text
708 * @return-taint onlysafefor_html
709 */
710 protected function getRestrictedElement( $message ) {
711 if ( $this->plaintext ) {
712 return $this->msg( $message )->text();
713 }
714
715 $content = $this->msg( $message )->escaped();
716 $attribs = [ 'class' => 'history-deleted' ];
717
718 return Html::rawElement( 'span', $attribs, $content );
719 }
720
721 /**
722 * Helper method for styling restricted element.
723 * @param string $content
724 * @return string HTML or wiki text
725 */
726 protected function styleRestricedElement( $content ) {
727 if ( $this->plaintext ) {
728 return $content;
729 }
730 $attribs = [ 'class' => 'history-deleted' ];
731
732 return Html::rawElement( 'span', $attribs, $content );
733 }
734
735 /**
736 * Shortcut for wfMessage which honors local context.
737 * @param string $key
738 * @return Message
739 */
740 protected function msg( $key ) {
741 return $this->context->msg( $key );
742 }
743
744 /**
745 * @param User $user
746 * @param int $toolFlags Combination of Linker::TOOL_LINKS_* flags
747 * @return string wikitext or html
748 * @return-taint onlysafefor_html
749 */
750 protected function makeUserLink( User $user, $toolFlags = 0 ) {
751 if ( $this->plaintext ) {
752 $element = $user->getName();
753 } else {
754 $element = Linker::userLink(
755 $user->getId(),
756 $user->getName()
757 );
758
759 if ( $this->linkFlood ) {
760 $element .= Linker::userToolLinks(
761 $user->getId(),
762 $user->getName(),
763 true, // redContribsWhenNoEdits
764 $toolFlags,
765 $user->getEditCount()
766 );
767 }
768 }
769
770 return $element;
771 }
772
773 /**
774 * @return array Array of titles that should be preloaded with LinkBatch
775 */
776 public function getPreloadTitles() {
777 return [];
778 }
779
780 /**
781 * @return array Output of getMessageParameters() for testing
782 */
783 public function getMessageParametersForTesting() {
784 // This function was added because getMessageParameters() is
785 // protected and a change from protected to public caused
786 // problems with extensions
787 return $this->getMessageParameters();
788 }
789
790 /**
791 * Get the array of parameters, converted from legacy format if necessary.
792 * @since 1.25
793 * @return array
794 */
795 protected function getParametersForApi() {
796 return $this->entry->getParameters();
797 }
798
799 /**
800 * Format parameters for API output
801 *
802 * The result array should generally map named keys to values. Index and
803 * type should be omitted, e.g. "4::foo" should be returned as "foo" in the
804 * output. Values should generally be unformatted.
805 *
806 * Renames or removals of keys besides from the legacy numeric format to
807 * modern named style should be avoided. Any renames should be announced to
808 * the mediawiki-api-announce mailing list.
809 *
810 * @since 1.25
811 * @return array
812 */
813 public function formatParametersForApi() {
814 $logParams = [];
815 foreach ( $this->getParametersForApi() as $key => $value ) {
816 $vals = explode( ':', $key, 3 );
817 if ( count( $vals ) !== 3 ) {
818 $logParams[$key] = $value;
819 continue;
820 }
821 $logParams += $this->formatParameterValueForApi( $vals[2], $vals[1], $value );
822 }
823 ApiResult::setIndexedTagName( $logParams, 'param' );
824 ApiResult::setArrayType( $logParams, 'assoc' );
825
826 return $logParams;
827 }
828
829 /**
830 * Format a single parameter value for API output
831 *
832 * @since 1.25
833 * @param string $name
834 * @param string $type
835 * @param string $value
836 * @return array
837 */
838 protected function formatParameterValueForApi( $name, $type, $value ) {
839 $type = strtolower( trim( $type ) );
840 switch ( $type ) {
841 case 'bool':
842 $value = (bool)$value;
843 break;
844
845 case 'number':
846 if ( ctype_digit( $value ) || is_int( $value ) ) {
847 $value = (int)$value;
848 } else {
849 $value = (float)$value;
850 }
851 break;
852
853 case 'array':
854 case 'assoc':
855 case 'kvp':
856 if ( is_array( $value ) ) {
857 ApiResult::setArrayType( $value, $type );
858 }
859 break;
860
861 case 'timestamp':
862 $value = wfTimestamp( TS_ISO_8601, $value );
863 break;
864
865 case 'msg':
866 case 'msg-content':
867 $msg = $this->msg( $value );
868 if ( $type === 'msg-content' ) {
869 $msg->inContentLanguage();
870 }
871 $value = [];
872 $value["{$name}_key"] = $msg->getKey();
873 if ( $msg->getParams() ) {
874 $value["{$name}_params"] = $msg->getParams();
875 }
876 $value["{$name}_text"] = $msg->text();
877 return $value;
878
879 case 'title':
880 case 'title-link':
881 $title = Title::newFromText( $value );
882 if ( !$title ) {
883 // Huh? Do something halfway sane.
884 $title = SpecialPage::getTitleFor( 'Badtitle', $value );
885 }
886 $value = [];
887 ApiQueryBase::addTitleInfo( $value, $title, "{$name}_" );
888 return $value;
889
890 case 'user':
891 case 'user-link':
892 $user = User::newFromName( $value );
893 if ( $user ) {
894 $value = $user->getName();
895 }
896 break;
897
898 default:
899 // do nothing
900 break;
901 }
902
903 return [ $name => $value ];
904 }
905 }
906
907 /**
908 * This class formats all log entries for log types
909 * which have not been converted to the new system.
910 * This is not about old log entries which store
911 * parameters in a different format - the new
912 * LogFormatter classes have code to support formatting
913 * those too.
914 * @since 1.19
915 */
916 class LegacyLogFormatter extends LogFormatter {
917 /**
918 * Backward compatibility for extension changing the comment from
919 * the LogLine hook. This will be set by the first call on getComment(),
920 * then it might be modified by the hook when calling getActionLinks(),
921 * so that the modified value will be returned when calling getComment()
922 * a second time.
923 *
924 * @var string|null
925 */
926 private $comment = null;
927
928 /**
929 * Cache for the result of getActionLinks() so that it does not need to
930 * run multiple times depending on the order that getComment() and
931 * getActionLinks() are called.
932 *
933 * @var string|null
934 */
935 private $revert = null;
936
937 public function getComment() {
938 if ( $this->comment === null ) {
939 $this->comment = parent::getComment();
940 }
941
942 // Make sure we execute the LogLine hook so that we immediately return
943 // the correct value.
944 if ( $this->revert === null ) {
945 $this->getActionLinks();
946 }
947
948 return $this->comment;
949 }
950
951 /**
952 * @return string
953 * @return-taint onlysafefor_html
954 */
955 protected function getActionMessage() {
956 $entry = $this->entry;
957 $action = LogPage::actionText(
958 $entry->getType(),
959 $entry->getSubtype(),
960 $entry->getTarget(),
961 $this->plaintext ? null : $this->context->getSkin(),
962 (array)$entry->getParameters(),
963 !$this->plaintext // whether to filter [[]] links
964 );
965
966 $performer = $this->getPerformerElement();
967 if ( !$this->irctext ) {
968 $sep = $this->msg( 'word-separator' );
969 $sep = $this->plaintext ? $sep->text() : $sep->escaped();
970 $action = $performer . $sep . $action;
971 }
972
973 return $action;
974 }
975
976 public function getActionLinks() {
977 if ( $this->revert !== null ) {
978 return $this->revert;
979 }
980
981 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
982 $this->revert = '';
983 return $this->revert;
984 }
985
986 $title = $this->entry->getTarget();
987 $type = $this->entry->getType();
988 $subtype = $this->entry->getSubtype();
989
990 // Do nothing. The implementation is handled by the hook modifiying the
991 // passed-by-ref parameters. This also changes the default value so that
992 // getComment() and getActionLinks() do not call them indefinitely.
993 $this->revert = '';
994
995 // This is to populate the $comment member of this instance so that it
996 // can be modified when calling the hook just below.
997 if ( $this->comment === null ) {
998 $this->getComment();
999 }
1000
1001 $params = $this->entry->getParameters();
1002
1003 Hooks::run( 'LogLine', [ $type, $subtype, $title, $params,
1004 &$this->comment, &$this->revert, $this->entry->getTimestamp() ] );
1005
1006 return $this->revert;
1007 }
1008 }