MediaWiki  1.30.0
CommentStore.php
Go to the documentation of this file.
1 <?php
24 
30 class CommentStore {
31 
37 
43  const MAX_COMMENT_LENGTH = 65535;
44 
50  const MAX_DATA_LENGTH = 65535;
51 
60  protected static $tempTables = [
61  'rev_comment' => [
62  'table' => 'revision_comment_temp',
63  'pk' => 'revcomment_rev',
64  'field' => 'revcomment_comment_id',
65  'joinPK' => 'rev_id',
66  ],
67  'img_description' => [
68  'table' => 'image_comment_temp',
69  'pk' => 'imgcomment_name',
70  'field' => 'imgcomment_description_id',
71  'joinPK' => 'img_name',
72  ],
73  ];
74 
80  protected static $formerTempTables = [];
81 
83  protected $key;
84 
86  protected $stage;
87 
89  protected $joinCache = null;
90 
92  protected $lang;
93 
100  public function __construct( $key, Language $lang = null ) {
102 
103  $this->key = $key;
105  $this->lang = $lang ?: $wgContLang;
106  }
107 
114  public static function newKey( $key ) {
115  return new CommentStore( $key );
116  }
117 
129  public function getFields() {
130  $fields = [];
131  if ( $this->stage === MIGRATION_OLD ) {
132  $fields["{$this->key}_text"] = $this->key;
133  $fields["{$this->key}_data"] = 'NULL';
134  $fields["{$this->key}_cid"] = 'NULL';
135  } else {
136  if ( $this->stage < MIGRATION_NEW ) {
137  $fields["{$this->key}_old"] = $this->key;
138  }
139  if ( isset( self::$tempTables[$this->key] ) ) {
140  $fields["{$this->key}_pk"] = self::$tempTables[$this->key]['joinPK'];
141  } else {
142  $fields["{$this->key}_id"] = "{$this->key}_id";
143  }
144  }
145  return $fields;
146  }
147 
160  public function getJoin() {
161  if ( $this->joinCache === null ) {
162  $tables = [];
163  $fields = [];
164  $joins = [];
165 
166  if ( $this->stage === MIGRATION_OLD ) {
167  $fields["{$this->key}_text"] = $this->key;
168  $fields["{$this->key}_data"] = 'NULL';
169  $fields["{$this->key}_cid"] = 'NULL';
170  } else {
171  $join = $this->stage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN';
172 
173  if ( isset( self::$tempTables[$this->key] ) ) {
174  $t = self::$tempTables[$this->key];
175  $alias = "temp_$this->key";
176  $tables[$alias] = $t['table'];
177  $joins[$alias] = [ $join, "{$alias}.{$t['pk']} = {$t['joinPK']}" ];
178  $joinField = "{$alias}.{$t['field']}";
179  } else {
180  $joinField = "{$this->key}_id";
181  }
182 
183  $alias = "comment_$this->key";
184  $tables[$alias] = 'comment';
185  $joins[$alias] = [ $join, "{$alias}.comment_id = {$joinField}" ];
186 
187  if ( $this->stage === MIGRATION_NEW ) {
188  $fields["{$this->key}_text"] = "{$alias}.comment_text";
189  } else {
190  $fields["{$this->key}_text"] = "COALESCE( {$alias}.comment_text, $this->key )";
191  }
192  $fields["{$this->key}_data"] = "{$alias}.comment_data";
193  $fields["{$this->key}_cid"] = "{$alias}.comment_id";
194  }
195 
196  $this->joinCache = [
197  'tables' => $tables,
198  'fields' => $fields,
199  'joins' => $joins,
200  ];
201  }
202 
203  return $this->joinCache;
204  }
205 
216  private function getCommentInternal( IDatabase $db = null, $row, $fallback = false ) {
217  $key = $this->key;
218  $row = (array)$row;
219  if ( array_key_exists( "{$key}_text", $row ) && array_key_exists( "{$key}_data", $row ) ) {
220  $cid = isset( $row["{$key}_cid"] ) ? $row["{$key}_cid"] : null;
221  $text = $row["{$key}_text"];
222  $data = $row["{$key}_data"];
223  } elseif ( $this->stage === MIGRATION_OLD ) {
224  $cid = null;
225  if ( $fallback && isset( $row[$key] ) ) {
226  wfLogWarning( "Using deprecated fallback handling for comment $key" );
227  $text = $row[$key];
228  } else {
229  wfLogWarning( "Missing {$key}_text and {$key}_data fields in row with MIGRATION_OLD" );
230  $text = '';
231  }
232  $data = null;
233  } else {
234  if ( isset( self::$tempTables[$key] ) ) {
235  if ( array_key_exists( "{$key}_pk", $row ) ) {
236  if ( !$db ) {
237  throw new InvalidArgumentException(
238  "\$row does not contain fields needed for comment $key and getComment(), but "
239  . "does have fields for getCommentLegacy()"
240  );
241  }
242  $t = self::$tempTables[$key];
243  $id = $row["{$key}_pk"];
244  $row2 = $db->selectRow(
245  [ $t['table'], 'comment' ],
246  [ 'comment_id', 'comment_text', 'comment_data' ],
247  [ $t['pk'] => $id ],
248  __METHOD__,
249  [],
250  [ 'comment' => [ 'JOIN', [ "comment_id = {$t['field']}" ] ] ]
251  );
252  } elseif ( $fallback && isset( $row[$key] ) ) {
253  wfLogWarning( "Using deprecated fallback handling for comment $key" );
254  $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
255  } else {
256  throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
257  }
258  } else {
259  if ( array_key_exists( "{$key}_id", $row ) ) {
260  if ( !$db ) {
261  throw new InvalidArgumentException(
262  "\$row does not contain fields needed for comment $key and getComment(), but "
263  . "does have fields for getCommentLegacy()"
264  );
265  }
266  $id = $row["{$key}_id"];
267  $row2 = $db->selectRow(
268  'comment',
269  [ 'comment_id', 'comment_text', 'comment_data' ],
270  [ 'comment_id' => $id ],
271  __METHOD__
272  );
273  } elseif ( $fallback && isset( $row[$key] ) ) {
274  wfLogWarning( "Using deprecated fallback handling for comment $key" );
275  $row2 = (object)[ 'comment_text' => $row[$key], 'comment_data' => null ];
276  } else {
277  throw new InvalidArgumentException( "\$row does not contain fields needed for comment $key" );
278  }
279  }
280 
281  if ( $row2 ) {
282  $cid = $row2->comment_id;
283  $text = $row2->comment_text;
284  $data = $row2->comment_data;
285  } elseif ( $this->stage < MIGRATION_NEW && array_key_exists( "{$key}_old", $row ) ) {
286  $cid = null;
287  $text = $row["{$key}_old"];
288  $data = null;
289  } else {
290  // @codeCoverageIgnoreStart
291  wfLogWarning( "Missing comment row for $key, id=$id" );
292  $cid = null;
293  $text = '';
294  $data = null;
295  // @codeCoverageIgnoreEnd
296  }
297  }
298 
299  $msg = null;
300  if ( $data !== null ) {
301  $data = FormatJson::decode( $data );
302  if ( !is_object( $data ) ) {
303  // @codeCoverageIgnoreStart
304  wfLogWarning( "Invalid JSON object in comment: $data" );
305  $data = null;
306  // @codeCoverageIgnoreEnd
307  } else {
308  $data = (array)$data;
309  if ( isset( $data['_message'] ) ) {
310  $msg = self::decodeMessage( $data['_message'] )
311  ->setInterfaceMessageFlag( true );
312  }
313  if ( !empty( $data['_null'] ) ) {
314  $data = null;
315  } else {
316  foreach ( $data as $k => $v ) {
317  if ( substr( $k, 0, 1 ) === '_' ) {
318  unset( $data[$k] );
319  }
320  }
321  }
322  }
323  }
324 
325  return new CommentStoreComment( $cid, $text, $msg, $data );
326  }
327 
340  public function getComment( $row, $fallback = false ) {
341  return $this->getCommentInternal( null, $row, $fallback );
342  }
343 
359  public function getCommentLegacy( IDatabase $db, $row, $fallback = false ) {
360  return $this->getCommentInternal( $db, $row, $fallback );
361  }
362 
383  public function createComment( IDatabase $dbw, $comment, array $data = null ) {
384  $comment = CommentStoreComment::newUnsavedComment( $comment, $data );
385 
386  # Truncate comment in a Unicode-sensitive manner
387  $comment->text = $this->lang->truncate( $comment->text, self::MAX_COMMENT_LENGTH );
388  if ( mb_strlen( $comment->text, 'UTF-8' ) > self::COMMENT_CHARACTER_LIMIT ) {
389  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this->lang )->escaped();
390  if ( mb_strlen( $ellipsis ) >= self::COMMENT_CHARACTER_LIMIT ) {
391  // WTF?
392  $ellipsis = '...';
393  }
394  $maxLength = self::COMMENT_CHARACTER_LIMIT - mb_strlen( $ellipsis, 'UTF-8' );
395  $comment->text = mb_substr( $comment->text, 0, $maxLength, 'UTF-8' ) . $ellipsis;
396  }
397 
398  if ( $this->stage > MIGRATION_OLD && !$comment->id ) {
399  $dbData = $comment->data;
400  if ( !$comment->message instanceof RawMessage ) {
401  if ( $dbData === null ) {
402  $dbData = [ '_null' => true ];
403  }
404  $dbData['_message'] = self::encodeMessage( $comment->message );
405  }
406  if ( $dbData !== null ) {
407  $dbData = FormatJson::encode( (object)$dbData, false, FormatJson::ALL_OK );
408  $len = strlen( $dbData );
409  if ( $len > self::MAX_DATA_LENGTH ) {
410  $max = self::MAX_DATA_LENGTH;
411  throw new OverflowException( "Comment data is too long ($len bytes, maximum is $max)" );
412  }
413  }
414 
415  $hash = self::hash( $comment->text, $dbData );
416  $comment->id = $dbw->selectField(
417  'comment',
418  'comment_id',
419  [
420  'comment_hash' => $hash,
421  'comment_text' => $comment->text,
422  'comment_data' => $dbData,
423  ],
424  __METHOD__
425  );
426  if ( !$comment->id ) {
427  $dbw->insert(
428  'comment',
429  [
430  'comment_hash' => $hash,
431  'comment_text' => $comment->text,
432  'comment_data' => $dbData,
433  ],
434  __METHOD__
435  );
436  $comment->id = $dbw->insertId();
437  }
438  }
439 
440  return $comment;
441  }
442 
450  private function insertInternal( IDatabase $dbw, $comment, $data ) {
451  $fields = [];
452  $callback = null;
453 
454  $comment = $this->createComment( $dbw, $comment, $data );
455 
456  if ( $this->stage <= MIGRATION_WRITE_BOTH ) {
457  $fields[$this->key] = $this->lang->truncate( $comment->text, 255 );
458  }
459 
460  if ( $this->stage >= MIGRATION_WRITE_BOTH ) {
461  if ( isset( self::$tempTables[$this->key] ) ) {
462  $t = self::$tempTables[$this->key];
463  $func = __METHOD__;
464  $commentId = $comment->id;
465  $callback = function ( $id ) use ( $dbw, $commentId, $t, $func ) {
466  $dbw->insert(
467  $t['table'],
468  [
469  $t['pk'] => $id,
470  $t['field'] => $commentId,
471  ],
472  $func
473  );
474  };
475  } else {
476  $fields["{$this->key}_id"] = $comment->id;
477  }
478  }
479 
480  return [ $fields, $callback ];
481  }
482 
493  public function insert( IDatabase $dbw, $comment, $data = null ) {
494  if ( isset( self::$tempTables[$this->key] ) ) {
495  throw new InvalidArgumentException( "Must use insertWithTempTable() for $this->key" );
496  }
497 
498  list( $fields ) = $this->insertInternal( $dbw, $comment, $data );
499  return $fields;
500  }
501 
518  public function insertWithTempTable( IDatabase $dbw, $comment, $data = null ) {
519  if ( isset( self::$formerTempTables[$this->key] ) ) {
520  wfDeprecated( __METHOD__ . " for $this->key", self::$formerTempTables[$this->key] );
521  } elseif ( !isset( self::$tempTables[$this->key] ) ) {
522  throw new InvalidArgumentException( "Must use insert() for $this->key" );
523  }
524 
525  list( $fields, $callback ) = $this->insertInternal( $dbw, $comment, $data );
526  if ( !$callback ) {
527  $callback = function () {
528  // Do nothing.
529  };
530  }
531  return [ $fields, $callback ];
532  }
533 
539  protected static function encodeMessage( Message $msg ) {
540  $key = count( $msg->getKeysToTry() ) > 1 ? $msg->getKeysToTry() : $msg->getKey();
541  $params = $msg->getParams();
542  foreach ( $params as &$param ) {
543  if ( $param instanceof Message ) {
544  $param = [
545  'message' => self::encodeMessage( $param )
546  ];
547  }
548  }
549  array_unshift( $params, $key );
550  return $params;
551  }
552 
558  protected static function decodeMessage( $data ) {
559  $key = array_shift( $data );
560  foreach ( $data as &$param ) {
561  if ( is_object( $param ) ) {
562  $param = (array)$param;
563  }
564  if ( is_array( $param ) && count( $param ) === 1 && isset( $param['message'] ) ) {
565  $param = self::decodeMessage( $param['message'] );
566  }
567  }
568  return new Message( $key, $data );
569  }
570 
577  public static function hash( $text, $data ) {
578  $hash = crc32( $text ) ^ crc32( (string)$data );
579 
580  // 64-bit PHP returns an unsigned CRC, change it to signed for
581  // insertion into the database.
582  if ( $hash >= 0x80000000 ) {
583  $hash |= -1 << 32;
584  }
585 
586  return $hash;
587  }
588 
589 }
CommentStore\$formerTempTables
static array $formerTempTables
Fields that formerly used $tempTables Key is '$key', value is the MediaWiki version in which it was r...
Definition: CommentStore.php:80
CommentStoreComment\newUnsavedComment
static newUnsavedComment( $comment, array $data=null)
Create a new, unsaved CommentStoreComment.
Definition: CommentStoreComment.php:67
object
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:25
CommentStore\$joinCache
array null $joinCache
Cache for self::getJoin()
Definition: CommentStore.php:89
$tables
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:988
CommentStore\getCommentInternal
getCommentInternal(IDatabase $db=null, $row, $fallback=false)
Extract the comment from a row.
Definition: CommentStore.php:216
captcha-old.count
count
Definition: captcha-old.py:249
$wgCommentTableSchemaMigrationStage
int $wgCommentTableSchemaMigrationStage
Comment table schema migration stage.
Definition: DefaultSettings.php:8765
$fallback
$fallback
Definition: MessagesAb.php:11
MIGRATION_NEW
const MIGRATION_NEW
Definition: Defines.php:296
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
CommentStore\insertWithTempTable
insertWithTempTable(IDatabase $dbw, $comment, $data=null)
Insert a comment in a temporary table in preparation for a row that references it.
Definition: CommentStore.php:518
CommentStore
CommentStore handles storage of comments (edit summaries, log reasons, etc) in the database.
Definition: CommentStore.php:30
$params
$params
Definition: styleTest.css.php:40
MIGRATION_WRITE_BOTH
const MIGRATION_WRITE_BOTH
Definition: Defines.php:294
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1203
Wikimedia\Rdbms\IDatabase\selectField
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
CommentStore\$tempTables
static array $tempTables
Define fields that use temporary tables for transitional purposes Keys are '$key',...
Definition: CommentStore.php:60
CommentStore\newKey
static newKey( $key)
Static constructor for easier chaining.
Definition: CommentStore.php:114
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
Wikimedia\Rdbms\IDatabase\insert
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
CommentStore\$key
string $key
Definition: CommentStore.php:83
php
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:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
CommentStore\getJoin
getJoin()
Get SELECT fields and joins for the comment key.
Definition: CommentStore.php:160
CommentStore\insert
insert(IDatabase $dbw, $comment, $data=null)
Insert a comment in preparation for a row that references it.
Definition: CommentStore.php:493
key
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:25
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1176
CommentStore\$stage
int $stage
One of the MIGRATION_* constants.
Definition: CommentStore.php:86
CommentStore\getFields
getFields()
Get SELECT fields for the comment key.
Definition: CommentStore.php:129
CommentStore\insertInternal
insertInternal(IDatabase $dbw, $comment, $data)
Implementation for self::insert() and self::insertWithTempTable()
Definition: CommentStore.php:450
CommentStore\getComment
getComment( $row, $fallback=false)
Extract the comment from a row.
Definition: CommentStore.php:340
CommentStore\decodeMessage
static decodeMessage( $data)
Decode a message that was encoded by self::encodeMessage()
Definition: CommentStore.php:558
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
CommentStore\getCommentLegacy
getCommentLegacy(IDatabase $db, $row, $fallback=false)
Extract the comment from a row, with legacy lookups.
Definition: CommentStore.php:359
list
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
CommentStore\encodeMessage
static encodeMessage(Message $msg)
Encode a Message as a PHP data structure.
Definition: CommentStore.php:539
MIGRATION_OLD
const MIGRATION_OLD
Definition: Defines.php:293
CommentStore\MAX_DATA_LENGTH
const MAX_DATA_LENGTH
Maximum length of serialized data in bytes.
Definition: CommentStore.php:50
CommentStore\createComment
createComment(IDatabase $dbw, $comment, array $data=null)
Create a new CommentStoreComment, inserting it into the database if necessary.
Definition: CommentStore.php:383
CommentStore\hash
static hash( $text, $data)
Hashing function for comment storage.
Definition: CommentStore.php:577
CommentStore\COMMENT_CHARACTER_LIMIT
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
Definition: CommentStore.php:36
CommentStore\MAX_COMMENT_LENGTH
const MAX_COMMENT_LENGTH
Maximum length of a comment in bytes.
Definition: CommentStore.php:43
as
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
Definition: distributors.txt:9
true
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:1965
wfMessage
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
$t
$t
Definition: testCompression.php:67
Wikimedia\Rdbms\IDatabase\insertId
insertId()
Get the inserted value of an auto-increment row.
RawMessage
Variant of the Message class.
Definition: RawMessage.php:34
CommentStore\__construct
__construct( $key, Language $lang=null)
Definition: CommentStore.php:100
CommentStoreComment
CommentStoreComment represents a comment stored by CommentStore.
Definition: CommentStoreComment.php:30
Language
Internationalisation code.
Definition: Language.php:35
CommentStore\$lang
Language $lang
Language to use for comment truncation.
Definition: CommentStore.php:92
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$wgContLang
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 content language as $wgContLang
Definition: design.txt:56