* follow-up r97636: decrease indentation & mention revision per Nikerabbit
[lhc/web/wiklou.git] / includes / Cdb_PHP.php
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
8 *
9 * @file
10 */
11
12 /**
13 * Common functions for readers and writers
14 */
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
19 *
20 * @param $a
21 * @param $b
22 *
23 * @return int
24 */
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;
31 }
32 }
33
34 /**
35 * Shift a signed integer right as if it were unsigned
36 * @param $a
37 * @param $b
38 * @return int
39 */
40 public static function unsignedShiftRight( $a, $b ) {
41 if ( $b == 0 ) {
42 return $a;
43 }
44 if ( $a & 0x80000000 ) {
45 return ( ( $a & 0x7fffffff ) >> $b ) | ( 0x40000000 >> ( $b - 1 ) );
46 } else {
47 return $a >> $b;
48 }
49 }
50
51 /**
52 * The CDB hash function.
53 *
54 * @param $s
55 *
56 * @return
57 */
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 =
66 (
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;
76 }
77 return $h;
78 }
79 }
80
81 /**
82 * CDB reader class
83 */
84 class CdbReader_PHP extends CdbReader {
85 /** The file handle */
86 var $handle;
87
88 /* number of hash slots searched under this key */
89 var $loop;
90
91 /* initialized if loop is nonzero */
92 var $khash;
93
94 /* initialized if loop is nonzero */
95 var $kpos;
96
97 /* initialized if loop is nonzero */
98 var $hpos;
99
100 /* initialized if loop is nonzero */
101 var $hslots;
102
103 /* initialized if findNext() returns true */
104 var $dpos;
105
106 /* initialized if cdb_findnext() returns 1 */
107 var $dlen;
108
109 function __construct( $fileName ) {
110 $this->handle = fopen( $fileName, 'rb' );
111 if ( !$this->handle ) {
112 throw new MWException( 'Unable to open CDB file "' . $fileName . '"' );
113 }
114 $this->findStart();
115 }
116
117 function close() {
118 if( isset( $this->handle ) ) {
119 fclose( $this->handle );
120 }
121 unset( $this->handle );
122 }
123
124 /**
125 * @param $key
126 * @return bool|string
127 */
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;
134 }
135 }
136
137 /**
138 * @param $key
139 * @param $pos
140 * @return bool
141 */
142 protected function match( $key, $pos ) {
143 $buf = $this->read( strlen( $key ), $pos );
144 return $buf === $key;
145 }
146
147 protected function findStart() {
148 $this->loop = 0;
149 }
150
151 /**
152 * @throws MWException
153 * @param $length
154 * @param $pos
155 * @return string
156 */
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.' );
161 }
162
163 if ( $length == 0 ) {
164 return '';
165 }
166
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' );
170 }
171 return $buf;
172 }
173
174 /**
175 * Unpack an unsigned integer and throw an exception if it needs more than 31 bits
176 * @param $s
177 * @return
178 */
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' );
183 }
184 return $data[1];
185 }
186
187 /**
188 * Unpack a 32-bit signed integer
189 * @param $s
190 * @return int
191 */
192 protected function unpackSigned( $s ) {
193 $data = unpack( 'va/vb', $s );
194 return $data['a'] | ( $data['b'] << 16 );
195 }
196
197 /**
198 * @param $key
199 * @return bool
200 */
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;
208 }
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;
215 }
216
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;
222 }
223 $this->loop += 1;
224 $this->kpos += 8;
225 if ( $this->kpos == $this->hpos + ( $this->hslots << 3 ) ) {
226 $this->kpos = $this->hpos;
227 }
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;
237 }
238 }
239 }
240 return false;
241 }
242
243 /**
244 * @param $key
245 * @return bool
246 */
247 protected function find( $key ) {
248 $this->findStart();
249 return $this->findNext( $key );
250 }
251 }
252
253 /**
254 * CDB writer class
255 */
256 class CdbWriter_PHP extends CdbWriter {
257 var $handle, $realFileName, $tmpFileName;
258
259 var $hplist;
260 var $numEntries, $pos;
261
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 . '"' );
268 }
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' );
274 }
275 }
276
277 function __destruct() {
278 if ( isset( $this->handle ) ) {
279 $this->close();
280 }
281 }
282
283 /**
284 * @param $key
285 * @param $value
286 * @return
287 */
288 public function set( $key, $value ) {
289 if ( strval( $key ) === '' ) {
290 // DBA cross-check hack
291 return;
292 }
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 ) );
297 }
298
299 /**
300 * @throws MWException
301 */
302 public function close() {
303 $this->finish();
304 if( isset($this->handle) ) {
305 fclose( $this->handle );
306 }
307 if ( wfIsWindows() && file_exists($this->realFileName) ) {
308 unlink( $this->realFileName );
309 }
310 if ( !rename( $this->tmpFileName, $this->realFileName ) ) {
311 throw new MWException( 'Unable to move the new CDB file into place.' );
312 }
313 unset( $this->handle );
314 }
315
316 /**
317 * @throws MWException
318 * @param $buf
319 */
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.' );
324 }
325 }
326
327 /**
328 * @throws MWException
329 * @param $len
330 */
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' );
335 }
336 $this->pos = $newpos;
337 }
338
339 /**
340 * @param $keylen
341 * @param $datalen
342 * @param $h
343 */
344 protected function addend( $keylen, $datalen, $h ) {
345 $this->hplist[] = array(
346 'h' => $h,
347 'p' => $this->pos
348 );
349
350 $this->numentries++;
351 $this->posplus( 8 );
352 $this->posplus( $keylen );
353 $this->posplus( $datalen );
354 }
355
356 /**
357 * @throws MWException
358 * @param $keylen
359 * @param $datalen
360 */
361 protected function addbegin( $keylen, $datalen ) {
362 if ( $keylen > 0x7fffffff ) {
363 throw new MWException( __METHOD__.': key length too long' );
364 }
365 if ( $datalen > 0x7fffffff ) {
366 throw new MWException( __METHOD__.': data length too long' );
367 }
368 $buf = pack( 'VV', $keylen, $datalen );
369 $this->write( $buf );
370 }
371
372 /**
373 * @throws MWException
374 */
375 protected function finish() {
376 // Hack for DBA cross-check
377 $this->hplist = array_reverse( $this->hplist );
378
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'] ];
383 }
384
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;
391 }
392
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;
399 }
400
401 $final = '';
402 for ( $i = 0; $i < 256; ++$i ) {
403 $count = $counts[$i];
404
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 );
409
410 $hashtable = array();
411 for ( $u = 0; $u < $len; ++$u ) {
412 $hashtable[$u] = array( 'h' => 0, 'p' => 0 );
413 }
414
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;
425 }
426
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 );
435 }
436 }
437
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' );
442 }
443 $this->write( $final );
444 }
445 }