Committing my new logging classes for review. Will later commit changes that use...
[lhc/web/wiklou.git] / includes / LogPage.php
1 <?php
2 /**
3 * Contain log classes
4 *
5 * Copyright © 2002, 2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 */
25
26 /**
27 * Class to simplify the use of log pages.
28 * The logs are now kept in a table which is easier to manage and trim
29 * than ever-growing wiki pages.
30 *
31 */
32 class LogPage {
33 const DELETED_ACTION = 1;
34 const DELETED_COMMENT = 2;
35 const DELETED_USER = 4;
36 const DELETED_RESTRICTED = 8;
37 // Convenience fields
38 const SUPPRESSED_USER = 12;
39 const SUPPRESSED_ACTION = 9;
40 /* @access private */
41 var $type, $action, $comment, $params;
42
43 /**
44 * @var User
45 */
46 var $doer;
47
48 /**
49 * @var Title
50 */
51 var $target;
52
53 /* @acess public */
54 var $updateRecentChanges, $sendToUDP;
55
56 /**
57 * Constructor
58 *
59 * @param $type String: one of '', 'block', 'protect', 'rights', 'delete',
60 * 'upload', 'move'
61 * @param $rc Boolean: whether to update recent changes as well as the logging table
62 * @param $udp String: pass 'UDP' to send to the UDP feed if NOT sent to RC
63 */
64 public function __construct( $type, $rc = true, $udp = 'skipUDP' ) {
65 $this->type = $type;
66 $this->updateRecentChanges = $rc;
67 $this->sendToUDP = ( $udp == 'UDP' );
68 }
69
70 /**
71 * @return bool|int|null
72 */
73 protected function saveContent() {
74 global $wgLogRestrictions;
75
76 $dbw = wfGetDB( DB_MASTER );
77 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
78
79 $this->timestamp = $now = wfTimestampNow();
80 $data = array(
81 'log_id' => $log_id,
82 'log_type' => $this->type,
83 'log_action' => $this->action,
84 'log_timestamp' => $dbw->timestamp( $now ),
85 'log_user' => $this->doer->getId(),
86 'log_user_text' => $this->doer->getName(),
87 'log_namespace' => $this->target->getNamespace(),
88 'log_title' => $this->target->getDBkey(),
89 'log_page' => $this->target->getArticleId(),
90 'log_comment' => $this->comment,
91 'log_params' => $this->params
92 );
93 $dbw->insert( 'logging', $data, __METHOD__ );
94 $newId = !is_null( $log_id ) ? $log_id : $dbw->insertId();
95
96 # And update recentchanges
97 if( $this->updateRecentChanges ) {
98 $titleObj = SpecialPage::getTitleFor( 'Log', $this->type );
99
100 RecentChange::notifyLog(
101 $now, $titleObj, $this->doer, $this->getRcComment(), '',
102 $this->type, $this->action, $this->target, $this->comment,
103 $this->params, $newId
104 );
105 } elseif( $this->sendToUDP ) {
106 # Don't send private logs to UDP
107 if( isset( $wgLogRestrictions[$this->type] ) && $wgLogRestrictions[$this->type] != '*' ) {
108 return true;
109 }
110
111 # Notify external application via UDP.
112 # We send this to IRC but do not want to add it the RC table.
113 $titleObj = SpecialPage::getTitleFor( 'Log', $this->type );
114 $rc = RecentChange::newLogEntry(
115 $now, $titleObj, $this->doer, $this->getRcComment(), '',
116 $this->type, $this->action, $this->target, $this->comment,
117 $this->params, $newId
118 );
119 $rc->notifyRC2UDP();
120 }
121 return $newId;
122 }
123
124 /**
125 * Get the RC comment from the last addEntry() call
126 *
127 * @return string
128 */
129 public function getRcComment() {
130 $rcComment = $this->actionText;
131
132 if( $this->comment != '' ) {
133 if ( $rcComment == '' ) {
134 $rcComment = $this->comment;
135 } else {
136 $rcComment .= wfMsgForContent( 'colon-separator' ) . $this->comment;
137 }
138 }
139
140 return $rcComment;
141 }
142
143 /**
144 * Get the comment from the last addEntry() call
145 */
146 public function getComment() {
147 return $this->comment;
148 }
149
150 /**
151 * Get the list of valid log types
152 *
153 * @return Array of strings
154 */
155 public static function validTypes() {
156 global $wgLogTypes;
157 return $wgLogTypes;
158 }
159
160 /**
161 * Is $type a valid log type
162 *
163 * @param $type String: log type to check
164 * @return Boolean
165 */
166 public static function isLogType( $type ) {
167 return in_array( $type, LogPage::validTypes() );
168 }
169
170 /**
171 * Get the name for the given log type
172 *
173 * @param $type String: logtype
174 * @return String: log name
175 * @deprecated in 1.19, warnings in 1.21. Use getName()
176 */
177 public static function logName( $type ) {
178 global $wgLogNames;
179
180 if( isset( $wgLogNames[$type] ) ) {
181 return str_replace( '_', ' ', wfMsg( $wgLogNames[$type] ) );
182 } else {
183 // Bogus log types? Perhaps an extension was removed.
184 return $type;
185 }
186 }
187
188 /**
189 * Get the log header for the given log type
190 *
191 * @todo handle missing log types
192 * @param $type String: logtype
193 * @return String: headertext of this logtype
194 * @deprecated in 1.19, warnings in 1.21. Use getDescription()
195 */
196 public static function logHeader( $type ) {
197 global $wgLogHeaders;
198 return wfMsgExt( $wgLogHeaders[$type], array( 'parseinline' ) );
199 }
200
201 /**
202 * Generate text for a log entry
203 *
204 * @param $type String: log type
205 * @param $action String: log action
206 * @param $title Mixed: Title object or null
207 * @param $skin Mixed: Skin object or null. If null, we want to use the wiki
208 * content language, since that will go to the IRC feed.
209 * @param $params Array: parameters
210 * @param $filterWikilinks Boolean: whether to filter wiki links
211 * @return HTML string
212 */
213 public static function actionText( $type, $action, $title = null, $skin = null,
214 $params = array(), $filterWikilinks = false )
215 {
216 global $wgLang, $wgContLang, $wgLogActions;
217
218 if ( is_null( $skin ) ) {
219 $langObj = $wgContLang;
220 $langObjOrNull = null;
221 } else {
222 $langObj = $wgLang;
223 $langObjOrNull = $wgLang;
224 }
225
226 $key = "$type/$action";
227
228 # Defer patrol log to PatrolLog class
229 if( $key == 'patrol/patrol' ) {
230 return PatrolLog::makeActionText( $title, $params, $langObjOrNull );
231 }
232
233 if( isset( $wgLogActions[$key] ) ) {
234 if( is_null( $title ) ) {
235 $rv = wfMsgExt( $wgLogActions[$key], array( 'parsemag', 'escape', 'language' => $langObj ) );
236 } else {
237 $titleLink = self::getTitleLink( $type, $langObjOrNull, $title, $params );
238
239 if( preg_match( '/^rights\/(rights|autopromote)/', $key ) ) {
240 $rightsnone = wfMsgExt( 'rightsnone', array( 'parsemag', 'language' => $langObj ) );
241
242 if( $skin ) {
243 foreach ( $params as &$param ) {
244 $groupArray = array_map( 'trim', explode( ',', $param ) );
245 $groupArray = array_map( array( 'User', 'getGroupMember' ), $groupArray );
246 $param = $wgLang->listToText( $groupArray );
247 }
248 }
249
250 if( !isset( $params[0] ) || trim( $params[0] ) == '' ) {
251 $params[0] = $rightsnone;
252 }
253
254 if( !isset( $params[1] ) || trim( $params[1] ) == '' ) {
255 $params[1] = $rightsnone;
256 }
257 }
258
259 if( count( $params ) == 0 ) {
260 $rv = wfMsgExt( $wgLogActions[$key], array( 'parsemag', 'escape', 'replaceafter', 'language' => $langObj ), $titleLink );
261 } else {
262 $details = '';
263 array_unshift( $params, $titleLink );
264
265 // User suppression
266 if ( preg_match( '/^(block|suppress)\/(block|reblock)$/', $key ) ) {
267 if ( $skin ) {
268 $params[1] = '<span class="blockExpiry" dir="ltr" title="' . htmlspecialchars( $params[1] ). '">' .
269 $wgLang->translateBlockExpiry( $params[1] ) . '</span>';
270 } else {
271 $params[1] = $wgContLang->translateBlockExpiry( $params[1] );
272 }
273
274 $params[2] = isset( $params[2] ) ?
275 self::formatBlockFlags( $params[2], $langObj ) : '';
276 // Page protections
277 } elseif ( $type == 'protect' && count($params) == 3 ) {
278 // Restrictions and expiries
279 if( $skin ) {
280 $details .= $wgLang->getDirMark() . htmlspecialchars( " {$params[1]}" );
281 } else {
282 $details .= " {$params[1]}";
283 }
284
285 // Cascading flag...
286 if( $params[2] ) {
287 $details .= ' [' . wfMsgExt( 'protect-summary-cascade', array( 'parsemag', 'language' => $langObj ) ) . ']';
288 }
289 // Page moves
290 } elseif ( $type == 'move' && count( $params ) == 3 ) {
291 if( $params[2] ) {
292 $details .= ' [' . wfMsgExt( 'move-redirect-suppressed', array( 'parsemag', 'language' => $langObj ) ) . ']';
293 }
294 // Revision deletion
295 } elseif ( preg_match( '/^(delete|suppress)\/revision$/', $key ) && count( $params ) == 5 ) {
296 $count = substr_count( $params[2], ',' ) + 1; // revisions
297 $ofield = intval( substr( $params[3], 7 ) ); // <ofield=x>
298 $nfield = intval( substr( $params[4], 7 ) ); // <nfield=x>
299 $details .= ': ' . RevisionDeleter::getLogMessage( $count, $nfield, $ofield, $langObj, false );
300 // Log deletion
301 } elseif ( preg_match( '/^(delete|suppress)\/event$/', $key ) && count( $params ) == 4 ) {
302 $count = substr_count( $params[1], ',' ) + 1; // log items
303 $ofield = intval( substr( $params[2], 7 ) ); // <ofield=x>
304 $nfield = intval( substr( $params[3], 7 ) ); // <nfield=x>
305 $details .= ': ' . RevisionDeleter::getLogMessage( $count, $nfield, $ofield, $langObj, true );
306 }
307
308 $rv = wfMsgExt( $wgLogActions[$key], array( 'parsemag', 'escape', 'replaceafter', 'language' => $langObj ), $params ) . $details;
309 }
310 }
311 } else {
312 global $wgLogActionsHandlers;
313
314 if( isset( $wgLogActionsHandlers[$key] ) ) {
315 $args = func_get_args();
316 $rv = call_user_func_array( $wgLogActionsHandlers[$key], $args );
317 } else {
318 wfDebug( "LogPage::actionText - unknown action $key\n" );
319 $rv = "$action";
320 }
321 }
322
323 // For the perplexed, this feature was added in r7855 by Erik.
324 // The feature was added because we liked adding [[$1]] in our log entries
325 // but the log entries are parsed as Wikitext on RecentChanges but as HTML
326 // on Special:Log. The hack is essentially that [[$1]] represented a link
327 // to the title in question. The first parameter to the HTML version (Special:Log)
328 // is that link in HTML form, and so this just gets rid of the ugly [[]].
329 // However, this is a horrible hack and it doesn't work like you expect if, say,
330 // you want to link to something OTHER than the title of the log entry.
331 // The real problem, which Erik was trying to fix (and it sort-of works now) is
332 // that the same messages are being treated as both wikitext *and* HTML.
333 if( $filterWikilinks ) {
334 $rv = str_replace( '[[', '', $rv );
335 $rv = str_replace( ']]', '', $rv );
336 }
337
338 return $rv;
339 }
340
341 /**
342 * TODO document
343 * @param $type String
344 * @param $lang Language or null
345 * @param $title Title
346 * @param $params Array
347 * @return String
348 */
349 protected static function getTitleLink( $type, $lang, $title, &$params ) {
350 global $wgContLang, $wgUserrightsInterwikiDelimiter;
351
352 if( !$lang ) {
353 return $title->getPrefixedText();
354 }
355
356 switch( $type ) {
357 case 'move':
358 $titleLink = Linker::link(
359 $title,
360 htmlspecialchars( $title->getPrefixedText() ),
361 array(),
362 array( 'redirect' => 'no' )
363 );
364
365 $targetTitle = Title::newFromText( $params[0] );
366
367 if ( !$targetTitle ) {
368 # Workaround for broken database
369 $params[0] = htmlspecialchars( $params[0] );
370 } else {
371 $params[0] = Linker::link(
372 $targetTitle,
373 htmlspecialchars( $params[0] )
374 );
375 }
376 break;
377 case 'block':
378 if( substr( $title->getText(), 0, 1 ) == '#' ) {
379 $titleLink = $title->getText();
380 } else {
381 // @todo Store the user identifier in the parameters
382 // to make this faster for future log entries
383 $id = User::idFromName( $title->getText() );
384 $titleLink = Linker::userLink( $id, $title->getText() )
385 . Linker::userToolLinks( $id, $title->getText(), false, Linker::TOOL_LINKS_NOBLOCK );
386 }
387 break;
388 case 'rights':
389 $text = $wgContLang->ucfirst( $title->getText() );
390 $parts = explode( $wgUserrightsInterwikiDelimiter, $text, 2 );
391
392 if ( count( $parts ) == 2 ) {
393 $titleLink = WikiMap::foreignUserLink( $parts[1], $parts[0],
394 htmlspecialchars( $title->getPrefixedText() ) );
395
396 if ( $titleLink !== false ) {
397 break;
398 }
399 }
400 $titleLink = Linker::link( Title::makeTitle( NS_USER, $text ) );
401 break;
402 case 'merge':
403 $titleLink = Linker::link(
404 $title,
405 $title->getPrefixedText(),
406 array(),
407 array( 'redirect' => 'no' )
408 );
409 $params[0] = Linker::link(
410 Title::newFromText( $params[0] ),
411 htmlspecialchars( $params[0] )
412 );
413 $params[1] = $lang->timeanddate( $params[1] );
414 break;
415 default:
416 if( $title->getNamespace() == NS_SPECIAL ) {
417 list( $name, $par ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
418
419 # Use the language name for log titles, rather than Log/X
420 if( $name == 'Log' ) {
421 $titleLink = '(' . Linker::link( $title, LogPage::logName( $par ) ) . ')';
422 } else {
423 $titleLink = Linker::link( $title );
424 }
425 } else {
426 $titleLink = Linker::link( $title );
427 }
428 }
429
430 return $titleLink;
431 }
432
433 /**
434 * Add a log entry
435 *
436 * @param $action String: one of '', 'block', 'protect', 'rights', 'delete', 'upload', 'move', 'move_redir'
437 * @param $target Title object
438 * @param $comment String: description associated
439 * @param $params Array: parameters passed later to wfMsg.* functions
440 * @param $doer User object: the user doing the action
441 *
442 * @return bool|int|null
443 */
444 public function addEntry( $action, $target, $comment, $params = array(), $doer = null ) {
445 global $wgContLang;
446
447 if ( !is_array( $params ) ) {
448 $params = array( $params );
449 }
450
451 if ( $comment === null ) {
452 $comment = '';
453 }
454
455 # Truncate for whole multibyte characters.
456 $comment = $wgContLang->truncate( $comment, 255 );
457
458 $this->action = $action;
459 $this->target = $target;
460 $this->comment = $comment;
461 $this->params = LogPage::makeParamBlob( $params );
462
463 if ( $doer === null ) {
464 global $wgUser;
465 $doer = $wgUser;
466 } elseif ( !is_object( $doer ) ) {
467 $doer = User::newFromId( $doer );
468 }
469
470 $this->doer = $doer;
471
472 $this->actionText = LogPage::actionText( $this->type, $action, $target, null, $params );
473
474 return $this->saveContent();
475 }
476
477 /**
478 * Add relations to log_search table
479 *
480 * @param $field String
481 * @param $values Array
482 * @param $logid Integer
483 * @return Boolean
484 */
485 public function addRelations( $field, $values, $logid ) {
486 if( !strlen( $field ) || empty( $values ) ) {
487 return false; // nothing
488 }
489
490 $data = array();
491
492 foreach( $values as $value ) {
493 $data[] = array(
494 'ls_field' => $field,
495 'ls_value' => $value,
496 'ls_log_id' => $logid
497 );
498 }
499
500 $dbw = wfGetDB( DB_MASTER );
501 $dbw->insert( 'log_search', $data, __METHOD__, 'IGNORE' );
502
503 return true;
504 }
505
506 /**
507 * Create a blob from a parameter array
508 *
509 * @param $params Array
510 * @return String
511 */
512 public static function makeParamBlob( $params ) {
513 return implode( "\n", $params );
514 }
515
516 /**
517 * Extract a parameter array from a blob
518 *
519 * @param $blob String
520 * @return Array
521 */
522 public static function extractParams( $blob ) {
523 if ( $blob === '' ) {
524 return array();
525 } else {
526 return explode( "\n", $blob );
527 }
528 }
529
530 /**
531 * Convert a comma-delimited list of block log flags
532 * into a more readable (and translated) form
533 *
534 * @param $flags Flags to format
535 * @param $lang Language object to use
536 * @return String
537 */
538 public static function formatBlockFlags( $flags, $lang ) {
539 $flags = explode( ',', trim( $flags ) );
540
541 if( count( $flags ) > 0 ) {
542 for( $i = 0; $i < count( $flags ); $i++ ) {
543 $flags[$i] = self::formatBlockFlag( $flags[$i], $lang );
544 }
545 return '(' . $lang->commaList( $flags ) . ')';
546 } else {
547 return '';
548 }
549 }
550
551 /**
552 * Translate a block log flag if possible
553 *
554 * @param $flag int Flag to translate
555 * @param $lang Language object to use
556 * @return String
557 */
558 public static function formatBlockFlag( $flag, $lang ) {
559 static $messages = array();
560
561 if( !isset( $messages[$flag] ) ) {
562 $messages[$flag] = htmlspecialchars( $flag ); // Fallback
563
564 // For grepping. The following core messages can be used here:
565 // * block-log-flags-angry-autoblock
566 // * block-log-flags-anononly
567 // * block-log-flags-hiddenname
568 // * block-log-flags-noautoblock
569 // * block-log-flags-nocreate
570 // * block-log-flags-noemail
571 // * block-log-flags-nousertalk
572 $msg = wfMessage( 'block-log-flags-' . $flag )->inLanguage( $lang );
573
574 if ( $msg->exists() ) {
575 $messages[$flag] = $msg->escaped();
576 }
577 }
578
579 return $messages[$flag];
580 }
581
582
583 /**
584 * Name of the log.
585 * @return Message
586 * @since 1.19
587 */
588 public function getName() {
589 global $wgLogNames;
590
591 // BC
592 if ( isset( $wgLogNames[$this->type] ) ) {
593 $key = $wgLogNames[$this->type];
594 } else {
595 $key = 'log-name-' . $this->type;
596 }
597
598 return wfMessage( $key );
599 }
600
601 /**
602 * Description of this log type.
603 * @return Message
604 * @since 1.19
605 */
606 public function getDescription() {
607 global $wgLogHeaders;
608 // BC
609 if ( isset( $wgLogHeaders[$this->type] ) ) {
610 $key = $wgLogHeaders[$this->type];
611 } else {
612 $key = 'log-description-' . $this->type;
613 }
614 return wfMessage( $key );
615 }
616
617 /**
618 * Returns the right needed to read this log type.
619 * @return string
620 * @since 1.19
621 */
622 public function getRestriction() {
623 global $wgLogRestrictions;
624 if ( isset( $wgLogRestrictions[$this->type] ) ) {
625 $restriction = $wgLogRestrictions[$this->type];
626 } else {
627 // '' always returns true with $user->isAllowed()
628 $restriction = '';
629 }
630 return $restriction;
631 }
632
633 /**
634 * Tells if this log is not viewable by all.
635 * @return bool
636 * @since 1.19
637 */
638 public function isRestricted() {
639 $restriction = $this->getRestriction();
640 return $restriction !== '' && $restriction !== '*';
641 }
642
643 }