Fixing some of the "@return true" or "@return false", need to be "@return bool" and...
[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 function __construct( LogEntry $entry ) {
81 $this->entry = $entry;
82 $this->context = RequestContext::getMain();
83 }
84
85 /**
86 * Replace the default context
87 * @param $context IContextSource
88 */
89 public function setContext( IContextSource $context ) {
90 $this->context = $context;
91 }
92
93 /**
94 * Set the visibility restrictions for displaying content.
95 * If set to public, and an item is deleted, then it will be replaced
96 * with a placeholder even if the context user is allowed to view it.
97 * @param $audience integer self::FOR_THIS_USER or self::FOR_PUBLIC
98 */
99 public function setAudience( $audience ) {
100 $this->audience = ( $audience == self::FOR_THIS_USER )
101 ? self::FOR_THIS_USER
102 : self::FOR_PUBLIC;
103 }
104
105 /**
106 * Check if a log item can be displayed
107 * @param $field integer LogPage::DELETED_* constant
108 * @return bool
109 */
110 protected function canView( $field ) {
111 if ( $this->audience == self::FOR_THIS_USER ) {
112 return LogEventsList::userCanBitfield(
113 $this->entry->getDeleted(), $field, $this->context->getUser() );
114 } else {
115 return !$this->entry->isDeleted( $field );
116 }
117 }
118
119 /**
120 * If set to true, will produce user tool links after
121 * the user name. This should be replaced with generic
122 * CSS/JS solution.
123 * @param $value boolean
124 */
125 public function setShowUserToolLinks( $value ) {
126 $this->linkFlood = $value;
127 }
128
129 /**
130 * Ugly hack to produce plaintext version of the message.
131 * Usually you also want to set extraneous request context
132 * to avoid formatting for any particular user.
133 * @see getActionText()
134 * @return string text
135 */
136 public function getPlainActionText() {
137 $this->plaintext = true;
138 $text = $this->getActionText();
139 $this->plaintext = false;
140 return $text;
141 }
142
143 /**
144 * Gets the log action, including username.
145 * @return string HTML
146 */
147 public function getActionText() {
148 if ( $this->canView( LogPage::DELETED_ACTION ) ) {
149 $element = $this->getActionMessage();
150 if ( $element instanceof Message ) {
151 $element = $this->plaintext ? $element->text() : $element->escaped();
152 }
153 if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) {
154 $element = $this->styleRestricedElement( $element );
155 }
156 } else {
157 $performer = $this->getPerformerElement() . $this->msg( 'word-separator' )->text();
158 $element = $performer . $this->getRestrictedElement( 'rev-deleted-event' );
159 }
160
161 return $element;
162 }
163
164 /**
165 * Returns a sentence describing the log action. Usually
166 * a Message object is returned, but old style log types
167 * and entries might return pre-escaped html string.
168 * @return Message|string pre-escaped html
169 */
170 protected function getActionMessage() {
171 $message = $this->msg( $this->getMessageKey() );
172 $message->params( $this->getMessageParameters() );
173 return $message;
174 }
175
176 /**
177 * Returns a key to be used for formatting the action sentence.
178 * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log
179 * types will use custom keys, and subclasses can also alter the
180 * key depending on the entry itself.
181 * @return string message key
182 */
183 protected function getMessageKey() {
184 $type = $this->entry->getType();
185 $subtype = $this->entry->getSubtype();
186 $key = "logentry-$type-$subtype";
187 return $key;
188 }
189
190 /**
191 * Extracts the optional extra parameters for use in action messages.
192 * The array indexes start from number 3.
193 * @return array
194 */
195 protected function extractParameters() {
196 $entry = $this->entry;
197 $params = array();
198
199 if ( $entry->isLegacy() ) {
200 foreach ( $entry->getParameters() as $index => $value ) {
201 $params[$index + 3] = $value;
202 }
203 }
204
205 // Filter out parameters which are not in format #:foo
206 foreach ( $entry->getParameters() as $key => $value ) {
207 if ( strpos( $key, ':' ) === false ) continue;
208 list( $index, $type, $name ) = explode( ':', $key, 3 );
209 $params[$index - 1] = $value;
210 }
211
212 /* Message class doesn't like non consecutive numbering.
213 * Fill in missing indexes with empty strings to avoid
214 * incorrect renumbering.
215 */
216 if ( count( $params ) ) {
217 $max = max( array_keys( $params ) );
218 for ( $i = 4; $i < $max; $i++ ) {
219 if ( !isset( $params[$i] ) ) {
220 $params[$i] = '';
221 }
222 }
223 }
224 return $params;
225 }
226
227 /**
228 * Formats parameters intented for action message from
229 * array of all parameters. There are three hardcoded
230 * parameters (array is zero-indexed, this list not):
231 * - 1: user name with premade link
232 * - 2: usable for gender magic function
233 * - 3: target page with premade link
234 * @return array
235 */
236 protected function getMessageParameters() {
237 if ( isset( $this->parsedParameters ) ) {
238 return $this->parsedParameters;
239 }
240
241 $entry = $this->entry;
242 $params = $this->extractParameters();
243 $params[0] = Message::rawParam( $this->getPerformerElement() );
244 $params[1] = $entry->getPerformer()->getName();
245 $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) );
246
247 // Bad things happens if the numbers are not in correct order
248 ksort( $params );
249 return $this->parsedParameters = $params;
250 }
251
252 /**
253 * Helper to make a link to the page, taking the plaintext
254 * value in consideration.
255 * @param $title Title the page
256 * @param $parameters array query parameters
257 * @return String
258 */
259 protected function makePageLink( Title $title = null, $parameters = array() ) {
260 if ( !$this->plaintext ) {
261 $link = Linker::link( $title, null, array(), $parameters );
262 } else {
263 if ( !$title instanceof Title ) {
264 throw new MWException( "Expected title, got null" );
265 }
266 $link = '[[' . $title->getPrefixedText() . ']]';
267 }
268 return $link;
269 }
270
271 /**
272 * Provides the name of the user who performed the log action.
273 * Used as part of log action message or standalone, depending
274 * which parts of the log entry has been hidden.
275 */
276 public function getPerformerElement() {
277 if ( $this->canView( LogPage::DELETED_USER ) ) {
278 $performer = $this->entry->getPerformer();
279 $element = $this->makeUserLink( $performer );
280 if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) {
281 $element = $this->styleRestricedElement( $element );
282 }
283 } else {
284 $element = $this->getRestrictedElement( 'rev-deleted-user' );
285 }
286
287 return $element;
288 }
289
290 /**
291 * Gets the luser provided comment
292 * @return string HTML
293 */
294 public function getComment() {
295 if ( $this->canView( LogPage::DELETED_COMMENT ) ) {
296 $comment = Linker::commentBlock( $this->entry->getComment() );
297 // No hard coded spaces thanx
298 $element = ltrim( $comment );
299 if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) {
300 $element = $this->styleRestricedElement( $element );
301 }
302 } else {
303 $element = $this->getRestrictedElement( 'rev-deleted-comment' );
304 }
305
306 return $element;
307 }
308
309 /**
310 * Helper method for displaying restricted element.
311 * @param $message string
312 * @return string HTML or wikitext
313 */
314 protected function getRestrictedElement( $message ) {
315 if ( $this->plaintext ) {
316 return $this->msg( $message )->text();
317 }
318
319 $content = $this->msg( $message )->escaped();
320 $attribs = array( 'class' => 'history-deleted' );
321 return Html::rawElement( 'span', $attribs, $content );
322 }
323
324 /**
325 * Helper method for styling restricted element.
326 * @param $content string
327 * @return string HTML or wikitext
328 */
329 protected function styleRestricedElement( $content ) {
330 if ( $this->plaintext ) {
331 return $content;
332 }
333 $attribs = array( 'class' => 'history-deleted' );
334 return Html::rawElement( 'span', $attribs, $content );
335 }
336
337 /**
338 * Shortcut for wfMessage which honors local context.
339 * @todo Would it be better to require replacing the global context instead?
340 * @param $key string
341 * @return Message
342 */
343 protected function msg( $key ) {
344 return wfMessage( $key )
345 ->inLanguage( $this->context->getLanguage() )
346 ->title( $this->context->getTitle() );
347 }
348
349 protected function makeUserLink( User $user ) {
350 if ( $this->plaintext ) {
351 $element = $user->getName();
352 } else {
353 $element = Linker::userLink(
354 $user->getId(),
355 $user->getName()
356 );
357
358 if ( $this->linkFlood ) {
359 $element .= Linker::userToolLinks(
360 $user->getId(),
361 $user->getName(),
362 true, // Red if no edits
363 0, // Flags
364 $user->getEditCount()
365 );
366 }
367 }
368 return $element;
369 }
370
371 /**
372 * @return Array of titles that should be preloaded with LinkBatch.
373 */
374 public function getPreloadTitles() {
375 return array();
376 }
377
378 }
379
380 /**
381 * This class formats all log entries for log types
382 * which have not been converted to the new system.
383 * This is not about old log entries which store
384 * parameters in a different format - the new
385 * LogFormatter classes have code to support formatting
386 * those too.
387 * @since 1.19
388 */
389 class LegacyLogFormatter extends LogFormatter {
390 protected function getActionMessage() {
391 $entry = $this->entry;
392 $action = LogPage::actionText(
393 $entry->getType(),
394 $entry->getSubtype(),
395 $entry->getTarget(),
396 $this->plaintext ? null : $this->context->getSkin(),
397 (array)$entry->getParameters(),
398 !$this->plaintext // whether to filter [[]] links
399 );
400
401 $performer = $this->getPerformerElement();
402 return $performer . $this->msg( 'word-separator' )->text() . $action;
403 }
404
405 }
406
407 /**
408 * This class formats move log entries.
409 * @since 1.19
410 */
411 class MoveLogFormatter extends LogFormatter {
412 public function getPreloadTitles() {
413 $params = $this->extractParameters();
414 return array( Title::newFromText( $params[3] ) );
415 }
416
417 protected function getMessageKey() {
418 $key = parent::getMessageKey();
419 $params = $this->getMessageParameters();
420 if ( isset( $params[4] ) && $params[4] === '1' ) {
421 $key .= '-noredirect';
422 }
423 return $key;
424 }
425
426 protected function getMessageParameters() {
427 $params = parent::getMessageParameters();
428 $oldname = $this->makePageLink( $this->entry->getTarget(), array( 'redirect' => 'no' ) );
429 $newname = $this->makePageLink( Title::newFromText( $params[3] ) );
430 $params[2] = Message::rawParam( $oldname );
431 $params[3] = Message::rawParam( $newname );
432 return $params;
433 }
434 }
435
436 /**
437 * This class formats delete log entries.
438 * @since 1.19
439 */
440 class DeleteLogFormatter extends LogFormatter {
441 protected function getMessageKey() {
442 $key = parent::getMessageKey();
443 if ( in_array( $this->entry->getSubtype(), array( 'event', 'revision' ) ) ) {
444 if ( count( $this->getMessageParameters() ) < 5 ) {
445 return "$key-legacy";
446 }
447 }
448 return $key;
449 }
450
451 protected function getMessageParameters() {
452 if ( isset( $this->parsedParametersDeleteLog ) ) {
453 return $this->parsedParametersDeleteLog;
454 }
455
456 $params = parent::getMessageParameters();
457 $subtype = $this->entry->getSubtype();
458 if ( in_array( $subtype, array( 'event', 'revision' ) ) ) {
459 if (
460 ($subtype === 'event' && count( $params ) === 6 ) ||
461 ($subtype === 'revision' && isset( $params[3] ) && $params[3] === 'revision' )
462 ) {
463 $paramStart = $subtype === 'revision' ? 4 : 3;
464
465 $old = $this->parseBitField( $params[$paramStart+1] );
466 $new = $this->parseBitField( $params[$paramStart+2] );
467 list( $hid, $unhid, $extra ) = RevisionDeleter::getChanges( $new, $old );
468 $changes = array();
469 foreach ( $hid as $v ) {
470 $changes[] = $this->msg( "$v-hid" )->plain();
471 }
472 foreach ( $unhid as $v ) {
473 $changes[] = $this->msg( "$v-unhid" )->plain();
474 }
475 foreach ( $extra as $v ) {
476 $changes[] = $this->msg( $v )->plain();
477 }
478 $changeText = $this->context->getLanguage()->listToText( $changes );
479
480
481 $newParams = array_slice( $params, 0, 3 );
482 $newParams[3] = $changeText;
483 $count = count( explode( ',', $params[$paramStart] ) );
484 $newParams[4] = $this->context->getLanguage()->formatNum( $count );
485 return $this->parsedParametersDeleteLog = $newParams;
486 } else {
487 return $this->parsedParametersDeleteLog = array_slice( $params, 0, 3 );
488 }
489 }
490
491 return $this->parsedParametersDeleteLog = $params;
492 }
493
494 protected function parseBitField( $string ) {
495 // Input is like ofield=2134 or just the number
496 if ( strpos( $string, 'field=' ) === 1 ) {
497 list( , $field ) = explode( '=', $string );
498 return (int) $field;
499 } else {
500 return (int) $string;
501 }
502 }
503 }
504
505 /**
506 * This class formats patrol log entries.
507 * @since 1.19
508 */
509 class PatrolLogFormatter extends LogFormatter {
510 protected function getMessageKey() {
511 $key = parent::getMessageKey();
512 $params = $this->getMessageParameters();
513 if ( isset( $params[5] ) && $params[5] ) {
514 $key .= '-auto';
515 }
516 return $key;
517 }
518
519 protected function getMessageParameters() {
520 $params = parent::getMessageParameters();
521 $newParams = array_slice( $params, 0, 3 );
522
523 $target = $this->entry->getTarget();
524 $oldid = $params[3];
525 $revision = $this->context->getLanguage()->formatNum( $oldid, true );
526
527 if ( $this->plaintext ) {
528 $revlink = $revision;
529 } elseif ( $target->exists() ) {
530 $query = array(
531 'oldid' => $oldid,
532 'diff' => 'prev'
533 );
534 $revlink = Linker::link( $target, htmlspecialchars( $revision ), array(), $query );
535 } else {
536 $revlink = htmlspecialchars( $revision );
537 }
538
539 $newParams[3] = Message::rawParam( $revlink );
540 return $newParams;
541 }
542 }
543
544 /**
545 * This class formats new user log entries.
546 * @since 1.19
547 */
548 class NewUsersLogFormatter extends LogFormatter {
549 protected function getMessageParameters() {
550 $params = parent::getMessageParameters();
551 if ( $this->entry->getSubtype() === 'create2' ) {
552 if ( isset( $params[3] ) ) {
553 $target = User::newFromId( $params[3] );
554 } else {
555 $target = User::newFromName( $this->entry->getTarget()->getText(), false );
556 }
557 $params[2] = Message::rawParam( $this->makeUserLink( $target ) );
558 $params[3] = $target->getName();
559 }
560 return $params;
561 }
562
563 public function getComment() {
564 $timestamp = wfTimestamp( TS_MW, $this->entry->getTimestamp() );
565 if ( $timestamp < '20080129000000' ) {
566 # Suppress $comment from old entries (before 2008-01-29),
567 # not needed and can contain incorrect links
568 return '';
569 }
570 return parent::getComment();
571 }
572 }