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