Merge "Fix small typos"
[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 GPL-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 * A value class to process existing log entries. In other words, this class caches a log
160 * entry from the database and provides an immutable object-oriented representation of it.
161 *
162 * @since 1.19
163 */
164 class DatabaseLogEntry extends LogEntryBase {
165
166 /**
167 * Returns array of information that is needed for querying
168 * log entries. Array contains the following keys:
169 * tables, fields, conds, options and join_conds
170 *
171 * @return array
172 */
173 public static function getSelectQueryData() {
174 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
175 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
176
177 $tables = array_merge(
178 [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
179 );
180 $fields = [
181 'log_id', 'log_type', 'log_action', 'log_timestamp',
182 'log_namespace', 'log_title', // unused log_page
183 'log_params', 'log_deleted',
184 'user_id', 'user_name', 'user_editcount',
185 ] + $commentQuery['fields'] + $actorQuery['fields'];
186
187 $joins = [
188 // IPs don't have an entry in user table
189 'user' => [ 'LEFT JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
190 ] + $commentQuery['joins'] + $actorQuery['joins'];
191
192 return [
193 'tables' => $tables,
194 'fields' => $fields,
195 'conds' => [],
196 'options' => [],
197 'join_conds' => $joins,
198 ];
199 }
200
201 /**
202 * Constructs new LogEntry from database result row.
203 * Supports rows from both logging and recentchanges table.
204 *
205 * @param stdClass|array $row
206 * @return DatabaseLogEntry
207 */
208 public static function newFromRow( $row ) {
209 $row = (object)$row;
210 if ( isset( $row->rc_logid ) ) {
211 return new RCDatabaseLogEntry( $row );
212 } else {
213 return new self( $row );
214 }
215 }
216
217 /**
218 * Loads a LogEntry with the given id from database
219 *
220 * @param int $id
221 * @param IDatabase $db
222 * @return DatabaseLogEntry|null
223 */
224 public static function newFromId( $id, IDatabase $db ) {
225 $queryInfo = self::getSelectQueryData();
226 $queryInfo['conds'] += [ 'log_id' => $id ];
227 $row = $db->selectRow(
228 $queryInfo['tables'],
229 $queryInfo['fields'],
230 $queryInfo['conds'],
231 __METHOD__,
232 $queryInfo['options'],
233 $queryInfo['join_conds']
234 );
235 if ( !$row ) {
236 return null;
237 }
238 return self::newFromRow( $row );
239 }
240
241 /** @var stdClass Database result row. */
242 protected $row;
243
244 /** @var User */
245 protected $performer;
246
247 /** @var array Parameters for log entry */
248 protected $params;
249
250 /** @var int A rev id associated to the log entry */
251 protected $revId = null;
252
253 /** @var bool Whether the parameters for this log entry are stored in new or old format. */
254 protected $legacy;
255
256 protected function __construct( $row ) {
257 $this->row = $row;
258 }
259
260 /**
261 * Returns the unique database id.
262 *
263 * @return int
264 */
265 public function getId() {
266 return (int)$this->row->log_id;
267 }
268
269 /**
270 * Returns whatever is stored in the database field.
271 *
272 * @return string
273 */
274 protected function getRawParameters() {
275 return $this->row->log_params;
276 }
277
278 public function isLegacy() {
279 // This extracts the property
280 $this->getParameters();
281 return $this->legacy;
282 }
283
284 public function getType() {
285 return $this->row->log_type;
286 }
287
288 public function getSubtype() {
289 return $this->row->log_action;
290 }
291
292 public function getParameters() {
293 if ( !isset( $this->params ) ) {
294 $blob = $this->getRawParameters();
295 Wikimedia\suppressWarnings();
296 $params = LogEntryBase::extractParams( $blob );
297 Wikimedia\restoreWarnings();
298 if ( $params !== false ) {
299 $this->params = $params;
300 $this->legacy = false;
301 } else {
302 $this->params = LogPage::extractParams( $blob );
303 $this->legacy = true;
304 }
305
306 if ( isset( $this->params['associated_rev_id'] ) ) {
307 $this->revId = $this->params['associated_rev_id'];
308 unset( $this->params['associated_rev_id'] );
309 }
310 }
311
312 return $this->params;
313 }
314
315 public function getAssociatedRevId() {
316 // This extracts the property
317 $this->getParameters();
318 return $this->revId;
319 }
320
321 public function getPerformer() {
322 if ( !$this->performer ) {
323 $actorId = isset( $this->row->log_actor ) ? (int)$this->row->log_actor : 0;
324 $userId = (int)$this->row->log_user;
325 if ( $userId !== 0 || $actorId !== 0 ) {
326 // logged-in users
327 if ( isset( $this->row->user_name ) ) {
328 $this->performer = User::newFromRow( $this->row );
329 } elseif ( $actorId !== 0 ) {
330 $this->performer = User::newFromActorId( $actorId );
331 } else {
332 $this->performer = User::newFromId( $userId );
333 }
334 } else {
335 // IP users
336 $userText = $this->row->log_user_text;
337 $this->performer = User::newFromName( $userText, false );
338 }
339 }
340
341 return $this->performer;
342 }
343
344 public function getTarget() {
345 $namespace = $this->row->log_namespace;
346 $page = $this->row->log_title;
347 $title = Title::makeTitle( $namespace, $page );
348
349 return $title;
350 }
351
352 public function getTimestamp() {
353 return wfTimestamp( TS_MW, $this->row->log_timestamp );
354 }
355
356 public function getComment() {
357 return CommentStore::getStore()->getComment( 'log_comment', $this->row )->text;
358 }
359
360 public function getDeleted() {
361 return $this->row->log_deleted;
362 }
363 }
364
365 /**
366 * A subclass of DatabaseLogEntry for objects constructed from entries in the
367 * recentchanges table (rather than the logging table).
368 */
369 class RCDatabaseLogEntry extends DatabaseLogEntry {
370
371 public function getId() {
372 return $this->row->rc_logid;
373 }
374
375 protected function getRawParameters() {
376 return $this->row->rc_params;
377 }
378
379 public function getAssociatedRevId() {
380 return $this->row->rc_this_oldid;
381 }
382
383 public function getType() {
384 return $this->row->rc_log_type;
385 }
386
387 public function getSubtype() {
388 return $this->row->rc_log_action;
389 }
390
391 public function getPerformer() {
392 if ( !$this->performer ) {
393 $actorId = isset( $this->row->rc_actor ) ? (int)$this->row->rc_actor : 0;
394 $userId = (int)$this->row->rc_user;
395 if ( $actorId !== 0 ) {
396 $this->performer = User::newFromActorId( $actorId );
397 } elseif ( $userId !== 0 ) {
398 $this->performer = User::newFromId( $userId );
399 } else {
400 $userText = $this->row->rc_user_text;
401 // Might be an IP, don't validate the username
402 $this->performer = User::newFromName( $userText, false );
403 }
404 }
405
406 return $this->performer;
407 }
408
409 public function getTarget() {
410 $namespace = $this->row->rc_namespace;
411 $page = $this->row->rc_title;
412 $title = Title::makeTitle( $namespace, $page );
413
414 return $title;
415 }
416
417 public function getTimestamp() {
418 return wfTimestamp( TS_MW, $this->row->rc_timestamp );
419 }
420
421 public function getComment() {
422 return CommentStore::getStore()
423 // Legacy because the row may have used RecentChange::selectFields()
424 ->getCommentLegacy( wfGetDB( DB_REPLICA ), 'rc_comment', $this->row )->text;
425 }
426
427 public function getDeleted() {
428 return $this->row->rc_deleted;
429 }
430 }
431
432 /**
433 * Class for creating new log entries and inserting them into the database.
434 *
435 * @since 1.19
436 */
437 class ManualLogEntry extends LogEntryBase {
438 /** @var string Type of log entry */
439 protected $type;
440
441 /** @var string Sub type of log entry */
442 protected $subtype;
443
444 /** @var array Parameters for log entry */
445 protected $parameters = [];
446
447 /** @var array */
448 protected $relations = [];
449
450 /** @var User Performer of the action for the log entry */
451 protected $performer;
452
453 /** @var Title Target title for the log entry */
454 protected $target;
455
456 /** @var string Timestamp of creation of the log entry */
457 protected $timestamp;
458
459 /** @var string Comment for the log entry */
460 protected $comment = '';
461
462 /** @var int A rev id associated to the log entry */
463 protected $revId = 0;
464
465 /** @var string[] Change tags add to the log entry */
466 protected $tags = [];
467
468 /** @var int Deletion state of the log entry */
469 protected $deleted;
470
471 /** @var int ID of the log entry */
472 protected $id;
473
474 /** @var bool Can this log entry be patrolled? */
475 protected $isPatrollable = false;
476
477 /** @var bool Whether this is a legacy log entry */
478 protected $legacy = false;
479
480 /**
481 * @since 1.19
482 * @param string $type
483 * @param string $subtype
484 */
485 public function __construct( $type, $subtype ) {
486 $this->type = $type;
487 $this->subtype = $subtype;
488 }
489
490 /**
491 * Set extra log parameters.
492 *
493 * You can pass params to the log action message by prefixing the keys with
494 * a number and optional type, using colons to separate the fields. The
495 * numbering should start with number 4, the first three parameters are
496 * hardcoded for every message.
497 *
498 * If you want to store stuff that should not be available in messages, don't
499 * prefix the array key with a number and don't use the colons.
500 *
501 * Example:
502 * $entry->setParameters(
503 * '4::color' => 'blue',
504 * '5:number:count' => 3000,
505 * 'animal' => 'dog'
506 * );
507 *
508 * @since 1.19
509 * @param array $parameters Associative array
510 */
511 public function setParameters( $parameters ) {
512 $this->parameters = $parameters;
513 }
514
515 /**
516 * Declare arbitrary tag/value relations to this log entry.
517 * These can be used to filter log entries later on.
518 *
519 * @param array $relations Map of (tag => (list of values|value))
520 * @since 1.22
521 */
522 public function setRelations( array $relations ) {
523 $this->relations = $relations;
524 }
525
526 /**
527 * Set the user that performed the action being logged.
528 *
529 * @since 1.19
530 * @param User $performer
531 */
532 public function setPerformer( User $performer ) {
533 $this->performer = $performer;
534 }
535
536 /**
537 * Set the title of the object changed.
538 *
539 * @since 1.19
540 * @param Title $target
541 */
542 public function setTarget( Title $target ) {
543 $this->target = $target;
544 }
545
546 /**
547 * Set the timestamp of when the logged action took place.
548 *
549 * @since 1.19
550 * @param string $timestamp
551 */
552 public function setTimestamp( $timestamp ) {
553 $this->timestamp = $timestamp;
554 }
555
556 /**
557 * Set a comment associated with the action being logged.
558 *
559 * @since 1.19
560 * @param string $comment
561 */
562 public function setComment( $comment ) {
563 $this->comment = $comment;
564 }
565
566 /**
567 * Set an associated revision id.
568 *
569 * For example, the ID of the revision that was inserted to mark a page move
570 * or protection, file upload, etc.
571 *
572 * @since 1.27
573 * @param int $revId
574 */
575 public function setAssociatedRevId( $revId ) {
576 $this->revId = $revId;
577 }
578
579 /**
580 * Set change tags for the log entry.
581 *
582 * Passing `null` means the same as empty array,
583 * for compatibility with WikiPage::doUpdateRestrictions().
584 *
585 * @since 1.27
586 * @param string|string[]|null $tags
587 */
588 public function setTags( $tags ) {
589 if ( $tags === null ) {
590 $tags = [];
591 } elseif ( is_string( $tags ) ) {
592 $tags = [ $tags ];
593 }
594 $this->tags = $tags;
595 }
596
597 /**
598 * Set whether this log entry should be made patrollable
599 * This shouldn't depend on config, only on whether there is full support
600 * in the software for patrolling this log entry.
601 * False by default
602 *
603 * @since 1.27
604 * @param bool $patrollable
605 */
606 public function setIsPatrollable( $patrollable ) {
607 $this->isPatrollable = (bool)$patrollable;
608 }
609
610 /**
611 * Set the 'legacy' flag
612 *
613 * @since 1.25
614 * @param bool $legacy
615 */
616 public function setLegacy( $legacy ) {
617 $this->legacy = $legacy;
618 }
619
620 /**
621 * Set the 'deleted' flag.
622 *
623 * @since 1.19
624 * @param int $deleted One of LogPage::DELETED_* bitfield constants
625 */
626 public function setDeleted( $deleted ) {
627 $this->deleted = $deleted;
628 }
629
630 /**
631 * Insert the entry into the `logging` table.
632 *
633 * @param IDatabase|null $dbw
634 * @return int ID of the log entry
635 * @throws MWException
636 */
637 public function insert( IDatabase $dbw = null ) {
638 global $wgActorTableSchemaMigrationStage;
639
640 $dbw = $dbw ?: wfGetDB( DB_MASTER );
641
642 if ( $this->timestamp === null ) {
643 $this->timestamp = wfTimestampNow();
644 }
645
646 // Trim spaces on user supplied text
647 $comment = trim( $this->getComment() );
648
649 $params = $this->getParameters();
650 $relations = $this->relations;
651
652 // Ensure actor relations are set
653 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) &&
654 empty( $relations['target_author_actor'] )
655 ) {
656 $actorIds = [];
657 if ( !empty( $relations['target_author_id'] ) ) {
658 foreach ( $relations['target_author_id'] as $id ) {
659 $actorIds[] = User::newFromId( $id )->getActorId( $dbw );
660 }
661 }
662 if ( !empty( $relations['target_author_ip'] ) ) {
663 foreach ( $relations['target_author_ip'] as $ip ) {
664 $actorIds[] = User::newFromName( $ip, false )->getActorId( $dbw );
665 }
666 }
667 if ( $actorIds ) {
668 $relations['target_author_actor'] = $actorIds;
669 $params['authorActors'] = $actorIds;
670 }
671 }
672 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
673 unset( $relations['target_author_id'], $relations['target_author_ip'] );
674 unset( $params['authorIds'], $params['authorIPs'] );
675 }
676
677 // Additional fields for which there's no space in the database table schema
678 $revId = $this->getAssociatedRevId();
679 if ( $revId ) {
680 $params['associated_rev_id'] = $revId;
681 $relations['associated_rev_id'] = $revId;
682 }
683
684 $data = [
685 'log_type' => $this->getType(),
686 'log_action' => $this->getSubtype(),
687 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
688 'log_namespace' => $this->getTarget()->getNamespace(),
689 'log_title' => $this->getTarget()->getDBkey(),
690 'log_page' => $this->getTarget()->getArticleID(),
691 'log_params' => LogEntryBase::makeParamBlob( $params ),
692 ];
693 if ( isset( $this->deleted ) ) {
694 $data['log_deleted'] = $this->deleted;
695 }
696 $data += CommentStore::getStore()->insert( $dbw, 'log_comment', $comment );
697 $data += ActorMigration::newMigration()
698 ->getInsertValues( $dbw, 'log_user', $this->getPerformer() );
699
700 $dbw->insert( 'logging', $data, __METHOD__ );
701 $this->id = $dbw->insertId();
702
703 $rows = [];
704 foreach ( $relations as $tag => $values ) {
705 if ( !strlen( $tag ) ) {
706 throw new MWException( "Got empty log search tag." );
707 }
708
709 if ( !is_array( $values ) ) {
710 $values = [ $values ];
711 }
712
713 foreach ( $values as $value ) {
714 $rows[] = [
715 'ls_field' => $tag,
716 'ls_value' => $value,
717 'ls_log_id' => $this->id
718 ];
719 }
720 }
721 if ( count( $rows ) ) {
722 $dbw->insert( 'log_search', $rows, __METHOD__, 'IGNORE' );
723 }
724
725 return $this->id;
726 }
727
728 /**
729 * Get a RecentChanges object for the log entry
730 *
731 * @param int $newId
732 * @return RecentChange
733 * @since 1.23
734 */
735 public function getRecentChange( $newId = 0 ) {
736 $formatter = LogFormatter::newFromEntry( $this );
737 $context = RequestContext::newExtraneousContext( $this->getTarget() );
738 $formatter->setContext( $context );
739
740 $logpage = SpecialPage::getTitleFor( 'Log', $this->getType() );
741 $user = $this->getPerformer();
742 $ip = "";
743 if ( $user->isAnon() ) {
744 // "MediaWiki default" and friends may have
745 // no IP address in their name
746 if ( IP::isIPAddress( $user->getName() ) ) {
747 $ip = $user->getName();
748 }
749 }
750
751 return RecentChange::newLogEntry(
752 $this->getTimestamp(),
753 $logpage,
754 $user,
755 $formatter->getPlainActionText(),
756 $ip,
757 $this->getType(),
758 $this->getSubtype(),
759 $this->getTarget(),
760 $this->getComment(),
761 LogEntryBase::makeParamBlob( $this->getParameters() ),
762 $newId,
763 $formatter->getIRCActionComment(), // Used for IRC feeds
764 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
765 $this->getIsPatrollable()
766 );
767 }
768
769 /**
770 * Publish the log entry.
771 *
772 * @param int $newId Id of the log entry.
773 * @param string $to One of: rcandudp (default), rc, udp
774 */
775 public function publish( $newId, $to = 'rcandudp' ) {
776 DeferredUpdates::addCallableUpdate(
777 function () use ( $newId, $to ) {
778 $log = new LogPage( $this->getType() );
779 if ( !$log->isRestricted() ) {
780 $rc = $this->getRecentChange( $newId );
781
782 if ( $to === 'rc' || $to === 'rcandudp' ) {
783 // save RC, passing tags so they are applied there
784 $rc->addTags( $this->getTags() );
785 $rc->save( $rc::SEND_NONE );
786 }
787
788 if ( $to === 'udp' || $to === 'rcandudp' ) {
789 $rc->notifyRCFeeds();
790 }
791 }
792 },
793 DeferredUpdates::POSTSEND,
794 wfGetDB( DB_MASTER )
795 );
796 }
797
798 public function getType() {
799 return $this->type;
800 }
801
802 public function getSubtype() {
803 return $this->subtype;
804 }
805
806 public function getParameters() {
807 return $this->parameters;
808 }
809
810 /**
811 * @return User
812 */
813 public function getPerformer() {
814 return $this->performer;
815 }
816
817 /**
818 * @return Title
819 */
820 public function getTarget() {
821 return $this->target;
822 }
823
824 public function getTimestamp() {
825 $ts = $this->timestamp ?? wfTimestampNow();
826
827 return wfTimestamp( TS_MW, $ts );
828 }
829
830 public function getComment() {
831 return $this->comment;
832 }
833
834 /**
835 * @since 1.27
836 * @return int
837 */
838 public function getAssociatedRevId() {
839 return $this->revId;
840 }
841
842 /**
843 * @since 1.27
844 * @return string[]
845 */
846 public function getTags() {
847 return $this->tags;
848 }
849
850 /**
851 * Whether this log entry is patrollable
852 *
853 * @since 1.27
854 * @return bool
855 */
856 public function getIsPatrollable() {
857 return $this->isPatrollable;
858 }
859
860 /**
861 * @since 1.25
862 * @return bool
863 */
864 public function isLegacy() {
865 return $this->legacy;
866 }
867
868 public function getDeleted() {
869 return (int)$this->deleted;
870 }
871 }