3 * Manage storage of comments in the database
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.
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.
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
23 use MediaWiki\MediaWikiServices
;
24 use Wikimedia\Rdbms\IDatabase
;
27 * CommentStore handles storage of comments (edit summaries, log reasons, etc)
34 * Maximum length of a comment in UTF-8 characters. Longer comments will be truncated.
35 * @note This must be at least 255 and not greater than floor( MAX_COMMENT_LENGTH / 4 ).
37 const COMMENT_CHARACTER_LIMIT
= 500;
40 * Maximum length of a comment in bytes. Longer comments will be truncated.
41 * @note This value is determined by the size of the underlying database field,
42 * currently BLOB in MySQL/MariaDB.
44 const MAX_COMMENT_LENGTH
= 65535;
47 * Maximum length of serialized data in bytes. Longer data will result in an exception.
48 * @note This value is determined by the size of the underlying database field,
49 * currently BLOB in MySQL/MariaDB.
51 const MAX_DATA_LENGTH
= 65535;
54 * Define fields that use temporary tables for transitional purposes
55 * @var array Keys are '$key', values are arrays with these possible fields:
56 * - table: Temporary table name
57 * - pk: Temporary table column referring to the main table's primary key
58 * - field: Temporary table column referring comment.comment_id
59 * - joinPK: Main table's primary key
60 * - stage: Migration stage
61 * - deprecatedIn: Version when using insertWithTempTable() was deprecated
63 protected $tempTables = [
65 'table' => 'revision_comment_temp',
66 'pk' => 'revcomment_rev',
67 'field' => 'revcomment_comment_id',
69 'stage' => MIGRATION_OLD
,
70 'deprecatedIn' => null,
72 'img_description' => [
73 'table' => 'image_comment_temp',
74 'pk' => 'imgcomment_name',
75 'field' => 'imgcomment_description_id',
76 'joinPK' => 'img_name',
77 'stage' => MIGRATION_WRITE_NEW
,
78 'deprecatedIn' => '1.32',
87 protected $key = null;
89 /** @var int One of the MIGRATION_* constants */
92 /** @var array[] Cache for `self::getJoin()` */
93 protected $joinCache = [];
95 /** @var Language Language to use for comment truncation */
99 * @param Language $lang Language to use for comment truncation. Defaults
100 * to content language.
101 * @param int $migrationStage One of the MIGRATION_* constants
103 public function __construct( Language
$lang, $migrationStage ) {
104 $this->stage
= $migrationStage;
109 * Static constructor for easier chaining
110 * @deprecated in 1.31 Should not be constructed with a $key, use CommentStore::getStore
111 * @param string $key A key such as "rev_comment" identifying the comment
112 * field being fetched.
113 * @return CommentStore
115 public static function newKey( $key ) {
116 global $wgCommentTableSchemaMigrationStage;
117 wfDeprecated( __METHOD__
, '1.31' );
118 $store = new CommentStore( MediaWikiServices
::getInstance()->getContentLanguage(),
119 $wgCommentTableSchemaMigrationStage );
126 * @deprecated in 1.31 Use DI to inject a CommentStore instance into your class.
127 * @return CommentStore
129 public static function getStore() {
130 return MediaWikiServices
::getInstance()->getCommentStore();
134 * Compat method allowing use of self::newKey until removed.
135 * @param string|null $methodKey
136 * @throws InvalidArgumentException
139 private function getKey( $methodKey = null ) {
140 $key = $this->key ??
$methodKey;
141 if ( $key === null ) {
142 // @codeCoverageIgnoreStart
143 throw new InvalidArgumentException( '$key should not be null' );
144 // @codeCoverageIgnoreEnd
150 * Get SELECT fields for the comment key
152 * Each resulting row should be passed to `self::getCommentLegacy()` to get the
155 * @note Use of this method may require a subsequent database query to
156 * actually fetch the comment. If possible, use `self::getJoin()` instead.
159 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
160 * @param string|null $key A key such as "rev_comment" identifying the comment
161 * field being fetched.
162 * @return string[] to include in the `$vars` to `IDatabase->select()`. All
163 * fields are aliased, so `+` is safe to use.
165 public function getFields( $key = null ) {
166 $key = $this->getKey( $key );
168 if ( $this->stage
=== MIGRATION_OLD
) {
169 $fields["{$key}_text"] = $key;
170 $fields["{$key}_data"] = 'NULL';
171 $fields["{$key}_cid"] = 'NULL';
173 if ( $this->stage
< MIGRATION_NEW
) {
174 $fields["{$key}_old"] = $key;
177 $tempTableStage = isset( $this->tempTables
[$key] )
178 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
179 if ( $tempTableStage < MIGRATION_NEW
) {
180 $fields["{$key}_pk"] = $this->tempTables
[$key]['joinPK'];
182 if ( $tempTableStage > MIGRATION_OLD
) {
183 $fields["{$key}_id"] = "{$key}_id";
190 * Get SELECT fields and joins for the comment key
192 * Each resulting row should be passed to `self::getComment()` to get the
196 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
197 * @param string|null $key A key such as "rev_comment" identifying the comment
198 * field being fetched.
199 * @return array With three keys:
200 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
201 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
202 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
203 * All tables, fields, and joins are aliased, so `+` is safe to use.
205 public function getJoin( $key = null ) {
206 $key = $this->getKey( $key );
207 if ( !array_key_exists( $key, $this->joinCache
) ) {
212 if ( $this->stage
=== MIGRATION_OLD
) {
213 $fields["{$key}_text"] = $key;
214 $fields["{$key}_data"] = 'NULL';
215 $fields["{$key}_cid"] = 'NULL';
217 $join = $this->stage
=== MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN';
219 $tempTableStage = isset( $this->tempTables
[$key] )
220 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
221 if ( $tempTableStage < MIGRATION_NEW
) {
222 $t = $this->tempTables
[$key];
223 $alias = "temp_$key";
224 $tables[$alias] = $t['table'];
225 $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
226 if ( $tempTableStage === MIGRATION_OLD
) {
227 $joinField = "{$alias}.{$t['field']}";
229 $joins[$alias][0] = 'LEFT JOIN';
230 $joinField = "(CASE WHEN {$key}_id != 0 THEN {$key}_id ELSE {$alias}.{$t['field']} END)";
233 $joinField = "{$key}_id";
236 $alias = "comment_$key";
237 $tables[$alias] = 'comment';
238 $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
240 if ( $this->stage
=== MIGRATION_NEW
) {
241 $fields["{$key}_text"] = "{$alias}.comment_text";
243 $fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
245 $fields["{$key}_data"] = "{$alias}.comment_data";
246 $fields["{$key}_cid"] = "{$alias}.comment_id";
249 $this->joinCache
[$key] = [
256 return $this->joinCache
[$key];
260 * Extract the comment from a row
262 * Shared implementation for getComment() and getCommentLegacy()
264 * @param IDatabase|null $db Database handle for getCommentLegacy(), or null for getComment()
265 * @param string $key A key such as "rev_comment" identifying the comment
266 * field being fetched.
267 * @param object|array $row
268 * @param bool $fallback
269 * @return CommentStoreComment
271 private function getCommentInternal( IDatabase
$db = null, $key, $row, $fallback = false ) {
273 if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
274 $cid = $row["{$key}_cid"] ??
null;
275 $text = $row["{$key}_text"];
276 $data = $row["{$key}_data"];
277 } elseif ( $this->stage
=== MIGRATION_OLD
) {
279 if ( $fallback && isset( $row[$key] ) ) {
280 wfLogWarning( "Using deprecated fallback handling for comment $key" );
283 wfLogWarning( "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD" );
288 $tempTableStage = isset( $this->tempTables
[$key] )
289 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
291 if ( $tempTableStage > MIGRATION_OLD
&& array_key_exists( "{$key}_id", $row ) ) {
293 throw new InvalidArgumentException(
294 "\$row does not contain fields needed for comment $key and getComment(), but "
295 . "does have fields for getCommentLegacy()"
298 $id = $row["{$key}_id"];
299 $row2 = $db->selectRow(
301 [ 'comment_id', 'comment_text', 'comment_data' ],
302 [ 'comment_id' => $id ],
306 if ( !$row2 && $tempTableStage < MIGRATION_NEW
&& array_key_exists( "{$key}_pk", $row ) ) {
308 throw new InvalidArgumentException(
309 "\$row does not contain fields needed for comment $key and getComment(), but "
310 . "does have fields for getCommentLegacy()"
313 $t = $this->tempTables
[$key];
314 $id = $row["{$key}_pk"];
315 $row2 = $db->selectRow(
316 [ $t['table'], 'comment' ],
317 [ 'comment_id', 'comment_text', 'comment_data' ],
321 [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
324 if ( $row2 === null && $fallback && isset( $row[$key] ) ) {
325 wfLogWarning( "Using deprecated fallback handling for comment $key" );
326 $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
328 if ( $row2 === null ) {
329 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
333 $cid = $row2->comment_id
;
334 $text = $row2->comment_text
;
335 $data = $row2->comment_data
;
336 } elseif ( $this->stage
< MIGRATION_NEW
&& array_key_exists( "{$key}_old", $row ) ) {
338 $text = $row["{$key}_old"];
341 // @codeCoverageIgnoreStart
342 wfLogWarning( "Missing comment row for $key, id=$id" );
346 // @codeCoverageIgnoreEnd
351 if ( $data !== null ) {
352 $data = FormatJson
::decode( $data, true );
353 if ( !is_array( $data ) ) {
354 // @codeCoverageIgnoreStart
355 wfLogWarning( "Invalid JSON object in comment: $data" );
357 // @codeCoverageIgnoreEnd
359 if ( isset( $data['_message'] ) ) {
360 $msg = self
::decodeMessage( $data['_message'] )
361 ->setInterfaceMessageFlag( true );
363 if ( !empty( $data['_null'] ) ) {
366 foreach ( $data as $k => $v ) {
367 if ( substr( $k, 0, 1 ) === '_' ) {
375 return new CommentStoreComment( $cid, $text, $msg, $data );
379 * Extract the comment from a row
381 * Use `self::getJoin()` to ensure the row contains the needed data.
383 * If you need to fake a comment in a row for some reason, set fields
384 * `{$key}_text` (string) and `{$key}_data` (JSON string or null).
387 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
388 * @param string $key A key such as "rev_comment" identifying the comment
389 * field being fetched.
390 * @param object|array|null $row Result row.
391 * @param bool $fallback If true, fall back as well as possible instead of throwing an exception.
392 * @return CommentStoreComment
394 public function getComment( $key, $row = null, $fallback = false ) {
395 // Compat for method sig change in 1.31 (introduction of $key)
396 if ( $this->key
!== null ) {
399 $key = $this->getKey();
401 if ( $row === null ) {
402 // @codeCoverageIgnoreStart
403 throw new InvalidArgumentException( '$row must not be null' );
404 // @codeCoverageIgnoreEnd
406 return $this->getCommentInternal( null, $key, $row, $fallback );
410 * Extract the comment from a row, with legacy lookups.
412 * If `$row` might have been generated using `self::getFields()` rather
413 * than `self::getJoin()`, use this. Prefer `self::getComment()` if you
414 * know callers used `self::getJoin()` for the row fetch.
416 * If you need to fake a comment in a row for some reason, set fields
417 * `{$key}_text` (string) and `{$key}_data` (JSON string or null).
420 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
421 * @param IDatabase $db Database handle to use for lookup
422 * @param string $key A key such as "rev_comment" identifying the comment
423 * field being fetched.
424 * @param object|array|null $row Result row.
425 * @param bool $fallback If true, fall back as well as possible instead of throwing an exception.
426 * @return CommentStoreComment
428 public function getCommentLegacy( IDatabase
$db, $key, $row = null, $fallback = false ) {
429 // Compat for method sig change in 1.31 (introduction of $key)
430 if ( $this->key
!== null ) {
433 $key = $this->getKey();
435 if ( $row === null ) {
436 // @codeCoverageIgnoreStart
437 throw new InvalidArgumentException( '$row must not be null' );
438 // @codeCoverageIgnoreEnd
440 return $this->getCommentInternal( $db, $key, $row, $fallback );
444 * Create a new CommentStoreComment, inserting it into the database if necessary
446 * If a comment is going to be passed to `self::insert()` or the like
447 * multiple times, it will be more efficient to pass a CommentStoreComment
448 * once rather than making `self::insert()` do it every time through.
450 * @note When passing a CommentStoreComment, this may set `$comment->id` if
451 * it's not already set. If `$comment->id` is already set, it will not be
452 * verified that the specified comment actually exists or that it
453 * corresponds to the comment text, message, and/or data in the
454 * CommentStoreComment.
455 * @param IDatabase $dbw Database handle to insert on. Unused if `$comment`
456 * is a CommentStoreComment and `$comment->id` is set.
457 * @param string|Message|CommentStoreComment $comment Comment text or Message object, or
458 * a CommentStoreComment.
459 * @param array|null $data Structured data to store. Keys beginning with '_' are reserved.
460 * Ignored if $comment is a CommentStoreComment.
461 * @return CommentStoreComment
463 public function createComment( IDatabase
$dbw, $comment, array $data = null ) {
464 $comment = CommentStoreComment
::newUnsavedComment( $comment, $data );
466 # Truncate comment in a Unicode-sensitive manner
467 $comment->text
= $this->lang
->truncateForVisual( $comment->text
, self
::COMMENT_CHARACTER_LIMIT
);
469 if ( $this->stage
> MIGRATION_OLD
&& !$comment->id
) {
470 $dbData = $comment->data
;
471 if ( !$comment->message
instanceof RawMessage
) {
472 if ( $dbData === null ) {
473 $dbData = [ '_null' => true ];
475 $dbData['_message'] = self
::encodeMessage( $comment->message
);
477 if ( $dbData !== null ) {
478 $dbData = FormatJson
::encode( (object)$dbData, false, FormatJson
::ALL_OK
);
479 $len = strlen( $dbData );
480 if ( $len > self
::MAX_DATA_LENGTH
) {
481 $max = self
::MAX_DATA_LENGTH
;
482 throw new OverflowException( "Comment data is too long ($len bytes, maximum is $max)" );
486 $hash = self
::hash( $comment->text
, $dbData );
487 $comment->id
= $dbw->selectField(
491 'comment_hash' => $hash,
492 'comment_text' => $comment->text
,
493 'comment_data' => $dbData,
497 if ( !$comment->id
) {
501 'comment_hash' => $hash,
502 'comment_text' => $comment->text
,
503 'comment_data' => $dbData,
507 $comment->id
= $dbw->insertId();
515 * Implementation for `self::insert()` and `self::insertWithTempTable()`
516 * @param IDatabase $dbw
517 * @param string $key A key such as "rev_comment" identifying the comment
518 * field being fetched.
519 * @param string|Message|CommentStoreComment $comment
520 * @param array|null $data
521 * @return array [ array $fields, callable $callback ]
523 private function insertInternal( IDatabase
$dbw, $key, $comment, $data ) {
527 $comment = $this->createComment( $dbw, $comment, $data );
529 if ( $this->stage
<= MIGRATION_WRITE_BOTH
) {
530 $fields[$key] = $this->lang
->truncateForDatabase( $comment->text
, 255 );
533 if ( $this->stage
>= MIGRATION_WRITE_BOTH
) {
534 $tempTableStage = isset( $this->tempTables
[$key] )
535 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
536 if ( $tempTableStage <= MIGRATION_WRITE_BOTH
) {
537 $t = $this->tempTables
[$key];
539 $commentId = $comment->id
;
540 $callback = function ( $id ) use ( $dbw, $commentId, $t, $func ) {
545 $t['field'] => $commentId,
551 if ( $tempTableStage >= MIGRATION_WRITE_BOTH
) {
552 $fields["{$key}_id"] = $comment->id
;
556 return [ $fields, $callback ];
560 * Insert a comment in preparation for a row that references it
562 * @note It's recommended to include both the call to this method and the
563 * row insert in the same transaction.
566 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
567 * @param IDatabase $dbw Database handle to insert on
568 * @param string $key A key such as "rev_comment" identifying the comment
569 * field being fetched.
570 * @param string|Message|CommentStoreComment|null $comment As for `self::createComment()`
571 * @param array|null $data As for `self::createComment()`
572 * @return array Fields for the insert or update
574 public function insert( IDatabase
$dbw, $key, $comment = null, $data = null ) {
575 // Compat for method sig change in 1.31 (introduction of $key)
576 if ( $this->key
!== null ) {
581 if ( $comment === null ) {
582 // @codeCoverageIgnoreStart
583 throw new InvalidArgumentException( '$comment can not be null' );
584 // @codeCoverageIgnoreEnd
587 $tempTableStage = isset( $this->tempTables
[$key] )
588 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
589 if ( $tempTableStage < MIGRATION_WRITE_NEW
) {
590 throw new InvalidArgumentException( "Must use insertWithTempTable() for $key" );
593 list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
598 * Insert a comment in a temporary table in preparation for a row that references it
600 * This is currently needed for "rev_comment" and "img_description". In the
601 * future that requirement will be removed.
603 * @note It's recommended to include both the call to this method and the
604 * row insert in the same transaction.
607 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
608 * @param IDatabase $dbw Database handle to insert on
609 * @param string $key A key such as "rev_comment" identifying the comment
610 * field being fetched.
611 * @param string|Message|CommentStoreComment|null $comment As for `self::createComment()`
612 * @param array|null $data As for `self::createComment()`
613 * @return array Two values:
614 * - array Fields for the insert or update
615 * - callable Function to call when the primary key of the row being
616 * inserted/updated is known. Pass it that primary key.
618 public function insertWithTempTable( IDatabase
$dbw, $key, $comment = null, $data = null ) {
619 // Compat for method sig change in 1.31 (introduction of $key)
620 if ( $this->key
!== null ) {
623 $key = $this->getKey();
625 if ( $comment === null ) {
626 // @codeCoverageIgnoreStart
627 throw new InvalidArgumentException( '$comment can not be null' );
628 // @codeCoverageIgnoreEnd
631 if ( !isset( $this->tempTables
[$key] ) ) {
632 throw new InvalidArgumentException( "Must use insert() for $key" );
633 } elseif ( isset( $this->tempTables
[$key]['deprecatedIn'] ) ) {
634 wfDeprecated( __METHOD__
. " for $key", $this->tempTables
[$key]['deprecatedIn'] );
637 list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
639 $callback = function () {
643 return [ $fields, $callback ];
647 * Encode a Message as a PHP data structure
648 * @param Message $msg
651 protected static function encodeMessage( Message
$msg ) {
652 $key = count( $msg->getKeysToTry() ) > 1 ?
$msg->getKeysToTry() : $msg->getKey();
653 $params = $msg->getParams();
654 foreach ( $params as &$param ) {
655 if ( $param instanceof Message
) {
657 'message' => self
::encodeMessage( $param )
661 array_unshift( $params, $key );
666 * Decode a message that was encoded by self::encodeMessage()
670 protected static function decodeMessage( $data ) {
671 $key = array_shift( $data );
672 foreach ( $data as &$param ) {
673 if ( is_object( $param ) ) {
674 $param = (array)$param;
676 if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
677 $param = self
::decodeMessage( $param['message'] );
680 return new Message( $key, $data );
684 * Hashing function for comment storage
685 * @param string $text Comment text
686 * @param string|null $data Comment data
687 * @return int 32-bit signed integer
689 public static function hash( $text, $data ) {
690 $hash = crc32( $text ) ^
crc32( (string)$data );
692 // 64-bit PHP returns an unsigned CRC, change it to signed for
693 // insertion into the database.
694 if ( $hash >= 0x80000000 ) {