Split logging classes to individual files
[lhc/web/wiklou.git] / includes / logging / ManualLogEntry.php
1 <?php
2 /**
3 * Contains a class for dealing with manual log 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 * @author Niklas Laxström
22 * @license GPL-2.0-or-later
23 * @since 1.19
24 */
25
26 use MediaWiki\ChangeTags\Taggable;
27 use MediaWiki\Linker\LinkTarget;
28 use MediaWiki\User\UserIdentity;
29 use Wikimedia\Rdbms\IDatabase;
30 use Wikimedia\Assert\Assert;
31
32 /**
33 * Class for creating new log entries and inserting them into the database.
34 *
35 * @since 1.19
36 */
37 class ManualLogEntry extends LogEntryBase implements Taggable {
38 /** @var string Type of log entry */
39 protected $type;
40
41 /** @var string Sub type of log entry */
42 protected $subtype;
43
44 /** @var array Parameters for log entry */
45 protected $parameters = [];
46
47 /** @var array */
48 protected $relations = [];
49
50 /** @var User Performer of the action for the log entry */
51 protected $performer;
52
53 /** @var Title Target title for the log entry */
54 protected $target;
55
56 /** @var string Timestamp of creation of the log entry */
57 protected $timestamp;
58
59 /** @var string Comment for the log entry */
60 protected $comment = '';
61
62 /** @var int A rev id associated to the log entry */
63 protected $revId = 0;
64
65 /** @var string[] Change tags add to the log entry */
66 protected $tags = [];
67
68 /** @var int Deletion state of the log entry */
69 protected $deleted;
70
71 /** @var int ID of the log entry */
72 protected $id;
73
74 /** @var bool Can this log entry be patrolled? */
75 protected $isPatrollable = false;
76
77 /** @var bool Whether this is a legacy log entry */
78 protected $legacy = false;
79
80 /**
81 * @since 1.19
82 * @param string $type
83 * @param string $subtype
84 */
85 public function __construct( $type, $subtype ) {
86 $this->type = $type;
87 $this->subtype = $subtype;
88 }
89
90 /**
91 * Set extra log parameters.
92 *
93 * You can pass params to the log action message by prefixing the keys with
94 * a number and optional type, using colons to separate the fields. The
95 * numbering should start with number 4, the first three parameters are
96 * hardcoded for every message.
97 *
98 * If you want to store stuff that should not be available in messages, don't
99 * prefix the array key with a number and don't use the colons.
100 *
101 * Example:
102 * $entry->setParameters(
103 * '4::color' => 'blue',
104 * '5:number:count' => 3000,
105 * 'animal' => 'dog'
106 * );
107 *
108 * @since 1.19
109 * @param array $parameters Associative array
110 */
111 public function setParameters( $parameters ) {
112 $this->parameters = $parameters;
113 }
114
115 /**
116 * Declare arbitrary tag/value relations to this log entry.
117 * These can be used to filter log entries later on.
118 *
119 * @param array $relations Map of (tag => (list of values|value))
120 * @since 1.22
121 */
122 public function setRelations( array $relations ) {
123 $this->relations = $relations;
124 }
125
126 /**
127 * Set the user that performed the action being logged.
128 *
129 * @since 1.19
130 * @param UserIdentity $performer
131 */
132 public function setPerformer( UserIdentity $performer ) {
133 $this->performer = User::newFromIdentity( $performer );
134 }
135
136 /**
137 * Set the title of the object changed.
138 *
139 * @since 1.19
140 * @param LinkTarget $target
141 */
142 public function setTarget( LinkTarget $target ) {
143 $this->target = Title::newFromLinkTarget( $target );
144 }
145
146 /**
147 * Set the timestamp of when the logged action took place.
148 *
149 * @since 1.19
150 * @param string $timestamp
151 */
152 public function setTimestamp( $timestamp ) {
153 $this->timestamp = $timestamp;
154 }
155
156 /**
157 * Set a comment associated with the action being logged.
158 *
159 * @since 1.19
160 * @param string $comment
161 */
162 public function setComment( $comment ) {
163 $this->comment = $comment;
164 }
165
166 /**
167 * Set an associated revision id.
168 *
169 * For example, the ID of the revision that was inserted to mark a page move
170 * or protection, file upload, etc.
171 *
172 * @since 1.27
173 * @param int $revId
174 */
175 public function setAssociatedRevId( $revId ) {
176 $this->revId = $revId;
177 }
178
179 /**
180 * Set change tags for the log entry.
181 *
182 * Passing `null` means the same as empty array,
183 * for compatibility with WikiPage::doUpdateRestrictions().
184 *
185 * @since 1.27
186 * @param string|string[]|null $tags
187 * @deprecated since 1.33 Please use addTags() instead
188 */
189 public function setTags( $tags ) {
190 if ( $this->tags ) {
191 wfDebug( 'Overwriting existing ManualLogEntry tags' );
192 }
193 $this->tags = [];
194 if ( $tags !== null ) {
195 $this->addTags( $tags );
196 }
197 }
198
199 /**
200 * Add change tags for the log entry
201 *
202 * @since 1.33
203 * @param string|string[] $tags Tags to apply
204 */
205 public function addTags( $tags ) {
206 if ( is_string( $tags ) ) {
207 $tags = [ $tags ];
208 }
209 Assert::parameterElementType( 'string', $tags, 'tags' );
210 $this->tags = array_unique( array_merge( $this->tags, $tags ) );
211 }
212
213 /**
214 * Set whether this log entry should be made patrollable
215 * This shouldn't depend on config, only on whether there is full support
216 * in the software for patrolling this log entry.
217 * False by default
218 *
219 * @since 1.27
220 * @param bool $patrollable
221 */
222 public function setIsPatrollable( $patrollable ) {
223 $this->isPatrollable = (bool)$patrollable;
224 }
225
226 /**
227 * Set the 'legacy' flag
228 *
229 * @since 1.25
230 * @param bool $legacy
231 */
232 public function setLegacy( $legacy ) {
233 $this->legacy = $legacy;
234 }
235
236 /**
237 * Set the 'deleted' flag.
238 *
239 * @since 1.19
240 * @param int $deleted One of LogPage::DELETED_* bitfield constants
241 */
242 public function setDeleted( $deleted ) {
243 $this->deleted = $deleted;
244 }
245
246 /**
247 * Insert the entry into the `logging` table.
248 *
249 * @param IDatabase|null $dbw
250 * @return int ID of the log entry
251 * @throws MWException
252 */
253 public function insert( IDatabase $dbw = null ) {
254 global $wgActorTableSchemaMigrationStage;
255
256 $dbw = $dbw ?: wfGetDB( DB_MASTER );
257
258 if ( $this->timestamp === null ) {
259 $this->timestamp = wfTimestampNow();
260 }
261
262 // Trim spaces on user supplied text
263 $comment = trim( $this->getComment() );
264
265 $params = $this->getParameters();
266 $relations = $this->relations;
267
268 // Ensure actor relations are set
269 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) &&
270 empty( $relations['target_author_actor'] )
271 ) {
272 $actorIds = [];
273 if ( !empty( $relations['target_author_id'] ) ) {
274 foreach ( $relations['target_author_id'] as $id ) {
275 $actorIds[] = User::newFromId( $id )->getActorId( $dbw );
276 }
277 }
278 if ( !empty( $relations['target_author_ip'] ) ) {
279 foreach ( $relations['target_author_ip'] as $ip ) {
280 $actorIds[] = User::newFromName( $ip, false )->getActorId( $dbw );
281 }
282 }
283 if ( $actorIds ) {
284 $relations['target_author_actor'] = $actorIds;
285 $params['authorActors'] = $actorIds;
286 }
287 }
288 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
289 unset( $relations['target_author_id'], $relations['target_author_ip'] );
290 unset( $params['authorIds'], $params['authorIPs'] );
291 }
292
293 // Additional fields for which there's no space in the database table schema
294 $revId = $this->getAssociatedRevId();
295 if ( $revId ) {
296 $params['associated_rev_id'] = $revId;
297 $relations['associated_rev_id'] = $revId;
298 }
299
300 $data = [
301 'log_type' => $this->getType(),
302 'log_action' => $this->getSubtype(),
303 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
304 'log_namespace' => $this->getTarget()->getNamespace(),
305 'log_title' => $this->getTarget()->getDBkey(),
306 'log_page' => $this->getTarget()->getArticleID(),
307 'log_params' => LogEntryBase::makeParamBlob( $params ),
308 ];
309 if ( isset( $this->deleted ) ) {
310 $data['log_deleted'] = $this->deleted;
311 }
312 $data += CommentStore::getStore()->insert( $dbw, 'log_comment', $comment );
313 $data += ActorMigration::newMigration()
314 ->getInsertValues( $dbw, 'log_user', $this->getPerformer() );
315
316 $dbw->insert( 'logging', $data, __METHOD__ );
317 $this->id = $dbw->insertId();
318
319 $rows = [];
320 foreach ( $relations as $tag => $values ) {
321 if ( !strlen( $tag ) ) {
322 throw new MWException( "Got empty log search tag." );
323 }
324
325 if ( !is_array( $values ) ) {
326 $values = [ $values ];
327 }
328
329 foreach ( $values as $value ) {
330 $rows[] = [
331 'ls_field' => $tag,
332 'ls_value' => $value,
333 'ls_log_id' => $this->id
334 ];
335 }
336 }
337 if ( count( $rows ) ) {
338 $dbw->insert( 'log_search', $rows, __METHOD__, 'IGNORE' );
339 }
340
341 return $this->id;
342 }
343
344 /**
345 * Get a RecentChanges object for the log entry
346 *
347 * @param int $newId
348 * @return RecentChange
349 * @since 1.23
350 */
351 public function getRecentChange( $newId = 0 ) {
352 $formatter = LogFormatter::newFromEntry( $this );
353 $context = RequestContext::newExtraneousContext( $this->getTarget() );
354 $formatter->setContext( $context );
355
356 $logpage = SpecialPage::getTitleFor( 'Log', $this->getType() );
357 $user = $this->getPerformer();
358 $ip = "";
359 if ( $user->isAnon() ) {
360 // "MediaWiki default" and friends may have
361 // no IP address in their name
362 if ( IP::isIPAddress( $user->getName() ) ) {
363 $ip = $user->getName();
364 }
365 }
366
367 return RecentChange::newLogEntry(
368 $this->getTimestamp(),
369 $logpage,
370 $user,
371 $formatter->getPlainActionText(),
372 $ip,
373 $this->getType(),
374 $this->getSubtype(),
375 $this->getTarget(),
376 $this->getComment(),
377 LogEntryBase::makeParamBlob( $this->getParameters() ),
378 $newId,
379 $formatter->getIRCActionComment(), // Used for IRC feeds
380 $this->getAssociatedRevId(), // Used for e.g. moves and uploads
381 $this->getIsPatrollable()
382 );
383 }
384
385 /**
386 * Publish the log entry.
387 *
388 * @param int $newId Id of the log entry.
389 * @param string $to One of: rcandudp (default), rc, udp
390 */
391 public function publish( $newId, $to = 'rcandudp' ) {
392 $canAddTags = true;
393 // FIXME: this code should be removed once all callers properly call publish()
394 if ( $to === 'udp' && !$newId && !$this->getAssociatedRevId() ) {
395 \MediaWiki\Logger\LoggerFactory::getInstance( 'logging' )->warning(
396 'newId and/or revId must be set when calling ManualLogEntry::publish()',
397 [
398 'newId' => $newId,
399 'to' => $to,
400 'revId' => $this->getAssociatedRevId(),
401 // pass a new exception to register the stack trace
402 'exception' => new RuntimeException()
403 ]
404 );
405 $canAddTags = false;
406 }
407
408 DeferredUpdates::addCallableUpdate(
409 function () use ( $newId, $to, $canAddTags ) {
410 $log = new LogPage( $this->getType() );
411 if ( !$log->isRestricted() ) {
412 Hooks::runWithoutAbort( 'ManualLogEntryBeforePublish', [ $this ] );
413 $rc = $this->getRecentChange( $newId );
414
415 if ( $to === 'rc' || $to === 'rcandudp' ) {
416 // save RC, passing tags so they are applied there
417 $rc->addTags( $this->getTags() );
418 $rc->save( $rc::SEND_NONE );
419 } else {
420 $tags = $this->getTags();
421 if ( $tags && $canAddTags ) {
422 $revId = $this->getAssociatedRevId();
423 ChangeTags::addTags(
424 $tags,
425 null,
426 $revId > 0 ? $revId : null,
427 $newId > 0 ? $newId : null
428 );
429 }
430 }
431
432 if ( $to === 'udp' || $to === 'rcandudp' ) {
433 $rc->notifyRCFeeds();
434 }
435 }
436 },
437 DeferredUpdates::POSTSEND,
438 wfGetDB( DB_MASTER )
439 );
440 }
441
442 public function getType() {
443 return $this->type;
444 }
445
446 public function getSubtype() {
447 return $this->subtype;
448 }
449
450 public function getParameters() {
451 return $this->parameters;
452 }
453
454 /**
455 * @return User
456 */
457 public function getPerformer() {
458 return $this->performer;
459 }
460
461 /**
462 * @return Title
463 */
464 public function getTarget() {
465 return $this->target;
466 }
467
468 public function getTimestamp() {
469 $ts = $this->timestamp ?? wfTimestampNow();
470
471 return wfTimestamp( TS_MW, $ts );
472 }
473
474 public function getComment() {
475 return $this->comment;
476 }
477
478 /**
479 * @since 1.27
480 * @return int
481 */
482 public function getAssociatedRevId() {
483 return $this->revId;
484 }
485
486 /**
487 * @since 1.27
488 * @return string[]
489 */
490 public function getTags() {
491 return $this->tags;
492 }
493
494 /**
495 * Whether this log entry is patrollable
496 *
497 * @since 1.27
498 * @return bool
499 */
500 public function getIsPatrollable() {
501 return $this->isPatrollable;
502 }
503
504 /**
505 * @since 1.25
506 * @return bool
507 */
508 public function isLegacy() {
509 return $this->legacy;
510 }
511
512 public function getDeleted() {
513 return (int)$this->deleted;
514 }
515 }