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