3fc27a29449f9acbf81476b5a4e4137b484d03d1
[lhc/web/wiklou.git] / includes / HistoryBlob.php
1 <?php
2
3 /**
4 * Base class for general text storage via the "object" flag in old_flags, or
5 * two-part external storage URLs. Used for represent efficient concatenated
6 * storage, and migration-related pointer objects.
7 */
8 interface HistoryBlob
9 {
10 /**
11 * Adds an item of text, returns a stub object which points to the item.
12 * You must call setLocation() on the stub object before storing it to the
13 * database
14 *
15 * @param $text string
16 *
17 * @return String: the key for getItem()
18 */
19 function addItem( $text );
20
21 /**
22 * Get item by key, or false if the key is not present
23 *
24 * @param $key string
25 *
26 * @return String or false
27 */
28 function getItem( $key );
29
30 /**
31 * Set the "default text"
32 * This concept is an odd property of the current DB schema, whereby each text item has a revision
33 * associated with it. The default text is the text of the associated revision. There may, however,
34 * be other revisions in the same object.
35 *
36 * Default text is not required for two-part external storage URLs.
37 *
38 * @param $text string
39 */
40 function setText( $text );
41
42 /**
43 * Get default text. This is called from Revision::getRevisionText()
44 *
45 * @return String
46 */
47 function getText();
48 }
49
50 /**
51 * Concatenated gzip (CGZ) storage
52 * Improves compression ratio by concatenating like objects before gzipping
53 */
54 class ConcatenatedGzipHistoryBlob implements HistoryBlob
55 {
56 public $mVersion = 0, $mCompressed = false, $mItems = array(), $mDefaultHash = '';
57 public $mSize = 0;
58 public $mMaxSize = 10000000;
59 public $mMaxCount = 100;
60
61 /** Constructor */
62 public function __construct() {
63 if ( !function_exists( 'gzdeflate' ) ) {
64 throw new MWException( "Need zlib support to read or write this kind of history object (ConcatenatedGzipHistoryBlob)\n" );
65 }
66 }
67
68 /**
69 * @param $text string
70 * @return string
71 */
72 public function addItem( $text ) {
73 $this->uncompress();
74 $hash = md5( $text );
75 if ( !isset( $this->mItems[$hash] ) ) {
76 $this->mItems[$hash] = $text;
77 $this->mSize += strlen( $text );
78 }
79 return $hash;
80 }
81
82 /**
83 * @param $hash string
84 * @return array|bool
85 */
86 public function getItem( $hash ) {
87 $this->uncompress();
88 if ( array_key_exists( $hash, $this->mItems ) ) {
89 return $this->mItems[$hash];
90 } else {
91 return false;
92 }
93 }
94
95 /**
96 * @param $text string
97 * @return void
98 */
99 public function setText( $text ) {
100 $this->uncompress();
101 $this->mDefaultHash = $this->addItem( $text );
102 }
103
104 /**
105 * @return array|bool
106 */
107 public function getText() {
108 $this->uncompress();
109 return $this->getItem( $this->mDefaultHash );
110 }
111
112 /**
113 * Remove an item
114 *
115 * @param $hash string
116 */
117 public function removeItem( $hash ) {
118 $this->mSize -= strlen( $this->mItems[$hash] );
119 unset( $this->mItems[$hash] );
120 }
121
122 /**
123 * Compress the bulk data in the object
124 */
125 public function compress() {
126 if ( !$this->mCompressed ) {
127 $this->mItems = gzdeflate( serialize( $this->mItems ) );
128 $this->mCompressed = true;
129 }
130 }
131
132 /**
133 * Uncompress bulk data
134 */
135 public function uncompress() {
136 if ( $this->mCompressed ) {
137 $this->mItems = unserialize( gzinflate( $this->mItems ) );
138 $this->mCompressed = false;
139 }
140 }
141
142 /**
143 * @return array
144 */
145 function __sleep() {
146 $this->compress();
147 return array( 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' );
148 }
149
150 function __wakeup() {
151 $this->uncompress();
152 }
153
154 /**
155 * Helper function for compression jobs
156 * Returns true until the object is "full" and ready to be committed
157 *
158 * @return bool
159 */
160 public function isHappy() {
161 return $this->mSize < $this->mMaxSize
162 && count( $this->mItems ) < $this->mMaxCount;
163 }
164 }
165
166
167 /**
168 * Pointer object for an item within a CGZ blob stored in the text table.
169 */
170 class HistoryBlobStub {
171 /**
172 * One-step cache variable to hold base blobs; operations that
173 * pull multiple revisions may often pull multiple times from
174 * the same blob. By keeping the last-used one open, we avoid
175 * redundant unserialization and decompression overhead.
176 */
177 protected static $blobCache = array();
178
179 var $mOldId, $mHash, $mRef;
180
181 /**
182 * @param $hash Strng: the content hash of the text
183 * @param $oldid Integer: the old_id for the CGZ object
184 */
185 function __construct( $hash = '', $oldid = 0 ) {
186 $this->mHash = $hash;
187 }
188
189 /**
190 * Sets the location (old_id) of the main object to which this object
191 * points
192 */
193 function setLocation( $id ) {
194 $this->mOldId = $id;
195 }
196
197 /**
198 * Sets the location (old_id) of the referring object
199 */
200 function setReferrer( $id ) {
201 $this->mRef = $id;
202 }
203
204 /**
205 * Gets the location of the referring object
206 */
207 function getReferrer() {
208 return $this->mRef;
209 }
210
211 /**
212 * @return string
213 */
214 function getText() {
215 $fname = 'HistoryBlobStub::getText';
216
217 if( isset( self::$blobCache[$this->mOldId] ) ) {
218 $obj = self::$blobCache[$this->mOldId];
219 } else {
220 $dbr = wfGetDB( DB_SLAVE );
221 $row = $dbr->selectRow( 'text', array( 'old_flags', 'old_text' ), array( 'old_id' => $this->mOldId ) );
222 if( !$row ) {
223 return false;
224 }
225 $flags = explode( ',', $row->old_flags );
226 if( in_array( 'external', $flags ) ) {
227 $url=$row->old_text;
228 @list( /* $proto */ ,$path)=explode('://',$url,2);
229 if ( $path == "" ) {
230 wfProfileOut( $fname );
231 return false;
232 }
233 $row->old_text = ExternalStore::fetchFromUrl($url);
234
235 }
236 if( !in_array( 'object', $flags ) ) {
237 return false;
238 }
239
240 if( in_array( 'gzip', $flags ) ) {
241 // This shouldn't happen, but a bug in the compress script
242 // may at times gzip-compress a HistoryBlob object row.
243 $obj = unserialize( gzinflate( $row->old_text ) );
244 } else {
245 $obj = unserialize( $row->old_text );
246 }
247
248 if( !is_object( $obj ) ) {
249 // Correct for old double-serialization bug.
250 $obj = unserialize( $obj );
251 }
252
253 // Save this item for reference; if pulling many
254 // items in a row we'll likely use it again.
255 $obj->uncompress();
256 self::$blobCache = array( $this->mOldId => $obj );
257 }
258 return $obj->getItem( $this->mHash );
259 }
260
261 /**
262 * Get the content hash
263 *
264 * @return string
265 */
266 function getHash() {
267 return $this->mHash;
268 }
269 }
270
271
272 /**
273 * To speed up conversion from 1.4 to 1.5 schema, text rows can refer to the
274 * leftover cur table as the backend. This avoids expensively copying hundreds
275 * of megabytes of data during the conversion downtime.
276 *
277 * Serialized HistoryBlobCurStub objects will be inserted into the text table
278 * on conversion if $wgFastSchemaUpgrades is set to true.
279 */
280 class HistoryBlobCurStub {
281 var $mCurId;
282
283 /**
284 * @param $curid Integer: the cur_id pointed to
285 */
286 function __construct( $curid = 0 ) {
287 $this->mCurId = $curid;
288 }
289
290 /**
291 * Sets the location (cur_id) of the main object to which this object
292 * points
293 */
294 function setLocation( $id ) {
295 $this->mCurId = $id;
296 }
297
298 /**
299 * @return string|false
300 */
301 function getText() {
302 $dbr = wfGetDB( DB_SLAVE );
303 $row = $dbr->selectRow( 'cur', array( 'cur_text' ), array( 'cur_id' => $this->mCurId ) );
304 if( !$row ) {
305 return false;
306 }
307 return $row->cur_text;
308 }
309 }
310
311 /**
312 * Diff-based history compression
313 * Requires xdiff 1.5+ and zlib
314 */
315 class DiffHistoryBlob implements HistoryBlob {
316 /** Uncompressed item cache */
317 var $mItems = array();
318
319 /** Total uncompressed size */
320 var $mSize = 0;
321
322 /**
323 * Array of diffs. If a diff D from A to B is notated D = B - A, and Z is
324 * an empty string:
325 *
326 * { item[map[i]] - item[map[i-1]] where i > 0
327 * diff[i] = {
328 * { item[map[i]] - Z where i = 0
329 */
330 var $mDiffs;
331
332 /** The diff map, see above */
333 var $mDiffMap;
334
335 /**
336 * The key for getText()
337 */
338 var $mDefaultKey;
339
340 /**
341 * Compressed storage
342 */
343 var $mCompressed;
344
345 /**
346 * True if the object is locked against further writes
347 */
348 var $mFrozen = false;
349
350 /**
351 * The maximum uncompressed size before the object becomes sad
352 * Should be less than max_allowed_packet
353 */
354 var $mMaxSize = 10000000;
355
356 /**
357 * The maximum number of text items before the object becomes sad
358 */
359 var $mMaxCount = 100;
360
361 /** Constants from xdiff.h */
362 const XDL_BDOP_INS = 1;
363 const XDL_BDOP_CPY = 2;
364 const XDL_BDOP_INSB = 3;
365
366 function __construct() {
367 if ( !function_exists( 'gzdeflate' ) ) {
368 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
369 }
370 }
371
372 /**
373 * @throws MWException
374 * @param $text string
375 * @return int
376 */
377 function addItem( $text ) {
378 if ( $this->mFrozen ) {
379 throw new MWException( __METHOD__.": Cannot add more items after sleep/wakeup" );
380 }
381
382 $this->mItems[] = $text;
383 $this->mSize += strlen( $text );
384 $this->mDiffs = null; // later
385 return count( $this->mItems ) - 1;
386 }
387
388 /**
389 * @param $key string
390 * @return string
391 */
392 function getItem( $key ) {
393 return $this->mItems[$key];
394 }
395
396 /**
397 * @param $text string
398 */
399 function setText( $text ) {
400 $this->mDefaultKey = $this->addItem( $text );
401 }
402
403 /**
404 * @return string
405 */
406 function getText() {
407 return $this->getItem( $this->mDefaultKey );
408 }
409
410 /**
411 * @throws MWException
412 */
413 function compress() {
414 if ( !function_exists( 'xdiff_string_rabdiff' ) ){
415 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
416 }
417 if ( isset( $this->mDiffs ) ) {
418 // Already compressed
419 return;
420 }
421 if ( !count( $this->mItems ) ) {
422 // Empty
423 return;
424 }
425
426 // Create two diff sequences: one for main text and one for small text
427 $sequences = array(
428 'small' => array(
429 'tail' => '',
430 'diffs' => array(),
431 'map' => array(),
432 ),
433 'main' => array(
434 'tail' => '',
435 'diffs' => array(),
436 'map' => array(),
437 ),
438 );
439 $smallFactor = 0.5;
440
441 for ( $i = 0; $i < count( $this->mItems ); $i++ ) {
442 $text = $this->mItems[$i];
443 if ( $i == 0 ) {
444 $seqName = 'main';
445 } else {
446 $mainTail = $sequences['main']['tail'];
447 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
448 $seqName = 'small';
449 } else {
450 $seqName = 'main';
451 }
452 }
453 $seq =& $sequences[$seqName];
454 $tail = $seq['tail'];
455 $diff = $this->diff( $tail, $text );
456 $seq['diffs'][] = $diff;
457 $seq['map'][] = $i;
458 $seq['tail'] = $text;
459 }
460 unset( $seq ); // unlink dangerous alias
461
462 // Knit the sequences together
463 $tail = '';
464 $this->mDiffs = array();
465 $this->mDiffMap = array();
466 foreach ( $sequences as $seq ) {
467 if ( !count( $seq['diffs'] ) ) {
468 continue;
469 }
470 if ( $tail === '' ) {
471 $this->mDiffs[] = $seq['diffs'][0];
472 } else {
473 $head = $this->patch( '', $seq['diffs'][0] );
474 $this->mDiffs[] = $this->diff( $tail, $head );
475 }
476 $this->mDiffMap[] = $seq['map'][0];
477 for ( $i = 1; $i < count( $seq['diffs'] ); $i++ ) {
478 $this->mDiffs[] = $seq['diffs'][$i];
479 $this->mDiffMap[] = $seq['map'][$i];
480 }
481 $tail = $seq['tail'];
482 }
483 }
484
485 function diff( $t1, $t2 ) {
486 # Need to do a null concatenation with warnings off, due to bugs in the current version of xdiff
487 # "String is not zero-terminated"
488 wfSuppressWarnings();
489 $diff = xdiff_string_rabdiff( $t1, $t2 ) . '';
490 wfRestoreWarnings();
491 return $diff;
492 }
493
494 function patch( $base, $diff ) {
495 if ( function_exists( 'xdiff_string_bpatch' ) ) {
496 wfSuppressWarnings();
497 $text = xdiff_string_bpatch( $base, $diff ) . '';
498 wfRestoreWarnings();
499 return $text;
500 }
501
502 # Pure PHP implementation
503
504 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
505
506 # Check the checksum if mhash is available
507 if ( extension_loaded( 'mhash' ) ) {
508 $ofp = mhash( MHASH_ADLER32, $base );
509 if ( $ofp !== substr( $diff, 0, 4 ) ) {
510 wfDebug( __METHOD__. ": incorrect base checksum\n" );
511 return false;
512 }
513 }
514 if ( $header['csize'] != strlen( $base ) ) {
515 wfDebug( __METHOD__. ": incorrect base length\n" );
516 return false;
517 }
518
519 $p = 8;
520 $out = '';
521 while ( $p < strlen( $diff ) ) {
522 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
523 $op = $x['op'];
524 ++$p;
525 switch ( $op ) {
526 case self::XDL_BDOP_INS:
527 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
528 $p++;
529 $out .= substr( $diff, $p, $x['size'] );
530 $p += $x['size'];
531 break;
532 case self::XDL_BDOP_INSB:
533 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
534 $p += 4;
535 $out .= substr( $diff, $p, $x['csize'] );
536 $p += $x['csize'];
537 break;
538 case self::XDL_BDOP_CPY:
539 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
540 $p += 8;
541 $out .= substr( $base, $x['off'], $x['csize'] );
542 break;
543 default:
544 wfDebug( __METHOD__.": invalid op\n" );
545 return false;
546 }
547 }
548 return $out;
549 }
550
551 function uncompress() {
552 if ( !$this->mDiffs ) {
553 return;
554 }
555 $tail = '';
556 for ( $diffKey = 0; $diffKey < count( $this->mDiffs ); $diffKey++ ) {
557 $textKey = $this->mDiffMap[$diffKey];
558 $text = $this->patch( $tail, $this->mDiffs[$diffKey] );
559 $this->mItems[$textKey] = $text;
560 $tail = $text;
561 }
562 }
563
564 function __sleep() {
565 $this->compress();
566 if ( !count( $this->mItems ) ) {
567 // Empty object
568 $info = false;
569 } else {
570 // Take forward differences to improve the compression ratio for sequences
571 $map = '';
572 $prev = 0;
573 foreach ( $this->mDiffMap as $i ) {
574 if ( $map !== '' ) {
575 $map .= ',';
576 }
577 $map .= $i - $prev;
578 $prev = $i;
579 }
580 $info = array(
581 'diffs' => $this->mDiffs,
582 'map' => $map
583 );
584 }
585 if ( isset( $this->mDefaultKey ) ) {
586 $info['default'] = $this->mDefaultKey;
587 }
588 $this->mCompressed = gzdeflate( serialize( $info ) );
589 return array( 'mCompressed' );
590 }
591
592 function __wakeup() {
593 // addItem() doesn't work if mItems is partially filled from mDiffs
594 $this->mFrozen = true;
595 $info = unserialize( gzinflate( $this->mCompressed ) );
596 unset( $this->mCompressed );
597
598 if ( !$info ) {
599 // Empty object
600 return;
601 }
602
603 if ( isset( $info['default'] ) ) {
604 $this->mDefaultKey = $info['default'];
605 }
606 $this->mDiffs = $info['diffs'];
607 if ( isset( $info['base'] ) ) {
608 // Old format
609 $this->mDiffMap = range( 0, count( $this->mDiffs ) - 1 );
610 array_unshift( $this->mDiffs,
611 pack( 'VVCV', 0, 0, self::XDL_BDOP_INSB, strlen( $info['base'] ) ) .
612 $info['base'] );
613 } else {
614 // New format
615 $map = explode( ',', $info['map'] );
616 $cur = 0;
617 $this->mDiffMap = array();
618 foreach ( $map as $i ) {
619 $cur += $i;
620 $this->mDiffMap[] = $cur;
621 }
622 }
623 $this->uncompress();
624 }
625
626 /**
627 * Helper function for compression jobs
628 * Returns true until the object is "full" and ready to be committed
629 */
630 function isHappy() {
631 return $this->mSize < $this->mMaxSize
632 && count( $this->mItems ) < $this->mMaxCount;
633 }
634
635 }