MediaWiki REL1_31
CommentStore.php
Go to the documentation of this file.
1<?php
25
32
38
44 const MAX_COMMENT_LENGTH = 65535;
45
51 const MAX_DATA_LENGTH = 65535;
52
61 protected static $tempTables = [
62 'rev_comment' => [
63 'table' => 'revision_comment_temp',
64 'pk' => 'revcomment_rev',
65 'field' => 'revcomment_comment_id',
66 'joinPK' => 'rev_id',
67 ],
68 'img_description' => [
69 'table' => 'image_comment_temp',
70 'pk' => 'imgcomment_name',
71 'field' => 'imgcomment_description_id',
72 'joinPK' => 'img_name',
73 ],
74 ];
75
81 protected static $formerTempTables = [];
82
88 protected $key = null;
89
91 protected $stage;
92
94 protected $joinCache = [];
95
97 protected $lang;
98
104 public function __construct( Language $lang, $migrationStage ) {
105 $this->stage = $migrationStage;
106 $this->lang = $lang;
107 }
108
116 public static function newKey( $key ) {
118 // TODO uncomment once not used in extensions
119 // wfDeprecated( __METHOD__, '1.31' );
121 $store->key = $key;
122 return $store;
123 }
124
130 public static function getStore() {
131 return MediaWikiServices::getInstance()->getCommentStore();
132 }
133
140 private function getKey( $methodKey = null ) {
141 $key = $this->key !== null ? $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
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 if ( isset( self::$tempTables[$key] ) ) {
178 $fields["{$key}_pk"] = self::$tempTables[$key]['joinPK'];
179 } else {
180 $fields["{$key}_id"] = "{$key}_id";
181 }
182 }
183 return $fields;
184 }
185
202 public function getJoin( $key = null ) {
203 $key = $this->getKey( $key );
204 if ( !array_key_exists( $key, $this->joinCache ) ) {
205 $tables = [];
206 $fields = [];
207 $joins = [];
208
209 if ( $this->stage === MIGRATION_OLD ) {
210 $fields["{$key}_text"] = $key;
211 $fields["{$key}_data"] = 'NULL';
212 $fields["{$key}_cid"] = 'NULL';
213 } else {
214 $join = $this->stage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN';
215
216 if ( isset( self::$tempTables[$key] ) ) {
217 $t = self::$tempTables[$key];
218 $alias = "temp_$key";
219 $tables[$alias] = $t['table'];
220 $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
221 $joinField = "{$alias}.{$t['field']}";
222 } else {
223 $joinField = "{$key}_id";
224 }
225
226 $alias = "comment_$key";
227 $tables[$alias] = 'comment';
228 $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
229
230 if ( $this->stage === MIGRATION_NEW ) {
231 $fields["{$key}_text"] = "{$alias}.comment_text";
232 } else {
233 $fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
234 }
235 $fields["{$key}_data"] = "{$alias}.comment_data";
236 $fields["{$key}_cid"] = "{$alias}.comment_id";
237 }
238
239 $this->joinCache[$key] = [
240 'tables' => $tables,
241 'fields' => $fields,
242 'joins' => $joins,
243 ];
244 }
245
246 return $this->joinCache[$key];
247 }
248
261 private function getCommentInternal( IDatabase $db = null, $key, $row, $fallback = false ) {
262 $row = (array)$row;
263 if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
264 $cid = isset( $row["{$key}_cid"] ) ? $row["{$key}_cid"] : null;
265 $text = $row["{$key}_text"];
266 $data = $row["{$key}_data"];
267 } elseif ( $this->stage === MIGRATION_OLD ) {
268 $cid = null;
269 if ( $fallback && isset( $row[$key] ) ) {
270 wfLogWarning( "Using deprecated fallback handling for comment $key" );
271 $text = $row[$key];
272 } else {
273 wfLogWarning( "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD" );
274 $text = '';
275 }
276 $data = null;
277 } else {
278 if ( isset( self::$tempTables[$key] ) ) {
279 if ( array_key_exists( "{$key}_pk", $row ) ) {
280 if ( !$db ) {
281 throw new InvalidArgumentException(
282 "\$row does not contain fields needed for comment $key and getComment(), but "
283 . "does have fields for getCommentLegacy()"
284 );
285 }
286 $t = self::$tempTables[$key];
287 $id = $row["{$key}_pk"];
288 $row2 = $db->selectRow(
289 [ $t['table'], 'comment' ],
290 [ 'comment_id', 'comment_text', 'comment_data' ],
291 [ $t['pk'] => $id ],
292 __METHOD__,
293 [],
294 [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
295 );
296 } elseif ( $fallback && isset( $row[$key] ) ) {
297 wfLogWarning( "Using deprecated fallback handling for comment $key" );
298 $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
299 } else {
300 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
301 }
302 } else {
303 if ( array_key_exists( "{$key}_id", $row ) ) {
304 if ( !$db ) {
305 throw new InvalidArgumentException(
306 "\$row does not contain fields needed for comment $key and getComment(), but "
307 . "does have fields for getCommentLegacy()"
308 );
309 }
310 $id = $row["{$key}_id"];
311 $row2 = $db->selectRow(
312 'comment',
313 [ 'comment_id', 'comment_text', 'comment_data' ],
314 [ 'comment_id' => $id ],
315 __METHOD__
316 );
317 } elseif ( $fallback && isset( $row[$key] ) ) {
318 wfLogWarning( "Using deprecated fallback handling for comment $key" );
319 $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
320 } else {
321 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
322 }
323 }
324
325 if ( $row2 ) {
326 $cid = $row2->comment_id;
327 $text = $row2->comment_text;
328 $data = $row2->comment_data;
329 } elseif ( $this->stage < MIGRATION_NEW && array_key_exists( "{$key}_old", $row ) ) {
330 $cid = null;
331 $text = $row["{$key}_old"];
332 $data = null;
333 } else {
334 // @codeCoverageIgnoreStart
335 wfLogWarning( "Missing comment row for $key, id=$id" );
336 $cid = null;
337 $text = '';
338 $data = null;
339 // @codeCoverageIgnoreEnd
340 }
341 }
342
343 $msg = null;
344 if ( $data !== null ) {
345 $data = FormatJson::decode( $data );
346 if ( !is_object( $data ) ) {
347 // @codeCoverageIgnoreStart
348 wfLogWarning( "Invalid JSON object in comment: $data" );
349 $data = null;
350 // @codeCoverageIgnoreEnd
351 } else {
352 $data = (array)$data;
353 if ( isset( $data['_message'] ) ) {
354 $msg = self::decodeMessage( $data['_message'] )
355 ->setInterfaceMessageFlag( true );
356 }
357 if ( !empty( $data['_null'] ) ) {
358 $data = null;
359 } else {
360 foreach ( $data as $k => $v ) {
361 if ( substr( $k, 0, 1 ) === '_' ) {
362 unset( $data[$k] );
363 }
364 }
365 }
366 }
367 }
368
369 return new CommentStoreComment( $cid, $text, $msg, $data );
370 }
371
388 public function getComment( $key, $row = null, $fallback = false ) {
389 // Compat for method sig change in 1.31 (introduction of $key)
390 if ( $this->key !== null ) {
391 $fallback = $row;
392 $row = $key;
393 $key = $this->getKey();
394 }
395 if ( $row === null ) {
396 // @codeCoverageIgnoreStart
397 throw new InvalidArgumentException( '$row must not be null' );
398 // @codeCoverageIgnoreEnd
399 }
400 return $this->getCommentInternal( null, $key, $row, $fallback );
401 }
402
422 public function getCommentLegacy( IDatabase $db, $key, $row = null, $fallback = false ) {
423 // Compat for method sig change in 1.31 (introduction of $key)
424 if ( $this->key !== null ) {
425 $fallback = $row;
426 $row = $key;
427 $key = $this->getKey();
428 }
429 if ( $row === null ) {
430 // @codeCoverageIgnoreStart
431 throw new InvalidArgumentException( '$row must not be null' );
432 // @codeCoverageIgnoreEnd
433 }
434 return $this->getCommentInternal( $db, $key, $row, $fallback );
435 }
436
457 public function createComment( IDatabase $dbw, $comment, array $data = null ) {
458 $comment = CommentStoreComment::newUnsavedComment( $comment, $data );
459
460 # Truncate comment in a Unicode-sensitive manner
461 $comment->text = $this->lang->truncate( $comment->text, self::MAX_COMMENT_LENGTH );
462 if ( mb_strlen( $comment->text, 'UTF-8' ) > self::COMMENT_CHARACTER_LIMIT ) {
463 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this->lang )->escaped();
464 if ( mb_strlen( $ellipsis ) >= self::COMMENT_CHARACTER_LIMIT ) {
465 // WTF?
466 $ellipsis = '...';
467 }
468 $maxLength = self::COMMENT_CHARACTER_LIMIT - mb_strlen( $ellipsis, 'UTF-8' );
469 $comment->text = mb_substr( $comment->text, 0, $maxLength, 'UTF-8' ) . $ellipsis;
470 }
471
472 if ( $this->stage > MIGRATION_OLD && !$comment->id ) {
473 $dbData = $comment->data;
474 if ( !$comment->message instanceof RawMessage ) {
475 if ( $dbData === null ) {
476 $dbData = [ '_null' => true ];
477 }
478 $dbData['_message'] = self::encodeMessage( $comment->message );
479 }
480 if ( $dbData !== null ) {
481 $dbData = FormatJson::encode( (object)$dbData, false, FormatJson::ALL_OK );
482 $len = strlen( $dbData );
483 if ( $len > self::MAX_DATA_LENGTH ) {
484 $max = self::MAX_DATA_LENGTH;
485 throw new OverflowException( "Comment data is too long ($len bytes, maximum is $max)" );
486 }
487 }
488
489 $hash = self::hash( $comment->text, $dbData );
490 $comment->id = $dbw->selectField(
491 'comment',
492 'comment_id',
493 [
494 'comment_hash' => $hash,
495 'comment_text' => $comment->text,
496 'comment_data' => $dbData,
497 ],
498 __METHOD__
499 );
500 if ( !$comment->id ) {
501 $dbw->insert(
502 'comment',
503 [
504 'comment_hash' => $hash,
505 'comment_text' => $comment->text,
506 'comment_data' => $dbData,
507 ],
508 __METHOD__
509 );
510 $comment->id = $dbw->insertId();
511 }
512 }
513
514 return $comment;
515 }
516
526 private function insertInternal( IDatabase $dbw, $key, $comment, $data ) {
527 $fields = [];
528 $callback = null;
529
530 $comment = $this->createComment( $dbw, $comment, $data );
531
532 if ( $this->stage <= MIGRATION_WRITE_BOTH ) {
533 $fields[$key] = $this->lang->truncate( $comment->text, 255 );
534 }
535
536 if ( $this->stage >= MIGRATION_WRITE_BOTH ) {
537 if ( isset( self::$tempTables[$key] ) ) {
538 $t = self::$tempTables[$key];
539 $func = __METHOD__;
540 $commentId = $comment->id;
541 $callback = function ( $id ) use ( $dbw, $commentId, $t, $func ) {
542 $dbw->insert(
543 $t['table'],
544 [
545 $t['pk'] => $id,
546 $t['field'] => $commentId,
547 ],
548 $func
549 );
550 };
551 } else {
552 $fields["{$key}_id"] = $comment->id;
553 }
554 }
555
556 return [ $fields, $callback ];
557 }
558
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 ) {
577 $data = $comment;
578 $comment = $key;
579 $key = $this->key;
580 }
581 if ( $comment === null ) {
582 // @codeCoverageIgnoreStart
583 throw new InvalidArgumentException( '$comment can not be null' );
584 // @codeCoverageIgnoreEnd
585 }
586
587 if ( isset( self::$tempTables[$key] ) ) {
588 throw new InvalidArgumentException( "Must use insertWithTempTable() for $key" );
589 }
590
591 list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
592 return $fields;
593 }
594
616 public function insertWithTempTable( IDatabase $dbw, $key, $comment = null, $data = null ) {
617 // Compat for method sig change in 1.31 (introduction of $key)
618 if ( $this->key !== null ) {
619 $data = $comment;
620 $comment = $key;
621 $key = $this->getKey();
622 }
623 if ( $comment === null ) {
624 // @codeCoverageIgnoreStart
625 throw new InvalidArgumentException( '$comment can not be null' );
626 // @codeCoverageIgnoreEnd
627 }
628
629 if ( isset( self::$formerTempTables[$key] ) ) {
630 wfDeprecated( __METHOD__ . " for $key", self::$formerTempTables[$key] );
631 } elseif ( !isset( self::$tempTables[$key] ) ) {
632 throw new InvalidArgumentException( "Must use insert() for $key" );
633 }
634
635 list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
636 if ( !$callback ) {
637 $callback = function () {
638 // Do nothing.
639 };
640 }
641 return [ $fields, $callback ];
642 }
643
649 protected static function encodeMessage( Message $msg ) {
650 $key = count( $msg->getKeysToTry() ) > 1 ? $msg->getKeysToTry() : $msg->getKey();
651 $params = $msg->getParams();
652 foreach ( $params as &$param ) {
653 if ( $param instanceof Message ) {
654 $param = [
655 'message' => self::encodeMessage( $param )
656 ];
657 }
658 }
659 array_unshift( $params, $key );
660 return $params;
661 }
662
668 protected static function decodeMessage( $data ) {
669 $key = array_shift( $data );
670 foreach ( $data as &$param ) {
671 if ( is_object( $param ) ) {
672 $param = (array)$param;
673 }
674 if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
675 $param = self::decodeMessage( $param['message'] );
676 }
677 }
678 return new Message( $key, $data );
679 }
680
687 public static function hash( $text, $data ) {
688 $hash = crc32( $text ) ^ crc32( (string)$data );
689
690 // 64-bit PHP returns an unsigned CRC, change it to signed for
691 // insertion into the database.
692 if ( $hash >= 0x80000000 ) {
693 $hash |= -1 << 32;
694 }
695
696 return $hash;
697 }
698
699}
int $wgCommentTableSchemaMigrationStage
Comment table schema migration stage.
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)
Throws a warning that $function is deprecated.
$fallback
CommentStoreComment represents a comment stored by CommentStore.
CommentStore handles storage of comments (edit summaries, log reasons, etc) in the database.
int $stage
One of the MIGRATION_* constants.
static newKey( $key)
Static constructor for easier chaining.
getKey( $methodKey=null)
Compat method allowing use of self::newKey until removed.
getComment( $key, $row=null, $fallback=false)
Extract the comment from a row.
__construct(Language $lang, $migrationStage)
getJoin( $key=null)
Get SELECT fields and joins for the comment key.
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.
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.
getFields( $key=null)
Get SELECT fields for the comment key.
insertInternal(IDatabase $dbw, $key, $comment, $data)
Implementation for self::insert() and self::insertWithTempTable()
Language $lang
Language to use for comment truncation.
const MAX_COMMENT_LENGTH
Maximum length of a comment in bytes.
static decodeMessage( $data)
Decode a message that was encoded by self::encodeMessage()
static array $formerTempTables
Fields that formerly used $tempTables Key is '$key', value is the MediaWiki version in which it was r...
string null $key
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.
static array $tempTables
Define fields that use temporary tables for transitional purposes Keys are '$key',...
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.
getCommentInternal(IDatabase $db=null, $key, $row, $fallback=false)
Extract the comment from a row.
Internationalisation code.
Definition Language.php:35
MediaWikiServices is the service locator for the application scope of MediaWiki.
The Message class provides methods which fulfil two basic services:
Definition Message.php:159
Variant of the Message class.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition design.txt:26
the array() calling protocol came about after MediaWiki 1.4rc1.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition hooks.txt:1015
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2006
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:64
const MIGRATION_NEW
Definition Defines.php:305
const MIGRATION_WRITE_BOTH
Definition Defines.php:303
const MIGRATION_OLD
Definition Defines.php:302
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
insertId()
Get the inserted value of an auto-increment row.
$params
if(!isset( $args[0])) $lang