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