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