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 MediaWiki\ChangeTags\Taggable
;
32 use MediaWiki\Linker\LinkTarget
;
33 use MediaWiki\User\UserIdentity
;
34 use Wikimedia\Rdbms\IDatabase
;
35 use Wikimedia\Assert\Assert
;
38 * Interface for log entries. Every log entry has these methods.
49 public function getType();
56 public function getSubtype();
59 * The full logtype in format maintype/subtype.
63 public function getFullType();
66 * Get the extra parameters stored for this message.
70 public function getParameters();
73 * Get the user for performed this action.
77 public function getPerformer();
80 * Get the target page of this action.
84 public function getTarget();
87 * Get the timestamp when the action was executed.
91 public function getTimestamp();
94 * Get the user provided comment.
98 public function getComment();
101 * Get the access restriction.
105 public function getDeleted();
108 * @param int $field One of LogPage::DELETED_* bitfield constants
111 public function isDeleted( $field );
115 * Extends the LogEntryInterface with some basic functionality
119 abstract class LogEntryBase
implements LogEntry
{
121 public function getFullType() {
122 return $this->getType() . '/' . $this->getSubtype();
125 public function isDeleted( $field ) {
126 return ( $this->getDeleted() & $field ) === $field;
130 * Whether the parameters for this log are stored in new or
135 public function isLegacy() {
140 * Create a blob from a parameter array
143 * @param array $params
146 public static function makeParamBlob( $params ) {
147 return serialize( (array)$params );
151 * Extract a parameter array from a blob
154 * @param string $blob
157 public static function extractParams( $blob ) {
158 return unserialize( $blob );
163 * A value class to process existing log entries. In other words, this class caches a log
164 * entry from the database and provides an immutable object-oriented representation of it.
168 class DatabaseLogEntry
extends LogEntryBase
{
171 * Returns array of information that is needed for querying
172 * log entries. Array contains the following keys:
173 * tables, fields, conds, options and join_conds
177 public static function getSelectQueryData() {
178 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
179 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
181 $tables = array_merge(
182 [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ]
185 'log_id', 'log_type', 'log_action', 'log_timestamp',
186 'log_namespace', 'log_title', // unused log_page
187 'log_params', 'log_deleted',
188 'user_id', 'user_name', 'user_editcount',
189 ] +
$commentQuery['fields'] +
$actorQuery['fields'];
192 // IPs don't have an entry in user table
193 'user' => [ 'LEFT JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
194 ] +
$commentQuery['joins'] +
$actorQuery['joins'];
201 'join_conds' => $joins,
206 * Constructs new LogEntry from database result row.
207 * Supports rows from both logging and recentchanges table.
209 * @param stdClass|array $row
210 * @return DatabaseLogEntry
212 public static function newFromRow( $row ) {
214 if ( isset( $row->rc_logid
) ) {
215 return new RCDatabaseLogEntry( $row );
217 return new self( $row );
222 * Loads a LogEntry with the given id from database
225 * @param IDatabase $db
226 * @return DatabaseLogEntry|null
228 public static function newFromId( $id, IDatabase
$db ) {
229 $queryInfo = self
::getSelectQueryData();
230 $queryInfo['conds'] +
= [ 'log_id' => $id ];
231 $row = $db->selectRow(
232 $queryInfo['tables'],
233 $queryInfo['fields'],
236 $queryInfo['options'],
237 $queryInfo['join_conds']
242 return self
::newFromRow( $row );
245 /** @var stdClass Database result row. */
249 protected $performer;
251 /** @var array Parameters for log entry */
254 /** @var int A rev id associated to the log entry */
255 protected $revId = null;
257 /** @var bool Whether the parameters for this log entry are stored in new or old format. */
260 protected function __construct( $row ) {
265 * Returns the unique database id.
269 public function getId() {
270 return (int)$this->row
->log_id
;
274 * Returns whatever is stored in the database field.
278 protected function getRawParameters() {
279 return $this->row
->log_params
;
282 public function isLegacy() {
283 // This extracts the property
284 $this->getParameters();
285 return $this->legacy
;
288 public function getType() {
289 return $this->row
->log_type
;
292 public function getSubtype() {
293 return $this->row
->log_action
;
296 public function getParameters() {
297 if ( !isset( $this->params
) ) {
298 $blob = $this->getRawParameters();
299 Wikimedia\
suppressWarnings();
300 $params = LogEntryBase
::extractParams( $blob );
301 Wikimedia\restoreWarnings
();
302 if ( $params !== false ) {
303 $this->params
= $params;
304 $this->legacy
= false;
306 $this->params
= LogPage
::extractParams( $blob );
307 $this->legacy
= true;
310 if ( isset( $this->params
['associated_rev_id'] ) ) {
311 $this->revId
= $this->params
['associated_rev_id'];
312 unset( $this->params
['associated_rev_id'] );
316 return $this->params
;
319 public function getAssociatedRevId() {
320 // This extracts the property
321 $this->getParameters();
325 public function getPerformer() {
326 if ( !$this->performer
) {
327 $actorId = isset( $this->row
->log_actor
) ?
(int)$this->row
->log_actor
: 0;
328 $userId = (int)$this->row
->log_user
;
329 if ( $userId !== 0 ||
$actorId !== 0 ) {
331 if ( isset( $this->row
->user_name
) ) {
332 $this->performer
= User
::newFromRow( $this->row
);
333 } elseif ( $actorId !== 0 ) {
334 $this->performer
= User
::newFromActorId( $actorId );
336 $this->performer
= User
::newFromId( $userId );
340 $userText = $this->row
->log_user_text
;
341 $this->performer
= User
::newFromName( $userText, false );
345 return $this->performer
;
348 public function getTarget() {
349 $namespace = $this->row
->log_namespace
;
350 $page = $this->row
->log_title
;
351 $title = Title
::makeTitle( $namespace, $page );
356 public function getTimestamp() {
357 return wfTimestamp( TS_MW
, $this->row
->log_timestamp
);
360 public function getComment() {
361 return CommentStore
::getStore()->getComment( 'log_comment', $this->row
)->text
;
364 public function getDeleted() {
365 return $this->row
->log_deleted
;
370 * A subclass of DatabaseLogEntry for objects constructed from entries in the
371 * recentchanges table (rather than the logging table).
373 class RCDatabaseLogEntry
extends DatabaseLogEntry
{
375 public function getId() {
376 return $this->row
->rc_logid
;
379 protected function getRawParameters() {
380 return $this->row
->rc_params
;
383 public function getAssociatedRevId() {
384 return $this->row
->rc_this_oldid
;
387 public function getType() {
388 return $this->row
->rc_log_type
;
391 public function getSubtype() {
392 return $this->row
->rc_log_action
;
395 public function getPerformer() {
396 if ( !$this->performer
) {
397 $actorId = isset( $this->row
->rc_actor
) ?
(int)$this->row
->rc_actor
: 0;
398 $userId = (int)$this->row
->rc_user
;
399 if ( $actorId !== 0 ) {
400 $this->performer
= User
::newFromActorId( $actorId );
401 } elseif ( $userId !== 0 ) {
402 $this->performer
= User
::newFromId( $userId );
404 $userText = $this->row
->rc_user_text
;
405 // Might be an IP, don't validate the username
406 $this->performer
= User
::newFromName( $userText, false );
410 return $this->performer
;
413 public function getTarget() {
414 $namespace = $this->row
->rc_namespace
;
415 $page = $this->row
->rc_title
;
416 $title = Title
::makeTitle( $namespace, $page );
421 public function getTimestamp() {
422 return wfTimestamp( TS_MW
, $this->row
->rc_timestamp
);
425 public function getComment() {
426 return CommentStore
::getStore()
427 // Legacy because the row may have used RecentChange::selectFields()
428 ->getCommentLegacy( wfGetDB( DB_REPLICA
), 'rc_comment', $this->row
)->text
;
431 public function getDeleted() {
432 return $this->row
->rc_deleted
;
437 * Class for creating new log entries and inserting them into the database.
441 class ManualLogEntry
extends LogEntryBase
implements Taggable
{
442 /** @var string Type of log entry */
445 /** @var string Sub type of log entry */
448 /** @var array Parameters for log entry */
449 protected $parameters = [];
452 protected $relations = [];
454 /** @var User Performer of the action for the log entry */
455 protected $performer;
457 /** @var Title Target title for the log entry */
460 /** @var string Timestamp of creation of the log entry */
461 protected $timestamp;
463 /** @var string Comment for the log entry */
464 protected $comment = '';
466 /** @var int A rev id associated to the log entry */
467 protected $revId = 0;
469 /** @var string[] Change tags add to the log entry */
470 protected $tags = [];
472 /** @var int Deletion state of the log entry */
475 /** @var int ID of the log entry */
478 /** @var bool Can this log entry be patrolled? */
479 protected $isPatrollable = false;
481 /** @var bool Whether this is a legacy log entry */
482 protected $legacy = false;
486 * @param string $type
487 * @param string $subtype
489 public function __construct( $type, $subtype ) {
491 $this->subtype
= $subtype;
495 * Set extra log parameters.
497 * You can pass params to the log action message by prefixing the keys with
498 * a number and optional type, using colons to separate the fields. The
499 * numbering should start with number 4, the first three parameters are
500 * hardcoded for every message.
502 * If you want to store stuff that should not be available in messages, don't
503 * prefix the array key with a number and don't use the colons.
506 * $entry->setParameters(
507 * '4::color' => 'blue',
508 * '5:number:count' => 3000,
513 * @param array $parameters Associative array
515 public function setParameters( $parameters ) {
516 $this->parameters
= $parameters;
520 * Declare arbitrary tag/value relations to this log entry.
521 * These can be used to filter log entries later on.
523 * @param array $relations Map of (tag => (list of values|value))
526 public function setRelations( array $relations ) {
527 $this->relations
= $relations;
531 * Set the user that performed the action being logged.
534 * @param UserIdentity $performer
536 public function setPerformer( UserIdentity
$performer ) {
537 $this->performer
= User
::newFromIdentity( $performer );
541 * Set the title of the object changed.
544 * @param LinkTarget $target
546 public function setTarget( LinkTarget
$target ) {
547 $this->target
= Title
::newFromLinkTarget( $target );
551 * Set the timestamp of when the logged action took place.
554 * @param string $timestamp
556 public function setTimestamp( $timestamp ) {
557 $this->timestamp
= $timestamp;
561 * Set a comment associated with the action being logged.
564 * @param string $comment
566 public function setComment( $comment ) {
567 $this->comment
= $comment;
571 * Set an associated revision id.
573 * For example, the ID of the revision that was inserted to mark a page move
574 * or protection, file upload, etc.
579 public function setAssociatedRevId( $revId ) {
580 $this->revId
= $revId;
584 * Set change tags for the log entry.
586 * Passing `null` means the same as empty array,
587 * for compatibility with WikiPage::doUpdateRestrictions().
590 * @param string|string[]|null $tags
591 * @deprecated since 1.33 Please use addTags() instead
593 public function setTags( $tags ) {
595 wfDebug( 'Overwriting existing ManualLogEntry tags' );
598 if ( $tags !== null ) {
599 $this->addTags( $tags );
604 * Add change tags for the log entry
607 * @param string|string[] $tags Tags to apply
609 public function addTags( $tags ) {
610 if ( is_string( $tags ) ) {
613 Assert
::parameterElementType( 'string', $tags, 'tags' );
614 $this->tags
= array_unique( array_merge( $this->tags
, $tags ) );
618 * Set whether this log entry should be made patrollable
619 * This shouldn't depend on config, only on whether there is full support
620 * in the software for patrolling this log entry.
624 * @param bool $patrollable
626 public function setIsPatrollable( $patrollable ) {
627 $this->isPatrollable
= (bool)$patrollable;
631 * Set the 'legacy' flag
634 * @param bool $legacy
636 public function setLegacy( $legacy ) {
637 $this->legacy
= $legacy;
641 * Set the 'deleted' flag.
644 * @param int $deleted One of LogPage::DELETED_* bitfield constants
646 public function setDeleted( $deleted ) {
647 $this->deleted
= $deleted;
651 * Insert the entry into the `logging` table.
653 * @param IDatabase|null $dbw
654 * @return int ID of the log entry
655 * @throws MWException
657 public function insert( IDatabase
$dbw = null ) {
658 global $wgActorTableSchemaMigrationStage;
660 $dbw = $dbw ?
: wfGetDB( DB_MASTER
);
662 if ( $this->timestamp
=== null ) {
663 $this->timestamp
= wfTimestampNow();
666 // Trim spaces on user supplied text
667 $comment = trim( $this->getComment() );
669 $params = $this->getParameters();
670 $relations = $this->relations
;
672 // Ensure actor relations are set
673 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
674 empty( $relations['target_author_actor'] )
677 if ( !empty( $relations['target_author_id'] ) ) {
678 foreach ( $relations['target_author_id'] as $id ) {
679 $actorIds[] = User
::newFromId( $id )->getActorId( $dbw );
682 if ( !empty( $relations['target_author_ip'] ) ) {
683 foreach ( $relations['target_author_ip'] as $ip ) {
684 $actorIds[] = User
::newFromName( $ip, false )->getActorId( $dbw );
688 $relations['target_author_actor'] = $actorIds;
689 $params['authorActors'] = $actorIds;
692 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) ) {
693 unset( $relations['target_author_id'], $relations['target_author_ip'] );
694 unset( $params['authorIds'], $params['authorIPs'] );
697 // Additional fields for which there's no space in the database table schema
698 $revId = $this->getAssociatedRevId();
700 $params['associated_rev_id'] = $revId;
701 $relations['associated_rev_id'] = $revId;
705 'log_type' => $this->getType(),
706 'log_action' => $this->getSubtype(),
707 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
708 'log_namespace' => $this->getTarget()->getNamespace(),
709 'log_title' => $this->getTarget()->getDBkey(),
710 'log_page' => $this->getTarget()->getArticleID(),
711 'log_params' => LogEntryBase
::makeParamBlob( $params ),
713 if ( isset( $this->deleted
) ) {
714 $data['log_deleted'] = $this->deleted
;
716 $data +
= CommentStore
::getStore()->insert( $dbw, 'log_comment', $comment );
717 $data +
= ActorMigration
::newMigration()
718 ->getInsertValues( $dbw, 'log_user', $this->getPerformer() );
720 $dbw->insert( 'logging', $data, __METHOD__
);
721 $this->id
= $dbw->insertId();
724 foreach ( $relations as $tag => $values ) {
725 if ( !strlen( $tag ) ) {
726 throw new MWException( "Got empty log search tag." );
729 if ( !is_array( $values ) ) {
730 $values = [ $values ];
733 foreach ( $values as $value ) {
736 'ls_value' => $value,
737 'ls_log_id' => $this->id
741 if ( count( $rows ) ) {
742 $dbw->insert( 'log_search', $rows, __METHOD__
, 'IGNORE' );
749 * Get a RecentChanges object for the log entry
752 * @return RecentChange
755 public function getRecentChange( $newId = 0 ) {
756 $formatter = LogFormatter
::newFromEntry( $this );
757 $context = RequestContext
::newExtraneousContext( $this->getTarget() );
758 $formatter->setContext( $context );
760 $logpage = SpecialPage
::getTitleFor( 'Log', $this->getType() );
761 $user = $this->getPerformer();
763 if ( $user->isAnon() ) {
764 // "MediaWiki default" and friends may have
765 // no IP address in their name
766 if ( IP
::isIPAddress( $user->getName() ) ) {
767 $ip = $user->getName();
771 return RecentChange
::newLogEntry(
772 $this->getTimestamp(),
775 $formatter->getPlainActionText(),
781 LogEntryBase
::makeParamBlob( $this->getParameters() ),
783 $formatter->getIRCActionComment(), // Used for IRC feeds
784 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
785 $this->getIsPatrollable()
790 * Publish the log entry.
792 * @param int $newId Id of the log entry.
793 * @param string $to One of: rcandudp (default), rc, udp
795 public function publish( $newId, $to = 'rcandudp' ) {
796 DeferredUpdates
::addCallableUpdate(
797 function () use ( $newId, $to ) {
798 $log = new LogPage( $this->getType() );
799 if ( !$log->isRestricted() ) {
800 Hooks
::runWithoutAbort( 'ManualLogEntryBeforePublish', [ $this ] );
801 $rc = $this->getRecentChange( $newId );
803 if ( $to === 'rc' ||
$to === 'rcandudp' ) {
804 // save RC, passing tags so they are applied there
805 $rc->addTags( $this->getTags() );
806 $rc->save( $rc::SEND_NONE
);
808 $tags = $this->getTags();
810 $revId = $this->getAssociatedRevId(); // Use null if $revId is 0
811 ChangeTags
::addTags( $tags, null, $revId > 0 ?
$revId : null, $newId );
815 if ( $to === 'udp' ||
$to === 'rcandudp' ) {
816 $rc->notifyRCFeeds();
820 DeferredUpdates
::POSTSEND
,
825 public function getType() {
829 public function getSubtype() {
830 return $this->subtype
;
833 public function getParameters() {
834 return $this->parameters
;
840 public function getPerformer() {
841 return $this->performer
;
847 public function getTarget() {
848 return $this->target
;
851 public function getTimestamp() {
852 $ts = $this->timestamp ??
wfTimestampNow();
854 return wfTimestamp( TS_MW
, $ts );
857 public function getComment() {
858 return $this->comment
;
865 public function getAssociatedRevId() {
873 public function getTags() {
878 * Whether this log entry is patrollable
883 public function getIsPatrollable() {
884 return $this->isPatrollable
;
891 public function isLegacy() {
892 return $this->legacy
;
895 public function getDeleted() {
896 return (int)$this->deleted
;