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