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