9use InvalidArgumentException;
11use Wikimedia\Assert\Assert;
12use Wikimedia\AtEase\AtEase;
13use Wikimedia\Timestamp\ConvertibleTimestamp;
54 private const FILE_PREFIX =
'mw-GlobalIdGenerator';
57 private const CLOCK_TIME =
'time';
59 private const CLOCK_COUNTER =
'counter';
61 private const CLOCK_SEQUENCE =
'clkSeq';
63 private const CLOCK_OFFSET =
'offset';
65 private const CLOCK_OFFSET_COUNTER =
'offsetCounter';
74 __CLASS__ .
' with a BagOStuff instance was deprecated in MediaWiki 1.37.',
79 if ( $tempDirectory ===
false || $tempDirectory ===
'' ) {
80 throw new InvalidArgumentException(
"No temp directory provided" );
82 $this->tmpDir = $tempDirectory;
84 if ( function_exists(
'posix_geteuid' ) ) {
85 $fileSuffix = posix_geteuid();
86 } elseif ( function_exists(
'getmyuid' ) ) {
87 $fileSuffix = getmyuid();
91 $this->uniqueFilePrefix = self::FILE_PREFIX . $fileSuffix;
92 $this->nodeIdFile = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UID-nodeid';
95 $this->lockFile88 = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UID-88';
96 $this->lockFile128 = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UID-128';
97 $this->lockFileUUID = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UUID-128';
118 Assert::parameter( $base <= 36,
'$base',
'must be <= 36' );
119 Assert::parameter( $base >= 2,
'$base',
'must be >= 2' );
122 $info[self::CLOCK_OFFSET_COUNTER] %= 1024;
133 $time = $info[self::CLOCK_TIME];
134 $counter = $info[self::CLOCK_OFFSET_COUNTER];
138 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
140 $id_bin .= $this->getNodeId32();
142 if ( strlen( $id_bin ) !== 88 ) {
143 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
164 Assert::parameter( $base <= 36,
'$base',
'must be <= 36' );
165 Assert::parameter( $base >= 2,
'$base',
'must be >= 2' );
167 $info = $this->
getTimeAndDelay(
'lockFile128', 16384, 1_048_576, 1_048_576 );
168 $info[self::CLOCK_OFFSET_COUNTER] %= 1_048_576;
179 $time = $info[self::CLOCK_TIME];
180 $counter = $info[self::CLOCK_OFFSET_COUNTER];
181 $clkSeq = $info[self::CLOCK_SEQUENCE];
185 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
187 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
189 $id_bin .= $this->getNodeId48();
191 if ( strlen( $id_bin ) !== 128 ) {
192 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
216 $clkSeq_bin = \Wikimedia\base_convert( $info[self::CLOCK_SEQUENCE], 10, 2, 14 );
218 $info[self::CLOCK_TIME],
219 $info[self::CLOCK_OFFSET_COUNTER]
222 $id_bin = substr( $time_bin, 28, 32 );
224 $id_bin .= substr( $time_bin, 12, 16 );
228 $id_bin .= substr( $time_bin, 0, 12 );
232 $id_bin .= substr( $clkSeq_bin, 0, 6 );
234 $id_bin .= substr( $clkSeq_bin, 6, 8 );
236 $id_bin .= $this->getNodeId48();
238 if ( strlen( $id_bin ) !== 128 ) {
239 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
241 $hex = \Wikimedia\base_convert( $id_bin, 2, 16, 32 );
242 return sprintf(
'%s-%s-%s-%s-%s',
244 substr( $hex, 0, 8 ),
246 substr( $hex, 8, 4 ),
248 substr( $hex, 12, 4 ),
250 substr( $hex, 16, 4 ),
252 substr( $hex, 20, 12 )
263 return str_replace(
'-',
'', $this->
newUUIDv1() );
273 $hex = bin2hex( random_bytes( 32 / 2 ) );
275 return sprintf(
'%s-%s-%s-%s-%s',
277 substr( $hex, 0, 8 ),
279 substr( $hex, 8, 4 ),
281 '4' . substr( $hex, 12, 3 ),
283 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
285 substr( $hex, 19, 12 )
296 return str_replace(
'-',
'', $this->
newUUIDv4() );
335 '/^([0-9a-f]{8})-([0-9a-f]{4})-(1[0-9a-f]{3})-([89ab][0-9a-f]{3})-([0-9a-f]{12})$/',
339 throw new InvalidArgumentException(
"Invalid UUIDv1 {$uuid}" );
342 $timestamp = hexdec( substr( $components[3], 1 ) . $components[2] . $components[1] );
345 $unixTime = ( $timestamp - 0x01b21dd213814000 ) / 1e7;
347 return ConvertibleTimestamp::convert( $format, $unixTime );
364 if ( $bits < 16 || $bits > 48 ) {
365 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
368 $path = $this->tmpDir .
'/' . $this->uniqueFilePrefix .
'-' . rawurlencode( $bucket ) .
'-48';
370 if ( isset( $this->fileHandles[
$path] ) ) {
371 $handle = $this->fileHandles[
$path];
373 $handle = fopen(
$path,
'cb+' );
374 $this->fileHandles[
$path] = $handle ?:
null;
377 if ( $handle ===
false ) {
378 throw new RuntimeException(
"Could not open '{$path}'." );
380 if ( !flock( $handle, LOCK_EX ) ) {
382 throw new RuntimeException(
"Could not acquire '{$path}'." );
388 $counter = floor( (
float)trim( fgets( $handle ) ) ) + $count;
391 ftruncate( $handle, 0 );
396 fwrite( $handle, (
string)fmod( $counter, 2 ** 48 ) );
400 flock( $handle, LOCK_UN );
403 $divisor = 2 ** $bits;
406 $currentId = floor( $counter - $count );
407 for ( $i = 0; $i < $count; ++$i ) {
409 $ids[] = fmod( ++$currentId, $divisor );
432 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
434 if ( isset( $this->fileHandles[$this->$lockFile] ) ) {
435 $handle = $this->fileHandles[$this->$lockFile];
437 $handle = fopen( $this->$lockFile,
'cb+' );
438 $this->fileHandles[$this->$lockFile] = $handle ?:
null;
441 if ( $handle ===
false ) {
442 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
444 if ( !flock( $handle, LOCK_EX ) ) {
446 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
491 $msecCounterSize = $counterSize * 1000;
496 $data = explode(
' ', fgets( $handle ) );
498 if ( count( $data ) === 4 ) {
500 $clkSeq = (int)$data[0] % $clockSeqSize;
501 $prevSec = (int)$data[1];
502 $prevMsecCounter = (int)$data[2] % $msecCounterSize;
503 $randOffset = (int)$data[3] % $counterSize;
508 if ( $sec ===
false ) {
511 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
514 $randOffset = random_int( 0, $offsetSize - 1 );
515 trigger_error(
"Clock was set back; sequence number incremented." );
516 } elseif ( $sec === $prevSec ) {
518 $msecCounter = $prevMsecCounter + 1;
519 if ( $msecCounter >= $msecCounterSize ) {
521 flock( $handle, LOCK_UN );
522 throw new RuntimeException(
"Counter overflow for timestamp value." );
530 $clkSeq = random_int( 0, $clockSeqSize - 1 );
533 $randOffset = random_int( 0, $offsetSize - 1 );
537 ftruncate( $handle, 0 );
539 fwrite( $handle,
"{$clkSeq} {$sec} {$msecCounter} {$randOffset}" );
541 flock( $handle, LOCK_UN );
544 $msec = (int)( $msecCounter / 1000 );
545 $counter = $msecCounter % 1000;
548 self::CLOCK_TIME => [ $sec, $msec ],
549 self::CLOCK_COUNTER => $counter,
550 self::CLOCK_SEQUENCE => $clkSeq,
551 self::CLOCK_OFFSET => $randOffset,
552 self::CLOCK_OFFSET_COUNTER => $counter + $randOffset,
564 $start = microtime(
true );
568 if ( $ct >= $time ) {
573 }
while ( ( microtime(
true ) - $start ) <= 0.010 );
584 [ $sec, $msec ] = $time;
585 $ts = 1000 * $sec + $msec;
586 if ( $ts > 2 ** 52 ) {
587 throw new RuntimeException( __METHOD__ .
588 ': sorry, this function doesn\'t work after the year 144680' );
591 return substr( \
Wikimedia\base_convert( (
string)$ts, 10, 2, 46 ), -46 );
601 [ $sec, $msec ] = $time;
602 $offset =
'122192928000000000';
605 if ( PHP_INT_SIZE >= 8 ) {
606 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
607 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60,
'0', STR_PAD_LEFT );
608 } elseif ( extension_loaded(
'gmp' ) ) {
610 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
612 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
613 $ts = gmp_add( $ts, (
string)$delta );
615 $ts = gmp_mod( $ts, gmp_pow(
'2', 60 ) );
616 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
617 } elseif ( extension_loaded(
'bcmath' ) ) {
619 $ts = bcadd( bcmul( $sec,
'1000' ), $msec );
621 $ts = bcadd( bcmul( $ts,
'10000' ), $offset );
622 $ts = bcadd( $ts, (
string)$delta );
624 $ts = bcmod( $ts, bcpow(
'2',
'60' ) );
625 $id_bin = \Wikimedia\base_convert( $ts, 10, 2, 60 );
627 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
635 private function load() {
636 if ( $this->loaded ) {
640 $this->loaded =
true;
643 $nodeId = @file_get_contents( $this->nodeIdFile ) ?:
'';
645 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
646 AtEase::suppressWarnings();
647 if ( PHP_OS_FAMILY ===
'Windows' ) {
649 $csv = trim( ( $this->shellCallback )(
'getmac /NH /FO CSV' ) );
650 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
651 $info = str_getcsv( $line,
",",
"\"",
"\\" );
653 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
654 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
658 preg_match(
'/\s([0-9a-f]{2}(?::[0-9a-f]{2}){5})\s/',
659 ( $this->shellCallback )(
'/sbin/ifconfig -a' ), $m );
660 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
662 AtEase::restoreWarnings();
663 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
664 $nodeId = bin2hex( random_bytes( 12 / 2 ) );
666 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
668 file_put_contents( $this->nodeIdFile, $nodeId );
670 $this->nodeId32 = \Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
671 $this->nodeId48 = \Wikimedia\base_convert( $nodeId, 16, 2, 48 );
677 private function getNodeId32() {
686 private function getNodeId48() {
703 private function deleteCacheFiles() {
704 foreach ( $this->fileHandles as
$path => $handle ) {
705 if ( $handle !==
null ) {
708 if ( is_file(
$path ) ) {
711 unset( $this->fileHandles[
$path] );
713 if ( is_file( $this->nodeIdFile ) ) {
714 unlink( $this->nodeIdFile );
731 $this->deleteCacheFiles();
736 array_map(
'fclose', array_filter( $this->fileHandles ) );