MediaWiki REL1_37
CommentStore.php
Go to the documentation of this file.
1<?php
23
43
48 public const COMMENT_CHARACTER_LIMIT = 500;
49
55 public const MAX_DATA_LENGTH = 65535;
56
67 protected const TEMP_TABLES = [
68 'rev_comment' => [
69 'table' => 'revision_comment_temp',
70 'pk' => 'revcomment_rev',
71 'field' => 'revcomment_comment_id',
72 'joinPK' => 'rev_id',
73 'stage' => MIGRATION_OLD,
74 'deprecatedIn' => null,
75 ],
76 'img_description' => [
77 'stage' => MIGRATION_NEW,
78 'deprecatedIn' => '1.32',
79 ],
80 ];
81
88 private $stage;
89
91 private $joinCache = [];
92
94 private $lang;
95
103 public function __construct( Language $lang, $stage ) {
104 if ( ( $stage & SCHEMA_COMPAT_WRITE_BOTH ) === 0 ) {
105 throw new InvalidArgumentException( '$stage must include a write mode' );
106 }
107 if ( ( $stage & SCHEMA_COMPAT_READ_BOTH ) === 0 ) {
108 throw new InvalidArgumentException( '$stage must include a read mode' );
109 }
110
111 $this->stage = $stage;
112 $this->lang = $lang;
113 }
114
120 public static function getStore() {
121 return MediaWikiServices::getInstance()->getCommentStore();
122 }
123
140 public function getFields( $key ) {
141 $fields = [];
142 if ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
143 $fields["{$key}_text"] = $key;
144 $fields["{$key}_data"] = 'NULL';
145 $fields["{$key}_cid"] = 'NULL';
146 } else { // READ_BOTH or READ_NEW
147 if ( $this->stage & SCHEMA_COMPAT_READ_OLD ) {
148 $fields["{$key}_old"] = $key;
149 }
150
151 $tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
152 if ( $tempTableStage & SCHEMA_COMPAT_READ_OLD ) {
153 $fields["{$key}_pk"] = static::TEMP_TABLES[$key]['joinPK'];
154 }
155 if ( $tempTableStage & SCHEMA_COMPAT_READ_NEW ) {
156 $fields["{$key}_id"] = "{$key}_id";
157 }
158 }
159 return $fields;
160 }
161
179 public function getJoin( $key ) {
180 if ( !array_key_exists( $key, $this->joinCache ) ) {
181 $tables = [];
182 $fields = [];
183 $joins = [];
184
185 if ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
186 $fields["{$key}_text"] = $key;
187 $fields["{$key}_data"] = 'NULL';
188 $fields["{$key}_cid"] = 'NULL';
189 } else { // READ_BOTH or READ_NEW
190 $join = ( $this->stage & SCHEMA_COMPAT_READ_OLD ) ? 'LEFT JOIN' : 'JOIN';
191
192 $tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
193 if ( $tempTableStage & SCHEMA_COMPAT_READ_OLD ) {
194 $t = static::TEMP_TABLES[$key];
195 $alias = "temp_$key";
196 $tables[$alias] = $t['table'];
197 $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
198 if ( ( $tempTableStage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
199 $joinField = "{$alias}.{$t['field']}";
200 } else {
201 // Nothing hits this code path for now, but will in the future when we set
202 // static::TEMP_TABLES['rev_comment']['stage'] to MIGRATION_WRITE_NEW while
203 // merging revision_comment_temp into revision.
204 // @codeCoverageIgnoreStart
205 $joins[$alias][0] = 'LEFT JOIN';
206 $joinField = "(CASE WHEN {$key}_id != 0 THEN {$key}_id ELSE {$alias}.{$t['field']} END)";
207 throw new LogicException( 'Nothing should reach this code path at this time' );
208 // @codeCoverageIgnoreEnd
209 }
210 } else {
211 $joinField = "{$key}_id";
212 }
213
214 $alias = "comment_$key";
215 $tables[$alias] = 'comment';
216 $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
217
218 if ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_NEW ) {
219 $fields["{$key}_text"] = "{$alias}.comment_text";
220 } else {
221 $fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
222 }
223 $fields["{$key}_data"] = "{$alias}.comment_data";
224 $fields["{$key}_cid"] = "{$alias}.comment_id";
225 }
226
227 $this->joinCache[$key] = [
228 'tables' => $tables,
229 'fields' => $fields,
230 'joins' => $joins,
231 ];
232 }
233
234 return $this->joinCache[$key];
235 }
236
249 private function getCommentInternal( ?IDatabase $db, $key, $row, $fallback = false ) {
250 $row = (array)$row;
251 if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
252 $cid = $row["{$key}_cid"] ?? null;
253 $text = $row["{$key}_text"];
254 $data = $row["{$key}_data"];
255 } elseif ( ( $this->stage & SCHEMA_COMPAT_READ_BOTH ) === SCHEMA_COMPAT_READ_OLD ) {
256 $cid = null;
257 if ( $fallback && isset( $row[$key] ) ) {
258 wfLogWarning( "Using deprecated fallback handling for comment $key" );
259 $text = $row[$key];
260 } else {
262 "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD / READ_OLD"
263 );
264 $text = '';
265 }
266 $data = null;
267 } else {
268 $tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
269 $row2 = null;
270 if ( ( $tempTableStage & SCHEMA_COMPAT_READ_NEW ) && array_key_exists( "{$key}_id", $row ) ) {
271 if ( !$db ) {
272 throw new InvalidArgumentException(
273 "\$row does not contain fields needed for comment $key and getComment(), but "
274 . "does have fields for getCommentLegacy()"
275 );
276 }
277 $id = $row["{$key}_id"];
278 $row2 = $db->selectRow(
279 'comment',
280 [ 'comment_id', 'comment_text', 'comment_data' ],
281 [ 'comment_id' => $id ],
282 __METHOD__
283 );
284 }
285 if ( !$row2 && ( $tempTableStage & SCHEMA_COMPAT_READ_OLD ) &&
286 array_key_exists( "{$key}_pk", $row )
287 ) {
288 if ( !$db ) {
289 throw new InvalidArgumentException(
290 "\$row does not contain fields needed for comment $key and getComment(), but "
291 . "does have fields for getCommentLegacy()"
292 );
293 }
294 $t = static::TEMP_TABLES[$key];
295 $id = $row["{$key}_pk"];
296 $row2 = $db->selectRow(
297 [ $t['table'], 'comment' ],
298 [ 'comment_id', 'comment_text', 'comment_data' ],
299 [ $t['pk'] => $id ],
300 __METHOD__,
301 [],
302 [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
303 );
304 }
305 if ( $row2 === null && $fallback && isset( $row[$key] ) ) {
306 wfLogWarning( "Using deprecated fallback handling for comment $key" );
307 $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
308 }
309 if ( $row2 === null ) {
310 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
311 }
312
313 if ( $row2 ) {
314 $cid = $row2->comment_id;
315 $text = $row2->comment_text;
316 $data = $row2->comment_data;
317 } elseif ( ( $this->stage & SCHEMA_COMPAT_READ_OLD ) &&
318 array_key_exists( "{$key}_old", $row )
319 ) {
320 $cid = null;
321 $text = $row["{$key}_old"];
322 $data = null;
323 } else {
324 // @codeCoverageIgnoreStart
325 wfLogWarning( "Missing comment row for $key, id=$id" );
326 $cid = null;
327 $text = '';
328 $data = null;
329 // @codeCoverageIgnoreEnd
330 }
331 }
332
333 $msg = null;
334 if ( $data !== null ) {
335 $data = FormatJson::decode( $data, true );
336 if ( !is_array( $data ) ) {
337 // @codeCoverageIgnoreStart
338 wfLogWarning( "Invalid JSON object in comment: $data" );
339 $data = null;
340 // @codeCoverageIgnoreEnd
341 } else {
342 if ( isset( $data['_message'] ) ) {
343 $msg = self::decodeMessage( $data['_message'] )
344 ->setInterfaceMessageFlag( true );
345 }
346 if ( !empty( $data['_null'] ) ) {
347 $data = null;
348 } else {
349 foreach ( $data as $k => $v ) {
350 if ( substr( $k, 0, 1 ) === '_' ) {
351 unset( $data[$k] );
352 }
353 }
354 }
355 }
356 }
357
358 return new CommentStoreComment( $cid, $text, $msg, $data );
359 }
360
377 public function getComment( $key, $row = null, $fallback = false ) {
378 if ( $row === null ) {
379 // @codeCoverageIgnoreStart
380 throw new InvalidArgumentException( '$row must not be null' );
381 // @codeCoverageIgnoreEnd
382 }
383 return $this->getCommentInternal( null, $key, $row, $fallback );
384 }
385
405 public function getCommentLegacy( IDatabase $db, $key, $row = null, $fallback = false ) {
406 if ( $row === null ) {
407 // @codeCoverageIgnoreStart
408 throw new InvalidArgumentException( '$row must not be null' );
409 // @codeCoverageIgnoreEnd
410 }
411 return $this->getCommentInternal( $db, $key, $row, $fallback );
412 }
413
434 public function createComment( IDatabase $dbw, $comment, array $data = null ) {
435 $comment = CommentStoreComment::newUnsavedComment( $comment, $data );
436
437 # Truncate comment in a Unicode-sensitive manner
438 $comment->text = $this->lang->truncateForVisual( $comment->text, self::COMMENT_CHARACTER_LIMIT );
439
440 if ( ( $this->stage & SCHEMA_COMPAT_WRITE_NEW ) && !$comment->id ) {
441 $dbData = $comment->data;
442 if ( !$comment->message instanceof RawMessage ) {
443 if ( $dbData === null ) {
444 $dbData = [ '_null' => true ];
445 }
446 $dbData['_message'] = self::encodeMessage( $comment->message );
447 }
448 if ( $dbData !== null ) {
449 $dbData = FormatJson::encode( (object)$dbData, false, FormatJson::ALL_OK );
450 $len = strlen( $dbData );
451 if ( $len > self::MAX_DATA_LENGTH ) {
452 $max = self::MAX_DATA_LENGTH;
453 throw new OverflowException( "Comment data is too long ($len bytes, maximum is $max)" );
454 }
455 }
456
457 $hash = self::hash( $comment->text, $dbData );
458 $commentId = $dbw->selectField(
459 'comment',
460 'comment_id',
461 [
462 'comment_hash' => $hash,
463 'comment_text' => $comment->text,
464 'comment_data' => $dbData,
465 ],
466 __METHOD__
467 );
468 if ( !$commentId ) {
469 $dbw->insert(
470 'comment',
471 [
472 'comment_hash' => $hash,
473 'comment_text' => $comment->text,
474 'comment_data' => $dbData,
475 ],
476 __METHOD__
477 );
478 $commentId = $dbw->insertId();
479 }
480 $comment->id = (int)$commentId;
481 }
482
483 return $comment;
484 }
485
495 private function insertInternal( IDatabase $dbw, $key, $comment, $data ) {
496 $fields = [];
497 $callback = null;
498
499 $comment = $this->createComment( $dbw, $comment, $data );
500
501 if ( $this->stage & SCHEMA_COMPAT_WRITE_OLD ) {
502 $fields[$key] = $this->lang->truncateForDatabase( $comment->text, 255 );
503 }
504
505 if ( $this->stage & SCHEMA_COMPAT_WRITE_NEW ) {
506 $tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
507 if ( $tempTableStage & SCHEMA_COMPAT_WRITE_OLD ) {
508 $t = static::TEMP_TABLES[$key];
509 $func = __METHOD__;
510 $commentId = $comment->id;
511 $callback = static function ( $id ) use ( $dbw, $commentId, $t, $func ) {
512 $dbw->insert(
513 $t['table'],
514 [
515 $t['pk'] => $id,
516 $t['field'] => $commentId,
517 ],
518 $func
519 );
520 };
521 }
522 if ( $tempTableStage & SCHEMA_COMPAT_WRITE_NEW ) {
523 $fields["{$key}_id"] = $comment->id;
524 }
525 }
526
527 return [ $fields, $callback ];
528 }
529
545 public function insert( IDatabase $dbw, $key, $comment = null, $data = null ) {
546 if ( $comment === null ) {
547 // @codeCoverageIgnoreStart
548 throw new InvalidArgumentException( '$comment can not be null' );
549 // @codeCoverageIgnoreEnd
550 }
551
552 $tempTableStage = static::TEMP_TABLES[$key]['stage'] ?? MIGRATION_NEW;
553 if ( $tempTableStage & SCHEMA_COMPAT_WRITE_OLD ) {
554 throw new InvalidArgumentException( "Must use insertWithTempTable() for $key" );
555 }
556
557 list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
558 return $fields;
559 }
560
582 public function insertWithTempTable( IDatabase $dbw, $key, $comment = null, $data = null ) {
583 if ( $comment === null ) {
584 // @codeCoverageIgnoreStart
585 throw new InvalidArgumentException( '$comment can not be null' );
586 // @codeCoverageIgnoreEnd
587 }
588
589 if ( !isset( static::TEMP_TABLES[$key] ) ) {
590 throw new InvalidArgumentException( "Must use insert() for $key" );
591 } elseif ( isset( static::TEMP_TABLES[$key]['deprecatedIn'] ) ) {
592 wfDeprecated( __METHOD__ . " for $key", static::TEMP_TABLES[$key]['deprecatedIn'] );
593 }
594
595 list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
596 if ( !$callback ) {
597 $callback = static function () {
598 // Do nothing.
599 };
600 }
601 return [ $fields, $callback ];
602 }
603
609 private static function encodeMessage( Message $msg ) {
610 $key = count( $msg->getKeysToTry() ) > 1 ? $msg->getKeysToTry() : $msg->getKey();
611 $params = $msg->getParams();
612 foreach ( $params as &$param ) {
613 if ( $param instanceof Message ) {
614 $param = [
615 'message' => self::encodeMessage( $param )
616 ];
617 }
618 }
619 array_unshift( $params, $key );
620 return $params;
621 }
622
628 private static function decodeMessage( $data ) {
629 $key = array_shift( $data );
630 foreach ( $data as &$param ) {
631 if ( is_object( $param ) ) {
632 $param = (array)$param;
633 }
634 if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
635 $param = self::decodeMessage( $param['message'] );
636 }
637 }
638 return new Message( $key, $data );
639 }
640
647 public static function hash( $text, $data ) {
648 $hash = crc32( $text ) ^ crc32( (string)$data );
649
650 // 64-bit PHP returns an unsigned CRC, change it to signed for
651 // insertion into the database.
652 if ( $hash >= 0x80000000 ) {
653 $hash |= -1 << 32;
654 }
655
656 return $hash;
657 }
658
659}
const SCHEMA_COMPAT_WRITE_BOTH
Definition Defines.php:270
const SCHEMA_COMPAT_READ_NEW
Definition Defines.php:267
const SCHEMA_COMPAT_READ_BOTH
Definition Defines.php:273
const SCHEMA_COMPAT_WRITE_OLD
Definition Defines.php:262
const SCHEMA_COMPAT_READ_OLD
Definition Defines.php:263
const MIGRATION_NEW
Definition Defines.php:303
const SCHEMA_COMPAT_WRITE_NEW
Definition Defines.php:266
const MIGRATION_OLD
Definition Defines.php:300
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
$fallback
Value object for a comment stored by CommentStore.
Handle database storage of comments such as edit summaries and log reasons.
getFields( $key)
Get SELECT fields for the comment key.
int $stage
One of the MIGRATION_* constants, or an appropriate combination of SCHEMA_COMPAT_* constants.
getComment( $key, $row=null, $fallback=false)
Extract the comment from a row.
createComment(IDatabase $dbw, $comment, array $data=null)
Create a new CommentStoreComment, inserting it into the database if necessary.
insertWithTempTable(IDatabase $dbw, $key, $comment=null, $data=null)
Insert a comment in a temporary table in preparation for a row that references it.
__construct(Language $lang, $stage)
getCommentLegacy(IDatabase $db, $key, $row=null, $fallback=false)
Extract the comment from a row, with legacy lookups.
static hash( $text, $data)
Hashing function for comment storage.
getCommentInternal(?IDatabase $db, $key, $row, $fallback=false)
Extract the comment from a row.
insertInternal(IDatabase $dbw, $key, $comment, $data)
Implementation for self::insert() and self::insertWithTempTable()
Language $lang
Language to use for comment truncation.
static decodeMessage( $data)
Decode a message that was encoded by self::encodeMessage()
const TEMP_TABLES
Define fields that use temporary tables for transitional purposes Array keys are field names,...
array[] $joinCache
Cache for self::getJoin()
static encodeMessage(Message $msg)
Encode a Message as a PHP data structure.
insert(IDatabase $dbw, $key, $comment=null, $data=null)
Insert a comment in preparation for a row that references it.
const MAX_DATA_LENGTH
Maximum length of serialized data in bytes.
static getStore()
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
getJoin( $key)
Get SELECT fields and joins for the comment key.
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition Language.php:42
MediaWikiServices is the service locator for the application scope of MediaWiki.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:138
getParams()
Returns the message parameters.
Definition Message.php:368
getKeysToTry()
Definition Message.php:342
getKey()
Returns the message key.
Definition Message.php:357
Variant of the Message class.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
insert( $table, $rows, $fname=__METHOD__, $options=[])
Insert the given row(s) into a table.
insertId()
Get the inserted value of an auto-increment row.
return true
Definition router.php:92
if(!isset( $args[0])) $lang