Clean up UIDGenerator field comments
[lhc/web/wiklou.git] / includes / utils / UIDGenerator.php
1 <?php
2 /**
3 * This file deals with UID generation.
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 use Wikimedia\Assert\Assert;
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Class for getting statistically unique IDs
27 *
28 * @since 1.21
29 */
30 class UIDGenerator {
31 /** @var UIDGenerator */
32 protected static $instance = null;
33 /** @var string Local file path */
34 protected $nodeIdFile;
35 /** @var string Node ID in binary (32 bits) */
36 protected $nodeId32;
37 /** @var string Node ID in binary (48 bits) */
38 protected $nodeId48;
39
40 /** @var string Local file path */
41 protected $lockFile88;
42 /** @var string Local file path */
43 protected $lockFile128;
44 /** @var string Local file path */
45 protected $lockFileUUID;
46
47 /** @var array Cached file handles */
48 protected $fileHandles = []; // cached file handles
49
50 const QUICK_RAND = 1; // get randomness from fast and insecure sources
51 const QUICK_VOLATILE = 2; // use an APC like in-memory counter if available
52
53 protected function __construct() {
54 $this->nodeIdFile = wfTempDir() . '/mw-' . __CLASS__ . '-UID-nodeid';
55 $nodeId = '';
56 if ( is_file( $this->nodeIdFile ) ) {
57 $nodeId = file_get_contents( $this->nodeIdFile );
58 }
59 // Try to get some ID that uniquely identifies this machine (RFC 4122)...
60 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
61 Wikimedia\suppressWarnings();
62 if ( wfIsWindows() ) {
63 // https://technet.microsoft.com/en-us/library/bb490913.aspx
64 $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) );
65 $line = substr( $csv, 0, strcspn( $csv, "\n" ) );
66 $info = str_getcsv( $line );
67 $nodeId = isset( $info[0] ) ? str_replace( '-', '', $info[0] ) : '';
68 } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X
69 // See https://linux.die.net/man/8/ifconfig
70 $m = [];
71 preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
72 wfShellExec( '/sbin/ifconfig -a' ), $m );
73 $nodeId = isset( $m[1] ) ? str_replace( ':', '', $m[1] ) : '';
74 }
75 Wikimedia\restoreWarnings();
76 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
77 $nodeId = MWCryptRand::generateHex( 12, true );
78 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 ); // set multicast bit
79 }
80 file_put_contents( $this->nodeIdFile, $nodeId ); // cache
81 }
82 $this->nodeId32 = Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
83 $this->nodeId48 = Wikimedia\base_convert( $nodeId, 16, 2, 48 );
84 // If different processes run as different users, they may have different temp dirs.
85 // This is dealt with by initializing the clock sequence number and counters randomly.
86 $this->lockFile88 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-88';
87 $this->lockFile128 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-128';
88 $this->lockFileUUID = wfTempDir() . '/mw-' . __CLASS__ . '-UUID-128';
89 }
90
91 /**
92 * @todo move to MW-specific factory class and inject temp dir
93 * @return UIDGenerator
94 */
95 protected static function singleton() {
96 if ( self::$instance === null ) {
97 self::$instance = new self();
98 }
99
100 return self::$instance;
101 }
102
103 /**
104 * Get a statistically unique 88-bit unsigned integer ID string.
105 * The bits of the UID are prefixed with the time (down to the millisecond).
106 *
107 * These IDs are suitable as values for the shard key of distributed data.
108 * If a column uses these as values, it should be declared UNIQUE to handle collisions.
109 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
110 * They can also be stored "DECIMAL(27) UNSIGNED" or BINARY(11) in MySQL.
111 *
112 * UID generation is serialized on each server (as the node ID is for the whole machine).
113 *
114 * @param int $base Specifies a base other than 10
115 * @return string Number
116 * @throws RuntimeException
117 */
118 public static function newTimestampedUID88( $base = 10 ) {
119 Assert::parameterType( 'integer', $base, '$base' );
120 Assert::parameter( $base <= 36, '$base', 'must be <= 36' );
121 Assert::parameter( $base >= 2, '$base', 'must be >= 2' );
122
123 $gen = self::singleton();
124 $info = $gen->getTimeAndDelay( 'lockFile88', 1, 1024, 1024 );
125 $info['offsetCounter'] = $info['offsetCounter'] % 1024;
126 return Wikimedia\base_convert( $gen->getTimestampedID88( $info ), 2, $base );
127 }
128
129 /**
130 * @param array $info The result of UIDGenerator::getTimeAndDelay() or
131 * a plain (UIDGenerator::millitime(), counter, clock sequence) array.
132 * @return string 88 bits
133 * @throws RuntimeException
134 */
135 protected function getTimestampedID88( array $info ) {
136 if ( isset( $info['time'] ) ) {
137 $time = $info['time'];
138 $counter = $info['offsetCounter'];
139 } else {
140 $time = $info[0];
141 $counter = $info[1];
142 }
143 // Take the 46 LSBs of "milliseconds since epoch"
144 $id_bin = $this->millisecondsSinceEpochBinary( $time );
145 // Add a 10 bit counter resulting in 56 bits total
146 $id_bin .= str_pad( decbin( $counter ), 10, '0', STR_PAD_LEFT );
147 // Add the 32 bit node ID resulting in 88 bits total
148 $id_bin .= $this->nodeId32;
149 // Convert to a 1-27 digit integer string
150 if ( strlen( $id_bin ) !== 88 ) {
151 throw new RuntimeException( "Detected overflow for millisecond timestamp." );
152 }
153
154 return $id_bin;
155 }
156
157 /**
158 * Get a statistically unique 128-bit unsigned integer ID string.
159 * The bits of the UID are prefixed with the time (down to the millisecond).
160 *
161 * These IDs are suitable as globally unique IDs, without any enforced uniqueness.
162 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
163 * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL.
164 *
165 * UID generation is serialized on each server (as the node ID is for the whole machine).
166 *
167 * @param int $base Specifies a base other than 10
168 * @return string Number
169 * @throws RuntimeException
170 */
171 public static function newTimestampedUID128( $base = 10 ) {
172 Assert::parameterType( 'integer', $base, '$base' );
173 Assert::parameter( $base <= 36, '$base', 'must be <= 36' );
174 Assert::parameter( $base >= 2, '$base', 'must be >= 2' );
175
176 $gen = self::singleton();
177 $info = $gen->getTimeAndDelay( 'lockFile128', 16384, 1048576, 1048576 );
178 $info['offsetCounter'] = $info['offsetCounter'] % 1048576;
179
180 return Wikimedia\base_convert( $gen->getTimestampedID128( $info ), 2, $base );
181 }
182
183 /**
184 * @param array $info The result of UIDGenerator::getTimeAndDelay() or
185 * a plain (UIDGenerator::millitime(), counter, clock sequence) array.
186 * @return string 128 bits
187 * @throws RuntimeException
188 */
189 protected function getTimestampedID128( array $info ) {
190 if ( isset( $info['time'] ) ) {
191 $time = $info['time'];
192 $counter = $info['offsetCounter'];
193 $clkSeq = $info['clkSeq'];
194 } else {
195 $time = $info[0];
196 $counter = $info[1];
197 $clkSeq = $info[2];
198 }
199 // Take the 46 LSBs of "milliseconds since epoch"
200 $id_bin = $this->millisecondsSinceEpochBinary( $time );
201 // Add a 20 bit counter resulting in 66 bits total
202 $id_bin .= str_pad( decbin( $counter ), 20, '0', STR_PAD_LEFT );
203 // Add a 14 bit clock sequence number resulting in 80 bits total
204 $id_bin .= str_pad( decbin( $clkSeq ), 14, '0', STR_PAD_LEFT );
205 // Add the 48 bit node ID resulting in 128 bits total
206 $id_bin .= $this->nodeId48;
207 // Convert to a 1-39 digit integer string
208 if ( strlen( $id_bin ) !== 128 ) {
209 throw new RuntimeException( "Detected overflow for millisecond timestamp." );
210 }
211
212 return $id_bin;
213 }
214
215 /**
216 * Return an RFC4122 compliant v1 UUID
217 *
218 * @return string
219 * @throws RuntimeException
220 * @since 1.27
221 */
222 public static function newUUIDv1() {
223 $gen = self::singleton();
224 // There can be up to 10000 intervals for the same millisecond timestamp.
225 // [0,4999] counter + [0,5000] offset is in [0,9999] for the offset counter.
226 // Add this onto the timestamp to allow making up to 5000 IDs per second.
227 return $gen->getUUIDv1( $gen->getTimeAndDelay( 'lockFileUUID', 16384, 5000, 5001 ) );
228 }
229
230 /**
231 * Return an RFC4122 compliant v1 UUID
232 *
233 * @return string 32 hex characters with no hyphens
234 * @throws RuntimeException
235 * @since 1.27
236 */
237 public static function newRawUUIDv1() {
238 return str_replace( '-', '', self::newUUIDv1() );
239 }
240
241 /**
242 * @param array $info Result of UIDGenerator::getTimeAndDelay()
243 * @return string 128 bits
244 */
245 protected function getUUIDv1( array $info ) {
246 $clkSeq_bin = Wikimedia\base_convert( $info['clkSeq'], 10, 2, 14 );
247 $time_bin = $this->intervalsSinceGregorianBinary( $info['time'], $info['offsetCounter'] );
248 // Take the 32 bits of "time low"
249 $id_bin = substr( $time_bin, 28, 32 );
250 // Add 16 bits of "time mid" resulting in 48 bits total
251 $id_bin .= substr( $time_bin, 12, 16 );
252 // Add 4 bit version resulting in 52 bits total
253 $id_bin .= '0001';
254 // Add 12 bits of "time high" resulting in 64 bits total
255 $id_bin .= substr( $time_bin, 0, 12 );
256 // Add 2 bits of "variant" resulting in 66 bits total
257 $id_bin .= '10';
258 // Add 6 bits of "clock seq high" resulting in 72 bits total
259 $id_bin .= substr( $clkSeq_bin, 0, 6 );
260 // Add 8 bits of "clock seq low" resulting in 80 bits total
261 $id_bin .= substr( $clkSeq_bin, 6, 8 );
262 // Add the 48 bit node ID resulting in 128 bits total
263 $id_bin .= $this->nodeId48;
264 // Convert to a 32 char hex string with dashes
265 if ( strlen( $id_bin ) !== 128 ) {
266 throw new RuntimeException( "Detected overflow for millisecond timestamp." );
267 }
268 $hex = Wikimedia\base_convert( $id_bin, 2, 16, 32 );
269 return sprintf( '%s-%s-%s-%s-%s',
270 // "time_low" (32 bits)
271 substr( $hex, 0, 8 ),
272 // "time_mid" (16 bits)
273 substr( $hex, 8, 4 ),
274 // "time_hi_and_version" (16 bits)
275 substr( $hex, 12, 4 ),
276 // "clk_seq_hi_res" (8 bits) and "clk_seq_low" (8 bits)
277 substr( $hex, 16, 4 ),
278 // "node" (48 bits)
279 substr( $hex, 20, 12 )
280 );
281 }
282
283 /**
284 * Return an RFC4122 compliant v4 UUID
285 *
286 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
287 * @return string
288 * @throws RuntimeException
289 */
290 public static function newUUIDv4( $flags = 0 ) {
291 $hex = ( $flags & self::QUICK_RAND )
292 ? wfRandomString( 31 )
293 : MWCryptRand::generateHex( 31 );
294
295 return sprintf( '%s-%s-%s-%s-%s',
296 // "time_low" (32 bits)
297 substr( $hex, 0, 8 ),
298 // "time_mid" (16 bits)
299 substr( $hex, 8, 4 ),
300 // "time_hi_and_version" (16 bits)
301 '4' . substr( $hex, 12, 3 ),
302 // "clk_seq_hi_res" (8 bits, variant is binary 10x) and "clk_seq_low" (8 bits)
303 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
304 // "node" (48 bits)
305 substr( $hex, 19, 12 )
306 );
307 }
308
309 /**
310 * Return an RFC4122 compliant v4 UUID
311 *
312 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
313 * @return string 32 hex characters with no hyphens
314 * @throws RuntimeException
315 */
316 public static function newRawUUIDv4( $flags = 0 ) {
317 return str_replace( '-', '', self::newUUIDv4( $flags ) );
318 }
319
320 /**
321 * Return an ID that is sequential *only* for this node and bucket
322 *
323 * These IDs are suitable for per-host sequence numbers, e.g. for some packet protocols.
324 * If UIDGenerator::QUICK_VOLATILE is used the counter might reset on server restart.
325 *
326 * @param string $bucket Arbitrary bucket name (should be ASCII)
327 * @param int $bits Bit size (<=48) of resulting numbers before wrap-around
328 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
329 * @return float Integer value as float
330 * @since 1.23
331 */
332 public static function newSequentialPerNodeID( $bucket, $bits = 48, $flags = 0 ) {
333 return current( self::newSequentialPerNodeIDs( $bucket, $bits, 1, $flags ) );
334 }
335
336 /**
337 * Return IDs that are sequential *only* for this node and bucket
338 *
339 * @see UIDGenerator::newSequentialPerNodeID()
340 * @param string $bucket Arbitrary bucket name (should be ASCII)
341 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
342 * @param int $count Number of IDs to return
343 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
344 * @return array Ordered list of float integer values
345 * @since 1.23
346 */
347 public static function newSequentialPerNodeIDs( $bucket, $bits, $count, $flags = 0 ) {
348 $gen = self::singleton();
349 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count, $flags );
350 }
351
352 /**
353 * Return IDs that are sequential *only* for this node and bucket
354 *
355 * @see UIDGenerator::newSequentialPerNodeID()
356 * @param string $bucket Arbitrary bucket name (should be ASCII)
357 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
358 * @param int $count Number of IDs to return
359 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
360 * @return array Ordered list of float integer values
361 * @throws RuntimeException
362 */
363 protected function getSequentialPerNodeIDs( $bucket, $bits, $count, $flags ) {
364 if ( $count <= 0 ) {
365 return []; // nothing to do
366 } elseif ( $bits < 16 || $bits > 48 ) {
367 throw new RuntimeException( "Requested bit size ($bits) is out of range." );
368 }
369
370 $counter = null; // post-increment persistent counter value
371
372 // Use APC/etc if requested, available, and not in CLI mode;
373 // Counter values would not survive across script instances in CLI mode.
374 $cache = null;
375 if ( ( $flags & self::QUICK_VOLATILE ) && !wfIsCLI() ) {
376 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
377 }
378 if ( $cache ) {
379 $counter = $cache->incrWithInit( $bucket, $cache::TTL_INDEFINITE, $count, $count );
380 if ( $counter === false ) {
381 throw new RuntimeException( 'Unable to set value to ' . get_class( $cache ) );
382 }
383 }
384
385 // Note: use of fmod() avoids "division by zero" on 32 bit machines
386 if ( $counter === null ) {
387 $path = wfTempDir() . '/mw-' . __CLASS__ . '-' . rawurlencode( $bucket ) . '-48';
388 // Get the UID lock file handle
389 if ( isset( $this->fileHandles[$path] ) ) {
390 $handle = $this->fileHandles[$path];
391 } else {
392 $handle = fopen( $path, 'cb+' );
393 $this->fileHandles[$path] = $handle ?: null; // cache
394 }
395 // Acquire the UID lock file
396 if ( $handle === false ) {
397 throw new RuntimeException( "Could not open '{$path}'." );
398 } elseif ( !flock( $handle, LOCK_EX ) ) {
399 fclose( $handle );
400 throw new RuntimeException( "Could not acquire '{$path}'." );
401 }
402 // Fetch the counter value and increment it...
403 rewind( $handle );
404 $counter = floor( trim( fgets( $handle ) ) ) + $count; // fetch as float
405 // Write back the new counter value
406 ftruncate( $handle, 0 );
407 rewind( $handle );
408 fwrite( $handle, fmod( $counter, 2 ** 48 ) ); // warp-around as needed
409 fflush( $handle );
410 // Release the UID lock file
411 flock( $handle, LOCK_UN );
412 }
413
414 $ids = [];
415 $divisor = 2 ** $bits;
416 $currentId = floor( $counter - $count ); // pre-increment counter value
417 for ( $i = 0; $i < $count; ++$i ) {
418 $ids[] = fmod( ++$currentId, $divisor );
419 }
420
421 return $ids;
422 }
423
424 /**
425 * Get a (time,counter,clock sequence) where (time,counter) is higher
426 * than any previous (time,counter) value for the given clock sequence.
427 * This is useful for making UIDs sequential on a per-node bases.
428 *
429 * @param string $lockFile Name of a local lock file
430 * @param int $clockSeqSize The number of possible clock sequence values
431 * @param int $counterSize The number of possible counter values
432 * @param int $offsetSize The number of possible offset values
433 * @return array (result of UIDGenerator::millitime(), counter, clock sequence)
434 * @throws RuntimeException
435 */
436 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
437 // Get the UID lock file handle
438 if ( isset( $this->fileHandles[$lockFile] ) ) {
439 $handle = $this->fileHandles[$lockFile];
440 } else {
441 $handle = fopen( $this->$lockFile, 'cb+' );
442 $this->fileHandles[$lockFile] = $handle ?: null; // cache
443 }
444 // Acquire the UID lock file
445 if ( $handle === false ) {
446 throw new RuntimeException( "Could not open '{$this->$lockFile}'." );
447 } elseif ( !flock( $handle, LOCK_EX ) ) {
448 fclose( $handle );
449 throw new RuntimeException( "Could not acquire '{$this->$lockFile}'." );
450 }
451 // Get the current timestamp, clock sequence number, last time, and counter
452 rewind( $handle );
453 $data = explode( ' ', fgets( $handle ) ); // "<clk seq> <sec> <msec> <counter> <offset>"
454 $clockChanged = false; // clock set back significantly?
455 if ( count( $data ) == 5 ) { // last UID info already initialized
456 $clkSeq = (int)$data[0] % $clockSeqSize;
457 $prevTime = [ (int)$data[1], (int)$data[2] ];
458 $offset = (int)$data[4] % $counterSize; // random counter offset
459 $counter = 0; // counter for UIDs with the same timestamp
460 // Delay until the clock reaches the time of the last ID.
461 // This detects any microtime() drift among processes.
462 $time = $this->timeWaitUntil( $prevTime );
463 if ( !$time ) { // too long to delay?
464 $clockChanged = true; // bump clock sequence number
465 $time = self::millitime();
466 } elseif ( $time == $prevTime ) {
467 // Bump the counter if there are timestamp collisions
468 $counter = (int)$data[3] % $counterSize;
469 if ( ++$counter >= $counterSize ) { // sanity (starts at 0)
470 flock( $handle, LOCK_UN ); // abort
471 throw new RuntimeException( "Counter overflow for timestamp value." );
472 }
473 }
474 } else { // last UID info not initialized
475 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
476 $counter = 0;
477 $offset = mt_rand( 0, $offsetSize - 1 );
478 $time = self::millitime();
479 }
480 // microtime() and gettimeofday() can drift from time() at least on Windows.
481 // The drift is immediate for processes running while the system clock changes.
482 // time() does not have this problem. See https://bugs.php.net/bug.php?id=42659.
483 $drift = time() - $time[0];
484 if ( abs( $drift ) >= 2 ) {
485 // We don't want processes using too high or low timestamps to avoid duplicate
486 // UIDs and clock sequence number churn. This process should just be restarted.
487 flock( $handle, LOCK_UN ); // abort
488 throw new RuntimeException( "Process clock is outdated or drifted ({$drift}s)." );
489 }
490 // If microtime() is synced and a clock change was detected, then the clock went back
491 if ( $clockChanged ) {
492 // Bump the clock sequence number and also randomize the counter offset,
493 // which is useful for UIDs that do not include the clock sequence number.
494 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
495 $offset = mt_rand( 0, $offsetSize - 1 );
496 trigger_error( "Clock was set back; sequence number incremented." );
497 }
498 // Update the (clock sequence number, timestamp, counter)
499 ftruncate( $handle, 0 );
500 rewind( $handle );
501 fwrite( $handle, "{$clkSeq} {$time[0]} {$time[1]} {$counter} {$offset}" );
502 fflush( $handle );
503 // Release the UID lock file
504 flock( $handle, LOCK_UN );
505
506 return [
507 'time' => $time,
508 'counter' => $counter,
509 'clkSeq' => $clkSeq,
510 'offset' => $offset,
511 'offsetCounter' => $counter + $offset
512 ];
513 }
514
515 /**
516 * Wait till the current timestamp reaches $time and return the current
517 * timestamp. This returns false if it would have to wait more than 10ms.
518 *
519 * @param array $time Result of UIDGenerator::millitime()
520 * @return array|bool UIDGenerator::millitime() result or false
521 */
522 protected function timeWaitUntil( array $time ) {
523 do {
524 $ct = self::millitime();
525 if ( $ct >= $time ) { // https://secure.php.net/manual/en/language.operators.comparison.php
526 return $ct; // current timestamp is higher than $time
527 }
528 } while ( ( ( $time[0] - $ct[0] ) * 1000 + ( $time[1] - $ct[1] ) ) <= 10 );
529
530 return false;
531 }
532
533 /**
534 * @param array $time Result of UIDGenerator::millitime()
535 * @return string 46 LSBs of "milliseconds since epoch" in binary (rolls over in 4201)
536 * @throws RuntimeException
537 */
538 protected function millisecondsSinceEpochBinary( array $time ) {
539 list( $sec, $msec ) = $time;
540 $ts = 1000 * $sec + $msec;
541 if ( $ts > 2 ** 52 ) {
542 throw new RuntimeException( __METHOD__ .
543 ': sorry, this function doesn\'t work after the year 144680' );
544 }
545
546 return substr( Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
547 }
548
549 /**
550 * @param array $time Result of UIDGenerator::millitime()
551 * @param int $delta Number of intervals to add on to the timestamp
552 * @return string 60 bits of "100ns intervals since 15 October 1582" (rolls over in 3400)
553 * @throws RuntimeException
554 */
555 protected function intervalsSinceGregorianBinary( array $time, $delta = 0 ) {
556 list( $sec, $msec ) = $time;
557 $offset = '122192928000000000';
558 if ( PHP_INT_SIZE >= 8 ) { // 64 bit integers
559 $ts = ( 1000 * $sec + $msec ) * 10000 + (int)$offset + $delta;
560 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60, '0', STR_PAD_LEFT );
561 } elseif ( extension_loaded( 'gmp' ) ) {
562 $ts = gmp_add( gmp_mul( (string)$sec, '1000' ), (string)$msec ); // ms
563 $ts = gmp_add( gmp_mul( $ts, '10000' ), $offset ); // 100ns intervals
564 $ts = gmp_add( $ts, (string)$delta );
565 $ts = gmp_mod( $ts, gmp_pow( '2', '60' ) ); // wrap around
566 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60, '0', STR_PAD_LEFT );
567 } elseif ( extension_loaded( 'bcmath' ) ) {
568 $ts = bcadd( bcmul( $sec, 1000 ), $msec ); // ms
569 $ts = bcadd( bcmul( $ts, 10000 ), $offset ); // 100ns intervals
570 $ts = bcadd( $ts, $delta );
571 $ts = bcmod( $ts, bcpow( 2, 60 ) ); // wrap around
572 $id_bin = Wikimedia\base_convert( $ts, 10, 2, 60 );
573 } else {
574 throw new RuntimeException( 'bcmath or gmp extension required for 32 bit machines.' );
575 }
576 return $id_bin;
577 }
578
579 /**
580 * @return array (current time in seconds, milliseconds since then)
581 */
582 protected static function millitime() {
583 list( $msec, $sec ) = explode( ' ', microtime() );
584
585 return [ (int)$sec, (int)( $msec * 1000 ) ];
586 }
587
588 /**
589 * Delete all cache files that have been created.
590 *
591 * This is a cleanup method primarily meant to be used from unit tests to
592 * avoid poluting the local filesystem. If used outside of a unit test
593 * environment it should be used with caution as it may destroy state saved
594 * in the files.
595 *
596 * @see unitTestTearDown
597 * @since 1.23
598 */
599 protected function deleteCacheFiles() {
600 // Bug: 44850
601 foreach ( $this->fileHandles as $path => $handle ) {
602 if ( $handle !== null ) {
603 fclose( $handle );
604 }
605 if ( is_file( $path ) ) {
606 unlink( $path );
607 }
608 unset( $this->fileHandles[$path] );
609 }
610 if ( is_file( $this->nodeIdFile ) ) {
611 unlink( $this->nodeIdFile );
612 }
613 }
614
615 /**
616 * Cleanup resources when tearing down after a unit test.
617 *
618 * This is a cleanup method primarily meant to be used from unit tests to
619 * avoid poluting the local filesystem. If used outside of a unit test
620 * environment it should be used with caution as it may destroy state saved
621 * in the files.
622 *
623 * @see deleteCacheFiles
624 * @since 1.23
625 */
626 public static function unitTestTearDown() {
627 // Bug: 44850
628 $gen = self::singleton();
629 $gen->deleteCacheFiles();
630 }
631
632 function __destruct() {
633 array_map( 'fclose', array_filter( $this->fileHandles ) );
634 }
635 }