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