Debian Codegraph @

includes/logging/LogFormatter.php

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