Пример #1
1
 /**
  * Finds next strong pseudoprime number, following after $num
  *
  * @param gmp resource $num
  * @return gmp resource
  * @access public
  */
 function nextPrime($num)
 {
     if (!gmp_cmp(gmp_mod($num, 2), 0)) {
         $num = gmp_sub($num, 1);
     }
     do {
         $num = gmp_add($num, 2);
     } while (!gmp_prob_prime($num));
     return $num;
 }
 public function testMod()
 {
     $this->assertEquals(gmp_strval(gmp_mod($this->a, $this->a)), $this->math->mod($this->a, $this->a));
     $this->assertEquals(gmp_strval(gmp_mod($this->b, $this->b)), $this->math->mod($this->b, $this->b));
     $this->assertEquals(gmp_strval(gmp_mod($this->c, $this->c)), $this->math->mod($this->c, $this->c));
     $this->assertEquals(0, $this->math->mod(1, 1));
 }
Пример #3
0
Файл: mlpnn.php Проект: 0-php/AI
function main()
{
    global $numEpochs;
    global $numPatterns;
    global $patNum;
    global $RMSerror;
    // initiate the weights
    initWeights();
    // load in the data
    initData();
    // train the network
    for ($j = 0; $j <= $numEpochs; $j++) {
        for ($i = 0; $i < $numPatterns; $i++) {
            //select a pattern at random
            //srand();
            $patNum = rand(0, $numPatterns - 1);
            //calculate the current network output
            //and error for this pattern
            calcNet();
            //change network weights
            WeightChangesHO();
            WeightChangesIH();
        }
        //display the overall network error
        //after each epoch
        calcOverallError();
        if (gmp_mod($j, 50) == 0) {
            print "epoch = " . $j . "  RMS Error = " . $RMSerror . "</br>";
        }
    }
    //training has finished
    //display the results
    displayResults();
}
Пример #4
0
 /**
  * @param int $cycle weather cycle we in (hours/3)
  * @param CWeatherFunction $wf cycle season weather function (weights)
  *
  * @return WeatherValue
  */
 public function getCycleWeatherValue($cycle, CWeatherFunction $wf)
 {
     $numWS = $wf->getNumWeatherSetups();
     if (!$numWS) {
         return 0;
     }
     /* old weather
             $noiseValue = $this->rawWeatherProvider($cycle);
     
             // sum all weights, usually adds up to 100
             $value = (int)($noiseValue * $wf->getWeatherSetupsTotalWeight());
              */
     $noiseValue = \Nel\Misc\wang_hash64($cycle);
     // noise is 64bit unsigned, so use GMP library
     // value = wangHash64(cycle) % wf.getWeatherSetupsTotalWeight();
     $value = gmp_strval(gmp_mod($noiseValue, $wf->getWeatherSetupsTotalWeight()));
     $currWeight = 0;
     for ($k = 0; $k < $numWS; $k++) {
         $weight = $wf->getWeatherSetupWeight($k);
         if ($value >= $currWeight && $value < $currWeight + $weight) {
             $scaledWeather = ($value - $currWeight) / $weight + $k;
             $weather = $scaledWeather / $numWS;
             return new WeatherValue($k, $weather, $wf);
         }
         $currWeight += $weight;
     }
     return new WeatherValue($numWS, 1, $wf);
 }
function GetAuthID($i64friendID)
{
    $tmpfriendID = $i64friendID;
    $iServer = "1";
    if (extension_loaded('bcmath') == 1) {
        //decode communityid with bcmath
        if (bcmod($i64friendID, "2") == "0") {
            $iServer = "0";
        }
        $tmpfriendID = bcsub($tmpfriendID, $iServer);
        if (bccomp("76561197960265728", $tmpfriendID) == -1) {
            $tmpfriendID = bcsub($tmpfriendID, "76561197960265728");
        }
        $tmpfriendID = bcdiv($tmpfriendID, "2");
        return "STEAM_0:" . $iServer . ":" . $tmpfriendID;
    } else {
        if (extension_loaded('gmp') == 1) {
            //decode communityid with gmp
            if (gmp_mod($i64friendID, "2") == "0") {
                $iServer = "0";
            }
            $tmpfriendID = gmp_sub($tmpfriendID, $iServer);
            if (gmp_cmp("76561197960265728", $tmpfriendID) == -1) {
                $tmpfriendID = gmp_sub($tmpfriendID, "76561197960265728");
            }
            $tmpfriendID = gmp_div($tmpfriendID, "2");
            return "STEAM_0:" . $iServer . ":" . gmp_strval($tmpfriendID);
        }
    }
    return false;
}
Пример #6
0
 /**
  * Pack a long.
  *
  * If it is a 32bit PHP we suppose that this log is treated by bcmath
  * TODO 32bit
  *
  * @param int|string $value
  *
  * @return string the packed long
  */
 public static function packLong($value)
 {
     if (PHP_INT_SIZE > 4) {
         $value = (int) $value;
         $binaryString = chr($value >> 56 & 0xff) . chr($value >> 48 & 0xff) . chr($value >> 40 & 0xff) . chr($value >> 32 & 0xff) . chr($value >> 24 & 0xff) . chr($value >> 16 & 0xff) . chr($value >> 8 & 0xff) . chr($value & 0xff);
     } else {
         /*
          * To get the two's complement of a binary number,
          * the bits are inverted, or "flipped",
          * by using the bitwise NOT operation;
          * the value of 1 is then added to the resulting value
          */
         $bitString = '';
         $isNegative = $value[0] == '-';
         if (function_exists("bcmod")) {
             //add 1 for the two's complement
             if ($isNegative) {
                 $value = bcadd($value, '1');
             }
             while ($value !== '0') {
                 $bitString = (string) abs((int) bcmod($value, '2')) . $bitString;
                 $value = bcdiv($value, '2');
             }
         } elseif (function_exists("gmp_mod")) {
             //add 1 for the two's complement
             if ($isNegative) {
                 $value = gmp_strval(gmp_add($value, '1'));
             }
             while ($value !== '0') {
                 $bitString = gmp_strval(gmp_abs(gmp_mod($value, '2'))) . $bitString;
                 $value = gmp_strval(gmp_div_q($value, '2'));
             }
         } else {
             while ($value != 0) {
                 list($value, $remainder) = self::str2bin((string) $value);
                 $bitString = $remainder . $bitString;
             }
         }
         //Now do the logical not for the two's complement last phase
         if ($isNegative) {
             $len = strlen($bitString);
             for ($x = 0; $x < $len; $x++) {
                 $bitString[$x] = $bitString[$x] == '1' ? '0' : '1';
             }
         }
         //pad to have 64 bit
         if ($bitString != '' && $isNegative) {
             $bitString = str_pad($bitString, 64, '1', STR_PAD_LEFT);
         } else {
             $bitString = str_pad($bitString, 64, '0', STR_PAD_LEFT);
         }
         $hi = substr($bitString, 0, 32);
         $lo = substr($bitString, 32, 32);
         $hiBin = pack('H*', str_pad(base_convert($hi, 2, 16), 8, 0, STR_PAD_LEFT));
         $loBin = pack('H*', str_pad(base_convert($lo, 2, 16), 8, 0, STR_PAD_LEFT));
         $binaryString = $hiBin . $loBin;
     }
     return $binaryString;
 }
Пример #7
0
 function irand($min, $max = null)
 {
     if (is_null($max)) {
         $max = $min;
         $min = 0;
     }
     $this->next();
     return gmp_intval(gmp_mod(gmp_init('0x' . $this->context), gmp_init($max - $min))) + $min;
 }
Пример #8
0
 public function generate($serial)
 {
     $mul = gmp_mul(strval($this->mulFactor), strval($serial));
     $add = gmp_add($mul, $this->diffFactor);
     $mod = gmp_mod($add, strval($this->amount));
     $num = gmp_strval($mod);
     //        $num = ($this->mulFactor * $serial + $this->diffFactor) % $this->amount;
     return str_pad($num, $this->length, $this->padding, STR_PAD_LEFT);
 }
Пример #9
0
 public static function inc($X, $n)
 {
     $s = gmp_strval($X, 2);
     $s1 = (string) substr($s, 0, -$n);
     $s = gmp_add(gmp_init(substr($s, -$n), 2), 1);
     $s = gmp_mod($s, gmp_pow(2, $n));
     $s2 = str_pad(gmp_strval($s, 2), $n, '0', STR_PAD_LEFT);
     return gmp_init($s1 . $s2, 2);
 }
Пример #10
0
 public function testmod()
 {
     $a = 1234;
     $b = '1234123412341234123412341234123412412341234213412421341342342';
     $c = '0x1234123412341234123412341234123412412341234213412421341342342';
     $math = new GmpEngine();
     $this->assertEquals(gmp_strval(gmp_mod($a, $a)), $math->mod($a, $a));
     $this->assertEquals(gmp_strval(gmp_mod($b, $b)), $math->mod($b, $b));
     $this->assertEquals(gmp_strval(gmp_mod($c, $c)), $math->mod($c, $c));
     $this->assertEquals(0, $math->mod(1, 1));
 }
Пример #11
0
 public function edwards($P, $Q)
 {
     $x1 = $P[0];
     $y1 = $P[1];
     $x2 = $Q[0];
     $y2 = $Q[1];
     $t = gmp_mul($this->params['d'], gmp_mul(gmp_mul($x1, $x2), gmp_mul($y1, $y2)));
     $x3 = gmp_mul(gmp_add(gmp_mul($x1, $y2), gmp_mul($x2, $y1)), $this->inv(gmp_add(1, $t)));
     $y3 = gmp_mul(gmp_add(gmp_mul($y1, $y2), gmp_mul($x1, $x2)), $this->inv(gmp_sub(1, $t)));
     return array(gmp_mod($x3, $this->params['q']), gmp_mod($y3, $this->params['q']));
 }
Пример #12
0
 private static function nextSeed()
 {
     // GMP available
     if (sjMathRandom::$m_hasGMP) {
         sjMathRandom::$m_seed = (int) gmp_mod(gmp_add(gmp_mul(sjMathRandom::$m_seed, sjMathRandom::PARAM_A), sjMathRandom::PARAM_B), sjMathRandom::PARAM_C);
     } else {
         if (sjMathRandom::$m_hasBCMath) {
             sjMathRandom::$m_seed = (int) bcmod(bcadd(bcmul(sjMathRandom::$m_seed, sjMathRandom::PARAM_A), sjMathRandom::PARAM_B), sjMathRandom::PARAM_C);
         } else {
             die('sjMathRandom: no suported math library available');
         }
     }
 }
Пример #13
0
function is_pentagonal($num)
{
    // we do a sqr with remainder
    list($sr, $rem) = gmp_sqrtrem(gmp_add(gmp_mul(24, $num), 1));
    // if it's not an exact root don't bother with the rest
    if (gmp_strval($rem) == '0') {
        $d = gmp_add($sr, 1);
        $m = gmp_strval(gmp_mod($d, 6));
        if ($m == '0') {
            return true;
        }
    }
    return false;
}
Пример #14
0
/**
 * Назначение: Основные пользовательские функции
 */
function number62_encode($number)
{
    if (preg_match('#^[0-9]+$#iu', $number) == 0) {
        return "";
    }
    $out = "";
    $string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    do {
        $key = gmp_mod($number, 62);
        $out = $string[$key] . $out;
        $number = gmp_strval(gmp_div_q($number, 62, GMP_ROUND_ZERO));
    } while (gmp_cmp($number, 0) > 0);
    return $out;
}
Пример #15
0
 protected function getEncodedValue()
 {
     $numericValue = gmp_init($this->value, 10);
     $contentLength = $this->getContentLength();
     if (gmp_sign($numericValue) < 0) {
         $numericValue = gmp_add($numericValue, gmp_sub(gmp_pow(2, 8 * $contentLength), 1));
         $numericValue = gmp_add($numericValue, 1);
     }
     $result = '';
     for ($shiftLength = ($contentLength - 1) * 8; $shiftLength >= 0; $shiftLength -= 8) {
         $octet = gmp_strval(gmp_mod($this->rightShift($numericValue, $shiftLength), 256));
         $result .= chr($octet);
     }
     return $result;
 }
Пример #16
0
function Zend_OpenId_bigNumToBin2($bn)
{
    if (extension_loaded('gmp')) {
        /*The GMP conversion code in this function was liberally copied 
        	 and adapted from  JanRain's Auth_OpenId_MathLibrary::longToBinary*/
        $cmp = gmp_cmp($bn, 0);
        if ($cmp < 0) {
            throw new Zend_OpenId_Exception('Big integer arithmetic error', Zend_OpenId_Exception::ERROR_LONG_MATH);
        }
        if ($cmp == 0) {
            return "";
        }
        $bytes = array();
        while (gmp_cmp($bn, 0) > 0) {
            array_unshift($bytes, gmp_mod($bn, 256));
            $bn = gmp_div($bn, pow(2, 8));
        }
        if ($bytes && $bytes[0] > 127) {
            array_unshift($bytes, 0);
        }
        $string = '';
        foreach ($bytes as $byte) {
            $string .= pack('C', $byte);
        }
        return $string;
    } else {
        if (extension_loaded('bcmath')) {
            $cmp = bccomp($bn, 0);
            if ($cmp == 0) {
                return chr(0);
            } else {
                if ($cmp < 0) {
                    throw new Zend_OpenId_Exception('Big integer arithmetic error', Zend_OpenId_Exception::ERROR_LONG_MATH);
                }
            }
            $bin = "";
            while (bccomp($bn, 0) > 0) {
                $bin = chr(bcmod($bn, 256)) . $bin;
                $bn = bcdiv($bn, 256);
            }
            return $bin;
        }
    }
    throw new Zend_OpenId_Exception('The system doesn\'t have proper big integer extension', Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH);
}
function recoverPubKey($r, $s, $e, $recoveryFlags, $G)
{
    $isYEven = ($recoveryFlags & 1) != 0;
    $isSecondKey = ($recoveryFlags & 2) != 0;
    $curve = $G->getCurve();
    $signature = new Signature($r, $s);
    // Precalculate (p + 1) / 4 where p is the field order
    static $p_over_four;
    // XXX just assuming only one curve/prime will be used
    if (!$p_over_four) {
        $p_over_four = gmp_div(gmp_add($curve->getPrime(), 1), 4);
    }
    // 1.1 Compute x
    if (!$isSecondKey) {
        $x = $r;
    } else {
        $x = gmp_add($r, $G->getOrder());
    }
    // 1.3 Convert x to point
    $alpha = gmp_mod(gmp_add(gmp_add(gmp_pow($x, 3), gmp_mul($curve->getA(), $x)), $curve->getB()), $curve->getPrime());
    $beta = NumberTheory::modular_exp($alpha, $p_over_four, $curve->getPrime());
    // If beta is even, but y isn't or vice versa, then convert it,
    // otherwise we're done and y == beta.
    if (isBignumEven($beta) == $isYEven) {
        $y = gmp_sub($curve->getPrime(), $beta);
    } else {
        $y = $beta;
    }
    // 1.4 Check that nR is at infinity (implicitly done in construtor)
    $R = new Point($curve, $x, $y, $G->getOrder());
    $point_negate = function ($p) {
        return new Point($p->curve, $p->x, gmp_neg($p->y), $p->order);
    };
    // 1.6.1 Compute a candidate public key Q = r^-1 (sR - eG)
    $rInv = NumberTheory::inverse_mod($r, $G->getOrder());
    $eGNeg = $point_negate(Point::mul($e, $G));
    $Q = Point::mul($rInv, Point::add(Point::mul($s, $R), $eGNeg));
    // 1.6.2 Test Q as a public key
    $Qk = new PublicKey($G, $Q);
    if ($Qk->verifies($e, $signature)) {
        return $Qk;
    }
    return false;
}
Пример #18
0
function deskripsi($chiper, $d, $n)
{
    $time_start = microtime(true);
    //Pesan Enkripsi dipecah menjadi array dengan batasan "+"
    $hasildekrip = '';
    $hasil = '';
    $dekrip = explode(" ", $chiper);
    foreach ($dekrip as $nilai) {
        //Rumus Deskripsi ---> PlainTeks = <enkripsi>^<d>mod<n>
        $gm1 = gmp_pow($nilai, gmp_strval($d));
        $gm2 = gmp_mod($gm1, $n);
        $gm3 = gmp_strval($gm2);
        $hasildekrip .= chr($gm3);
    }
    $time_end = microtime(true);
    // Waktu Eksekusi
    $time = $time_end - $time_start;
    $hasil = array($time, $hasildekrip);
    return $hasil;
}
Пример #19
0
function printmsg($message, $pwd)
{
    $mod = gmp_init('fffffffdffffffffffffffffffffffff', 16);
    $mul = gmp_init('b562a81099dff41937c5ae51ba7427a4', 16);
    $key = str_repeat(sprintf('%04x', crc32($pwd) & 0xffff), 8);
    $key = gmp_init($key, 16);
    $pwd = gmp_init($pwd, 16);
    for ($i = 0; $i < strlen($message); $i += 32) {
        $msg = substr($message, $i, 32);
        $msg = gmp_init($msg, 16);
        $msg = gmp_add($msg, $pwd);
        $msg = gmp_mul($msg, $mul);
        $msg = gmp_add($msg, $key);
        $msg = gmp_mod($msg, $mod);
        $msg = gmp_strval($msg, 16);
        $msg = str_pad($msg, 32, '0', STR_PAD_LEFT);
        $msg = pack('H*', $msg);
        echo $msg;
    }
}
Пример #20
0
 /**
  * verify using gmp extendsions
  */
 function _verifyByGmp($message, $sig, $sigKeys)
 {
     $p = $sigKeys['p'];
     $q = $sigKeys['q'];
     $g = $sigKeys['g'];
     $pubKey = $sigKeys['pub_key'];
     list($r_sig, $s_sig) = explode(":", $sig);
     $r_sig = base64_decode($r_sig);
     $s_sig = base64_decode($s_sig);
     $p = gmp_init($p);
     $q = gmp_init($q);
     $g = gmp_init($g);
     $pubKey = gmp_init($pubKey);
     $s1 = Security_DSA::_bindecGmp($r_sig);
     $s2 = Security_DSA::_bindecGmp($s_sig);
     $w = gmp_invert($s2, $q);
     $hash_m = gmp_init('0x' . sha1($message));
     $u1 = gmp_mod(gmp_mul($hash_m, $w), $q);
     $u2 = gmp_mod(gmp_mul($s1, $w), $q);
     $v = gmp_mod(gmp_mod(gmp_mul(gmp_powm($g, $u1, $p), gmp_powm($pubKey, $u2, $p)), $p), $q);
     return gmp_cmp($v, $s1) == 0;
 }
Пример #21
0
 public static function double(Point $p1)
 {
     $p = $p1->curve->prime;
     $a = $p1->curve->a;
     $inverse = gmp_invert(gmp_mul(2, $p1->y), $p);
     $three_x2 = gmp_mul(3, gmp_pow($p1->x, 2));
     $l = gmp_mod(gmp_mul(gmp_add($three_x2, $a), $inverse), $p);
     $x3 = gmp_mod(gmp_sub(gmp_pow($l, 2), gmp_mul(2, $p1->x)), $p);
     $y3 = gmp_mod(gmp_sub(gmp_mul($l, gmp_sub($p1->x, $x3)), $p1->y), $p);
     if (gmp_cmp(0, $y3) > 0) {
         $y3 = gmp_add($p, $y3);
     }
     return new Point($p1->curve, $x3, $y3);
 }
Пример #22
0
 /**
  * @param string $left_operand
  * @param string $right_operand
  * @return string
  */
 public function modulus($left_operand, $modulus)
 {
     $result = gmp_mod($left_operand, $modulus);
     return gmp_strval($result);
 }
Пример #23
0
<?php

var_dump(gmp_mod());
var_dump(gmp_mod(""));
var_dump(gmp_mod("", ""));
var_dump(gmp_mod(0, 1));
var_dump(gmp_mod(0, -1));
var_dump(gmp_mod(-1, 0));
var_dump(gmp_mod(array(), array()));
$a = gmp_init("-100000000");
$b = gmp_init("353467");
var_dump(gmp_mod($a, $b));
echo "Done\n";
Пример #24
0
 /**
  * Return the modulo of two numbers, utilize Math extensions
  *
  * @param mixed a First operand
  * @param mixed b Second operand
  * @return mixed
  * @access private
  */
 function _mod($a, $b)
 {
     switch (MATH_BASEX_MATHEXTENSION) {
         case 'bcmath':
             return bcmod($a, $b);
         case 'gmp':
             return gmp_strval(gmp_mod($a, $b));
         case 'none':
             return $a % $b;
     }
 }
Пример #25
0
 function mod($base, $modulus)
 {
     return gmp_mod($base, $modulus);
 }
Пример #26
0
function get_subnet_html($subnet_ip)
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images;
    $html = $js = '';
    $font_color = '#FFFFFF';
    $style['content_box'] = <<<EOL
        margin: 10px 20px;
        padding: 2px 4px;
        background-color: #FFFFFF;
        vertical-align: top;
EOL;
    $style['label_box'] = <<<EOL
        font-weight: bold;
        padding: 2px 4px;
        border: solid 1px {$color['border']};
        background-color: {$color['window_content_bg']};
EOL;
    // Load the subnet record
    list($status, $rows, $subnet) = ona_find_subnet($subnet_ip);
    // If we didn't get one, tell them to add a record here
    if ($rows == 0 or $status) {
        // Calculate what the end of this block is so we can reccomend the max subnet size
        // GD: add IPv6 functionnality by imposing GMP use when not ipv4 subnet
        list($status, $rows, $subnets) = db_get_records($onadb, "subnets", "ip_addr > " . ip_mangle($subnet_ip, 'numeric'), "ip_addr", 1);
        if (!is_ipv4($subnet_ip)) {
            if ($rows >= 1) {
                $subnet_ip_end = gmp_sub(gmp_init($subnets[0]['ip_addr']), 1);
                $size = gmp_add(gmp_sub($subnet_ip_end, $subnet_ip), 1);
                if (gmp_mod($size, 2) == 1) {
                    gmp_sub($size, 1);
                }
                // GD: very bad way to get the mask ... but gmp_log() does not exist !
                for ($mask = 65; $mask > 48; $mask--) {
                    if (gmp_cmp($size, gmp_pow("2", $mask)) > 0) {
                        $mask++;
                        break;
                    }
                }
                $subnet['ip_addr'] = ip_mangle(gmp_strval($subnet_ip), 'dotted');
                $subnet['ip_addr_end'] = ip_mangle(gmp_strval($subnet_ip_end), 'dotted');
                $str_subnet_ip = gmp_strval($subnet_ip);
                $size = gmp_strval($size);
            } else {
                $subnet_ip_end = -1;
                $size = 0;
            }
        } else {
            if ($rows >= 1) {
                $subnet_ip_end = $subnets[0]['ip_addr'] - 1;
                $size = $subnet_ip_end - $subnet_ip + 1;
                if ($size % 2 == 1) {
                    $size--;
                }
                $mask = ceil(32 - log($size) / log(2));
                $subnet['ip_addr'] = ip_mangle($subnet_ip, 'dotted');
                $subnet['ip_addr_end'] = ip_mangle($subnet_ip_end, 'dotted');
                $str_subnet_ip = $subnet_ip;
            } else {
                $subnet_ip_end = -1;
                $size = 0;
            }
        }
        $html .= <<<EOL
        <!-- NO SUBNET -->
        <table cellspacing="0" border="0" cellpadding="0">

            <!-- LABEL -->
            <tr><td width=100% colspan="2" nowrap="true" style="{$style['label_box']}">
                <a title="Add a new subnet here"
                   class="act"
                   onClick="xajax_window_submit('edit_subnet', 'ip_addr=>{$str_subnet_ip}', 'editor');"
                >Add a subnet here</a>
            </td></tr>

            <tr>
                <td align="right" nowrap="true" style="color: {$font_color};"><b>IP Range</b>&nbsp;</td>
                <td class="padding" nowrap="true" align="left" style="color: {$font_color};">{$subnet['ip_addr']}&nbsp;-&nbsp;{$subnet['ip_addr_end']}&nbsp({$size} addresses)</td>
            </tr>

EOL;
        $largest_subnet = array(0, 0, 0);
        // -- IPv4
        if (is_ipv4($subnet_ip)) {
            $ip = $subnet_ip;
            while ($ip < $subnet_ip_end) {
                // find the largest mask for the specified ip
                $myip = ip_mangle($ip, 'dotted');
                $mymask = $mask;
                while ($mymask <= 30) {
                    $ip1 = ip_mangle($ip, 'binary');
                    $ip2 = str_pad(substr($ip1, 0, $mymask), 32, '0');
                    $mysize = pow(2, 32 - $mymask);
                    $myhosts = $mysize - 2;
                    $ip1 = ip_mangle($ip1, 'dotted');
                    $ip2 = ip_mangle($ip2, 'dotted');
                    if ($ip1 == $ip2 and $ip + $mysize - 1 <= $subnet_ip_end) {
                        break;
                    }
                    $mymask++;
                }
                if ($mymask == 31) {
                    break;
                }
                if ($mysize > $largest_subnet[2]) {
                    $largest_subnet = array(ip_mangle($ip, 'dotted'), $mymask, $mysize);
                }
                $html .= <<<EOL
                <!--
                <tr>
                    <td align="right" nowrap="true" style="color: {$font_color};">&nbsp;</td>
                    <td class="padding" align="left" style="color: {$font_color};">{$myip} /{$mymask}&nbsp;({$myhosts} hosts)</td>
                </tr>
                -->
EOL;
                // Increment $ip
                $ip += $mysize;
            }
            // remove 2 for gateway and broadcast
            $largest_subnet[2] = $largest_subnet[2] - 2;
        } else {
            $ip = gmp_init($subnet_ip);
            // GD: trying to avoid falling into time/memory-trap
            // Won't enter in the loop if difference between IP and next subnet IP is too big
            // (more than 5 x /64)
            if (gmp_cmp(gmp_sub($subnet_ip_end, $ip), gmp_mul("18446744073709551616", "5")) > 0) {
                $html .= <<<EOL
\t<tr>
\t<td align="right" nowrap="true" style="color: {$font_color};">&nbsp;</td>
\t<td align="right" nowrap="true" style="color: {$font_color};">Next Subnet too far away</td>
\t<tr>
EOL;
                return array($html, $js);
            }
            while (gmp_cmp($ip, $subnet_ip_end) < 0) {
                // find the largest mask for the specified ip
                $myip = ip_mangle(gmp_strval($ip), 'dotted');
                $mymask = $mask;
                while ($mymask <= 64) {
                    $ip1 = ip_mangle(gmp_strval($ip), 'bin128');
                    $ip2 = str_pad(substr($ip1, 0, $mymask), 128, '0');
                    $mysize = gmp_pow("2", 128 - $mymask);
                    $myhosts = gmp_strval(gmp_sub($mysize, 2));
                    $ip1 = ip_mangle($ip1, 'dotted');
                    $ip2 = ip_mangle($ip2, 'dotted');
                    if (strcmp($ip1, $ip2) == 0 and gmp_cmp(gmp_sub(gmp_add($ip, $mysize), 1), $subnet_ip_end) <= 0) {
                        break;
                    }
                    $mymask++;
                }
                if ($mymask == 90) {
                    break;
                }
                if (gmp_cmp($mysize, $largest_subnet[2]) > 0) {
                    $largest_subnet = array(ip_mangle(gmp_strval($ip), 'dotted'), $mymask, $mysize);
                }
                $html .= <<<EOL
                <!--
                <tr>
                    <td align="right" nowrap="true" style="color: {$font_color};">&nbsp;</td>
                    <td class="padding" align="left" style="color: {$font_color};">{$mask} {$myip} /{$mymask}&nbsp;({$myhosts} hosts)td>
                </tr>
                -->
EOL;
                // Increment $ip
                $ip = gmp_add($ip, $mysize);
            }
            // DON'T remove 2 for gateway and broadcast
            $largest_subnet[2] = gmp_strval($largest_subnet[2]);
        }
        $html .= <<<EOL

            <tr>
                <td align="right" nowrap="true" style="color: {$font_color};"><b>Largest block</b>&nbsp;</td>
                <td class="padding" nowrap="true" align="left" style="color: {$font_color};">{$largest_subnet[0]} /{$largest_subnet[1]}&nbsp;({$largest_subnet[2]} usable hosts)</td>
            </tr>

        </table>
EOL;
        return array($html, $js);
    }
    // --
    // -- FOUND SUBNET IN DB
    // --
    // Convert IP and Netmask to a presentable format
    $subnet['ip_addr'] = ip_mangle($subnet['ip_addr'], 'dotted');
    $subnet['ip_mask'] = ip_mangle($subnet['ip_mask'], 'dotted');
    $subnet['ip_mask_cidr'] = ip_mangle($subnet['ip_mask'], 'cidr');
    list($status, $rows, $type) = ona_get_subnet_type_record(array('id' => $subnet['subnet_type_id']));
    $subnet['type'] = $type['display_name'];
    // Calculate the percentage of the subnet that's used (total size - allocated hosts - dhcp pool size)
    $usage_html = get_subnet_usage_html($subnet['id']);
    foreach (array_keys((array) $subnet) as $key) {
        $subnet[$key] = htmlentities($subnet[$key], ENT_QUOTES, $conf['php_charset']);
    }
    foreach (array_keys((array) $location) as $key) {
        $location[$key] = htmlentities($location[$key], ENT_QUOTES, $conf['php_charset']);
    }
    $html .= <<<EOL

        <!-- SUBNET INFORMATION -->
        <table cellspacing="0" border="0" cellpadding="0">

            <!-- LABEL -->
            <tr><td width=100% colspan="2" nowrap="true" style="{$style['label_box']}">
                <a title="View subnet. ID: {$subnet['id']}"
                   class="nav"
                   onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$subnet['id']}\\', \\'display\\')');"
                >{$subnet['name']}</a>
            </td></tr>

            <tr>
                <td align="right" nowrap="true" style="color: {$font_color};"><b>IP Address</b>&nbsp;</td>
                <td class="padding" align="left" style="color: {$font_color};">{$subnet['ip_addr']}&nbsp;/{$subnet['ip_mask_cidr']}</td>
            </tr>

            <tr>
                <td align="right" nowrap="true" style="color: {$font_color};"><b>Usage</b>&nbsp;</td>
                <td class="padding" align="left" style="color: {$font_color};">{$usage_html}</td>
            </tr>

EOL;
    if ($subnet['type']) {
        $html .= <<<EOL
            <tr>
                <td align="right" nowrap="true" style="color: {$font_color};"><b>Type</b>&nbsp;</td>
                <td class="padding" align="left" style="color: {$font_color};">{$subnet['type']}&nbsp;</td>
            </tr>
EOL;
    }
    $html .= <<<EOL
        </table>
EOL;
    return array($html, $js);
}
 public static function gmp_dec2base($dec, $base, $digits = FALSE)
 {
     if (extension_loaded('gmp')) {
         if ($base < 2 or $base > 256) {
             die("Invalid Base: " . $base);
         }
         $value = "";
         if (!$digits) {
             $digits = self::digits($base);
         }
         $dec = gmp_init($dec);
         $base = gmp_init($base);
         while (gmp_cmp($dec, gmp_sub($base, '1')) > 0) {
             $rest = gmp_mod($dec, $base);
             $dec = gmp_div($dec, $base);
             $value = $digits[gmp_intval($rest)] . $value;
         }
         $value = $digits[gmp_intval($dec)] . $value;
         return (string) $value;
     } else {
         throw new ErrorException("Please install GMP");
     }
 }
Пример #28
0
 /**
  * @param array $time Result of UIDGenerator::millitime()
  * @param integer $delta Number of intervals to add on to the timestamp
  * @return string 60 bits of "100ns intervals since 15 October 1582" (rolls over in 3400)
  * @throws RuntimeException
  */
 protected function intervalsSinceGregorianBinary(array $time, $delta = 0)
 {
     list($sec, $msec) = $time;
     $offset = '122192928000000000';
     if (PHP_INT_SIZE >= 8) {
         // 64 bit integers
         $ts = (1000 * $sec + $msec) * 10000 + (int) $offset + $delta;
         $id_bin = str_pad(decbin($ts % pow(2, 60)), 60, '0', STR_PAD_LEFT);
     } elseif (extension_loaded('gmp')) {
         $ts = gmp_add(gmp_mul((string) $sec, '1000'), (string) $msec);
         // ms
         $ts = gmp_add(gmp_mul($ts, '10000'), $offset);
         // 100ns intervals
         $ts = gmp_add($ts, (string) $delta);
         $ts = gmp_mod($ts, gmp_pow('2', '60'));
         // wrap around
         $id_bin = str_pad(gmp_strval($ts, 2), 60, '0', STR_PAD_LEFT);
     } elseif (extension_loaded('bcmath')) {
         $ts = bcadd(bcmul($sec, 1000), $msec);
         // ms
         $ts = bcadd(bcmul($ts, 10000), $offset);
         // 100ns intervals
         $ts = bcadd($ts, $delta);
         $ts = bcmod($ts, bcpow(2, 60));
         // wrap around
         $id_bin = Wikimedia\base_convert($ts, 10, 2, 60);
     } else {
         throw new RuntimeException('bcmath or gmp extension required for 32 bit machines.');
     }
     return $id_bin;
 }
Пример #29
0
 /**
  * get modular
  *
  * calculates the remainder
  *
  * @param Math_BigInteger
  * @return Math_BigInteger
  * @see _trim()
  * @access private
  */
 function mod($modul)
 {
     $result = new Math_BigInteger();
     switch (MATH_BIGINTEGER_MODE) {
         case MATH_BIGINTEGER_MODE_GMP:
             $result->value = gmp_mod($this->value, $modul->value);
             return $result;
         case MATH_BIGINTEGER_MODE_BCMATH:
             $result->value = bcmod($this->value, $modul->value);
             return $result;
     }
     throw new InvalidArgumentException('Math_BigInteger only works with either GMP or BCMATH extension. ');
     return false;
 }
 /**
  * Calculate the modulus of $i1 and $i2: $i1 % $i2
  *
  * @param object Math_Integer $int1
  * @param object Math_Integer $int2
  * @return object Math_Integer on success, PEAR_Error otherwise
  * @access public
  */
 function &mod(&$int1, &$int2)
 {
     /*{{{*/
     if (PEAR::isError($err = Math_IntegerOp::_validInts($int1, $int2))) {
         return $err;
     }
     switch (MATH_INTLIB) {
         /*{{{*/
         case 'gmp':
             $tmp = gmp_strval(gmp_mod($int1->getValue(), $int2->getValue()));
             break;
         case 'bcmath':
             $tmp = bcmod($int1->getValue(), $int2->getValue());
             break;
         case 'std':
             $tmp = $int1->getValue() % $int2->getValue();
             break;
     }
     /*}}}*/
     return new Math_Integer($tmp);
 }