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