Merge "Use HTTP method as hint for the locking mode of sqlite"
[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 if ( is_string( $send ) ) {
373 // Callers used to pass undocumented strings like 'noudp'
374 // or 'pleasedontudp' instead of self::SEND_NONE (true).
375 // @deprecated since 1.31 Use SEND_NONE instead.
376 $send = self::SEND_NONE;
377 }
378
379 $dbw = wfGetDB( DB_MASTER );
380 if ( !is_array( $this->mExtra ) ) {
381 $this->mExtra = [];
382 }
383
384 if ( !$wgPutIPinRC ) {
385 $this->mAttribs['rc_ip'] = '';
386 }
387
388 # Strict mode fixups (not-NULL fields)
389 foreach ( [ 'minor', 'bot', 'new', 'patrolled', 'deleted' ] as $field ) {
390 $this->mAttribs["rc_$field"] = (int)$this->mAttribs["rc_$field"];
391 }
392 # ...more fixups (NULL fields)
393 foreach ( [ 'old_len', 'new_len' ] as $field ) {
394 $this->mAttribs["rc_$field"] = isset( $this->mAttribs["rc_$field"] )
395 ? (int)$this->mAttribs["rc_$field"]
396 : null;
397 }
398
399 # If our database is strict about IP addresses, use NULL instead of an empty string
400 $strictIPs = in_array( $dbw->getType(), [ 'oracle', 'postgres' ] ); // legacy
401 if ( $strictIPs && $this->mAttribs['rc_ip'] == '' ) {
402 unset( $this->mAttribs['rc_ip'] );
403 }
404
405 # Trim spaces on user supplied text
406 $this->mAttribs['rc_comment'] = trim( $this->mAttribs['rc_comment'] );
407
408 # Fixup database timestamps
409 $this->mAttribs['rc_timestamp'] = $dbw->timestamp( $this->mAttribs['rc_timestamp'] );
410
411 # # If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
412 if ( $this->mAttribs['rc_cur_id'] == 0 ) {
413 unset( $this->mAttribs['rc_cur_id'] );
414 }
415
416 $row = $this->mAttribs;
417
418 # Convert mAttribs['rc_comment'] for CommentStore
419 $comment = $row['rc_comment'];
420 unset( $row['rc_comment'], $row['rc_comment_text'], $row['rc_comment_data'] );
421 $row += CommentStore::getStore()->insert( $dbw, 'rc_comment', $comment );
422
423 # Convert mAttribs['rc_user'] etc for ActorMigration
424 $user = User::newFromAnyId(
425 $row['rc_user'] ?? null,
426 $row['rc_user_text'] ?? null,
427 $row['rc_actor'] ?? null
428 );
429 unset( $row['rc_user'], $row['rc_user_text'], $row['rc_actor'] );
430 $row += ActorMigration::newMigration()->getInsertValues( $dbw, 'rc_user', $user );
431
432 # Don't reuse an existing rc_id for the new row, if one happens to be
433 # set for some reason.
434 unset( $row['rc_id'] );
435
436 # Insert new row
437 $dbw->insert( 'recentchanges', $row, __METHOD__ );
438
439 # Set the ID
440 $this->mAttribs['rc_id'] = $dbw->insertId();
441
442 # Notify extensions
443 // Avoid PHP 7.1 warning from passing $this by reference
444 $rc = $this;
445 Hooks::run( 'RecentChange_save', [ &$rc ] );
446
447 if ( count( $this->tags ) ) {
448 ChangeTags::addTags( $this->tags, $this->mAttribs['rc_id'],
449 $this->mAttribs['rc_this_oldid'], $this->mAttribs['rc_logid'], null, $this );
450 }
451
452 if ( $send === self::SEND_FEED ) {
453 // Emit the change to external applications via RCFeeds.
454 $this->notifyRCFeeds();
455 }
456
457 # E-mail notifications
458 if ( $wgUseEnotif || $wgShowUpdatedMarker ) {
459 $editor = $this->getPerformer();
460 $title = $this->getTitle();
461
462 // Never send an RC notification email about categorization changes
463 if (
464 Hooks::run( 'AbortEmailNotification', [ $editor, $title, $this ] ) &&
465 $this->mAttribs['rc_type'] != RC_CATEGORIZE
466 ) {
467 // @FIXME: This would be better as an extension hook
468 // Send emails or email jobs once this row is safely committed
469 $dbw->onTransactionCommitOrIdle(
470 function () use ( $editor, $title ) {
471 $enotif = new EmailNotification();
472 $enotif->notifyOnPageChange(
473 $editor,
474 $title,
475 $this->mAttribs['rc_timestamp'],
476 $this->mAttribs['rc_comment'],
477 $this->mAttribs['rc_minor'],
478 $this->mAttribs['rc_last_oldid'],
479 $this->mExtra['pageStatus']
480 );
481 },
482 __METHOD__
483 );
484 }
485 }
486
487 // Update the cached list of active users
488 if ( $this->mAttribs['rc_user'] > 0 ) {
489 JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newCacheUpdateJob() );
490 }
491 }
492
493 /**
494 * Notify all the feeds about the change.
495 * @param array|null $feeds Optional feeds to send to, defaults to $wgRCFeeds
496 */
497 public function notifyRCFeeds( array $feeds = null ) {
498 global $wgRCFeeds;
499 if ( $feeds === null ) {
500 $feeds = $wgRCFeeds;
501 }
502
503 $performer = $this->getPerformer();
504
505 foreach ( $feeds as $params ) {
506 $params += [
507 'omit_bots' => false,
508 'omit_anon' => false,
509 'omit_user' => false,
510 'omit_minor' => false,
511 'omit_patrolled' => false,
512 ];
513
514 if (
515 ( $params['omit_bots'] && $this->mAttribs['rc_bot'] ) ||
516 ( $params['omit_anon'] && $performer->isAnon() ) ||
517 ( $params['omit_user'] && !$performer->isAnon() ) ||
518 ( $params['omit_minor'] && $this->mAttribs['rc_minor'] ) ||
519 ( $params['omit_patrolled'] && $this->mAttribs['rc_patrolled'] ) ||
520 $this->mAttribs['rc_type'] == RC_EXTERNAL
521 ) {
522 continue;
523 }
524
525 $actionComment = $this->mExtra['actionCommentIRC'] ?? null;
526
527 $feed = RCFeed::factory( $params );
528 $feed->notify( $this, $actionComment );
529 }
530 }
531
532 /**
533 * @since 1.22
534 * @deprecated since 1.29 Use RCFeed::factory() instead
535 * @param string $uri URI to get the engine object for
536 * @param array $params
537 * @return RCFeedEngine The engine object
538 * @throws MWException
539 */
540 public static function getEngine( $uri, $params = [] ) {
541 // TODO: Merge into RCFeed::factory().
542 global $wgRCEngines;
543 $scheme = parse_url( $uri, PHP_URL_SCHEME );
544 if ( !$scheme ) {
545 throw new MWException( "Invalid RCFeed uri: '$uri'" );
546 }
547 if ( !isset( $wgRCEngines[$scheme] ) ) {
548 throw new MWException( "Unknown RCFeedEngine scheme: '$scheme'" );
549 }
550 if ( defined( 'MW_PHPUNIT_TEST' ) && is_object( $wgRCEngines[$scheme] ) ) {
551 return $wgRCEngines[$scheme];
552 }
553 return new $wgRCEngines[$scheme]( $params );
554 }
555
556 /**
557 * Mark a given change as patrolled
558 *
559 * @param RecentChange|int $change RecentChange or corresponding rc_id
560 * @param bool $auto For automatic patrol
561 * @param string|string[]|null $tags Change tags to add to the patrol log entry
562 * ($user should be able to add the specified tags before this is called)
563 * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
564 */
565 public static function markPatrolled( $change, $auto = false, $tags = null ) {
566 global $wgUser;
567
568 $change = $change instanceof RecentChange
569 ? $change
570 : self::newFromId( $change );
571
572 if ( !$change instanceof RecentChange ) {
573 return null;
574 }
575
576 return $change->doMarkPatrolled( $wgUser, $auto, $tags );
577 }
578
579 /**
580 * Mark this RecentChange as patrolled
581 *
582 * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
583 * 'markedaspatrollederror-noautopatrol' as errors
584 * @param User $user User object doing the action
585 * @param bool $auto For automatic patrol
586 * @param string|string[]|null $tags Change tags to add to the patrol log entry
587 * ($user should be able to add the specified tags before this is called)
588 * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
589 */
590 public function doMarkPatrolled( User $user, $auto = false, $tags = null ) {
591 global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol;
592
593 // Fix up $tags so that the MarkPatrolled hook below always gets an array
594 if ( $tags === null ) {
595 $tags = [];
596 } elseif ( is_string( $tags ) ) {
597 $tags = [ $tags ];
598 }
599
600 $errors = [];
601 // If recentchanges patrol is disabled, only new pages or new file versions
602 // can be patrolled, provided the appropriate config variable is set
603 if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol || $this->getAttribute( 'rc_type' ) != RC_NEW ) &&
604 ( !$wgUseFilePatrol || !( $this->getAttribute( 'rc_type' ) == RC_LOG &&
605 $this->getAttribute( 'rc_log_type' ) == 'upload' ) ) ) {
606 $errors[] = [ 'rcpatroldisabled' ];
607 }
608 // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
609 $right = $auto ? 'autopatrol' : 'patrol';
610 $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
611 if ( !Hooks::run( 'MarkPatrolled',
612 [ $this->getAttribute( 'rc_id' ), &$user, false, $auto, &$tags ] )
613 ) {
614 $errors[] = [ 'hookaborted' ];
615 }
616 // Users without the 'autopatrol' right can't patrol their
617 // own revisions
618 if ( $user->getName() === $this->getAttribute( 'rc_user_text' )
619 && !$user->isAllowed( 'autopatrol' )
620 ) {
621 $errors[] = [ 'markedaspatrollederror-noautopatrol' ];
622 }
623 if ( $errors ) {
624 return $errors;
625 }
626 // If the change was patrolled already, do nothing
627 if ( $this->getAttribute( 'rc_patrolled' ) ) {
628 return [];
629 }
630 // Actually set the 'patrolled' flag in RC
631 $this->reallyMarkPatrolled();
632 // Log this patrol event
633 PatrolLog::record( $this, $auto, $user, $tags );
634
635 Hooks::run(
636 'MarkPatrolledComplete',
637 [ $this->getAttribute( 'rc_id' ), &$user, false, $auto ]
638 );
639
640 return [];
641 }
642
643 /**
644 * Mark this RecentChange patrolled, without error checking
645 * @return int Number of affected rows
646 */
647 public function reallyMarkPatrolled() {
648 $dbw = wfGetDB( DB_MASTER );
649 $dbw->update(
650 'recentchanges',
651 [
652 'rc_patrolled' => self::PRC_PATROLLED
653 ],
654 [
655 'rc_id' => $this->getAttribute( 'rc_id' )
656 ],
657 __METHOD__
658 );
659 // Invalidate the page cache after the page has been patrolled
660 // to make sure that the Patrol link isn't visible any longer!
661 $this->getTitle()->invalidateCache();
662
663 return $dbw->affectedRows();
664 }
665
666 /**
667 * Makes an entry in the database corresponding to an edit
668 *
669 * @param string $timestamp
670 * @param Title $title
671 * @param bool $minor
672 * @param User $user
673 * @param string $comment
674 * @param int $oldId
675 * @param string $lastTimestamp
676 * @param bool $bot
677 * @param string $ip
678 * @param int $oldSize
679 * @param int $newSize
680 * @param int $newId
681 * @param int $patrol
682 * @param array $tags
683 * @return RecentChange
684 */
685 public static function notifyEdit(
686 $timestamp, $title, $minor, $user, $comment, $oldId, $lastTimestamp,
687 $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0,
688 $tags = []
689 ) {
690 $rc = new RecentChange;
691 $rc->mTitle = $title;
692 $rc->mPerformer = $user;
693 $rc->mAttribs = [
694 'rc_timestamp' => $timestamp,
695 'rc_namespace' => $title->getNamespace(),
696 'rc_title' => $title->getDBkey(),
697 'rc_type' => RC_EDIT,
698 'rc_source' => self::SRC_EDIT,
699 'rc_minor' => $minor ? 1 : 0,
700 'rc_cur_id' => $title->getArticleID(),
701 'rc_user' => $user->getId(),
702 'rc_user_text' => $user->getName(),
703 'rc_actor' => $user->getActorId(),
704 'rc_comment' => &$comment,
705 'rc_comment_text' => &$comment,
706 'rc_comment_data' => null,
707 'rc_this_oldid' => $newId,
708 'rc_last_oldid' => $oldId,
709 'rc_bot' => $bot ? 1 : 0,
710 'rc_ip' => self::checkIPAddress( $ip ),
711 'rc_patrolled' => intval( $patrol ),
712 'rc_new' => 0, # obsolete
713 'rc_old_len' => $oldSize,
714 'rc_new_len' => $newSize,
715 'rc_deleted' => 0,
716 'rc_logid' => 0,
717 'rc_log_type' => null,
718 'rc_log_action' => '',
719 'rc_params' => ''
720 ];
721
722 $rc->mExtra = [
723 'prefixedDBkey' => $title->getPrefixedDBkey(),
724 'lastTimestamp' => $lastTimestamp,
725 'oldSize' => $oldSize,
726 'newSize' => $newSize,
727 'pageStatus' => 'changed'
728 ];
729
730 DeferredUpdates::addCallableUpdate(
731 function () use ( $rc, $tags ) {
732 $rc->addTags( $tags );
733 $rc->save();
734 },
735 DeferredUpdates::POSTSEND,
736 wfGetDB( DB_MASTER )
737 );
738
739 return $rc;
740 }
741
742 /**
743 * Makes an entry in the database corresponding to page creation
744 * Note: the title object must be loaded with the new id using resetArticleID()
745 *
746 * @param string $timestamp
747 * @param Title $title
748 * @param bool $minor
749 * @param User $user
750 * @param string $comment
751 * @param bool $bot
752 * @param string $ip
753 * @param int $size
754 * @param int $newId
755 * @param int $patrol
756 * @param array $tags
757 * @return RecentChange
758 */
759 public static function notifyNew(
760 $timestamp, $title, $minor, $user, $comment, $bot,
761 $ip = '', $size = 0, $newId = 0, $patrol = 0, $tags = []
762 ) {
763 $rc = new RecentChange;
764 $rc->mTitle = $title;
765 $rc->mPerformer = $user;
766 $rc->mAttribs = [
767 'rc_timestamp' => $timestamp,
768 'rc_namespace' => $title->getNamespace(),
769 'rc_title' => $title->getDBkey(),
770 'rc_type' => RC_NEW,
771 'rc_source' => self::SRC_NEW,
772 'rc_minor' => $minor ? 1 : 0,
773 'rc_cur_id' => $title->getArticleID(),
774 'rc_user' => $user->getId(),
775 'rc_user_text' => $user->getName(),
776 'rc_actor' => $user->getActorId(),
777 'rc_comment' => &$comment,
778 'rc_comment_text' => &$comment,
779 'rc_comment_data' => null,
780 'rc_this_oldid' => $newId,
781 'rc_last_oldid' => 0,
782 'rc_bot' => $bot ? 1 : 0,
783 'rc_ip' => self::checkIPAddress( $ip ),
784 'rc_patrolled' => intval( $patrol ),
785 'rc_new' => 1, # obsolete
786 'rc_old_len' => 0,
787 'rc_new_len' => $size,
788 'rc_deleted' => 0,
789 'rc_logid' => 0,
790 'rc_log_type' => null,
791 'rc_log_action' => '',
792 'rc_params' => ''
793 ];
794
795 $rc->mExtra = [
796 'prefixedDBkey' => $title->getPrefixedDBkey(),
797 'lastTimestamp' => 0,
798 'oldSize' => 0,
799 'newSize' => $size,
800 'pageStatus' => 'created'
801 ];
802
803 DeferredUpdates::addCallableUpdate(
804 function () use ( $rc, $tags ) {
805 $rc->addTags( $tags );
806 $rc->save();
807 },
808 DeferredUpdates::POSTSEND,
809 wfGetDB( DB_MASTER )
810 );
811
812 return $rc;
813 }
814
815 /**
816 * @param string $timestamp
817 * @param Title $title
818 * @param User $user
819 * @param string $actionComment
820 * @param string $ip
821 * @param string $type
822 * @param string $action
823 * @param Title $target
824 * @param string $logComment
825 * @param string $params
826 * @param int $newId
827 * @param string $actionCommentIRC
828 * @return bool
829 */
830 public static function notifyLog( $timestamp, $title, $user, $actionComment, $ip, $type,
831 $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
832 ) {
833 global $wgLogRestrictions;
834
835 # Don't add private logs to RC!
836 if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
837 return false;
838 }
839 $rc = self::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
840 $target, $logComment, $params, $newId, $actionCommentIRC );
841 $rc->save();
842
843 return true;
844 }
845
846 /**
847 * @param string $timestamp
848 * @param Title $title
849 * @param User $user
850 * @param string $actionComment
851 * @param string $ip
852 * @param string $type
853 * @param string $action
854 * @param Title $target
855 * @param string $logComment
856 * @param string $params
857 * @param int $newId
858 * @param string $actionCommentIRC
859 * @param int $revId Id of associated revision, if any
860 * @param bool $isPatrollable Whether this log entry is patrollable
861 * @return RecentChange
862 */
863 public static function newLogEntry( $timestamp, $title, $user, $actionComment, $ip,
864 $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '',
865 $revId = 0, $isPatrollable = false ) {
866 global $wgRequest;
867
868 # # Get pageStatus for email notification
869 switch ( $type . '-' . $action ) {
870 case 'delete-delete':
871 case 'delete-delete_redir':
872 $pageStatus = 'deleted';
873 break;
874 case 'move-move':
875 case 'move-move_redir':
876 $pageStatus = 'moved';
877 break;
878 case 'delete-restore':
879 $pageStatus = 'restored';
880 break;
881 case 'upload-upload':
882 $pageStatus = 'created';
883 break;
884 case 'upload-overwrite':
885 default:
886 $pageStatus = 'changed';
887 break;
888 }
889
890 // Allow unpatrolled status for patrollable log entries
891 $markPatrolled = $isPatrollable ? $user->isAllowed( 'autopatrol' ) : true;
892
893 $rc = new RecentChange;
894 $rc->mTitle = $target;
895 $rc->mPerformer = $user;
896 $rc->mAttribs = [
897 'rc_timestamp' => $timestamp,
898 'rc_namespace' => $target->getNamespace(),
899 'rc_title' => $target->getDBkey(),
900 'rc_type' => RC_LOG,
901 'rc_source' => self::SRC_LOG,
902 'rc_minor' => 0,
903 'rc_cur_id' => $target->getArticleID(),
904 'rc_user' => $user->getId(),
905 'rc_user_text' => $user->getName(),
906 'rc_actor' => $user->getActorId(),
907 'rc_comment' => &$logComment,
908 'rc_comment_text' => &$logComment,
909 'rc_comment_data' => null,
910 'rc_this_oldid' => $revId,
911 'rc_last_oldid' => 0,
912 'rc_bot' => $user->isAllowed( 'bot' ) ? (int)$wgRequest->getBool( 'bot', true ) : 0,
913 'rc_ip' => self::checkIPAddress( $ip ),
914 'rc_patrolled' => $markPatrolled ? self::PRC_AUTOPATROLLED : self::PRC_UNPATROLLED,
915 'rc_new' => 0, # obsolete
916 'rc_old_len' => null,
917 'rc_new_len' => null,
918 'rc_deleted' => 0,
919 'rc_logid' => $newId,
920 'rc_log_type' => $type,
921 'rc_log_action' => $action,
922 'rc_params' => $params
923 ];
924
925 $rc->mExtra = [
926 'prefixedDBkey' => $title->getPrefixedDBkey(),
927 'lastTimestamp' => 0,
928 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
929 'pageStatus' => $pageStatus,
930 'actionCommentIRC' => $actionCommentIRC
931 ];
932
933 return $rc;
934 }
935
936 /**
937 * Constructs a RecentChange object for the given categorization
938 * This does not call save() on the object and thus does not write to the db
939 *
940 * @since 1.27
941 *
942 * @param string $timestamp Timestamp of the recent change to occur
943 * @param Title $categoryTitle Title of the category a page is being added to or removed from
944 * @param User|null $user User object of the user that made the change
945 * @param string $comment Change summary
946 * @param Title $pageTitle Title of the page that is being added or removed
947 * @param int $oldRevId Parent revision ID of this change
948 * @param int $newRevId Revision ID of this change
949 * @param string $lastTimestamp Parent revision timestamp of this change
950 * @param bool $bot true, if the change was made by a bot
951 * @param string $ip IP address of the user, if the change was made anonymously
952 * @param int $deleted Indicates whether the change has been deleted
953 * @param bool|null $added true, if the category was added, false for removed
954 *
955 * @return RecentChange
956 */
957 public static function newForCategorization(
958 $timestamp,
959 Title $categoryTitle,
960 User $user = null,
961 $comment,
962 Title $pageTitle,
963 $oldRevId,
964 $newRevId,
965 $lastTimestamp,
966 $bot,
967 $ip = '',
968 $deleted = 0,
969 $added = null
970 ) {
971 // Done in a backwards compatible way.
972 $params = [
973 'hidden-cat' => WikiCategoryPage::factory( $categoryTitle )->isHidden()
974 ];
975 if ( $added !== null ) {
976 $params['added'] = $added;
977 }
978
979 $rc = new RecentChange;
980 $rc->mTitle = $categoryTitle;
981 $rc->mPerformer = $user;
982 $rc->mAttribs = [
983 'rc_timestamp' => $timestamp,
984 'rc_namespace' => $categoryTitle->getNamespace(),
985 'rc_title' => $categoryTitle->getDBkey(),
986 'rc_type' => RC_CATEGORIZE,
987 'rc_source' => self::SRC_CATEGORIZE,
988 'rc_minor' => 0,
989 'rc_cur_id' => $pageTitle->getArticleID(),
990 'rc_user' => $user ? $user->getId() : 0,
991 'rc_user_text' => $user ? $user->getName() : '',
992 'rc_actor' => $user ? $user->getActorId() : null,
993 'rc_comment' => &$comment,
994 'rc_comment_text' => &$comment,
995 'rc_comment_data' => null,
996 'rc_this_oldid' => $newRevId,
997 'rc_last_oldid' => $oldRevId,
998 'rc_bot' => $bot ? 1 : 0,
999 'rc_ip' => self::checkIPAddress( $ip ),
1000 'rc_patrolled' => self::PRC_AUTOPATROLLED, // Always patrolled, just like log entries
1001 'rc_new' => 0, # obsolete
1002 'rc_old_len' => null,
1003 'rc_new_len' => null,
1004 'rc_deleted' => $deleted,
1005 'rc_logid' => 0,
1006 'rc_log_type' => null,
1007 'rc_log_action' => '',
1008 'rc_params' => serialize( $params )
1009 ];
1010
1011 $rc->mExtra = [
1012 'prefixedDBkey' => $categoryTitle->getPrefixedDBkey(),
1013 'lastTimestamp' => $lastTimestamp,
1014 'oldSize' => 0,
1015 'newSize' => 0,
1016 'pageStatus' => 'changed'
1017 ];
1018
1019 return $rc;
1020 }
1021
1022 /**
1023 * Get a parameter value
1024 *
1025 * @since 1.27
1026 *
1027 * @param string $name parameter name
1028 * @return mixed
1029 */
1030 public function getParam( $name ) {
1031 $params = $this->parseParams();
1032 return $params[$name] ?? null;
1033 }
1034
1035 /**
1036 * Initialises the members of this object from a mysql row object
1037 *
1038 * @param mixed $row
1039 */
1040 public function loadFromRow( $row ) {
1041 $this->mAttribs = get_object_vars( $row );
1042 $this->mAttribs['rc_timestamp'] = wfTimestamp( TS_MW, $this->mAttribs['rc_timestamp'] );
1043 // rc_deleted MUST be set
1044 $this->mAttribs['rc_deleted'] = $row->rc_deleted;
1045
1046 if ( isset( $this->mAttribs['rc_ip'] ) ) {
1047 // Clean up CIDRs for Postgres per T164898. ("127.0.0.1" casts to "127.0.0.1/32")
1048 $n = strpos( $this->mAttribs['rc_ip'], '/' );
1049 if ( $n !== false ) {
1050 $this->mAttribs['rc_ip'] = substr( $this->mAttribs['rc_ip'], 0, $n );
1051 }
1052 }
1053
1054 $comment = CommentStore::getStore()
1055 // Legacy because $row may have come from self::selectFields()
1056 ->getCommentLegacy( wfGetDB( DB_REPLICA ), 'rc_comment', $row, true )
1057 ->text;
1058 $this->mAttribs['rc_comment'] = &$comment;
1059 $this->mAttribs['rc_comment_text'] = &$comment;
1060 $this->mAttribs['rc_comment_data'] = null;
1061
1062 $user = User::newFromAnyId(
1063 $this->mAttribs['rc_user'] ?? null,
1064 $this->mAttribs['rc_user_text'] ?? null,
1065 $this->mAttribs['rc_actor'] ?? null
1066 );
1067 $this->mAttribs['rc_user'] = $user->getId();
1068 $this->mAttribs['rc_user_text'] = $user->getName();
1069 $this->mAttribs['rc_actor'] = $user->getActorId();
1070 }
1071
1072 /**
1073 * Get an attribute value
1074 *
1075 * @param string $name Attribute name
1076 * @return mixed
1077 */
1078 public function getAttribute( $name ) {
1079 if ( $name === 'rc_comment' ) {
1080 return CommentStore::getStore()
1081 ->getComment( 'rc_comment', $this->mAttribs, true )->text;
1082 }
1083
1084 if ( $name === 'rc_user' || $name === 'rc_user_text' || $name === 'rc_actor' ) {
1085 $user = User::newFromAnyId(
1086 $this->mAttribs['rc_user'] ?? null,
1087 $this->mAttribs['rc_user_text'] ?? null,
1088 $this->mAttribs['rc_actor'] ?? null
1089 );
1090 if ( $name === 'rc_user' ) {
1091 return $user->getId();
1092 }
1093 if ( $name === 'rc_user_text' ) {
1094 return $user->getName();
1095 }
1096 if ( $name === 'rc_actor' ) {
1097 return $user->getActorId();
1098 }
1099 }
1100
1101 return $this->mAttribs[$name] ?? null;
1102 }
1103
1104 /**
1105 * @return array
1106 */
1107 public function getAttributes() {
1108 return $this->mAttribs;
1109 }
1110
1111 /**
1112 * Gets the end part of the diff URL associated with this object
1113 * Blank if no diff link should be displayed
1114 * @param bool $forceCur
1115 * @return string
1116 */
1117 public function diffLinkTrail( $forceCur ) {
1118 if ( $this->mAttribs['rc_type'] == RC_EDIT ) {
1119 $trail = "curid=" . (int)( $this->mAttribs['rc_cur_id'] ) .
1120 "&oldid=" . (int)( $this->mAttribs['rc_last_oldid'] );
1121 if ( $forceCur ) {
1122 $trail .= '&diff=0';
1123 } else {
1124 $trail .= '&diff=' . (int)( $this->mAttribs['rc_this_oldid'] );
1125 }
1126 } else {
1127 $trail = '';
1128 }
1129
1130 return $trail;
1131 }
1132
1133 /**
1134 * Returns the change size (HTML).
1135 * The lengths can be given optionally.
1136 * @param int $old
1137 * @param int $new
1138 * @return string
1139 */
1140 public function getCharacterDifference( $old = 0, $new = 0 ) {
1141 if ( $old === 0 ) {
1142 $old = $this->mAttribs['rc_old_len'];
1143 }
1144 if ( $new === 0 ) {
1145 $new = $this->mAttribs['rc_new_len'];
1146 }
1147 if ( $old === null || $new === null ) {
1148 return '';
1149 }
1150
1151 return ChangesList::showCharacterDifference( $old, $new );
1152 }
1153
1154 private static function checkIPAddress( $ip ) {
1155 global $wgRequest;
1156 if ( $ip ) {
1157 if ( !IP::isIPAddress( $ip ) ) {
1158 throw new MWException( "Attempt to write \"" . $ip .
1159 "\" as an IP address into recent changes" );
1160 }
1161 } else {
1162 $ip = $wgRequest->getIP();
1163 if ( !$ip ) {
1164 $ip = '';
1165 }
1166 }
1167
1168 return $ip;
1169 }
1170
1171 /**
1172 * Check whether the given timestamp is new enough to have a RC row with a given tolerance
1173 * as the recentchanges table might not be cleared out regularly (so older entries might exist)
1174 * or rows which will be deleted soon shouldn't be included.
1175 *
1176 * @param mixed $timestamp MWTimestamp compatible timestamp
1177 * @param int $tolerance Tolerance in seconds
1178 * @return bool
1179 */
1180 public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
1181 global $wgRCMaxAge;
1182
1183 return wfTimestamp( TS_UNIX, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
1184 }
1185
1186 /**
1187 * Parses and returns the rc_params attribute
1188 *
1189 * @since 1.26
1190 *
1191 * @return mixed|bool false on failed unserialization
1192 */
1193 public function parseParams() {
1194 $rcParams = $this->getAttribute( 'rc_params' );
1195
1196 Wikimedia\suppressWarnings();
1197 $unserializedParams = unserialize( $rcParams );
1198 Wikimedia\restoreWarnings();
1199
1200 return $unserializedParams;
1201 }
1202
1203 /**
1204 * Tags to append to the recent change,
1205 * and associated revision/log
1206 *
1207 * @since 1.28
1208 *
1209 * @param string|string[] $tags
1210 */
1211 public function addTags( $tags ) {
1212 if ( is_string( $tags ) ) {
1213 $this->tags[] = $tags;
1214 } else {
1215 $this->tags = array_merge( $tags, $this->tags );
1216 }
1217 }
1218 }