<?php

class uuid_v4 {

/*  Show:
        RFC rfc4122, July 2005
        Section 4.4.: 'Algorithms for Creating a UUID from Truly Random or Pseudo-Random Numbers'
*/
    private $uuid_v4 = false;

    function __construct ( $gen = true ) {
        if ( $gen ) {
            $this -> gen_uuid_v4();
        }
    }

    public function gen_uuid_v4() {
        $a = array();
        $a[] = mt_rand( 0, 0xffff ) + ( mt_rand( 0, 0xffff ) << 16 );
        $a[] = mt_rand( 0, 0xffff );
        $a[] = (4 << 12) | ( mt_rand( 0, 0x1000 ) );
        $a[] = ( 1 << 7 ) | ( mt_rand( 0, 0xf0 ) );
        $a[] = mt_rand( 0, 0xff );

        for ( $i = 0; $i < 6; $i++ ) {
            $a[] = mt_rand( 0, 0xf8 );
        }

        $this -> uuid_v4 = sprintf(
            '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x', $a[0], $a[1], $a[2], $a[3], $a[4], $a[5], $a[6], $a[7], $a[8], $a[9],$a[10]
        );
    }

    public function get_uuid() {
        if ( false == $this -> uuid_v4 ) {
            $this -> uuid_v4 = $this -> gen_uuid_v4();
        }
        return $this -> uuid_v4;
    }

    public function get_new_uuid() {
        $this -> gen_uuid_v4();
        return $this -> uuid_v4;
    }
    
    public function test_uuid( $uuid ) {
    
        $subject  = strtolower($uuid);
        $hexchars = '[0-9a-f]';
        $hexcharsLimited = '[89abcdef]';
        $pattern  = '/^' . $hexchars . '{8}' 
                  . '-'  . $hexchars . '{4}'
                  . '-'  . $hexchars . '{4}'
                  . '-'  . $hexcharsLimited . $hexchars . '{3}'
                  . '-'  . $hexchars . '{12}' . '$/';
        if ( 1 == preg_match ( $pattern , $subject ) ) {
            return true;
        } else {
            return false;
        }
    }

}


##################### Test/Usage ###############################
/* 
$oUuid = new uuid_v4;
for ($i = 0; $i<10; $i++ ) {
    $uuid = $oUuid -> get_new_uuid();
    $t =  'false';
    if ( $oUuid -> test_uuid( $uuid ) ) $t = 'true';
    echo $uuid . ' ( ' . $t . " )\n";
}
echo "-----------------------------\n";
$oUuid = new uuid_v4();
for ($i = 0; $i<10; $i++ ) {
    echo $oUuid -> get_uuid() . "\n";
}
#*/