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