Merge "Fix Postgres support"
[lhc/web/wiklou.git] / includes / logging / LogEntry.php
1 <?php
2 /**
3 * Contain classes for dealing with individual log entries
4 *
5 * This is how I see the log system history:
6 * - appending to plain wiki pages
7 * - formatting log entries based on database fields
8 * - user is now part of the action message
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @file
26 * @author Niklas Laxström
27 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
28 * @since 1.19
29 */
30
31 use Wikimedia\Rdbms\IDatabase;
32
33 /**
34 * Interface for log entries. Every log entry has these methods.
35 *
36 * @since 1.19
37 */
38 interface LogEntry {
39
40 /**
41 * The main log type.
42 *
43 * @return string
44 */
45 public function getType();
46
47 /**
48 * The log subtype.
49 *
50 * @return string
51 */
52 public function getSubtype();
53
54 /**
55 * The full logtype in format maintype/subtype.
56 *
57 * @return string
58 */
59 public function getFullType();
60
61 /**
62 * Get the extra parameters stored for this message.
63 *
64 * @return array
65 */
66 public function getParameters();
67
68 /**
69 * Get the user for performed this action.
70 *
71 * @return User
72 */
73 public function getPerformer();
74
75 /**
76 * Get the target page of this action.
77 *
78 * @return Title
79 */
80 public function getTarget();
81
82 /**
83 * Get the timestamp when the action was executed.
84 *
85 * @return string
86 */
87 public function getTimestamp();
88
89 /**
90 * Get the user provided comment.
91 *
92 * @return string
93 */
94 public function getComment();
95
96 /**
97 * Get the access restriction.
98 *
99 * @return string
100 */
101 public function getDeleted();
102
103 /**
104 * @param int $field One of LogPage::DELETED_* bitfield constants
105 * @return bool
106 */
107 public function isDeleted( $field );
108 }
109
110 /**
111 * Extends the LogEntryInterface with some basic functionality
112 *
113 * @since 1.19
114 */
115 abstract class LogEntryBase implements LogEntry {
116
117 public function getFullType() {
118 return $this->getType() . '/' . $this->getSubtype();
119 }
120
121 public function isDeleted( $field ) {
122 return ( $this->getDeleted() & $field ) === $field;
123 }
124
125 /**
126 * Whether the parameters for this log are stored in new or
127 * old format.
128 *
129 * @return bool
130 */
131 public function isLegacy() {
132 return false;
133 }
134
135 /**
136 * Create a blob from a parameter array
137 *
138 * @since 1.26
139 * @param array $params
140 * @return string
141 */
142 public static function makeParamBlob( $params ) {
143 return serialize( (array)$params );
144 }
145
146 /**
147 * Extract a parameter array from a blob
148 *
149 * @since 1.26
150 * @param string $blob
151 * @return array
152 */
153 public static function extractParams( $blob ) {
154 return unserialize( $blob );
155 }
156 }
157
158 /**
159 * This class wraps around database result row.
160 *
161 * @since 1.19
162 */
163 class DatabaseLogEntry extends LogEntryBase {
164
165 /**
166 * Returns array of information that is needed for querying
167 * log entries. Array contains the following keys:
168 * tables, fields, conds, options and join_conds
169 *
170 * @return array
171 */
172 public static function getSelectQueryData() {
173 $tables = [ 'logging', 'user' ];
174 $fields = [
175 'log_id', 'log_type', 'log_action', 'log_timestamp',
176 'log_user', 'log_user_text',
177 'log_namespace', 'log_title', // unused log_page
178 'log_comment', 'log_params', 'log_deleted',
179 'user_id', 'user_name', 'user_editcount',
180 ];
181
182 $joins = [
183 // IPs don't have an entry in user table
184 'user' => [ 'LEFT JOIN', 'log_user=user_id' ],
185 ];
186
187 return [
188 'tables' => $tables,
189 'fields' => $fields,
190 'conds' => [],
191 'options' => [],
192 'join_conds' => $joins,
193 ];
194 }
195
196 /**
197 * Constructs new LogEntry from database result row.
198 * Supports rows from both logging and recentchanges table.
199 *
200 * @param stdClass|array $row
201 * @return DatabaseLogEntry
202 */
203 public static function newFromRow( $row ) {
204 $row = (object)$row;
205 if ( isset( $row->rc_logid ) ) {
206 return new RCDatabaseLogEntry( $row );
207 } else {
208 return new self( $row );
209 }
210 }
211
212 /** @var stdClass Database result row. */
213 protected $row;
214
215 /** @var User */
216 protected $performer;
217
218 /** @var array Parameters for log entry */
219 protected $params;
220
221 /** @var int A rev id associated to the log entry */
222 protected $revId = null;
223
224 /** @var bool Whether the parameters for this log entry are stored in new or old format. */
225 protected $legacy;
226
227 protected function __construct( $row ) {
228 $this->row = $row;
229 }
230
231 /**
232 * Returns the unique database id.
233 *
234 * @return int
235 */
236 public function getId() {
237 return (int)$this->row->log_id;
238 }
239
240 /**
241 * Returns whatever is stored in the database field.
242 *
243 * @return string
244 */
245 protected function getRawParameters() {
246 return $this->row->log_params;
247 }
248
249 public function isLegacy() {
250 // This extracts the property
251 $this->getParameters();
252 return $this->legacy;
253 }
254
255 public function getType() {
256 return $this->row->log_type;
257 }
258
259 public function getSubtype() {
260 return $this->row->log_action;
261 }
262
263 public function getParameters() {
264 if ( !isset( $this->params ) ) {
265 $blob = $this->getRawParameters();
266 MediaWiki\suppressWarnings();
267 $params = LogEntryBase::extractParams( $blob );
268 MediaWiki\restoreWarnings();
269 if ( $params !== false ) {
270 $this->params = $params;
271 $this->legacy = false;
272 } else {
273 $this->params = LogPage::extractParams( $blob );
274 $this->legacy = true;
275 }
276
277 if ( isset( $this->params['associated_rev_id'] ) ) {
278 $this->revId = $this->params['associated_rev_id'];
279 unset( $this->params['associated_rev_id'] );
280 }
281 }
282
283 return $this->params;
284 }
285
286 public function getAssociatedRevId() {
287 // This extracts the property
288 $this->getParameters();
289 return $this->revId;
290 }
291
292 public function getPerformer() {
293 if ( !$this->performer ) {
294 $userId = (int)$this->row->log_user;
295 if ( $userId !== 0 ) {
296 // logged-in users
297 if ( isset( $this->row->user_name ) ) {
298 $this->performer = User::newFromRow( $this->row );
299 } else {
300 $this->performer = User::newFromId( $userId );
301 }
302 } else {
303 // IP users
304 $userText = $this->row->log_user_text;
305 $this->performer = User::newFromName( $userText, false );
306 }
307 }
308
309 return $this->performer;
310 }
311
312 public function getTarget() {
313 $namespace = $this->row->log_namespace;
314 $page = $this->row->log_title;
315 $title = Title::makeTitle( $namespace, $page );
316
317 return $title;
318 }
319
320 public function getTimestamp() {
321 return wfTimestamp( TS_MW, $this->row->log_timestamp );
322 }
323
324 public function getComment() {
325 return $this->row->log_comment;
326 }
327
328 public function getDeleted() {
329 return $this->row->log_deleted;
330 }
331 }
332
333 class RCDatabaseLogEntry extends DatabaseLogEntry {
334
335 public function getId() {
336 return $this->row->rc_logid;
337 }
338
339 protected function getRawParameters() {
340 return $this->row->rc_params;
341 }
342
343 public function getAssociatedRevId() {
344 return $this->row->rc_this_oldid;
345 }
346
347 public function getType() {
348 return $this->row->rc_log_type;
349 }
350
351 public function getSubtype() {
352 return $this->row->rc_log_action;
353 }
354
355 public function getPerformer() {
356 if ( !$this->performer ) {
357 $userId = (int)$this->row->rc_user;
358 if ( $userId !== 0 ) {
359 $this->performer = User::newFromId( $userId );
360 } else {
361 $userText = $this->row->rc_user_text;
362 // Might be an IP, don't validate the username
363 $this->performer = User::newFromName( $userText, false );
364 }
365 }
366
367 return $this->performer;
368 }
369
370 public function getTarget() {
371 $namespace = $this->row->rc_namespace;
372 $page = $this->row->rc_title;
373 $title = Title::makeTitle( $namespace, $page );
374
375 return $title;
376 }
377
378 public function getTimestamp() {
379 return wfTimestamp( TS_MW, $this->row->rc_timestamp );
380 }
381
382 public function getComment() {
383 return $this->row->rc_comment;
384 }
385
386 public function getDeleted() {
387 return $this->row->rc_deleted;
388 }
389 }
390
391 /**
392 * Class for creating log entries manually, to inject them into the database.
393 *
394 * @since 1.19
395 */
396 class ManualLogEntry extends LogEntryBase {
397 /** @var string Type of log entry */
398 protected $type;
399
400 /** @var string Sub type of log entry */
401 protected $subtype;
402
403 /** @var array Parameters for log entry */
404 protected $parameters = [];
405
406 /** @var array */
407 protected $relations = [];
408
409 /** @var User Performer of the action for the log entry */
410 protected $performer;
411
412 /** @var Title Target title for the log entry */
413 protected $target;
414
415 /** @var string Timestamp of creation of the log entry */
416 protected $timestamp;
417
418 /** @var string Comment for the log entry */
419 protected $comment = '';
420
421 /** @var int A rev id associated to the log entry */
422 protected $revId = 0;
423
424 /** @var array Change tags add to the log entry */
425 protected $tags = null;
426
427 /** @var int Deletion state of the log entry */
428 protected $deleted;
429
430 /** @var int ID of the log entry */
431 protected $id;
432
433 /** @var bool Can this log entry be patrolled? */
434 protected $isPatrollable = false;
435
436 /** @var bool Whether this is a legacy log entry */
437 protected $legacy = false;
438
439 /**
440 * Constructor.
441 *
442 * @since 1.19
443 * @param string $type
444 * @param string $subtype
445 */
446 public function __construct( $type, $subtype ) {
447 $this->type = $type;
448 $this->subtype = $subtype;
449 }
450
451 /**
452 * Set extra log parameters.
453 *
454 * You can pass params to the log action message by prefixing the keys with
455 * a number and optional type, using colons to separate the fields. The
456 * numbering should start with number 4, the first three parameters are
457 * hardcoded for every message.
458 *
459 * If you want to store stuff that should not be available in messages, don't
460 * prefix the array key with a number and don't use the colons.
461 *
462 * Example:
463 * $entry->setParameters(
464 * '4::color' => 'blue',
465 * '5:number:count' => 3000,
466 * 'animal' => 'dog'
467 * );
468 *
469 * @since 1.19
470 * @param array $parameters Associative array
471 */
472 public function setParameters( $parameters ) {
473 $this->parameters = $parameters;
474 }
475
476 /**
477 * Declare arbitrary tag/value relations to this log entry.
478 * These can be used to filter log entries later on.
479 *
480 * @param array $relations Map of (tag => (list of values|value))
481 * @since 1.22
482 */
483 public function setRelations( array $relations ) {
484 $this->relations = $relations;
485 }
486
487 /**
488 * Set the user that performed the action being logged.
489 *
490 * @since 1.19
491 * @param User $performer
492 */
493 public function setPerformer( User $performer ) {
494 $this->performer = $performer;
495 }
496
497 /**
498 * Set the title of the object changed.
499 *
500 * @since 1.19
501 * @param Title $target
502 */
503 public function setTarget( Title $target ) {
504 $this->target = $target;
505 }
506
507 /**
508 * Set the timestamp of when the logged action took place.
509 *
510 * @since 1.19
511 * @param string $timestamp
512 */
513 public function setTimestamp( $timestamp ) {
514 $this->timestamp = $timestamp;
515 }
516
517 /**
518 * Set a comment associated with the action being logged.
519 *
520 * @since 1.19
521 * @param string $comment
522 */
523 public function setComment( $comment ) {
524 $this->comment = $comment;
525 }
526
527 /**
528 * Set an associated revision id.
529 *
530 * For example, the ID of the revision that was inserted to mark a page move
531 * or protection, file upload, etc.
532 *
533 * @since 1.27
534 * @param int $revId
535 */
536 public function setAssociatedRevId( $revId ) {
537 $this->revId = $revId;
538 }
539
540 /**
541 * Set change tags for the log entry.
542 *
543 * @since 1.27
544 * @param string|string[] $tags
545 */
546 public function setTags( $tags ) {
547 if ( is_string( $tags ) ) {
548 $tags = [ $tags ];
549 }
550 $this->tags = $tags;
551 }
552
553 /**
554 * Set whether this log entry should be made patrollable
555 * This shouldn't depend on config, only on whether there is full support
556 * in the software for patrolling this log entry.
557 * False by default
558 *
559 * @since 1.27
560 * @param bool $patrollable
561 */
562 public function setIsPatrollable( $patrollable ) {
563 $this->isPatrollable = (bool)$patrollable;
564 }
565
566 /**
567 * Set the 'legacy' flag
568 *
569 * @since 1.25
570 * @param bool $legacy
571 */
572 public function setLegacy( $legacy ) {
573 $this->legacy = $legacy;
574 }
575
576 /**
577 * Set the 'deleted' flag.
578 *
579 * @since 1.19
580 * @param int $deleted One of LogPage::DELETED_* bitfield constants
581 */
582 public function setDeleted( $deleted ) {
583 $this->deleted = $deleted;
584 }
585
586 /**
587 * Insert the entry into the `logging` table.
588 *
589 * @param IDatabase $dbw
590 * @return int ID of the log entry
591 * @throws MWException
592 */
593 public function insert( IDatabase $dbw = null ) {
594 global $wgContLang;
595
596 $dbw = $dbw ?: wfGetDB( DB_MASTER );
597 $id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
598
599 if ( $this->timestamp === null ) {
600 $this->timestamp = wfTimestampNow();
601 }
602
603 // Trim spaces on user supplied text
604 $comment = trim( $this->getComment() );
605
606 // Truncate for whole multibyte characters.
607 $comment = $wgContLang->truncate( $comment, 255 );
608
609 $params = $this->getParameters();
610 $relations = $this->relations;
611
612 // Additional fields for which there's no space in the database table schema
613 $revId = $this->getAssociatedRevId();
614 if ( $revId ) {
615 $params['associated_rev_id'] = $revId;
616 $relations['associated_rev_id'] = $revId;
617 }
618
619 $data = [
620 'log_id' => $id,
621 'log_type' => $this->getType(),
622 'log_action' => $this->getSubtype(),
623 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
624 'log_user' => $this->getPerformer()->getId(),
625 'log_user_text' => $this->getPerformer()->getName(),
626 'log_namespace' => $this->getTarget()->getNamespace(),
627 'log_title' => $this->getTarget()->getDBkey(),
628 'log_page' => $this->getTarget()->getArticleID(),
629 'log_comment' => $comment,
630 'log_params' => LogEntryBase::makeParamBlob( $params ),
631 ];
632 if ( isset( $this->deleted ) ) {
633 $data['log_deleted'] = $this->deleted;
634 }
635
636 $dbw->insert( 'logging', $data, __METHOD__ );
637 $this->id = $dbw->insertId();
638
639 $rows = [];
640 foreach ( $relations as $tag => $values ) {
641 if ( !strlen( $tag ) ) {
642 throw new MWException( "Got empty log search tag." );
643 }
644
645 if ( !is_array( $values ) ) {
646 $values = [ $values ];
647 }
648
649 foreach ( $values as $value ) {
650 $rows[] = [
651 'ls_field' => $tag,
652 'ls_value' => $value,
653 'ls_log_id' => $this->id
654 ];
655 }
656 }
657 if ( count( $rows ) ) {
658 $dbw->insert( 'log_search', $rows, __METHOD__, 'IGNORE' );
659 }
660
661 return $this->id;
662 }
663
664 /**
665 * Get a RecentChanges object for the log entry
666 *
667 * @param int $newId
668 * @return RecentChange
669 * @since 1.23
670 */
671 public function getRecentChange( $newId = 0 ) {
672 $formatter = LogFormatter::newFromEntry( $this );
673 $context = RequestContext::newExtraneousContext( $this->getTarget() );
674 $formatter->setContext( $context );
675
676 $logpage = SpecialPage::getTitleFor( 'Log', $this->getType() );
677 $user = $this->getPerformer();
678 $ip = "";
679 if ( $user->isAnon() ) {
680 // "MediaWiki default" and friends may have
681 // no IP address in their name
682 if ( IP::isIPAddress( $user->getName() ) ) {
683 $ip = $user->getName();
684 }
685 }
686
687 return RecentChange::newLogEntry(
688 $this->getTimestamp(),
689 $logpage,
690 $user,
691 $formatter->getPlainActionText(),
692 $ip,
693 $this->getType(),
694 $this->getSubtype(),
695 $this->getTarget(),
696 $this->getComment(),
697 LogEntryBase::makeParamBlob( $this->getParameters() ),
698 $newId,
699 $formatter->getIRCActionComment(), // Used for IRC feeds
700 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
701 $this->getIsPatrollable()
702 );
703 }
704
705 /**
706 * Publish the log entry.
707 *
708 * @param int $newId Id of the log entry.
709 * @param string $to One of: rcandudp (default), rc, udp
710 */
711 public function publish( $newId, $to = 'rcandudp' ) {
712 DeferredUpdates::addCallableUpdate(
713 function () use ( $newId, $to ) {
714 $log = new LogPage( $this->getType() );
715 if ( !$log->isRestricted() ) {
716 $rc = $this->getRecentChange( $newId );
717
718 if ( $to === 'rc' || $to === 'rcandudp' ) {
719 // save RC, passing tags so they are applied there
720 $tags = $this->getTags();
721 if ( is_null( $tags ) ) {
722 $tags = [];
723 }
724 $rc->addTags( $tags );
725 $rc->save( 'pleasedontudp' );
726 }
727
728 if ( $to === 'udp' || $to === 'rcandudp' ) {
729 $rc->notifyRCFeeds();
730 }
731
732 // Log the autopatrol if the log entry is patrollable
733 if ( $this->getIsPatrollable() &&
734 $rc->getAttribute( 'rc_patrolled' ) === 1
735 ) {
736 PatrolLog::record( $rc, true, $this->getPerformer() );
737 }
738 }
739 },
740 DeferredUpdates::POSTSEND,
741 wfGetDB( DB_MASTER )
742 );
743 }
744
745 public function getType() {
746 return $this->type;
747 }
748
749 public function getSubtype() {
750 return $this->subtype;
751 }
752
753 public function getParameters() {
754 return $this->parameters;
755 }
756
757 /**
758 * @return User
759 */
760 public function getPerformer() {
761 return $this->performer;
762 }
763
764 /**
765 * @return Title
766 */
767 public function getTarget() {
768 return $this->target;
769 }
770
771 public function getTimestamp() {
772 $ts = $this->timestamp !== null ? $this->timestamp : wfTimestampNow();
773
774 return wfTimestamp( TS_MW, $ts );
775 }
776
777 public function getComment() {
778 return $this->comment;
779 }
780
781 /**
782 * @since 1.27
783 * @return int
784 */
785 public function getAssociatedRevId() {
786 return $this->revId;
787 }
788
789 /**
790 * @since 1.27
791 * @return array
792 */
793 public function getTags() {
794 return $this->tags;
795 }
796
797 /**
798 * Whether this log entry is patrollable
799 *
800 * @since 1.27
801 * @return bool
802 */
803 public function getIsPatrollable() {
804 return $this->isPatrollable;
805 }
806
807 /**
808 * @since 1.25
809 * @return bool
810 */
811 public function isLegacy() {
812 return $this->legacy;
813 }
814
815 public function getDeleted() {
816 return (int)$this->deleted;
817 }
818 }