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 'stage' => MIGRATION_NEW
,
74 'deprecatedIn' => '1.32',
83 protected $key = null;
86 * @var int One of the MIGRATION_* constants
87 * @todo Deprecate and remove once extensions seem unlikely to need to use
88 * it for migration anymore.
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. Always
102 * MIGRATION_NEW for MediaWiki core since 1.33.
104 public function __construct( Language
$lang, $migrationStage ) {
105 $this->stage
= $migrationStage;
110 * Static constructor for easier chaining
111 * @deprecated in 1.31 Should not be constructed with a $key, use CommentStore::getStore
112 * @param string $key A key such as "rev_comment" identifying the comment
113 * field being fetched.
114 * @return CommentStore
116 public static function newKey( $key ) {
117 wfDeprecated( __METHOD__
, '1.31' );
118 $store = new CommentStore(
119 MediaWikiServices
::getInstance()->getContentLanguage(), MIGRATION_NEW
127 * @deprecated in 1.31 Use DI to inject a CommentStore instance into your class.
128 * @return CommentStore
130 public static function getStore() {
131 return MediaWikiServices
::getInstance()->getCommentStore();
135 * Compat method allowing use of self::newKey until removed.
136 * @param string|null $methodKey
137 * @throws InvalidArgumentException
140 private function getKey( $methodKey = null ) {
141 $key = $this->key ??
$methodKey;
142 if ( $key === null ) {
143 // @codeCoverageIgnoreStart
144 throw new InvalidArgumentException( '$key should not be null' );
145 // @codeCoverageIgnoreEnd
151 * Get SELECT fields for the comment key
153 * Each resulting row should be passed to `self::getCommentLegacy()` to get the
156 * @note Use of this method may require a subsequent database query to
157 * actually fetch the comment. If possible, use `self::getJoin()` instead.
160 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
161 * @param string|null $key A key such as "rev_comment" identifying the comment
162 * field being fetched.
163 * @return string[] to include in the `$vars` to `IDatabase->select()`. All
164 * fields are aliased, so `+` is safe to use.
166 public function getFields( $key = null ) {
167 $key = $this->getKey( $key );
169 if ( $this->stage
=== MIGRATION_OLD
) {
170 $fields["{$key}_text"] = $key;
171 $fields["{$key}_data"] = 'NULL';
172 $fields["{$key}_cid"] = 'NULL';
174 if ( $this->stage
< MIGRATION_NEW
) {
175 $fields["{$key}_old"] = $key;
178 $tempTableStage = isset( $this->tempTables
[$key] )
179 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
180 if ( $tempTableStage < MIGRATION_NEW
) {
181 $fields["{$key}_pk"] = $this->tempTables
[$key]['joinPK'];
183 if ( $tempTableStage > MIGRATION_OLD
) {
184 $fields["{$key}_id"] = "{$key}_id";
191 * Get SELECT fields and joins for the comment key
193 * Each resulting row should be passed to `self::getComment()` to get the
197 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
198 * @param string|null $key A key such as "rev_comment" identifying the comment
199 * field being fetched.
200 * @return array With three keys:
201 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
202 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
203 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
204 * All tables, fields, and joins are aliased, so `+` is safe to use.
206 public function getJoin( $key = null ) {
207 $key = $this->getKey( $key );
208 if ( !array_key_exists( $key, $this->joinCache
) ) {
213 if ( $this->stage
=== MIGRATION_OLD
) {
214 $fields["{$key}_text"] = $key;
215 $fields["{$key}_data"] = 'NULL';
216 $fields["{$key}_cid"] = 'NULL';
218 $join = $this->stage
=== MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN';
220 $tempTableStage = isset( $this->tempTables
[$key] )
221 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
222 if ( $tempTableStage < MIGRATION_NEW
) {
223 $t = $this->tempTables
[$key];
224 $alias = "temp_$key";
225 $tables[$alias] = $t['table'];
226 $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
227 if ( $tempTableStage === MIGRATION_OLD
) {
228 $joinField = "{$alias}.{$t['field']}";
230 // Nothing hits this code path for now, but will in the future when we set
231 // $this->tempTables['rev_comment']['stage'] to MIGRATION_WRITE_NEW while
232 // merging revision_comment_temp into revision.
233 // @codeCoverageIgnoreStart
234 $joins[$alias][0] = 'LEFT JOIN';
235 $joinField = "(CASE WHEN {$key}_id != 0 THEN {$key}_id ELSE {$alias}.{$t['field']} END)";
236 throw new LogicException( 'Nothing should reach this code path at this time' );
237 // @codeCoverageIgnoreEnd
240 $joinField = "{$key}_id";
243 $alias = "comment_$key";
244 $tables[$alias] = 'comment';
245 $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
247 if ( $this->stage
=== MIGRATION_NEW
) {
248 $fields["{$key}_text"] = "{$alias}.comment_text";
250 $fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
252 $fields["{$key}_data"] = "{$alias}.comment_data";
253 $fields["{$key}_cid"] = "{$alias}.comment_id";
256 $this->joinCache
[$key] = [
263 return $this->joinCache
[$key];
267 * Extract the comment from a row
269 * Shared implementation for getComment() and getCommentLegacy()
271 * @param IDatabase|null $db Database handle for getCommentLegacy(), or null for getComment()
272 * @param string $key A key such as "rev_comment" identifying the comment
273 * field being fetched.
274 * @param object|array $row
275 * @param bool $fallback
276 * @return CommentStoreComment
278 private function getCommentInternal( IDatabase
$db = null, $key, $row, $fallback = false ) {
280 if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
281 $cid = $row["{$key}_cid"] ??
null;
282 $text = $row["{$key}_text"];
283 $data = $row["{$key}_data"];
284 } elseif ( $this->stage
=== MIGRATION_OLD
) {
286 if ( $fallback && isset( $row[$key] ) ) {
287 wfLogWarning( "Using deprecated fallback handling for comment $key" );
290 wfLogWarning( "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD" );
295 $tempTableStage = isset( $this->tempTables
[$key] )
296 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
298 if ( $tempTableStage > MIGRATION_OLD
&& array_key_exists( "{$key}_id", $row ) ) {
300 throw new InvalidArgumentException(
301 "\$row does not contain fields needed for comment $key and getComment(), but "
302 . "does have fields for getCommentLegacy()"
305 $id = $row["{$key}_id"];
306 $row2 = $db->selectRow(
308 [ 'comment_id', 'comment_text', 'comment_data' ],
309 [ 'comment_id' => $id ],
313 if ( !$row2 && $tempTableStage < MIGRATION_NEW
&& array_key_exists( "{$key}_pk", $row ) ) {
315 throw new InvalidArgumentException(
316 "\$row does not contain fields needed for comment $key and getComment(), but "
317 . "does have fields for getCommentLegacy()"
320 $t = $this->tempTables
[$key];
321 $id = $row["{$key}_pk"];
322 $row2 = $db->selectRow(
323 [ $t['table'], 'comment' ],
324 [ 'comment_id', 'comment_text', 'comment_data' ],
328 [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
331 if ( $row2 === null && $fallback && isset( $row[$key] ) ) {
332 wfLogWarning( "Using deprecated fallback handling for comment $key" );
333 $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
335 if ( $row2 === null ) {
336 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
340 $cid = $row2->comment_id
;
341 $text = $row2->comment_text
;
342 $data = $row2->comment_data
;
343 } elseif ( $this->stage
< MIGRATION_NEW
&& array_key_exists( "{$key}_old", $row ) ) {
345 $text = $row["{$key}_old"];
348 // @codeCoverageIgnoreStart
349 wfLogWarning( "Missing comment row for $key, id=$id" );
353 // @codeCoverageIgnoreEnd
358 if ( $data !== null ) {
359 $data = FormatJson
::decode( $data, true );
360 if ( !is_array( $data ) ) {
361 // @codeCoverageIgnoreStart
362 wfLogWarning( "Invalid JSON object in comment: $data" );
364 // @codeCoverageIgnoreEnd
366 if ( isset( $data['_message'] ) ) {
367 $msg = self
::decodeMessage( $data['_message'] )
368 ->setInterfaceMessageFlag( true );
370 if ( !empty( $data['_null'] ) ) {
373 foreach ( $data as $k => $v ) {
374 if ( substr( $k, 0, 1 ) === '_' ) {
382 return new CommentStoreComment( $cid, $text, $msg, $data );
386 * Extract the comment from a row
388 * Use `self::getJoin()` to ensure the row contains the needed data.
390 * If you need to fake a comment in a row for some reason, set fields
391 * `{$key}_text` (string) and `{$key}_data` (JSON string or null).
394 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
395 * @param string $key A key such as "rev_comment" identifying the comment
396 * field being fetched.
397 * @param object|array|null $row Result row.
398 * @param bool $fallback If true, fall back as well as possible instead of throwing an exception.
399 * @return CommentStoreComment
401 public function getComment( $key, $row = null, $fallback = false ) {
402 // Compat for method sig change in 1.31 (introduction of $key)
403 if ( $this->key
!== null ) {
406 $key = $this->getKey();
408 if ( $row === null ) {
409 // @codeCoverageIgnoreStart
410 throw new InvalidArgumentException( '$row must not be null' );
411 // @codeCoverageIgnoreEnd
413 return $this->getCommentInternal( null, $key, $row, $fallback );
417 * Extract the comment from a row, with legacy lookups.
419 * If `$row` might have been generated using `self::getFields()` rather
420 * than `self::getJoin()`, use this. Prefer `self::getComment()` if you
421 * know callers used `self::getJoin()` for the row fetch.
423 * If you need to fake a comment in a row for some reason, set fields
424 * `{$key}_text` (string) and `{$key}_data` (JSON string or null).
427 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
428 * @param IDatabase $db Database handle to use for lookup
429 * @param string $key A key such as "rev_comment" identifying the comment
430 * field being fetched.
431 * @param object|array|null $row Result row.
432 * @param bool $fallback If true, fall back as well as possible instead of throwing an exception.
433 * @return CommentStoreComment
435 public function getCommentLegacy( IDatabase
$db, $key, $row = null, $fallback = false ) {
436 // Compat for method sig change in 1.31 (introduction of $key)
437 if ( $this->key
!== null ) {
440 $key = $this->getKey();
442 if ( $row === null ) {
443 // @codeCoverageIgnoreStart
444 throw new InvalidArgumentException( '$row must not be null' );
445 // @codeCoverageIgnoreEnd
447 return $this->getCommentInternal( $db, $key, $row, $fallback );
451 * Create a new CommentStoreComment, inserting it into the database if necessary
453 * If a comment is going to be passed to `self::insert()` or the like
454 * multiple times, it will be more efficient to pass a CommentStoreComment
455 * once rather than making `self::insert()` do it every time through.
457 * @note When passing a CommentStoreComment, this may set `$comment->id` if
458 * it's not already set. If `$comment->id` is already set, it will not be
459 * verified that the specified comment actually exists or that it
460 * corresponds to the comment text, message, and/or data in the
461 * CommentStoreComment.
462 * @param IDatabase $dbw Database handle to insert on. Unused if `$comment`
463 * is a CommentStoreComment and `$comment->id` is set.
464 * @param string|Message|CommentStoreComment $comment Comment text or Message object, or
465 * a CommentStoreComment.
466 * @param array|null $data Structured data to store. Keys beginning with '_' are reserved.
467 * Ignored if $comment is a CommentStoreComment.
468 * @return CommentStoreComment
470 public function createComment( IDatabase
$dbw, $comment, array $data = null ) {
471 $comment = CommentStoreComment
::newUnsavedComment( $comment, $data );
473 # Truncate comment in a Unicode-sensitive manner
474 $comment->text
= $this->lang
->truncateForVisual( $comment->text
, self
::COMMENT_CHARACTER_LIMIT
);
476 if ( $this->stage
> MIGRATION_OLD
&& !$comment->id
) {
477 $dbData = $comment->data
;
478 if ( !$comment->message
instanceof RawMessage
) {
479 if ( $dbData === null ) {
480 $dbData = [ '_null' => true ];
482 $dbData['_message'] = self
::encodeMessage( $comment->message
);
484 if ( $dbData !== null ) {
485 $dbData = FormatJson
::encode( (object)$dbData, false, FormatJson
::ALL_OK
);
486 $len = strlen( $dbData );
487 if ( $len > self
::MAX_DATA_LENGTH
) {
488 $max = self
::MAX_DATA_LENGTH
;
489 throw new OverflowException( "Comment data is too long ($len bytes, maximum is $max)" );
493 $hash = self
::hash( $comment->text
, $dbData );
494 $comment->id
= $dbw->selectField(
498 'comment_hash' => $hash,
499 'comment_text' => $comment->text
,
500 'comment_data' => $dbData,
504 if ( !$comment->id
) {
508 'comment_hash' => $hash,
509 'comment_text' => $comment->text
,
510 'comment_data' => $dbData,
514 $comment->id
= $dbw->insertId();
522 * Implementation for `self::insert()` and `self::insertWithTempTable()`
523 * @param IDatabase $dbw
524 * @param string $key A key such as "rev_comment" identifying the comment
525 * field being fetched.
526 * @param string|Message|CommentStoreComment $comment
527 * @param array|null $data
528 * @return array [ array $fields, callable $callback ]
530 private function insertInternal( IDatabase
$dbw, $key, $comment, $data ) {
534 $comment = $this->createComment( $dbw, $comment, $data );
536 if ( $this->stage
<= MIGRATION_WRITE_BOTH
) {
537 $fields[$key] = $this->lang
->truncateForDatabase( $comment->text
, 255 );
540 if ( $this->stage
>= MIGRATION_WRITE_BOTH
) {
541 $tempTableStage = isset( $this->tempTables
[$key] )
542 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
543 if ( $tempTableStage <= MIGRATION_WRITE_BOTH
) {
544 $t = $this->tempTables
[$key];
546 $commentId = $comment->id
;
547 $callback = function ( $id ) use ( $dbw, $commentId, $t, $func ) {
552 $t['field'] => $commentId,
558 if ( $tempTableStage >= MIGRATION_WRITE_BOTH
) {
559 $fields["{$key}_id"] = $comment->id
;
563 return [ $fields, $callback ];
567 * Insert a comment in preparation for a row that references it
569 * @note It's recommended to include both the call to this method and the
570 * row insert in the same transaction.
573 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
574 * @param IDatabase $dbw Database handle to insert on
575 * @param string $key A key such as "rev_comment" identifying the comment
576 * field being fetched.
577 * @param string|Message|CommentStoreComment|null $comment As for `self::createComment()`
578 * @param array|null $data As for `self::createComment()`
579 * @return array Fields for the insert or update
581 public function insert( IDatabase
$dbw, $key, $comment = null, $data = null ) {
582 // Compat for method sig change in 1.31 (introduction of $key)
583 if ( $this->key
!== null ) {
588 if ( $comment === null ) {
589 // @codeCoverageIgnoreStart
590 throw new InvalidArgumentException( '$comment can not be null' );
591 // @codeCoverageIgnoreEnd
594 $tempTableStage = isset( $this->tempTables
[$key] )
595 ?
$this->tempTables
[$key]['stage'] : MIGRATION_NEW
;
596 if ( $tempTableStage < MIGRATION_WRITE_NEW
) {
597 throw new InvalidArgumentException( "Must use insertWithTempTable() for $key" );
600 list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
605 * Insert a comment in a temporary table in preparation for a row that references it
607 * This is currently needed for "rev_comment" and "img_description". In the
608 * future that requirement will be removed.
610 * @note It's recommended to include both the call to this method and the
611 * row insert in the same transaction.
614 * @since 1.31 Method signature changed, $key parameter added (with deprecated back compat)
615 * @param IDatabase $dbw Database handle to insert on
616 * @param string $key A key such as "rev_comment" identifying the comment
617 * field being fetched.
618 * @param string|Message|CommentStoreComment|null $comment As for `self::createComment()`
619 * @param array|null $data As for `self::createComment()`
620 * @return array Two values:
621 * - array Fields for the insert or update
622 * - callable Function to call when the primary key of the row being
623 * inserted/updated is known. Pass it that primary key.
625 public function insertWithTempTable( IDatabase
$dbw, $key, $comment = null, $data = null ) {
626 // Compat for method sig change in 1.31 (introduction of $key)
627 if ( $this->key
!== null ) {
630 $key = $this->getKey();
632 if ( $comment === null ) {
633 // @codeCoverageIgnoreStart
634 throw new InvalidArgumentException( '$comment can not be null' );
635 // @codeCoverageIgnoreEnd
638 if ( !isset( $this->tempTables
[$key] ) ) {
639 throw new InvalidArgumentException( "Must use insert() for $key" );
640 } elseif ( isset( $this->tempTables
[$key]['deprecatedIn'] ) ) {
641 wfDeprecated( __METHOD__
. " for $key", $this->tempTables
[$key]['deprecatedIn'] );
644 list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
646 $callback = function () {
650 return [ $fields, $callback ];
654 * Encode a Message as a PHP data structure
655 * @param Message $msg
658 protected static function encodeMessage( Message
$msg ) {
659 $key = count( $msg->getKeysToTry() ) > 1 ?
$msg->getKeysToTry() : $msg->getKey();
660 $params = $msg->getParams();
661 foreach ( $params as &$param ) {
662 if ( $param instanceof Message
) {
664 'message' => self
::encodeMessage( $param )
668 array_unshift( $params, $key );
673 * Decode a message that was encoded by self::encodeMessage()
677 protected static function decodeMessage( $data ) {
678 $key = array_shift( $data );
679 foreach ( $data as &$param ) {
680 if ( is_object( $param ) ) {
681 $param = (array)$param;
683 if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
684 $param = self
::decodeMessage( $param['message'] );
687 return new Message( $key, $data );
691 * Hashing function for comment storage
692 * @param string $text Comment text
693 * @param string|null $data Comment data
694 * @return int 32-bit signed integer
696 public static function hash( $text, $data ) {
697 $hash = crc32( $text ) ^
crc32( (string)$data );
699 // 64-bit PHP returns an unsigned CRC, change it to signed for
700 // insertion into the database.
701 if ( $hash >= 0x80000000 ) {