Mostly drop old comment schemas
[lhc/web/wiklou.git] / includes / CommentStore.php
1 <?php
2 /**
3 * Manage storage of comments in the database
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 */
22
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\Rdbms\IDatabase;
25
26 /**
27 * CommentStore handles storage of comments (edit summaries, log reasons, etc)
28 * in the database.
29 * @since 1.30
30 */
31 class CommentStore {
32
33 /**
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 ).
36 */
37 const COMMENT_CHARACTER_LIMIT = 500;
38
39 /**
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.
43 */
44 const MAX_COMMENT_LENGTH = 65535;
45
46 /**
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.
50 */
51 const MAX_DATA_LENGTH = 65535;
52
53 /**
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
62 */
63 protected $tempTables = [
64 'rev_comment' => [
65 'table' => 'revision_comment_temp',
66 'pk' => 'revcomment_rev',
67 'field' => 'revcomment_comment_id',
68 'joinPK' => 'rev_id',
69 'stage' => MIGRATION_OLD,
70 'deprecatedIn' => null,
71 ],
72 'img_description' => [
73 'stage' => MIGRATION_NEW,
74 'deprecatedIn' => '1.32',
75 ],
76 ];
77
78 /**
79 * @since 1.30
80 * @deprecated in 1.31
81 * @var string|null
82 */
83 protected $key = null;
84
85 /**
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.
89 */
90 protected $stage;
91
92 /** @var array[] Cache for `self::getJoin()` */
93 protected $joinCache = [];
94
95 /** @var Language Language to use for comment truncation */
96 protected $lang;
97
98 /**
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.
103 */
104 public function __construct( Language $lang, $migrationStage ) {
105 $this->stage = $migrationStage;
106 $this->lang = $lang;
107 }
108
109 /**
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
115 */
116 public static function newKey( $key ) {
117 wfDeprecated( __METHOD__, '1.31' );
118 $store = new CommentStore(
119 MediaWikiServices::getInstance()->getContentLanguage(), MIGRATION_NEW
120 );
121 $store->key = $key;
122 return $store;
123 }
124
125 /**
126 * @since 1.31
127 * @deprecated in 1.31 Use DI to inject a CommentStore instance into your class.
128 * @return CommentStore
129 */
130 public static function getStore() {
131 return MediaWikiServices::getInstance()->getCommentStore();
132 }
133
134 /**
135 * Compat method allowing use of self::newKey until removed.
136 * @param string|null $methodKey
137 * @throws InvalidArgumentException
138 * @return string
139 */
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
146 }
147 return $key;
148 }
149
150 /**
151 * Get SELECT fields for the comment key
152 *
153 * Each resulting row should be passed to `self::getCommentLegacy()` to get the
154 * actual comment.
155 *
156 * @note Use of this method may require a subsequent database query to
157 * actually fetch the comment. If possible, use `self::getJoin()` instead.
158 *
159 * @since 1.30
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.
165 */
166 public function getFields( $key = null ) {
167 $key = $this->getKey( $key );
168 $fields = [];
169 if ( $this->stage === MIGRATION_OLD ) {
170 $fields["{$key}_text"] = $key;
171 $fields["{$key}_data"] = 'NULL';
172 $fields["{$key}_cid"] = 'NULL';
173 } else {
174 if ( $this->stage < MIGRATION_NEW ) {
175 $fields["{$key}_old"] = $key;
176 }
177
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'];
182 }
183 if ( $tempTableStage > MIGRATION_OLD ) {
184 $fields["{$key}_id"] = "{$key}_id";
185 }
186 }
187 return $fields;
188 }
189
190 /**
191 * Get SELECT fields and joins for the comment key
192 *
193 * Each resulting row should be passed to `self::getComment()` to get the
194 * actual comment.
195 *
196 * @since 1.30
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.
205 */
206 public function getJoin( $key = null ) {
207 $key = $this->getKey( $key );
208 if ( !array_key_exists( $key, $this->joinCache ) ) {
209 $tables = [];
210 $fields = [];
211 $joins = [];
212
213 if ( $this->stage === MIGRATION_OLD ) {
214 $fields["{$key}_text"] = $key;
215 $fields["{$key}_data"] = 'NULL';
216 $fields["{$key}_cid"] = 'NULL';
217 } else {
218 $join = $this->stage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN';
219
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']}";
229 } else {
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
238 }
239 } else {
240 $joinField = "{$key}_id";
241 }
242
243 $alias = "comment_$key";
244 $tables[$alias] = 'comment';
245 $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
246
247 if ( $this->stage === MIGRATION_NEW ) {
248 $fields["{$key}_text"] = "{$alias}.comment_text";
249 } else {
250 $fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
251 }
252 $fields["{$key}_data"] = "{$alias}.comment_data";
253 $fields["{$key}_cid"] = "{$alias}.comment_id";
254 }
255
256 $this->joinCache[$key] = [
257 'tables' => $tables,
258 'fields' => $fields,
259 'joins' => $joins,
260 ];
261 }
262
263 return $this->joinCache[$key];
264 }
265
266 /**
267 * Extract the comment from a row
268 *
269 * Shared implementation for getComment() and getCommentLegacy()
270 *
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
277 */
278 private function getCommentInternal( IDatabase $db = null, $key, $row, $fallback = false ) {
279 $row = (array)$row;
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 ) {
285 $cid = null;
286 if ( $fallback && isset( $row[$key] ) ) {
287 wfLogWarning( "Using deprecated fallback handling for comment $key" );
288 $text = $row[$key];
289 } else {
290 wfLogWarning( "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD" );
291 $text = '';
292 }
293 $data = null;
294 } else {
295 $tempTableStage = isset( $this->tempTables[$key] )
296 ? $this->tempTables[$key]['stage'] : MIGRATION_NEW;
297 $row2 = null;
298 if ( $tempTableStage > MIGRATION_OLD && array_key_exists( "{$key}_id", $row ) ) {
299 if ( !$db ) {
300 throw new InvalidArgumentException(
301 "\$row does not contain fields needed for comment $key and getComment(), but "
302 . "does have fields for getCommentLegacy()"
303 );
304 }
305 $id = $row["{$key}_id"];
306 $row2 = $db->selectRow(
307 'comment',
308 [ 'comment_id', 'comment_text', 'comment_data' ],
309 [ 'comment_id' => $id ],
310 __METHOD__
311 );
312 }
313 if ( !$row2 && $tempTableStage < MIGRATION_NEW && array_key_exists( "{$key}_pk", $row ) ) {
314 if ( !$db ) {
315 throw new InvalidArgumentException(
316 "\$row does not contain fields needed for comment $key and getComment(), but "
317 . "does have fields for getCommentLegacy()"
318 );
319 }
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' ],
325 [ $t['pk'] => $id ],
326 __METHOD__,
327 [],
328 [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
329 );
330 }
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 ];
334 }
335 if ( $row2 === null ) {
336 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
337 }
338
339 if ( $row2 ) {
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 ) ) {
344 $cid = null;
345 $text = $row["{$key}_old"];
346 $data = null;
347 } else {
348 // @codeCoverageIgnoreStart
349 wfLogWarning( "Missing comment row for $key, id=$id" );
350 $cid = null;
351 $text = '';
352 $data = null;
353 // @codeCoverageIgnoreEnd
354 }
355 }
356
357 $msg = null;
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" );
363 $data = null;
364 // @codeCoverageIgnoreEnd
365 } else {
366 if ( isset( $data['_message'] ) ) {
367 $msg = self::decodeMessage( $data['_message'] )
368 ->setInterfaceMessageFlag( true );
369 }
370 if ( !empty( $data['_null'] ) ) {
371 $data = null;
372 } else {
373 foreach ( $data as $k => $v ) {
374 if ( substr( $k, 0, 1 ) === '_' ) {
375 unset( $data[$k] );
376 }
377 }
378 }
379 }
380 }
381
382 return new CommentStoreComment( $cid, $text, $msg, $data );
383 }
384
385 /**
386 * Extract the comment from a row
387 *
388 * Use `self::getJoin()` to ensure the row contains the needed data.
389 *
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).
392 *
393 * @since 1.30
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
400 */
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 ) {
404 $fallback = $row;
405 $row = $key;
406 $key = $this->getKey();
407 }
408 if ( $row === null ) {
409 // @codeCoverageIgnoreStart
410 throw new InvalidArgumentException( '$row must not be null' );
411 // @codeCoverageIgnoreEnd
412 }
413 return $this->getCommentInternal( null, $key, $row, $fallback );
414 }
415
416 /**
417 * Extract the comment from a row, with legacy lookups.
418 *
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.
422 *
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).
425 *
426 * @since 1.30
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
434 */
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 ) {
438 $fallback = $row;
439 $row = $key;
440 $key = $this->getKey();
441 }
442 if ( $row === null ) {
443 // @codeCoverageIgnoreStart
444 throw new InvalidArgumentException( '$row must not be null' );
445 // @codeCoverageIgnoreEnd
446 }
447 return $this->getCommentInternal( $db, $key, $row, $fallback );
448 }
449
450 /**
451 * Create a new CommentStoreComment, inserting it into the database if necessary
452 *
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.
456 *
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
469 */
470 public function createComment( IDatabase $dbw, $comment, array $data = null ) {
471 $comment = CommentStoreComment::newUnsavedComment( $comment, $data );
472
473 # Truncate comment in a Unicode-sensitive manner
474 $comment->text = $this->lang->truncateForVisual( $comment->text, self::COMMENT_CHARACTER_LIMIT );
475
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 ];
481 }
482 $dbData['_message'] = self::encodeMessage( $comment->message );
483 }
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)" );
490 }
491 }
492
493 $hash = self::hash( $comment->text, $dbData );
494 $comment->id = $dbw->selectField(
495 'comment',
496 'comment_id',
497 [
498 'comment_hash' => $hash,
499 'comment_text' => $comment->text,
500 'comment_data' => $dbData,
501 ],
502 __METHOD__
503 );
504 if ( !$comment->id ) {
505 $dbw->insert(
506 'comment',
507 [
508 'comment_hash' => $hash,
509 'comment_text' => $comment->text,
510 'comment_data' => $dbData,
511 ],
512 __METHOD__
513 );
514 $comment->id = $dbw->insertId();
515 }
516 }
517
518 return $comment;
519 }
520
521 /**
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 ]
529 */
530 private function insertInternal( IDatabase $dbw, $key, $comment, $data ) {
531 $fields = [];
532 $callback = null;
533
534 $comment = $this->createComment( $dbw, $comment, $data );
535
536 if ( $this->stage <= MIGRATION_WRITE_BOTH ) {
537 $fields[$key] = $this->lang->truncateForDatabase( $comment->text, 255 );
538 }
539
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];
545 $func = __METHOD__;
546 $commentId = $comment->id;
547 $callback = function ( $id ) use ( $dbw, $commentId, $t, $func ) {
548 $dbw->insert(
549 $t['table'],
550 [
551 $t['pk'] => $id,
552 $t['field'] => $commentId,
553 ],
554 $func
555 );
556 };
557 }
558 if ( $tempTableStage >= MIGRATION_WRITE_BOTH ) {
559 $fields["{$key}_id"] = $comment->id;
560 }
561 }
562
563 return [ $fields, $callback ];
564 }
565
566 /**
567 * Insert a comment in preparation for a row that references it
568 *
569 * @note It's recommended to include both the call to this method and the
570 * row insert in the same transaction.
571 *
572 * @since 1.30
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
580 */
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 ) {
584 $data = $comment;
585 $comment = $key;
586 $key = $this->key;
587 }
588 if ( $comment === null ) {
589 // @codeCoverageIgnoreStart
590 throw new InvalidArgumentException( '$comment can not be null' );
591 // @codeCoverageIgnoreEnd
592 }
593
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" );
598 }
599
600 list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
601 return $fields;
602 }
603
604 /**
605 * Insert a comment in a temporary table in preparation for a row that references it
606 *
607 * This is currently needed for "rev_comment" and "img_description". In the
608 * future that requirement will be removed.
609 *
610 * @note It's recommended to include both the call to this method and the
611 * row insert in the same transaction.
612 *
613 * @since 1.30
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.
624 */
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 ) {
628 $data = $comment;
629 $comment = $key;
630 $key = $this->getKey();
631 }
632 if ( $comment === null ) {
633 // @codeCoverageIgnoreStart
634 throw new InvalidArgumentException( '$comment can not be null' );
635 // @codeCoverageIgnoreEnd
636 }
637
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'] );
642 }
643
644 list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
645 if ( !$callback ) {
646 $callback = function () {
647 // Do nothing.
648 };
649 }
650 return [ $fields, $callback ];
651 }
652
653 /**
654 * Encode a Message as a PHP data structure
655 * @param Message $msg
656 * @return array
657 */
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 ) {
663 $param = [
664 'message' => self::encodeMessage( $param )
665 ];
666 }
667 }
668 array_unshift( $params, $key );
669 return $params;
670 }
671
672 /**
673 * Decode a message that was encoded by self::encodeMessage()
674 * @param array $data
675 * @return Message
676 */
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;
682 }
683 if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
684 $param = self::decodeMessage( $param['message'] );
685 }
686 }
687 return new Message( $key, $data );
688 }
689
690 /**
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
695 */
696 public static function hash( $text, $data ) {
697 $hash = crc32( $text ) ^ crc32( (string)$data );
698
699 // 64-bit PHP returns an unsigned CRC, change it to signed for
700 // insertion into the database.
701 if ( $hash >= 0x80000000 ) {
702 $hash |= -1 << 32;
703 }
704
705 return $hash;
706 }
707
708 }