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