Merge "Avoid using outdated $casToken field for BagOStuff calls"
[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 string[] Change tags add to the log entry */
468 protected $tags = [];
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 * Passing `null` means the same as empty array,
585 * for compatibility with WikiPage::doUpdateRestrictions().
586 *
587 * @since 1.27
588 * @param string|string[]|null $tags
589 */
590 public function setTags( $tags ) {
591 if ( $tags === null ) {
592 $tags = [];
593 } elseif ( is_string( $tags ) ) {
594 $tags = [ $tags ];
595 }
596 $this->tags = $tags;
597 }
598
599 /**
600 * Set whether this log entry should be made patrollable
601 * This shouldn't depend on config, only on whether there is full support
602 * in the software for patrolling this log entry.
603 * False by default
604 *
605 * @since 1.27
606 * @param bool $patrollable
607 */
608 public function setIsPatrollable( $patrollable ) {
609 $this->isPatrollable = (bool)$patrollable;
610 }
611
612 /**
613 * Set the 'legacy' flag
614 *
615 * @since 1.25
616 * @param bool $legacy
617 */
618 public function setLegacy( $legacy ) {
619 $this->legacy = $legacy;
620 }
621
622 /**
623 * Set the 'deleted' flag.
624 *
625 * @since 1.19
626 * @param int $deleted One of LogPage::DELETED_* bitfield constants
627 */
628 public function setDeleted( $deleted ) {
629 $this->deleted = $deleted;
630 }
631
632 /**
633 * Insert the entry into the `logging` table.
634 *
635 * @param IDatabase|null $dbw
636 * @return int ID of the log entry
637 * @throws MWException
638 */
639 public function insert( IDatabase $dbw = null ) {
640 global $wgActorTableSchemaMigrationStage;
641
642 $dbw = $dbw ?: wfGetDB( DB_MASTER );
643
644 if ( $this->timestamp === null ) {
645 $this->timestamp = wfTimestampNow();
646 }
647
648 // Trim spaces on user supplied text
649 $comment = trim( $this->getComment() );
650
651 $params = $this->getParameters();
652 $relations = $this->relations;
653
654 // Ensure actor relations are set
655 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) &&
656 empty( $relations['target_author_actor'] )
657 ) {
658 $actorIds = [];
659 if ( !empty( $relations['target_author_id'] ) ) {
660 foreach ( $relations['target_author_id'] as $id ) {
661 $actorIds[] = User::newFromId( $id )->getActorId( $dbw );
662 }
663 }
664 if ( !empty( $relations['target_author_ip'] ) ) {
665 foreach ( $relations['target_author_ip'] as $ip ) {
666 $actorIds[] = User::newFromName( $ip, false )->getActorId( $dbw );
667 }
668 }
669 if ( $actorIds ) {
670 $relations['target_author_actor'] = $actorIds;
671 $params['authorActors'] = $actorIds;
672 }
673 }
674 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
675 unset( $relations['target_author_id'], $relations['target_author_ip'] );
676 unset( $params['authorIds'], $params['authorIPs'] );
677 }
678
679 // Additional fields for which there's no space in the database table schema
680 $revId = $this->getAssociatedRevId();
681 if ( $revId ) {
682 $params['associated_rev_id'] = $revId;
683 $relations['associated_rev_id'] = $revId;
684 }
685
686 $data = [
687 'log_type' => $this->getType(),
688 'log_action' => $this->getSubtype(),
689 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
690 'log_namespace' => $this->getTarget()->getNamespace(),
691 'log_title' => $this->getTarget()->getDBkey(),
692 'log_page' => $this->getTarget()->getArticleID(),
693 'log_params' => LogEntryBase::makeParamBlob( $params ),
694 ];
695 if ( isset( $this->deleted ) ) {
696 $data['log_deleted'] = $this->deleted;
697 }
698 $data += CommentStore::getStore()->insert( $dbw, 'log_comment', $comment );
699 $data += ActorMigration::newMigration()
700 ->getInsertValues( $dbw, 'log_user', $this->getPerformer() );
701
702 $dbw->insert( 'logging', $data, __METHOD__ );
703 $this->id = $dbw->insertId();
704
705 $rows = [];
706 foreach ( $relations as $tag => $values ) {
707 if ( !strlen( $tag ) ) {
708 throw new MWException( "Got empty log search tag." );
709 }
710
711 if ( !is_array( $values ) ) {
712 $values = [ $values ];
713 }
714
715 foreach ( $values as $value ) {
716 $rows[] = [
717 'ls_field' => $tag,
718 'ls_value' => $value,
719 'ls_log_id' => $this->id
720 ];
721 }
722 }
723 if ( count( $rows ) ) {
724 $dbw->insert( 'log_search', $rows, __METHOD__, 'IGNORE' );
725 }
726
727 return $this->id;
728 }
729
730 /**
731 * Get a RecentChanges object for the log entry
732 *
733 * @param int $newId
734 * @return RecentChange
735 * @since 1.23
736 */
737 public function getRecentChange( $newId = 0 ) {
738 $formatter = LogFormatter::newFromEntry( $this );
739 $context = RequestContext::newExtraneousContext( $this->getTarget() );
740 $formatter->setContext( $context );
741
742 $logpage = SpecialPage::getTitleFor( 'Log', $this->getType() );
743 $user = $this->getPerformer();
744 $ip = "";
745 if ( $user->isAnon() ) {
746 // "MediaWiki default" and friends may have
747 // no IP address in their name
748 if ( IP::isIPAddress( $user->getName() ) ) {
749 $ip = $user->getName();
750 }
751 }
752
753 return RecentChange::newLogEntry(
754 $this->getTimestamp(),
755 $logpage,
756 $user,
757 $formatter->getPlainActionText(),
758 $ip,
759 $this->getType(),
760 $this->getSubtype(),
761 $this->getTarget(),
762 $this->getComment(),
763 LogEntryBase::makeParamBlob( $this->getParameters() ),
764 $newId,
765 $formatter->getIRCActionComment(), // Used for IRC feeds
766 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
767 $this->getIsPatrollable()
768 );
769 }
770
771 /**
772 * Publish the log entry.
773 *
774 * @param int $newId Id of the log entry.
775 * @param string $to One of: rcandudp (default), rc, udp
776 */
777 public function publish( $newId, $to = 'rcandudp' ) {
778 DeferredUpdates::addCallableUpdate(
779 function () use ( $newId, $to ) {
780 $log = new LogPage( $this->getType() );
781 if ( !$log->isRestricted() ) {
782 $rc = $this->getRecentChange( $newId );
783
784 if ( $to === 'rc' || $to === 'rcandudp' ) {
785 // save RC, passing tags so they are applied there
786 $rc->addTags( $this->getTags() );
787 $rc->save( $rc::SEND_NONE );
788 } else {
789 $tags = $this->getTags();
790 if ( $tags ) {
791 $revId = $this->getAssociatedRevId(); // Use null if $revId is 0
792 ChangeTags::addTags( $tags, null, $revId > 0 ? $revId : null, $newId );
793 }
794 }
795
796 if ( $to === 'udp' || $to === 'rcandudp' ) {
797 $rc->notifyRCFeeds();
798 }
799 }
800 },
801 DeferredUpdates::POSTSEND,
802 wfGetDB( DB_MASTER )
803 );
804 }
805
806 public function getType() {
807 return $this->type;
808 }
809
810 public function getSubtype() {
811 return $this->subtype;
812 }
813
814 public function getParameters() {
815 return $this->parameters;
816 }
817
818 /**
819 * @return User
820 */
821 public function getPerformer() {
822 return $this->performer;
823 }
824
825 /**
826 * @return Title
827 */
828 public function getTarget() {
829 return $this->target;
830 }
831
832 public function getTimestamp() {
833 $ts = $this->timestamp ?? wfTimestampNow();
834
835 return wfTimestamp( TS_MW, $ts );
836 }
837
838 public function getComment() {
839 return $this->comment;
840 }
841
842 /**
843 * @since 1.27
844 * @return int
845 */
846 public function getAssociatedRevId() {
847 return $this->revId;
848 }
849
850 /**
851 * @since 1.27
852 * @return string[]
853 */
854 public function getTags() {
855 return $this->tags;
856 }
857
858 /**
859 * Whether this log entry is patrollable
860 *
861 * @since 1.27
862 * @return bool
863 */
864 public function getIsPatrollable() {
865 return $this->isPatrollable;
866 }
867
868 /**
869 * @since 1.25
870 * @return bool
871 */
872 public function isLegacy() {
873 return $this->legacy;
874 }
875
876 public function getDeleted() {
877 return (int)$this->deleted;
878 }
879 }