Merge "CologneBlue rewrite: kill mWatchLinkNum, watchThisPage() is only called once...
[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 $fname = 'HistoryBlobStub::getText';
236
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;
244 }
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;
252 }
253 $row->old_text = ExternalStore::fetchFromUrl($url);
254
255 }
256 if( !in_array( 'object', $flags ) ) {
257 return false;
258 }
259
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 );
266 }
267
268 if( !is_object( $obj ) ) {
269 // Correct for old double-serialization bug.
270 $obj = unserialize( $obj );
271 }
272
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 );
277 }
278 return $obj->getItem( $this->mHash );
279 }
280
281 /**
282 * Get the content hash
283 *
284 * @return string
285 */
286 function getHash() {
287 return $this->mHash;
288 }
289 }
290
291
292 /**
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.
296 *
297 * Serialized HistoryBlobCurStub objects will be inserted into the text table
298 * on conversion if $wgFastSchemaUpgrades is set to true.
299 */
300 class HistoryBlobCurStub {
301 var $mCurId;
302
303 /**
304 * @param $curid Integer: the cur_id pointed to
305 */
306 function __construct( $curid = 0 ) {
307 $this->mCurId = $curid;
308 }
309
310 /**
311 * Sets the location (cur_id) of the main object to which this object
312 * points
313 *
314 * @param $id int
315 */
316 function setLocation( $id ) {
317 $this->mCurId = $id;
318 }
319
320 /**
321 * @return string|bool
322 */
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;
328 }
329 return $row->cur_text;
330 }
331 }
332
333 /**
334 * Diff-based history compression
335 * Requires xdiff 1.5+ and zlib
336 */
337 class DiffHistoryBlob implements HistoryBlob {
338 /** Uncompressed item cache */
339 var $mItems = array();
340
341 /** Total uncompressed size */
342 var $mSize = 0;
343
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:
347 *
348 * { item[map[i]] - item[map[i-1]] where i > 0
349 * diff[i] = {
350 * { item[map[i]] - Z where i = 0
351 */
352 var $mDiffs;
353
354 /** The diff map, see above */
355 var $mDiffMap;
356
357 /**
358 * The key for getText()
359 */
360 var $mDefaultKey;
361
362 /**
363 * Compressed storage
364 */
365 var $mCompressed;
366
367 /**
368 * True if the object is locked against further writes
369 */
370 var $mFrozen = false;
371
372 /**
373 * The maximum uncompressed size before the object becomes sad
374 * Should be less than max_allowed_packet
375 */
376 var $mMaxSize = 10000000;
377
378 /**
379 * The maximum number of text items before the object becomes sad
380 */
381 var $mMaxCount = 100;
382
383 /** Constants from xdiff.h */
384 const XDL_BDOP_INS = 1;
385 const XDL_BDOP_CPY = 2;
386 const XDL_BDOP_INSB = 3;
387
388 function __construct() {
389 if ( !function_exists( 'gzdeflate' ) ) {
390 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
391 }
392 }
393
394 /**
395 * @throws MWException
396 * @param $text string
397 * @return int
398 */
399 function addItem( $text ) {
400 if ( $this->mFrozen ) {
401 throw new MWException( __METHOD__.": Cannot add more items after sleep/wakeup" );
402 }
403
404 $this->mItems[] = $text;
405 $this->mSize += strlen( $text );
406 $this->mDiffs = null; // later
407 return count( $this->mItems ) - 1;
408 }
409
410 /**
411 * @param $key string
412 * @return string
413 */
414 function getItem( $key ) {
415 return $this->mItems[$key];
416 }
417
418 /**
419 * @param $text string
420 */
421 function setText( $text ) {
422 $this->mDefaultKey = $this->addItem( $text );
423 }
424
425 /**
426 * @return string
427 */
428 function getText() {
429 return $this->getItem( $this->mDefaultKey );
430 }
431
432 /**
433 * @throws MWException
434 */
435 function compress() {
436 if ( !function_exists( 'xdiff_string_rabdiff' ) ){
437 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
438 }
439 if ( isset( $this->mDiffs ) ) {
440 // Already compressed
441 return;
442 }
443 if ( !count( $this->mItems ) ) {
444 // Empty
445 return;
446 }
447
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(),
454 ),
455 'main' => array(
456 'tail' => '',
457 'diffs' => array(),
458 'map' => array(),
459 ),
460 );
461 $smallFactor = 0.5;
462
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';
473 }
474 }
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;
481 }
482 unset( $seq ); // unlink dangerous alias
483
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;
491 }
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 );
497 }
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];
502 }
503 $tail = $seq['tail'];
504 }
505 }
506
507 /**
508 * @param $t1
509 * @param $t2
510 * @return string
511 */
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;
519 }
520
521 /**
522 * @param $base
523 * @param $diff
524 * @return bool|string
525 */
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;
532 }
533
534 # Pure PHP implementation
535
536 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
537
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;
543 }
544 if ( $header['csize'] != strlen( $base ) ) {
545 wfDebug( __METHOD__. ": incorrect base length\n" );
546 return false;
547 }
548
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;
576 }
577 }
578 return $out;
579 }
580
581 /**
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.
584 *
585 * Returns false if no hashing library is available
586 */
587 function xdiffAdler32( $s ) {
588 static $init;
589 if ( $init === null ) {
590 $init = str_repeat( "\xf0", 205 ) . "\xee" . str_repeat( "\xf0", 67 ) . "\x02";
591 }
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;
601 }
602 return strrev( $hash );
603 }
604
605 function uncompress() {
606 if ( !$this->mDiffs ) {
607 return;
608 }
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;
615 }
616 }
617
618 /**
619 * @return array
620 */
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 .= ',';
633 }
634 $map .= $i - $prev;
635 $prev = $i;
636 }
637 $info = array(
638 'diffs' => $this->mDiffs,
639 'map' => $map
640 );
641 }
642 if ( isset( $this->mDefaultKey ) ) {
643 $info['default'] = $this->mDefaultKey;
644 }
645 $this->mCompressed = gzdeflate( serialize( $info ) );
646 return array( 'mCompressed' );
647 }
648
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 );
654
655 if ( !$info ) {
656 // Empty object
657 return;
658 }
659
660 if ( isset( $info['default'] ) ) {
661 $this->mDefaultKey = $info['default'];
662 }
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;
678 }
679 }
680 $this->uncompress();
681 }
682
683 /**
684 * Helper function for compression jobs
685 * Returns true until the object is "full" and ready to be committed
686 *
687 * @return bool
688 */
689 function isHappy() {
690 return $this->mSize < $this->mMaxSize
691 && count( $this->mItems ) < $this->mMaxCount;
692 }
693
694 }