MediaWiki REL1_32
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
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
83 protected $key = null;
84
86 protected $stage;
87
89 protected $joinCache = [];
90
92 protected $lang;
93
99 public function __construct( Language $lang, $migrationStage ) {
100 $this->stage = $migrationStage;
101 $this->lang = $lang;
102 }
103
111 public static function newKey( $key ) {
113 wfDeprecated( __METHOD__, '1.31' );
114 $store = new CommentStore( MediaWikiServices::getInstance()->getContentLanguage(),
116 $store->key = $key;
117 return $store;
118 }
119
125 public static function getStore() {
126 return MediaWikiServices::getInstance()->getCommentStore();
127 }
128
135 private function getKey( $methodKey = null ) {
136 $key = $this->key ?? $methodKey;
137 if ( $key === null ) {
138 // @codeCoverageIgnoreStart
139 throw new InvalidArgumentException( '$key should not be null' );
140 // @codeCoverageIgnoreEnd
141 }
142 return $key;
143 }
144
161 public function getFields( $key = null ) {
162 $key = $this->getKey( $key );
163 $fields = [];
164 if ( $this->stage === MIGRATION_OLD ) {
165 $fields["{$key}_text"] = $key;
166 $fields["{$key}_data"] = 'NULL';
167 $fields["{$key}_cid"] = 'NULL';
168 } else {
169 if ( $this->stage < MIGRATION_NEW ) {
170 $fields["{$key}_old"] = $key;
171 }
172
173 $tempTableStage = isset( $this->tempTables[$key] )
174 ? $this->tempTables[$key]['stage'] : MIGRATION_NEW;
175 if ( $tempTableStage < MIGRATION_NEW ) {
176 $fields["{$key}_pk"] = $this->tempTables[$key]['joinPK'];
177 }
178 if ( $tempTableStage > MIGRATION_OLD ) {
179 $fields["{$key}_id"] = "{$key}_id";
180 }
181 }
182 return $fields;
183 }
184
201 public function getJoin( $key = null ) {
202 $key = $this->getKey( $key );
203 if ( !array_key_exists( $key, $this->joinCache ) ) {
204 $tables = [];
205 $fields = [];
206 $joins = [];
207
208 if ( $this->stage === MIGRATION_OLD ) {
209 $fields["{$key}_text"] = $key;
210 $fields["{$key}_data"] = 'NULL';
211 $fields["{$key}_cid"] = 'NULL';
212 } else {
213 $join = $this->stage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN';
214
215 $tempTableStage = isset( $this->tempTables[$key] )
216 ? $this->tempTables[$key]['stage'] : MIGRATION_NEW;
217 if ( $tempTableStage < MIGRATION_NEW ) {
218 $t = $this->tempTables[$key];
219 $alias = "temp_$key";
220 $tables[$alias] = $t['table'];
221 $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
222 if ( $tempTableStage === MIGRATION_OLD ) {
223 $joinField = "{$alias}.{$t['field']}";
224 } else {
225 // Nothing hits this code path for now, but will in the future when we set
226 // $this->tempTables['rev_comment']['stage'] to MIGRATION_WRITE_NEW while
227 // merging revision_comment_temp into revision.
228 // @codeCoverageIgnoreStart
229 $joins[$alias][0] = 'LEFT JOIN';
230 $joinField = "(CASE WHEN {$key}_id != 0 THEN {$key}_id ELSE {$alias}.{$t['field']} END)";
231 throw new LogicException( 'Nothing should reach this code path at this time' );
232 // @codeCoverageIgnoreEnd
233 }
234 } else {
235 $joinField = "{$key}_id";
236 }
237
238 $alias = "comment_$key";
239 $tables[$alias] = 'comment';
240 $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
241
242 if ( $this->stage === MIGRATION_NEW ) {
243 $fields["{$key}_text"] = "{$alias}.comment_text";
244 } else {
245 $fields["{$key}_text"] = "COALESCE( {$alias}.comment_text, $key )";
246 }
247 $fields["{$key}_data"] = "{$alias}.comment_data";
248 $fields["{$key}_cid"] = "{$alias}.comment_id";
249 }
250
251 $this->joinCache[$key] = [
252 'tables' => $tables,
253 'fields' => $fields,
254 'joins' => $joins,
255 ];
256 }
257
258 return $this->joinCache[$key];
259 }
260
273 private function getCommentInternal( IDatabase $db = null, $key, $row, $fallback = false ) {
274 $row = (array)$row;
275 if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
276 $cid = $row["{$key}_cid"] ?? null;
277 $text = $row["{$key}_text"];
278 $data = $row["{$key}_data"];
279 } elseif ( $this->stage === MIGRATION_OLD ) {
280 $cid = null;
281 if ( $fallback && isset( $row[$key] ) ) {
282 wfLogWarning( "Using deprecated fallback handling for comment $key" );
283 $text = $row[$key];
284 } else {
285 wfLogWarning( "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD" );
286 $text = '';
287 }
288 $data = null;
289 } else {
290 $tempTableStage = isset( $this->tempTables[$key] )
291 ? $this->tempTables[$key]['stage'] : MIGRATION_NEW;
292 $row2 = null;
293 if ( $tempTableStage > MIGRATION_OLD && array_key_exists( "{$key}_id", $row ) ) {
294 if ( !$db ) {
295 throw new InvalidArgumentException(
296 "\$row does not contain fields needed for comment $key and getComment(), but "
297 . "does have fields for getCommentLegacy()"
298 );
299 }
300 $id = $row["{$key}_id"];
301 $row2 = $db->selectRow(
302 'comment',
303 [ 'comment_id', 'comment_text', 'comment_data' ],
304 [ 'comment_id' => $id ],
305 __METHOD__
306 );
307 }
308 if ( !$row2 && $tempTableStage < MIGRATION_NEW && array_key_exists( "{$key}_pk", $row ) ) {
309 if ( !$db ) {
310 throw new InvalidArgumentException(
311 "\$row does not contain fields needed for comment $key and getComment(), but "
312 . "does have fields for getCommentLegacy()"
313 );
314 }
315 $t = $this->tempTables[$key];
316 $id = $row["{$key}_pk"];
317 $row2 = $db->selectRow(
318 [ $t['table'], 'comment' ],
319 [ 'comment_id', 'comment_text', 'comment_data' ],
320 [ $t['pk'] => $id ],
321 __METHOD__,
322 [],
323 [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
324 );
325 }
326 if ( $row2 === null && $fallback && isset( $row[$key] ) ) {
327 wfLogWarning( "Using deprecated fallback handling for comment $key" );
328 $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
329 }
330 if ( $row2 === null ) {
331 throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
332 }
333
334 if ( $row2 ) {
335 $cid = $row2->comment_id;
336 $text = $row2->comment_text;
337 $data = $row2->comment_data;
338 } elseif ( $this->stage < MIGRATION_NEW && array_key_exists( "{$key}_old", $row ) ) {
339 $cid = null;
340 $text = $row["{$key}_old"];
341 $data = null;
342 } else {
343 // @codeCoverageIgnoreStart
344 wfLogWarning( "Missing comment row for $key, id=$id" );
345 $cid = null;
346 $text = '';
347 $data = null;
348 // @codeCoverageIgnoreEnd
349 }
350 }
351
352 $msg = null;
353 if ( $data !== null ) {
354 $data = FormatJson::decode( $data );
355 if ( !is_object( $data ) ) {
356 // @codeCoverageIgnoreStart
357 wfLogWarning( "Invalid JSON object in comment: $data" );
358 $data = null;
359 // @codeCoverageIgnoreEnd
360 } else {
361 $data = (array)$data;
362 if ( isset( $data['_message'] ) ) {
363 $msg = self::decodeMessage( $data['_message'] )
364 ->setInterfaceMessageFlag( true );
365 }
366 if ( !empty( $data['_null'] ) ) {
367 $data = null;
368 } else {
369 foreach ( $data as $k => $v ) {
370 if ( substr( $k, 0, 1 ) === '_' ) {
371 unset( $data[$k] );
372 }
373 }
374 }
375 }
376 }
377
378 return new CommentStoreComment( $cid, $text, $msg, $data );
379 }
380
397 public function getComment( $key, $row = null, $fallback = false ) {
398 // Compat for method sig change in 1.31 (introduction of $key)
399 if ( $this->key !== null ) {
400 $fallback = $row;
401 $row = $key;
402 $key = $this->getKey();
403 }
404 if ( $row === null ) {
405 // @codeCoverageIgnoreStart
406 throw new InvalidArgumentException( '$row must not be null' );
407 // @codeCoverageIgnoreEnd
408 }
409 return $this->getCommentInternal( null, $key, $row, $fallback );
410 }
411
431 public function getCommentLegacy( IDatabase $db, $key, $row = null, $fallback = false ) {
432 // Compat for method sig change in 1.31 (introduction of $key)
433 if ( $this->key !== null ) {
434 $fallback = $row;
435 $row = $key;
436 $key = $this->getKey();
437 }
438 if ( $row === null ) {
439 // @codeCoverageIgnoreStart
440 throw new InvalidArgumentException( '$row must not be null' );
441 // @codeCoverageIgnoreEnd
442 }
443 return $this->getCommentInternal( $db, $key, $row, $fallback );
444 }
445
466 public function createComment( IDatabase $dbw, $comment, array $data = null ) {
467 $comment = CommentStoreComment::newUnsavedComment( $comment, $data );
468
469 # Truncate comment in a Unicode-sensitive manner
470 $comment->text = $this->lang->truncateForVisual( $comment->text, self::COMMENT_CHARACTER_LIMIT );
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->truncateForDatabase( $comment->text, 255 );
534 }
535
536 if ( $this->stage >= MIGRATION_WRITE_BOTH ) {
537 $tempTableStage = isset( $this->tempTables[$key] )
538 ? $this->tempTables[$key]['stage'] : MIGRATION_NEW;
539 if ( $tempTableStage <= MIGRATION_WRITE_BOTH ) {
540 $t = $this->tempTables[$key];
541 $func = __METHOD__;
542 $commentId = $comment->id;
543 $callback = function ( $id ) use ( $dbw, $commentId, $t, $func ) {
544 $dbw->insert(
545 $t['table'],
546 [
547 $t['pk'] => $id,
548 $t['field'] => $commentId,
549 ],
550 $func
551 );
552 };
553 }
554 if ( $tempTableStage >= MIGRATION_WRITE_BOTH ) {
555 $fields["{$key}_id"] = $comment->id;
556 }
557 }
558
559 return [ $fields, $callback ];
560 }
561
577 public function insert( IDatabase $dbw, $key, $comment = null, $data = null ) {
578 // Compat for method sig change in 1.31 (introduction of $key)
579 if ( $this->key !== null ) {
580 $data = $comment;
581 $comment = $key;
582 $key = $this->key;
583 }
584 if ( $comment === null ) {
585 // @codeCoverageIgnoreStart
586 throw new InvalidArgumentException( '$comment can not be null' );
587 // @codeCoverageIgnoreEnd
588 }
589
590 $tempTableStage = isset( $this->tempTables[$key] )
591 ? $this->tempTables[$key]['stage'] : MIGRATION_NEW;
592 if ( $tempTableStage < MIGRATION_WRITE_NEW ) {
593 throw new InvalidArgumentException( "Must use insertWithTempTable() for $key" );
594 }
595
596 list( $fields ) = $this->insertInternal( $dbw, $key, $comment, $data );
597 return $fields;
598 }
599
621 public function insertWithTempTable( IDatabase $dbw, $key, $comment = null, $data = null ) {
622 // Compat for method sig change in 1.31 (introduction of $key)
623 if ( $this->key !== null ) {
624 $data = $comment;
625 $comment = $key;
626 $key = $this->getKey();
627 }
628 if ( $comment === null ) {
629 // @codeCoverageIgnoreStart
630 throw new InvalidArgumentException( '$comment can not be null' );
631 // @codeCoverageIgnoreEnd
632 }
633
634 if ( !isset( $this->tempTables[$key] ) ) {
635 throw new InvalidArgumentException( "Must use insert() for $key" );
636 } elseif ( isset( $this->tempTables[$key]['deprecatedIn'] ) ) {
637 wfDeprecated( __METHOD__ . " for $key", $this->tempTables[$key]['deprecatedIn'] );
638 }
639
640 list( $fields, $callback ) = $this->insertInternal( $dbw, $key, $comment, $data );
641 if ( !$callback ) {
642 $callback = function () {
643 // Do nothing.
644 };
645 }
646 return [ $fields, $callback ];
647 }
648
654 protected static function encodeMessage( Message $msg ) {
655 $key = count( $msg->getKeysToTry() ) > 1 ? $msg->getKeysToTry() : $msg->getKey();
656 $params = $msg->getParams();
657 foreach ( $params as &$param ) {
658 if ( $param instanceof Message ) {
659 $param = [
660 'message' => self::encodeMessage( $param )
661 ];
662 }
663 }
664 array_unshift( $params, $key );
665 return $params;
666 }
667
673 protected static function decodeMessage( $data ) {
674 $key = array_shift( $data );
675 foreach ( $data as &$param ) {
676 if ( is_object( $param ) ) {
677 $param = (array)$param;
678 }
679 if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
680 $param = self::decodeMessage( $param['message'] );
681 }
682 }
683 return new Message( $key, $data );
684 }
685
692 public static function hash( $text, $data ) {
693 $hash = crc32( $text ) ^ crc32( (string)$data );
694
695 // 64-bit PHP returns an unsigned CRC, change it to signed for
696 // insertion into the database.
697 if ( $hash >= 0x80000000 ) {
698 $hash |= -1 << 32;
699 }
700
701 return $hash;
702 }
703
704}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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()
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.
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:160
getParams()
Returns the message parameters.
Definition Message.php:355
getKeysToTry()
Definition Message.php:329
getKey()
Returns the message key.
Definition Message.php:344
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 document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
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 $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:62
const MIGRATION_WRITE_NEW
Definition Defines.php:317
const MIGRATION_NEW
Definition Defines.php:318
const MIGRATION_WRITE_BOTH
Definition Defines.php:316
const MIGRATION_OLD
Definition Defines.php:315
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 use $formDescriptor instead 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 key
Definition hooks.txt:2214
this hook is for auditing only 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:1035
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:2055
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
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.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$params
if(!isset( $args[0])) $lang