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;
82 public function __construct() {
83 if ( !function_exists( 'gzdeflate' ) ) {
84 throw new MWException( "Need zlib support to read or write this kind of history object (ConcatenatedGzipHistoryBlob)\n" );
92 public function addItem( $text ) {
95 if ( !isset( $this->mItems
[$hash] ) ) {
96 $this->mItems
[$hash] = $text;
97 $this->mSize +
= strlen( $text );
103 * @param $hash string
106 public function getItem( $hash ) {
108 if ( array_key_exists( $hash, $this->mItems
) ) {
109 return $this->mItems
[$hash];
116 * @param $text string
119 public function setText( $text ) {
121 $this->mDefaultHash
= $this->addItem( $text );
127 public function getText() {
129 return $this->getItem( $this->mDefaultHash
);
135 * @param $hash string
137 public function removeItem( $hash ) {
138 $this->mSize
-= strlen( $this->mItems
[$hash] );
139 unset( $this->mItems
[$hash] );
143 * Compress the bulk data in the object
145 public function compress() {
146 if ( !$this->mCompressed
) {
147 $this->mItems
= gzdeflate( serialize( $this->mItems
) );
148 $this->mCompressed
= true;
153 * Uncompress bulk data
155 public function uncompress() {
156 if ( $this->mCompressed
) {
157 $this->mItems
= unserialize( gzinflate( $this->mItems
) );
158 $this->mCompressed
= false;
167 return array( 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' );
170 function __wakeup() {
175 * Helper function for compression jobs
176 * Returns true until the object is "full" and ready to be committed
180 public function isHappy() {
181 return $this->mSize
< $this->mMaxSize
182 && count( $this->mItems
) < $this->mMaxCount
;
188 * Pointer object for an item within a CGZ blob stored in the text table.
190 class HistoryBlobStub
{
192 * One-step cache variable to hold base blobs; operations that
193 * pull multiple revisions may often pull multiple times from
194 * the same blob. By keeping the last-used one open, we avoid
195 * redundant unserialization and decompression overhead.
197 protected static $blobCache = array();
199 var $mOldId, $mHash, $mRef;
202 * @param $hash string the content hash of the text
203 * @param $oldid Integer the old_id for the CGZ object
205 function __construct( $hash = '', $oldid = 0 ) {
206 $this->mHash
= $hash;
210 * Sets the location (old_id) of the main object to which this object
213 function setLocation( $id ) {
218 * Sets the location (old_id) of the referring object
220 function setReferrer( $id ) {
225 * Gets the location of the referring object
227 function getReferrer() {
235 $fname = 'HistoryBlobStub::getText';
237 if( isset( self
::$blobCache[$this->mOldId
] ) ) {
238 $obj = self
::$blobCache[$this->mOldId
];
240 $dbr = wfGetDB( DB_SLAVE
);
241 $row = $dbr->selectRow( 'text', array( 'old_flags', 'old_text' ), array( 'old_id' => $this->mOldId
) );
245 $flags = explode( ',', $row->old_flags
);
246 if( in_array( 'external', $flags ) ) {
248 $parts = explode( '://', $url, 2 );
249 if ( !isset( $parts[1] ) ||
$parts[1] == '' ) {
250 wfProfileOut( $fname );
253 $row->old_text
= ExternalStore
::fetchFromUrl($url);
256 if( !in_array( 'object', $flags ) ) {
260 if( in_array( 'gzip', $flags ) ) {
261 // This shouldn't happen, but a bug in the compress script
262 // may at times gzip-compress a HistoryBlob object row.
263 $obj = unserialize( gzinflate( $row->old_text
) );
265 $obj = unserialize( $row->old_text
);
268 if( !is_object( $obj ) ) {
269 // Correct for old double-serialization bug.
270 $obj = unserialize( $obj );
273 // Save this item for reference; if pulling many
274 // items in a row we'll likely use it again.
276 self
::$blobCache = array( $this->mOldId
=> $obj );
278 return $obj->getItem( $this->mHash
);
282 * Get the content hash
293 * To speed up conversion from 1.4 to 1.5 schema, text rows can refer to the
294 * leftover cur table as the backend. This avoids expensively copying hundreds
295 * of megabytes of data during the conversion downtime.
297 * Serialized HistoryBlobCurStub objects will be inserted into the text table
298 * on conversion if $wgFastSchemaUpgrades is set to true.
300 class HistoryBlobCurStub
{
304 * @param $curid Integer: the cur_id pointed to
306 function __construct( $curid = 0 ) {
307 $this->mCurId
= $curid;
311 * Sets the location (cur_id) of the main object to which this object
316 function setLocation( $id ) {
321 * @return string|bool
324 $dbr = wfGetDB( DB_SLAVE
);
325 $row = $dbr->selectRow( 'cur', array( 'cur_text' ), array( 'cur_id' => $this->mCurId
) );
329 return $row->cur_text
;
334 * Diff-based history compression
335 * Requires xdiff 1.5+ and zlib
337 class DiffHistoryBlob
implements HistoryBlob
{
338 /** Uncompressed item cache */
339 var $mItems = array();
341 /** Total uncompressed size */
345 * Array of diffs. If a diff D from A to B is notated D = B - A, and Z is
348 * { item[map[i]] - item[map[i-1]] where i > 0
350 * { item[map[i]] - Z where i = 0
354 /** The diff map, see above */
358 * The key for getText()
368 * True if the object is locked against further writes
370 var $mFrozen = false;
373 * The maximum uncompressed size before the object becomes sad
374 * Should be less than max_allowed_packet
376 var $mMaxSize = 10000000;
379 * The maximum number of text items before the object becomes sad
381 var $mMaxCount = 100;
383 /** Constants from xdiff.h */
384 const XDL_BDOP_INS
= 1;
385 const XDL_BDOP_CPY
= 2;
386 const XDL_BDOP_INSB
= 3;
388 function __construct() {
389 if ( !function_exists( 'gzdeflate' ) ) {
390 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
395 * @throws MWException
396 * @param $text string
399 function addItem( $text ) {
400 if ( $this->mFrozen
) {
401 throw new MWException( __METHOD__
.": Cannot add more items after sleep/wakeup" );
404 $this->mItems
[] = $text;
405 $this->mSize +
= strlen( $text );
406 $this->mDiffs
= null; // later
407 return count( $this->mItems
) - 1;
414 function getItem( $key ) {
415 return $this->mItems
[$key];
419 * @param $text string
421 function setText( $text ) {
422 $this->mDefaultKey
= $this->addItem( $text );
429 return $this->getItem( $this->mDefaultKey
);
433 * @throws MWException
435 function compress() {
436 if ( !function_exists( 'xdiff_string_rabdiff' ) ){
437 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
439 if ( isset( $this->mDiffs
) ) {
440 // Already compressed
443 if ( !count( $this->mItems
) ) {
448 // Create two diff sequences: one for main text and one for small text
463 for ( $i = 0; $i < count( $this->mItems
); $i++
) {
464 $text = $this->mItems
[$i];
468 $mainTail = $sequences['main']['tail'];
469 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
475 $seq =& $sequences[$seqName];
476 $tail = $seq['tail'];
477 $diff = $this->diff( $tail, $text );
478 $seq['diffs'][] = $diff;
480 $seq['tail'] = $text;
482 unset( $seq ); // unlink dangerous alias
484 // Knit the sequences together
486 $this->mDiffs
= array();
487 $this->mDiffMap
= array();
488 foreach ( $sequences as $seq ) {
489 if ( !count( $seq['diffs'] ) ) {
492 if ( $tail === '' ) {
493 $this->mDiffs
[] = $seq['diffs'][0];
495 $head = $this->patch( '', $seq['diffs'][0] );
496 $this->mDiffs
[] = $this->diff( $tail, $head );
498 $this->mDiffMap
[] = $seq['map'][0];
499 for ( $i = 1; $i < count( $seq['diffs'] ); $i++
) {
500 $this->mDiffs
[] = $seq['diffs'][$i];
501 $this->mDiffMap
[] = $seq['map'][$i];
503 $tail = $seq['tail'];
512 function diff( $t1, $t2 ) {
513 # Need to do a null concatenation with warnings off, due to bugs in the current version of xdiff
514 # "String is not zero-terminated"
515 wfSuppressWarnings();
516 $diff = xdiff_string_rabdiff( $t1, $t2 ) . '';
524 * @return bool|string
526 function patch( $base, $diff ) {
527 if ( function_exists( 'xdiff_string_bpatch' ) ) {
528 wfSuppressWarnings();
529 $text = xdiff_string_bpatch( $base, $diff ) . '';
534 # Pure PHP implementation
536 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
538 # Check the checksum if hash/mhash is available
539 $ofp = $this->xdiffAdler32( $base );
540 if ( $ofp !== false && $ofp !== substr( $diff, 0, 4 ) ) {
541 wfDebug( __METHOD__
. ": incorrect base checksum\n" );
544 if ( $header['csize'] != strlen( $base ) ) {
545 wfDebug( __METHOD__
. ": incorrect base length\n" );
551 while ( $p < strlen( $diff ) ) {
552 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
556 case self
::XDL_BDOP_INS
:
557 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
559 $out .= substr( $diff, $p, $x['size'] );
562 case self
::XDL_BDOP_INSB
:
563 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
565 $out .= substr( $diff, $p, $x['csize'] );
568 case self
::XDL_BDOP_CPY
:
569 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
571 $out .= substr( $base, $x['off'], $x['csize'] );
574 wfDebug( __METHOD__
.": invalid op\n" );
582 * Compute a binary "Adler-32" checksum as defined by LibXDiff, i.e. with
583 * the bytes backwards and initialised with 0 instead of 1. See bug 34428.
585 * Returns false if no hashing library is available
587 function xdiffAdler32( $s ) {
589 if ( $init === null ) {
590 $init = str_repeat( "\xf0", 205 ) . "\xee" . str_repeat( "\xf0", 67 ) . "\x02";
592 // The real Adler-32 checksum of $init is zero, so it initialises the
593 // state to zero, as it is at the start of LibXDiff's checksum
594 // algorithm. Appending the subject string then simulates LibXDiff.
595 if ( function_exists( 'hash' ) ) {
596 $hash = hash( 'adler32', $init . $s, true );
597 } elseif ( function_exists( 'mhash' ) ) {
598 $hash = mhash( MHASH_ADLER32
, $init . $s );
602 return strrev( $hash );
605 function uncompress() {
606 if ( !$this->mDiffs
) {
610 for ( $diffKey = 0; $diffKey < count( $this->mDiffs
); $diffKey++
) {
611 $textKey = $this->mDiffMap
[$diffKey];
612 $text = $this->patch( $tail, $this->mDiffs
[$diffKey] );
613 $this->mItems
[$textKey] = $text;
623 if ( !count( $this->mItems
) ) {
627 // Take forward differences to improve the compression ratio for sequences
630 foreach ( $this->mDiffMap
as $i ) {
638 'diffs' => $this->mDiffs
,
642 if ( isset( $this->mDefaultKey
) ) {
643 $info['default'] = $this->mDefaultKey
;
645 $this->mCompressed
= gzdeflate( serialize( $info ) );
646 return array( 'mCompressed' );
649 function __wakeup() {
650 // addItem() doesn't work if mItems is partially filled from mDiffs
651 $this->mFrozen
= true;
652 $info = unserialize( gzinflate( $this->mCompressed
) );
653 unset( $this->mCompressed
);
660 if ( isset( $info['default'] ) ) {
661 $this->mDefaultKey
= $info['default'];
663 $this->mDiffs
= $info['diffs'];
664 if ( isset( $info['base'] ) ) {
666 $this->mDiffMap
= range( 0, count( $this->mDiffs
) - 1 );
667 array_unshift( $this->mDiffs
,
668 pack( 'VVCV', 0, 0, self
::XDL_BDOP_INSB
, strlen( $info['base'] ) ) .
672 $map = explode( ',', $info['map'] );
674 $this->mDiffMap
= array();
675 foreach ( $map as $i ) {
677 $this->mDiffMap
[] = $cur;
684 * Helper function for compression jobs
685 * Returns true until the object is "full" and ready to be committed
690 return $this->mSize
< $this->mMaxSize
691 && count( $this->mItems
) < $this->mMaxCount
;