3 * Contain classes for dealing with individual log entries
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
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.
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.
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
26 * @author Niklas Laxström
27 * @license GPL-2.0-or-later
31 use Wikimedia\Rdbms\IDatabase
;
34 * Interface for log entries. Every log entry has these methods.
45 public function getType();
52 public function getSubtype();
55 * The full logtype in format maintype/subtype.
59 public function getFullType();
62 * Get the extra parameters stored for this message.
66 public function getParameters();
69 * Get the user for performed this action.
73 public function getPerformer();
76 * Get the target page of this action.
80 public function getTarget();
83 * Get the timestamp when the action was executed.
87 public function getTimestamp();
90 * Get the user provided comment.
94 public function getComment();
97 * Get the access restriction.
101 public function getDeleted();
104 * @param int $field One of LogPage::DELETED_* bitfield constants
107 public function isDeleted( $field );
111 * Extends the LogEntryInterface with some basic functionality
115 abstract class LogEntryBase
implements LogEntry
{
117 public function getFullType() {
118 return $this->getType() . '/' . $this->getSubtype();
121 public function isDeleted( $field ) {
122 return ( $this->getDeleted() & $field ) === $field;
126 * Whether the parameters for this log are stored in new or
131 public function isLegacy() {
136 * Create a blob from a parameter array
139 * @param array $params
142 public static function makeParamBlob( $params ) {
143 return serialize( (array)$params );
147 * Extract a parameter array from a blob
150 * @param string $blob
153 public static function extractParams( $blob ) {
154 return unserialize( $blob );
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.
164 class DatabaseLogEntry
extends LogEntryBase
{
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
173 public static function getSelectQueryData() {
174 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
175 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
177 $tables = array_merge(
178 [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
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'];
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'];
197 'join_conds' => $joins,
202 * Constructs new LogEntry from database result row.
203 * Supports rows from both logging and recentchanges table.
205 * @param stdClass|array $row
206 * @return DatabaseLogEntry
208 public static function newFromRow( $row ) {
210 if ( isset( $row->rc_logid
) ) {
211 return new RCDatabaseLogEntry( $row );
213 return new self( $row );
218 * Loads a LogEntry with the given id from database
221 * @param IDatabase $db
222 * @return DatabaseLogEntry|null
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'],
232 $queryInfo['options'],
233 $queryInfo['join_conds']
238 return self
::newFromRow( $row );
241 /** @var stdClass Database result row. */
245 protected $performer;
247 /** @var array Parameters for log entry */
250 /** @var int A rev id associated to the log entry */
251 protected $revId = null;
253 /** @var bool Whether the parameters for this log entry are stored in new or old format. */
256 protected function __construct( $row ) {
261 * Returns the unique database id.
265 public function getId() {
266 return (int)$this->row
->log_id
;
270 * Returns whatever is stored in the database field.
274 protected function getRawParameters() {
275 return $this->row
->log_params
;
278 public function isLegacy() {
279 // This extracts the property
280 $this->getParameters();
281 return $this->legacy
;
284 public function getType() {
285 return $this->row
->log_type
;
288 public function getSubtype() {
289 return $this->row
->log_action
;
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;
302 $this->params
= LogPage
::extractParams( $blob );
303 $this->legacy
= true;
306 if ( isset( $this->params
['associated_rev_id'] ) ) {
307 $this->revId
= $this->params
['associated_rev_id'];
308 unset( $this->params
['associated_rev_id'] );
312 return $this->params
;
315 public function getAssociatedRevId() {
316 // This extracts the property
317 $this->getParameters();
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 ) {
327 if ( isset( $this->row
->user_name
) ) {
328 $this->performer
= User
::newFromRow( $this->row
);
329 } elseif ( $actorId !== 0 ) {
330 $this->performer
= User
::newFromActorId( $actorId );
332 $this->performer
= User
::newFromId( $userId );
336 $userText = $this->row
->log_user_text
;
337 $this->performer
= User
::newFromName( $userText, false );
341 return $this->performer
;
344 public function getTarget() {
345 $namespace = $this->row
->log_namespace
;
346 $page = $this->row
->log_title
;
347 $title = Title
::makeTitle( $namespace, $page );
352 public function getTimestamp() {
353 return wfTimestamp( TS_MW
, $this->row
->log_timestamp
);
356 public function getComment() {
357 return CommentStore
::getStore()->getComment( 'log_comment', $this->row
)->text
;
360 public function getDeleted() {
361 return $this->row
->log_deleted
;
366 * A subclass of DatabaseLogEntry for objects constructed from entries in the
367 * recentchanges table (rather than the logging table).
369 class RCDatabaseLogEntry
extends DatabaseLogEntry
{
371 public function getId() {
372 return $this->row
->rc_logid
;
375 protected function getRawParameters() {
376 return $this->row
->rc_params
;
379 public function getAssociatedRevId() {
380 return $this->row
->rc_this_oldid
;
383 public function getType() {
384 return $this->row
->rc_log_type
;
387 public function getSubtype() {
388 return $this->row
->rc_log_action
;
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 );
400 $userText = $this->row
->rc_user_text
;
401 // Might be an IP, don't validate the username
402 $this->performer
= User
::newFromName( $userText, false );
406 return $this->performer
;
409 public function getTarget() {
410 $namespace = $this->row
->rc_namespace
;
411 $page = $this->row
->rc_title
;
412 $title = Title
::makeTitle( $namespace, $page );
417 public function getTimestamp() {
418 return wfTimestamp( TS_MW
, $this->row
->rc_timestamp
);
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
;
427 public function getDeleted() {
428 return $this->row
->rc_deleted
;
433 * Class for creating new log entries and inserting them into the database.
437 class ManualLogEntry
extends LogEntryBase
{
438 /** @var string Type of log entry */
441 /** @var string Sub type of log entry */
444 /** @var array Parameters for log entry */
445 protected $parameters = [];
448 protected $relations = [];
450 /** @var User Performer of the action for the log entry */
451 protected $performer;
453 /** @var Title Target title for the log entry */
456 /** @var string Timestamp of creation of the log entry */
457 protected $timestamp;
459 /** @var string Comment for the log entry */
460 protected $comment = '';
462 /** @var int A rev id associated to the log entry */
463 protected $revId = 0;
465 /** @var array Change tags add to the log entry */
466 protected $tags = null;
468 /** @var int Deletion state of the log entry */
471 /** @var int ID of the log entry */
474 /** @var bool Can this log entry be patrolled? */
475 protected $isPatrollable = false;
477 /** @var bool Whether this is a legacy log entry */
478 protected $legacy = false;
482 * @param string $type
483 * @param string $subtype
485 public function __construct( $type, $subtype ) {
487 $this->subtype
= $subtype;
491 * Set extra log parameters.
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.
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.
502 * $entry->setParameters(
503 * '4::color' => 'blue',
504 * '5:number:count' => 3000,
509 * @param array $parameters Associative array
511 public function setParameters( $parameters ) {
512 $this->parameters
= $parameters;
516 * Declare arbitrary tag/value relations to this log entry.
517 * These can be used to filter log entries later on.
519 * @param array $relations Map of (tag => (list of values|value))
522 public function setRelations( array $relations ) {
523 $this->relations
= $relations;
527 * Set the user that performed the action being logged.
530 * @param User $performer
532 public function setPerformer( User
$performer ) {
533 $this->performer
= $performer;
537 * Set the title of the object changed.
540 * @param Title $target
542 public function setTarget( Title
$target ) {
543 $this->target
= $target;
547 * Set the timestamp of when the logged action took place.
550 * @param string $timestamp
552 public function setTimestamp( $timestamp ) {
553 $this->timestamp
= $timestamp;
557 * Set a comment associated with the action being logged.
560 * @param string $comment
562 public function setComment( $comment ) {
563 $this->comment
= $comment;
567 * Set an associated revision id.
569 * For example, the ID of the revision that was inserted to mark a page move
570 * or protection, file upload, etc.
575 public function setAssociatedRevId( $revId ) {
576 $this->revId
= $revId;
580 * Set change tags for the log entry.
583 * @param string|string[] $tags
585 public function setTags( $tags ) {
586 if ( is_string( $tags ) ) {
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.
599 * @param bool $patrollable
601 public function setIsPatrollable( $patrollable ) {
602 $this->isPatrollable
= (bool)$patrollable;
606 * Set the 'legacy' flag
609 * @param bool $legacy
611 public function setLegacy( $legacy ) {
612 $this->legacy
= $legacy;
616 * Set the 'deleted' flag.
619 * @param int $deleted One of LogPage::DELETED_* bitfield constants
621 public function setDeleted( $deleted ) {
622 $this->deleted
= $deleted;
626 * Insert the entry into the `logging` table.
628 * @param IDatabase|null $dbw
629 * @return int ID of the log entry
630 * @throws MWException
632 public function insert( IDatabase
$dbw = null ) {
633 global $wgActorTableSchemaMigrationStage;
635 $dbw = $dbw ?
: wfGetDB( DB_MASTER
);
637 if ( $this->timestamp
=== null ) {
638 $this->timestamp
= wfTimestampNow();
641 // Trim spaces on user supplied text
642 $comment = trim( $this->getComment() );
644 $params = $this->getParameters();
645 $relations = $this->relations
;
647 // Ensure actor relations are set
648 if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
&&
649 empty( $relations['target_author_actor'] )
652 if ( !empty( $relations['target_author_id'] ) ) {
653 foreach ( $relations['target_author_id'] as $id ) {
654 $actorIds[] = User
::newFromId( $id )->getActorId( $dbw );
657 if ( !empty( $relations['target_author_ip'] ) ) {
658 foreach ( $relations['target_author_ip'] as $ip ) {
659 $actorIds[] = User
::newFromName( $ip, false )->getActorId( $dbw );
663 $relations['target_author_actor'] = $actorIds;
664 $params['authorActors'] = $actorIds;
667 if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_NEW
) {
668 unset( $relations['target_author_id'], $relations['target_author_ip'] );
669 unset( $params['authorIds'], $params['authorIPs'] );
672 // Additional fields for which there's no space in the database table schema
673 $revId = $this->getAssociatedRevId();
675 $params['associated_rev_id'] = $revId;
676 $relations['associated_rev_id'] = $revId;
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 ),
688 if ( isset( $this->deleted
) ) {
689 $data['log_deleted'] = $this->deleted
;
691 $data +
= CommentStore
::getStore()->insert( $dbw, 'log_comment', $comment );
692 $data +
= ActorMigration
::newMigration()
693 ->getInsertValues( $dbw, 'log_user', $this->getPerformer() );
695 $dbw->insert( 'logging', $data, __METHOD__
);
696 $this->id
= $dbw->insertId();
699 foreach ( $relations as $tag => $values ) {
700 if ( !strlen( $tag ) ) {
701 throw new MWException( "Got empty log search tag." );
704 if ( !is_array( $values ) ) {
705 $values = [ $values ];
708 foreach ( $values as $value ) {
711 'ls_value' => $value,
712 'ls_log_id' => $this->id
716 if ( count( $rows ) ) {
717 $dbw->insert( 'log_search', $rows, __METHOD__
, 'IGNORE' );
724 * Get a RecentChanges object for the log entry
727 * @return RecentChange
730 public function getRecentChange( $newId = 0 ) {
731 $formatter = LogFormatter
::newFromEntry( $this );
732 $context = RequestContext
::newExtraneousContext( $this->getTarget() );
733 $formatter->setContext( $context );
735 $logpage = SpecialPage
::getTitleFor( 'Log', $this->getType() );
736 $user = $this->getPerformer();
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();
746 return RecentChange
::newLogEntry(
747 $this->getTimestamp(),
750 $formatter->getPlainActionText(),
756 LogEntryBase
::makeParamBlob( $this->getParameters() ),
758 $formatter->getIRCActionComment(), // Used for IRC feeds
759 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
760 $this->getIsPatrollable()
765 * Publish the log entry.
767 * @param int $newId Id of the log entry.
768 * @param string $to One of: rcandudp (default), rc, udp
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 );
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 ) ) {
783 $rc->addTags( $tags );
784 $rc->save( $rc::SEND_NONE
);
787 if ( $to === 'udp' ||
$to === 'rcandudp' ) {
788 $rc->notifyRCFeeds();
792 DeferredUpdates
::POSTSEND
,
797 public function getType() {
801 public function getSubtype() {
802 return $this->subtype
;
805 public function getParameters() {
806 return $this->parameters
;
812 public function getPerformer() {
813 return $this->performer
;
819 public function getTarget() {
820 return $this->target
;
823 public function getTimestamp() {
824 $ts = $this->timestamp
!== null ?
$this->timestamp
: wfTimestampNow();
826 return wfTimestamp( TS_MW
, $ts );
829 public function getComment() {
830 return $this->comment
;
837 public function getAssociatedRevId() {
845 public function getTags() {
850 * Whether this log entry is patrollable
855 public function getIsPatrollable() {
856 return $this->isPatrollable
;
863 public function isLegacy() {
864 return $this->legacy
;
867 public function getDeleted() {
868 return (int)$this->deleted
;