Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
27.62% covered (danger)
27.62%
58 / 210
20.51% covered (danger)
20.51%
8 / 39
CRAP
0.00% covered (danger)
0.00%
0 / 1
RecentChange
27.75% covered (danger)
27.75%
58 / 209
20.51% covered (danger)
20.51%
8 / 39
1917.94
0.00% covered (danger)
0.00%
0 / 1
 __construct
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
1.00
 newFromRow
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 parseToRCType
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 parseFromRCType
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 getChangeTypes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 newFromId
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 newFromConds
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getQueryInfo
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
6
 setAttribs
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setAttribute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setExtra
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getTitle
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 getPage
25.00% covered (danger)
25.00%
2 / 8
0.00% covered (danger)
0.00%
0 / 1
6.80
 getPerformerIdentity
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 save
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 notifyRCFeeds
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 markPatrolled
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 reallyMarkPatrolled
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 notifyEdit
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 notifyNew
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 newLogEntry
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 getParam
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 loadFromRow
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
3
 isInternal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAttribute
64.29% covered (warning)
64.29%
9 / 14
0.00% covered (danger)
0.00%
0 / 1
9.23
 getAttributes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getExtra
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getExtras
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 diffLinkTrail
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 isInRCLifespan
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 parseParams
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getTags
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addTags
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getEditResult
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setEditResult
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUserIdentityFromAnyId
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
156
 setHighlights
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getHighlights
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isHighlighted
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\RecentChanges;
8
9use InvalidArgumentException;
10use MediaWiki\ChangeTags\Taggable;
11use MediaWiki\Debug\DeprecationHelper;
12use MediaWiki\Logging\LogEntryBase;
13use MediaWiki\MainConfigNames;
14use MediaWiki\MediaWikiServices;
15use MediaWiki\Page\PageIdentity;
16use MediaWiki\Page\PageReference;
17use MediaWiki\Page\PageReferenceValue;
18use MediaWiki\Permissions\Authority;
19use MediaWiki\Permissions\PermissionStatus;
20use MediaWiki\Storage\EditResult;
21use MediaWiki\Title\Title;
22use MediaWiki\User\UserIdentity;
23use MediaWiki\User\UserIdentityValue;
24use RuntimeException;
25use Wikimedia\Timestamp\TimestampFormat as TS;
26
27/**
28 * @defgroup RecentChanges Recent changes
29 * Discovery and review of recent edits and log events on the wiki.
30 *
31 * The Recent changes feature stores a temporary copy of the long-term
32 * `revision` and `logging` table rows which represent page edits and
33 * log actions respectively.
34 *
35 * Recent changes augments revision and logging rows with additional metadata
36 * that empower reviewers to efficiently find edits related to their
37 * interest, or edits that warrant a closer look. This includes page
38 * namespace, "minor" edit status, and user type. As well as metadata we
39 * don't store elsewhere, such the bot flag (rc_bot), edit type (page creation,
40 * edit, or something else), and patrolling state (rc_patrolled).
41 *
42 * The patrolled status facilitates edit review via the "mark as patrolled"
43 * button, in combination with filtering by patrol status via SpecialRecentChanges,
44 * SpecialWatchlist, and ApiQueryRecentChanges.
45 */
46
47/**
48 * Utility class for creating and reading rows in the recentchanges table.
49 *
50 * mAttribs:
51 *  rc_id           id of the row in the recentchanges table
52 *  rc_timestamp    time the entry was made
53 *  rc_namespace    namespace #
54 *  rc_title        non-prefixed db key
55 *  rc_source       change source
56 *  rc_minor        is minor
57 *  rc_cur_id       page_id of associated page entry
58 *  rc_user         user id who made the entry
59 *  rc_user_text    user name who made the entry
60 *  rc_comment      edit summary
61 *  rc_this_oldid   rev_id associated with this entry (or zero)
62 *  rc_last_oldid   rev_id associated with the entry before this one (or zero)
63 *  rc_bot          is bot, hidden
64 *  rc_ip           IP address of the user in dotted quad notation
65 *  rc_patrolled    boolean whether or not someone has marked this edit as patrolled
66 *  rc_old_len      integer byte length of the text before the edit
67 *  rc_new_len      the same after the edit
68 *  rc_deleted      partial deletion
69 *  rc_logid        the log_id value for this log entry (or zero)
70 *  rc_log_type     the log type (or null)
71 *  rc_log_action   the log action (or null)
72 *  rc_params       log params
73 *
74 * mExtra:
75 *  prefixedDBkey   prefixed db key, used by external app via msg queue
76 *  oldSize         text size before the change
77 *  newSize         text size after the change
78 *  pageStatus      status of the page: created, deleted, moved, restored, changed
79 *
80 * temporary:       not stored in the database
81 *      notificationtimestamp
82 *      numberofWatchingusers
83 *      watchlistExpiry        for temporary watchlist items
84 *
85 * @todo Deprecate access to mAttribs (direct or via getAttributes). Right now
86 *  we're having to include both rc_comment and rc_comment_text/rc_comment_data
87 *  so random crap works right.
88 *
89 * @ingroup RecentChanges
90 */
91class RecentChange implements Taggable {
92    use DeprecationHelper;
93
94    private const CHANGE_TYPES = [
95        'edit' => RC_EDIT,
96        'new' => RC_NEW,
97        'log' => RC_LOG,
98        'external' => RC_EXTERNAL,
99        'categorize' => RC_CATEGORIZE,
100    ];
101
102    // Constants for the rc_source field.  Extensions may also have
103    // their own source constants.
104    public const SRC_EDIT = 'mw.edit';
105    public const SRC_NEW = 'mw.new';
106    public const SRC_LOG = 'mw.log';
107    public const SRC_CATEGORIZE = 'mw.categorize';
108
109    /**
110     * Values of the `rc_source` attribute that may be added by MediaWiki core.
111     * It can be useful in database queries to exclude extension-added RC entries.
112     * If you have a RecentChange object, use the isInternal() method on it instead
113     * of this constant.
114     *
115     * @var array<string>
116     */
117    public const INTERNAL_SOURCES = [
118        self::SRC_EDIT,
119        self::SRC_NEW,
120        self::SRC_LOG,
121        self::SRC_CATEGORIZE,
122    ];
123
124    public const PRC_UNPATROLLED = PatrolManager::PRC_UNPATROLLED;
125    public const PRC_PATROLLED = PatrolManager::PRC_PATROLLED;
126    public const PRC_AUTOPATROLLED = PatrolManager::PRC_AUTOPATROLLED;
127
128    public const SEND_NONE = RecentChangeStore::SEND_NONE;
129    public const SEND_FEED = RecentChangeStore::SEND_FEED;
130
131    /** Flag for RecentChange::getQueryInfo() */
132    public const STRAIGHT_JOIN_ACTOR = 1;
133
134    /** @var array */
135    public $mAttribs = [];
136    /** @var array */
137    public $mExtra = [];
138
139    /**
140     * @var PageReference|null
141     */
142    private $mPage = null;
143
144    /**
145     * @var UserIdentity|null
146     */
147    private $mPerformer = null;
148
149    /** @var int */
150    public $numberofWatchingusers = 0;
151    /** @var bool */
152    public $notificationtimestamp;
153
154    /**
155     * @var string|null The expiry time, if this is a temporary watchlist item.
156     */
157    public $watchlistExpiry;
158
159    /**
160     * @var int Line number of recent change. Default -1.
161     */
162    public $counter = -1;
163
164    /**
165     * @var array List of tags to apply
166     */
167    private $tags = [];
168
169    /**
170     * @var EditResult|null EditResult associated with the edit
171     */
172    private $editResult = null;
173
174    /**
175     * @var array<string,bool> Highlighted filters, for ChangesList. The key
176     *   is the group name and then a slash and then the filter name.
177     */
178    private $highlights = [];
179
180    public function __construct(
181        ?PageReference $page = null,
182        ?UserIdentity $performer = null
183    ) {
184        $this->deprecatePublicPropertyFallback(
185            'mTitle',
186            '1.37',
187            function () {
188                return Title::castFromPageReference( $this->mPage );
189            },
190            function ( ?Title $title ) {
191                $this->mPage = $title;
192            }
193        );
194
195        $this->mPage = $page;
196        $this->mPerformer = $performer;
197    }
198
199    # Factory methods
200
201    /**
202     * @deprecated since 1.45, use MediaWikiServices::getInstance()
203     *   ->getRecentChangeFactory()->newRecentChangeFromRow() instead.
204     *
205     * @param mixed $row
206     * @return RecentChange
207     */
208    public static function newFromRow( $row ) {
209        return MediaWikiServices::getInstance()
210            ->getRecentChangeFactory()
211            ->newRecentChangeFromRow( $row );
212    }
213
214    /**
215     * Parsing text to RC_* constants
216     *
217     * @deprecated since 1.46
218     * @since 1.24
219     * @param string|array $type Callers must make sure that the given types are valid RC types.
220     * @return int|array RC_TYPE
221     */
222    public static function parseToRCType( $type ) {
223        wfDeprecated( __METHOD__, '1.46' );
224
225        if ( is_array( $type ) ) {
226            $retval = [];
227            foreach ( $type as $t ) {
228                $retval[] = self::parseToRCType( $t );
229            }
230
231            return $retval;
232        }
233
234        if ( !array_key_exists( $type, self::CHANGE_TYPES ) ) {
235            throw new InvalidArgumentException( "Unknown type '$type'" );
236        }
237        return self::CHANGE_TYPES[$type];
238    }
239
240    /**
241     * Parsing RC_* constants to human-readable test
242     *
243     * @deprecated since 1.46
244     * @since 1.24
245     * @param int $rcType
246     * @return string
247     */
248    public static function parseFromRCType( $rcType ) {
249        wfDeprecated( __METHOD__, '1.46' );
250
251        return array_search( $rcType, self::CHANGE_TYPES, true ) ?: "$rcType";
252    }
253
254    /**
255     * Get an array of all change types
256     *
257     * @since 1.26
258     *
259     * @return array
260     */
261    public static function getChangeTypes() {
262        return array_keys( self::CHANGE_TYPES );
263    }
264
265    /**
266     * Obtain the recent change with a given rc_id value
267     *
268     * @deprecated since 1.45, use MediaWikiServices::getInstance()
269     *   ->getRecentChangeLookup()->getRecentChangeById() instead.
270     *
271     * @param int $rcid The rc_id value to retrieve
272     * @return RecentChange|null
273     */
274    public static function newFromId( $rcid ) {
275        return MediaWikiServices::getInstance()
276            ->getRecentChangeLookup()
277            ->getRecentChangeById( $rcid );
278    }
279
280    /**
281     * Find the first recent change matching some specific conditions
282     *
283     * @deprecated since 1.45, use MediaWikiServices::getInstance()
284     *   ->getRecentChangeLookup()->getRecentChangeByConds() instead.
285     *
286     * @param array $conds Array of conditions
287     * @param mixed $fname Override the method name in profiling/logs @phan-mandatory-param
288     * @param int $dbType DB_* constant
289     *
290     * @return RecentChange|null
291     */
292    public static function newFromConds(
293        $conds,
294        $fname = __METHOD__,
295        $dbType = DB_REPLICA
296    ) {
297        return MediaWikiServices::getInstance()
298            ->getRecentChangeLookup()
299            ->getRecentChangeByConds( $conds, $fname, $dbType === DB_PRIMARY );
300    }
301
302    /**
303     * Return the tables, fields, and join conditions to be selected to create
304     * a new recentchanges object.
305     *
306     * Since 1.34, rc_user and rc_user_text have not been present in the
307     * database, but they continue to be available in query results as
308     * aliases.
309     *
310     * @since 1.31
311     * @param int $joinFlags May be STRAIGHT_JOIN_ACTOR to use a straight join
312     *   on the actor table, preventing the database from placing the actor
313     *   table first in the join. This is appropriate when there are no
314     *   restrictive conditions on the actor table, and the conditions are
315     *   potentially complex and unindexed, and the query is limited and
316     *   ordered by timestamp. Since 1.45.
317     *
318     * @return array[] With three keys:
319     *   - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
320     *   - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
321     *   - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
322     * @phan-return array{tables:string[],fields:string[],joins:array}
323     */
324    public static function getQueryInfo( int $joinFlags = 0 ) {
325        return [
326            'tables' => [
327                'recentchanges',
328                'recentchanges_actor' => 'actor',
329                'recentchanges_comment' => 'comment',
330            ],
331            'fields' => [
332                'rc_id',
333                'rc_timestamp',
334                'rc_namespace',
335                'rc_title',
336                'rc_minor',
337                'rc_bot',
338                'rc_cur_id',
339                'rc_this_oldid',
340                'rc_last_oldid',
341                'rc_source',
342                'rc_patrolled',
343                'rc_ip',
344                'rc_old_len',
345                'rc_new_len',
346                'rc_deleted',
347                'rc_logid',
348                'rc_log_type',
349                'rc_log_action',
350                'rc_params',
351                'rc_actor',
352                'rc_user' => 'recentchanges_actor.actor_user',
353                'rc_user_text' => 'recentchanges_actor.actor_name',
354                'rc_comment_text' => 'recentchanges_comment.comment_text',
355                'rc_comment_data' => 'recentchanges_comment.comment_data',
356                'rc_comment_id' => 'recentchanges_comment.comment_id',
357            ],
358            'joins' => [
359                // Optimizer sometimes refuses to pick up the correct join order (T311360)
360                'recentchanges_actor' => [
361                    ( $joinFlags & self::STRAIGHT_JOIN_ACTOR ) ? 'STRAIGHT_JOIN' : 'JOIN',
362                    'actor_id=rc_actor'
363                ],
364                'recentchanges_comment' => [ 'STRAIGHT_JOIN', 'comment_id=rc_comment_id' ],
365            ],
366        ];
367    }
368
369    # Accessors
370
371    /**
372     * @param array $attribs
373     */
374    public function setAttribs( $attribs ) {
375        $this->mAttribs = $attribs;
376    }
377
378    /**
379     * @since 1.45
380     * @param string $name
381     * @param mixed $value
382     */
383    public function setAttribute( $name, $value ) {
384        $this->mAttribs[$name] = $value;
385    }
386
387    /**
388     * @param array $extra
389     */
390    public function setExtra( $extra ) {
391        $this->mExtra = $extra;
392    }
393
394    /**
395     * @deprecated since 1.37, use getPage() instead.
396     * @return Title
397     */
398    public function getTitle() {
399        $this->mPage = Title::castFromPageReference( $this->getPage() );
400        return $this->mPage ?: Title::makeTitle( NS_SPECIAL, 'BadTitle' );
401    }
402
403    /**
404     * @since 1.37
405     * @return ?PageReference
406     */
407    public function getPage(): ?PageReference {
408        if ( !$this->mPage ) {
409            // NOTE: As per the 1.36 release, we always provide rc_title,
410            //       even in cases where it doesn't really make sense.
411            //       In the future, rc_title may be nullable, or we may use
412            //       empty strings in entries that do not refer to a page.
413            if ( ( $this->mAttribs['rc_title'] ?? '' ) === '' ) {
414                return null;
415            }
416
417            // XXX: We could use rc_cur_id to create a PageIdentityValue,
418            //      at least if it's not a special page.
419            //      However, RecentChangeFactory::createCategorizationRecentChange() puts the ID of the
420            //      categorized page into rc_cur_id, but the title of the category page into rc_title.
421            $this->mPage = PageReferenceValue::localReference(
422                (int)$this->mAttribs['rc_namespace'],
423                $this->mAttribs['rc_title']
424            );
425        }
426
427        return $this->mPage;
428    }
429
430    /**
431     * Get the UserIdentity of the client that performed this change.
432     *
433     * @since 1.36
434     *
435     * @return UserIdentity
436     */
437    public function getPerformerIdentity(): UserIdentity {
438        if ( !$this->mPerformer ) {
439            $this->mPerformer = $this->getUserIdentityFromAnyId(
440                $this->mAttribs['rc_user'] ?? null,
441                $this->mAttribs['rc_user_text'] ?? null,
442                $this->mAttribs['rc_actor'] ?? null
443            );
444        }
445
446        return $this->mPerformer;
447    }
448
449    /**
450     * Writes the data in this object to the database
451     *
452     * @deprecated since 1.45, use RecentChangeFactory::insertRecentChange() instead.
453     *
454     * @param bool $send self::SEND_FEED or self::SEND_NONE
455     */
456    public function save( $send = self::SEND_FEED ) {
457        MediaWikiServices::getInstance()->getRecentChangeFactory()->insertRecentChange( $this, $send );
458    }
459
460    /**
461     * Notify all the feeds about the change.
462     *
463     * @deprecated since 1.45, use RecentChangeRCFeedNotifier::notifyRCFeeds() instead.
464     *
465     * @param array|null $feeds Optional feeds to send to, defaults to $wgRCFeeds
466     */
467    public function notifyRCFeeds( ?array $feeds = null ) {
468        MediaWikiServices::getInstance()->getRecentChangeRCFeedNotifier()->notifyRCFeeds( $this, $feeds );
469    }
470
471    /**
472     * Mark this RecentChange as patrolled
473     *
474     * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
475     * 'markedaspatrollederror-noautopatrol' as errors
476     *
477     * @deprecated since 1.45, use PatrolManager::markPatrolled() instead.
478     *
479     * @param Authority $performer User performing the action
480     * @param string|string[]|null $tags Change tags to add to the patrol log entry
481     *   ($user should be able to add the specified tags before this is called)
482     * @return PermissionStatus
483     */
484    public function markPatrolled( Authority $performer, $tags = null ): PermissionStatus {
485        return MediaWikiServices::getInstance()
486            ->getPatrolManager()
487            ->markPatrolled( $this, $performer, $tags );
488    }
489
490    /**
491     * Mark this RecentChange patrolled, without error checking
492     *
493     * @deprecated since 1.45, use PatrolManager::reallyMarkPatrolled() instead.
494     *
495     * @return int Number of database rows changed, usually 1, but 0 if
496     * another request already patrolled it in the mean time.
497     */
498    public function reallyMarkPatrolled() {
499        return MediaWikiServices::getInstance()
500            ->getPatrolManager()
501            ->reallyMarkPatrolled( $this );
502    }
503
504    /**
505     * Makes an entry in the database corresponding to an edit
506     *
507     * @since 1.36 Added $editResult parameter
508     * @deprecated since 1.45, use RecentChangeFactory::createEditRecentChange() instead to create
509     * the log entry, then use RecentChangeFactory::insertRecentChange() to insert it into the database.
510     * Hard-deprecated in 1.46.
511     *
512     * @param string $timestamp
513     * @param PageIdentity $page
514     * @param bool $minor
515     * @param UserIdentity $user
516     * @param string $comment
517     * @param int $oldId
518     * @param string $lastTimestamp
519     * @param bool $bot
520     * @param string $ip
521     * @param int $oldSize
522     * @param int $newSize
523     * @param int $newId
524     * @param int $patrol
525     * @param string[] $tags
526     * @param EditResult|null $editResult EditResult associated with this edit. Can be safely
527     *  skipped if the edit is not a revert. Used only for marking revert tags.
528     *
529     * @return RecentChange
530     */
531    public static function notifyEdit(
532        $timestamp, $page, $minor, $user, $comment, $oldId, $lastTimestamp,
533        $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0,
534        $tags = [], ?EditResult $editResult = null
535    ) {
536        wfDeprecated( __METHOD__, '1.45' );
537        $rc = MediaWikiServices::getInstance()->getRecentChangeFactory()
538            ->createEditRecentChange(
539                $timestamp, $page, $minor, $user, $comment, $oldId,
540                $bot, $ip, $oldSize, $newSize, $newId, $patrol, $tags, $editResult
541            );
542        $rc->save();
543        return $rc;
544    }
545
546    /**
547     * Makes an entry in the database corresponding to page creation
548     * @note $page must reflect the state of the database after the page creation. In particular,
549     *       $page->getId() must return the newly assigned page ID.
550     *
551     * @deprecated since 1.45, use RecentChangeFactory::createNewPageRecentChange() instead to create
552     * the log entry, then use RecentChangeFactory::insertRecentChange() to insert it into the database.
553     * Hard-deprecated in 1.46.
554     *
555     * @param string $timestamp
556     * @param PageIdentity $page
557     * @param bool $minor
558     * @param UserIdentity $user
559     * @param string $comment
560     * @param bool $bot
561     * @param string $ip
562     * @param int $size
563     * @param int $newId
564     * @param int $patrol
565     * @param string[] $tags
566     *
567     * @return RecentChange
568     */
569    public static function notifyNew(
570        $timestamp,
571        $page, $minor, $user, $comment, $bot,
572        $ip = '', $size = 0, $newId = 0, $patrol = 0, $tags = []
573    ) {
574        wfDeprecated( __METHOD__, '1.45' );
575        $rc = MediaWikiServices::getInstance()->getRecentChangeFactory()
576            ->createNewPageRecentChange(
577                $timestamp, $page, $minor, $user, $comment, $bot,
578                $ip, $size, $newId, $patrol, $tags
579            );
580        $rc->save();
581        return $rc;
582    }
583
584    /**
585     * @deprecated since 1.45, use RecentChangeFactory::createLogRecentChange() instead.
586     * Hard-deprecated in 1.46.
587     *
588     * @param string $timestamp
589     * @param PageReference $logPage
590     * @param UserIdentity $user
591     * @param string $actionComment
592     * @param string $ip
593     * @param string $type
594     * @param string $action
595     * @param PageReference $target
596     * @param string $logComment
597     * @param string $params
598     * @param int $newId
599     * @param string $actionCommentIRC
600     * @param int $revId Id of associated revision, if any
601     * @param bool $isPatrollable Whether this log entry is patrollable
602     * @param bool|null $forceBotFlag Override the default behavior and set bot flag to
603     *     the value of the argument. When omitted or null, it falls back to the global state.
604     *
605     * @return RecentChange
606     */
607    public static function newLogEntry( $timestamp,
608        $logPage, $user, $actionComment, $ip,
609        $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '',
610        $revId = 0, $isPatrollable = false, $forceBotFlag = null
611    ) {
612        wfDeprecated( __METHOD__, '1.45' );
613        return MediaWikiServices::getInstance()->getRecentChangeFactory()
614            ->createLogRecentChange(
615                $timestamp, $logPage, $user, $actionComment, $ip,
616                $type, $action, $target, $logComment, $params, $newId, $actionCommentIRC,
617                $revId, $isPatrollable, $forceBotFlag
618            );
619    }
620
621    /**
622     * Get a parameter value
623     *
624     * @since 1.27
625     *
626     * @param string $name parameter name
627     * @return mixed
628     */
629    public function getParam( $name ) {
630        $params = $this->parseParams();
631        return $params[$name] ?? null;
632    }
633
634    /**
635     * Initialises the members of this object from a mysql row object
636     *
637     * @param mixed $row
638     */
639    public function loadFromRow( $row ) {
640        $this->mAttribs = get_object_vars( $row );
641        $this->mAttribs['rc_timestamp'] = wfTimestamp( TS::MW, $this->mAttribs['rc_timestamp'] );
642        // rc_deleted MUST be set
643        $this->mAttribs['rc_deleted'] = $row->rc_deleted;
644
645        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
646        $comment = MediaWikiServices::getInstance()->getCommentStore()
647            // Legacy because $row may have come from self::selectFields()
648            ->getCommentLegacy( $dbr, 'rc_comment', $row, true )
649            ->text;
650        $this->mAttribs['rc_comment'] = &$comment;
651        $this->mAttribs['rc_comment_text'] = &$comment;
652        $this->mAttribs['rc_comment_data'] = null;
653
654        $this->mPerformer = $this->getUserIdentityFromAnyId(
655            $row->rc_user ?? null,
656            $row->rc_user_text ?? null,
657            $row->rc_actor ?? null
658        );
659        $this->mAttribs['rc_user'] = $this->mPerformer->getId();
660        $this->mAttribs['rc_user_text'] = $this->mPerformer->getName();
661
662        // Watchlist expiry.
663        if ( isset( $row->we_expiry ) && $row->we_expiry ) {
664            $this->watchlistExpiry = wfTimestamp( TS::MW, $row->we_expiry );
665        }
666    }
667
668    /**
669     * Check if the change is internal (edit, new, log, categorize). External changes are
670     * those that are defined by external sources, such as extensions.
671     *
672     * @since 1.45
673     * @return bool
674     */
675    public function isInternal() {
676        return in_array( $this->getAttribute( 'rc_source' ), self::INTERNAL_SOURCES );
677    }
678
679    /**
680     * Get an attribute value
681     *
682     * @param string $name Attribute name
683     * @return mixed
684     */
685    public function getAttribute( $name ) {
686        if ( $name === 'rc_comment' ) {
687            return MediaWikiServices::getInstance()->getCommentStore()
688                ->getComment( 'rc_comment', $this->mAttribs, true )->text;
689        }
690
691        if ( $name === 'rc_user' || $name === 'rc_user_text' || $name === 'rc_actor' ) {
692            $user = $this->getPerformerIdentity();
693
694            if ( $name === 'rc_user' ) {
695                return $user->getId();
696            }
697            if ( $name === 'rc_user_text' ) {
698                return $user->getName();
699            }
700            // We now know that $name === 'rc_actor'
701            // NOTE: rc_actor exists in the database, but application logic should not use it.
702            wfDeprecatedMsg( 'Accessing deprecated field rc_actor', '1.36' );
703            $actorStore = MediaWikiServices::getInstance()->getActorStore();
704            $db = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
705            return $actorStore->findActorId( $user, $db );
706        }
707
708        return $this->mAttribs[$name] ?? null;
709    }
710
711    /**
712     * @return array
713     */
714    public function getAttributes() {
715        return $this->mAttribs;
716    }
717
718    /**
719     * @internal
720     *
721     * @param string $name
722     * @return mixed
723     */
724    public function getExtra( $name ) {
725        return $this->mExtra[$name] ?? null;
726    }
727
728    /**
729     * @internal
730     *
731     * @return array
732     */
733    public function getExtras() {
734        return $this->mExtra;
735    }
736
737    /**
738     * Gets the end part of the diff URL associated with this object
739     * Blank if no diff link should be displayed
740     * @param bool $forceCur
741     * @return string
742     */
743    public function diffLinkTrail( $forceCur ) {
744        if ( $this->mAttribs['rc_source'] == self::SRC_EDIT ) {
745            $trail = "curid=" . (int)( $this->mAttribs['rc_cur_id'] ) .
746                "&oldid=" . (int)( $this->mAttribs['rc_last_oldid'] );
747            if ( $forceCur ) {
748                $trail .= '&diff=0';
749            } else {
750                $trail .= '&diff=' . (int)( $this->mAttribs['rc_this_oldid'] );
751            }
752        } else {
753            $trail = '';
754        }
755
756        return $trail;
757    }
758
759    /**
760     * Check whether the given timestamp is new enough to have a RC row with a given tolerance
761     * as the recentchanges table might not be cleared out regularly (so older entries might exist)
762     * or rows which will be deleted soon shouldn't be included.
763     *
764     * @param mixed $timestamp MWTimestamp compatible timestamp
765     * @param int $tolerance Tolerance in seconds
766     * @return bool
767     */
768    public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
769        $rcMaxAge =
770            MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::RCMaxAge );
771
772        return (int)wfTimestamp( TS::UNIX, $timestamp ) > time() - $tolerance - $rcMaxAge;
773    }
774
775    /**
776     * Parses and returns the rc_params attribute
777     *
778     * @since 1.26
779     * @return mixed|bool false on failed unserialization
780     */
781    public function parseParams() {
782        return LogEntryBase::extractParams( $this->getAttribute( 'rc_params' ),
783            $this->getAttribute( 'rc_log_type' ) . '/' . $this->getAttribute( 'rc_log_action' ) );
784    }
785
786    /**
787     * @internal
788     *
789     * @return string[]
790     */
791    public function getTags(): array {
792        return $this->tags;
793    }
794
795    /**
796     * Tags to append to the recent change,
797     * and associated revision/log
798     *
799     * @since 1.28
800     *
801     * @param string|string[] $tags
802     */
803    public function addTags( $tags ) {
804        if ( is_string( $tags ) ) {
805            $this->tags[] = $tags;
806        } else {
807            $this->tags = array_merge( $tags, $this->tags );
808        }
809    }
810
811    /**
812     * @internal
813     *
814     * @return EditResult|null
815     */
816    public function getEditResult(): ?EditResult {
817        return $this->editResult;
818    }
819
820    /**
821     * Sets the EditResult associated with the edit.
822     *
823     * @since 1.36
824     *
825     * @param EditResult|null $editResult
826     */
827    public function setEditResult( ?EditResult $editResult ) {
828        $this->editResult = $editResult;
829    }
830
831    /**
832     * @param string|int|null $userId
833     * @param string|null $userName
834     * @param string|int|null $actorId
835     *
836     * @return UserIdentity
837     */
838    private function getUserIdentityFromAnyId(
839        $userId,
840        $userName,
841        $actorId = null
842    ): UserIdentity {
843        // XXX: Is this logic needed elsewhere? Should it be reusable?
844
845        $userId = $userId !== null ? (int)$userId : null;
846        $actorId = $actorId !== null ? (int)$actorId : 0;
847
848        $actorStore = MediaWikiServices::getInstance()->getActorStore();
849        if ( $userName && $actorId ) {
850            // Likely the fields are coming from a join on actor table,
851            // so can definitely build a UserIdentityValue.
852            return $actorStore->newActorFromRowFields( $userId, $userName, $actorId );
853        }
854        if ( $userId !== null ) {
855            if ( $userName !== null ) {
856                // NOTE: For IPs and external users, $userId will be 0.
857                $user = new UserIdentityValue( $userId, $userName );
858            } else {
859                $user = $actorStore->getUserIdentityByUserId( $userId );
860
861                if ( !$user ) {
862                    throw new RuntimeException( "User not found by ID: $userId" );
863                }
864            }
865        } elseif ( $actorId > 0 ) {
866            $db = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
867            $user = $actorStore->getActorById( $actorId, $db );
868
869            if ( !$user ) {
870                throw new RuntimeException( "User not found by actor ID: $actorId" );
871            }
872        } elseif ( $userName !== null ) {
873            $user = $actorStore->getUserIdentityByName( $userName );
874
875            if ( !$user ) {
876                throw new RuntimeException( "User not found by name: $userName" );
877            }
878        } else {
879            throw new RuntimeException( 'At least one of user ID, actor ID or user name must be given' );
880        }
881
882        return $user;
883    }
884
885    /**
886     * @param array<string,bool> $highlights
887     */
888    public function setHighlights( array $highlights ) {
889        $this->highlights = $highlights;
890    }
891
892    /**
893     * @return array<string,bool>
894     */
895    public function getHighlights() {
896        return $this->highlights;
897    }
898
899    public function isHighlighted( string $key ): bool {
900        return $this->highlights[$key] ?? false;
901    }
902}
903
904/** @deprecated class alias since 1.44 */
905class_alias( RecentChange::class, 'RecentChange' );