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