e463c45ab10983a5408355f51f3441a435092364
[lhc/web/wiklou.git] / includes / logging / LogFormatter.php
1 <?php
2 /**
3 * Contains classes for formatting log entries
4 *
5 * @file
6 * @author Niklas Laxström
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
8 * @since 1.19
9 */
10
11 /**
12 * Implements the default log formatting.
13 * Can be overridden by subclassing and setting
14 * $wgLogActionsHandlers['type/subtype'] = 'class'; or
15 * $wgLogActionsHandlers['type/*'] = 'class';
16 * @since 1.19
17 */
18 class LogFormatter {
19 // Audience options for viewing usernames, comments, and actions
20 const FOR_PUBLIC = 1;
21 const FOR_THIS_USER = 2;
22
23 // Static->
24
25 /**
26 * Constructs a new formatter suitable for given entry.
27 * @param $entry LogEntry
28 * @return LogFormatter
29 */
30 public static function newFromEntry( LogEntry $entry ) {
31 global $wgLogActionsHandlers;
32 $fulltype = $entry->getFullType();
33 $wildcard = $entry->getType() . '/*';
34 $handler = '';
35
36 if ( isset( $wgLogActionsHandlers[$fulltype] ) ) {
37 $handler = $wgLogActionsHandlers[$fulltype];
38 } elseif ( isset( $wgLogActionsHandlers[$wildcard] ) ) {
39 $handler = $wgLogActionsHandlers[$wildcard];
40 }
41
42 if ( $handler !== '' && is_string( $handler ) && class_exists( $handler ) ) {
43 return new $handler( $entry );
44 }
45
46 return new LegacyLogFormatter( $entry );
47 }
48
49 /**
50 * Handy shortcut for constructing a formatter directly from
51 * database row.
52 * @param $row
53 * @see DatabaseLogEntry::getSelectQueryData
54 * @return LogFormatter
55 */
56 public static function newFromRow( $row ) {
57 return self::newFromEntry( DatabaseLogEntry::newFromRow( $row ) );
58 }
59
60 // Nonstatic->
61
62 /// @var LogEntry
63 protected $entry;
64
65 /// Integer constant for handling log_deleted
66 protected $audience = self::FOR_PUBLIC;
67
68 /// Whether to output user tool links
69 protected $linkFlood = false;
70
71 /**
72 * Set to true if we are constructing a message text that is going to
73 * be included in page history or send to IRC feed. Links are replaced
74 * with plaintext or with [[pagename]] kind of syntax, that is parsed
75 * by page histories and IRC feeds.
76 * @var boolean
77 */
78 protected $plaintext = false;
79
80 protected $irctext = false;
81
82 protected function __construct( LogEntry $entry ) {
83 $this->entry = $entry;
84 $this->context = RequestContext::getMain();
85 }
86
87 /**
88 * Replace the default context
89 * @param $context IContextSource
90 */
91 public function setContext( IContextSource $context ) {
92 $this->context = $context;
93 }
94
95 /**
96 * Set the visibility restrictions for displaying content.
97 * If set to public, and an item is deleted, then it will be replaced
98 * with a placeholder even if the context user is allowed to view it.
99 * @param $audience integer self::FOR_THIS_USER or self::FOR_PUBLIC
100 */
101 public function setAudience( $audience ) {
102 $this->audience = ( $audience == self::FOR_THIS_USER )
103 ? self::FOR_THIS_USER
104 : self::FOR_PUBLIC;
105 }
106
107 /**
108 * Check if a log item can be displayed
109 * @param $field integer LogPage::DELETED_* constant
110 * @return bool
111 */
112 protected function canView( $field ) {
113 if ( $this->audience == self::FOR_THIS_USER ) {
114 return LogEventsList::userCanBitfield(
115 $this->entry->getDeleted(), $field, $this->context->getUser() );
116 } else {
117 return !$this->entry->isDeleted( $field );
118 }
119 }
120
121 /**
122 * If set to true, will produce user tool links after
123 * the user name. This should be replaced with generic
124 * CSS/JS solution.
125 * @param $value boolean
126 */
127 public function setShowUserToolLinks( $value ) {
128 $this->linkFlood = $value;
129 }
130
131 /**
132 * Ugly hack to produce plaintext version of the message.
133 * Usually you also want to set extraneous request context
134 * to avoid formatting for any particular user.
135 * @see getActionText()
136 * @return string text
137 */
138 public function getPlainActionText() {
139 $this->plaintext = true;
140 $text = $this->getActionText();
141 $this->plaintext = false;
142 return $text;
143 }
144
145 /**
146 * Even uglier hack to maintain backwards compatibilty with IRC bots
147 * (bug 34508).
148 * @see getActionText()
149 * @return string text
150 */
151 public function getIRCActionComment() {
152 $actionComment = $this->getIRCActionText();
153 $comment = $this->entry->getComment();
154
155 if ( $comment != '' ) {
156 if ( $actionComment == '' ) {
157 $actionComment = $comment;
158 } else {
159 $actionComment .= wfMsgForContent( 'colon-separator' ) . $comment;
160 }
161 }
162
163 return $actionComment;
164 }
165
166 /**
167 * Even uglier hack to maintain backwards compatibilty with IRC bots
168 * (bug 34508).
169 * @see getActionText()
170 * @return string text
171 */
172 public function getIRCActionText() {
173 $this->plaintext = true;
174 $this->irctext = true;
175 $text = $this->getActionText();
176
177 $entry = $this->entry;
178 $parameters = $entry->getParameters();
179 // @see LogPage::actionText()
180 $msgOpts = array( 'parsemag', 'escape', 'replaceafter', 'content' );
181 // Text of title the action is aimed at.
182 $target = $entry->getTarget()->getPrefixedText() ;
183 $text = null;
184 switch( $entry->getType() ) {
185 case 'move':
186 switch( $entry->getSubtype() ) {
187 case 'move':
188 $movesource = $parameters['4::target'];
189 $text = wfMsgExt( '1movedto2', $msgOpts, $target, $movesource );
190 break;
191 case 'move_redir':
192 $movesource = $parameters['4::target'];
193 $text = wfMsgExt( '1movedto2_redir', $msgOpts, $target, $movesource );
194 break;
195 case 'move-noredirect':
196 break;
197 case 'move_redir-noredirect':
198 break;
199 }
200 break;
201
202 case 'delete':
203 switch( $entry->getSubtype() ) {
204 case 'delete':
205 $text = wfMsgExt( 'deletedarticle', $msgOpts, $target );
206 break;
207 case 'restore':
208 $text = wfMsgExt( 'undeletedarticle', $msgOpts, $target );
209 break;
210 //case 'revision': // Revision deletion
211 //case 'event': // Log deletion
212 // see https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/LogPage.php?&pathrev=97044&r1=97043&r2=97044
213 //default:
214 }
215 break;
216
217 case 'patrol':
218 // https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/PatrolLog.php?&pathrev=97495&r1=97494&r2=97495
219 // Create a diff link to the patrolled revision
220 if ( $entry->getSubtype() === 'patrol' ) {
221 $diffLink = htmlspecialchars(
222 wfMsgForContent( 'patrol-log-diff', $parameters['4::curid'] ) );
223 $text = wfMsgForContent( 'patrol-log-line', $diffLink, "[[$target]]", "" );
224 } else {
225 // broken??
226 }
227 break;
228
229 case 'protect':
230 switch( $entry->getSubtype() ) {
231 case 'protect':
232 $text = wfMsgExt( 'protectedarticle', $msgOpts, $target . ' ' . $parameters[0] );
233 break;
234 case 'unprotect':
235 $text = wfMsgExt( 'unprotectedarticle', $msgOpts, $target );
236 break;
237 case 'modify':
238 $text = wfMsgExt( 'modifiedarticleprotection', $msgOpts, $target . ' ' . $parameters[0] );
239 break;
240 }
241 break;
242
243 case 'newusers':
244 switch( $entry->getSubtype() ) {
245 case 'newusers':
246 case 'create':
247 $text = wfMsgExt( 'newuserlog-create-entry', $msgOpts /* no params */ );
248 break;
249 case 'create2':
250 $text = wfMsgExt( 'newuserlog-create2-entry', $msgOpts, $target );
251 break;
252 case 'autocreate':
253 $text = wfMsgExt( 'newuserlog-autocreate-entry', $msgOpts /* no params */ );
254 break;
255 }
256 break;
257
258 case 'upload':
259 switch( $entry->getSubtype() ) {
260 case 'upload':
261 $text = wfMsgExt( 'uploadedimage', $msgOpts, $target );
262 break;
263 case 'overwrite':
264 $text = wfMsgExt( 'overwroteimage', $msgOpts, $target );
265 break;
266 }
267 break;
268
269
270 // case 'suppress' --private log -- aaron (sign your messages so we know who to blame in a few years :-D)
271 // default:
272 }
273 if( is_null( $text ) ) {
274 $text = $this->getPlainActionText();
275 }
276
277 $this->plaintext = false;
278 $this->irctext = false;
279 return $text;
280 }
281
282 /**
283 * Gets the log action, including username.
284 * @return string HTML
285 */
286 public function getActionText() {
287 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
288 $element = $this->getActionMessage();
289 if ( $element instanceof Message ) {
290 $element = $this->plaintext ? $element->text() : $element->escaped();
291 }
292 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
293 $element = $this->styleRestricedElement( $element );
294 }
295 } else {
296 $performer = $this->getPerformerElement() . $this->msg( 'word-separator' )->text();
297 $element = $performer . $this->getRestrictedElement( 'rev-deleted-event' );
298 }
299
300 return $element;
301 }
302
303 /**
304 * Returns a sentence describing the log action. Usually
305 * a Message object is returned, but old style log types
306 * and entries might return pre-escaped html string.
307 * @return Message|string pre-escaped html
308 */
309 protected function getActionMessage() {
310 $message = $this->msg( $this->getMessageKey() );
311 $message->params( $this->getMessageParameters() );
312 return $message;
313 }
314
315 /**
316 * Returns a key to be used for formatting the action sentence.
317 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
318 * types will use custom keys, and subclasses can also alter the
319 * key depending on the entry itself.
320 * @return string message key
321 */
322 protected function getMessageKey() {
323 $type = $this->entry->getType();
324 $subtype = $this->entry->getSubtype();
325
326 return "logentry-$type-$subtype";
327 }
328
329 /**
330 * Extracts the optional extra parameters for use in action messages.
331 * The array indexes start from number 3.
332 * @return array
333 */
334 protected function extractParameters() {
335 $entry = $this->entry;
336 $params = array();
337
338 if ( $entry->isLegacy() ) {
339 foreach ( $entry->getParameters() as $index => $value ) {
340 $params[$index + 3] = $value;
341 }
342 }
343
344 // Filter out parameters which are not in format #:foo
345 foreach ( $entry->getParameters() as $key => $value ) {
346 if ( strpos( $key, ':' ) === false ) continue;
347 list( $index, $type, $name ) = explode( ':', $key, 3 );
348 $params[$index - 1] = $value;
349 }
350
351 /* Message class doesn't like non consecutive numbering.
352 * Fill in missing indexes with empty strings to avoid
353 * incorrect renumbering.
354 */
355 if ( count( $params ) ) {
356 $max = max( array_keys( $params ) );
357 for ( $i = 4; $i < $max; $i++ ) {
358 if ( !isset( $params[$i] ) ) {
359 $params[$i] = '';
360 }
361 }
362 }
363 return $params;
364 }
365
366 /**
367 * Formats parameters intented for action message from
368 * array of all parameters. There are three hardcoded
369 * parameters (array is zero-indexed, this list not):
370 * - 1: user name with premade link
371 * - 2: usable for gender magic function
372 * - 3: target page with premade link
373 * @return array
374 */
375 protected function getMessageParameters() {
376 if ( isset( $this->parsedParameters ) ) {
377 return $this->parsedParameters;
378 }
379
380 $entry = $this->entry;
381 $params = $this->extractParameters();
382 $params[0] = Message::rawParam( $this->getPerformerElement() );
383 $params[1] = $entry->getPerformer()->getName();
384 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
385
386 // Bad things happens if the numbers are not in correct order
387 ksort( $params );
388 return $this->parsedParameters = $params;
389 }
390
391 /**
392 * Helper to make a link to the page, taking the plaintext
393 * value in consideration.
394 * @param $title Title the page
395 * @param $parameters array query parameters
396 * @return String
397 */
398 protected function makePageLink( Title $title = null, $parameters = array() ) {
399 if ( !$this->plaintext ) {
400 $link = Linker::link( $title, null, array(), $parameters );
401 } else {
402 if ( !$title instanceof Title ) {
403 throw new MWException( "Expected title, got null" );
404 }
405 $link = '[[' . $title->getPrefixedText() . ']]';
406 }
407 return $link;
408 }
409
410 /**
411 * Provides the name of the user who performed the log action.
412 * Used as part of log action message or standalone, depending
413 * which parts of the log entry has been hidden.
414 * @return String
415 */
416 public function getPerformerElement() {
417 if ( $this->canView( LogPage::DELETED_USER ) ) {
418 $performer = $this->entry->getPerformer();
419 $element = $this->makeUserLink( $performer );
420 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
421 $element = $this->styleRestricedElement( $element );
422 }
423 } else {
424 $element = $this->getRestrictedElement( 'rev-deleted-user' );
425 }
426
427 return $element;
428 }
429
430 /**
431 * Gets the luser provided comment
432 * @return string HTML
433 */
434 public function getComment() {
435 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
436 $comment = Linker::commentBlock( $this->entry->getComment() );
437 // No hard coded spaces thanx
438 $element = ltrim( $comment );
439 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
440 $element = $this->styleRestricedElement( $element );
441 }
442 } else {
443 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
444 }
445
446 return $element;
447 }
448
449 /**
450 * Helper method for displaying restricted element.
451 * @param $message string
452 * @return string HTML or wikitext
453 */
454 protected function getRestrictedElement( $message ) {
455 if ( $this->plaintext ) {
456 return $this->msg( $message )->text();
457 }
458
459 $content = $this->msg( $message )->escaped();
460 $attribs = array( 'class' => 'history-deleted' );
461 return Html::rawElement( 'span', $attribs, $content );
462 }
463
464 /**
465 * Helper method for styling restricted element.
466 * @param $content string
467 * @return string HTML or wikitext
468 */
469 protected function styleRestricedElement( $content ) {
470 if ( $this->plaintext ) {
471 return $content;
472 }
473 $attribs = array( 'class' => 'history-deleted' );
474 return Html::rawElement( 'span', $attribs, $content );
475 }
476
477 /**
478 * Shortcut for wfMessage which honors local context.
479 * @todo Would it be better to require replacing the global context instead?
480 * @param $key string
481 * @return Message
482 */
483 protected function msg( $key ) {
484 return wfMessage( $key )
485 ->inLanguage( $this->context->getLanguage() )
486 ->title( $this->context->getTitle() );
487 }
488
489 protected function makeUserLink( User $user ) {
490 if ( $this->plaintext ) {
491 $element = $user->getName();
492 } else {
493 $element = Linker::userLink(
494 $user->getId(),
495 $user->getName()
496 );
497
498 if ( $this->linkFlood ) {
499 $element .= Linker::userToolLinks(
500 $user->getId(),
501 $user->getName(),
502 true, // Red if no edits
503 0, // Flags
504 $user->getEditCount()
505 );
506 }
507 }
508 return $element;
509 }
510
511 /**
512 * @return Array of titles that should be preloaded with LinkBatch.
513 */
514 public function getPreloadTitles() {
515 return array();
516 }
517
518 }
519
520 /**
521 * This class formats all log entries for log types
522 * which have not been converted to the new system.
523 * This is not about old log entries which store
524 * parameters in a different format - the new
525 * LogFormatter classes have code to support formatting
526 * those too.
527 * @since 1.19
528 */
529 class LegacyLogFormatter extends LogFormatter {
530 protected function getActionMessage() {
531 $entry = $this->entry;
532 $action = LogPage::actionText(
533 $entry->getType(),
534 $entry->getSubtype(),
535 $entry->getTarget(),
536 $this->plaintext ? null : $this->context->getSkin(),
537 (array)$entry->getParameters(),
538 !$this->plaintext // whether to filter [[]] links
539 );
540
541 $performer = $this->getPerformerElement();
542 if ( !$this->irctext ) {
543 $action = $performer . $this->msg( 'word-separator' )->text() . $action;
544 }
545
546 return $action;
547 }
548
549 }
550
551 /**
552 * This class formats move log entries.
553 * @since 1.19
554 */
555 class MoveLogFormatter extends LogFormatter {
556 public function getPreloadTitles() {
557 $params = $this->extractParameters();
558 return array( Title::newFromText( $params[3] ) );
559 }
560
561 protected function getMessageKey() {
562 $key = parent::getMessageKey();
563 $params = $this->getMessageParameters();
564 if ( isset( $params[4] ) && $params[4] === '1' ) {
565 $key .= '-noredirect';
566 }
567 return $key;
568 }
569
570 protected function getMessageParameters() {
571 $params = parent::getMessageParameters();
572 $oldname = $this->makePageLink( $this->entry->getTarget(), array( 'redirect' => 'no' ) );
573 $newname = $this->makePageLink( Title::newFromText( $params[3] ) );
574 $params[2] = Message::rawParam( $oldname );
575 $params[3] = Message::rawParam( $newname );
576 return $params;
577 }
578 }
579
580 /**
581 * This class formats delete log entries.
582 * @since 1.19
583 */
584 class DeleteLogFormatter extends LogFormatter {
585 protected function getMessageKey() {
586 $key = parent::getMessageKey();
587 if ( in_array( $this->entry->getSubtype(), array( 'event', 'revision' ) ) ) {
588 if ( count( $this->getMessageParameters() ) < 5 ) {
589 return "$key-legacy";
590 }
591 }
592 return $key;
593 }
594
595 protected function getMessageParameters() {
596 if ( isset( $this->parsedParametersDeleteLog ) ) {
597 return $this->parsedParametersDeleteLog;
598 }
599
600 $params = parent::getMessageParameters();
601 $subtype = $this->entry->getSubtype();
602 if ( in_array( $subtype, array( 'event', 'revision' ) ) ) {
603 if (
604 ($subtype === 'event' && count( $params ) === 6 ) ||
605 ($subtype === 'revision' && isset( $params[3] ) && $params[3] === 'revision' )
606 ) {
607 $paramStart = $subtype === 'revision' ? 4 : 3;
608
609 $old = $this->parseBitField( $params[$paramStart+1] );
610 $new = $this->parseBitField( $params[$paramStart+2] );
611 list( $hid, $unhid, $extra ) = RevisionDeleter::getChanges( $new, $old );
612 $changes = array();
613 foreach ( $hid as $v ) {
614 $changes[] = $this->msg( "$v-hid" )->plain();
615 }
616 foreach ( $unhid as $v ) {
617 $changes[] = $this->msg( "$v-unhid" )->plain();
618 }
619 foreach ( $extra as $v ) {
620 $changes[] = $this->msg( $v )->plain();
621 }
622 $changeText = $this->context->getLanguage()->listToText( $changes );
623
624
625 $newParams = array_slice( $params, 0, 3 );
626 $newParams[3] = $changeText;
627 $count = count( explode( ',', $params[$paramStart] ) );
628 $newParams[4] = $this->context->getLanguage()->formatNum( $count );
629 return $this->parsedParametersDeleteLog = $newParams;
630 } else {
631 return $this->parsedParametersDeleteLog = array_slice( $params, 0, 3 );
632 }
633 }
634
635 return $this->parsedParametersDeleteLog = $params;
636 }
637
638 protected function parseBitField( $string ) {
639 // Input is like ofield=2134 or just the number
640 if ( strpos( $string, 'field=' ) === 1 ) {
641 list( , $field ) = explode( '=', $string );
642 return (int) $field;
643 } else {
644 return (int) $string;
645 }
646 }
647 }
648
649 /**
650 * This class formats patrol log entries.
651 * @since 1.19
652 */
653 class PatrolLogFormatter extends LogFormatter {
654 protected function getMessageKey() {
655 $key = parent::getMessageKey();
656 $params = $this->getMessageParameters();
657 if ( isset( $params[5] ) && $params[5] ) {
658 $key .= '-auto';
659 }
660 return $key;
661 }
662
663 protected function getMessageParameters() {
664 $params = parent::getMessageParameters();
665
666 $target = $this->entry->getTarget();
667 $oldid = $params[3];
668 $revision = $this->context->getLanguage()->formatNum( $oldid, true );
669
670 if ( $this->plaintext ) {
671 $revlink = $revision;
672 } elseif ( $target->exists() ) {
673 $query = array(
674 'oldid' => $oldid,
675 'diff' => 'prev'
676 );
677 $revlink = Linker::link( $target, htmlspecialchars( $revision ), array(), $query );
678 } else {
679 $revlink = htmlspecialchars( $revision );
680 }
681
682 $params[3] = Message::rawParam( $revlink );
683 return $params;
684 }
685 }
686
687 /**
688 * This class formats new user log entries.
689 * @since 1.19
690 */
691 class NewUsersLogFormatter extends LogFormatter {
692 protected function getMessageParameters() {
693 $params = parent::getMessageParameters();
694 if ( $this->entry->getSubtype() === 'create2' ) {
695 if ( isset( $params[3] ) ) {
696 $target = User::newFromId( $params[3] );
697 } else {
698 $target = User::newFromName( $this->entry->getTarget()->getText(), false );
699 }
700 $params[2] = Message::rawParam( $this->makeUserLink( $target ) );
701 $params[3] = $target->getName();
702 }
703 return $params;
704 }
705
706 public function getComment() {
707 $timestamp = wfTimestamp( TS_MW, $this->entry->getTimestamp() );
708 if ( $timestamp < '20080129000000' ) {
709 # Suppress $comment from old entries (before 2008-01-29),
710 # not needed and can contain incorrect links
711 return '';
712 }
713 return parent::getComment();
714 }
715 }