Debian Codegraph @

includes/recentchanges/RecentChange.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\ChangeTags\Taggable;
22 use MediaWiki\Config\Config;
23 use MediaWiki\Debug\DeprecationHelper;
24 use MediaWiki\Deferred\DeferredUpdates;
25 use MediaWiki\HookContainer\HookRunner;
26 use MediaWiki\Json\FormatJson;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Page\PageIdentity;
30 use MediaWiki\Page\PageReference;
31 use MediaWiki\Page\PageReferenceValue;
32 use MediaWiki\Permissions\Authority;
33 use MediaWiki\Permissions\PermissionStatus;
34 use MediaWiki\RCFeed\RCFeed;
35 use MediaWiki\Storage\EditResult;
36 use MediaWiki\Title\Title;
37 use MediaWiki\User\UserIdentity;
38 use MediaWiki\User\UserIdentityValue;
39 use MediaWiki\Utils\MWTimestamp;
40 use Wikimedia\Assert\Assert;
41 use Wikimedia\IPUtils;
42
43 /**
44 * @defgroup RecentChanges Recent changes
45 * Discovery and review of recent edits and log events on the wiki.
46 *
47 * The Recent changes feature stores a temporary copy of the long-term
48 * `revision` and `logging` table rows which represent page edits and
49 * log actions respectively.
50 *
51 * Recent changes augments revision and logging rows with additional metadata
52 * that empower reviewers to efficiently find edits related to their
53 * interest, or edits that warrant a closer look. This includes page
54 * namespace, "minor" edit status, and user type. As well as metadata we
55 * don't store elsewhere, such the bot flag (rc_bot), edit type (page creation,
56 * edit, or something else), and patrolling state (rc_patrolled).
57 *
58 * The patrolled status facilitates edit review via the "mark as patrolled"
59 * button, in combination with filtering by patrol status via SpecialRecentChanges,
60 * SpecialWatchlist, and ApiQueryRecentChanges.
61 */
62
63 /**
64 * Utility class for creating and reading rows in the recentchanges table.
65 *
66 * mAttribs:
67 * rc_id id of the row in the recentchanges table
68 * rc_timestamp time the entry was made
69 * rc_namespace namespace #
70 * rc_title non-prefixed db key
71 * rc_type is new entry, used to determine whether updating is necessary
72 * rc_source string representation of change source
73 * rc_minor is minor
74 * rc_cur_id page_id of associated page entry
75 * rc_user user id who made the entry
76 * rc_user_text user name who made the entry
77 * rc_comment edit summary
78 * rc_this_oldid rev_id associated with this entry (or zero)
79 * rc_last_oldid rev_id associated with the entry before this one (or zero)
80 * rc_bot is bot, hidden
81 * rc_ip IP address of the user in dotted quad notation
82 * rc_new obsolete, use rc_source=='mw.new'
83 * rc_patrolled boolean whether or not someone has marked this edit as patrolled
84 * rc_old_len integer byte length of the text before the edit
85 * rc_new_len the same after the edit
86 * rc_deleted partial deletion
87 * rc_logid the log_id value for this log entry (or zero)
88 * rc_log_type the log type (or null)
89 * rc_log_action the log action (or null)
90 * rc_params log params
91 *
92 * mExtra:
93 * prefixedDBkey prefixed db key, used by external app via msg queue
94 * lastTimestamp timestamp of previous entry, used in WHERE clause during update
95 * oldSize text size before the change
96 * newSize text size after the change
97 * pageStatus status of the page: created, deleted, moved, restored, changed
98 *
99 * temporary: not stored in the database
100 * notificationtimestamp
101 * numberofWatchingusers
102 * watchlistExpiry for temporary watchlist items
103 *
104 * @todo Deprecate access to mAttribs (direct or via getAttributes). Right now
105 * we're having to include both rc_comment and rc_comment_text/rc_comment_data
106 * so random crap works right.
107 *
108 * @ingroup RecentChanges
109 */
110 class RecentChange implements Taggable {
111 use DeprecationHelper;
112
113 // Constants for the rc_source field. Extensions may also have
114 // their own source constants.
115 public const SRC_EDIT = 'mw.edit';
116 public const SRC_NEW = 'mw.new';
117 public const SRC_LOG = 'mw.log';
118 public const SRC_EXTERNAL = 'mw.external'; // obsolete
119 public const SRC_CATEGORIZE = 'mw.categorize';
120
121 public const PRC_UNPATROLLED = 0;
122 public const PRC_PATROLLED = 1;
123 public const PRC_AUTOPATROLLED = 2;
124
125 /**
126 * @var bool For save() - save to the database only, without any events.
127 */
128 public const SEND_NONE = true;
129
130 /**
131 * @var bool For save() - do emit the change to RCFeeds (usually public).
132 */
133 public const SEND_FEED = false;
134
135 /** @var array */
136 public $mAttribs = [];
137 /** @var array */
138 public $mExtra = [];
139
140 /**
141 * @var PageReference|null
142 */
143 private $mPage = null;
144
145 /**
146 * @var UserIdentity|null
147 */
148 private $mPerformer = null;
149
150 /** @var int */
151 public $numberofWatchingusers = 0;
152 /** @var bool */
153 public $notificationtimestamp;
154
155 /**
156 * @var string|null The expiry time, if this is a temporary watchlist item.
157 */
158 public $watchlistExpiry;
159
160 /**
161 * @var int Line number of recent change. Default -1.
162 */
163 public $counter = -1;
164
165 /**
166 * @var array List of tags to apply
167 */
168 private $tags = [];
169
170 /**
171 * @var EditResult|null EditResult associated with the edit
172 */
173 private $editResult = null;
174
175 private const CHANGE_TYPES = [
176 'edit' => RC_EDIT,
177 'new' => RC_NEW,
178 'log' => RC_LOG,
179 'external' => RC_EXTERNAL,
180 'categorize' => RC_CATEGORIZE,
181 ];
182
183 # Factory methods
184
185 /**
186 * @param mixed $row
187 * @return RecentChange
188 */
189 public static function newFromRow( $row ) {
190 $rc = new RecentChange;
191 $rc->loadFromRow( $row );
192
193 return $rc;
194 }
195
196 /**
197 * Parsing text to RC_* constants
198 * @since 1.24
199 * @param string|array $type Callers must make sure that the given types are valid RC types.
200 * @return int|array RC_TYPE
201 */
202 public static function parseToRCType( $type ) {
203 if ( is_array( $type ) ) {
204 $retval = [];
205 foreach ( $type as $t ) {
206 $retval[] = self::parseToRCType( $t );
207 }
208
209 return $retval;
210 }
211
212 if ( !array_key_exists( $type, self::CHANGE_TYPES ) ) {
213 throw new InvalidArgumentException( "Unknown type '$type'" );
214 }
215 return self::CHANGE_TYPES[$type];
216 }
217
218 /**
219 * Parsing RC_* constants to human-readable test
220 * @since 1.24
221 * @param int $rcType
222 * @return string
223 */
224 public static function parseFromRCType( $rcType ) {
225 return array_search( $rcType, self::CHANGE_TYPES, true ) ?: "$rcType";
226 }
227
228 /**
229 * Get an array of all change types
230 *
231 * @since 1.26
232 *
233 * @return array
234 */
235 public static function getChangeTypes() {
236 return array_keys( self::CHANGE_TYPES );
237 }
238
239 /**
240 * Obtain the recent change with a given rc_id value
241 *
242 * @param int $rcid The rc_id value to retrieve
243 * @return RecentChange|null
244 */
245 public static function newFromId( $rcid ) {
246 return self::newFromConds( [ 'rc_id' => $rcid ], __METHOD__ );
247 }
248
249 /**
250 * Find the first recent change matching some specific conditions
251 *
252 * @param array $conds Array of conditions
253 * @param mixed $fname Override the method name in profiling/logs @phan-mandatory-param
254 * @param int $dbType DB_* constant
255 *
256 * @return RecentChange|null
257 */
258 public static function newFromConds(
259 $conds,
260 $fname = __METHOD__,
261 $dbType = DB_REPLICA
262 ) {
263 $icp = MediaWikiServices::getInstance()->getConnectionProvider();
264
265 $db = ( $dbType === DB_REPLICA ) ? $icp->getReplicaDatabase() : $icp->getPrimaryDatabase();
266
267 $rcQuery = self::getQueryInfo();
268 $row = $db->newSelectQueryBuilder()
269 ->queryInfo( $rcQuery )
270 ->where( $conds )
271 ->caller( $fname )
272 ->fetchRow();
273 if ( $row !== false ) {
274 return self::newFromRow( $row );
275 } else {
276 return null;
277 }
278 }
279
280 /**
281 * Return the tables, fields, and join conditions to be selected to create
282 * a new recentchanges object.
283 *
284 * Since 1.34, rc_user and rc_user_text have not been present in the
285 * database, but they continue to be available in query results as
286 * aliases.
287 *
288 * @since 1.31
289 * @return array[] With three keys:
290 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
291 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
292 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
293 * @phan-return array{tables:string[],fields:string[],joins:array}
294 */
295 public static function getQueryInfo() {
296 $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'rc_comment' );
297 // Optimizer sometimes refuses to pick up the correct join order (T311360)
298 $commentQuery['joins']['comment_rc_comment'][0] = 'STRAIGHT_JOIN';
299 return [
300 'tables' => [
301 'recentchanges',
302 'recentchanges_actor' => 'actor'
303 ] + $commentQuery['tables'],
304 'fields' => [
305 'rc_id',
306 'rc_timestamp',
307 'rc_namespace',
308 'rc_title',
309 'rc_minor',
310 'rc_bot',
311 'rc_new',
312 'rc_cur_id',
313 'rc_this_oldid',
314 'rc_last_oldid',
315 'rc_type',
316 'rc_source',
317 'rc_patrolled',
318 'rc_ip',
319 'rc_old_len',
320 'rc_new_len',
321 'rc_deleted',
322 'rc_logid',
323 'rc_log_type',
324 'rc_log_action',
325 'rc_params',
326 'rc_actor',
327 'rc_user' => 'recentchanges_actor.actor_user',
328 'rc_user_text' => 'recentchanges_actor.actor_name',
329 ] + $commentQuery['fields'],
330 'joins' => [
331 'recentchanges_actor' => [ 'STRAIGHT_JOIN', 'actor_id=rc_actor' ]
332 ] + $commentQuery['joins'],
333 ];
334 }
335
336 public function __construct() {
337 $this->deprecatePublicPropertyFallback(
338 'mTitle',
339 '1.37',
340 function () {
341 return Title::castFromPageReference( $this->mPage );
342 },
343 function ( ?Title $title ) {
344 $this->mPage = $title;
345 }
346 );
347 }
348
349 # Accessors
350
351 /**
352 * @param array $attribs
353 */
354 public function setAttribs( $attribs ) {
355 $this->mAttribs = $attribs;
356 }
357
358 /**
359 * @param array $extra
360 */
361 public function setExtra( $extra ) {
362 $this->mExtra = $extra;
363 }
364
365 /**
366 * @deprecated since 1.37, use getPage() instead.
367 * @return Title
368 */
369 public function getTitle() {
370 $this->mPage = Title::castFromPageReference( $this->getPage() );
371 return $this->mPage ?: Title::makeTitle( NS_SPECIAL, 'BadTitle' );
372 }
373
374 /**
375 * @since 1.37
376 * @return ?PageReference
377 */
378 public function getPage(): ?PageReference {
379 if ( !$this->mPage ) {
380 // NOTE: As per the 1.36 release, we always provide rc_title,
381 // even in cases where it doesn't really make sense.
382 // In the future, rc_title may be nullable, or we may use
383 // empty strings in entries that do not refer to a page.
384 if ( ( $this->mAttribs['rc_title'] ?? '' ) === '' ) {
385 return null;
386 }
387
388 // XXX: We could use rc_cur_id to create a PageIdentityValue,
389 // at least if it's not a special page.
390 // However, newForCategorization() puts the ID of the categorized page into
391 // rc_cur_id, but the title of the category page into rc_title.
392 $this->mPage = new PageReferenceValue(
393 (int)$this->mAttribs['rc_namespace'],
394 $this->mAttribs['rc_title'],
395 PageReference::LOCAL
396 );
397 }
398
399 return $this->mPage;
400 }
401
402 /**
403 * Get the UserIdentity of the client that performed this change.
404 *
405 * @since 1.36
406 *
407 * @return UserIdentity
408 */
409 public function getPerformerIdentity(): UserIdentity {
410 if ( !$this->mPerformer ) {
411 $this->mPerformer = $this->getUserIdentityFromAnyId(
412 $this->mAttribs['rc_user'] ?? null,
413 $this->mAttribs['rc_user_text'] ?? null,
414 $this->mAttribs['rc_actor'] ?? null
415 );
416 }
417
418 return $this->mPerformer;
419 }
420
421 /**
422 * Writes the data in this object to the database
423 *
424 * For compatibility reasons, the SEND_ constants internally reference a value
425 * that may seem negated from their purpose (none=true, feed=false). This is
426 * because the parameter used to be called "$noudp", defaulting to false.
427 *
428 * @param bool $send self::SEND_FEED or self::SEND_NONE
429 */
430 public function save( $send = self::SEND_FEED ) {
431 $services = MediaWikiServices::getInstance();
432 $mainConfig = $services->getMainConfig();
433 $putIPinRC = $mainConfig->get( MainConfigNames::PutIPinRC );
434 $dbw = $services->getConnectionProvider()->getPrimaryDatabase();
435 if ( !is_array( $this->mExtra ) ) {
436 $this->mExtra = [];
437 }
438
439 if ( !$putIPinRC ) {
440 $this->mAttribs['rc_ip'] = '';
441 }
442
443 # Strict mode fixups (not-NULL fields)
444 foreach ( [ 'minor', 'bot', 'new', 'patrolled', 'deleted' ] as $field ) {
445 $this->mAttribs["rc_$field"] = (int)$this->mAttribs["rc_$field"];
446 }
447 # ...more fixups (NULL fields)
448 foreach ( [ 'old_len', 'new_len' ] as $field ) {
449 $this->mAttribs["rc_$field"] = isset( $this->mAttribs["rc_$field"] )
450 ? (int)$this->mAttribs["rc_$field"]
451 : null;
452 }
453
454 $row = $this->mAttribs;
455
456 # Trim spaces on user supplied text
457 $row['rc_comment'] = trim( $row['rc_comment'] ?? '' );
458
459 # Fixup database timestamps
460 $row['rc_timestamp'] = $dbw->timestamp( $row['rc_timestamp'] );
461
462 # # If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
463 if ( $row['rc_cur_id'] == 0 ) {
464 unset( $row['rc_cur_id'] );
465 }
466
467 # Convert mAttribs['rc_comment'] for CommentStore
468 $comment = $row['rc_comment'];
469 unset( $row['rc_comment'], $row['rc_comment_text'], $row['rc_comment_data'] );
470 $row += $services->getCommentStore()->insert( $dbw, 'rc_comment', $comment );
471
472 # Normalize UserIdentity to actor ID
473 $user = $this->getPerformerIdentity();
474 if ( array_key_exists( 'forImport', $this->mExtra ) && $this->mExtra['forImport'] ) {
475 $actorStore = $services->getActorStoreFactory()->getActorStoreForImport();
476 } else {
477 $actorStore = $services->getActorStoreFactory()->getActorStore();
478 }
479 $row['rc_actor'] = $actorStore->acquireActorId( $user, $dbw );
480 unset( $row['rc_user'], $row['rc_user_text'] );
481
482 # Don't reuse an existing rc_id for the new row, if one happens to be
483 # set for some reason.
484 unset( $row['rc_id'] );
485
486 # Insert new row
487 $dbw->newInsertQueryBuilder()
488 ->insertInto( 'recentchanges' )
489 ->row( $row )
490 ->caller( __METHOD__ )->execute();
491
492 # Set the ID
493 $this->mAttribs['rc_id'] = $dbw->insertId();
494
495 # Notify extensions
496 $hookRunner = new HookRunner( $services->getHookContainer() );
497 $hookRunner->onRecentChange_save( $this );
498
499 // Apply revert tags (if needed)
500 if ( $this->editResult !== null && count( $this->editResult->getRevertTags() ) ) {
501 MediaWikiServices::getInstance()->getChangeTagsStore()->addTags(
502 $this->editResult->getRevertTags(),
503 $this->mAttribs['rc_id'],
504 $this->mAttribs['rc_this_oldid'],
505 $this->mAttribs['rc_logid'],
506 FormatJson::encode( $this->editResult ),
507 $this
508 );
509 }
510
511 if ( count( $this->tags ) ) {
512 // $this->tags may contain revert tags we already applied above, they will
513 // just be ignored.
514 MediaWikiServices::getInstance()->getChangeTagsStore()->addTags(
515 $this->tags,
516 $this->mAttribs['rc_id'],
517 $this->mAttribs['rc_this_oldid'],
518 $this->mAttribs['rc_logid'],
519 null,
520 $this
521 );
522 }
523
524 if ( $send === self::SEND_FEED ) {
525 // Emit the change to external applications via RCFeeds.
526 $this->notifyRCFeeds();
527 }
528
529 # E-mail notifications
530 if ( self::isEnotifEnabled( $mainConfig ) ) {
531 $userFactory = $services->getUserFactory();
532 $editor = $userFactory->newFromUserIdentity( $this->getPerformerIdentity() );
533 $page = $this->getPage();
534 $title = Title::castFromPageReference( $page );
535
536 // Never send an RC notification email about categorization changes
537 if (
538 $title &&
539 $hookRunner->onAbortEmailNotification( $editor, $title, $this ) &&
540 $this->mAttribs['rc_type'] != RC_CATEGORIZE
541 ) {
542 // @FIXME: This would be better as an extension hook
543 // Send emails or email jobs once this row is safely committed
544 $dbw->onTransactionCommitOrIdle(
545 function () use ( $editor, $title ) {
546 $enotif = new EmailNotification();
547 $enotif->notifyOnPageChange(
548 $editor,
549 $title,
550 $this->mAttribs['rc_timestamp'],
551 $this->mAttribs['rc_comment'],
552 $this->mAttribs['rc_minor'],
553 $this->mAttribs['rc_last_oldid'],
554 $this->mExtra['pageStatus']
555 );
556 },
557 __METHOD__
558 );
559 }
560 }
561
562 $jobs = [];
563 // Flush old entries from the `recentchanges` table
564 if ( mt_rand( 0, 9 ) == 0 ) {
565 $jobs[] = RecentChangesUpdateJob::newPurgeJob();
566 }
567 // Update the cached list of active users
568 if ( $this->mAttribs['rc_user'] > 0 ) {
569 $jobs[] = RecentChangesUpdateJob::newCacheUpdateJob();
570 }
571 $services->getJobQueueGroup()->lazyPush( $jobs );
572 }
573
574 /**
575 * Notify all the feeds about the change.
576 * @param array|null $feeds Optional feeds to send to, defaults to $wgRCFeeds
577 */
578 public function notifyRCFeeds( ?array $feeds = null ) {
579 // T403757: Don't send 'suppressed from creation' recent changes entries to the RCFeeds as they do not
580 // have systems to appropriately redact suppressed / deleted material
581 if ( $this->mAttribs['rc_deleted'] != 0 ) {
582 return;
583 }
584
585 $feeds ??=
586 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::RCFeeds );
587
588 $performer = $this->getPerformerIdentity();
589
590 foreach ( $feeds as $params ) {
591 $params += [
592 'omit_bots' => false,
593 'omit_anon' => false,
594 'omit_user' => false,
595 'omit_minor' => false,
596 'omit_patrolled' => false,
597 ];
598
599 if (
600 ( $params['omit_bots'] && $this->mAttribs['rc_bot'] ) ||
601 ( $params['omit_anon'] && !$performer->isRegistered() ) ||
602 ( $params['omit_user'] && $performer->isRegistered() ) ||
603 ( $params['omit_minor'] && $this->mAttribs['rc_minor'] ) ||
604 ( $params['omit_patrolled'] && $this->mAttribs['rc_patrolled'] ) ||
605 $this->mAttribs['rc_type'] == RC_EXTERNAL
606 ) {
607 continue;
608 }
609
610 $actionComment = $this->mExtra['actionCommentIRC'] ?? null;
611
612 $feed = RCFeed::factory( $params );
613 $feed->notify( $this, $actionComment );
614 }
615 }
616
617 /**
618 * Mark this RecentChange as patrolled
619 *
620 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
621 * 'markedaspatrollederror-noautopatrol' as errors
622 *
623 * @deprecated since 1.43 Use markPatrolled() instead
624 *
625 * @param Authority $performer User performing the action
626 * @param bool|null $auto Unused. Passing true logs a warning.
627 * @param string|string[]|null $tags Change tags to add to the patrol log entry
628 * ($user should be able to add the specified tags before this is called)
629 * @return array[] Array of permissions errors, see PermissionManager::getPermissionErrors()
630 */
631 public function doMarkPatrolled( Authority $performer, $auto = null, $tags = null ) {
632 wfDeprecated( __METHOD__, '1.43' );
633 if ( $auto ) {
634 wfWarn( __METHOD__ . ' with $auto = true' );
635 return [];
636 }
637 return $this->markPatrolled( $performer, $tags )->toLegacyErrorArray();
638 }
639
640 /**
641 * Mark this RecentChange as patrolled
642 *
643 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
644 * 'markedaspatrollederror-noautopatrol' as errors
645 *
646 * @param Authority $performer User performing the action
647 * @param string|string[]|null $tags Change tags to add to the patrol log entry
648 * ($user should be able to add the specified tags before this is called)
649 * @return PermissionStatus
650 */
651 public function markPatrolled( Authority $performer, $tags = null ): PermissionStatus {
652 $services = MediaWikiServices::getInstance();
653 $mainConfig = $services->getMainConfig();
654 $useRCPatrol = $mainConfig->get( MainConfigNames::UseRCPatrol );
655 $useNPPatrol = $mainConfig->get( MainConfigNames::UseNPPatrol );
656 $useFilePatrol = $mainConfig->get( MainConfigNames::UseFilePatrol );
657 // Fix up $tags so that the MarkPatrolled hook below always gets an array
658 if ( $tags === null ) {
659 $tags = [];
660 } elseif ( is_string( $tags ) ) {
661 $tags = [ $tags ];
662 }
663
664 $status = PermissionStatus::newEmpty();
665 // If recentchanges patrol is disabled, only new pages or new file versions
666 // can be patrolled, provided the appropriate config variable is set
667 if ( !$useRCPatrol && ( !$useNPPatrol || $this->getAttribute( 'rc_type' ) != RC_NEW ) &&
668 ( !$useFilePatrol || !( $this->getAttribute( 'rc_type' ) == RC_LOG &&
669 $this->getAttribute( 'rc_log_type' ) == 'upload' ) ) ) {
670 $status->fatal( 'rcpatroldisabled' );
671 }
672 $performer->authorizeWrite( 'patrol', $this->getTitle(), $status );
673 $user = $services->getUserFactory()->newFromAuthority( $performer );
674 $hookRunner = new HookRunner( $services->getHookContainer() );
675 if ( !$hookRunner->onMarkPatrolled(
676 $this->getAttribute( 'rc_id' ), $user, false, false, $tags )
677 ) {
678 $status->fatal( 'hookaborted' );
679 }
680 // Users without the 'autopatrol' right can't patrol their own revisions
681 if ( $performer->getUser()->getName() === $this->getAttribute( 'rc_user_text' ) &&
682 !$performer->isAllowed( 'autopatrol' )
683 ) {
684 $status->fatal( 'markedaspatrollederror-noautopatrol' );
685 }
686 if ( !$status->isGood() ) {
687 return $status;
688 }
689 // If the change was patrolled already, do nothing
690 if ( $this->getAttribute( 'rc_patrolled' ) ) {
691 return $status;
692 }
693 // Attempt to set the 'patrolled' flag in RC database
694 $affectedRowCount = $this->reallyMarkPatrolled();
695
696 if ( $affectedRowCount === 0 ) {
697 // Query succeeded but no rows change, e.g. another request
698 // patrolled the same change just before us.
699 // Avoid duplicate log entry (T196182).
700 return $status;
701 }
702
703 // Log this patrol event
704 PatrolLog::record( $this, false, $performer->getUser(), $tags );
705
706 $hookRunner->onMarkPatrolledComplete(
707 $this->getAttribute( 'rc_id' ), $user, false, false );
708
709 return $status;
710 }
711
712 /**
713 * Mark this RecentChange patrolled, without error checking
714 *
715 * @return int Number of database rows changed, usually 1, but 0 if
716 * another request already patrolled it in the mean time.
717 */
718 public function reallyMarkPatrolled() {
719 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
720 $dbw->newUpdateQueryBuilder()
721 ->update( 'recentchanges' )
722 ->set( [ 'rc_patrolled' => self::PRC_PATROLLED ] )
723 ->where( [
724 'rc_id' => $this->getAttribute( 'rc_id' ),
725 'rc_patrolled' => self::PRC_UNPATROLLED,
726 ] )
727 ->caller( __METHOD__ )->execute();
728 $affectedRowCount = $dbw->affectedRows();
729 // The change was patrolled already, do nothing
730 if ( $affectedRowCount === 0 ) {
731 return 0;
732 }
733 // Invalidate the page cache after the page has been patrolled
734 // to make sure that the Patrol link isn't visible any longer!
735 $this->getTitle()->invalidateCache();
736
737 // Enqueue a reverted tag update (in case the edit was a revert)
738 $revisionId = $this->getAttribute( 'rc_this_oldid' );
739 if ( $revisionId ) {
740 $revertedTagUpdateManager =
741 MediaWikiServices::getInstance()->getRevertedTagUpdateManager();
742 $revertedTagUpdateManager->approveRevertedTagForRevision( $revisionId );
743 }
744
745 return $affectedRowCount;
746 }
747
748 /**
749 * Makes an entry in the database corresponding to an edit
750 *
751 * @since 1.36 Added $editResult parameter
752 *
753 * @param string $timestamp
754 * @param PageIdentity $page
755 * @param bool $minor
756 * @param UserIdentity $user
757 * @param string $comment
758 * @param int $oldId
759 * @param string $lastTimestamp
760 * @param bool $bot
761 * @param string $ip
762 * @param int $oldSize
763 * @param int $newSize
764 * @param int $newId
765 * @param int $patrol
766 * @param string[] $tags
767 * @param EditResult|null $editResult EditResult associated with this edit. Can be safely
768 * skipped if the edit is not a revert. Used only for marking revert tags.
769 *
770 * @return RecentChange
771 */
772 public static function notifyEdit(
773 $timestamp, $page, $minor, $user, $comment, $oldId, $lastTimestamp,
774 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0,
775 $tags = [], ?EditResult $editResult = null
776 ) {
777 Assert::parameter( $page->exists(), '$page', 'must represent an existing page' );
778
779 $rc = new RecentChange;
780 $rc->mPage = $page;
781 $rc->mPerformer = $user;
782 $rc->mAttribs = [
783 'rc_timestamp' => $timestamp,
784 'rc_namespace' => $page->getNamespace(),
785 'rc_title' => $page->getDBkey(),
786 'rc_type' => RC_EDIT,
787 'rc_source' => self::SRC_EDIT,
788 'rc_minor' => $minor ? 1 : 0,
789 'rc_cur_id' => $page->getId(),
790 'rc_user' => $user->getId(),
791 'rc_user_text' => $user->getName(),
792 'rc_comment' => &$comment,
793 'rc_comment_text' => &$comment,
794 'rc_comment_data' => null,
795 'rc_this_oldid' => (int)$newId,
796 'rc_last_oldid' => $oldId,
797 'rc_bot' => $bot ? 1 : 0,
798 'rc_ip' => self::checkIPAddress( $ip ),
799 'rc_patrolled' => intval( $patrol ),
800 'rc_new' => 0, # obsolete
801 'rc_old_len' => $oldSize,
802 'rc_new_len' => $newSize,
803 'rc_deleted' => 0,
804 'rc_logid' => 0,
805 'rc_log_type' => null,
806 'rc_log_action' => '',
807 'rc_params' => ''
808 ];
809
810 // TODO: deprecate the 'prefixedDBkey' entry, let callers do the formatting.
811 $formatter = MediaWikiServices::getInstance()->getTitleFormatter();
812
813 $rc->mExtra = [
814 'prefixedDBkey' => $formatter->getPrefixedDBkey( $page ),
815 'lastTimestamp' => $lastTimestamp,
816 'oldSize' => $oldSize,
817 'newSize' => $newSize,
818 'pageStatus' => 'changed'
819 ];
820
821 DeferredUpdates::addCallableUpdate(
822 static function () use ( $rc, $tags, $editResult ) {
823 $rc->addTags( $tags );
824 $rc->setEditResult( $editResult );
825 $rc->save();
826 },
827 DeferredUpdates::POSTSEND,
828 MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase()
829 );
830
831 return $rc;
832 }
833
834 /**
835 * Makes an entry in the database corresponding to page creation
836 * @note $page must reflect the state of the database after the page creation. In particular,
837 * $page->getId() must return the newly assigned page ID.
838 *
839 * @param string $timestamp
840 * @param PageIdentity $page
841 * @param bool $minor
842 * @param UserIdentity $user
843 * @param string $comment
844 * @param bool $bot
845 * @param string $ip
846 * @param int $size
847 * @param int $newId
848 * @param int $patrol
849 * @param string[] $tags
850 *
851 * @return RecentChange
852 */
853 public static function notifyNew(
854 $timestamp,
855 $page, $minor, $user, $comment, $bot,
856 $ip = '', $size = 0, $newId = 0, $patrol = 0, $tags = []
857 ) {
858 Assert::parameter( $page->exists(), '$page', 'must represent an existing page' );
859
860 $rc = new RecentChange;
861 $rc->mPage = $page;
862 $rc->mPerformer = $user;
863 $rc->mAttribs = [
864 'rc_timestamp' => $timestamp,
865 'rc_namespace' => $page->getNamespace(),
866 'rc_title' => $page->getDBkey(),
867 'rc_type' => RC_NEW,
868 'rc_source' => self::SRC_NEW,
869 'rc_minor' => $minor ? 1 : 0,
870 'rc_cur_id' => $page->getId(),
871 'rc_user' => $user->getId(),
872 'rc_user_text' => $user->getName(),
873 'rc_comment' => &$comment,
874 'rc_comment_text' => &$comment,
875 'rc_comment_data' => null,
876 'rc_this_oldid' => (int)$newId,
877 'rc_last_oldid' => 0,
878 'rc_bot' => $bot ? 1 : 0,
879 'rc_ip' => self::checkIPAddress( $ip ),
880 'rc_patrolled' => intval( $patrol ),
881 'rc_new' => 1, # obsolete
882 'rc_old_len' => 0,
883 'rc_new_len' => $size,
884 'rc_deleted' => 0,
885 'rc_logid' => 0,
886 'rc_log_type' => null,
887 'rc_log_action' => '',
888 'rc_params' => ''
889 ];
890
891 // TODO: deprecate the 'prefixedDBkey' entry, let callers do the formatting.
892 $formatter = MediaWikiServices::getInstance()->getTitleFormatter();
893
894 $rc->mExtra = [
895 'prefixedDBkey' => $formatter->getPrefixedDBkey( $page ),
896 'lastTimestamp' => 0,
897 'oldSize' => 0,
898 'newSize' => $size,
899 'pageStatus' => 'created'
900 ];
901
902 DeferredUpdates::addCallableUpdate(
903 static function () use ( $rc, $tags ) {
904 $rc->addTags( $tags );
905 $rc->save();
906 },
907 DeferredUpdates::POSTSEND,
908 MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase()
909 );
910
911 return $rc;
912 }
913
914 /**
915 * @param string $timestamp
916 * @param PageReference $logPage
917 * @param UserIdentity $user
918 * @param string $actionComment
919 * @param string $ip
920 * @param string $type
921 * @param string $action
922 * @param PageReference $target
923 * @param string $logComment
924 * @param string $params
925 * @param int $newId
926 * @param string $actionCommentIRC
927 *
928 * @return bool
929 */
930 public static function notifyLog( $timestamp,
931 $logPage, $user, $actionComment, $ip, $type,
932 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
933 ) {
934 $logRestrictions = MediaWikiServices::getInstance()->getMainConfig()
935 ->get( MainConfigNames::LogRestrictions );
936
937 # Don't add private logs to RC!
938 if ( isset( $logRestrictions[$type] ) && $logRestrictions[$type] != '*' ) {
939 return false;
940 }
941 $rc = self::newLogEntry( $timestamp,
942 $logPage, $user, $actionComment, $ip, $type, $action,
943 $target, $logComment, $params, $newId, $actionCommentIRC );
944 $rc->save();
945
946 return true;
947 }
948
949 /**
950 * @param string $timestamp
951 * @param PageReference $logPage
952 * @param UserIdentity $user
953 * @param string $actionComment
954 * @param string $ip
955 * @param string $type
956 * @param string $action
957 * @param PageReference $target
958 * @param string $logComment
959 * @param string $params
960 * @param int $newId
961 * @param string $actionCommentIRC
962 * @param int $revId Id of associated revision, if any
963 * @param bool $isPatrollable Whether this log entry is patrollable
964 * @param bool|null $forceBotFlag Override the default behavior and set bot flag to
965 * the value of the argument. When omitted or null, it falls back to the global state.
966 * @param int|null $deleted Value to set as rc_deleted (one of the LogPage::DELETED_* constants or 0)
967 *
968 * @return RecentChange
969 */
970 public static function newLogEntry( $timestamp,
971 $logPage, $user, $actionComment, $ip,
972 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '',
973 $revId = 0, $isPatrollable = false, $forceBotFlag = null, $deleted = 0
974 ) {
975 global $wgRequest;
976
977 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
978
979 # # Get pageStatus for email notification
980 switch ( $type . '-' . $action ) {
981 case 'delete-delete':
982 case 'delete-delete_redir':
983 case 'delete-delete_redir2':
984 $pageStatus = 'deleted';
985 break;
986 case 'move-move':
987 case 'move-move_redir':
988 $pageStatus = 'moved';
989 break;
990 case 'delete-restore':
991 $pageStatus = 'restored';
992 break;
993 case 'upload-upload':
994 $pageStatus = 'created';
995 break;
996 case 'upload-overwrite':
997 default:
998 $pageStatus = 'changed';
999 break;
1000 }
1001
1002 // Allow unpatrolled status for patrollable log entries
1003 $canAutopatrol = $permissionManager->userHasRight( $user, 'autopatrol' );
1004 $markPatrolled = $isPatrollable ? $canAutopatrol : true;
1005
1006 if ( $target instanceof PageIdentity && $target->canExist() ) {
1007 $pageId = $target->getId();
1008 } else {
1009 $pageId = 0;
1010 }
1011
1012 if ( $forceBotFlag !== null ) {
1013 $bot = (int)$forceBotFlag;
1014 } else {
1015 $bot = $permissionManager->userHasRight( $user, 'bot' ) ?
1016 (int)$wgRequest->getBool( 'bot', true ) : 0;
1017 }
1018
1019 $rc = new RecentChange;
1020 $rc->mPage = $target;
1021 $rc->mPerformer = $user;
1022 $rc->mAttribs = [
1023 'rc_timestamp' => $timestamp,
1024 'rc_namespace' => $target->getNamespace(),
1025 'rc_title' => $target->getDBkey(),
1026 'rc_type' => RC_LOG,
1027 'rc_source' => self::SRC_LOG,
1028 'rc_minor' => 0,
1029 'rc_cur_id' => $pageId,
1030 'rc_user' => $user->getId(),
1031 'rc_user_text' => $user->getName(),
1032 'rc_comment' => &$logComment,
1033 'rc_comment_text' => &$logComment,
1034 'rc_comment_data' => null,
1035 'rc_this_oldid' => (int)$revId,
1036 'rc_last_oldid' => 0,
1037 'rc_bot' => $bot,
1038 'rc_ip' => self::checkIPAddress( $ip ),
1039 'rc_patrolled' => $markPatrolled ? self::PRC_AUTOPATROLLED : self::PRC_UNPATROLLED,
1040 'rc_new' => 0, # obsolete
1041 'rc_old_len' => null,
1042 'rc_new_len' => null,
1043 'rc_deleted' => $deleted,
1044 'rc_logid' => $newId,
1045 'rc_log_type' => $type,
1046 'rc_log_action' => $action,
1047 'rc_params' => $params
1048 ];
1049
1050 // TODO: deprecate the 'prefixedDBkey' entry, let callers do the formatting.
1051 $formatter = MediaWikiServices::getInstance()->getTitleFormatter();
1052
1053 $rc->mExtra = [
1054 // XXX: This does not correspond to rc_namespace/rc_title/rc_cur_id.
1055 // Is that intentional? For all other kinds of RC entries, prefixedDBkey
1056 // matches rc_namespace/rc_title. Do we even need $logPage?
1057 'prefixedDBkey' => $formatter->getPrefixedDBkey( $logPage ),
1058 'lastTimestamp' => 0,
1059 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
1060 'pageStatus' => $pageStatus,
1061 'actionCommentIRC' => $actionCommentIRC
1062 ];
1063
1064 return $rc;
1065 }
1066
1067 /**
1068 * Constructs a RecentChange object for the given categorization
1069 * This does not call save() on the object and thus does not write to the db
1070 *
1071 * @since 1.27
1072 *
1073 * @param string $timestamp Timestamp of the recent change to occur
1074 * @param PageIdentity $categoryTitle the category a page is being added to or removed from
1075 * @param UserIdentity|null $user User object of the user that made the change
1076 * @param string $comment Change summary
1077 * @param PageIdentity $pageTitle the page that is being added or removed
1078 * @param int $oldRevId Parent revision ID of this change
1079 * @param int $newRevId Revision ID of this change
1080 * @param string $lastTimestamp Parent revision timestamp of this change
1081 * @param bool $bot true, if the change was made by a bot
1082 * @param string $ip IP address of the user, if the change was made anonymously
1083 * @param int $deleted Indicates whether the change has been deleted
1084 * @param bool|null $added true, if the category was added, false for removed
1085 * @param bool $forImport Whether the associated revision was imported
1086 *
1087 * @return RecentChange
1088 */
1089 public static function newForCategorization(
1090 $timestamp,
1091 PageIdentity $categoryTitle,
1092 ?UserIdentity $user,
1093 $comment,
1094 PageIdentity $pageTitle,
1095 $oldRevId,
1096 $newRevId,
1097 $lastTimestamp,
1098 $bot,
1099 $ip = '',
1100 $deleted = 0,
1101 $added = null,
1102 bool $forImport = false
1103 ) {
1104 // Done in a backwards compatible way.
1105 $categoryWikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()
1106 ->newFromTitle( $categoryTitle );
1107
1108 '@phan-var WikiCategoryPage $categoryWikiPage';
1109 $params = [
1110 'hidden-cat' => $categoryWikiPage->isHidden()
1111 ];
1112 if ( $added !== null ) {
1113 $params['added'] = $added;
1114 }
1115
1116 if ( !$user ) {
1117 // XXX: when and why do we need this?
1118 $user = MediaWikiServices::getInstance()->getActorStore()->getUnknownActor();
1119 }
1120
1121 $rc = new RecentChange;
1122 $rc->mPage = $categoryTitle;
1123 $rc->mPerformer = $user;
1124 $rc->mAttribs = [
1125 'rc_timestamp' => MWTimestamp::convert( TS_MW, $timestamp ),
1126 'rc_namespace' => $categoryTitle->getNamespace(),
1127 'rc_title' => $categoryTitle->getDBkey(),
1128 'rc_type' => RC_CATEGORIZE,
1129 'rc_source' => self::SRC_CATEGORIZE,
1130 'rc_minor' => 0,
1131 // XXX: rc_cur_id does not correspond to rc_namespace/rc_title.
1132 // It's because when the page (rc_cur_id) is deleted, we want
1133 // to delete the categorization entries, too (see LinksDeletionUpdate).
1134 'rc_cur_id' => $pageTitle->getId(),
1135 'rc_user' => $user->getId(),
1136 'rc_user_text' => $user->getName(),
1137 'rc_comment' => &$comment,
1138 'rc_comment_text' => &$comment,
1139 'rc_comment_data' => null,
1140 'rc_this_oldid' => (int)$newRevId,
1141 'rc_last_oldid' => $oldRevId,
1142 'rc_bot' => $bot ? 1 : 0,
1143 'rc_ip' => self::checkIPAddress( $ip ),
1144 'rc_patrolled' => self::PRC_AUTOPATROLLED, // Always patrolled, just like log entries
1145 'rc_new' => 0, # obsolete
1146 'rc_old_len' => null,
1147 'rc_new_len' => null,
1148 'rc_deleted' => $deleted,
1149 'rc_logid' => 0,
1150 'rc_log_type' => null,
1151 'rc_log_action' => '',
1152 'rc_params' => serialize( $params )
1153 ];
1154
1155 // TODO: deprecate the 'prefixedDBkey' entry, let callers do the formatting.
1156 $formatter = MediaWikiServices::getInstance()->getTitleFormatter();
1157
1158 $rc->mExtra = [
1159 'prefixedDBkey' => $formatter->getPrefixedDBkey( $categoryTitle ),
1160 'lastTimestamp' => $lastTimestamp,
1161 'oldSize' => 0,
1162 'newSize' => 0,
1163 'pageStatus' => 'changed',
1164 'forImport' => $forImport,
1165 ];
1166
1167 return $rc;
1168 }
1169
1170 /**
1171 * Get a parameter value
1172 *
1173 * @since 1.27
1174 *
1175 * @param string $name parameter name
1176 * @return mixed
1177 */
1178 public function getParam( $name ) {
1179 $params = $this->parseParams();
1180 return $params[$name] ?? null;
1181 }
1182
1183 /**
1184 * Initialises the members of this object from a mysql row object
1185 *
1186 * @param mixed $row
1187 */
1188 public function loadFromRow( $row ) {
1189 $this->mAttribs = get_object_vars( $row );
1190 $this->mAttribs['rc_timestamp'] = wfTimestamp( TS_MW, $this->mAttribs['rc_timestamp'] );
1191 // rc_deleted MUST be set
1192 $this->mAttribs['rc_deleted'] = $row->rc_deleted;
1193
1194 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1195 $comment = MediaWikiServices::getInstance()->getCommentStore()
1196 // Legacy because $row may have come from self::selectFields()
1197 ->getCommentLegacy( $dbr, 'rc_comment', $row, true )
1198 ->text;
1199 $this->mAttribs['rc_comment'] = &$comment;
1200 $this->mAttribs['rc_comment_text'] = &$comment;
1201 $this->mAttribs['rc_comment_data'] = null;
1202
1203 $this->mPerformer = $this->getUserIdentityFromAnyId(
1204 $row->rc_user ?? null,
1205 $row->rc_user_text ?? null,
1206 $row->rc_actor ?? null
1207 );
1208 $this->mAttribs['rc_user'] = $this->mPerformer->getId();
1209 $this->mAttribs['rc_user_text'] = $this->mPerformer->getName();
1210
1211 // Watchlist expiry.
1212 if ( isset( $row->we_expiry ) && $row->we_expiry ) {
1213 $this->watchlistExpiry = wfTimestamp( TS_MW, $row->we_expiry );
1214 }
1215 }
1216
1217 /**
1218 * Get an attribute value
1219 *
1220 * @param string $name Attribute name
1221 * @return mixed
1222 */
1223 public function getAttribute( $name ) {
1224 if ( $name === 'rc_comment' ) {
1225 return MediaWikiServices::getInstance()->getCommentStore()
1226 ->getComment( 'rc_comment', $this->mAttribs, true )->text;
1227 }
1228
1229 if ( $name === 'rc_user' || $name === 'rc_user_text' || $name === 'rc_actor' ) {
1230 $user = $this->getPerformerIdentity();
1231
1232 if ( $name === 'rc_user' ) {
1233 return $user->getId();
1234 }
1235 if ( $name === 'rc_user_text' ) {
1236 return $user->getName();
1237 }
1238 if ( $name === 'rc_actor' ) {
1239 // NOTE: rc_actor exists in the database, but application logic should not use it.
1240 wfDeprecatedMsg( 'Accessing deprecated field rc_actor', '1.36' );
1241 $actorStore = MediaWikiServices::getInstance()->getActorStore();
1242 $db = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1243 return $actorStore->findActorId( $user, $db );
1244 }
1245 }
1246
1247 return $this->mAttribs[$name] ?? null;
1248 }
1249
1250 /**
1251 * @return array
1252 */
1253 public function getAttributes() {
1254 return $this->mAttribs;
1255 }
1256
1257 /**
1258 * Gets the end part of the diff URL associated with this object
1259 * Blank if no diff link should be displayed
1260 * @param bool $forceCur
1261 * @return string
1262 */
1263 public function diffLinkTrail( $forceCur ) {
1264 if ( $this->mAttribs['rc_type'] == RC_EDIT ) {
1265 $trail = "curid=" . (int)( $this->mAttribs['rc_cur_id'] ) .
1266 "&oldid=" . (int)( $this->mAttribs['rc_last_oldid'] );
1267 if ( $forceCur ) {
1268 $trail .= '&diff=0';
1269 } else {
1270 $trail .= '&diff=' . (int)( $this->mAttribs['rc_this_oldid'] );
1271 }
1272 } else {
1273 $trail = '';
1274 }
1275
1276 return $trail;
1277 }
1278
1279 /**
1280 * Returns the change size (HTML).
1281 * The lengths can be given optionally.
1282 * @param int $old
1283 * @param int $new
1284 * @return string
1285 */
1286 public function getCharacterDifference( $old = 0, $new = 0 ) {
1287 if ( $old === 0 ) {
1288 $old = $this->mAttribs['rc_old_len'];
1289 }
1290 if ( $new === 0 ) {
1291 $new = $this->mAttribs['rc_new_len'];
1292 }
1293 if ( $old === null || $new === null ) {
1294 return '';
1295 }
1296
1297 return ChangesList::showCharacterDifference( $old, $new );
1298 }
1299
1300 private static function checkIPAddress( $ip ) {
1301 global $wgRequest;
1302
1303 if ( $ip ) {
1304 if ( !IPUtils::isIPAddress( $ip ) ) {
1305 throw new RuntimeException( "Attempt to write \"" . $ip .
1306 "\" as an IP address into recent changes" );
1307 }
1308 } else {
1309 $ip = $wgRequest->getIP();
1310 if ( !$ip ) {
1311 $ip = '';
1312 }
1313 }
1314
1315 return $ip;
1316 }
1317
1318 /**
1319 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
1320 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
1321 * or rows which will be deleted soon shouldn't be included.
1322 *
1323 * @param mixed $timestamp MWTimestamp compatible timestamp
1324 * @param int $tolerance Tolerance in seconds
1325 * @return bool
1326 */
1327 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
1328 $rcMaxAge =
1329 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::RCMaxAge );
1330
1331 return (int)wfTimestamp( TS_UNIX, $timestamp ) > time() - $tolerance - $rcMaxAge;
1332 }
1333
1334 /**
1335 * Whether e-mail notifications are generally enabled on this wiki.
1336 *
1337 * This is used for:
1338 *
1339 * - performance optimization in RecentChange::save().
1340 * After an edit, whether or not we need to use the EmailNotification
1341 * service to determine which EnotifNotifyJob to dispatch.
1342 *
1343 * - performance optmization in WatchlistManager.
1344 * After using reset ("Mark all pages as seen") on Special:Watchlist,
1345 * whether to only look for user talk data to reset, or whether to look
1346 * at all possible pages for timestamps to reset.
1347 *
1348 * TODO: Determine whether these optimizations still make sense.
1349 *
1350 * FIXME: The $wgShowUpdatedMarker variable was added to this condtion
1351 * in 2008 (2cf12c973d, SVN r35001) because at the time the per-user
1352 * "last seen" marker for watchlist and page history, was managed by
1353 * the EmailNotification/UserMailed classes. As of August 2022, this
1354 * appears to no longer be the case.
1355 *
1356 * @since 1.40
1357 * @param Config $conf
1358 * @return bool
1359 */
1360 public static function isEnotifEnabled( Config $conf ): bool {
1361 return $conf->get( MainConfigNames::EnotifUserTalk ) ||
1362 $conf->get( MainConfigNames::EnotifWatchlist ) ||
1363 $conf->get( MainConfigNames::ShowUpdatedMarker );
1364 }
1365
1366 /**
1367 * Get the extra URL that is given as part of the notification to RCFeed consumers.
1368 *
1369 * This is mainly to facilitate patrolling or other content review.
1370 *
1371 * @since 1.40
1372 * @return string|null URL
1373 */
1374 public function getNotifyUrl() {
1375 $services = MediaWikiServices::getInstance();
1376 $mainConfig = $services->getMainConfig();
1377 $useRCPatrol = $mainConfig->get( MainConfigNames::UseRCPatrol );
1378 $useNPPatrol = $mainConfig->get( MainConfigNames::UseNPPatrol );
1379 $localInterwikis = $mainConfig->get( MainConfigNames::LocalInterwikis );
1380 $canonicalServer = $mainConfig->get( MainConfigNames::CanonicalServer );
1381 $script = $mainConfig->get( MainConfigNames::Script );
1382
1383 $type = $this->getAttribute( 'rc_type' );
1384 if ( $type == RC_LOG ) {
1385 $url = null;
1386 } else {
1387 $url = $canonicalServer . $script;
1388 if ( $type == RC_NEW ) {
1389 $query = '?oldid=' . $this->getAttribute( 'rc_this_oldid' );
1390 } else {
1391 $query = '?diff=' . $this->getAttribute( 'rc_this_oldid' )
1392 . '&oldid=' . $this->getAttribute( 'rc_last_oldid' );
1393 }
1394 if ( $useRCPatrol || ( $this->getAttribute( 'rc_type' ) == RC_NEW && $useNPPatrol ) ) {
1395 $query .= '&rcid=' . $this->getAttribute( 'rc_id' );
1396 }
1397
1398 ( new HookRunner( $services->getHookContainer() ) )->onIRCLineURL( $url, $query, $this );
1399 $url .= $query;
1400 }
1401
1402 return $url;
1403 }
1404
1405 /**
1406 * Parses and returns the rc_params attribute
1407 *
1408 * @since 1.26
1409 * @return mixed|bool false on failed unserialization
1410 */
1411 public function parseParams() {
1412 return LogEntryBase::extractParams( $this->getAttribute( 'rc_params' ),
1413 $this->getAttribute( 'rc_log_type' ) . '/' . $this->getAttribute( 'rc_log_action' ) );
1414 }
1415
1416 /**
1417 * Tags to append to the recent change,
1418 * and associated revision/log
1419 *
1420 * @since 1.28
1421 *
1422 * @param string|string[] $tags
1423 */
1424 public function addTags( $tags ) {
1425 if ( is_string( $tags ) ) {
1426 $this->tags[] = $tags;
1427 } else {
1428 $this->tags = array_merge( $tags, $this->tags );
1429 }
1430 }
1431
1432 /**
1433 * Sets the EditResult associated with the edit.
1434 *
1435 * @since 1.36
1436 *
1437 * @param EditResult|null $editResult
1438 */
1439 public function setEditResult( ?EditResult $editResult ) {
1440 $this->editResult = $editResult;
1441 }
1442
1443 /**
1444 * @param string|int|null $userId
1445 * @param string|null $userName
1446 * @param string|int|null $actorId
1447 *
1448 * @return UserIdentity
1449 */
1450 private function getUserIdentityFromAnyId(
1451 $userId,
1452 $userName,
1453 $actorId = null
1454 ): UserIdentity {
1455 // XXX: Is this logic needed elsewhere? Should it be reusable?
1456
1457 $userId = isset( $userId ) ? (int)$userId : null;
1458 $actorId = isset( $actorId ) ? (int)$actorId : 0;
1459
1460 $actorStore = MediaWikiServices::getInstance()->getActorStore();
1461 if ( $userName && $actorId ) {
1462 // Likely the fields are coming from a join on actor table,
1463 // so can definitely build a UserIdentityValue.
1464 return $actorStore->newActorFromRowFields( $userId, $userName, $actorId );
1465 }
1466 if ( $userId !== null ) {
1467 if ( $userName !== null ) {
1468 // NOTE: For IPs and external users, $userId will be 0.
1469 $user = new UserIdentityValue( $userId, $userName );
1470 } else {
1471 $user = $actorStore->getUserIdentityByUserId( $userId );
1472
1473 if ( !$user ) {
1474 throw new RuntimeException( "User not found by ID: $userId" );
1475 }
1476 }
1477 } elseif ( $actorId > 0 ) {
1478 $db = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1479 $user = $actorStore->getActorById( $actorId, $db );
1480
1481 if ( !$user ) {
1482 throw new RuntimeException( "User not found by actor ID: $actorId" );
1483 }
1484 } elseif ( $userName !== null ) {
1485 $user = $actorStore->getUserIdentityByName( $userName );
1486
1487 if ( !$user ) {
1488 throw new RuntimeException( "User not found by name: $userName" );
1489 }
1490 } else {
1491 throw new RuntimeException( 'At least one of user ID, actor ID or user name must be given' );
1492 }
1493
1494 return $user;
1495 }
1496 }