3 * Efficient concatenated text storage.
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.
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.
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
24 * Base class for general text storage via the "object" flag in old_flags, or
25 * two-part external storage URLs. Used for represent efficient concatenated
26 * storage, and migration-related pointer objects.
31 * Adds an item of text, returns a stub object which points to the item.
32 * You must call setLocation() on the stub object before storing it to the
37 * @return String: the key for getItem()
39 function addItem( $text );
42 * Get item by key, or false if the key is not present
46 * @return String or false
48 function getItem( $key );
51 * Set the "default text"
52 * This concept is an odd property of the current DB schema, whereby each text item has a revision
53 * associated with it. The default text is the text of the associated revision. There may, however,
54 * be other revisions in the same object.
56 * Default text is not required for two-part external storage URLs.
60 function setText( $text );
63 * Get default text. This is called from Revision::getRevisionText()
71 * Concatenated gzip (CGZ) storage
72 * Improves compression ratio by concatenating like objects before gzipping
74 class ConcatenatedGzipHistoryBlob
implements HistoryBlob
76 public $mVersion = 0, $mCompressed = false, $mItems = array(), $mDefaultHash = '';
78 public $mMaxSize = 10000000;
79 public $mMaxCount = 100;
84 public function __construct() {
85 if ( !function_exists( 'gzdeflate' ) ) {
86 throw new MWException( "Need zlib support to read or write this kind of history object (ConcatenatedGzipHistoryBlob)\n" );
94 public function addItem( $text ) {
97 if ( !isset( $this->mItems
[$hash] ) ) {
98 $this->mItems
[$hash] = $text;
99 $this->mSize +
= strlen( $text );
105 * @param $hash string
108 public function getItem( $hash ) {
110 if ( array_key_exists( $hash, $this->mItems
) ) {
111 return $this->mItems
[$hash];
118 * @param $text string
121 public function setText( $text ) {
123 $this->mDefaultHash
= $this->addItem( $text );
129 public function getText() {
131 return $this->getItem( $this->mDefaultHash
);
137 * @param $hash string
139 public function removeItem( $hash ) {
140 $this->mSize
-= strlen( $this->mItems
[$hash] );
141 unset( $this->mItems
[$hash] );
145 * Compress the bulk data in the object
147 public function compress() {
148 if ( !$this->mCompressed
) {
149 $this->mItems
= gzdeflate( serialize( $this->mItems
) );
150 $this->mCompressed
= true;
155 * Uncompress bulk data
157 public function uncompress() {
158 if ( $this->mCompressed
) {
159 $this->mItems
= unserialize( gzinflate( $this->mItems
) );
160 $this->mCompressed
= false;
169 return array( 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' );
172 function __wakeup() {
177 * Helper function for compression jobs
178 * Returns true until the object is "full" and ready to be committed
182 public function isHappy() {
183 return $this->mSize
< $this->mMaxSize
184 && count( $this->mItems
) < $this->mMaxCount
;
189 * Pointer object for an item within a CGZ blob stored in the text table.
191 class HistoryBlobStub
{
193 * One-step cache variable to hold base blobs; operations that
194 * pull multiple revisions may often pull multiple times from
195 * the same blob. By keeping the last-used one open, we avoid
196 * redundant unserialization and decompression overhead.
198 protected static $blobCache = array();
200 var $mOldId, $mHash, $mRef;
203 * @param string $hash the content hash of the text
204 * @param $oldid Integer the old_id for the CGZ object
206 function __construct( $hash = '', $oldid = 0 ) {
207 $this->mHash
= $hash;
211 * Sets the location (old_id) of the main object to which this object
214 function setLocation( $id ) {
219 * Sets the location (old_id) of the referring object
221 function setReferrer( $id ) {
226 * Gets the location of the referring object
228 function getReferrer() {
236 if ( isset( self
::$blobCache[$this->mOldId
] ) ) {
237 $obj = self
::$blobCache[$this->mOldId
];
239 $dbr = wfGetDB( DB_SLAVE
);
240 $row = $dbr->selectRow( 'text', array( 'old_flags', 'old_text' ), array( 'old_id' => $this->mOldId
) );
244 $flags = explode( ',', $row->old_flags
);
245 if ( in_array( 'external', $flags ) ) {
246 $url = $row->old_text
;
247 $parts = explode( '://', $url, 2 );
248 if ( !isset( $parts[1] ) ||
$parts[1] == '' ) {
251 $row->old_text
= ExternalStore
::fetchFromUrl( $url );
254 if ( !in_array( 'object', $flags ) ) {
258 if ( in_array( 'gzip', $flags ) ) {
259 // This shouldn't happen, but a bug in the compress script
260 // may at times gzip-compress a HistoryBlob object row.
261 $obj = unserialize( gzinflate( $row->old_text
) );
263 $obj = unserialize( $row->old_text
);
266 if ( !is_object( $obj ) ) {
267 // Correct for old double-serialization bug.
268 $obj = unserialize( $obj );
271 // Save this item for reference; if pulling many
272 // items in a row we'll likely use it again.
274 self
::$blobCache = array( $this->mOldId
=> $obj );
276 return $obj->getItem( $this->mHash
);
280 * Get the content hash
290 * To speed up conversion from 1.4 to 1.5 schema, text rows can refer to the
291 * leftover cur table as the backend. This avoids expensively copying hundreds
292 * of megabytes of data during the conversion downtime.
294 * Serialized HistoryBlobCurStub objects will be inserted into the text table
295 * on conversion if $wgLegacySchemaConversion is set to true.
297 class HistoryBlobCurStub
{
301 * @param $curid Integer: the cur_id pointed to
303 function __construct( $curid = 0 ) {
304 $this->mCurId
= $curid;
308 * Sets the location (cur_id) of the main object to which this object
313 function setLocation( $id ) {
318 * @return string|bool
321 $dbr = wfGetDB( DB_SLAVE
);
322 $row = $dbr->selectRow( 'cur', array( 'cur_text' ), array( 'cur_id' => $this->mCurId
) );
326 return $row->cur_text
;
331 * Diff-based history compression
332 * Requires xdiff 1.5+ and zlib
334 class DiffHistoryBlob
implements HistoryBlob
{
335 /** Uncompressed item cache */
336 var $mItems = array();
338 /** Total uncompressed size */
342 * Array of diffs. If a diff D from A to B is notated D = B - A, and Z is
345 * { item[map[i]] - item[map[i-1]] where i > 0
347 * { item[map[i]] - Z where i = 0
351 /** The diff map, see above */
355 * The key for getText()
365 * True if the object is locked against further writes
367 var $mFrozen = false;
370 * The maximum uncompressed size before the object becomes sad
371 * Should be less than max_allowed_packet
373 var $mMaxSize = 10000000;
376 * The maximum number of text items before the object becomes sad
378 var $mMaxCount = 100;
380 /** Constants from xdiff.h */
381 const XDL_BDOP_INS
= 1;
382 const XDL_BDOP_CPY
= 2;
383 const XDL_BDOP_INSB
= 3;
385 function __construct() {
386 if ( !function_exists( 'gzdeflate' ) ) {
387 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
392 * @throws MWException
393 * @param $text string
396 function addItem( $text ) {
397 if ( $this->mFrozen
) {
398 throw new MWException( __METHOD__
. ": Cannot add more items after sleep/wakeup" );
401 $this->mItems
[] = $text;
402 $this->mSize +
= strlen( $text );
403 $this->mDiffs
= null; // later
404 return count( $this->mItems
) - 1;
411 function getItem( $key ) {
412 return $this->mItems
[$key];
416 * @param $text string
418 function setText( $text ) {
419 $this->mDefaultKey
= $this->addItem( $text );
426 return $this->getItem( $this->mDefaultKey
);
430 * @throws MWException
432 function compress() {
433 if ( !function_exists( 'xdiff_string_rabdiff' ) ) {
434 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
436 if ( isset( $this->mDiffs
) ) {
437 // Already compressed
440 if ( !count( $this->mItems
) ) {
445 // Create two diff sequences: one for main text and one for small text
460 for ( $i = 0; $i < count( $this->mItems
); $i++
) {
461 $text = $this->mItems
[$i];
465 $mainTail = $sequences['main']['tail'];
466 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
472 $seq =& $sequences[$seqName];
473 $tail = $seq['tail'];
474 $diff = $this->diff( $tail, $text );
475 $seq['diffs'][] = $diff;
477 $seq['tail'] = $text;
479 unset( $seq ); // unlink dangerous alias
481 // Knit the sequences together
483 $this->mDiffs
= array();
484 $this->mDiffMap
= array();
485 foreach ( $sequences as $seq ) {
486 if ( !count( $seq['diffs'] ) ) {
489 if ( $tail === '' ) {
490 $this->mDiffs
[] = $seq['diffs'][0];
492 $head = $this->patch( '', $seq['diffs'][0] );
493 $this->mDiffs
[] = $this->diff( $tail, $head );
495 $this->mDiffMap
[] = $seq['map'][0];
496 for ( $i = 1; $i < count( $seq['diffs'] ); $i++
) {
497 $this->mDiffs
[] = $seq['diffs'][$i];
498 $this->mDiffMap
[] = $seq['map'][$i];
500 $tail = $seq['tail'];
509 function diff( $t1, $t2 ) {
510 # Need to do a null concatenation with warnings off, due to bugs in the current version of xdiff
511 # "String is not zero-terminated"
512 wfSuppressWarnings();
513 $diff = xdiff_string_rabdiff( $t1, $t2 ) . '';
521 * @return bool|string
523 function patch( $base, $diff ) {
524 if ( function_exists( 'xdiff_string_bpatch' ) ) {
525 wfSuppressWarnings();
526 $text = xdiff_string_bpatch( $base, $diff ) . '';
531 # Pure PHP implementation
533 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
535 # Check the checksum if hash extension is available
536 $ofp = $this->xdiffAdler32( $base );
537 if ( $ofp !== false && $ofp !== substr( $diff, 0, 4 ) ) {
538 wfDebug( __METHOD__
. ": incorrect base checksum\n" );
541 if ( $header['csize'] != strlen( $base ) ) {
542 wfDebug( __METHOD__
. ": incorrect base length\n" );
548 while ( $p < strlen( $diff ) ) {
549 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
553 case self
::XDL_BDOP_INS
:
554 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
556 $out .= substr( $diff, $p, $x['size'] );
559 case self
::XDL_BDOP_INSB
:
560 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
562 $out .= substr( $diff, $p, $x['csize'] );
565 case self
::XDL_BDOP_CPY
:
566 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
568 $out .= substr( $base, $x['off'], $x['csize'] );
571 wfDebug( __METHOD__
. ": invalid op\n" );
579 * Compute a binary "Adler-32" checksum as defined by LibXDiff, i.e. with
580 * the bytes backwards and initialised with 0 instead of 1. See bug 34428.
583 * @return string|bool: false if the hash extension is not available
585 function xdiffAdler32( $s ) {
586 if ( !function_exists( 'hash' ) ) {
591 if ( $init === null ) {
592 $init = str_repeat( "\xf0", 205 ) . "\xee" . str_repeat( "\xf0", 67 ) . "\x02";
595 // The real Adler-32 checksum of $init is zero, so it initialises the
596 // state to zero, as it is at the start of LibXDiff's checksum
597 // algorithm. Appending the subject string then simulates LibXDiff.
598 return strrev( hash( 'adler32', $init . $s, true ) );
601 function uncompress() {
602 if ( !$this->mDiffs
) {
606 for ( $diffKey = 0; $diffKey < count( $this->mDiffs
); $diffKey++
) {
607 $textKey = $this->mDiffMap
[$diffKey];
608 $text = $this->patch( $tail, $this->mDiffs
[$diffKey] );
609 $this->mItems
[$textKey] = $text;
619 if ( !count( $this->mItems
) ) {
623 // Take forward differences to improve the compression ratio for sequences
626 foreach ( $this->mDiffMap
as $i ) {
634 'diffs' => $this->mDiffs
,
638 if ( isset( $this->mDefaultKey
) ) {
639 $info['default'] = $this->mDefaultKey
;
641 $this->mCompressed
= gzdeflate( serialize( $info ) );
642 return array( 'mCompressed' );
645 function __wakeup() {
646 // addItem() doesn't work if mItems is partially filled from mDiffs
647 $this->mFrozen
= true;
648 $info = unserialize( gzinflate( $this->mCompressed
) );
649 unset( $this->mCompressed
);
656 if ( isset( $info['default'] ) ) {
657 $this->mDefaultKey
= $info['default'];
659 $this->mDiffs
= $info['diffs'];
660 if ( isset( $info['base'] ) ) {
662 $this->mDiffMap
= range( 0, count( $this->mDiffs
) - 1 );
663 array_unshift( $this->mDiffs
,
664 pack( 'VVCV', 0, 0, self
::XDL_BDOP_INSB
, strlen( $info['base'] ) ) .
668 $map = explode( ',', $info['map'] );
670 $this->mDiffMap
= array();
671 foreach ( $map as $i ) {
673 $this->mDiffMap
[] = $cur;
680 * Helper function for compression jobs
681 * Returns true until the object is "full" and ready to be committed
686 return $this->mSize
< $this->mMaxSize
687 && count( $this->mItems
) < $this->mMaxCount
;