Example #1
1
 /**
  * Get human readable file size, quick and dirty.
  * 
  * @todo Improve i18n support.
  *
  * @param int $bytes
  * @param string $format
  * @param int|null $decimal_places
  * @return string Human readable string with file size.
  */
 public static function humanReadableBytes($bytes, $format = "en", $decimal_places = null)
 {
     switch ($format) {
         case "sv":
             $dec_separator = ",";
             $thousands_separator = " ";
             break;
         default:
         case "en":
             $dec_separator = ".";
             $thousands_separator = ",";
             break;
     }
     $b = (int) $bytes;
     $s = array('B', 'kB', 'MB', 'GB', 'TB');
     if ($b <= 0) {
         return "0 " . $s[0];
     }
     $con = 1024;
     $e = (int) log($b, $con);
     $e = min($e, count($s) - 1);
     $v = $b / pow($con, $e);
     if ($decimal_places === null) {
         $decimal_places = max(0, 2 - (int) log($v, 10));
     }
     return number_format($v, !$e ? 0 : $decimal_places, $dec_separator, $thousands_separator) . ' ' . $s[$e];
 }
Example #2
1
 function calculateGFRResult()
 {
     $tmpArr = array();
     $tmpArr[] = date('Y-m-d H:i:s');
     //observation time
     $tmpArr[] = 'GFR (CALC)';
     //desc
     $gender = NSDR::populate($this->_patientId . "::com.clearhealth.person.displayGender");
     $crea = NSDR::populate($this->_patientId . "::com.clearhealth.labResults[populate(@description=CREA)]");
     $genderFactor = null;
     $creaValue = null;
     $personAge = null;
     $raceFactor = 1;
     switch ($gender[key($gender)]) {
         case 'M':
             $genderFactor = 1;
             break;
         case 'F':
             $genderFactor = 0.742;
             break;
     }
     if ((int) strtotime($crea['observation_time']) >= strtotime('now - 60 days') && strtolower($crea[key($crea)]['units']) == 'mg/dl') {
         $creaValue = $crea[key($crea)]['value'];
     }
     $person = new Person();
     $person->personId = $this->_patientId;
     $person->populate();
     if ($person->age > 0) {
         $personAge = $person->age;
     }
     $personStat = new PatientStatistics();
     $personStat->personId = $this->_patientId;
     $personStat->populate();
     if ($personStat->race == "AFAM") {
         $raceFactor = 1.21;
     }
     $gfrValue = "INC";
     if ($personAge > 0 && $creaValue > 0) {
         $gfrValue = "" . (int) round(pow($creaValue, -1.154) * pow($personAge, -0.203) * $genderFactor * $raceFactor * 186);
     }
     trigger_error("gfr:: " . $gfrValue, E_USER_NOTICE);
     $tmpArr[] = $gfrValue;
     // lab value
     $tmpArr[] = 'mL/min/1.73 m2';
     //units
     $tmpArr[] = '';
     //ref range
     $tmpArr[] = '';
     //abnormal
     $tmpArr[] = 'F';
     //status
     $tmpArr[] = date('Y-m-d H:i:s') . '::' . '0';
     // observationTime::(boolean)normal; 0 = abnormal, 1 = normal
     $tmpArr[] = '0';
     //sign
     //$this->_calcLabResults[uniqid()] = $tmpArr;
     $this->_calcLabResults[1] = $tmpArr;
     // temporarily set index to one(1) to be able to include in selected lab results
     return $tmpArr;
 }
Example #3
0
/**
 * Exponential expression / raise number into power
 *
 * @param string $base         base to raise
 * @param string $exp          exponent to use
 * @param mixed  $use_function pow function to use, or false for auto-detect
 *
 * @return mixed string or float
 */
function PMA_pow($base, $exp, $use_function = false)
{
    static $pow_function = null;
    if (null == $pow_function) {
        $pow_function = PMA_detect_pow();
    }
    if (!$use_function) {
        $use_function = $pow_function;
    }
    if ($exp < 0 && 'pow' != $use_function) {
        return false;
    }
    switch ($use_function) {
        case 'bcpow':
            // bcscale() needed for testing PMA_pow() with base values < 1
            bcscale(10);
            $pow = bcpow($base, $exp);
            break;
        case 'gmp_pow':
            $pow = gmp_strval(gmp_pow($base, $exp));
            break;
        case 'pow':
            $base = (double) $base;
            $exp = (int) $exp;
            $pow = pow($base, $exp);
            break;
        default:
            $pow = $use_function($base, $exp);
    }
    return $pow;
}
Example #4
0
	function stdev(Array $x) {
		$n = count($x);
		if($n == 0 || ($n - 1) == 0) return null;
		$sum = sum($x);
		$sumSq = sum_sq($x);
		return sqrt(($sumSq - (pow($sum, 2)/$n))/($n - 1));
	}
Example #5
0
function main($num)
{
    if ($num < 0) {
        $s = 1;
        $num = -$num;
    } else {
        $s = 0;
    }
    $zs = floor($num);
    $bzs = decbin($zs);
    $xs = $num - $zs;
    $res = (double) ($bzs . '.' . tenToBinary($xs, 1));
    $teme = ws($res);
    $e = decbin($teme + 127);
    if ($teme == 0) {
        $e = '0' . $e;
    }
    $temm = $res / pow(10, $teme);
    $m = end(explode(".", $temm));
    $lenm = strlen($m);
    if ($lenm < 23) {
        $m .= addzero(23 - $lenm);
    }
    return $s . ' ' . $e . ' ' . $m . ' ';
}
Example #6
0
 function postContent()
 {
     if (!($user = \Idno\Core\site()->session()->currentUser())) {
         $this->setResponse(403);
         echo 'You must be logged in to approve IndieAuth requests.';
         exit;
     }
     $me = $this->getInput('me');
     $client_id = $this->getInput('client_id');
     $redirect_uri = $this->getInput('redirect_uri');
     $state = $this->getInput('state');
     $scope = $this->getInput('scope');
     if (!empty($me) && parse_url($me, PHP_URL_HOST) == parse_url($user->getURL(), PHP_URL_HOST)) {
         $indieauth_codes = $user->indieauth_codes;
         if (empty($indieauth_codes)) {
             $indieauth_codes = array();
         }
         $code = md5(rand(0, 99999) . time() . $user->getUUID() . $client_id . $state . rand(0, 999999));
         $indieauth_codes[$code] = array('me' => $me, 'redirect_uri' => $redirect_uri, 'scope' => $scope, 'state' => $state, 'client_id' => $client_id, 'issued_at' => time(), 'nonce' => mt_rand(1000000, pow(2, 30)));
         $user->indieauth_codes = $indieauth_codes;
         $user->save();
         if (strpos($redirect_uri, '?') === false) {
             $redirect_uri .= '?';
         } else {
             $redirect_uri .= '&';
         }
         $redirect_uri .= http_build_query(array('code' => $code, 'state' => $state, 'me' => $me));
         $this->forward($redirect_uri);
     }
 }
Example #7
0
function Correlation($array1, $array2)
{
    $avg_array1 = average($array1);
    $avg_array2 = average($array2);
    #print "$avg_array1----- $avg_array2<br>";
    $sum_correlation_up = 0;
    for ($i = 0; $i < count($array1); $i++) {
        $sum_correlation_up = $sum_correlation_up + ($array1[$i] - $avg_array1) * ($array2[$i] - $avg_array2);
    }
    #print $sum_correlation_up."<br>";
    $sum_array1_sumpow2 = 0;
    for ($i = 0; $i < count($array1); $i++) {
        $sum_array1_sumpow2 = $sum_array1_sumpow2 + pow($array1[$i] - $avg_array1, 2);
    }
    $sum_array1_sumpow2_sqrt = sqrt($sum_array1_sumpow2);
    #rint $sum_array1_sumpow2_sqrt."<br>";
    $sum_array2_sumpow2 = 0;
    for ($i = 0; $i < count($array1); $i++) {
        $sum_array2_sumpow2 = $sum_array2_sumpow2 + pow($array2[$i] - $avg_array2, 2);
    }
    $sum_array2_sumpow2_sqrt = sqrt($sum_array2_sumpow2);
    #print $sum_array2_sumpow2_sqrt."<br>";
    $correlation = $sum_correlation_up / ($sum_array1_sumpow2_sqrt * $sum_array2_sumpow2_sqrt);
    return $correlation;
}
Example #8
0
 /**
  * {@inheritDoc}
  *
  * @param Convert $request
  */
 public function execute($request)
 {
     RequestNotSupportedException::assertSupports($this, $request);
     /** @var PaymentInterface $payment */
     $payment = $request->getSource();
     $model = ArrayObject::ensureArrayObject($payment->getDetails());
     //$model['DESCRIPTION'] = $payment->getDescription();
     if (false == $model['amount']) {
         $this->gateway->execute($currency = new GetCurrency($payment->getCurrencyCode()));
         if (2 < $currency->exp) {
             throw new RuntimeException('Unexpected currency exp.');
         }
         $divisor = pow(10, 2 - $currency->exp);
         $model['currency_code'] = $currency->numeric;
         $model['amount'] = abs($payment->getTotalAmount() / $divisor);
     }
     if (false == $model['order_id']) {
         $model['order_id'] = $payment->getNumber();
     }
     if (false == $model['customer_id']) {
         $model['customer_id'] = $payment->getClientId();
     }
     if (false == $model['customer_email']) {
         $model['customer_email'] = $payment->getClientEmail();
     }
     $request->setResult((array) $model);
 }
Example #9
0
function fiat_and_btc_to_price($fiat, $btc, $round = 'round')
{
    $fiat = gmp_strval($fiat);
    $btc = gmp_strval($btc);
    if (gmp_cmp($btc, "0") == 0) {
        return "";
    } else {
        if ($round == 'round') {
            $price = bcdiv($fiat, $btc, PRICE_PRECISION + 1);
            return sprintf("%." . PRICE_PRECISION . "f", $price);
        } else {
            if ($round == 'down') {
                $price = bcdiv($fiat, $btc, PRICE_PRECISION);
                // echo "rounding $fiat / $btc = " . bcdiv($fiat, $btc, 8) . " down to $price<br/>\n";
                return $price;
            } else {
                if ($round == 'up') {
                    $raw = bcdiv($fiat, $btc, 8);
                    $adjust = bcsub(bcdiv(1, pow(10, PRICE_PRECISION), 8), '0.00000001', 8);
                    $price = bcadd($raw, $adjust, PRICE_PRECISION);
                    // echo "rounding $fiat / $btc = $raw up to $price<br/>\n";
                    return $price;
                } else {
                    throw new Error("Bad Argument", "fiat_and_btc_to_price() has round = '{$round}'");
                }
            }
        }
    }
}
Example #10
0
function getGIFHeaderFilepointer(&$fd, &$ThisFileInfo)
{
    $ThisFileInfo['fileformat'] = 'gif';
    $ThisFileInfo['video']['dataformat'] = 'gif';
    $ThisFileInfo['video']['lossless'] = true;
    fseek($fd, $ThisFileInfo['avdataoffset'], SEEK_SET);
    $GIFheader = fread($fd, 13);
    $offset = 0;
    $ThisFileInfo['gif']['header']['raw']['identifier'] = substr($GIFheader, $offset, 3);
    $offset += 3;
    $ThisFileInfo['gif']['header']['raw']['version'] = substr($GIFheader, $offset, 3);
    $offset += 3;
    $ThisFileInfo['gif']['header']['raw']['width'] = LittleEndian2Int(substr($GIFheader, $offset, 2));
    $offset += 2;
    $ThisFileInfo['gif']['header']['raw']['height'] = LittleEndian2Int(substr($GIFheader, $offset, 2));
    $offset += 2;
    $ThisFileInfo['gif']['header']['raw']['flags'] = LittleEndian2Int(substr($GIFheader, $offset, 1));
    $offset += 1;
    $ThisFileInfo['gif']['header']['raw']['bg_color_index'] = LittleEndian2Int(substr($GIFheader, $offset, 1));
    $offset += 1;
    $ThisFileInfo['gif']['header']['raw']['aspect_ratio'] = LittleEndian2Int(substr($GIFheader, $offset, 1));
    $offset += 1;
    $ThisFileInfo['video']['resolution_x'] = $ThisFileInfo['gif']['header']['raw']['width'];
    $ThisFileInfo['video']['resolution_y'] = $ThisFileInfo['gif']['header']['raw']['height'];
    $ThisFileInfo['gif']['version'] = $ThisFileInfo['gif']['header']['raw']['version'];
    $ThisFileInfo['gif']['header']['flags']['global_color_table'] = (bool) ($ThisFileInfo['gif']['header']['raw']['flags'] & 0x80);
    if ($ThisFileInfo['gif']['header']['raw']['flags'] & 0x80) {
        // Number of bits per primary color available to the original image, minus 1
        $ThisFileInfo['gif']['header']['bits_per_pixel'] = 3 * ((($ThisFileInfo['gif']['header']['raw']['flags'] & 0x70) >> 4) + 1);
    } else {
        $ThisFileInfo['gif']['header']['bits_per_pixel'] = 0;
    }
    $ThisFileInfo['gif']['header']['flags']['global_color_sorted'] = (bool) ($ThisFileInfo['gif']['header']['raw']['flags'] & 0x40);
    if ($ThisFileInfo['gif']['header']['flags']['global_color_table']) {
        // the number of bytes contained in the Global Color Table. To determine that
        // actual size of the color table, raise 2 to [the value of the field + 1]
        $ThisFileInfo['gif']['header']['global_color_size'] = pow(2, ($ThisFileInfo['gif']['header']['raw']['flags'] & 0x7) + 1);
        $ThisFileInfo['video']['bits_per_sample'] = ($ThisFileInfo['gif']['header']['raw']['flags'] & 0x7) + 1;
    } else {
        $ThisFileInfo['gif']['header']['global_color_size'] = 0;
    }
    if ($ThisFileInfo['gif']['header']['raw']['aspect_ratio'] != 0) {
        // Aspect Ratio = (Pixel Aspect Ratio + 15) / 64
        $ThisFileInfo['gif']['header']['aspect_ratio'] = ($ThisFileInfo['gif']['header']['raw']['aspect_ratio'] + 15) / 64;
    }
    if ($ThisFileInfo['gif']['header']['flags']['global_color_table']) {
        $GIFcolorTable = fread($fd, 3 * $ThisFileInfo['gif']['header']['global_color_size']);
        $offset = 0;
        for ($i = 0; $i < $ThisFileInfo['gif']['header']['global_color_size']; $i++) {
            //$ThisFileInfo['gif']['global_color_table']['red'][$i]   = LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
            //$ThisFileInfo['gif']['global_color_table']['green'][$i] = LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
            //$ThisFileInfo['gif']['global_color_table']['blue'][$i]  = LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
            $red = LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
            $green = LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
            $blue = LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
            $ThisFileInfo['gif']['global_color_table'][$i] = $red << 16 | $green << 8 | $blue;
        }
    }
    return true;
}
Example #11
0
    function round_up($value, $places)
 {
 	$mult = pow(10, abs($places));
 	return $places < 0 ?
 	ceil($value / $mult) * $mult :
 	ceil($value * $mult) / $mult;
 }
Example #12
0
function hexTo32Float($strHex)
{
    $v = hexdec($strHex);
    $x = ($v & (1 << 23) - 1) + (1 << 23) * ($v >> 31 | 1);
    $exp = ($v >> 23 & 0xff) - 127;
    return $x * pow(2, $exp - 23);
}
Example #13
0
 function display()
 {
     global $mod_strings, $export_module, $current_language, $theme, $current_user, $dashletData, $sugar_flavor;
     if ($this->checkPostMaxSizeError()) {
         $this->errors[] = $GLOBALS['app_strings']['UPLOAD_ERROR_HOME_TEXT'];
         $contentLength = $_SERVER['CONTENT_LENGTH'];
         $maxPostSize = ini_get('post_max_size');
         if (stripos($maxPostSize, "k")) {
             $maxPostSize = (int) $maxPostSize * pow(2, 10);
         } elseif (stripos($maxPostSize, "m")) {
             $maxPostSize = (int) $maxPostSize * pow(2, 20);
         }
         $maxUploadSize = ini_get('upload_max_filesize');
         if (stripos($maxUploadSize, "k")) {
             $maxUploadSize = (int) $maxUploadSize * pow(2, 10);
         } elseif (stripos($maxUploadSize, "m")) {
             $maxUploadSize = (int) $maxUploadSize * pow(2, 20);
         }
         $max_size = min($maxPostSize, $maxUploadSize);
         $errMessage = string_format($GLOBALS['app_strings']['UPLOAD_MAXIMUM_EXCEEDED'], array($contentLength, $max_size));
         $this->errors[] = '* ' . $errMessage;
         $this->displayErrors();
     }
     include 'modules/Home/index.php';
 }
 /**
  * Ensure Decimal/Varint encoding on byte boundaries
  *
  * This test will ensure that the PHP driver is properly encoding Decimal
  * and Varint datatypes for positive values with leading 1's that land on
  * a byte boundary.
  *
  * @test
  * @ticket PHP-70
  */
 public function testByteBoundaryDecimalVarint()
 {
     // Create the table
     $query = "CREATE TABLE {$this->tableNamePrefix} (key timeuuid PRIMARY KEY, value_decimal decimal, value_varint varint)";
     $this->session->execute(new SimpleStatement($query));
     // Iterate through a few byte boundary positive values
     foreach (range(1, 20) as $i) {
         // Assign the values for the statement
         $key = new Timeuuid();
         $value_varint = pow(2, 8 * $i) - 1;
         $value_decimal = $value_varint / 100;
         $values = array($key, new Decimal($value_decimal), new Varint($value_varint));
         // Insert the value into the table
         $query = "INSERT INTO {$this->tableNamePrefix} (key, value_decimal, value_varint) VALUES (?, ?, ?)";
         $statement = new SimpleStatement($query);
         $options = new ExecutionOptions(array("arguments" => $values));
         $this->session->execute($statement, $options);
         // Select the decimal and varint
         $query = "SELECT value_decimal, value_varint FROM {$this->tableNamePrefix} WHERE key=?";
         $statement = new SimpleStatement($query);
         $options = new ExecutionOptions(array("arguments" => array($key)));
         $rows = $this->session->execute($statement, $options);
         // Ensure the decimal and varint are valid
         $this->assertCount(1, $rows);
         $row = $rows->first();
         $this->assertNotNull($row);
         $this->assertArrayHasKey("value_decimal", $row);
         $this->assertEquals($values[1], $row["value_decimal"]);
         $this->assertArrayHasKey("value_varint", $row);
         $this->assertEquals($values[2], $row["value_varint"]);
     }
 }
Example #15
0
 /**
  * Format a filesize
  *
  * @param int $size In bytes
  * @return string
  */
 public function fileSize($size)
 {
     if (!$size) {
         return '0 ' . $this->_sizes[0];
     }
     return round($size / pow(1024, $i = floor(log($size, 1024))), $i > 1 ? 2 : 0) . ' ' . $this->_sizes[$i];
 }
Example #16
0
function AwardForCapture($specsOwned, $mugsOwned, $sausageRollsOwned)
{
    $owned = $specsOwned * $mugsOwned * $sausageRollsOwned;
    $ownedValue = pow($owned, 2);
    $awardForCapture = 10 * $ownedValue / 2;
    return $awardForCapture;
}
Example #17
0
function aff_romain($param)
{
    $nombre_arab = $param[0];
    $nb_b10 = array('I', 'X', 'C', 'M');
    $nb_b5 = array('V', 'L', 'D');
    $nbrom = '';
    $nombre = $nombre_arab;
    if ($nombre >= 0 && $nombre < 4000) {
        for ($i = 3; $i >= 0; $i--) {
            $chiffre = floor($nombre / pow(10, $i));
            if ($chiffre >= 1) {
                $nombre = $nombre - $chiffre * pow(10, $i);
                if ($chiffre <= 3) {
                    for ($j = $chiffre; $j >= 1; $j--) {
                        $nbrom = $nbrom . $nb_b10[$i];
                    }
                } elseif ($chiffre == 9) {
                    $nbrom = $nbrom . $nb_b10[$i] . $nb_b10[$i + 1];
                } elseif ($chiffre == 4) {
                    $nbrom = $nbrom . $nb_b10[$i] . $nb_b5[$i];
                } else {
                    $nbrom = $nbrom . $nb_b5[$i];
                    for ($j = $chiffre - 5; $j >= 1; $j--) {
                        $nbrom = $nbrom . $nb_b10[$i];
                    }
                }
            }
        }
    } else {
        //Valeur Hors Limite;
        return $nombre_arab;
    }
    return $nbrom;
}
Example #18
0
 protected function _calculateNextRunAt()
 {
     $attempts = $this->getAttempts();
     $expMinutes = pow(2, $attempts);
     $nextRun = date("Y-m-d H:i:s", strtotime("+{$expMinutes} minutes"));
     return $nextRun;
 }
Example #19
0
 protected function _sierpinsky()
 {
     $newPolygones = array();
     $proceededLines = array();
     foreach ($this->_virtualPolygon as $points) {
         $lines = array(array(min($points[0], $points[1]), max($points[0], $points[1])), array(min($points[1], $points[2]), max($points[1], $points[2])), array(min($points[2], $points[0]), max($points[2], $points[0])));
         $new = array();
         foreach ($lines as $line) {
             if (!isset($proceededLines[$line[0]][$line[1]])) {
                 // Calculate new point
                 $newX = ($this->_points[$line[0]]->getX() + $this->_points[$line[1]]->getX()) / 2;
                 $newY = ($this->_points[$line[0]]->getY() + $this->_points[$line[1]]->getY()) / 2;
                 $newZ = ($this->_points[$line[0]]->getZ() + $this->_points[$line[1]]->getZ()) / 2;
                 $multiplikator = $this->_radius / sqrt(pow($newX, 2) + pow($newY, 2) + pow($newZ, 2));
                 $this->_points[] = new Image_3D_Point($newX * $multiplikator, $newY * $multiplikator, $newZ * $multiplikator);
                 $proceededLines[$line[0]][$line[1]] = count($this->_points) - 1;
             }
             $new[] = $proceededLines[$line[0]][$line[1]];
         }
         $newPolygones[] = array($points[0], $new[0], $new[2]);
         $newPolygones[] = array($points[1], $new[1], $new[0]);
         $newPolygones[] = array($points[2], $new[2], $new[1]);
         $newPolygones[] = array($new[0], $new[1], $new[2]);
     }
     $this->_virtualPolygon = $newPolygones;
 }
Example #20
0
 private static function make_apps_url($url)
 {
     $httpstr = is_https() ? 'https' : 'http';
     if (preg_match('#//goo\\.gl/#', $url)) {
         $results = mahara_shorturl_request($url);
         $url = $results->fullurl;
     }
     $embedsources = array(array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)leaf\\?id=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/$1leaf?id=$2', 'type' => 'spanicon'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)open\\?id=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/$1open?id=$2', 'type' => 'spanicon'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)present([a-z]*)/([a-z]+).*?id=([a-zA-Z0-9\\_\\-\\&\\=]+).*#', 'url' => $httpstr . '://docs.google.com/$1present$2/embed?id=$4', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)presentation/([a-zA-Z0-9\\_\\-\\/]+)/([a-z]+)\\?([a-zA-Z0-9\\_\\-\\&\\=]*).*#', 'url' => $httpstr . '://docs.google.com/$1presentation/$2/embed?$4', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)drawings.*id=([a-zA-Z0-9\\_\\-\\&\\=]+).*#', 'url' => $httpstr . '://docs.google.com/$1drawings/pub?id=$2', 'type' => 'image'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)drawings/([a-zA-Z0-9\\_\\-\\/]+)/([a-z]+)\\?([a-zA-Z0-9\\_\\-\\&\\=]*).*#', 'url' => $httpstr . '://docs.google.com/$1drawings/$2/$3?$4', 'type' => 'image'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)View.*id=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/$1View?id=$2', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)viewer.*srcid=([a-zA-Z0-9\\_\\-\\&\\=]+).*#', 'url' => $httpstr . '://docs.google.com/$1viewer?srcid=$2', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)document/([a-zA-Z0-9\\_\\-\\/]+)/pub.*#', 'url' => $httpstr . '://docs.google.com/$1document/$2/pub?embedded=true', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)file/([a-zA-Z0-9\\_\\-\\/]+)/([a-z]+).*#', 'url' => $httpstr . '://docs.google.com/$1file/$2/preview', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)viewer.*url=http([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+/\\:]+)\\.(pdf|tif|tiff|ppt|doc|docx).*#', 'url' => $httpstr . '://docs.google.com/$1viewer?url=http$2.$3&embedded=true', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)document/pub.*id=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/$1document/pub?id=$2', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)document/d/([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/$1document/d/$2/pub?embedded=true', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)spreadsheets/d/([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/$1spreadsheets/d/$2/pub?embedded=true', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)spreadsheet/.*key=([a-zA-Z0-9\\_\\-]+)([a-zA-Z0-9\\_\\-\\&\\=]*).*#', 'url' => $httpstr . '://docs.google.com/$1spreadsheet/pub?key=$2$3&widget=true', 'type' => 'iframe'), array('match' => '#.*docs.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)forms/([a-zA-Z0-9\\_\\-\\.\\/]*)/viewform\\?embedded=true.*#', 'url' => $httpstr . '://docs.google.com/$1forms/$2/viewform?embedded=true', 'type' => 'iframe'), array('match' => '#.*spreadsheets[0-9]?.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)viewform.*formkey=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://spreadsheets.google.com/$1embeddedform?formkey=$2', 'type' => 'iframe'), array('match' => '#.*spreadsheets[0-9]?.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)embeddedform.*formkey=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://spreadsheets.google.com/$1embeddedform?formkey=$2', 'type' => 'iframe'), array('match' => '#.*spreadsheets[0-9]?.google.com/([a-zA-Z0-9\\_\\-\\.\\/]*)pub.*key=([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://spreadsheets.google.com/$1pub?key=$2', 'type' => 'iframe'), array('match' => '#.*drive.google.com/.*file/d/([a-zA-Z0-9\\_\\-]+).*#', 'url' => $httpstr . '://docs.google.com/file/d/$1/preview', 'type' => 'iframe'), array('match' => '#.*www.google.com/calendar.*src=([a-zA-Z0-9\\.\\_\\-\\&\\%\\=/]+).*#', 'url' => $httpstr . '://www.google.com/calendar/embed?src=$1', 'type' => 'iframe'), array('match' => '#.*google.[^/]*/maps/ms\\?([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+/]+).*#', 'url' => $httpstr . '://maps.google.com/maps/ms?$1&output=embed', 'type' => 'iframe'), array('match' => '#.*maps.google.[^/]*/(maps)?\\?([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+/]+).*#', 'url' => $httpstr . '://maps.google.com/maps?$2&output=embed', 'type' => 'iframe'), array('match' => '#.*google.[^/]*/maps/place/([^/]+)/@([0-9\\-\\.]+),([0-9\\-\\.]+),([0-9]+)z/data=.+!1s([0-9xa-f]+):([0-9xa-f]+).*#', 'url' => function ($m) {
         $zoomlevel = min(max($m[4], 3), 21);
         $height = 188 * pow(2, 21 - $zoomlevel);
         return "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d{$height}!2d{$m[3]}!3d{$m[2]}!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s{$m[5]}%3A{$m[6]}!2s{$m[1]}!5e0";
     }, 'type' => 'iframe'), array('match' => '#.*mapsengine.google.com[^/]*/map/[^?]*\\?([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+\\?/]+).*#', 'url' => $httpstr . '://mapsengine.google.com/map/embed?$1', 'type' => 'iframe'), array('match' => '#.*www.google.com[^/]*/maps\\?([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+\\!/]+).*#', 'url' => $httpstr . '://www.google.com/maps?$1&output=embed', 'type' => 'iframe'), array('match' => '#.*www.google.com[^/]*/maps/embed\\?([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+\\!/]+).*#', 'url' => 'https://www.google.com/maps/embed?$1', 'type' => 'iframe'), array('match' => '#.*www.google.com.*?/\\@([a-zA-Z0-9\\.\\-]+)\\,([a-zA-Z0-9\\.\\-]+)\\,([0-9]+).*#', 'url' => 'https://maps.google.com/maps?ll=$1,$2&z=$3&output=embed', 'type' => 'iframe'), array('match' => '#.*books.google.[^/]*/books.*id=([a-zA-Z0-9\\_\\-\\&\\%\\=]+).*#', 'url' => 'http://books.google.com/books?id=$1', 'type' => 'iframe'), array('match' => '#http([a-zA-Z0-9\\.\\,\\;\\_\\-\\&\\%\\=\\+/\\:]+)\\.(pdf|tif|tiff|ppt|doc|docx)#', 'url' => $httpstr . '://docs.google.com/gview?url=http$1.$2&embedded=true', 'type' => 'iframe'));
     foreach ($embedsources as $source) {
         $url = htmlspecialchars_decode($url);
         // convert &amp; back to &, etc.
         if (preg_match($source['match'], $url)) {
             if (is_string($source['url'])) {
                 $apps_url = preg_replace($source['match'], $source['url'], $url);
             } else {
                 if (is_callable($source['url'])) {
                     $apps_url = preg_replace_callback($source['match'], $source['url'], $url);
                 }
             }
             // For correctly embed Google maps...
             $apps_url = str_replace('source=embed', 'output=embed', $apps_url);
             $apps_type = $source['type'];
             return array('url' => $apps_url, 'type' => $apps_type);
         }
     }
     // if we reach here then mahara does not understand the url
     return array('url' => $url, 'type' => false);
 }
Example #21
0
 /**
  * Checks if the current login attempt is locked according to an exponential timeout.
  * There is cap on the length of the timeout however. The timeout could grow to infinity without the cap.
  * This returns how many seconds the session is locked out from attempting a login.
  *
  * @param $identity string
  * @return false | int
  */
 public function locked_out($identity)
 {
     $lockout_options = $this->options['login_lockout'];
     if (!empty($identity) and is_array($lockout_options) and (in_array('ipaddress', $lockout_options) or in_array('identity', $lockout_options))) {
         $row = $this->storage->locked_out($identity, $this->ip_transformer->insert($this->request->getClientIp()));
         if (!$row) {
             return false;
         }
         $number_of_attempts = $row->attemptNum;
         $last_attempt = $row->lastAttempt;
         //y = 1.8^(n-1) where n is number of attempts, resulting in exponential timeouts, to prevent brute force attacks
         $lockout_duration = round(pow(1.8, $number_of_attempts - 1));
         //capping the lockout time
         if ($this->options['login_lockout_cap']) {
             $lockout_duration = min($lockout_duration, $this->options['login_lockout_cap']);
         }
         //adding the lockout time to the last attempt will create the overall timeout
         $timeout = strtotime($last_attempt) + $lockout_duration;
         //if the current time is less than the timeout, then attempt is locked out
         if (time() < $timeout) {
             //return the difference in seconds
             return (int) $timeout - time();
         }
     }
     return false;
 }
Example #22
0
/**
 * Provides a checkbox styled as a switch.
 *
 * @param Pieform  $form    The form to render the element for
 * @param array    $element The element to render
 *
 * The element can contain these variables (all are optional):
 *     switchtext        text        Text to be displayed on button - chosen by style
 *                                   valid options are 'onoff', 'yesno', 'truefalse' - used for headdata
 *     wrapperclass      text        Class to use on the div wrapper
 *
 * @return string           The HTML for the element
 */
function pieform_element_switchbox(Pieform $form, $element)
{
    $wrapper = !empty($element['wrapperclass']) ? $element['wrapperclass'] : '';
    $html = '<div class="' . $wrapper . '">' . pieform_element_checkbox($form, $element) . '</div>';
    $labels = pieform_element_switchbox_labeltext($element);
    // Dealing with the label text
    $type = $labels['type'];
    $onlabel = $labels['on'];
    $offlabel = $labels['off'];
    $strlength = max(strlen($onlabel), strlen($offlabel));
    $width = floor(57 + ($strlength - 2) * 3.5 + pow(1.4, $strlength - 2)) . 'px';
    $elementid = $form->make_id($element, $form->get_name());
    $html = '<div class="form-switch ' . $wrapper . '">';
    $html .= '    <div class="switch ' . $type . '" style="width:' . $width . '">';
    $html .= pieform_element_checkbox($form, $element);
    $html .= '        <label class="switch-label" tabindex="1" for="' . $elementid . '">';
    $html .= '            <span class="switch-inner" role="presentation"></span>';
    $html .= '            <span class="switch-indicator" role="presentation"></span>';
    $html .= '            <span class="state-label on" role="presentation" tabindex="-1">' . $onlabel . '</span>';
    $html .= '            <span class="state-label off" role="presentation" tabindex="-1">' . $offlabel . '</span>';
    $html .= '        </label>';
    $html .= '    </div>';
    $html .= '</div>';
    return $html;
}
 /**
  * Interpolate values in a matrice so that the total number of data points
  * in vert and horizontal axis are $aIntNbr more. For example $aIntNbr=2 will
  * make the data matrice have tiwce as many vertical and horizontal dta points.
  *
  * Note: This will blow up the matrcide in memory size in the order of $aInNbr^2
  *
  * @param  $ &$aData The original data matricde
  * @param  $aInNbr Interpolation factor
  * @return the interpolated matrice
  */
 function Linear(&$aData, $aIntFactor)
 {
     $step = pow(2, $aIntFactor - 1);
     $orig_cols = count($aData[0]);
     $orig_rows = count($aData);
     // Number of new columns/rows
     // N = (a-1) * 2^(f-1) + 1
     $p = pow(2, $aIntFactor - 1);
     $new_cols = $p * ($orig_cols - 1) + 1;
     $new_rows = $p * ($orig_rows - 1) + 1;
     $this->data = array_fill(0, $new_rows, array_fill(0, $new_cols, 0));
     // Initialize the new matrix with the values that we know
     for ($i = 0; $i < $new_rows; $i++) {
         for ($j = 0; $j < $new_cols; $j++) {
             $v = 0;
             if ($i % $step == 0 && $j % $step == 0) {
                 $v = $aData[$i / $step][$j / $step];
             }
             $this->data[$i][$j] = $v;
         }
     }
     for ($i = 0; $i < $new_rows - 1; $i += $step) {
         for ($j = 0; $j < $new_cols - 1; $j += $step) {
             $this->IntSquare($i, $j, $aIntFactor);
         }
     }
     return $this->data;
 }
Example #24
0
function filesize_formatted($path)
{
    $size = filesize($path);
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $power = $size > 0 ? floor(log($size, 1024)) : 0;
    return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
 public function getAmountInBaseUnits(Money $money)
 {
     $iso = $this->iso4217->getByAlpha3($money->getCurrency()->getName());
     $decimals = $iso['exp'];
     $dividend = pow(10, $decimals);
     return $money->getAmount() / $dividend;
 }
Example #26
0
 /**
  * Convert a string of what ever size to bites.
  *
  * Example input:8mb will produce output:83886080
  *
  * @param $string
  * @return int
  */
 public function convert($string)
 {
     if (!is_string($string)) {
         return 0;
     }
     $matches = [];
     preg_match("/([0-9]*)([a-zA-Z]*)/", $string, $matches);
     if (count($matches) != 3) {
         return 0;
     }
     $value = (int) $matches[1];
     $units = strtolower($matches[2]);
     switch ($units) {
         case "k":
         case "kb":
             return $value * 1024;
         case "m":
         case "mb":
             return $value * pow(1024, 2);
         case "g":
         case "gb":
             return $value * pow(1024, 3);
         case "t":
         case "tb":
             return $value * pow(1024, 4);
         case "p":
         case "pb":
             return $value * pow(1024, 5);
         default:
             return $value;
     }
 }
function clearByes($tid)
{
    $bye = bye();
    $pl = dbcount("(player_id)", DB_T_PLAYERS, "player_tour='" . $tid . "' AND player_checkin='1'");
    $max = getMaxPl($pl);
    $rounds = log($max) / log(2);
    for ($i = 1; $i <= $rounds; $i++) {
        for ($j = 1; $j <= $max / pow(2, $i); $j++) {
            $result = dbquery("SELECT * FROM " . DB_T_MATCHES . " WHERE match_round='" . $i . "' AND match_match='" . $j . "' AND match_tour='" . $tid . "'");
            $data = dbarray($result);
            if ($data['match_pl1'] == $bye && $data['match_pl2'] == $bye) {
                EnterResult($tid, $i, $j, 1, 0);
            }
            if ($data['match_pl1'] == $bye && $data['match_pl2'] != $bye && $data['match_pl2'] != 0) {
                EnterResult($tid, $i, $j, 0, 1);
            }
            if ($data['match_pl1'] != $bye && $data['match_pl2'] == $bye && $data['match_pl1'] != 0) {
                EnterResult($tid, $i, $j, 1, 0);
            }
        }
    }
    $x = $rounds + 1;
    $result2 = dbquery("SELECT * FROM " . DB_T_MATCHES . " WHERE match_round='" . $x . "' AND match_match='1' AND match_tour='" . $tid . "'");
    $data2 = dbarray($result);
    if ($data2['match_pl1'] == $bye && $data2['match_pl2'] == $bye) {
        EnterResult($tid, $x, 1, 1, 0);
    }
    if ($data2['match_pl1'] == $bye && $data2['match_pl2'] != $bye && $data2['match_pl2'] != 0) {
        EnterResult($tid, $x, 1, 0, 1);
    }
    if ($data2['match_pl1'] != $bye && $data2['match_pl2'] == $bye && $data2['match_pl1'] != 0) {
        EnterResult($tid, $x, 1, 1, 0);
    }
}
 /**
  * Generate a valid Google Translate request token.
  *
  * @param string $a text to translate
  *
  * @return string
  */
 private function TL($a)
 {
     $b = $this->generateB();
     for ($d = [], $e = 0, $f = 0; $f < mb_strlen($a, 'UTF-8'); $f++) {
         $g = $this->charCodeAt($a, $f);
         if (128 > $g) {
             $d[$e++] = $g;
         } else {
             if (2048 > $g) {
                 $d[$e++] = $g >> 6 | 192;
             } else {
                 if (55296 == ($g & 64512) && $f + 1 < mb_strlen($a, 'UTF-8') && 56320 == ($this->charCodeAt($a, $f + 1) & 64512)) {
                     $g = 65536 + (($g & 1023) << 10) + ($this->charCodeAt($a, ++$f) & 1023);
                     $d[$e++] = $g >> 18 | 240;
                     $d[$e++] = $g >> 12 & 63 | 128;
                 } else {
                     $d[$e++] = $g >> 12 | 224;
                     $d[$e++] = $g >> 6 & 63 | 128;
                 }
             }
             $d[$e++] = $g & 63 | 128;
         }
     }
     $a = $b;
     for ($e = 0; $e < count($d); $e++) {
         $a += $d[$e];
         $a = $this->RL($a, '+-a^+6');
     }
     $a = $this->RL($a, '+-3^+b+-f');
     if (0 > $a) {
         $a = ($a & 2147483647) + 2147483648;
     }
     $a = fmod($a, pow(10, 6));
     return $a . '.' . ($a ^ $b);
 }
Example #29
0
function bcadd($left, $right, $scale)
{
    // Deal with numbers smaller than $scale
    $_left = $left < pow(10, -$scale) ? 0 : $left;
    $_right = $right < pow(10, -$scale) ? 0 : $right;
    // first add the two numbers
    $sum = (double) ($_left + $_right);
    // check for a dot in the number
    if (strpos($sum, ".") === false) {
        // not found, integer
        $int_part = $sum;
        $real_part = 0;
    } else {
        // if not, we split
        list($int_part, $real_part) = explode(".", $sum);
    }
    // end checking for a dot
    // handle scale of 0
    if ($scale == 0) {
        return $int_part;
    }
    // handle real parts that need more precision
    if ($scale > strlen($real_part)) {
        for ($i = 0; $i <= $scale - strlen($real_part); $i++) {
            $real_part .= "0";
        }
    }
    // end checking for more precision needed
    // return built string
    return $int_part . "." . substr($real_part, 0, $scale);
}
 static function RemoveID3v1()
 {
     if ($ThisFileInfo['filesize'] >= pow(2, 31)) {
         $this->errors[] = 'Unable to write ID3v1 because file is larger than 2GB';
         return false;
     }
     // File MUST be writeable - CHMOD(646) at least
     if (is_writeable($this->filename)) {
         ob_start();
         if ($fp_source = fopen($this->filename, 'r+b')) {
             ob_end_clean();
             fseek($fp_source, -128, SEEK_END);
             if (fread($fp_source, 3) == 'TAG') {
                 ftruncate($fp_source, filesize($this->filename) - 128);
             } else {
                 // no ID3v1 tag to begin with - do nothing
             }
             fclose($fp_source);
             return true;
         } else {
             $errormessage = ob_get_contents();
             ob_end_clean();
             $this->errors[] = 'Could not open ' . $this->filename . ' mode "r+b"';
         }
     } else {
         $this->errors[] = $this->filename . ' is not writeable';
     }
     return false;
 }