Revert back to jQuery 1.7.2
[mediawiki.git] / includes / HistoryBlob.php
blobbb8ec5e3ddfdf4c0602968d4329faf17f962f9cc
1 <?php
2 /**
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
20 * @file
23 /**
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.
28 interface HistoryBlob
30 /**
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
33 * database
35 * @param $text string
37 * @return String: the key for getItem()
39 function addItem( $text );
41 /**
42 * Get item by key, or false if the key is not present
44 * @param $key string
46 * @return String or false
48 function getItem( $key );
50 /**
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.
58 * @param $text string
60 function setText( $text );
62 /**
63 * Get default text. This is called from Revision::getRevisionText()
65 * @return String
67 function getText();
70 /**
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 = '';
77 public $mSize = 0;
78 public $mMaxSize = 10000000;
79 public $mMaxCount = 100;
81 /** Constructor */
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" );
88 /**
89 * @param $text string
90 * @return string
92 public function addItem( $text ) {
93 $this->uncompress();
94 $hash = md5( $text );
95 if ( !isset( $this->mItems[$hash] ) ) {
96 $this->mItems[$hash] = $text;
97 $this->mSize += strlen( $text );
99 return $hash;
103 * @param $hash string
104 * @return array|bool
106 public function getItem( $hash ) {
107 $this->uncompress();
108 if ( array_key_exists( $hash, $this->mItems ) ) {
109 return $this->mItems[$hash];
110 } else {
111 return false;
116 * @param $text string
117 * @return void
119 public function setText( $text ) {
120 $this->uncompress();
121 $this->mDefaultHash = $this->addItem( $text );
125 * @return array|bool
127 public function getText() {
128 $this->uncompress();
129 return $this->getItem( $this->mDefaultHash );
133 * Remove an item
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;
163 * @return array
165 function __sleep() {
166 $this->compress();
167 return array( 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' );
170 function __wakeup() {
171 $this->uncompress();
175 * Helper function for compression jobs
176 * Returns true until the object is "full" and ready to be committed
178 * @return bool
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
211 * points
213 function setLocation( $id ) {
214 $this->mOldId = $id;
218 * Sets the location (old_id) of the referring object
220 function setReferrer( $id ) {
221 $this->mRef = $id;
225 * Gets the location of the referring object
227 function getReferrer() {
228 return $this->mRef;
232 * @return string
234 function getText() {
235 $fname = 'HistoryBlobStub::getText';
237 if( isset( self::$blobCache[$this->mOldId] ) ) {
238 $obj = self::$blobCache[$this->mOldId];
239 } else {
240 $dbr = wfGetDB( DB_SLAVE );
241 $row = $dbr->selectRow( 'text', array( 'old_flags', 'old_text' ), array( 'old_id' => $this->mOldId ) );
242 if( !$row ) {
243 return false;
245 $flags = explode( ',', $row->old_flags );
246 if( in_array( 'external', $flags ) ) {
247 $url=$row->old_text;
248 $parts = explode( '://', $url, 2 );
249 if ( !isset( $parts[1] ) || $parts[1] == '' ) {
250 wfProfileOut( $fname );
251 return false;
253 $row->old_text = ExternalStore::fetchFromUrl($url);
256 if( !in_array( 'object', $flags ) ) {
257 return false;
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 ) );
264 } else {
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.
275 $obj->uncompress();
276 self::$blobCache = array( $this->mOldId => $obj );
278 return $obj->getItem( $this->mHash );
282 * Get the content hash
284 * @return string
286 function getHash() {
287 return $this->mHash;
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 {
301 var $mCurId;
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
312 * points
314 * @param $id int
316 function setLocation( $id ) {
317 $this->mCurId = $id;
321 * @return string|bool
323 function getText() {
324 $dbr = wfGetDB( DB_SLAVE );
325 $row = $dbr->selectRow( 'cur', array( 'cur_text' ), array( 'cur_id' => $this->mCurId ) );
326 if( !$row ) {
327 return false;
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 */
342 var $mSize = 0;
344 /**
345 * Array of diffs. If a diff D from A to B is notated D = B - A, and Z is
346 * an empty string:
348 * { item[map[i]] - item[map[i-1]] where i > 0
349 * diff[i] = {
350 * { item[map[i]] - Z where i = 0
352 var $mDiffs;
354 /** The diff map, see above */
355 var $mDiffMap;
358 * The key for getText()
360 var $mDefaultKey;
363 * Compressed storage
365 var $mCompressed;
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
397 * @return int
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;
411 * @param $key string
412 * @return string
414 function getItem( $key ) {
415 return $this->mItems[$key];
419 * @param $text string
421 function setText( $text ) {
422 $this->mDefaultKey = $this->addItem( $text );
426 * @return string
428 function getText() {
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
441 return;
443 if ( !count( $this->mItems ) ) {
444 // Empty
445 return;
448 // Create two diff sequences: one for main text and one for small text
449 $sequences = array(
450 'small' => array(
451 'tail' => '',
452 'diffs' => array(),
453 'map' => array(),
455 'main' => array(
456 'tail' => '',
457 'diffs' => array(),
458 'map' => array(),
461 $smallFactor = 0.5;
463 for ( $i = 0; $i < count( $this->mItems ); $i++ ) {
464 $text = $this->mItems[$i];
465 if ( $i == 0 ) {
466 $seqName = 'main';
467 } else {
468 $mainTail = $sequences['main']['tail'];
469 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
470 $seqName = 'small';
471 } else {
472 $seqName = 'main';
475 $seq =& $sequences[$seqName];
476 $tail = $seq['tail'];
477 $diff = $this->diff( $tail, $text );
478 $seq['diffs'][] = $diff;
479 $seq['map'][] = $i;
480 $seq['tail'] = $text;
482 unset( $seq ); // unlink dangerous alias
484 // Knit the sequences together
485 $tail = '';
486 $this->mDiffs = array();
487 $this->mDiffMap = array();
488 foreach ( $sequences as $seq ) {
489 if ( !count( $seq['diffs'] ) ) {
490 continue;
492 if ( $tail === '' ) {
493 $this->mDiffs[] = $seq['diffs'][0];
494 } else {
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'];
508 * @param $t1
509 * @param $t2
510 * @return string
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 ) . '';
517 wfRestoreWarnings();
518 return $diff;
522 * @param $base
523 * @param $diff
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 ) . '';
530 wfRestoreWarnings();
531 return $text;
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" );
542 return false;
544 if ( $header['csize'] != strlen( $base ) ) {
545 wfDebug( __METHOD__. ": incorrect base length\n" );
546 return false;
549 $p = 8;
550 $out = '';
551 while ( $p < strlen( $diff ) ) {
552 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
553 $op = $x['op'];
554 ++$p;
555 switch ( $op ) {
556 case self::XDL_BDOP_INS:
557 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
558 $p++;
559 $out .= substr( $diff, $p, $x['size'] );
560 $p += $x['size'];
561 break;
562 case self::XDL_BDOP_INSB:
563 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
564 $p += 4;
565 $out .= substr( $diff, $p, $x['csize'] );
566 $p += $x['csize'];
567 break;
568 case self::XDL_BDOP_CPY:
569 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
570 $p += 8;
571 $out .= substr( $base, $x['off'], $x['csize'] );
572 break;
573 default:
574 wfDebug( __METHOD__.": invalid op\n" );
575 return false;
578 return $out;
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 ) {
588 static $init;
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 );
599 } else {
600 return false;
602 return strrev( $hash );
605 function uncompress() {
606 if ( !$this->mDiffs ) {
607 return;
609 $tail = '';
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;
614 $tail = $text;
619 * @return array
621 function __sleep() {
622 $this->compress();
623 if ( !count( $this->mItems ) ) {
624 // Empty object
625 $info = false;
626 } else {
627 // Take forward differences to improve the compression ratio for sequences
628 $map = '';
629 $prev = 0;
630 foreach ( $this->mDiffMap as $i ) {
631 if ( $map !== '' ) {
632 $map .= ',';
634 $map .= $i - $prev;
635 $prev = $i;
637 $info = array(
638 'diffs' => $this->mDiffs,
639 'map' => $map
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 );
655 if ( !$info ) {
656 // Empty object
657 return;
660 if ( isset( $info['default'] ) ) {
661 $this->mDefaultKey = $info['default'];
663 $this->mDiffs = $info['diffs'];
664 if ( isset( $info['base'] ) ) {
665 // Old format
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'] ) ) .
669 $info['base'] );
670 } else {
671 // New format
672 $map = explode( ',', $info['map'] );
673 $cur = 0;
674 $this->mDiffMap = array();
675 foreach ( $map as $i ) {
676 $cur += $i;
677 $this->mDiffMap[] = $cur;
680 $this->uncompress();
684 * Helper function for compression jobs
685 * Returns true until the object is "full" and ready to be committed
687 * @return bool
689 function isHappy() {
690 return $this->mSize < $this->mMaxSize
691 && count( $this->mItems ) < $this->mMaxCount;