aboutsummaryrefslogtreecommitdiffstats
path: root/includes/CommentStore.php
blob: 5e5a0373ae5ea0232671ef5c7bff47146145fb00 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

use MediaWiki\MediaWikiServices;
use Wikimedia\Rdbms\IDatabase;

/**
 * @defgroup CommentStore CommentStore
 *
 * The Comment store in MediaWiki is responsible for storing edit summaries,
 * log action comments and other such short strings (referred to as "comments").
 *
 * The CommentStore class handles the database abstraction for reading
 * and writing comments, which are represented by CommentStoreComment objects.
 *
 * Data is internally stored in the `comment` table.
 */

/**
 * Handle database storage of comments such as edit summaries and log reasons.
 *
 * @ingroup CommentStore
 * @since 1.30
 */
class CommentStore {

	/**
	 * Maximum length of a comment in UTF-8 characters. Longer comments will be truncated.
	 * @note This must be at least 255 and not greater than floor( MAX_DATA_LENGTH / 4 ).
	 */
	public const COMMENT_CHARACTER_LIMIT = 500;

	/**
	 * Maximum length of serialized data in bytes. Longer data will result in an exception.
	 * @note This value is determined by the size of the underlying database field,
	 *  currently BLOB in MySQL/MariaDB.
	 */
	public const MAX_DATA_LENGTH = 65535;

	/**
	 * Define fields that use temporary tables for transitional purposes
	 * Array keys are field names, values are arrays with these possible fields:
	 *  - table: Temporary table name
	 *  - pk: Temporary table column referring to the main table's primary key
	 *  - field: Temporary table column referring comment.comment_id
	 *  - joinPK: Main table's primary key
	 *  - stage: Migration stage
	 *  - deprecatedIn: Version when using insertWithTempTable() was deprecated
	 */
	protected const TEMP_TABLES = [
		'rev_comment' => [
			'table' => 'revision_comment_temp',
			'pk' => 'revcomment_rev',
			'field' => 'revcomment_comment_id',
			'joinPK' => 'rev_id',
			'stage' => MIGRATION_OLD,
			'deprecatedIn' => null,
		],
		'img_description' => [
			'stage' => MIGRATION_NEW,
			'deprecatedIn' => '1.32',
		],
	];

	/**
	 * @var int One of the MIGRATION_* constants, or an appropriate combination
	 *  of SCHEMA_COMPAT_* constants.
	 * @todo Deprecate and remove once extensions seem unlikely to need to use
	 *  it for migration anymore.
	 */
	private $stage;

	/** @var array[] Cache for `self::getJoin()` */
	private $joinCache = [];

	/** @var Language Language to use for comment truncation */
	private $lang;

	/**
	 * @param Language $lang Language to use for comment truncation. Defaults
	 *  to content language.
	 * @param int $stage One of the MIGRATION_* constants, or an appropriate
	 *  combination of SCHEMA_COMPAT_* constants. Always MIGRATION_NEW for
	 *  MediaWiki core since 1.33.
	 */
	public function __construct( Language $lang, $stage ) {
		if ( ( $stage & SCHEMA_COMPAT_WRITE_BOTH ) === 0 ) {
			throw new InvalidArgumentException( '$stage must include a write mode' );
		}
		if ( ( $stage & SCHEMA_COMPAT_READ_BOTH ) === 0 ) {
			throw new InvalidArgumentException( '$stage must include a read mode' );
		}

		$this->stage = $stage;
		$this->lang = $lang;
	}

	/**
	 * @since 1.31
	 * @deprecated in 1.31 Use DI to inject a CommentStore instance into your class.
	 * @return CommentStore
	 */
	public static function getStore() {
		return MediaWikiServices::getInstance()->getCommentStore();
	}

	/**
	 * Get SELECT fields for the comment key
	 *
	 * Each resulting row should be passed to `self::getCommentLegacy()` to get the
	 * actual comment.
	 *
	 * @note Use of this method may require a subsequent database query to
	 *  actually fetch the comment. If possible, use `self::getJoin()` instead.
	 *
	 * @since 1.30
	 * @since 1.31 Method signature changed, $key parameter added (required since 1.35)
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @return string[] to include in the `$vars` to `IDatabase->select()`. All
	 *  fields are aliased, so `+` is safe to use.
	 */
	public function getFields( $key ) {
		$fields = [];
		if ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
			$fields["{$key}_text"] = $key;
			$fields["{$key}_data"] = 'NULL';
			$fields["{$key}_cid"] = 'NULL';
		} else { // READ_BOTH or READ_NEW
			if ( $this->stage & SCHEMA_COMPAT_READ_OLD ) {
				$fields["{$key}_old"] = $key;
			}

			$tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
			if ( $tempTableStage & SCHEMA_COMPAT_READ_OLD ) {
				// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
				$fields["{$key}_pk"] = static::TEMP_TABLES[$key]['joinPK'];
			}
			if ( $tempTableStage & SCHEMA_COMPAT_READ_NEW ) {
				$fields["{$key}_id"] = "{$key}_id";
			}
		}
		return $fields;
	}

	/**
	 * Get SELECT fields and joins for the comment key
	 *
	 * Each resulting row should be passed to `self::getComment()` to get the
	 * actual comment.
	 *
	 * @since 1.30
	 * @since 1.31 Method signature changed, $key parameter added (required since 1.35)
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @return array[] With three keys:
	 *   - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
	 *   - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
	 *   - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
	 *  All tables, fields, and joins are aliased, so `+` is safe to use.
	 * @phan-return array{tables:string[],fields:string[],joins:array}
	 */
	public function getJoin( $key ) {
		if ( !array_key_exists( $key, $this->joinCache ) ) {
			$tables = [];
			$fields = [];
			$joins = [];

			if ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
				$fields["{$key}_text"] = $key;
				$fields["{$key}_data"] = 'NULL';
				$fields["{$key}_cid"] = 'NULL';
			} else { // READ_BOTH or READ_NEW
				$join = ( $this->stage & SCHEMA_COMPAT_READ_OLD ) ? 'LEFT JOIN' : 'JOIN';

				$tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
				if ( $tempTableStage & SCHEMA_COMPAT_READ_OLD ) {
					$t = static::TEMP_TABLES[$key];
					$alias = "temp_$key";
					// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
					$tables[$alias] = $t['table'];
					// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
					$joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
					if ( ( $tempTableStage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
						// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
						$joinField = "{$alias}.{$t['field']}";
					} else {
						// Nothing hits this code path for now, but will in the future when we set
						// static::TEMP_TABLES['rev_comment']['stage'] to MIGRATION_WRITE_NEW while
						// merging revision_comment_temp into revision.
						// @codeCoverageIgnoreStart
						$joins[$alias][0] = 'LEFT JOIN';
						// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
						$joinField = "(CASE WHEN {$key}_id != 0 THEN {$key}_id ELSE {$alias}.{$t['field']} END)";
						throw new LogicException( 'Nothing should reach this code path at this time' );
						// @codeCoverageIgnoreEnd
					}
				} else {
					$joinField = "{$key}_id";
				}

				$alias = "comment_$key";
				$tables[$alias] = 'comment';
				$joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];

				if ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_NEW ) {
					$fields["{$key}_text"] = "{$alias}.comment_text";
				} else {
					$fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
				}
				$fields["{$key}_data"] = "{$alias}.comment_data";
				$fields["{$key}_cid"] = "{$alias}.comment_id";
			}

			$this->joinCache[$key] = [
				'tables' => $tables,
				'fields' => $fields,
				'joins' => $joins,
			];
		}

		return $this->joinCache[$key];
	}

	/**
	 * Extract the comment from a row
	 *
	 * Shared implementation for getComment() and getCommentLegacy()
	 *
	 * @param IDatabase|null $db Database handle for getCommentLegacy(), or null for getComment()
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @param stdClass|array $row
	 * @param bool $fallback
	 * @return CommentStoreComment
	 */
	private function getCommentInternal( ?IDatabase $db, $key, $row, $fallback = false ) {
		$row = (array)$row;
		if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
			$cid = $row["{$key}_cid"] ?? null;
			$text = $row["{$key}_text"];
			$data = $row["{$key}_data"];
		} elseif ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
			$cid = null;
			if ( $fallback && isset( $row[$key] ) ) {
				wfLogWarning( "Using deprecated fallback handling for comment $key" );
				$text = $row[$key];
			} else {
				wfLogWarning(
					"Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD / READ_OLD"
				);
				$text = '';
			}
			$data = null;
		} else {
			$tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
			$row2 = null;
			if ( ( $tempTableStage & SCHEMA_COMPAT_READ_NEW ) && array_key_exists( "{$key}_id", $row ) ) {
				if ( !$db ) {
					throw new InvalidArgumentException(
						"\$row does not contain fields needed for comment $key and getComment(), but "
						. "does have fields for getCommentLegacy()"
					);
				}
				$id = $row["{$key}_id"];
				$row2 = $db->selectRow(
					'comment',
					[ 'comment_id', 'comment_text', 'comment_data' ],
					[ 'comment_id' => $id ],
					__METHOD__
				);
			}
			if ( !$row2 && ( $tempTableStage & SCHEMA_COMPAT_READ_OLD ) &&
				array_key_exists( "{$key}_pk", $row )
			) {
				if ( !$db ) {
					throw new InvalidArgumentException(
						"\$row does not contain fields needed for comment $key and getComment(), but "
						. "does have fields for getCommentLegacy()"
					);
				}
				$t = static::TEMP_TABLES[$key];
				$id = $row["{$key}_pk"];
				$row2 = $db->selectRow(
					// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
					[ $t['table'], 'comment' ],
					[ 'comment_id', 'comment_text', 'comment_data' ],
					// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
					[ $t['pk'] => $id ],
					__METHOD__,
					[],
					// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
					[ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
				);
			}
			if ( $row2 === null && $fallback && isset( $row[$key] ) ) {
				wfLogWarning( "Using deprecated fallback handling for comment $key" );
				$row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
			}
			if ( $row2 === null ) {
				throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
			}

			if ( $row2 ) {
				$cid = $row2->comment_id;
				$text = $row2->comment_text;
				$data = $row2->comment_data;
			} elseif ( ( $this->stage & SCHEMA_COMPAT_READ_OLD ) &&
				array_key_exists( "{$key}_old", $row )
			) {
				$cid = null;
				$text = $row["{$key}_old"];
				$data = null;
			} else {
				// @codeCoverageIgnoreStart
				// @phan-suppress-next-line PhanPossiblyUndeclaredVariable $id is set when $row2 is okay
				wfLogWarning( "Missing comment row for $key, id=$id" );
				$cid = null;
				$text = '';
				$data = null;
				// @codeCoverageIgnoreEnd
			}
		}

		$msg = null;
		if ( $data !== null ) {
			$data = FormatJson::decode( $data, true );
			if ( !is_array( $data ) ) {
				// @codeCoverageIgnoreStart
				wfLogWarning( "Invalid JSON object in comment: $data" );
				$data = null;
				// @codeCoverageIgnoreEnd
			} else {
				if ( isset( $data['_message'] ) ) {
					$msg = self::decodeMessage( $data['_message'] )
						->setInterfaceMessageFlag( true );
				}
				if ( !empty( $data['_null'] ) ) {
					$data = null;
				} else {
					foreach ( $data as $k => $v ) {
						if ( substr( $k, 0, 1 ) === '_' ) {
							unset( $data[$k] );
						}
					}
				}
			}
		}

		return new CommentStoreComment( $cid, $text, $msg, $data );
	}

	/**
	 * Extract the comment from a row
	 *
	 * Use `self::getJoin()` to ensure the row contains the needed data.
	 *
	 * If you need to fake a comment in a row for some reason, set fields
	 * `{$key}_text` (string) and `{$key}_data` (JSON string or null).
	 *
	 * @since 1.30
	 * @since 1.31 Method signature changed, $key parameter added (required since 1.35)
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @param stdClass|array|null $row Result row.
	 * @param bool $fallback If true, fall back as well as possible instead of throwing an exception.
	 * @return CommentStoreComment
	 */
	public function getComment( $key, $row = null, $fallback = false ) {
		if ( $row === null ) {
			// @codeCoverageIgnoreStart
			throw new InvalidArgumentException( '$row must not be null' );
			// @codeCoverageIgnoreEnd
		}
		return $this->getCommentInternal( null, $key, $row, $fallback );
	}

	/**
	 * Extract the comment from a row, with legacy lookups.
	 *
	 * If `$row` might have been generated using `self::getFields()` rather
	 * than `self::getJoin()`, use this. Prefer `self::getComment()` if you
	 * know callers used `self::getJoin()` for the row fetch.
	 *
	 * If you need to fake a comment in a row for some reason, set fields
	 * `{$key}_text` (string) and `{$key}_data` (JSON string or null).
	 *
	 * @since 1.30
	 * @since 1.31 Method signature changed, $key parameter added (required since 1.35)
	 * @param IDatabase $db Database handle to use for lookup
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @param stdClass|array|null $row Result row.
	 * @param bool $fallback If true, fall back as well as possible instead of throwing an exception.
	 * @return CommentStoreComment
	 */
	public function getCommentLegacy( IDatabase $db, $key, $row = null, $fallback = false ) {
		if ( $row === null ) {
			// @codeCoverageIgnoreStart
			throw new InvalidArgumentException( '$row must not be null' );
			// @codeCoverageIgnoreEnd
		}
		return $this->getCommentInternal( $db, $key, $row, $fallback );
	}

	/**
	 * Create a new CommentStoreComment, inserting it into the database if necessary
	 *
	 * If a comment is going to be passed to `self::insert()` or the like
	 * multiple times, it will be more efficient to pass a CommentStoreComment
	 * once rather than making `self::insert()` do it every time through.
	 *
	 * @note When passing a CommentStoreComment, this may set `$comment->id` if
	 *  it's not already set. If `$comment->id` is already set, it will not be
	 *  verified that the specified comment actually exists or that it
	 *  corresponds to the comment text, message, and/or data in the
	 *  CommentStoreComment.
	 * @param IDatabase $dbw Database handle to insert on. Unused if `$comment`
	 *  is a CommentStoreComment and `$comment->id` is set.
	 * @param string|Message|CommentStoreComment $comment Comment text or Message object, or
	 *  a CommentStoreComment.
	 * @param array|null $data Structured data to store. Keys beginning with '_' are reserved.
	 *  Ignored if $comment is a CommentStoreComment.
	 * @return CommentStoreComment
	 */
	public function createComment( IDatabase $dbw, $comment, array $data = null ) {
		$comment = CommentStoreComment::newUnsavedComment( $comment, $data );

		# Truncate comment in a Unicode-sensitive manner
		$comment->text = $this->lang->truncateForVisual( $comment->text, self::COMMENT_CHARACTER_LIMIT );

		if ( ( $this->stage & SCHEMA_COMPAT_WRITE_NEW ) && !$comment->id ) {
			$dbData = $comment->data;
			if ( !$comment->message instanceof RawMessage ) {
				if ( $dbData === null ) {
					$dbData = [ '_null' => true ];
				}
				$dbData['_message'] = self::encodeMessage( $comment->message );
			}
			if ( $dbData !== null ) {
				$dbData = FormatJson::encode( (object)$dbData, false, FormatJson::ALL_OK );
				$len = strlen( $dbData );
				if ( $len > self::MAX_DATA_LENGTH ) {
					$max = self::MAX_DATA_LENGTH;
					throw new OverflowException( "Comment data is too long ($len bytes, maximum is $max)" );
				}
			}

			$hash = self::hash( $comment->text, $dbData );
			$commentId = $dbw->selectField(
				'comment',
				'comment_id',
				[
					'comment_hash' => $hash,
					'comment_text' => $comment->text,
					'comment_data' => $dbData,
				],
				__METHOD__
			);
			if ( !$commentId ) {
				$dbw->insert(
					'comment',
					[
						'comment_hash' => $hash,
						'comment_text' => $comment->text,
						'comment_data' => $dbData,
					],
					__METHOD__
				);
				$commentId = $dbw->insertId();
			}
			$comment->id = (int)$commentId;
		}

		return $comment;
	}

	/**
	 * Implementation for `self::insert()` and `self::insertWithTempTable()`
	 * @param IDatabase $dbw
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @param string|Message|CommentStoreComment $comment
	 * @param array|null $data
	 * @return array [ array $fields, callable $callback ]
	 */
	private function insertInternal( IDatabase $dbw, $key, $comment, $data ) {
		$fields = [];
		$callback = null;

		$comment = $this->createComment( $dbw, $comment, $data );

		if ( $this->stage & SCHEMA_COMPAT_WRITE_OLD ) {
			$fields[$key] = $this->lang->truncateForDatabase( $comment->text, 255 );
		}

		if ( $this->stage & SCHEMA_COMPAT_WRITE_NEW ) {
			$tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
			if ( $tempTableStage & SCHEMA_COMPAT_WRITE_OLD ) {
				$t = static::TEMP_TABLES[$key];
				$func = __METHOD__;
				$commentId = $comment->id;
				$callback = static function ( $id ) use ( $dbw, $commentId, $t, $func ) {
					$dbw->insert(
						// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
						$t['table'],
						[
							// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
							$t['pk'] => $id,
							// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Only set for stage old
							$t['field'] => $commentId,
						],
						$func
					);
				};
			}
			if ( $tempTableStage & SCHEMA_COMPAT_WRITE_NEW ) {
				$fields["{$key}_id"] = $comment->id;
			}
		}

		return [ $fields, $callback ];
	}

	/**
	 * Insert a comment in preparation for a row that references it
	 *
	 * @note It's recommended to include both the call to this method and the
	 *  row insert in the same transaction.
	 *
	 * @since 1.30
	 * @since 1.31 Method signature changed, $key parameter added (required since 1.35)
	 * @param IDatabase $dbw Database handle to insert on
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @param string|Message|CommentStoreComment|null $comment As for `self::createComment()`
	 * @param array|null $data As for `self::createComment()`
	 * @return array Fields for the insert or update
	 */
	public function insert( IDatabase $dbw, $key, $comment = null, $data = null ) {
		if ( $comment === null ) {
			// @codeCoverageIgnoreStart
			throw new InvalidArgumentException( '$comment can not be null' );
			// @codeCoverageIgnoreEnd
		}

		$tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
		if ( $tempTableStage & SCHEMA_COMPAT_WRITE_OLD ) {
			throw new InvalidArgumentException( "Must use insertWithTempTable() for $key" );
		}

		list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
		return $fields;
	}

	/**
	 * Insert a comment in a temporary table in preparation for a row that references it
	 *
	 * This is currently needed for "rev_comment" and "img_description". In the
	 * future that requirement will be removed.
	 *
	 * @note It's recommended to include both the call to this method and the
	 *  row insert in the same transaction.
	 *
	 * @since 1.30
	 * @since 1.31 Method signature changed, $key parameter added (required since 1.35)
	 * @param IDatabase $dbw Database handle to insert on
	 * @param string $key A key such as "rev_comment" identifying the comment
	 *  field being fetched.
	 * @param string|Message|CommentStoreComment|null $comment As for `self::createComment()`
	 * @param array|null $data As for `self::createComment()`
	 * @return array Two values:
	 *  - array Fields for the insert or update
	 *  - callable Function to call when the primary key of the row being
	 *    inserted/updated is known. Pass it that primary key.
	 */
	public function insertWithTempTable( IDatabase $dbw, $key, $comment = null, $data = null ) {
		if ( $comment === null ) {
			// @codeCoverageIgnoreStart
			throw new InvalidArgumentException( '$comment can not be null' );
			// @codeCoverageIgnoreEnd
		}

		if ( !isset( static::TEMP_TABLES[$key] ) ) {
			throw new InvalidArgumentException( "Must use insert() for $key" );
		} elseif ( isset( static::TEMP_TABLES[$key]['deprecatedIn'] ) ) {
			wfDeprecated( __METHOD__ . " for $key", static::TEMP_TABLES[$key]['deprecatedIn'] );
		}

		list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
		if ( !$callback ) {
			$callback = static function () {
				// Do nothing.
			};
		}
		return [ $fields, $callback ];
	}

	/**
	 * Encode a Message as a PHP data structure
	 * @param Message $msg
	 * @return array
	 */
	private static function encodeMessage( Message $msg ) {
		$key = count( $msg->getKeysToTry() ) > 1 ? $msg->getKeysToTry() : $msg->getKey();
		$params = $msg->getParams();
		foreach ( $params as &$param ) {
			if ( $param instanceof Message ) {
				$param = [
					'message' => self::encodeMessage( $param )
				];
			}
		}
		array_unshift( $params, $key );
		return $params;
	}

	/**
	 * Decode a message that was encoded by self::encodeMessage()
	 * @param array $data
	 * @return Message
	 */
	private static function decodeMessage( $data ) {
		$key = array_shift( $data );
		foreach ( $data as &$param ) {
			if ( is_object( $param ) ) {
				$param = (array)$param;
			}
			if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
				$param = self::decodeMessage( $param['message'] );
			}
		}
		return new Message( $key, $data );
	}

	/**
	 * Hashing function for comment storage
	 * @param string $text Comment text
	 * @param string|null $data Comment data
	 * @return int 32-bit signed integer
	 */
	public static function hash( $text, $data ) {
		$hash = crc32( $text ) ^ crc32( (string)$data );

		// 64-bit PHP returns an unsigned CRC, change it to signed for
		// insertion into the database.
		if ( $hash >= 0x80000000 ) {
			$hash |= -1 << 32;
		}

		return $hash;
	}

}