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