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