Uglier than ugly hack to fix block log any many others by not having the username...
[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 'newusers':
230 switch( $entry->getSubtype() ) {
231 case 'newusers':
232 case 'create':
233 $text = wfMsgExt( 'newuserlog-create-entry', $msgOpts /* no params */ );
234 break;
235 case 'create2':
236 $text = wfMsgExt( 'newuserlog-create2-entry', $msgOpts, $target );
237 break;
238 case 'autocreate':
239 $text = wfMsgExt( 'newuserlog-autocreate-entry', $msgOpts /* no params */ );
240 break;
241 }
242 break;
243
244 case 'upload':
245 switch( $entry->getSubtype() ) {
246 case 'upload':
247 $text = wfMsgExt( 'uploadedimage', $msgOpts, $target );
248 break;
249 case 'overwrite':
250 $text = wfMsgExt( 'overwroteimage', $msgOpts, $target );
251 break;
252 }
253 break;
254
255
256 // case 'suppress' --private log -- aaron (sign your messages so we know who to blame in a few years :-D)
257 // default:
258 }
259 if( is_null( $text ) ) {
260 $text = $this->getPlainActionText();
261 }
262
263 $this->plaintext = false;
264 return $text;
265 }
266
267 /**
268 * Gets the log action, including username.
269 * @return string HTML
270 */
271 public function getActionText() {
272 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
273 $element = $this->getActionMessage();
274 if ( $element instanceof Message ) {
275 $element = $this->plaintext ? $element->text() : $element->escaped();
276 }
277 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
278 $element = $this->styleRestricedElement( $element );
279 }
280 } else {
281 $performer = $this->getPerformerElement() . $this->msg( 'word-separator' )->text();
282 $element = $performer . $this->getRestrictedElement( 'rev-deleted-event' );
283 }
284
285 return $element;
286 }
287
288 /**
289 * Returns a sentence describing the log action. Usually
290 * a Message object is returned, but old style log types
291 * and entries might return pre-escaped html string.
292 * @return Message|string pre-escaped html
293 */
294 protected function getActionMessage() {
295 $message = $this->msg( $this->getMessageKey() );
296 $message->params( $this->getMessageParameters() );
297 return $message;
298 }
299
300 /**
301 * Returns a key to be used for formatting the action sentence.
302 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
303 * types will use custom keys, and subclasses can also alter the
304 * key depending on the entry itself.
305 * @return string message key
306 */
307 protected function getMessageKey() {
308 $type = $this->entry->getType();
309 $subtype = $this->entry->getSubtype();
310
311 return "logentry-$type-$subtype";
312 }
313
314 /**
315 * Extracts the optional extra parameters for use in action messages.
316 * The array indexes start from number 3.
317 * @return array
318 */
319 protected function extractParameters() {
320 $entry = $this->entry;
321 $params = array();
322
323 if ( $entry->isLegacy() ) {
324 foreach ( $entry->getParameters() as $index => $value ) {
325 $params[$index + 3] = $value;
326 }
327 }
328
329 // Filter out parameters which are not in format #:foo
330 foreach ( $entry->getParameters() as $key => $value ) {
331 if ( strpos( $key, ':' ) === false ) continue;
332 list( $index, $type, $name ) = explode( ':', $key, 3 );
333 $params[$index - 1] = $value;
334 }
335
336 /* Message class doesn't like non consecutive numbering.
337 * Fill in missing indexes with empty strings to avoid
338 * incorrect renumbering.
339 */
340 if ( count( $params ) ) {
341 $max = max( array_keys( $params ) );
342 for ( $i = 4; $i < $max; $i++ ) {
343 if ( !isset( $params[$i] ) ) {
344 $params[$i] = '';
345 }
346 }
347 }
348 return $params;
349 }
350
351 /**
352 * Formats parameters intented for action message from
353 * array of all parameters. There are three hardcoded
354 * parameters (array is zero-indexed, this list not):
355 * - 1: user name with premade link
356 * - 2: usable for gender magic function
357 * - 3: target page with premade link
358 * @return array
359 */
360 protected function getMessageParameters() {
361 if ( isset( $this->parsedParameters ) ) {
362 return $this->parsedParameters;
363 }
364
365 $entry = $this->entry;
366 $params = $this->extractParameters();
367 $params[0] = Message::rawParam( $this->getPerformerElement() );
368 $params[1] = $entry->getPerformer()->getName();
369 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
370
371 // Bad things happens if the numbers are not in correct order
372 ksort( $params );
373 return $this->parsedParameters = $params;
374 }
375
376 /**
377 * Helper to make a link to the page, taking the plaintext
378 * value in consideration.
379 * @param $title Title the page
380 * @param $parameters array query parameters
381 * @return String
382 */
383 protected function makePageLink( Title $title = null, $parameters = array() ) {
384 if ( !$this->plaintext ) {
385 $link = Linker::link( $title, null, array(), $parameters );
386 } else {
387 if ( !$title instanceof Title ) {
388 throw new MWException( "Expected title, got null" );
389 }
390 $link = '[[' . $title->getPrefixedText() . ']]';
391 }
392 return $link;
393 }
394
395 /**
396 * Provides the name of the user who performed the log action.
397 * Used as part of log action message or standalone, depending
398 * which parts of the log entry has been hidden.
399 * @return String
400 */
401 public function getPerformerElement() {
402 if ( $this->canView( LogPage::DELETED_USER ) ) {
403 $performer = $this->entry->getPerformer();
404 $element = $this->makeUserLink( $performer );
405 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
406 $element = $this->styleRestricedElement( $element );
407 }
408 } else {
409 $element = $this->getRestrictedElement( 'rev-deleted-user' );
410 }
411
412 return $element;
413 }
414
415 /**
416 * Gets the luser provided comment
417 * @return string HTML
418 */
419 public function getComment() {
420 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
421 $comment = Linker::commentBlock( $this->entry->getComment() );
422 // No hard coded spaces thanx
423 $element = ltrim( $comment );
424 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
425 $element = $this->styleRestricedElement( $element );
426 }
427 } else {
428 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
429 }
430
431 return $element;
432 }
433
434 /**
435 * Helper method for displaying restricted element.
436 * @param $message string
437 * @return string HTML or wikitext
438 */
439 protected function getRestrictedElement( $message ) {
440 if ( $this->plaintext ) {
441 return $this->msg( $message )->text();
442 }
443
444 $content = $this->msg( $message )->escaped();
445 $attribs = array( 'class' => 'history-deleted' );
446 return Html::rawElement( 'span', $attribs, $content );
447 }
448
449 /**
450 * Helper method for styling restricted element.
451 * @param $content string
452 * @return string HTML or wikitext
453 */
454 protected function styleRestricedElement( $content ) {
455 if ( $this->plaintext ) {
456 return $content;
457 }
458 $attribs = array( 'class' => 'history-deleted' );
459 return Html::rawElement( 'span', $attribs, $content );
460 }
461
462 /**
463 * Shortcut for wfMessage which honors local context.
464 * @todo Would it be better to require replacing the global context instead?
465 * @param $key string
466 * @return Message
467 */
468 protected function msg( $key ) {
469 return wfMessage( $key )
470 ->inLanguage( $this->context->getLanguage() )
471 ->title( $this->context->getTitle() );
472 }
473
474 protected function makeUserLink( User $user ) {
475 if ( $this->plaintext ) {
476 $element = $user->getName();
477 } else {
478 $element = Linker::userLink(
479 $user->getId(),
480 $user->getName()
481 );
482
483 if ( $this->linkFlood ) {
484 $element .= Linker::userToolLinks(
485 $user->getId(),
486 $user->getName(),
487 true, // Red if no edits
488 0, // Flags
489 $user->getEditCount()
490 );
491 }
492 }
493 return $element;
494 }
495
496 /**
497 * @return Array of titles that should be preloaded with LinkBatch.
498 */
499 public function getPreloadTitles() {
500 return array();
501 }
502
503 }
504
505 /**
506 * This class formats all log entries for log types
507 * which have not been converted to the new system.
508 * This is not about old log entries which store
509 * parameters in a different format - the new
510 * LogFormatter classes have code to support formatting
511 * those too.
512 * @since 1.19
513 */
514 class LegacyLogFormatter extends LogFormatter {
515 protected function getActionMessage() {
516 $entry = $this->entry;
517 $action = LogPage::actionText(
518 $entry->getType(),
519 $entry->getSubtype(),
520 $entry->getTarget(),
521 $this->plaintext ? null : $this->context->getSkin(),
522 (array)$entry->getParameters(),
523 !$this->plaintext // whether to filter [[]] links
524 );
525
526 $performer = $this->getPerformerElement();
527 if ( !$this->irctext ) {
528 $action = $performer . $this->msg( 'word-separator' )->text() . $action;
529 }
530
531 return $action;
532 }
533
534 }
535
536 /**
537 * This class formats move log entries.
538 * @since 1.19
539 */
540 class MoveLogFormatter extends LogFormatter {
541 public function getPreloadTitles() {
542 $params = $this->extractParameters();
543 return array( Title::newFromText( $params[3] ) );
544 }
545
546 protected function getMessageKey() {
547 $key = parent::getMessageKey();
548 $params = $this->getMessageParameters();
549 if ( isset( $params[4] ) && $params[4] === '1' ) {
550 $key .= '-noredirect';
551 }
552 return $key;
553 }
554
555 protected function getMessageParameters() {
556 $params = parent::getMessageParameters();
557 $oldname = $this->makePageLink( $this->entry->getTarget(), array( 'redirect' => 'no' ) );
558 $newname = $this->makePageLink( Title::newFromText( $params[3] ) );
559 $params[2] = Message::rawParam( $oldname );
560 $params[3] = Message::rawParam( $newname );
561 return $params;
562 }
563 }
564
565 /**
566 * This class formats delete log entries.
567 * @since 1.19
568 */
569 class DeleteLogFormatter extends LogFormatter {
570 protected function getMessageKey() {
571 $key = parent::getMessageKey();
572 if ( in_array( $this->entry->getSubtype(), array( 'event', 'revision' ) ) ) {
573 if ( count( $this->getMessageParameters() ) < 5 ) {
574 return "$key-legacy";
575 }
576 }
577 return $key;
578 }
579
580 protected function getMessageParameters() {
581 if ( isset( $this->parsedParametersDeleteLog ) ) {
582 return $this->parsedParametersDeleteLog;
583 }
584
585 $params = parent::getMessageParameters();
586 $subtype = $this->entry->getSubtype();
587 if ( in_array( $subtype, array( 'event', 'revision' ) ) ) {
588 if (
589 ($subtype === 'event' && count( $params ) === 6 ) ||
590 ($subtype === 'revision' && isset( $params[3] ) && $params[3] === 'revision' )
591 ) {
592 $paramStart = $subtype === 'revision' ? 4 : 3;
593
594 $old = $this->parseBitField( $params[$paramStart+1] );
595 $new = $this->parseBitField( $params[$paramStart+2] );
596 list( $hid, $unhid, $extra ) = RevisionDeleter::getChanges( $new, $old );
597 $changes = array();
598 foreach ( $hid as $v ) {
599 $changes[] = $this->msg( "$v-hid" )->plain();
600 }
601 foreach ( $unhid as $v ) {
602 $changes[] = $this->msg( "$v-unhid" )->plain();
603 }
604 foreach ( $extra as $v ) {
605 $changes[] = $this->msg( $v )->plain();
606 }
607 $changeText = $this->context->getLanguage()->listToText( $changes );
608
609
610 $newParams = array_slice( $params, 0, 3 );
611 $newParams[3] = $changeText;
612 $count = count( explode( ',', $params[$paramStart] ) );
613 $newParams[4] = $this->context->getLanguage()->formatNum( $count );
614 return $this->parsedParametersDeleteLog = $newParams;
615 } else {
616 return $this->parsedParametersDeleteLog = array_slice( $params, 0, 3 );
617 }
618 }
619
620 return $this->parsedParametersDeleteLog = $params;
621 }
622
623 protected function parseBitField( $string ) {
624 // Input is like ofield=2134 or just the number
625 if ( strpos( $string, 'field=' ) === 1 ) {
626 list( , $field ) = explode( '=', $string );
627 return (int) $field;
628 } else {
629 return (int) $string;
630 }
631 }
632 }
633
634 /**
635 * This class formats patrol log entries.
636 * @since 1.19
637 */
638 class PatrolLogFormatter extends LogFormatter {
639 protected function getMessageKey() {
640 $key = parent::getMessageKey();
641 $params = $this->getMessageParameters();
642 if ( isset( $params[5] ) && $params[5] ) {
643 $key .= '-auto';
644 }
645 return $key;
646 }
647
648 protected function getMessageParameters() {
649 $params = parent::getMessageParameters();
650 $newParams = array_slice( $params, 0, 3 );
651
652 $target = $this->entry->getTarget();
653 $oldid = $params[3];
654 $revision = $this->context->getLanguage()->formatNum( $oldid, true );
655
656 if ( $this->plaintext ) {
657 $revlink = $revision;
658 } elseif ( $target->exists() ) {
659 $query = array(
660 'oldid' => $oldid,
661 'diff' => 'prev'
662 );
663 $revlink = Linker::link( $target, htmlspecialchars( $revision ), array(), $query );
664 } else {
665 $revlink = htmlspecialchars( $revision );
666 }
667
668 $newParams[3] = Message::rawParam( $revlink );
669 return $newParams;
670 }
671 }
672
673 /**
674 * This class formats new user log entries.
675 * @since 1.19
676 */
677 class NewUsersLogFormatter extends LogFormatter {
678 protected function getMessageParameters() {
679 $params = parent::getMessageParameters();
680 if ( $this->entry->getSubtype() === 'create2' ) {
681 if ( isset( $params[3] ) ) {
682 $target = User::newFromId( $params[3] );
683 } else {
684 $target = User::newFromName( $this->entry->getTarget()->getText(), false );
685 }
686 $params[2] = Message::rawParam( $this->makeUserLink( $target ) );
687 $params[3] = $target->getName();
688 }
689 return $params;
690 }
691
692 public function getComment() {
693 $timestamp = wfTimestamp( TS_MW, $this->entry->getTimestamp() );
694 if ( $timestamp < '20080129000000' ) {
695 # Suppress $comment from old entries (before 2008-01-29),
696 # not needed and can contain incorrect links
697 return '';
698 }
699 return parent::getComment();
700 }
701 }