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