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