Followup to r86053 - fix special page cases
[mediawiki.git] / includes / Cdb_PHP.php
blobf4029ba5e6bdcbc6c6bde50b2fe888d4384d0f2e
1 <?php
2 /**
3 * This is a port of D.J. Bernstein's CDB to PHP. It's based on the copy that
4 * appears in PHP 5.3. Changes are:
5 * * Error returns replaced with exceptions
6 * * Exception thrown if sizes or offsets are between 2GB and 4GB
7 * * Some variables renamed
9 * @file
12 /**
13 * Common functions for readers and writers
15 class CdbFunctions {
16 /**
17 * Take a modulo of a signed integer as if it were an unsigned integer.
18 * $b must be less than 0x40000000 and greater than 0
20 * @param $a
21 * @param $b
23 * @return int
25 public static function unsignedMod( $a, $b ) {
26 if ( $a & 0x80000000 ) {
27 $m = ( $a & 0x7fffffff ) % $b + 2 * ( 0x40000000 % $b );
28 return $m % $b;
29 } else {
30 return $a % $b;
34 /**
35 * Shift a signed integer right as if it were unsigned
36 * @param $a
37 * @param $b
38 * @return int
40 public static function unsignedShiftRight( $a, $b ) {
41 if ( $b == 0 ) {
42 return $a;
44 if ( $a & 0x80000000 ) {
45 return ( ( $a & 0x7fffffff ) >> $b ) | ( 0x40000000 >> ( $b - 1 ) );
46 } else {
47 return $a >> $b;
51 /**
52 * The CDB hash function.
54 * @param $s
56 * @return
58 public static function hash( $s ) {
59 $h = 5381;
60 for ( $i = 0; $i < strlen( $s ); $i++ ) {
61 $h5 = ($h << 5) & 0xffffffff;
62 // Do a 32-bit sum
63 // Inlined here for speed
64 $sum = ($h & 0x3fffffff) + ($h5 & 0x3fffffff);
65 $h =
67 ( $sum & 0x40000000 ? 1 : 0 )
68 + ( $h & 0x80000000 ? 2 : 0 )
69 + ( $h & 0x40000000 ? 1 : 0 )
70 + ( $h5 & 0x80000000 ? 2 : 0 )
71 + ( $h5 & 0x40000000 ? 1 : 0 )
72 ) << 30
73 | ( $sum & 0x3fffffff );
74 $h ^= ord( $s[$i] );
75 $h &= 0xffffffff;
77 return $h;
81 /**
82 * CDB reader class
84 class CdbReader_PHP extends CdbReader {
85 /** The file handle */
86 var $handle;
88 /* number of hash slots searched under this key */
89 var $loop;
91 /* initialized if loop is nonzero */
92 var $khash;
94 /* initialized if loop is nonzero */
95 var $kpos;
97 /* initialized if loop is nonzero */
98 var $hpos;
100 /* initialized if loop is nonzero */
101 var $hslots;
103 /* initialized if findNext() returns true */
104 var $dpos;
106 /* initialized if cdb_findnext() returns 1 */
107 var $dlen;
109 function __construct( $fileName ) {
110 $this->handle = fopen( $fileName, 'rb' );
111 if ( !$this->handle ) {
112 throw new MWException( 'Unable to open CDB file "' . $fileName . '"' );
114 $this->findStart();
117 function close() {
118 if( isset( $this->handle ) ) {
119 fclose( $this->handle );
121 unset( $this->handle );
125 * @param $key
126 * @return bool|string
128 public function get( $key ) {
129 // strval is required
130 if ( $this->find( strval( $key ) ) ) {
131 return $this->read( $this->dlen, $this->dpos );
132 } else {
133 return false;
138 * @param $key
139 * @param $pos
140 * @return bool
142 protected function match( $key, $pos ) {
143 $buf = $this->read( strlen( $key ), $pos );
144 return $buf === $key;
147 protected function findStart() {
148 $this->loop = 0;
152 * @throws MWException
153 * @param $length
154 * @param $pos
155 * @return string
157 protected function read( $length, $pos ) {
158 if ( fseek( $this->handle, $pos ) == -1 ) {
159 // This can easily happen if the internal pointers are incorrect
160 throw new MWException( __METHOD__.': seek failed, file may be corrupted.' );
163 if ( $length == 0 ) {
164 return '';
167 $buf = fread( $this->handle, $length );
168 if ( $buf === false || strlen( $buf ) !== $length ) {
169 throw new MWException( __METHOD__.': read from CDB file failed, file may be corrupted' );
171 return $buf;
175 * Unpack an unsigned integer and throw an exception if it needs more than 31 bits
176 * @param $s
177 * @return
179 protected function unpack31( $s ) {
180 $data = unpack( 'V', $s );
181 if ( $data[1] > 0x7fffffff ) {
182 throw new MWException( __METHOD__.': error in CDB file, integer too big' );
184 return $data[1];
188 * Unpack a 32-bit signed integer
189 * @param $s
190 * @return int
192 protected function unpackSigned( $s ) {
193 $data = unpack( 'va/vb', $s );
194 return $data['a'] | ( $data['b'] << 16 );
198 * @param $key
199 * @return bool
201 protected function findNext( $key ) {
202 if ( !$this->loop ) {
203 $u = CdbFunctions::hash( $key );
204 $buf = $this->read( 8, ( $u << 3 ) & 2047 );
205 $this->hslots = $this->unpack31( substr( $buf, 4 ) );
206 if ( !$this->hslots ) {
207 return false;
209 $this->hpos = $this->unpack31( substr( $buf, 0, 4 ) );
210 $this->khash = $u;
211 $u = CdbFunctions::unsignedShiftRight( $u, 8 );
212 $u = CdbFunctions::unsignedMod( $u, $this->hslots );
213 $u <<= 3;
214 $this->kpos = $this->hpos + $u;
217 while ( $this->loop < $this->hslots ) {
218 $buf = $this->read( 8, $this->kpos );
219 $pos = $this->unpack31( substr( $buf, 4 ) );
220 if ( !$pos ) {
221 return false;
223 $this->loop += 1;
224 $this->kpos += 8;
225 if ( $this->kpos == $this->hpos + ( $this->hslots << 3 ) ) {
226 $this->kpos = $this->hpos;
228 $u = $this->unpackSigned( substr( $buf, 0, 4 ) );
229 if ( $u === $this->khash ) {
230 $buf = $this->read( 8, $pos );
231 $keyLen = $this->unpack31( substr( $buf, 0, 4 ) );
232 if ( $keyLen == strlen( $key ) && $this->match( $key, $pos + 8 ) ) {
233 // Found
234 $this->dlen = $this->unpack31( substr( $buf, 4 ) );
235 $this->dpos = $pos + 8 + $keyLen;
236 return true;
240 return false;
244 * @param $key
245 * @return bool
247 protected function find( $key ) {
248 $this->findStart();
249 return $this->findNext( $key );
254 * CDB writer class
256 class CdbWriter_PHP extends CdbWriter {
257 var $handle, $realFileName, $tmpFileName;
259 var $hplist;
260 var $numEntries, $pos;
262 function __construct( $fileName ) {
263 $this->realFileName = $fileName;
264 $this->tmpFileName = $fileName . '.tmp.' . mt_rand( 0, 0x7fffffff );
265 $this->handle = fopen( $this->tmpFileName, 'wb' );
266 if ( !$this->handle ) {
267 throw new MWException( 'Unable to open CDB file for write "' . $fileName . '"' );
269 $this->hplist = array();
270 $this->numentries = 0;
271 $this->pos = 2048; // leaving space for the pointer array, 256 * 8
272 if ( fseek( $this->handle, $this->pos ) == -1 ) {
273 throw new MWException( __METHOD__.': fseek failed' );
277 function __destruct() {
278 if ( isset( $this->handle ) ) {
279 $this->close();
284 * @param $key
285 * @param $value
286 * @return
288 public function set( $key, $value ) {
289 if ( strval( $key ) === '' ) {
290 // DBA cross-check hack
291 return;
293 $this->addbegin( strlen( $key ), strlen( $value ) );
294 $this->write( $key );
295 $this->write( $value );
296 $this->addend( strlen( $key ), strlen( $value ), CdbFunctions::hash( $key ) );
300 * @throws MWException
302 public function close() {
303 $this->finish();
304 if( isset($this->handle) ) {
305 fclose( $this->handle );
307 if ( wfIsWindows() && file_exists($this->realFileName) ) {
308 unlink( $this->realFileName );
310 if ( !rename( $this->tmpFileName, $this->realFileName ) ) {
311 throw new MWException( 'Unable to move the new CDB file into place.' );
313 unset( $this->handle );
317 * @throws MWException
318 * @param $buf
320 protected function write( $buf ) {
321 $len = fwrite( $this->handle, $buf );
322 if ( $len !== strlen( $buf ) ) {
323 throw new MWException( 'Error writing to CDB file.' );
328 * @throws MWException
329 * @param $len
331 protected function posplus( $len ) {
332 $newpos = $this->pos + $len;
333 if ( $newpos > 0x7fffffff ) {
334 throw new MWException( 'A value in the CDB file is too large' );
336 $this->pos = $newpos;
340 * @param $keylen
341 * @param $datalen
342 * @param $h
344 protected function addend( $keylen, $datalen, $h ) {
345 $this->hplist[] = array(
346 'h' => $h,
347 'p' => $this->pos
350 $this->numentries++;
351 $this->posplus( 8 );
352 $this->posplus( $keylen );
353 $this->posplus( $datalen );
357 * @throws MWException
358 * @param $keylen
359 * @param $datalen
361 protected function addbegin( $keylen, $datalen ) {
362 if ( $keylen > 0x7fffffff ) {
363 throw new MWException( __METHOD__.': key length too long' );
365 if ( $datalen > 0x7fffffff ) {
366 throw new MWException( __METHOD__.': data length too long' );
368 $buf = pack( 'VV', $keylen, $datalen );
369 $this->write( $buf );
373 * @throws MWException
375 protected function finish() {
376 // Hack for DBA cross-check
377 $this->hplist = array_reverse( $this->hplist );
379 // Calculate the number of items that will be in each hashtable
380 $counts = array_fill( 0, 256, 0 );
381 foreach ( $this->hplist as $item ) {
382 ++ $counts[ 255 & $item['h'] ];
385 // Fill in $starts with the *end* indexes
386 $starts = array();
387 $pos = 0;
388 for ( $i = 0; $i < 256; ++$i ) {
389 $pos += $counts[$i];
390 $starts[$i] = $pos;
393 // Excessively clever and indulgent code to simultaneously fill $packedTables
394 // with the packed hashtables, and adjust the elements of $starts
395 // to actually point to the starts instead of the ends.
396 $packedTables = array_fill( 0, $this->numentries, false );
397 foreach ( $this->hplist as $item ) {
398 $packedTables[--$starts[255 & $item['h']]] = $item;
401 $final = '';
402 for ( $i = 0; $i < 256; ++$i ) {
403 $count = $counts[$i];
405 // The size of the hashtable will be double the item count.
406 // The rest of the slots will be empty.
407 $len = $count + $count;
408 $final .= pack( 'VV', $this->pos, $len );
410 $hashtable = array();
411 for ( $u = 0; $u < $len; ++$u ) {
412 $hashtable[$u] = array( 'h' => 0, 'p' => 0 );
415 // Fill the hashtable, using the next empty slot if the hashed slot
416 // is taken.
417 for ( $u = 0; $u < $count; ++$u ) {
418 $hp = $packedTables[$starts[$i] + $u];
419 $where = CdbFunctions::unsignedMod(
420 CdbFunctions::unsignedShiftRight( $hp['h'], 8 ), $len );
421 while ( $hashtable[$where]['p'] )
422 if ( ++$where == $len )
423 $where = 0;
424 $hashtable[$where] = $hp;
427 // Write the hashtable
428 for ( $u = 0; $u < $len; ++$u ) {
429 $buf = pack( 'vvV',
430 $hashtable[$u]['h'] & 0xffff,
431 CdbFunctions::unsignedShiftRight( $hashtable[$u]['h'], 16 ),
432 $hashtable[$u]['p'] );
433 $this->write( $buf );
434 $this->posplus( 8 );
438 // Write the pointer array at the start of the file
439 rewind( $this->handle );
440 if ( ftell( $this->handle ) != 0 ) {
441 throw new MWException( __METHOD__.': Error rewinding to start of file' );
443 $this->write( $final );