(bug 44595) LanguageTest::testIsSupportedLanguage fails on Windows
[lhc/web/wiklou.git] / includes / HistoryBlob.php
1 <?php
2 /**
3 * Efficient concatenated text storage.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
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.
27 */
28 interface HistoryBlob
29 {
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
34 *
35 * @param $text string
36 *
37 * @return String: the key for getItem()
38 */
39 function addItem( $text );
40
41 /**
42 * Get item by key, or false if the key is not present
43 *
44 * @param $key string
45 *
46 * @return String or false
47 */
48 function getItem( $key );
49
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.
55 *
56 * Default text is not required for two-part external storage URLs.
57 *
58 * @param $text string
59 */
60 function setText( $text );
61
62 /**
63 * Get default text. This is called from Revision::getRevisionText()
64 *
65 * @return String
66 */
67 function getText();
68 }
69
70 /**
71 * Concatenated gzip (CGZ) storage
72 * Improves compression ratio by concatenating like objects before gzipping
73 */
74 class ConcatenatedGzipHistoryBlob implements HistoryBlob
75 {
76 public $mVersion = 0, $mCompressed = false, $mItems = array(), $mDefaultHash = '';
77 public $mSize = 0;
78 public $mMaxSize = 10000000;
79 public $mMaxCount = 100;
80
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" );
85 }
86 }
87
88 /**
89 * @param $text string
90 * @return string
91 */
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 );
98 }
99 return $hash;
100 }
101
102 /**
103 * @param $hash string
104 * @return array|bool
105 */
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;
112 }
113 }
114
115 /**
116 * @param $text string
117 * @return void
118 */
119 public function setText( $text ) {
120 $this->uncompress();
121 $this->mDefaultHash = $this->addItem( $text );
122 }
123
124 /**
125 * @return array|bool
126 */
127 public function getText() {
128 $this->uncompress();
129 return $this->getItem( $this->mDefaultHash );
130 }
131
132 /**
133 * Remove an item
134 *
135 * @param $hash string
136 */
137 public function removeItem( $hash ) {
138 $this->mSize -= strlen( $this->mItems[$hash] );
139 unset( $this->mItems[$hash] );
140 }
141
142 /**
143 * Compress the bulk data in the object
144 */
145 public function compress() {
146 if ( !$this->mCompressed ) {
147 $this->mItems = gzdeflate( serialize( $this->mItems ) );
148 $this->mCompressed = true;
149 }
150 }
151
152 /**
153 * Uncompress bulk data
154 */
155 public function uncompress() {
156 if ( $this->mCompressed ) {
157 $this->mItems = unserialize( gzinflate( $this->mItems ) );
158 $this->mCompressed = false;
159 }
160 }
161
162 /**
163 * @return array
164 */
165 function __sleep() {
166 $this->compress();
167 return array( 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' );
168 }
169
170 function __wakeup() {
171 $this->uncompress();
172 }
173
174 /**
175 * Helper function for compression jobs
176 * Returns true until the object is "full" and ready to be committed
177 *
178 * @return bool
179 */
180 public function isHappy() {
181 return $this->mSize < $this->mMaxSize
182 && count( $this->mItems ) < $this->mMaxCount;
183 }
184 }
185
186
187 /**
188 * Pointer object for an item within a CGZ blob stored in the text table.
189 */
190 class HistoryBlobStub {
191 /**
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.
196 */
197 protected static $blobCache = array();
198
199 var $mOldId, $mHash, $mRef;
200
201 /**
202 * @param $hash string the content hash of the text
203 * @param $oldid Integer the old_id for the CGZ object
204 */
205 function __construct( $hash = '', $oldid = 0 ) {
206 $this->mHash = $hash;
207 }
208
209 /**
210 * Sets the location (old_id) of the main object to which this object
211 * points
212 */
213 function setLocation( $id ) {
214 $this->mOldId = $id;
215 }
216
217 /**
218 * Sets the location (old_id) of the referring object
219 */
220 function setReferrer( $id ) {
221 $this->mRef = $id;
222 }
223
224 /**
225 * Gets the location of the referring object
226 */
227 function getReferrer() {
228 return $this->mRef;
229 }
230
231 /**
232 * @return string
233 */
234 function getText() {
235 if( isset( self::$blobCache[$this->mOldId] ) ) {
236 $obj = self::$blobCache[$this->mOldId];
237 } else {
238 $dbr = wfGetDB( DB_SLAVE );
239 $row = $dbr->selectRow( 'text', array( 'old_flags', 'old_text' ), array( 'old_id' => $this->mOldId ) );
240 if( !$row ) {
241 return false;
242 }
243 $flags = explode( ',', $row->old_flags );
244 if( in_array( 'external', $flags ) ) {
245 $url = $row->old_text;
246 $parts = explode( '://', $url, 2 );
247 if ( !isset( $parts[1] ) || $parts[1] == '' ) {
248 return false;
249 }
250 $row->old_text = ExternalStore::fetchFromUrl($url);
251
252 }
253 if( !in_array( 'object', $flags ) ) {
254 return false;
255 }
256
257 if( in_array( 'gzip', $flags ) ) {
258 // This shouldn't happen, but a bug in the compress script
259 // may at times gzip-compress a HistoryBlob object row.
260 $obj = unserialize( gzinflate( $row->old_text ) );
261 } else {
262 $obj = unserialize( $row->old_text );
263 }
264
265 if( !is_object( $obj ) ) {
266 // Correct for old double-serialization bug.
267 $obj = unserialize( $obj );
268 }
269
270 // Save this item for reference; if pulling many
271 // items in a row we'll likely use it again.
272 $obj->uncompress();
273 self::$blobCache = array( $this->mOldId => $obj );
274 }
275 return $obj->getItem( $this->mHash );
276 }
277
278 /**
279 * Get the content hash
280 *
281 * @return string
282 */
283 function getHash() {
284 return $this->mHash;
285 }
286 }
287
288
289 /**
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.
293 *
294 * Serialized HistoryBlobCurStub objects will be inserted into the text table
295 * on conversion if $wgFastSchemaUpgrades is set to true.
296 */
297 class HistoryBlobCurStub {
298 var $mCurId;
299
300 /**
301 * @param $curid Integer: the cur_id pointed to
302 */
303 function __construct( $curid = 0 ) {
304 $this->mCurId = $curid;
305 }
306
307 /**
308 * Sets the location (cur_id) of the main object to which this object
309 * points
310 *
311 * @param $id int
312 */
313 function setLocation( $id ) {
314 $this->mCurId = $id;
315 }
316
317 /**
318 * @return string|bool
319 */
320 function getText() {
321 $dbr = wfGetDB( DB_SLAVE );
322 $row = $dbr->selectRow( 'cur', array( 'cur_text' ), array( 'cur_id' => $this->mCurId ) );
323 if( !$row ) {
324 return false;
325 }
326 return $row->cur_text;
327 }
328 }
329
330 /**
331 * Diff-based history compression
332 * Requires xdiff 1.5+ and zlib
333 */
334 class DiffHistoryBlob implements HistoryBlob {
335 /** Uncompressed item cache */
336 var $mItems = array();
337
338 /** Total uncompressed size */
339 var $mSize = 0;
340
341 /**
342 * Array of diffs. If a diff D from A to B is notated D = B - A, and Z is
343 * an empty string:
344 *
345 * { item[map[i]] - item[map[i-1]] where i > 0
346 * diff[i] = {
347 * { item[map[i]] - Z where i = 0
348 */
349 var $mDiffs;
350
351 /** The diff map, see above */
352 var $mDiffMap;
353
354 /**
355 * The key for getText()
356 */
357 var $mDefaultKey;
358
359 /**
360 * Compressed storage
361 */
362 var $mCompressed;
363
364 /**
365 * True if the object is locked against further writes
366 */
367 var $mFrozen = false;
368
369 /**
370 * The maximum uncompressed size before the object becomes sad
371 * Should be less than max_allowed_packet
372 */
373 var $mMaxSize = 10000000;
374
375 /**
376 * The maximum number of text items before the object becomes sad
377 */
378 var $mMaxCount = 100;
379
380 /** Constants from xdiff.h */
381 const XDL_BDOP_INS = 1;
382 const XDL_BDOP_CPY = 2;
383 const XDL_BDOP_INSB = 3;
384
385 function __construct() {
386 if ( !function_exists( 'gzdeflate' ) ) {
387 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
388 }
389 }
390
391 /**
392 * @throws MWException
393 * @param $text string
394 * @return int
395 */
396 function addItem( $text ) {
397 if ( $this->mFrozen ) {
398 throw new MWException( __METHOD__.": Cannot add more items after sleep/wakeup" );
399 }
400
401 $this->mItems[] = $text;
402 $this->mSize += strlen( $text );
403 $this->mDiffs = null; // later
404 return count( $this->mItems ) - 1;
405 }
406
407 /**
408 * @param $key string
409 * @return string
410 */
411 function getItem( $key ) {
412 return $this->mItems[$key];
413 }
414
415 /**
416 * @param $text string
417 */
418 function setText( $text ) {
419 $this->mDefaultKey = $this->addItem( $text );
420 }
421
422 /**
423 * @return string
424 */
425 function getText() {
426 return $this->getItem( $this->mDefaultKey );
427 }
428
429 /**
430 * @throws MWException
431 */
432 function compress() {
433 if ( !function_exists( 'xdiff_string_rabdiff' ) ) {
434 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
435 }
436 if ( isset( $this->mDiffs ) ) {
437 // Already compressed
438 return;
439 }
440 if ( !count( $this->mItems ) ) {
441 // Empty
442 return;
443 }
444
445 // Create two diff sequences: one for main text and one for small text
446 $sequences = array(
447 'small' => array(
448 'tail' => '',
449 'diffs' => array(),
450 'map' => array(),
451 ),
452 'main' => array(
453 'tail' => '',
454 'diffs' => array(),
455 'map' => array(),
456 ),
457 );
458 $smallFactor = 0.5;
459
460 for ( $i = 0; $i < count( $this->mItems ); $i++ ) {
461 $text = $this->mItems[$i];
462 if ( $i == 0 ) {
463 $seqName = 'main';
464 } else {
465 $mainTail = $sequences['main']['tail'];
466 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
467 $seqName = 'small';
468 } else {
469 $seqName = 'main';
470 }
471 }
472 $seq =& $sequences[$seqName];
473 $tail = $seq['tail'];
474 $diff = $this->diff( $tail, $text );
475 $seq['diffs'][] = $diff;
476 $seq['map'][] = $i;
477 $seq['tail'] = $text;
478 }
479 unset( $seq ); // unlink dangerous alias
480
481 // Knit the sequences together
482 $tail = '';
483 $this->mDiffs = array();
484 $this->mDiffMap = array();
485 foreach ( $sequences as $seq ) {
486 if ( !count( $seq['diffs'] ) ) {
487 continue;
488 }
489 if ( $tail === '' ) {
490 $this->mDiffs[] = $seq['diffs'][0];
491 } else {
492 $head = $this->patch( '', $seq['diffs'][0] );
493 $this->mDiffs[] = $this->diff( $tail, $head );
494 }
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];
499 }
500 $tail = $seq['tail'];
501 }
502 }
503
504 /**
505 * @param $t1
506 * @param $t2
507 * @return string
508 */
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 ) . '';
514 wfRestoreWarnings();
515 return $diff;
516 }
517
518 /**
519 * @param $base
520 * @param $diff
521 * @return bool|string
522 */
523 function patch( $base, $diff ) {
524 if ( function_exists( 'xdiff_string_bpatch' ) ) {
525 wfSuppressWarnings();
526 $text = xdiff_string_bpatch( $base, $diff ) . '';
527 wfRestoreWarnings();
528 return $text;
529 }
530
531 # Pure PHP implementation
532
533 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
534
535 # Check the checksum if hash/mhash is available
536 $ofp = $this->xdiffAdler32( $base );
537 if ( $ofp !== false && $ofp !== substr( $diff, 0, 4 ) ) {
538 wfDebug( __METHOD__. ": incorrect base checksum\n" );
539 return false;
540 }
541 if ( $header['csize'] != strlen( $base ) ) {
542 wfDebug( __METHOD__. ": incorrect base length\n" );
543 return false;
544 }
545
546 $p = 8;
547 $out = '';
548 while ( $p < strlen( $diff ) ) {
549 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
550 $op = $x['op'];
551 ++$p;
552 switch ( $op ) {
553 case self::XDL_BDOP_INS:
554 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
555 $p++;
556 $out .= substr( $diff, $p, $x['size'] );
557 $p += $x['size'];
558 break;
559 case self::XDL_BDOP_INSB:
560 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
561 $p += 4;
562 $out .= substr( $diff, $p, $x['csize'] );
563 $p += $x['csize'];
564 break;
565 case self::XDL_BDOP_CPY:
566 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
567 $p += 8;
568 $out .= substr( $base, $x['off'], $x['csize'] );
569 break;
570 default:
571 wfDebug( __METHOD__.": invalid op\n" );
572 return false;
573 }
574 }
575 return $out;
576 }
577
578 /**
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.
581 *
582 * Returns false if no hashing library is available
583 */
584 function xdiffAdler32( $s ) {
585 static $init;
586 if ( $init === null ) {
587 $init = str_repeat( "\xf0", 205 ) . "\xee" . str_repeat( "\xf0", 67 ) . "\x02";
588 }
589 // The real Adler-32 checksum of $init is zero, so it initialises the
590 // state to zero, as it is at the start of LibXDiff's checksum
591 // algorithm. Appending the subject string then simulates LibXDiff.
592 if ( function_exists( 'hash' ) ) {
593 $hash = hash( 'adler32', $init . $s, true );
594 } elseif ( function_exists( 'mhash' ) ) {
595 $hash = mhash( MHASH_ADLER32, $init . $s );
596 } else {
597 return false;
598 }
599 return strrev( $hash );
600 }
601
602 function uncompress() {
603 if ( !$this->mDiffs ) {
604 return;
605 }
606 $tail = '';
607 for ( $diffKey = 0; $diffKey < count( $this->mDiffs ); $diffKey++ ) {
608 $textKey = $this->mDiffMap[$diffKey];
609 $text = $this->patch( $tail, $this->mDiffs[$diffKey] );
610 $this->mItems[$textKey] = $text;
611 $tail = $text;
612 }
613 }
614
615 /**
616 * @return array
617 */
618 function __sleep() {
619 $this->compress();
620 if ( !count( $this->mItems ) ) {
621 // Empty object
622 $info = false;
623 } else {
624 // Take forward differences to improve the compression ratio for sequences
625 $map = '';
626 $prev = 0;
627 foreach ( $this->mDiffMap as $i ) {
628 if ( $map !== '' ) {
629 $map .= ',';
630 }
631 $map .= $i - $prev;
632 $prev = $i;
633 }
634 $info = array(
635 'diffs' => $this->mDiffs,
636 'map' => $map
637 );
638 }
639 if ( isset( $this->mDefaultKey ) ) {
640 $info['default'] = $this->mDefaultKey;
641 }
642 $this->mCompressed = gzdeflate( serialize( $info ) );
643 return array( 'mCompressed' );
644 }
645
646 function __wakeup() {
647 // addItem() doesn't work if mItems is partially filled from mDiffs
648 $this->mFrozen = true;
649 $info = unserialize( gzinflate( $this->mCompressed ) );
650 unset( $this->mCompressed );
651
652 if ( !$info ) {
653 // Empty object
654 return;
655 }
656
657 if ( isset( $info['default'] ) ) {
658 $this->mDefaultKey = $info['default'];
659 }
660 $this->mDiffs = $info['diffs'];
661 if ( isset( $info['base'] ) ) {
662 // Old format
663 $this->mDiffMap = range( 0, count( $this->mDiffs ) - 1 );
664 array_unshift( $this->mDiffs,
665 pack( 'VVCV', 0, 0, self::XDL_BDOP_INSB, strlen( $info['base'] ) ) .
666 $info['base'] );
667 } else {
668 // New format
669 $map = explode( ',', $info['map'] );
670 $cur = 0;
671 $this->mDiffMap = array();
672 foreach ( $map as $i ) {
673 $cur += $i;
674 $this->mDiffMap[] = $cur;
675 }
676 }
677 $this->uncompress();
678 }
679
680 /**
681 * Helper function for compression jobs
682 * Returns true until the object is "full" and ready to be committed
683 *
684 * @return bool
685 */
686 function isHappy() {
687 return $this->mSize < $this->mMaxSize
688 && count( $this->mItems ) < $this->mMaxCount;
689 }
690
691 }