Merge "Add a test for named vs. positional parameter whitespace stripping"
[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 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * Common functions for readers and writers
29 */
30 class CdbFunctions {
31 /**
32 * Take a modulo of a signed integer as if it were an unsigned integer.
33 * $b must be less than 0x40000000 and greater than 0
34 *
35 * @param $a
36 * @param $b
37 *
38 * @return int
39 */
40 public static function unsignedMod( $a, $b ) {
41 if ( $a & 0x80000000 ) {
42 $m = ( $a & 0x7fffffff ) % $b + 2 * ( 0x40000000 % $b );
43 return $m % $b;
44 } else {
45 return $a % $b;
46 }
47 }
48
49 /**
50 * Shift a signed integer right as if it were unsigned
51 * @param $a
52 * @param $b
53 * @return int
54 */
55 public static function unsignedShiftRight( $a, $b ) {
56 if ( $b == 0 ) {
57 return $a;
58 }
59 if ( $a & 0x80000000 ) {
60 return ( ( $a & 0x7fffffff ) >> $b ) | ( 0x40000000 >> ( $b - 1 ) );
61 } else {
62 return $a >> $b;
63 }
64 }
65
66 /**
67 * The CDB hash function.
68 *
69 * @param $s string
70 *
71 * @return
72 */
73 public static function hash( $s ) {
74 $h = 5381;
75 for ( $i = 0; $i < strlen( $s ); $i++ ) {
76 $h5 = ($h << 5) & 0xffffffff;
77 // Do a 32-bit sum
78 // Inlined here for speed
79 $sum = ($h & 0x3fffffff) + ($h5 & 0x3fffffff);
80 $h =
81 (
82 ( $sum & 0x40000000 ? 1 : 0 )
83 + ( $h & 0x80000000 ? 2 : 0 )
84 + ( $h & 0x40000000 ? 1 : 0 )
85 + ( $h5 & 0x80000000 ? 2 : 0 )
86 + ( $h5 & 0x40000000 ? 1 : 0 )
87 ) << 30
88 | ( $sum & 0x3fffffff );
89 $h ^= ord( $s[$i] );
90 $h &= 0xffffffff;
91 }
92 return $h;
93 }
94 }
95
96 /**
97 * CDB reader class
98 */
99 class CdbReader_PHP extends CdbReader {
100 /** The filename */
101 var $fileName;
102
103 /** The file handle */
104 var $handle;
105
106 /* number of hash slots searched under this key */
107 var $loop;
108
109 /* initialized if loop is nonzero */
110 var $khash;
111
112 /* initialized if loop is nonzero */
113 var $kpos;
114
115 /* initialized if loop is nonzero */
116 var $hpos;
117
118 /* initialized if loop is nonzero */
119 var $hslots;
120
121 /* initialized if findNext() returns true */
122 var $dpos;
123
124 /* initialized if cdb_findnext() returns 1 */
125 var $dlen;
126
127 /**
128 * @param $fileName string
129 * @throws MWException
130 */
131 function __construct( $fileName ) {
132 $this->fileName = $fileName;
133 $this->handle = fopen( $fileName, 'rb' );
134 if ( !$this->handle ) {
135 throw new MWException( 'Unable to open CDB file "' . $this->fileName . '".' );
136 }
137 $this->findStart();
138 }
139
140 function close() {
141 if( isset( $this->handle ) ) {
142 fclose( $this->handle );
143 }
144 unset( $this->handle );
145 }
146
147 /**
148 * @param $key
149 * @return bool|string
150 */
151 public function get( $key ) {
152 // strval is required
153 if ( $this->find( strval( $key ) ) ) {
154 return $this->read( $this->dlen, $this->dpos );
155 } else {
156 return false;
157 }
158 }
159
160 /**
161 * @param $key
162 * @param $pos
163 * @return bool
164 */
165 protected function match( $key, $pos ) {
166 $buf = $this->read( strlen( $key ), $pos );
167 return $buf === $key;
168 }
169
170 protected function findStart() {
171 $this->loop = 0;
172 }
173
174 /**
175 * @throws MWException
176 * @param $length
177 * @param $pos
178 * @return string
179 */
180 protected function read( $length, $pos ) {
181 if ( fseek( $this->handle, $pos ) == -1 ) {
182 // This can easily happen if the internal pointers are incorrect
183 throw new MWException(
184 'Seek failed, file "' . $this->fileName . '" may be corrupted.' );
185 }
186
187 if ( $length == 0 ) {
188 return '';
189 }
190
191 $buf = fread( $this->handle, $length );
192 if ( $buf === false || strlen( $buf ) !== $length ) {
193 throw new MWException(
194 'Read from CDB file failed, file "' . $this->fileName . '" may be corrupted.' );
195 }
196 return $buf;
197 }
198
199 /**
200 * Unpack an unsigned integer and throw an exception if it needs more than 31 bits
201 * @param $s
202 * @throws MWException
203 * @return mixed
204 */
205 protected function unpack31( $s ) {
206 $data = unpack( 'V', $s );
207 if ( $data[1] > 0x7fffffff ) {
208 throw new MWException(
209 'Error in CDB file "' . $this->fileName . '", integer too big.' );
210 }
211 return $data[1];
212 }
213
214 /**
215 * Unpack a 32-bit signed integer
216 * @param $s
217 * @return int
218 */
219 protected function unpackSigned( $s ) {
220 $data = unpack( 'va/vb', $s );
221 return $data['a'] | ( $data['b'] << 16 );
222 }
223
224 /**
225 * @param $key
226 * @return bool
227 */
228 protected function findNext( $key ) {
229 if ( !$this->loop ) {
230 $u = CdbFunctions::hash( $key );
231 $buf = $this->read( 8, ( $u << 3 ) & 2047 );
232 $this->hslots = $this->unpack31( substr( $buf, 4 ) );
233 if ( !$this->hslots ) {
234 return false;
235 }
236 $this->hpos = $this->unpack31( substr( $buf, 0, 4 ) );
237 $this->khash = $u;
238 $u = CdbFunctions::unsignedShiftRight( $u, 8 );
239 $u = CdbFunctions::unsignedMod( $u, $this->hslots );
240 $u <<= 3;
241 $this->kpos = $this->hpos + $u;
242 }
243
244 while ( $this->loop < $this->hslots ) {
245 $buf = $this->read( 8, $this->kpos );
246 $pos = $this->unpack31( substr( $buf, 4 ) );
247 if ( !$pos ) {
248 return false;
249 }
250 $this->loop += 1;
251 $this->kpos += 8;
252 if ( $this->kpos == $this->hpos + ( $this->hslots << 3 ) ) {
253 $this->kpos = $this->hpos;
254 }
255 $u = $this->unpackSigned( substr( $buf, 0, 4 ) );
256 if ( $u === $this->khash ) {
257 $buf = $this->read( 8, $pos );
258 $keyLen = $this->unpack31( substr( $buf, 0, 4 ) );
259 if ( $keyLen == strlen( $key ) && $this->match( $key, $pos + 8 ) ) {
260 // Found
261 $this->dlen = $this->unpack31( substr( $buf, 4 ) );
262 $this->dpos = $pos + 8 + $keyLen;
263 return true;
264 }
265 }
266 }
267 return false;
268 }
269
270 /**
271 * @param $key
272 * @return bool
273 */
274 protected function find( $key ) {
275 $this->findStart();
276 return $this->findNext( $key );
277 }
278 }
279
280 /**
281 * CDB writer class
282 */
283 class CdbWriter_PHP extends CdbWriter {
284 var $handle, $realFileName, $tmpFileName;
285
286 var $hplist;
287 var $numentries, $pos;
288
289 /**
290 * @param $fileName string
291 */
292 function __construct( $fileName ) {
293 $this->realFileName = $fileName;
294 $this->tmpFileName = $fileName . '.tmp.' . mt_rand( 0, 0x7fffffff );
295 $this->handle = fopen( $this->tmpFileName, 'wb' );
296 if ( !$this->handle ) {
297 $this->throwException(
298 'Unable to open CDB file "' . $this->tmpFileName . '" for write.' );
299 }
300 $this->hplist = array();
301 $this->numentries = 0;
302 $this->pos = 2048; // leaving space for the pointer array, 256 * 8
303 if ( fseek( $this->handle, $this->pos ) == -1 ) {
304 $this->throwException( 'fseek failed in file "' . $this->tmpFileName . '".' );
305 }
306 }
307
308 function __destruct() {
309 if ( isset( $this->handle ) ) {
310 $this->close();
311 }
312 }
313
314 /**
315 * @param $key
316 * @param $value
317 * @return
318 */
319 public function set( $key, $value ) {
320 if ( strval( $key ) === '' ) {
321 // DBA cross-check hack
322 return;
323 }
324 $this->addbegin( strlen( $key ), strlen( $value ) );
325 $this->write( $key );
326 $this->write( $value );
327 $this->addend( strlen( $key ), strlen( $value ), CdbFunctions::hash( $key ) );
328 }
329
330 /**
331 * @throws MWException
332 */
333 public function close() {
334 $this->finish();
335 if( isset($this->handle) ) {
336 fclose( $this->handle );
337 }
338 if ( wfIsWindows() && file_exists($this->realFileName) ) {
339 unlink( $this->realFileName );
340 }
341 if ( !rename( $this->tmpFileName, $this->realFileName ) ) {
342 $this->throwException( 'Unable to move the new CDB file into place.' );
343 }
344 unset( $this->handle );
345 }
346
347 /**
348 * @throws MWException
349 * @param $buf
350 */
351 protected function write( $buf ) {
352 $len = fwrite( $this->handle, $buf );
353 if ( $len !== strlen( $buf ) ) {
354 $this->throwException( 'Error writing to CDB file "'.$this->tmpFileName.'".' );
355 }
356 }
357
358 /**
359 * @throws MWException
360 * @param $len
361 */
362 protected function posplus( $len ) {
363 $newpos = $this->pos + $len;
364 if ( $newpos > 0x7fffffff ) {
365 $this->throwException(
366 'A value in the CDB file "'.$this->tmpFileName.'" is too large.' );
367 }
368 $this->pos = $newpos;
369 }
370
371 /**
372 * @param $keylen
373 * @param $datalen
374 * @param $h
375 */
376 protected function addend( $keylen, $datalen, $h ) {
377 $this->hplist[] = array(
378 'h' => $h,
379 'p' => $this->pos
380 );
381
382 $this->numentries++;
383 $this->posplus( 8 );
384 $this->posplus( $keylen );
385 $this->posplus( $datalen );
386 }
387
388 /**
389 * @throws MWException
390 * @param $keylen
391 * @param $datalen
392 */
393 protected function addbegin( $keylen, $datalen ) {
394 if ( $keylen > 0x7fffffff ) {
395 $this->throwException( 'Key length too long in file "'.$this->tmpFileName.'".' );
396 }
397 if ( $datalen > 0x7fffffff ) {
398 $this->throwException( 'Data length too long in file "'.$this->tmpFileName.'".' );
399 }
400 $buf = pack( 'VV', $keylen, $datalen );
401 $this->write( $buf );
402 }
403
404 /**
405 * @throws MWException
406 */
407 protected function finish() {
408 // Hack for DBA cross-check
409 $this->hplist = array_reverse( $this->hplist );
410
411 // Calculate the number of items that will be in each hashtable
412 $counts = array_fill( 0, 256, 0 );
413 foreach ( $this->hplist as $item ) {
414 ++ $counts[ 255 & $item['h'] ];
415 }
416
417 // Fill in $starts with the *end* indexes
418 $starts = array();
419 $pos = 0;
420 for ( $i = 0; $i < 256; ++$i ) {
421 $pos += $counts[$i];
422 $starts[$i] = $pos;
423 }
424
425 // Excessively clever and indulgent code to simultaneously fill $packedTables
426 // with the packed hashtables, and adjust the elements of $starts
427 // to actually point to the starts instead of the ends.
428 $packedTables = array_fill( 0, $this->numentries, false );
429 foreach ( $this->hplist as $item ) {
430 $packedTables[--$starts[255 & $item['h']]] = $item;
431 }
432
433 $final = '';
434 for ( $i = 0; $i < 256; ++$i ) {
435 $count = $counts[$i];
436
437 // The size of the hashtable will be double the item count.
438 // The rest of the slots will be empty.
439 $len = $count + $count;
440 $final .= pack( 'VV', $this->pos, $len );
441
442 $hashtable = array();
443 for ( $u = 0; $u < $len; ++$u ) {
444 $hashtable[$u] = array( 'h' => 0, 'p' => 0 );
445 }
446
447 // Fill the hashtable, using the next empty slot if the hashed slot
448 // is taken.
449 for ( $u = 0; $u < $count; ++$u ) {
450 $hp = $packedTables[$starts[$i] + $u];
451 $where = CdbFunctions::unsignedMod(
452 CdbFunctions::unsignedShiftRight( $hp['h'], 8 ), $len );
453 while ( $hashtable[$where]['p'] )
454 if ( ++$where == $len )
455 $where = 0;
456 $hashtable[$where] = $hp;
457 }
458
459 // Write the hashtable
460 for ( $u = 0; $u < $len; ++$u ) {
461 $buf = pack( 'vvV',
462 $hashtable[$u]['h'] & 0xffff,
463 CdbFunctions::unsignedShiftRight( $hashtable[$u]['h'], 16 ),
464 $hashtable[$u]['p'] );
465 $this->write( $buf );
466 $this->posplus( 8 );
467 }
468 }
469
470 // Write the pointer array at the start of the file
471 rewind( $this->handle );
472 if ( ftell( $this->handle ) != 0 ) {
473 $this->throwException( 'Error rewinding to start of file "'.$this->tmpFileName.'".' );
474 }
475 $this->write( $final );
476 }
477
478 /**
479 * Clean up the temp file and throw an exception
480 *
481 * @param $msg string
482 * @throws MWException
483 */
484 protected function throwException( $msg ) {
485 if ( $this->handle ) {
486 fclose( $this->handle );
487 unlink( $this->tmpFileName );
488 }
489 throw new MWException( $msg );
490 }
491 }