Merge "Type hint against LinkTarget in WatchedItemStore"
[lhc/web/wiklou.git] / includes / changes / RecentChange.php
1 <?php
2 /**
3 * Utility class for creating and accessing recent change entries.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 use MediaWiki\ChangeTags\Taggable;
23
24 /**
25 * Utility class for creating new RC entries
26 *
27 * mAttribs:
28 * rc_id id of the row in the recentchanges table
29 * rc_timestamp time the entry was made
30 * rc_namespace namespace #
31 * rc_title non-prefixed db key
32 * rc_type is new entry, used to determine whether updating is necessary
33 * rc_source string representation of change source
34 * rc_minor is minor
35 * rc_cur_id page_id of associated page entry
36 * rc_user user id who made the entry
37 * rc_user_text user name who made the entry
38 * rc_actor actor id who made the entry
39 * rc_comment edit summary
40 * rc_this_oldid rev_id associated with this entry (or zero)
41 * rc_last_oldid rev_id associated with the entry before this one (or zero)
42 * rc_bot is bot, hidden
43 * rc_ip IP address of the user in dotted quad notation
44 * rc_new obsolete, use rc_type==RC_NEW
45 * rc_patrolled boolean whether or not someone has marked this edit as patrolled
46 * rc_old_len integer byte length of the text before the edit
47 * rc_new_len the same after the edit
48 * rc_deleted partial deletion
49 * rc_logid the log_id value for this log entry (or zero)
50 * rc_log_type the log type (or null)
51 * rc_log_action the log action (or null)
52 * rc_params log params
53 *
54 * mExtra:
55 * prefixedDBkey prefixed db key, used by external app via msg queue
56 * lastTimestamp timestamp of previous entry, used in WHERE clause during update
57 * oldSize text size before the change
58 * newSize text size after the change
59 * pageStatus status of the page: created, deleted, moved, restored, changed
60 *
61 * temporary: not stored in the database
62 * notificationtimestamp
63 * numberofWatchingusers
64 *
65 * @todo Deprecate access to mAttribs (direct or via getAttributes). Right now
66 * we're having to include both rc_comment and rc_comment_text/rc_comment_data
67 * so random crap works right.
68 */
69 class RecentChange implements Taggable {
70 // Constants for the rc_source field. Extensions may also have
71 // their own source constants.
72 const SRC_EDIT = 'mw.edit';
73 const SRC_NEW = 'mw.new';
74 const SRC_LOG = 'mw.log';
75 const SRC_EXTERNAL = 'mw.external'; // obsolete
76 const SRC_CATEGORIZE = 'mw.categorize';
77
78 const PRC_UNPATROLLED = 0;
79 const PRC_PATROLLED = 1;
80 const PRC_AUTOPATROLLED = 2;
81
82 /**
83 * @var bool For save() - save to the database only, without any events.
84 */
85 const SEND_NONE = true;
86
87 /**
88 * @var bool For save() - do emit the change to RCFeeds (usually public).
89 */
90 const SEND_FEED = false;
91
92 public $mAttribs = [];
93 public $mExtra = [];
94
95 /**
96 * @var Title
97 */
98 public $mTitle = false;
99
100 /**
101 * @var User
102 */
103 private $mPerformer = false;
104
105 public $numberofWatchingusers = 0; # Dummy to prevent error message in SpecialRecentChangesLinked
106 public $notificationtimestamp;
107
108 /**
109 * @var int Line number of recent change. Default -1.
110 */
111 public $counter = -1;
112
113 /**
114 * @var array List of tags to apply
115 */
116 private $tags = [];
117
118 /**
119 * @var array Array of change types
120 */
121 private static $changeTypes = [
122 'edit' => RC_EDIT,
123 'new' => RC_NEW,
124 'log' => RC_LOG,
125 'external' => RC_EXTERNAL,
126 'categorize' => RC_CATEGORIZE,
127 ];
128
129 # Factory methods
130
131 /**
132 * @param mixed $row
133 * @return RecentChange
134 */
135 public static function newFromRow( $row ) {
136 $rc = new RecentChange;
137 $rc->loadFromRow( $row );
138
139 return $rc;
140 }
141
142 /**
143 * Parsing text to RC_* constants
144 * @since 1.24
145 * @param string|array $type
146 * @throws MWException
147 * @return int|array RC_TYPE
148 */
149 public static function parseToRCType( $type ) {
150 if ( is_array( $type ) ) {
151 $retval = [];
152 foreach ( $type as $t ) {
153 $retval[] = self::parseToRCType( $t );
154 }
155
156 return $retval;
157 }
158
159 if ( !array_key_exists( $type, self::$changeTypes ) ) {
160 throw new MWException( "Unknown type '$type'" );
161 }
162 return self::$changeTypes[$type];
163 }
164
165 /**
166 * Parsing RC_* constants to human-readable test
167 * @since 1.24
168 * @param int $rcType
169 * @return string $type
170 */
171 public static function parseFromRCType( $rcType ) {
172 return array_search( $rcType, self::$changeTypes, true ) ?: "$rcType";
173 }
174
175 /**
176 * Get an array of all change types
177 *
178 * @since 1.26
179 *
180 * @return array
181 */
182 public static function getChangeTypes() {
183 return array_keys( self::$changeTypes );
184 }
185
186 /**
187 * Obtain the recent change with a given rc_id value
188 *
189 * @param int $rcid The rc_id value to retrieve
190 * @return RecentChange|null
191 */
192 public static function newFromId( $rcid ) {
193 return self::newFromConds( [ 'rc_id' => $rcid ], __METHOD__ );
194 }
195
196 /**
197 * Find the first recent change matching some specific conditions
198 *
199 * @param array $conds Array of conditions
200 * @param mixed $fname Override the method name in profiling/logs
201 * @param int $dbType DB_* constant
202 *
203 * @return RecentChange|null
204 */
205 public static function newFromConds(
206 $conds,
207 $fname = __METHOD__,
208 $dbType = DB_REPLICA
209 ) {
210 $db = wfGetDB( $dbType );
211 $rcQuery = self::getQueryInfo();
212 $row = $db->selectRow(
213 $rcQuery['tables'], $rcQuery['fields'], $conds, $fname, [], $rcQuery['joins']
214 );
215 if ( $row !== false ) {
216 return self::newFromRow( $row );
217 } else {
218 return null;
219 }
220 }
221
222 /**
223 * Return the list of recentchanges fields that should be selected to create
224 * a new recentchanges object.
225 * @deprecated since 1.31, use self::getQueryInfo() instead.
226 * @return array
227 */
228 public static function selectFields() {
229 global $wgActorTableSchemaMigrationStage;
230
231 wfDeprecated( __METHOD__, '1.31' );
232 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
233 // If code is using this instead of self::getQueryInfo(), there's a
234 // decent chance it's going to try to directly access
235 // $row->rc_user or $row->rc_user_text and we can't give it
236 // useful values here once those aren't being used anymore.
237 throw new BadMethodCallException(
238 'Cannot use ' . __METHOD__
239 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
240 );
241 }
242
243 return [
244 'rc_id',
245 'rc_timestamp',
246 'rc_user',
247 'rc_user_text',
248 'rc_actor' => 'NULL',
249 'rc_namespace',
250 'rc_title',
251 'rc_minor',
252 'rc_bot',
253 'rc_new',
254 'rc_cur_id',
255 'rc_this_oldid',
256 'rc_last_oldid',
257 'rc_type',
258 'rc_source',
259 'rc_patrolled',
260 'rc_ip',
261 'rc_old_len',
262 'rc_new_len',
263 'rc_deleted',
264 'rc_logid',
265 'rc_log_type',
266 'rc_log_action',
267 'rc_params',
268 ] + CommentStore::getStore()->getFields( 'rc_comment' );
269 }
270
271 /**
272 * Return the tables, fields, and join conditions to be selected to create
273 * a new recentchanges object.
274 * @since 1.31
275 * @return array With three keys:
276 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
277 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
278 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
279 */
280 public static function getQueryInfo() {
281 $commentQuery = CommentStore::getStore()->getJoin( 'rc_comment' );
282 $actorQuery = ActorMigration::newMigration()->getJoin( 'rc_user' );
283 return [
284 'tables' => [ 'recentchanges' ] + $commentQuery['tables'] + $actorQuery['tables'],
285 'fields' => [
286 'rc_id',
287 'rc_timestamp',
288 'rc_namespace',
289 'rc_title',
290 'rc_minor',
291 'rc_bot',
292 'rc_new',
293 'rc_cur_id',
294 'rc_this_oldid',
295 'rc_last_oldid',
296 'rc_type',
297 'rc_source',
298 'rc_patrolled',
299 'rc_ip',
300 'rc_old_len',
301 'rc_new_len',
302 'rc_deleted',
303 'rc_logid',
304 'rc_log_type',
305 'rc_log_action',
306 'rc_params',
307 ] + $commentQuery['fields'] + $actorQuery['fields'],
308 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
309 ];
310 }
311
312 # Accessors
313
314 /**
315 * @param array $attribs
316 */
317 public function setAttribs( $attribs ) {
318 $this->mAttribs = $attribs;
319 }
320
321 /**
322 * @param array $extra
323 */
324 public function setExtra( $extra ) {
325 $this->mExtra = $extra;
326 }
327
328 /**
329 * @return Title
330 */
331 public function &getTitle() {
332 if ( $this->mTitle === false ) {
333 $this->mTitle = Title::makeTitle( $this->mAttribs['rc_namespace'], $this->mAttribs['rc_title'] );
334 }
335
336 return $this->mTitle;
337 }
338
339 /**
340 * Get the User object of the person who performed this change.
341 *
342 * @return User
343 */
344 public function getPerformer() {
345 if ( $this->mPerformer === false ) {
346 if ( !empty( $this->mAttribs['rc_actor'] ) ) {
347 $this->mPerformer = User::newFromActorId( $this->mAttribs['rc_actor'] );
348 } elseif ( !empty( $this->mAttribs['rc_user'] ) ) {
349 $this->mPerformer = User::newFromId( $this->mAttribs['rc_user'] );
350 } elseif ( !empty( $this->mAttribs['rc_user_text'] ) ) {
351 $this->mPerformer = User::newFromName( $this->mAttribs['rc_user_text'], false );
352 } else {
353 throw new MWException( 'RecentChange object lacks rc_actor, rc_user, and rc_user_text' );
354 }
355 }
356
357 return $this->mPerformer;
358 }
359
360 /**
361 * Writes the data in this object to the database
362 *
363 * For compatibility reasons, the SEND_ constants internally reference a value
364 * that may seem negated from their purpose (none=true, feed=false). This is
365 * because the parameter used to be called "$noudp", defaulting to false.
366 *
367 * @param bool $send self::SEND_FEED or self::SEND_NONE
368 */
369 public function save( $send = self::SEND_FEED ) {
370 global $wgPutIPinRC, $wgUseEnotif, $wgShowUpdatedMarker;
371
372 $dbw = wfGetDB( DB_MASTER );
373 if ( !is_array( $this->mExtra ) ) {
374 $this->mExtra = [];
375 }
376
377 if ( !$wgPutIPinRC ) {
378 $this->mAttribs['rc_ip'] = '';
379 }
380
381 # Strict mode fixups (not-NULL fields)
382 foreach ( [ 'minor', 'bot', 'new', 'patrolled', 'deleted' ] as $field ) {
383 $this->mAttribs["rc_$field"] = (int)$this->mAttribs["rc_$field"];
384 }
385 # ...more fixups (NULL fields)
386 foreach ( [ 'old_len', 'new_len' ] as $field ) {
387 $this->mAttribs["rc_$field"] = isset( $this->mAttribs["rc_$field"] )
388 ? (int)$this->mAttribs["rc_$field"]
389 : null;
390 }
391
392 # If our database is strict about IP addresses, use NULL instead of an empty string
393 $strictIPs = in_array( $dbw->getType(), [ 'oracle', 'postgres' ] ); // legacy
394 if ( $strictIPs && $this->mAttribs['rc_ip'] == '' ) {
395 unset( $this->mAttribs['rc_ip'] );
396 }
397
398 # Trim spaces on user supplied text
399 $this->mAttribs['rc_comment'] = trim( $this->mAttribs['rc_comment'] );
400
401 # Fixup database timestamps
402 $this->mAttribs['rc_timestamp'] = $dbw->timestamp( $this->mAttribs['rc_timestamp'] );
403
404 # # If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
405 if ( $this->mAttribs['rc_cur_id'] == 0 ) {
406 unset( $this->mAttribs['rc_cur_id'] );
407 }
408
409 $row = $this->mAttribs;
410
411 # Convert mAttribs['rc_comment'] for CommentStore
412 $comment = $row['rc_comment'];
413 unset( $row['rc_comment'], $row['rc_comment_text'], $row['rc_comment_data'] );
414 $row += CommentStore::getStore()->insert( $dbw, 'rc_comment', $comment );
415
416 # Convert mAttribs['rc_user'] etc for ActorMigration
417 $user = User::newFromAnyId(
418 $row['rc_user'] ?? null,
419 $row['rc_user_text'] ?? null,
420 $row['rc_actor'] ?? null
421 );
422 unset( $row['rc_user'], $row['rc_user_text'], $row['rc_actor'] );
423 $row += ActorMigration::newMigration()->getInsertValues( $dbw, 'rc_user', $user );
424
425 # Don't reuse an existing rc_id for the new row, if one happens to be
426 # set for some reason.
427 unset( $row['rc_id'] );
428
429 # Insert new row
430 $dbw->insert( 'recentchanges', $row, __METHOD__ );
431
432 # Set the ID
433 $this->mAttribs['rc_id'] = $dbw->insertId();
434
435 # Notify extensions
436 // Avoid PHP 7.1 warning from passing $this by reference
437 $rc = $this;
438 Hooks::run( 'RecentChange_save', [ &$rc ] );
439
440 if ( count( $this->tags ) ) {
441 ChangeTags::addTags( $this->tags, $this->mAttribs['rc_id'],
442 $this->mAttribs['rc_this_oldid'], $this->mAttribs['rc_logid'], null, $this );
443 }
444
445 if ( $send === self::SEND_FEED ) {
446 // Emit the change to external applications via RCFeeds.
447 $this->notifyRCFeeds();
448 }
449
450 # E-mail notifications
451 if ( $wgUseEnotif || $wgShowUpdatedMarker ) {
452 $editor = $this->getPerformer();
453 $title = $this->getTitle();
454
455 // Never send an RC notification email about categorization changes
456 if (
457 Hooks::run( 'AbortEmailNotification', [ $editor, $title, $this ] ) &&
458 $this->mAttribs['rc_type'] != RC_CATEGORIZE
459 ) {
460 // @FIXME: This would be better as an extension hook
461 // Send emails or email jobs once this row is safely committed
462 $dbw->onTransactionCommitOrIdle(
463 function () use ( $editor, $title ) {
464 $enotif = new EmailNotification();
465 $enotif->notifyOnPageChange(
466 $editor,
467 $title,
468 $this->mAttribs['rc_timestamp'],
469 $this->mAttribs['rc_comment'],
470 $this->mAttribs['rc_minor'],
471 $this->mAttribs['rc_last_oldid'],
472 $this->mExtra['pageStatus']
473 );
474 },
475 __METHOD__
476 );
477 }
478 }
479
480 // Update the cached list of active users
481 if ( $this->mAttribs['rc_user'] > 0 ) {
482 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newCacheUpdateJob() );
483 }
484 }
485
486 /**
487 * Notify all the feeds about the change.
488 * @param array|null $feeds Optional feeds to send to, defaults to $wgRCFeeds
489 */
490 public function notifyRCFeeds( array $feeds = null ) {
491 global $wgRCFeeds;
492 if ( $feeds === null ) {
493 $feeds = $wgRCFeeds;
494 }
495
496 $performer = $this->getPerformer();
497
498 foreach ( $feeds as $params ) {
499 $params += [
500 'omit_bots' => false,
501 'omit_anon' => false,
502 'omit_user' => false,
503 'omit_minor' => false,
504 'omit_patrolled' => false,
505 ];
506
507 if (
508 ( $params['omit_bots'] && $this->mAttribs['rc_bot'] ) ||
509 ( $params['omit_anon'] && $performer->isAnon() ) ||
510 ( $params['omit_user'] && !$performer->isAnon() ) ||
511 ( $params['omit_minor'] && $this->mAttribs['rc_minor'] ) ||
512 ( $params['omit_patrolled'] && $this->mAttribs['rc_patrolled'] ) ||
513 $this->mAttribs['rc_type'] == RC_EXTERNAL
514 ) {
515 continue;
516 }
517
518 $actionComment = $this->mExtra['actionCommentIRC'] ?? null;
519
520 $feed = RCFeed::factory( $params );
521 $feed->notify( $this, $actionComment );
522 }
523 }
524
525 /**
526 * @since 1.22
527 * @deprecated since 1.29 Use RCFeed::factory() instead
528 * @param string $uri URI to get the engine object for
529 * @param array $params
530 * @return RCFeedEngine The engine object
531 * @throws MWException
532 */
533 public static function getEngine( $uri, $params = [] ) {
534 // TODO: Merge into RCFeed::factory().
535 global $wgRCEngines;
536 $scheme = parse_url( $uri, PHP_URL_SCHEME );
537 if ( !$scheme ) {
538 throw new MWException( "Invalid RCFeed uri: '$uri'" );
539 }
540 if ( !isset( $wgRCEngines[$scheme] ) ) {
541 throw new MWException( "Unknown RCFeedEngine scheme: '$scheme'" );
542 }
543 if ( defined( 'MW_PHPUNIT_TEST' ) && is_object( $wgRCEngines[$scheme] ) ) {
544 return $wgRCEngines[$scheme];
545 }
546 return new $wgRCEngines[$scheme]( $params );
547 }
548
549 /**
550 * Mark a given change as patrolled
551 *
552 * @param RecentChange|int $change RecentChange or corresponding rc_id
553 * @param bool $auto For automatic patrol
554 * @param string|string[]|null $tags Change tags to add to the patrol log entry
555 * ($user should be able to add the specified tags before this is called)
556 * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
557 */
558 public static function markPatrolled( $change, $auto = false, $tags = null ) {
559 global $wgUser;
560
561 $change = $change instanceof RecentChange
562 ? $change
563 : self::newFromId( $change );
564
565 if ( !$change instanceof RecentChange ) {
566 return null;
567 }
568
569 return $change->doMarkPatrolled( $wgUser, $auto, $tags );
570 }
571
572 /**
573 * Mark this RecentChange as patrolled
574 *
575 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
576 * 'markedaspatrollederror-noautopatrol' as errors
577 * @param User $user User object doing the action
578 * @param bool $auto For automatic patrol
579 * @param string|string[]|null $tags Change tags to add to the patrol log entry
580 * ($user should be able to add the specified tags before this is called)
581 * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
582 */
583 public function doMarkPatrolled( User $user, $auto = false, $tags = null ) {
584 global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol;
585
586 // Fix up $tags so that the MarkPatrolled hook below always gets an array
587 if ( $tags === null ) {
588 $tags = [];
589 } elseif ( is_string( $tags ) ) {
590 $tags = [ $tags ];
591 }
592
593 $errors = [];
594 // If recentchanges patrol is disabled, only new pages or new file versions
595 // can be patrolled, provided the appropriate config variable is set
596 if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol || $this->getAttribute( 'rc_type' ) != RC_NEW ) &&
597 ( !$wgUseFilePatrol || !( $this->getAttribute( 'rc_type' ) == RC_LOG &&
598 $this->getAttribute( 'rc_log_type' ) == 'upload' ) ) ) {
599 $errors[] = [ 'rcpatroldisabled' ];
600 }
601 // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
602 $right = $auto ? 'autopatrol' : 'patrol';
603 $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
604 if ( !Hooks::run( 'MarkPatrolled',
605 [ $this->getAttribute( 'rc_id' ), &$user, false, $auto, &$tags ] )
606 ) {
607 $errors[] = [ 'hookaborted' ];
608 }
609 // Users without the 'autopatrol' right can't patrol their
610 // own revisions
611 if ( $user->getName() === $this->getAttribute( 'rc_user_text' )
612 && !$user->isAllowed( 'autopatrol' )
613 ) {
614 $errors[] = [ 'markedaspatrollederror-noautopatrol' ];
615 }
616 if ( $errors ) {
617 return $errors;
618 }
619 // If the change was patrolled already, do nothing
620 if ( $this->getAttribute( 'rc_patrolled' ) ) {
621 return [];
622 }
623 // Actually set the 'patrolled' flag in RC
624 $this->reallyMarkPatrolled();
625 // Log this patrol event
626 PatrolLog::record( $this, $auto, $user, $tags );
627
628 Hooks::run(
629 'MarkPatrolledComplete',
630 [ $this->getAttribute( 'rc_id' ), &$user, false, $auto ]
631 );
632
633 return [];
634 }
635
636 /**
637 * Mark this RecentChange patrolled, without error checking
638 * @return int Number of affected rows
639 */
640 public function reallyMarkPatrolled() {
641 $dbw = wfGetDB( DB_MASTER );
642 $dbw->update(
643 'recentchanges',
644 [
645 'rc_patrolled' => self::PRC_PATROLLED
646 ],
647 [
648 'rc_id' => $this->getAttribute( 'rc_id' )
649 ],
650 __METHOD__
651 );
652 // Invalidate the page cache after the page has been patrolled
653 // to make sure that the Patrol link isn't visible any longer!
654 $this->getTitle()->invalidateCache();
655
656 return $dbw->affectedRows();
657 }
658
659 /**
660 * Makes an entry in the database corresponding to an edit
661 *
662 * @param string $timestamp
663 * @param Title $title
664 * @param bool $minor
665 * @param User $user
666 * @param string $comment
667 * @param int $oldId
668 * @param string $lastTimestamp
669 * @param bool $bot
670 * @param string $ip
671 * @param int $oldSize
672 * @param int $newSize
673 * @param int $newId
674 * @param int $patrol
675 * @param array $tags
676 * @return RecentChange
677 */
678 public static function notifyEdit(
679 $timestamp, $title, $minor, $user, $comment, $oldId, $lastTimestamp,
680 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0,
681 $tags = []
682 ) {
683 $rc = new RecentChange;
684 $rc->mTitle = $title;
685 $rc->mPerformer = $user;
686 $rc->mAttribs = [
687 'rc_timestamp' => $timestamp,
688 'rc_namespace' => $title->getNamespace(),
689 'rc_title' => $title->getDBkey(),
690 'rc_type' => RC_EDIT,
691 'rc_source' => self::SRC_EDIT,
692 'rc_minor' => $minor ? 1 : 0,
693 'rc_cur_id' => $title->getArticleID(),
694 'rc_user' => $user->getId(),
695 'rc_user_text' => $user->getName(),
696 'rc_actor' => $user->getActorId(),
697 'rc_comment' => &$comment,
698 'rc_comment_text' => &$comment,
699 'rc_comment_data' => null,
700 'rc_this_oldid' => $newId,
701 'rc_last_oldid' => $oldId,
702 'rc_bot' => $bot ? 1 : 0,
703 'rc_ip' => self::checkIPAddress( $ip ),
704 'rc_patrolled' => intval( $patrol ),
705 'rc_new' => 0, # obsolete
706 'rc_old_len' => $oldSize,
707 'rc_new_len' => $newSize,
708 'rc_deleted' => 0,
709 'rc_logid' => 0,
710 'rc_log_type' => null,
711 'rc_log_action' => '',
712 'rc_params' => ''
713 ];
714
715 $rc->mExtra = [
716 'prefixedDBkey' => $title->getPrefixedDBkey(),
717 'lastTimestamp' => $lastTimestamp,
718 'oldSize' => $oldSize,
719 'newSize' => $newSize,
720 'pageStatus' => 'changed'
721 ];
722
723 DeferredUpdates::addCallableUpdate(
724 function () use ( $rc, $tags ) {
725 $rc->addTags( $tags );
726 $rc->save();
727 },
728 DeferredUpdates::POSTSEND,
729 wfGetDB( DB_MASTER )
730 );
731
732 return $rc;
733 }
734
735 /**
736 * Makes an entry in the database corresponding to page creation
737 * Note: the title object must be loaded with the new id using resetArticleID()
738 *
739 * @param string $timestamp
740 * @param Title $title
741 * @param bool $minor
742 * @param User $user
743 * @param string $comment
744 * @param bool $bot
745 * @param string $ip
746 * @param int $size
747 * @param int $newId
748 * @param int $patrol
749 * @param array $tags
750 * @return RecentChange
751 */
752 public static function notifyNew(
753 $timestamp, $title, $minor, $user, $comment, $bot,
754 $ip = '', $size = 0, $newId = 0, $patrol = 0, $tags = []
755 ) {
756 $rc = new RecentChange;
757 $rc->mTitle = $title;
758 $rc->mPerformer = $user;
759 $rc->mAttribs = [
760 'rc_timestamp' => $timestamp,
761 'rc_namespace' => $title->getNamespace(),
762 'rc_title' => $title->getDBkey(),
763 'rc_type' => RC_NEW,
764 'rc_source' => self::SRC_NEW,
765 'rc_minor' => $minor ? 1 : 0,
766 'rc_cur_id' => $title->getArticleID(),
767 'rc_user' => $user->getId(),
768 'rc_user_text' => $user->getName(),
769 'rc_actor' => $user->getActorId(),
770 'rc_comment' => &$comment,
771 'rc_comment_text' => &$comment,
772 'rc_comment_data' => null,
773 'rc_this_oldid' => $newId,
774 'rc_last_oldid' => 0,
775 'rc_bot' => $bot ? 1 : 0,
776 'rc_ip' => self::checkIPAddress( $ip ),
777 'rc_patrolled' => intval( $patrol ),
778 'rc_new' => 1, # obsolete
779 'rc_old_len' => 0,
780 'rc_new_len' => $size,
781 'rc_deleted' => 0,
782 'rc_logid' => 0,
783 'rc_log_type' => null,
784 'rc_log_action' => '',
785 'rc_params' => ''
786 ];
787
788 $rc->mExtra = [
789 'prefixedDBkey' => $title->getPrefixedDBkey(),
790 'lastTimestamp' => 0,
791 'oldSize' => 0,
792 'newSize' => $size,
793 'pageStatus' => 'created'
794 ];
795
796 DeferredUpdates::addCallableUpdate(
797 function () use ( $rc, $tags ) {
798 $rc->addTags( $tags );
799 $rc->save();
800 },
801 DeferredUpdates::POSTSEND,
802 wfGetDB( DB_MASTER )
803 );
804
805 return $rc;
806 }
807
808 /**
809 * @param string $timestamp
810 * @param Title $title
811 * @param User $user
812 * @param string $actionComment
813 * @param string $ip
814 * @param string $type
815 * @param string $action
816 * @param Title $target
817 * @param string $logComment
818 * @param string $params
819 * @param int $newId
820 * @param string $actionCommentIRC
821 * @return bool
822 */
823 public static function notifyLog( $timestamp, $title, $user, $actionComment, $ip, $type,
824 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
825 ) {
826 global $wgLogRestrictions;
827
828 # Don't add private logs to RC!
829 if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
830 return false;
831 }
832 $rc = self::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
833 $target, $logComment, $params, $newId, $actionCommentIRC );
834 $rc->save();
835
836 return true;
837 }
838
839 /**
840 * @param string $timestamp
841 * @param Title $title
842 * @param User $user
843 * @param string $actionComment
844 * @param string $ip
845 * @param string $type
846 * @param string $action
847 * @param Title $target
848 * @param string $logComment
849 * @param string $params
850 * @param int $newId
851 * @param string $actionCommentIRC
852 * @param int $revId Id of associated revision, if any
853 * @param bool $isPatrollable Whether this log entry is patrollable
854 * @return RecentChange
855 */
856 public static function newLogEntry( $timestamp, $title, $user, $actionComment, $ip,
857 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '',
858 $revId = 0, $isPatrollable = false ) {
859 global $wgRequest;
860
861 # # Get pageStatus for email notification
862 switch ( $type . '-' . $action ) {
863 case 'delete-delete':
864 case 'delete-delete_redir':
865 $pageStatus = 'deleted';
866 break;
867 case 'move-move':
868 case 'move-move_redir':
869 $pageStatus = 'moved';
870 break;
871 case 'delete-restore':
872 $pageStatus = 'restored';
873 break;
874 case 'upload-upload':
875 $pageStatus = 'created';
876 break;
877 case 'upload-overwrite':
878 default:
879 $pageStatus = 'changed';
880 break;
881 }
882
883 // Allow unpatrolled status for patrollable log entries
884 $markPatrolled = $isPatrollable ? $user->isAllowed( 'autopatrol' ) : true;
885
886 $rc = new RecentChange;
887 $rc->mTitle = $target;
888 $rc->mPerformer = $user;
889 $rc->mAttribs = [
890 'rc_timestamp' => $timestamp,
891 'rc_namespace' => $target->getNamespace(),
892 'rc_title' => $target->getDBkey(),
893 'rc_type' => RC_LOG,
894 'rc_source' => self::SRC_LOG,
895 'rc_minor' => 0,
896 'rc_cur_id' => $target->getArticleID(),
897 'rc_user' => $user->getId(),
898 'rc_user_text' => $user->getName(),
899 'rc_actor' => $user->getActorId(),
900 'rc_comment' => &$logComment,
901 'rc_comment_text' => &$logComment,
902 'rc_comment_data' => null,
903 'rc_this_oldid' => $revId,
904 'rc_last_oldid' => 0,
905 'rc_bot' => $user->isAllowed( 'bot' ) ? (int)$wgRequest->getBool( 'bot', true ) : 0,
906 'rc_ip' => self::checkIPAddress( $ip ),
907 'rc_patrolled' => $markPatrolled ? self::PRC_AUTOPATROLLED : self::PRC_UNPATROLLED,
908 'rc_new' => 0, # obsolete
909 'rc_old_len' => null,
910 'rc_new_len' => null,
911 'rc_deleted' => 0,
912 'rc_logid' => $newId,
913 'rc_log_type' => $type,
914 'rc_log_action' => $action,
915 'rc_params' => $params
916 ];
917
918 $rc->mExtra = [
919 'prefixedDBkey' => $title->getPrefixedDBkey(),
920 'lastTimestamp' => 0,
921 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
922 'pageStatus' => $pageStatus,
923 'actionCommentIRC' => $actionCommentIRC
924 ];
925
926 return $rc;
927 }
928
929 /**
930 * Constructs a RecentChange object for the given categorization
931 * This does not call save() on the object and thus does not write to the db
932 *
933 * @since 1.27
934 *
935 * @param string $timestamp Timestamp of the recent change to occur
936 * @param Title $categoryTitle Title of the category a page is being added to or removed from
937 * @param User|null $user User object of the user that made the change
938 * @param string $comment Change summary
939 * @param Title $pageTitle Title of the page that is being added or removed
940 * @param int $oldRevId Parent revision ID of this change
941 * @param int $newRevId Revision ID of this change
942 * @param string $lastTimestamp Parent revision timestamp of this change
943 * @param bool $bot true, if the change was made by a bot
944 * @param string $ip IP address of the user, if the change was made anonymously
945 * @param int $deleted Indicates whether the change has been deleted
946 * @param bool|null $added true, if the category was added, false for removed
947 *
948 * @return RecentChange
949 */
950 public static function newForCategorization(
951 $timestamp,
952 Title $categoryTitle,
953 User $user = null,
954 $comment,
955 Title $pageTitle,
956 $oldRevId,
957 $newRevId,
958 $lastTimestamp,
959 $bot,
960 $ip = '',
961 $deleted = 0,
962 $added = null
963 ) {
964 // Done in a backwards compatible way.
965 $params = [
966 'hidden-cat' => WikiCategoryPage::factory( $categoryTitle )->isHidden()
967 ];
968 if ( $added !== null ) {
969 $params['added'] = $added;
970 }
971
972 $rc = new RecentChange;
973 $rc->mTitle = $categoryTitle;
974 $rc->mPerformer = $user;
975 $rc->mAttribs = [
976 'rc_timestamp' => $timestamp,
977 'rc_namespace' => $categoryTitle->getNamespace(),
978 'rc_title' => $categoryTitle->getDBkey(),
979 'rc_type' => RC_CATEGORIZE,
980 'rc_source' => self::SRC_CATEGORIZE,
981 'rc_minor' => 0,
982 'rc_cur_id' => $pageTitle->getArticleID(),
983 'rc_user' => $user ? $user->getId() : 0,
984 'rc_user_text' => $user ? $user->getName() : '',
985 'rc_actor' => $user ? $user->getActorId() : null,
986 'rc_comment' => &$comment,
987 'rc_comment_text' => &$comment,
988 'rc_comment_data' => null,
989 'rc_this_oldid' => $newRevId,
990 'rc_last_oldid' => $oldRevId,
991 'rc_bot' => $bot ? 1 : 0,
992 'rc_ip' => self::checkIPAddress( $ip ),
993 'rc_patrolled' => self::PRC_AUTOPATROLLED, // Always patrolled, just like log entries
994 'rc_new' => 0, # obsolete
995 'rc_old_len' => null,
996 'rc_new_len' => null,
997 'rc_deleted' => $deleted,
998 'rc_logid' => 0,
999 'rc_log_type' => null,
1000 'rc_log_action' => '',
1001 'rc_params' => serialize( $params )
1002 ];
1003
1004 $rc->mExtra = [
1005 'prefixedDBkey' => $categoryTitle->getPrefixedDBkey(),
1006 'lastTimestamp' => $lastTimestamp,
1007 'oldSize' => 0,
1008 'newSize' => 0,
1009 'pageStatus' => 'changed'
1010 ];
1011
1012 return $rc;
1013 }
1014
1015 /**
1016 * Get a parameter value
1017 *
1018 * @since 1.27
1019 *
1020 * @param string $name parameter name
1021 * @return mixed
1022 */
1023 public function getParam( $name ) {
1024 $params = $this->parseParams();
1025 return $params[$name] ?? null;
1026 }
1027
1028 /**
1029 * Initialises the members of this object from a mysql row object
1030 *
1031 * @param mixed $row
1032 */
1033 public function loadFromRow( $row ) {
1034 $this->mAttribs = get_object_vars( $row );
1035 $this->mAttribs['rc_timestamp'] = wfTimestamp( TS_MW, $this->mAttribs['rc_timestamp'] );
1036 // rc_deleted MUST be set
1037 $this->mAttribs['rc_deleted'] = $row->rc_deleted;
1038
1039 if ( isset( $this->mAttribs['rc_ip'] ) ) {
1040 // Clean up CIDRs for Postgres per T164898. ("127.0.0.1" casts to "127.0.0.1/32")
1041 $n = strpos( $this->mAttribs['rc_ip'], '/' );
1042 if ( $n !== false ) {
1043 $this->mAttribs['rc_ip'] = substr( $this->mAttribs['rc_ip'], 0, $n );
1044 }
1045 }
1046
1047 $comment = CommentStore::getStore()
1048 // Legacy because $row may have come from self::selectFields()
1049 ->getCommentLegacy( wfGetDB( DB_REPLICA ), 'rc_comment', $row, true )
1050 ->text;
1051 $this->mAttribs['rc_comment'] = &$comment;
1052 $this->mAttribs['rc_comment_text'] = &$comment;
1053 $this->mAttribs['rc_comment_data'] = null;
1054
1055 $user = User::newFromAnyId(
1056 $this->mAttribs['rc_user'] ?? null,
1057 $this->mAttribs['rc_user_text'] ?? null,
1058 $this->mAttribs['rc_actor'] ?? null
1059 );
1060 $this->mAttribs['rc_user'] = $user->getId();
1061 $this->mAttribs['rc_user_text'] = $user->getName();
1062 $this->mAttribs['rc_actor'] = $user->getActorId();
1063 }
1064
1065 /**
1066 * Get an attribute value
1067 *
1068 * @param string $name Attribute name
1069 * @return mixed
1070 */
1071 public function getAttribute( $name ) {
1072 if ( $name === 'rc_comment' ) {
1073 return CommentStore::getStore()
1074 ->getComment( 'rc_comment', $this->mAttribs, true )->text;
1075 }
1076
1077 if ( $name === 'rc_user' || $name === 'rc_user_text' || $name === 'rc_actor' ) {
1078 $user = User::newFromAnyId(
1079 $this->mAttribs['rc_user'] ?? null,
1080 $this->mAttribs['rc_user_text'] ?? null,
1081 $this->mAttribs['rc_actor'] ?? null
1082 );
1083 if ( $name === 'rc_user' ) {
1084 return $user->getId();
1085 }
1086 if ( $name === 'rc_user_text' ) {
1087 return $user->getName();
1088 }
1089 if ( $name === 'rc_actor' ) {
1090 return $user->getActorId();
1091 }
1092 }
1093
1094 return $this->mAttribs[$name] ?? null;
1095 }
1096
1097 /**
1098 * @return array
1099 */
1100 public function getAttributes() {
1101 return $this->mAttribs;
1102 }
1103
1104 /**
1105 * Gets the end part of the diff URL associated with this object
1106 * Blank if no diff link should be displayed
1107 * @param bool $forceCur
1108 * @return string
1109 */
1110 public function diffLinkTrail( $forceCur ) {
1111 if ( $this->mAttribs['rc_type'] == RC_EDIT ) {
1112 $trail = "curid=" . (int)( $this->mAttribs['rc_cur_id'] ) .
1113 "&oldid=" . (int)( $this->mAttribs['rc_last_oldid'] );
1114 if ( $forceCur ) {
1115 $trail .= '&diff=0';
1116 } else {
1117 $trail .= '&diff=' . (int)( $this->mAttribs['rc_this_oldid'] );
1118 }
1119 } else {
1120 $trail = '';
1121 }
1122
1123 return $trail;
1124 }
1125
1126 /**
1127 * Returns the change size (HTML).
1128 * The lengths can be given optionally.
1129 * @param int $old
1130 * @param int $new
1131 * @return string
1132 */
1133 public function getCharacterDifference( $old = 0, $new = 0 ) {
1134 if ( $old === 0 ) {
1135 $old = $this->mAttribs['rc_old_len'];
1136 }
1137 if ( $new === 0 ) {
1138 $new = $this->mAttribs['rc_new_len'];
1139 }
1140 if ( $old === null || $new === null ) {
1141 return '';
1142 }
1143
1144 return ChangesList::showCharacterDifference( $old, $new );
1145 }
1146
1147 private static function checkIPAddress( $ip ) {
1148 global $wgRequest;
1149 if ( $ip ) {
1150 if ( !IP::isIPAddress( $ip ) ) {
1151 throw new MWException( "Attempt to write \"" . $ip .
1152 "\" as an IP address into recent changes" );
1153 }
1154 } else {
1155 $ip = $wgRequest->getIP();
1156 if ( !$ip ) {
1157 $ip = '';
1158 }
1159 }
1160
1161 return $ip;
1162 }
1163
1164 /**
1165 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
1166 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
1167 * or rows which will be deleted soon shouldn't be included.
1168 *
1169 * @param mixed $timestamp MWTimestamp compatible timestamp
1170 * @param int $tolerance Tolerance in seconds
1171 * @return bool
1172 */
1173 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
1174 global $wgRCMaxAge;
1175
1176 return wfTimestamp( TS_UNIX, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
1177 }
1178
1179 /**
1180 * Parses and returns the rc_params attribute
1181 *
1182 * @since 1.26
1183 *
1184 * @return mixed|bool false on failed unserialization
1185 */
1186 public function parseParams() {
1187 $rcParams = $this->getAttribute( 'rc_params' );
1188
1189 Wikimedia\suppressWarnings();
1190 $unserializedParams = unserialize( $rcParams );
1191 Wikimedia\restoreWarnings();
1192
1193 return $unserializedParams;
1194 }
1195
1196 /**
1197 * Tags to append to the recent change,
1198 * and associated revision/log
1199 *
1200 * @since 1.28
1201 *
1202 * @param string|string[] $tags
1203 */
1204 public function addTags( $tags ) {
1205 if ( is_string( $tags ) ) {
1206 $this->tags[] = $tags;
1207 } else {
1208 $this->tags = array_merge( $tags, $this->tags );
1209 }
1210 }
1211 }