23 use Wikimedia\Assert\Assert;
49 $this->nodeIdFile =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-nodeid';
51 if ( is_file( $this->nodeIdFile ) ) {
52 $nodeId = file_get_contents( $this->nodeIdFile );
55 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
56 MediaWiki\suppressWarnings();
60 $line = substr( $csv, 0, strcspn( $csv,
"\n" ) );
61 $info = str_getcsv(
$line );
62 $nodeId = isset( $info[0] ) ? str_replace(
'-',
'', $info[0] ) :
'';
63 } elseif ( is_executable(
'/sbin/ifconfig' ) ) {
66 preg_match(
'/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
68 $nodeId = isset( $m[1] ) ? str_replace(
':',
'', $m[1] ) :
'';
70 MediaWiki\restoreWarnings();
71 if ( !preg_match(
'/^[0-9a-f]{12}$/i', $nodeId ) ) {
73 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 );
75 file_put_contents( $this->nodeIdFile, $nodeId );
77 $this->nodeId32 = Wikimedia\base_convert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
78 $this->nodeId48 = Wikimedia\base_convert( $nodeId, 16, 2, 48 );
81 $this->lockFile88 =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-88';
82 $this->lockFile128 =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UID-128';
83 $this->lockFileUUID =
wfTempDir() .
'/mw-' . __CLASS__ .
'-UUID-128';
91 if ( self::$instance === null ) {
92 self::$instance =
new self();
95 return self::$instance;
114 Assert::parameterType(
'integer',
$base,
'$base' );
115 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
116 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
118 $gen = self::singleton();
119 $info = $gen->getTimeAndDelay(
'lockFile88', 1, 1024, 1024 );
120 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1024;
121 return Wikimedia\base_convert( $gen->getTimestampedID88( $info ), 2,
$base );
131 if ( isset( $info[
'time'] ) ) {
132 $time = $info[
'time'];
133 $counter = $info[
'offsetCounter'];
141 $id_bin .= str_pad( decbin( $counter ), 10,
'0', STR_PAD_LEFT );
145 if ( strlen( $id_bin ) !== 88 ) {
146 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
167 Assert::parameterType(
'integer',
$base,
'$base' );
168 Assert::parameter(
$base <= 36,
'$base',
'must be <= 36' );
169 Assert::parameter(
$base >= 2,
'$base',
'must be >= 2' );
171 $gen = self::singleton();
172 $info = $gen->getTimeAndDelay(
'lockFile128', 16384, 1048576, 1048576 );
173 $info[
'offsetCounter'] = $info[
'offsetCounter'] % 1048576;
175 return Wikimedia\base_convert( $gen->getTimestampedID128( $info ), 2,
$base );
185 if ( isset( $info[
'time'] ) ) {
186 $time = $info[
'time'];
187 $counter = $info[
'offsetCounter'];
188 $clkSeq = $info[
'clkSeq'];
197 $id_bin .= str_pad( decbin( $counter ), 20,
'0', STR_PAD_LEFT );
199 $id_bin .= str_pad( decbin( $clkSeq ), 14,
'0', STR_PAD_LEFT );
203 if ( strlen( $id_bin ) !== 128 ) {
204 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
218 $gen = self::singleton();
222 return $gen->getUUIDv1( $gen->getTimeAndDelay(
'lockFileUUID', 16384, 5000, 5001 ) );
233 return str_replace(
'-',
'', self::newUUIDv1() );
241 $clkSeq_bin = Wikimedia\base_convert( $info[
'clkSeq'], 10, 2, 14 );
244 $id_bin = substr( $time_bin, 28, 32 );
246 $id_bin .= substr( $time_bin, 12, 16 );
250 $id_bin .= substr( $time_bin, 0, 12 );
254 $id_bin .= substr( $clkSeq_bin, 0, 6 );
256 $id_bin .= substr( $clkSeq_bin, 6, 8 );
260 if ( strlen( $id_bin ) !== 128 ) {
261 throw new RuntimeException(
"Detected overflow for millisecond timestamp." );
263 $hex = Wikimedia\base_convert( $id_bin, 2, 16, 32 );
264 return sprintf(
'%s-%s-%s-%s-%s',
266 substr( $hex, 0, 8 ),
268 substr( $hex, 8, 4 ),
270 substr( $hex, 12, 4 ),
272 substr( $hex, 16, 4 ),
274 substr( $hex, 20, 12 )
286 $hex = (
$flags & self::QUICK_RAND )
290 return sprintf(
'%s-%s-%s-%s-%s',
292 substr( $hex, 0, 8 ),
294 substr( $hex, 8, 4 ),
296 '4' . substr( $hex, 12, 3 ),
298 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
300 substr( $hex, 19, 12 )
312 return str_replace(
'-',
'', self::newUUIDv4(
$flags ) );
328 return current( self::newSequentialPerNodeIDs( $bucket, $bits, 1,
$flags ) );
343 $gen = self::singleton();
344 return $gen->getSequentialPerNodeIDs( $bucket, $bits,
$count,
$flags );
361 } elseif ( $bits < 16 || $bits > 48 ) {
362 throw new RuntimeException(
"Requested bit size ($bits) is out of range." );
370 if ( (
$flags & self::QUICK_VOLATILE ) && PHP_SAPI !==
'cli' ) {
375 if ( $counter ===
false ) {
376 throw new RuntimeException(
'Unable to set value to ' . get_class(
$cache ) );
381 if ( $counter === null ) {
382 $path =
wfTempDir() .
'/mw-' . __CLASS__ .
'-' . 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}'." );
393 } elseif ( !flock( $handle, LOCK_EX ) ) {
395 throw new RuntimeException(
"Could not acquire '{$path}'." );
399 $counter = floor( trim( fgets( $handle ) ) ) +
$count;
401 ftruncate( $handle, 0 );
403 fwrite( $handle, fmod( $counter, pow( 2, 48 ) ) );
406 flock( $handle, LOCK_UN );
410 $divisor = pow( 2, $bits );
411 $currentId = floor( $counter -
$count );
412 for ( $i = 0; $i <
$count; ++$i ) {
413 $ids[] = fmod( ++$currentId, $divisor );
431 protected function getTimeAndDelay( $lockFile, $clockSeqSize, $counterSize, $offsetSize ) {
433 if ( isset( $this->fileHandles[$lockFile] ) ) {
434 $handle = $this->fileHandles[$lockFile];
436 $handle = fopen( $this->$lockFile,
'cb+' );
437 $this->fileHandles[$lockFile] = $handle ?: null;
440 if ( $handle ===
false ) {
441 throw new RuntimeException(
"Could not open '{$this->$lockFile}'." );
442 } elseif ( !flock( $handle, LOCK_EX ) ) {
444 throw new RuntimeException(
"Could not acquire '{$this->$lockFile}'." );
448 $data = explode(
' ', fgets( $handle ) );
449 $clockChanged =
false;
450 if ( count( $data ) == 5 ) {
451 $clkSeq = (int)$data[0] % $clockSeqSize;
452 $prevTime = [ (int)$data[1], (
int)$data[2] ];
453 $offset = (int)$data[4] % $counterSize;
459 $clockChanged =
true;
460 $time = self::millitime();
461 } elseif (
$time == $prevTime ) {
463 $counter = (int)$data[3] % $counterSize;
464 if ( ++$counter >= $counterSize ) {
465 flock( $handle, LOCK_UN );
466 throw new RuntimeException(
"Counter overflow for timestamp value." );
470 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
472 $offset = mt_rand( 0, $offsetSize - 1 );
473 $time = self::millitime();
478 if ( abs( time() -
$time[0] ) >= 2 ) {
481 flock( $handle, LOCK_UN );
482 throw new RuntimeException(
"Process clock is outdated or drifted." );
485 if ( $clockChanged ) {
488 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
489 $offset = mt_rand( 0, $offsetSize - 1 );
490 trigger_error(
"Clock was set back; sequence number incremented." );
493 ftruncate( $handle, 0 );
495 fwrite( $handle,
"{$clkSeq} {$time[0]} {$time[1]} {$counter} {$offset}" );
498 flock( $handle, LOCK_UN );
502 'counter' => $counter,
505 'offsetCounter' => $counter + $offset
518 $ct = self::millitime();
519 if ( $ct >= $time ) {
522 }
while ( ( ( $time[0] - $ct[0] ) * 1000 + ( $time[1] - $ct[1] ) ) <= 10 );
534 $ts = 1000 * $sec + $msec;
535 if ( $ts > pow( 2, 52 ) ) {
536 throw new RuntimeException( __METHOD__ .
537 ': sorry, this function doesn\'t work after the year 144680' );
540 return substr( Wikimedia\base_convert( $ts, 10, 2, 46 ), -46 );
551 $offset =
'122192928000000000';
552 if ( PHP_INT_SIZE >= 8 ) {
553 $ts = ( 1000 * $sec + $msec ) * 10000 + (
int)$offset + $delta;
554 $id_bin = str_pad( decbin( $ts % pow( 2, 60 ) ), 60,
'0', STR_PAD_LEFT );
555 } elseif ( extension_loaded(
'gmp' ) ) {
556 $ts = gmp_add( gmp_mul( (
string) $sec,
'1000' ), (
string) $msec );
557 $ts = gmp_add( gmp_mul( $ts,
'10000' ), $offset );
558 $ts = gmp_add( $ts, (
string) $delta );
559 $ts = gmp_mod( $ts, gmp_pow(
'2',
'60' ) );
560 $id_bin = str_pad( gmp_strval( $ts, 2 ), 60,
'0', STR_PAD_LEFT );
561 } elseif ( extension_loaded(
'bcmath' ) ) {
562 $ts = bcadd( bcmul( $sec, 1000 ), $msec );
563 $ts = bcadd( bcmul( $ts, 10000 ), $offset );
564 $ts = bcadd( $ts, $delta );
565 $ts = bcmod( $ts, bcpow( 2, 60 ) );
566 $id_bin = Wikimedia\base_convert( $ts, 10, 2, 60 );
568 throw new RuntimeException(
'bcmath or gmp extension required for 32 bit machines.' );
577 list( $msec, $sec ) = explode(
' ', microtime() );
579 return [ (int)$sec, (
int)( $msec * 1000 ) ];
595 foreach ( $this->fileHandles
as $path => $handle ) {
596 if ( $handle !== null ) {
599 if ( is_file(
$path ) ) {
602 unset( $this->fileHandles[
$path] );
604 if ( is_file( $this->nodeIdFile ) ) {
605 unlink( $this->nodeIdFile );
622 $gen = self::singleton();
623 $gen->deleteCacheFiles();
627 array_map(
'fclose', array_filter( $this->fileHandles ) );
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
the array() calling protocol came about after MediaWiki 1.4rc1.
static newTimestampedUID128($base=10)
Get a statistically unique 128-bit unsigned integer ID string.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static newSequentialPerNodeIDs($bucket, $bits, $count, $flags=0)
Return IDs that are sequential only for this node and bucket.
Class for getting statistically unique IDs.
millisecondsSinceEpochBinary(array $time)
it s the revision text itself In either if gzip is the revision text is gzipped $flags
wfShellExec($cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
intervalsSinceGregorianBinary(array $time, $delta=0)
wfIsWindows()
Check if the operating system is Windows.
wfRandomString($length=32)
Get a random string containing a number of pseudo-random hex characters.
see documentation in includes Linker php for Linker::makeImageLink & $time
static newTimestampedUID88($base=10)
Get a statistically unique 88-bit unsigned integer ID string.
getTimeAndDelay($lockFile, $clockSeqSize, $counterSize, $offsetSize)
Get a (time,counter,clock sequence) where (time,counter) is higher than any previous (time...
wfTempDir()
Tries to get the system directory for temporary files.
static newRawUUIDv4($flags=0)
Return an RFC4122 compliant v4 UUID.
getSequentialPerNodeIDs($bucket, $bits, $count, $flags)
Return IDs that are sequential only for this node and bucket.
static unitTestTearDown()
Cleanup resources when tearing down after a unit test.
static newUUIDv4($flags=0)
Return an RFC4122 compliant v4 UUID.
static newSequentialPerNodeID($bucket, $bits=48, $flags=0)
Return an ID that is sequential only for this node and bucket.
deleteCacheFiles()
Delete all cache files that have been created.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
static getLocalServerInstance($fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
static generateHex($chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format...
timeWaitUntil(array $time)
Wait till the current timestamp reaches $time and return the current timestamp.
static UIDGenerator $instance
getTimestampedID128(array $info)
getTimestampedID88(array $info)
static newRawUUIDv1()
Return an RFC4122 compliant v1 UUID.
static newUUIDv1()
Return an RFC4122 compliant v1 UUID.