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