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