Merge "Force phan-taint-check to think LogFormatter stuff is safe for html"
[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 global $wgContLang;
231
232 $this->plaintext = true;
233 $this->irctext = true;
234
235 $entry = $this->entry;
236 $parameters = $entry->getParameters();
237 // @see LogPage::actionText()
238 // Text of title the action is aimed at.
239 $target = $entry->getTarget()->getPrefixedText();
240 $text = null;
241 switch ( $entry->getType() ) {
242 case 'move':
243 switch ( $entry->getSubtype() ) {
244 case 'move':
245 $movesource = $parameters['4::target'];
246 $text = wfMessage( '1movedto2' )
247 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
248 break;
249 case 'move_redir':
250 $movesource = $parameters['4::target'];
251 $text = wfMessage( '1movedto2_redir' )
252 ->rawParams( $target, $movesource )->inContentLanguage()->escaped();
253 break;
254 case 'move-noredirect':
255 break;
256 case 'move_redir-noredirect':
257 break;
258 }
259 break;
260
261 case 'delete':
262 switch ( $entry->getSubtype() ) {
263 case 'delete':
264 $text = wfMessage( 'deletedarticle' )
265 ->rawParams( $target )->inContentLanguage()->escaped();
266 break;
267 case 'restore':
268 $text = wfMessage( 'undeletedarticle' )
269 ->rawParams( $target )->inContentLanguage()->escaped();
270 break;
271 //case 'revision': // Revision deletion
272 //case 'event': // Log deletion
273 // see https://github.com/wikimedia/mediawiki/commit/a9c243b7b5289dad204278dbe7ed571fd914e395
274 //default:
275 }
276 break;
277
278 case 'patrol':
279 // https://github.com/wikimedia/mediawiki/commit/1a05f8faf78675dc85984f27f355b8825b43efff
280 // Create a diff link to the patrolled revision
281 if ( $entry->getSubtype() === 'patrol' ) {
282 $diffLink = htmlspecialchars(
283 wfMessage( 'patrol-log-diff', $parameters['4::curid'] )
284 ->inContentLanguage()->text() );
285 $text = wfMessage( 'patrol-log-line', $diffLink, "[[$target]]", "" )
286 ->inContentLanguage()->text();
287 } else {
288 // broken??
289 }
290 break;
291
292 case 'protect':
293 switch ( $entry->getSubtype() ) {
294 case 'protect':
295 $text = wfMessage( 'protectedarticle' )
296 ->rawParams( $target . ' ' . $parameters['4::description'] )->inContentLanguage()->escaped();
297 break;
298 case 'unprotect':
299 $text = wfMessage( 'unprotectedarticle' )
300 ->rawParams( $target )->inContentLanguage()->escaped();
301 break;
302 case 'modify':
303 $text = wfMessage( 'modifiedarticleprotection' )
304 ->rawParams( $target . ' ' . $parameters['4::description'] )->inContentLanguage()->escaped();
305 break;
306 case 'move_prot':
307 $text = wfMessage( 'movedarticleprotection' )
308 ->rawParams( $target, $parameters['4::oldtitle'] )->inContentLanguage()->escaped();
309 break;
310 }
311 break;
312
313 case 'newusers':
314 switch ( $entry->getSubtype() ) {
315 case 'newusers':
316 case 'create':
317 $text = wfMessage( 'newuserlog-create-entry' )
318 ->inContentLanguage()->escaped();
319 break;
320 case 'create2':
321 case 'byemail':
322 $text = wfMessage( 'newuserlog-create2-entry' )
323 ->rawParams( $target )->inContentLanguage()->escaped();
324 break;
325 case 'autocreate':
326 $text = wfMessage( 'newuserlog-autocreate-entry' )
327 ->inContentLanguage()->escaped();
328 break;
329 }
330 break;
331
332 case 'upload':
333 switch ( $entry->getSubtype() ) {
334 case 'upload':
335 $text = wfMessage( 'uploadedimage' )
336 ->rawParams( $target )->inContentLanguage()->escaped();
337 break;
338 case 'overwrite':
339 $text = wfMessage( 'overwroteimage' )
340 ->rawParams( $target )->inContentLanguage()->escaped();
341 break;
342 }
343 break;
344
345 case 'rights':
346 if ( count( $parameters['4::oldgroups'] ) ) {
347 $oldgroups = implode( ', ', $parameters['4::oldgroups'] );
348 } else {
349 $oldgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
350 }
351 if ( count( $parameters['5::newgroups'] ) ) {
352 $newgroups = implode( ', ', $parameters['5::newgroups'] );
353 } else {
354 $newgroups = wfMessage( 'rightsnone' )->inContentLanguage()->escaped();
355 }
356 switch ( $entry->getSubtype() ) {
357 case 'rights':
358 $text = wfMessage( 'rightslogentry' )
359 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
360 break;
361 case 'autopromote':
362 $text = wfMessage( 'rightslogentry-autopromote' )
363 ->rawParams( $target, $oldgroups, $newgroups )->inContentLanguage()->escaped();
364 break;
365 }
366 break;
367
368 case 'merge':
369 $text = wfMessage( 'pagemerge-logentry' )
370 ->rawParams( $target, $parameters['4::dest'], $parameters['5::mergepoint'] )
371 ->inContentLanguage()->escaped();
372 break;
373
374 case 'block':
375 switch ( $entry->getSubtype() ) {
376 case 'block':
377 // Keep compatibility with extensions by checking for
378 // new key (5::duration/6::flags) or old key (0/optional 1)
379 if ( $entry->isLegacy() ) {
380 $rawDuration = $parameters[0];
381 $rawFlags = $parameters[1] ?? '';
382 } else {
383 $rawDuration = $parameters['5::duration'];
384 $rawFlags = $parameters['6::flags'];
385 }
386 $duration = $wgContLang->translateBlockExpiry(
387 $rawDuration,
388 null,
389 wfTimestamp( TS_UNIX, $entry->getTimestamp() )
390 );
391 $flags = BlockLogFormatter::formatBlockFlags( $rawFlags, $wgContLang );
392 $text = wfMessage( 'blocklogentry' )
393 ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped();
394 break;
395 case 'unblock':
396 $text = wfMessage( 'unblocklogentry' )
397 ->rawParams( $target )->inContentLanguage()->escaped();
398 break;
399 case 'reblock':
400 $duration = $wgContLang->translateBlockExpiry(
401 $parameters['5::duration'],
402 null,
403 wfTimestamp( TS_UNIX, $entry->getTimestamp() )
404 );
405 $flags = BlockLogFormatter::formatBlockFlags( $parameters['6::flags'], $wgContLang );
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 * @throws MWException
649 * @return string
650 */
651 protected function makePageLink( Title $title = null, $parameters = [], $html = null ) {
652 if ( !$title instanceof Title ) {
653 throw new MWException( 'Expected title, got null' );
654 }
655 if ( !$this->plaintext ) {
656 $html = $html !== null ? new HtmlArmor( $html ) : $html;
657 $link = $this->getLinkRenderer()->makeLink( $title, $html, [], $parameters );
658 } else {
659 $link = '[[' . $title->getPrefixedText() . ']]';
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 }