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