23use InvalidArgumentException;
25use Wikimedia\Assert\Assert;
26use Wikimedia\AtEase\AtEase;
27use Wikimedia\Timestamp\ConvertibleTimestamp;
68 private const FILE_PREFIX =
'mw-GlobalIdGenerator';
71 private const CLOCK_TIME =
'time';
73 private const CLOCK_COUNTER =
'counter';
75 private const CLOCK_SEQUENCE =
'clkSeq';
77 private const CLOCK_OFFSET =
'offset';
79 private const CLOCK_OFFSET_COUNTER =
'offsetCounter';
88 __CLASS__ .
' with a BagOStuff instance was deprecated in MediaWiki 1.37.',
93 if ( $tempDirectory ===
false || $tempDirectory ===
'' ) {
94 throw new InvalidArgumentException(
"No temp directory provided" );
96 $this->tmpDir = $tempDirectory;
98 if ( function_exists(
'posix_geteuid' ) ) {
99 $fileSuffix = posix_geteuid();
100 } elseif ( function_exists(
'getmyuid' ) ) {
101 $fileSuffix = getmyuid();
105 $this->uniqueFilePrefix = self::FILE_PREFIX . $fileSuffix;
106 $this->nodeIdFile = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UID-nodeid';
109 $this->lockFile88 = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UID-88';
110 $this->lockFile128 = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UID-128';
111 $this->lockFileUUID = $tempDirectory .
'/' . $this->uniqueFilePrefix .
'-UUID-128';
132 Assert::parameter( $base <= 36,
'$base',
'must be <= 36' );
133 Assert::parameter( $base >= 2,
'$base',
'must be >= 2' );
136 $info[self::CLOCK_OFFSET_COUNTER] %= 1024;
147 $time = $info[self::CLOCK_TIME];
148 $counter = $info[self::CLOCK_OFFSET_COUNTER];
152 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
154 $id_bin .= $this->getNodeId32();
156 if ( strlen( $id_bin ) !== 88 ) {
157 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
178 Assert::parameter( $base <= 36,
'$base',
'must be <= 36' );
179 Assert::parameter( $base >= 2,
'$base',
'must be >= 2' );
181 $info = $this->
getTimeAndDelay(
'lockFile128', 16384, 1_048_576, 1_048_576 );
182 $info[self::CLOCK_OFFSET_COUNTER] %= 1_048_576;
193 $time = $info[self::CLOCK_TIME];
194 $counter = $info[self::CLOCK_OFFSET_COUNTER];
195 $clkSeq = $info[self::CLOCK_SEQUENCE];
199 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
201 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
203 $id_bin .= $this->getNodeId48();
205 if ( strlen( $id_bin ) !== 128 ) {
206 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
230 $clkSeq_bin = \Wikimedia\base_convert( $info[self::CLOCK_SEQUENCE], 10, 2, 14 );
232 $info[self::CLOCK_TIME],
233 $info[self::CLOCK_OFFSET_COUNTER]
236 $id_bin = substr( $time_bin, 28, 32 );
238 $id_bin .= substr( $time_bin, 12, 16 );
242 $id_bin .= substr( $time_bin, 0, 12 );
246 $id_bin .= substr( $clkSeq_bin, 0, 6 );
248 $id_bin .= substr( $clkSeq_bin, 6, 8 );
250 $id_bin .= $this->getNodeId48();
252 if ( strlen( $id_bin ) !== 128 ) {
253 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
255 $hex = \Wikimedia\base_convert( $id_bin, 2, 16, 32 );
256 return sprintf(
'%s-%s-%s-%s-%s',
258 substr( $hex, 0, 8 ),
260 substr( $hex, 8, 4 ),
262 substr( $hex, 12, 4 ),
264 substr( $hex, 16, 4 ),
266 substr( $hex, 20, 12 )
277 return str_replace(
'-',
'', $this->
newUUIDv1() );
287 $hex = bin2hex( random_bytes( 32 / 2 ) );
289 return sprintf(
'%s-%s-%s-%s-%s',
291 substr( $hex, 0, 8 ),
293 substr( $hex, 8, 4 ),
295 '4' . substr( $hex, 12, 3 ),
297 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
299 substr( $hex, 19, 12 )
310 return str_replace(
'-',
'', $this->
newUUIDv4() );
349 '/^([0-9a-f]{8})-([0-9a-f]{4})-(1[0-9a-f]{3})-([89ab][0-9a-f]{3})-([0-9a-f]{12})$/',
353 throw new InvalidArgumentException(
"Invalid UUIDv1 {$uuid}" );
356 $timestamp = hexdec( substr( $components[3], 1 ) . $components[2] . $components[1] );
359 $unixTime = ( $timestamp - 0x01b21dd213814000 ) / 1e7;
361 return ConvertibleTimestamp::convert( $format, $unixTime );
378 if ( $bits < 16 || $bits > 48 ) {
379 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
382 $path = $this->tmpDir .
'/' . $this->uniqueFilePrefix .
'-' . rawurlencode( $bucket ) .
'-48';
384 if ( isset( $this->fileHandles[
$path] ) ) {
385 $handle = $this->fileHandles[
$path];
387 $handle = fopen(
$path,
'cb+' );
388 $this->fileHandles[
$path] = $handle ?:
null;
391 if ( $handle ===
false ) {
392 throw new RuntimeException(
"Could not open '{$path}'." );
394 if ( !flock( $handle, LOCK_EX ) ) {
396 throw new RuntimeException(
"Could not acquire '{$path}'." );
402 $counter = floor( (
float)trim( fgets( $handle ) ) ) + $count;
405 ftruncate( $handle, 0 );
410 fwrite( $handle, (
string)fmod( $counter, 2 ** 48 ) );
414 flock( $handle, LOCK_UN );
417 $divisor = 2 ** $bits;
420 $currentId = floor( $counter - $count );
421 for ( $i = 0; $i < $count; ++$i ) {
423 $ids[] = fmod( ++$currentId, $divisor );
446 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
448 if ( isset( $this->fileHandles[$this->$lockFile] ) ) {
449 $handle = $this->fileHandles[$this->$lockFile];
451 $handle = fopen( $this->$lockFile,
'cb+' );
452 $this->fileHandles[$this->$lockFile] = $handle ?:
null;
455 if ( $handle ===
false ) {
456 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
458 if ( !flock( $handle, LOCK_EX ) ) {
460 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
505 $msecCounterSize = $counterSize * 1000;
510 $data = explode(
' ', fgets( $handle ) );
512 if ( count( $data ) === 4 ) {
514 $clkSeq = (int)$data[0] % $clockSeqSize;
515 $prevSec = (int)$data[1];
516 $prevMsecCounter = (int)$data[2] % $msecCounterSize;
517 $randOffset = (int)$data[3] % $counterSize;
522 if ( $sec ===
false ) {
525 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
528 $randOffset = random_int( 0, $offsetSize - 1 );
529 trigger_error(
"Clock was set back; sequence number incremented." );
530 } elseif ( $sec === $prevSec ) {
532 $msecCounter = $prevMsecCounter + 1;
533 if ( $msecCounter >= $msecCounterSize ) {
535 flock( $handle, LOCK_UN );
536 throw new RuntimeException(
"Counter overflow for timestamp value." );
544 $clkSeq = random_int( 0, $clockSeqSize - 1 );
547 $randOffset = random_int( 0, $offsetSize - 1 );
551 ftruncate( $handle, 0 );
553 fwrite( $handle,
"{$clkSeq} {$sec} {$msecCounter} {$randOffset}" );
555 flock( $handle, LOCK_UN );
558 $msec = (int)( $msecCounter / 1000 );
559 $counter = $msecCounter % 1000;
562 self::CLOCK_TIME => [ $sec, $msec ],
563 self::CLOCK_COUNTER => $counter,
564 self::CLOCK_SEQUENCE => $clkSeq,
565 self::CLOCK_OFFSET => $randOffset,
566 self::CLOCK_OFFSET_COUNTER => $counter + $randOffset,
578 $start = microtime(
true );
582 if ( $ct >= $time ) {
587 }
while ( ( microtime(
true ) - $start ) <= 0.010 );
598 [ $sec, $msec ] = $time;
599 $ts = 1000 * $sec + $msec;
600 if ( $ts > 2 ** 52 ) {
601 throw new RuntimeException( __METHOD__ .
602 ': sorry, this function doesn\'t work after the year 144680' );
605 return substr( \
Wikimedia\base_convert( (
string)$ts, 10, 2, 46 ), -46 );
615 [ $sec, $msec ] = $time;
616 $offset =
'122192928000000000';
619 if ( PHP_INT_SIZE >= 8 ) {
620 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
621 $id_bin = str_pad( decbin( $ts % ( 2 ** 60 ) ), 60,
'0', STR_PAD_LEFT );
622 } elseif ( extension_loaded(
'gmp' ) ) {
624 $ts = gmp_add( gmp_mul( (
string)$sec,
'1000' ), (
string)$msec );
626 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
627 $ts = gmp_add( $ts, (
string)$delta );
629 $ts = gmp_mod( $ts, gmp_pow(
'2', 60 ) );
630 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
631 } elseif ( extension_loaded(
'bcmath' ) ) {
633 $ts = bcadd( bcmul( $sec,
'1000' ), $msec );
635 $ts = bcadd( bcmul( $ts,
'10000' ), $offset );
636 $ts = bcadd( $ts, (
string)$delta );
638 $ts = bcmod( $ts, bcpow(
'2',
'60' ) );
639 $id_bin = \Wikimedia\base_convert( $ts, 10, 2, 60 );
641 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
649 private function load() {
650 if ( $this->loaded ) {
654 $this->loaded =
true;
657 $nodeId = @file_get_contents( $this->nodeIdFile ) ?:
'';
659 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
660 AtEase::suppressWarnings();
661 if ( PHP_OS_FAMILY ===
'Windows' ) {
663 $csv = trim( ( $this->shellCallback )(
'getmac /NH /FO CSV' ) );
664 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
665 $info = str_getcsv( $line,
",",
"\"",
"\\" );
667 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
668 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
672 preg_match(
'/\s([0-9a-f]{2}(?::[0-9a-f]{2}){5})\s/',
673 ( $this->shellCallback )(
'/sbin/ifconfig -a' ), $m );
674 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
676 AtEase::restoreWarnings();
677 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
678 $nodeId = bin2hex( random_bytes( 12 / 2 ) );
680 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
682 file_put_contents( $this->nodeIdFile, $nodeId );
684 $this->nodeId32 = \Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
685 $this->nodeId48 = \Wikimedia\base_convert( $nodeId, 16, 2, 48 );
691 private function getNodeId32() {
700 private function getNodeId48() {
717 private function deleteCacheFiles() {
718 foreach ( $this->fileHandles as
$path => $handle ) {
719 if ( $handle !==
null ) {
722 if ( is_file(
$path ) ) {
725 unset( $this->fileHandles[
$path] );
727 if ( is_file( $this->nodeIdFile ) ) {
728 unlink( $this->nodeIdFile );
745 $this->deleteCacheFiles();
750 array_map(
'fclose', array_filter( $this->fileHandles ) );