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