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