Merge "Fix ParserOutput::getText 'unwrap' flag for end-of-doc comment"
[lhc/web/wiklou.git] / includes / logging / LogEntry.php
1 <?php
2 /**
3 * Contain classes for dealing with individual log entries
4 *
5 * This is how I see the log system history:
6 * - appending to plain wiki pages
7 * - formatting log entries based on database fields
8 * - user is now part of the action message
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @file
26 * @author Niklas Laxström
27 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
28 * @since 1.19
29 */
30
31 use Wikimedia\Rdbms\IDatabase;
32
33 /**
34 * Interface for log entries. Every log entry has these methods.
35 *
36 * @since 1.19
37 */
38 interface LogEntry {
39
40 /**
41 * The main log type.
42 *
43 * @return string
44 */
45 public function getType();
46
47 /**
48 * The log subtype.
49 *
50 * @return string
51 */
52 public function getSubtype();
53
54 /**
55 * The full logtype in format maintype/subtype.
56 *
57 * @return string
58 */
59 public function getFullType();
60
61 /**
62 * Get the extra parameters stored for this message.
63 *
64 * @return array
65 */
66 public function getParameters();
67
68 /**
69 * Get the user for performed this action.
70 *
71 * @return User
72 */
73 public function getPerformer();
74
75 /**
76 * Get the target page of this action.
77 *
78 * @return Title
79 */
80 public function getTarget();
81
82 /**
83 * Get the timestamp when the action was executed.
84 *
85 * @return string
86 */
87 public function getTimestamp();
88
89 /**
90 * Get the user provided comment.
91 *
92 * @return string
93 */
94 public function getComment();
95
96 /**
97 * Get the access restriction.
98 *
99 * @return string
100 */
101 public function getDeleted();
102
103 /**
104 * @param int $field One of LogPage::DELETED_* bitfield constants
105 * @return bool
106 */
107 public function isDeleted( $field );
108 }
109
110 /**
111 * Extends the LogEntryInterface with some basic functionality
112 *
113 * @since 1.19
114 */
115 abstract class LogEntryBase implements LogEntry {
116
117 public function getFullType() {
118 return $this->getType() . '/' . $this->getSubtype();
119 }
120
121 public function isDeleted( $field ) {
122 return ( $this->getDeleted() & $field ) === $field;
123 }
124
125 /**
126 * Whether the parameters for this log are stored in new or
127 * old format.
128 *
129 * @return bool
130 */
131 public function isLegacy() {
132 return false;
133 }
134
135 /**
136 * Create a blob from a parameter array
137 *
138 * @since 1.26
139 * @param array $params
140 * @return string
141 */
142 public static function makeParamBlob( $params ) {
143 return serialize( (array)$params );
144 }
145
146 /**
147 * Extract a parameter array from a blob
148 *
149 * @since 1.26
150 * @param string $blob
151 * @return array
152 */
153 public static function extractParams( $blob ) {
154 return unserialize( $blob );
155 }
156 }
157
158 /**
159 * This class wraps around database result row.
160 *
161 * @since 1.19
162 */
163 class DatabaseLogEntry extends LogEntryBase {
164
165 /**
166 * Returns array of information that is needed for querying
167 * log entries. Array contains the following keys:
168 * tables, fields, conds, options and join_conds
169 *
170 * @return array
171 */
172 public static function getSelectQueryData() {
173 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
174
175 $tables = [ 'logging', 'user' ] + $commentQuery['tables'];
176 $fields = [
177 'log_id', 'log_type', 'log_action', 'log_timestamp',
178 'log_user', 'log_user_text',
179 'log_namespace', 'log_title', // unused log_page
180 'log_params', 'log_deleted',
181 'user_id', 'user_name', 'user_editcount',
182 ] + $commentQuery['fields'];
183
184 $joins = [
185 // IPs don't have an entry in user table
186 'user' => [ 'LEFT JOIN', 'log_user=user_id' ],
187 ] + $commentQuery['joins'];
188
189 return [
190 'tables' => $tables,
191 'fields' => $fields,
192 'conds' => [],
193 'options' => [],
194 'join_conds' => $joins,
195 ];
196 }
197
198 /**
199 * Constructs new LogEntry from database result row.
200 * Supports rows from both logging and recentchanges table.
201 *
202 * @param stdClass|array $row
203 * @return DatabaseLogEntry
204 */
205 public static function newFromRow( $row ) {
206 $row = (object)$row;
207 if ( isset( $row->rc_logid ) ) {
208 return new RCDatabaseLogEntry( $row );
209 } else {
210 return new self( $row );
211 }
212 }
213
214 /** @var stdClass Database result row. */
215 protected $row;
216
217 /** @var User */
218 protected $performer;
219
220 /** @var array Parameters for log entry */
221 protected $params;
222
223 /** @var int A rev id associated to the log entry */
224 protected $revId = null;
225
226 /** @var bool Whether the parameters for this log entry are stored in new or old format. */
227 protected $legacy;
228
229 protected function __construct( $row ) {
230 $this->row = $row;
231 }
232
233 /**
234 * Returns the unique database id.
235 *
236 * @return int
237 */
238 public function getId() {
239 return (int)$this->row->log_id;
240 }
241
242 /**
243 * Returns whatever is stored in the database field.
244 *
245 * @return string
246 */
247 protected function getRawParameters() {
248 return $this->row->log_params;
249 }
250
251 public function isLegacy() {
252 // This extracts the property
253 $this->getParameters();
254 return $this->legacy;
255 }
256
257 public function getType() {
258 return $this->row->log_type;
259 }
260
261 public function getSubtype() {
262 return $this->row->log_action;
263 }
264
265 public function getParameters() {
266 if ( !isset( $this->params ) ) {
267 $blob = $this->getRawParameters();
268 MediaWiki\suppressWarnings();
269 $params = LogEntryBase::extractParams( $blob );
270 MediaWiki\restoreWarnings();
271 if ( $params !== false ) {
272 $this->params = $params;
273 $this->legacy = false;
274 } else {
275 $this->params = LogPage::extractParams( $blob );
276 $this->legacy = true;
277 }
278
279 if ( isset( $this->params['associated_rev_id'] ) ) {
280 $this->revId = $this->params['associated_rev_id'];
281 unset( $this->params['associated_rev_id'] );
282 }
283 }
284
285 return $this->params;
286 }
287
288 public function getAssociatedRevId() {
289 // This extracts the property
290 $this->getParameters();
291 return $this->revId;
292 }
293
294 public function getPerformer() {
295 if ( !$this->performer ) {
296 $userId = (int)$this->row->log_user;
297 if ( $userId !== 0 ) {
298 // logged-in users
299 if ( isset( $this->row->user_name ) ) {
300 $this->performer = User::newFromRow( $this->row );
301 } else {
302 $this->performer = User::newFromId( $userId );
303 }
304 } else {
305 // IP users
306 $userText = $this->row->log_user_text;
307 $this->performer = User::newFromName( $userText, false );
308 }
309 }
310
311 return $this->performer;
312 }
313
314 public function getTarget() {
315 $namespace = $this->row->log_namespace;
316 $page = $this->row->log_title;
317 $title = Title::makeTitle( $namespace, $page );
318
319 return $title;
320 }
321
322 public function getTimestamp() {
323 return wfTimestamp( TS_MW, $this->row->log_timestamp );
324 }
325
326 public function getComment() {
327 return CommentStore::getStore()->getComment( 'log_comment', $this->row )->text;
328 }
329
330 public function getDeleted() {
331 return $this->row->log_deleted;
332 }
333 }
334
335 class RCDatabaseLogEntry extends DatabaseLogEntry {
336
337 public function getId() {
338 return $this->row->rc_logid;
339 }
340
341 protected function getRawParameters() {
342 return $this->row->rc_params;
343 }
344
345 public function getAssociatedRevId() {
346 return $this->row->rc_this_oldid;
347 }
348
349 public function getType() {
350 return $this->row->rc_log_type;
351 }
352
353 public function getSubtype() {
354 return $this->row->rc_log_action;
355 }
356
357 public function getPerformer() {
358 if ( !$this->performer ) {
359 $userId = (int)$this->row->rc_user;
360 if ( $userId !== 0 ) {
361 $this->performer = User::newFromId( $userId );
362 } else {
363 $userText = $this->row->rc_user_text;
364 // Might be an IP, don't validate the username
365 $this->performer = User::newFromName( $userText, false );
366 }
367 }
368
369 return $this->performer;
370 }
371
372 public function getTarget() {
373 $namespace = $this->row->rc_namespace;
374 $page = $this->row->rc_title;
375 $title = Title::makeTitle( $namespace, $page );
376
377 return $title;
378 }
379
380 public function getTimestamp() {
381 return wfTimestamp( TS_MW, $this->row->rc_timestamp );
382 }
383
384 public function getComment() {
385 return CommentStore::getStore()
386 // Legacy because the row may have used RecentChange::selectFields()
387 ->getCommentLegacy( wfGetDB( DB_REPLICA ), 'rc_comment', $this->row )->text;
388 }
389
390 public function getDeleted() {
391 return $this->row->rc_deleted;
392 }
393 }
394
395 /**
396 * Class for creating log entries manually, to inject them into the database.
397 *
398 * @since 1.19
399 */
400 class ManualLogEntry extends LogEntryBase {
401 /** @var string Type of log entry */
402 protected $type;
403
404 /** @var string Sub type of log entry */
405 protected $subtype;
406
407 /** @var array Parameters for log entry */
408 protected $parameters = [];
409
410 /** @var array */
411 protected $relations = [];
412
413 /** @var User Performer of the action for the log entry */
414 protected $performer;
415
416 /** @var Title Target title for the log entry */
417 protected $target;
418
419 /** @var string Timestamp of creation of the log entry */
420 protected $timestamp;
421
422 /** @var string Comment for the log entry */
423 protected $comment = '';
424
425 /** @var int A rev id associated to the log entry */
426 protected $revId = 0;
427
428 /** @var array Change tags add to the log entry */
429 protected $tags = null;
430
431 /** @var int Deletion state of the log entry */
432 protected $deleted;
433
434 /** @var int ID of the log entry */
435 protected $id;
436
437 /** @var bool Can this log entry be patrolled? */
438 protected $isPatrollable = false;
439
440 /** @var bool Whether this is a legacy log entry */
441 protected $legacy = false;
442
443 /**
444 * @since 1.19
445 * @param string $type
446 * @param string $subtype
447 */
448 public function __construct( $type, $subtype ) {
449 $this->type = $type;
450 $this->subtype = $subtype;
451 }
452
453 /**
454 * Set extra log parameters.
455 *
456 * You can pass params to the log action message by prefixing the keys with
457 * a number and optional type, using colons to separate the fields. The
458 * numbering should start with number 4, the first three parameters are
459 * hardcoded for every message.
460 *
461 * If you want to store stuff that should not be available in messages, don't
462 * prefix the array key with a number and don't use the colons.
463 *
464 * Example:
465 * $entry->setParameters(
466 * '4::color' => 'blue',
467 * '5:number:count' => 3000,
468 * 'animal' => 'dog'
469 * );
470 *
471 * @since 1.19
472 * @param array $parameters Associative array
473 */
474 public function setParameters( $parameters ) {
475 $this->parameters = $parameters;
476 }
477
478 /**
479 * Declare arbitrary tag/value relations to this log entry.
480 * These can be used to filter log entries later on.
481 *
482 * @param array $relations Map of (tag => (list of values|value))
483 * @since 1.22
484 */
485 public function setRelations( array $relations ) {
486 $this->relations = $relations;
487 }
488
489 /**
490 * Set the user that performed the action being logged.
491 *
492 * @since 1.19
493 * @param User $performer
494 */
495 public function setPerformer( User $performer ) {
496 $this->performer = $performer;
497 }
498
499 /**
500 * Set the title of the object changed.
501 *
502 * @since 1.19
503 * @param Title $target
504 */
505 public function setTarget( Title $target ) {
506 $this->target = $target;
507 }
508
509 /**
510 * Set the timestamp of when the logged action took place.
511 *
512 * @since 1.19
513 * @param string $timestamp
514 */
515 public function setTimestamp( $timestamp ) {
516 $this->timestamp = $timestamp;
517 }
518
519 /**
520 * Set a comment associated with the action being logged.
521 *
522 * @since 1.19
523 * @param string $comment
524 */
525 public function setComment( $comment ) {
526 $this->comment = $comment;
527 }
528
529 /**
530 * Set an associated revision id.
531 *
532 * For example, the ID of the revision that was inserted to mark a page move
533 * or protection, file upload, etc.
534 *
535 * @since 1.27
536 * @param int $revId
537 */
538 public function setAssociatedRevId( $revId ) {
539 $this->revId = $revId;
540 }
541
542 /**
543 * Set change tags for the log entry.
544 *
545 * @since 1.27
546 * @param string|string[] $tags
547 */
548 public function setTags( $tags ) {
549 if ( is_string( $tags ) ) {
550 $tags = [ $tags ];
551 }
552 $this->tags = $tags;
553 }
554
555 /**
556 * Set whether this log entry should be made patrollable
557 * This shouldn't depend on config, only on whether there is full support
558 * in the software for patrolling this log entry.
559 * False by default
560 *
561 * @since 1.27
562 * @param bool $patrollable
563 */
564 public function setIsPatrollable( $patrollable ) {
565 $this->isPatrollable = (bool)$patrollable;
566 }
567
568 /**
569 * Set the 'legacy' flag
570 *
571 * @since 1.25
572 * @param bool $legacy
573 */
574 public function setLegacy( $legacy ) {
575 $this->legacy = $legacy;
576 }
577
578 /**
579 * Set the 'deleted' flag.
580 *
581 * @since 1.19
582 * @param int $deleted One of LogPage::DELETED_* bitfield constants
583 */
584 public function setDeleted( $deleted ) {
585 $this->deleted = $deleted;
586 }
587
588 /**
589 * Insert the entry into the `logging` table.
590 *
591 * @param IDatabase $dbw
592 * @return int ID of the log entry
593 * @throws MWException
594 */
595 public function insert( IDatabase $dbw = null ) {
596 $dbw = $dbw ?: wfGetDB( DB_MASTER );
597
598 if ( $this->timestamp === null ) {
599 $this->timestamp = wfTimestampNow();
600 }
601
602 // Trim spaces on user supplied text
603 $comment = trim( $this->getComment() );
604
605 $params = $this->getParameters();
606 $relations = $this->relations;
607
608 // Additional fields for which there's no space in the database table schema
609 $revId = $this->getAssociatedRevId();
610 if ( $revId ) {
611 $params['associated_rev_id'] = $revId;
612 $relations['associated_rev_id'] = $revId;
613 }
614
615 $data = [
616 'log_type' => $this->getType(),
617 'log_action' => $this->getSubtype(),
618 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
619 'log_user' => $this->getPerformer()->getId(),
620 'log_user_text' => $this->getPerformer()->getName(),
621 'log_namespace' => $this->getTarget()->getNamespace(),
622 'log_title' => $this->getTarget()->getDBkey(),
623 'log_page' => $this->getTarget()->getArticleID(),
624 'log_params' => LogEntryBase::makeParamBlob( $params ),
625 ];
626 if ( isset( $this->deleted ) ) {
627 $data['log_deleted'] = $this->deleted;
628 }
629 $data += CommentStore::getStore()->insert( $dbw, 'log_comment', $comment );
630
631 $dbw->insert( 'logging', $data, __METHOD__ );
632 $this->id = $dbw->insertId();
633
634 $rows = [];
635 foreach ( $relations as $tag => $values ) {
636 if ( !strlen( $tag ) ) {
637 throw new MWException( "Got empty log search tag." );
638 }
639
640 if ( !is_array( $values ) ) {
641 $values = [ $values ];
642 }
643
644 foreach ( $values as $value ) {
645 $rows[] = [
646 'ls_field' => $tag,
647 'ls_value' => $value,
648 'ls_log_id' => $this->id
649 ];
650 }
651 }
652 if ( count( $rows ) ) {
653 $dbw->insert( 'log_search', $rows, __METHOD__, 'IGNORE' );
654 }
655
656 return $this->id;
657 }
658
659 /**
660 * Get a RecentChanges object for the log entry
661 *
662 * @param int $newId
663 * @return RecentChange
664 * @since 1.23
665 */
666 public function getRecentChange( $newId = 0 ) {
667 $formatter = LogFormatter::newFromEntry( $this );
668 $context = RequestContext::newExtraneousContext( $this->getTarget() );
669 $formatter->setContext( $context );
670
671 $logpage = SpecialPage::getTitleFor( 'Log', $this->getType() );
672 $user = $this->getPerformer();
673 $ip = "";
674 if ( $user->isAnon() ) {
675 // "MediaWiki default" and friends may have
676 // no IP address in their name
677 if ( IP::isIPAddress( $user->getName() ) ) {
678 $ip = $user->getName();
679 }
680 }
681
682 return RecentChange::newLogEntry(
683 $this->getTimestamp(),
684 $logpage,
685 $user,
686 $formatter->getPlainActionText(),
687 $ip,
688 $this->getType(),
689 $this->getSubtype(),
690 $this->getTarget(),
691 $this->getComment(),
692 LogEntryBase::makeParamBlob( $this->getParameters() ),
693 $newId,
694 $formatter->getIRCActionComment(), // Used for IRC feeds
695 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
696 $this->getIsPatrollable()
697 );
698 }
699
700 /**
701 * Publish the log entry.
702 *
703 * @param int $newId Id of the log entry.
704 * @param string $to One of: rcandudp (default), rc, udp
705 */
706 public function publish( $newId, $to = 'rcandudp' ) {
707 DeferredUpdates::addCallableUpdate(
708 function () use ( $newId, $to ) {
709 $log = new LogPage( $this->getType() );
710 if ( !$log->isRestricted() ) {
711 $rc = $this->getRecentChange( $newId );
712
713 if ( $to === 'rc' || $to === 'rcandudp' ) {
714 // save RC, passing tags so they are applied there
715 $tags = $this->getTags();
716 if ( is_null( $tags ) ) {
717 $tags = [];
718 }
719 $rc->addTags( $tags );
720 $rc->save( 'pleasedontudp' );
721 }
722
723 if ( $to === 'udp' || $to === 'rcandudp' ) {
724 $rc->notifyRCFeeds();
725 }
726
727 // Log the autopatrol if the log entry is patrollable
728 if ( $this->getIsPatrollable() &&
729 $rc->getAttribute( 'rc_patrolled' ) === 1
730 ) {
731 PatrolLog::record( $rc, true, $this->getPerformer() );
732 }
733 }
734 },
735 DeferredUpdates::POSTSEND,
736 wfGetDB( DB_MASTER )
737 );
738 }
739
740 public function getType() {
741 return $this->type;
742 }
743
744 public function getSubtype() {
745 return $this->subtype;
746 }
747
748 public function getParameters() {
749 return $this->parameters;
750 }
751
752 /**
753 * @return User
754 */
755 public function getPerformer() {
756 return $this->performer;
757 }
758
759 /**
760 * @return Title
761 */
762 public function getTarget() {
763 return $this->target;
764 }
765
766 public function getTimestamp() {
767 $ts = $this->timestamp !== null ? $this->timestamp : wfTimestampNow();
768
769 return wfTimestamp( TS_MW, $ts );
770 }
771
772 public function getComment() {
773 return $this->comment;
774 }
775
776 /**
777 * @since 1.27
778 * @return int
779 */
780 public function getAssociatedRevId() {
781 return $this->revId;
782 }
783
784 /**
785 * @since 1.27
786 * @return array
787 */
788 public function getTags() {
789 return $this->tags;
790 }
791
792 /**
793 * Whether this log entry is patrollable
794 *
795 * @since 1.27
796 * @return bool
797 */
798 public function getIsPatrollable() {
799 return $this->isPatrollable;
800 }
801
802 /**
803 * @since 1.25
804 * @return bool
805 */
806 public function isLegacy() {
807 return $this->legacy;
808 }
809
810 public function getDeleted() {
811 return (int)$this->deleted;
812 }
813 }