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