function rrt($rate)
 {
     $min = 0;
     $max = 1;
     $R = 0.75;
     $count = 0;
     $arraylist = array();
     $fail_rate = $rate;
     $fail_start = ($min + mt_rand() / mt_getrandmax() * ($max - $min)) * (1 - $fail_rate);
     $p = $min + mt_rand() / mt_getrandmax() * ($max - $min);
     while (!($p > $fail_start && $p < $fail_start + $fail_rate)) {
         $count++;
         array_push($arraylist, $p);
         $flag = true;
         while ($flag) {
             $flag = false;
             $p = $min + mt_rand() / mt_getrandmax() * ($max - $min);
             $r = $R / (2 * count($arraylist));
             for ($i = 0; $i < count($arraylist); $i++) {
                 if ($p > $arraylist[$i] - $r && $p < $arraylist[$i] + $r) {
                     $flag = true;
                 }
             }
         }
     }
     return $count;
 }
 public function get_token()
 {
     // Create a token
     $token = hash('sha512', mt_rand(0, mt_getrandmax()) . microtime(TRUE));
     $_SESSION['token'] = $token;
     return $token;
 }
Exemple #3
0
 public static function send($data, $sampleRate = 1)
 {
     $config = Config::getInstance();
     if (!$config->isEnabled("statsd")) {
         return;
     }
     // sampling
     $sampledData = array();
     if ($sampleRate < 1) {
         foreach ($data as $stat => $value) {
             if (mt_rand() / mt_getrandmax() <= $sampleRate) {
                 $sampledData[$stat] = "{$value}|@{$sampleRate}";
             }
         }
     } else {
         $sampledData = $data;
     }
     if (empty($sampledData)) {
         return;
     }
     // Wrap this in a try/catch - failures in any of this should be silently ignored
     try {
         $host = $config->getConfig("statsd.host");
         $port = $config->getConfig("statsd.port");
         $fp = fsockopen("udp://{$host}", $port, $errno, $errstr);
         if (!$fp) {
             return;
         }
         foreach ($sampledData as $stat => $value) {
             fwrite($fp, "{$stat}:{$value}");
         }
         fclose($fp);
     } catch (Exception $e) {
     }
 }
Exemple #4
0
 /**
  * Return a random number in the specified range
  *
  * @param $min [optional]
  * @param $max [optional]
  * @return int A random integer value between min (or 0) and max
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public static function getRandomNumber($min = 0, $max = null)
 {
     if (null === $max) {
         $max = mt_getrandmax();
     }
     $range = $max - $min + 1;
     $offset = 0;
     if (function_exists('openssl_random_pseudo_bytes')) {
         // use openssl lib if it is installed
         $bytes = openssl_random_pseudo_bytes(PHP_INT_SIZE);
         $hex = bin2hex($bytes);
         // hex() doubles the length of the string
         $offset = abs(hexdec($hex) % $range);
         // random integer from 0 to $range
     } elseif ($fp = @fopen('/dev/urandom', 'rb')) {
         // attempt to use /dev/urandom if it exists but openssl isn't available
         $bytes = @fread($fp, PHP_INT_SIZE);
         $hex = bin2hex($bytes);
         // hex() doubles the length of the string
         $offset = abs(hexdec($hex) % $range);
         // random integer from 0 to $range
         fclose($fp);
     } else {
         throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase("Please make sure you have 'openssl' extension installed"));
     }
     return $min + $offset;
     // random integer from $min to $max
 }
Exemple #5
0
 public function __construct($dir)
 {
     if (self::$useDirectories === NULL) {
         // checks whether directory is writable
         $uniq = uniqid('_', TRUE);
         umask(00);
         if (!@mkdir("{$dir}/{$uniq}", 0777)) {
             // @ - is escalated to exception
             throw new InvalidStateException("Unable to write to directory '{$dir}'. Make this directory writable.");
         }
         // tests subdirectory mode
         self::$useDirectories = !ini_get('safe_mode');
         if (!self::$useDirectories && @file_put_contents("{$dir}/{$uniq}/_", '') !== FALSE) {
             // @ - error is expected
             self::$useDirectories = TRUE;
             unlink("{$dir}/{$uniq}/_");
         }
         rmdir("{$dir}/{$uniq}");
     }
     $this->dir = $dir;
     $this->useDirs = (bool) self::$useDirectories;
     if (mt_rand() / mt_getrandmax() < self::$gcProbability) {
         $this->clean(array());
     }
 }
 public function up()
 {
     //we'll need some places where the events can take place
     $locations = array('Rīga', 'Valmiera', 'Ventspils');
     foreach ($locations as $location) {
         $loc = \Model_Orm_Location::forge();
         $loc->title = $location;
         $loc->save();
     }
     //and let's create at least one event as well
     $demo_event = \Model_Orm_Event::forge();
     $demo_event->title = "Notikums pēc nedēļas";
     $demo_event->description = "Kaut kas, kam jānotiek nedēļu vēlāk nekā šī skripta izpilde.";
     $startdate = \Fuel\Core\Date::forge(time() + 7 * 24 * 60 * 60);
     $demo_event->start = $startdate->format('mysql', false);
     //'2013-11-27 07:00:00';
     $demo_event->location_id = 1;
     //pieņemsim, ka Rīgā;
     $demo_event->save();
     //the event shouldn't be empty - some agenda items
     $agenda_items = array('Notikuma pats, pats sākums', 'Kaut kad drusku vēlāk', 'Vēl mazliet vēlāk', 'Un nu jau arī beigas');
     foreach ($agenda_items as $agenda_item) {
         $demo_agenda = \Model_Orm_Agenda::forge();
         $demo_agenda->title = $agenda_item;
         $demo_agenda->event = $demo_event;
         $demo_agenda->save();
     }
     //we also need some users. at least two.
     \Auth::instance()->create_user("*****@*****.**", "fuel_dev", "*****@*****.**", 100, array("verified" => true, "verification_key" => md5(mt_rand(0, mt_getrandmax()))));
     \Auth::instance()->create_user("*****@*****.**", "fuel_dev", "*****@*****.**", 1, array("verified" => true, "verification_key" => md5(mt_rand(0, mt_getrandmax()))));
 }
Exemple #7
0
function getSiftScore($userid)
{
    if (!SHIFT_SCIENCE_KEY) {
        return mt_rand() / mt_getrandmax();
    }
    // create curl resource
    $ch = curl_init();
    $api_key = SHIFT_SCIENCE_KEY;
    // set url
    curl_setopt($ch, CURLOPT_URL, "https://api.siftscience.com/v203/score/{$userid}/?api_key={$api_key}");
    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // $output contains the output string
    $output = curl_exec($ch);
    // close curl resource to free up system resources
    curl_close($ch);
    $sift_data = json_decode($output);
    if ($sift_data->status != 0) {
        $sift_data->score = null;
        if ($sift_data->error_message != 'Specified user_id has no scorable events') {
            throw new Exception($sift_data->error_message);
        }
    }
    $sift_score = $sift_data->score;
    return $sift_score;
}
Exemple #8
0
 public static function send($data, $sampleRate = 1)
 {
     if (!self::$enabled) {
         return;
     }
     // sampling
     $sampledData = array();
     if ($sampleRate < 1) {
         foreach ($data as $stat => $value) {
             if (mt_rand() / mt_getrandmax() <= $sampleRate) {
                 $sampledData[$stat] = "{$value}|@{$sampleRate}";
             }
         }
     } else {
         $sampledData = $data;
     }
     if (empty($sampledData)) {
         return;
     }
     // Wrap this in a try/catch - failures in any of this should be silently ignored
     try {
         $host = 'statsd.p.rayku.com';
         $port = 8125;
         $fp = fsockopen("udp://{$host}", $port, $errno, $errstr);
         if (!$fp) {
             return;
         }
         foreach ($sampledData as $stat => $value) {
             fwrite($fp, "{$stat}:{$value}");
         }
         fclose($fp);
     } catch (Exception $e) {
     }
 }
 private function getRandom($min, $max)
 {
     $factor = (double) mt_rand() / (double) mt_getrandmax();
     $random = mt_rand($min, $max) * $factor;
     $result = $random + $min > $max ? $random : $random + $min;
     return round($result, 2);
 }
 function autologin()
 {
     if ($_COOKIE["autologin"]) {
         $data = unserialize($_COOKIE["autologin"]);
         if (isset($data['key']) and isset($data['user_id'])) {
             $cookiedata = $this->select_cookie($data['user_id'], $data['key']);
             if (!is_null($cookiedata)) {
                 $user_data = serialize(array('user_id' => $cookiedata[0]["id"], 'username' => $cookiedata[0]["username"], 'email' => $cookiedata[0]["email"], 'status' => $cookiedata[0]["activated"] == 1 ? '1' : '0'));
                 $ip = getenv("REMOTE_ADDR");
                 $sessid = '';
                 while (strlen($sessid) < 32) {
                     $sessid .= mt_rand(0, mt_getrandmax());
                 }
                 $session_id = md5(uniqid($sessid, TRUE));
                 $user_agent = $_SERVER["HTTP_USER_AGENT"];
                 $now = time();
                 $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
                 $aryCookie = unserialize($_COOKIE['ci_session']);
                 $this->clearsession($aryCookie['session_id']);
                 setcookie('ci_session', '', time() - 1, '/');
                 $sessiondata = $this->creatsession($session_id, $ip, $user_agent, $time, $user_data);
                 $ci_session_data = serialize(array('session_id' => $session_id, 'ip_address' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $user_agent, 'last_activity' => $time));
                 setcookie('autologin', serialize(array('user_id' => $data['user_id'], 'key' => $data['key'])), time() + 60 * 60 * 24 * 31 * 2, '/');
                 //setcookie('ci_session',$ci_session_data,0,'/');
                 //print_r($_COOKIE['ci_session']);
                 $this->update_user($data['user_id']);
                 return $session_id;
             }
         }
     }
     return FALSE;
 }
Exemple #11
0
function init()
{
    global $gcInternal, $gcProbability;
    if ($gcInternal === true && ($gcProbability === 1.0 || mt_rand() / mt_getrandmax() < $gcProbability)) {
        runGc();
    }
}
Exemple #12
0
 /**
  * 无key方式访问
  * @return $this
  */
 public function logisticWithoutKey()
 {
     $temp = mt_rand() / mt_getrandmax();
     $url = 'http://www.kuaidi100.com/query?type=' . $this->company_code . '&postid=' . $this->logistic_num . '&id=1&valicode=&temp=' . $temp;
     //初始化curl
     $ch = curl_init();
     //设置超时
     curl_setopt($ch, CURLOPT_TIMEOUT, 60);
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     curl_setopt($ch, CURLOPT_HEADER, FALSE);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/" . self::randomIp() . " Safari/536.11");
     $res = curl_exec($ch);
     curl_close($ch);
     $this->data = json_decode($res, true);
     if (is_array($this->data) && array_key_exists('status', $this->data)) {
         $this->status = $this->data['status'];
     }
     if (is_array($this->data) && array_key_exists('message', $this->data)) {
         $this->message = $this->data['message'];
     }
     if (is_array($this->data) && array_key_exists('state', $this->data)) {
         $this->state = $this->data['state'];
     }
     return $this;
 }
Exemple #13
0
 /**
  * Return a random number in the specified range
  *
  * @param $min [optional]
  * @param $max [optional]
  * @return int A random integer value between min (or 0) and max
  */
 public static function getRandomNumber($min = 0, $max = null)
 {
     if (null === $max) {
         $max = mt_getrandmax();
     }
     $range = $max - $min + 1;
     $offset = 0;
     if (function_exists('openssl_random_pseudo_bytes')) {
         // use openssl lib if it is installed
         $bytes = openssl_random_pseudo_bytes(PHP_INT_SIZE);
         $hex = bin2hex($bytes);
         // hex() doubles the length of the string
         $offset = abs(hexdec($hex) % $range);
         // random integer from 0 to $range
     } elseif ($fp = @fopen('/dev/urandom', 'rb')) {
         // attempt to use /dev/urandom if it exists but openssl isn't available
         $bytes = @fread($fp, PHP_INT_SIZE);
         $hex = bin2hex($bytes);
         // hex() doubles the length of the string
         $offset = abs(hexdec($hex) % $range);
         // random integer from 0 to $range
         fclose($fp);
     } else {
         // fallback to mt_rand() if all else fails
         mt_srand(mt_rand() + 100000000 * microtime() % PHP_INT_MAX);
         return mt_rand($min, $max);
         // random integer from $min to $max
     }
     return $min + $offset;
     // random integer from $min to $max
 }
 function array_random(array $array, $num = 1)
 {
     return array_random_callback($array, function () {
         $ramdom = ramdom_int();
         return $ramdom !== false ? floatval($ramdom) / floatval(PHP_INT_MAX + 1.0) : floatval(mt_rand()) / floatval(mt_getrandmax() + 1.0);
     }, $num);
 }
Exemple #15
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $faker = $this->getFaker();
     $fly1 = new Fly();
     $fly1->setName('chateau des vaux');
     $fly1->setLatitude('48');
     $fly1->setLongitude('1.0');
     $fly1->setDescription('magnifique chateau de la region ');
     $fly1->setCategory($faker->randomElement($fly1->getCategoryValues()));
     $manager->persist($fly1);
     $manager->flush();
     $lon_min = -1.0522795;
     $lon_max = 6.7260408;
     $lat_min = 42.4838724;
     $lat_max = 49.66374;
     foreach (range(1, 20) as $id) {
         $fly = new Fly();
         $fly->setName($faker->userName);
         $fly->setDescription($faker->realText(250));
         $fly->setLatitude(mt_rand() / mt_getrandmax() * ($lat_max - $lat_min) + $lat_min);
         $fly->setLongitude(mt_rand() / mt_getrandmax() * ($lon_max - $lon_min) + $lon_min);
         $fly->setCategory($faker->randomElement($fly1->getCategoryValues()));
         $manager->persist($fly);
     }
     $manager->flush();
 }
Exemple #16
0
 public static function send($data, $sampleRate = 1)
 {
     if (empty(Z_CONFIG::$STATSD_ENABLED)) {
         return;
     }
     // sampling
     $sampledData = array();
     if ($sampleRate < 1) {
         foreach ($data as $stat => $value) {
             if (mt_rand() / mt_getrandmax() <= $sampleRate) {
                 $sampledData[$stat] = "{$value}|@{$sampleRate}";
             }
         }
     } else {
         $sampledData = $data;
     }
     if (empty($sampledData)) {
         return;
     }
     // Wrap this in a try/catch - failures in any of this should be silently ignored
     try {
         $host = Z_CONFIG::$STATSD_HOST;
         $port = Z_CONFIG::$STATSD_PORT;
         $fp = fsockopen("udp://{$host}", $port, $errno, $errstr);
         if (!$fp) {
             return;
         }
         foreach ($sampledData as $stat => $value) {
             fwrite($fp, Z_CONFIG::$STATSD_PREFIX . "{$stat}:{$value}");
         }
         fclose($fp);
     } catch (Exception $e) {
     }
 }
Exemple #17
0
 public function RequestCode($return, $scope = [])
 {
     $state = mt_rand(0, mt_getrandmax());
     $scope = implode(',', $scope);
     $query_string = http_build_query(['state' => $state, 'scope' => $scope, 'return' => $return]);
     return (object) ['URL' => \s5\API::$OAuthBase . '/' . $this->API->Token . '?' . $query_string, 'State' => $state];
 }
Exemple #18
0
function auth_change_password($username, $password)
{
    $username_encoded = urlencode($username);
    $salt = hash("sha512", uniqid(mt_rand(1, mt_getrandmax()), true));
    $password_encoded = hash("sha512", $password . $salt);
    mysql_query("UPDATE users SET salt = '{$salt}', password = '******' WHERE username = '******'") or die(mysql_error());
}
function change_password($dbh1, $table_prefix1)
{
    // Create salted password (Careful not to over season)
    if (strcmp($_POST['new_pass_enc'], $_POST['new_pass_enc2']) !== 0) {
        $array['status'] = 'error';
        $array['message'] = "Heslá sa nezhodujú";
    } else {
        $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
        $password1 = hash('sha512', $_POST['new_pass_enc'] . $random_salt);
        if ($stmt = $dbh1->prepare("SELECT user_id FROM " . $table_prefix1 . "_password_reset WHERE hash = ? LIMIT 1")) {
            $stmt->bindParam(1, $_POST['string']);
            $stmt->execute();
            $stmt->result = $stmt->fetch();
            if ($insert_stmt = $dbh1->prepare("UPDATE " . $table_prefix1 . "_users SET password=?, salt=? WHERE id=?")) {
                $insert_stmt->bindParam(1, $password1);
                $insert_stmt->bindParam(2, $random_salt);
                $insert_stmt->bindParam(3, $stmt->result['user_id']);
                $insert_stmt->execute();
                $array['status'] = 'success';
                $array['message'] = "Heslo bolo úspešne zmenené. Budete presmerovany na prihlasovaciu stranku.";
                if ($select_stmt = $dbh1->prepare("DELETE FROM " . $table_prefix1 . "_password_reset WHERE hash=?")) {
                    $select_stmt->bindValue(1, $_POST['string']);
                    $select_stmt->execute();
                }
            } else {
                $array['status'] = 'error';
                $array['message'] = "Pri ukladaní údajov sa vyskytla chyba";
            }
        } else {
            $array['status'] = 'error';
            $array['message'] = "Pri zmene hesla sa vyskytla chyba. Odkaz nie je platný";
        }
    }
    echo json_encode($array);
}
 public function connectToUser($me, $you)
 {
     foreach ($this->conns as $c) {
         if ($c['two'] == $me->id && $c['one'] == $you->id && time() < $c['time'] + 30 && $c['active'] == 1) {
             $game_id = sha1(mt_rand(0, mt_getrandmax()) . 'fniyhksmi53?');
             $turn = mt_rand(0, 1) == 1 ? $me->id : $you->id;
             $game['id'] = $game_id;
             $game['turn'] = $turn;
             $game['moves'] = 0;
             $game['winner'] = 'PENDING';
             $game['one'] = $me->id;
             $game['two'] = $you->id;
             $arr = array();
             for ($r = 0; $r < 7; $r++) {
                 for ($c = 0; $c < 7; $c++) {
                     $arr[$r][$c] = -1;
                 }
             }
             $game['grid'] = $arr;
             $this->games[$game_id] = $game;
             $c['active'] = 0;
             return $game;
         }
     }
     $mycon['one'] = $me->id;
     $mycon['two'] = $you->id;
     $mycon['time'] = time();
     $mycon['active'] = 1;
     $this->conns[] = $mycon;
     return -1;
 }
Exemple #21
0
 public function create_new_order($order = array())
 {
     $index_lang = $this->CI->lang->line('index');
     if (isset($order['currency'])) {
         if (strlen($order['currency']) == 3) {
             //三个字母的ISO货币代码
             $order['currency'] = $this->get_currency_id_by_ISO($order['currency']);
         }
         $exchange_rate = $this->CI->pay_order->get_current_rate($order['currency']);
         if (!empty($exchange_rate)) {
             $order['exchange'] = $exchange_rate[0]->exchange;
         }
     }
     $order['order_sn'] = substr(mt_rand(1000000000, mt_getrandmax()), 0, 10);
     $order_prefix = $index_lang['order_prefix'] . $order['game_id'];
     $order['order_sn'] = $order_prefix . $order['order_sn'];
     $check_order_sn = $this->check_order_sn_duplicate($order['order_sn']);
     while ($check_order_sn) {
         //duplicate order_sn
         $order['order_sn'] = substr(mt_rand(1000000000, mt_getrandmax()), 0, 10);
         $order['order_sn'] = $order_prefix . $order['order_sn'];
         $check_order_sn = $this->check_order_sn_duplicate($order['order_sn']);
     }
     $order['order_status'] = $this->order_status['new_order'];
     $res = $this->CI->pay_order->create_new_order($order);
     if ($res) {
         return $order['order_sn'];
     }
 }
Exemple #22
0
function generate_encrypted_password($password)
{
    if (defined('CRYPT_SHA512') && CRYPT_SHA512 == 1) {
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes(8);
            $salt = bin2hex($bytes);
        } else {
            $salt = substr(md5(mt_rand(0, mt_getrandmax())), mt_rand(0, 16), 16);
        }
        $hash = crypt($password, '$6$rounds=100000$' . $salt . '$');
    } elseif (defined('CRYPT_MD5') && CRYPT_MD5 == 1) {
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes(4);
            $salt = bin2hex($bytes);
        } else {
            $salt = substr(md5(mt_rand(0, mt_getrandmax())), mt_rand(0, 24), 8);
        }
        $hash = crypt($password, '$1$' . $salt . '$');
    } else {
        if (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes(4);
            $salt = bin2hex($bytes);
        } else {
            $salt = substr(md5(mt_rand(0, mt_getrandmax())), mt_rand(0, 24), 8);
        }
        $hash = '$md5$' . $salt . '$' . md5($salt . $password);
    }
    return $hash;
}
Exemple #23
0
 /**
  * Create a new album.
  * @param integer $parent_id id of parent album
  * @param string  $name the name of this new album (it will become the directory name on disk)
  * @param integer $title the title of the new album
  * @param string  $description (optional) the longer description of this album
  * @return Item_Model
  */
 static function create($parent, $name, $title, $description = null, $owner_id = null)
 {
     if (!$parent->loaded || !$parent->is_album()) {
         throw new Exception("@todo INVALID_PARENT");
     }
     if (strpos($name, "/")) {
         throw new Exception("@todo NAME_CANNOT_CONTAIN_SLASH");
     }
     // We don't allow trailing periods as a security measure
     // ref: http://dev.kohanaphp.com/issues/684
     if (rtrim($name, ".") != $name) {
         throw new Exception("@todo NAME_CANNOT_END_IN_PERIOD");
     }
     $album = ORM::factory("item");
     $album->type = "album";
     $album->title = $title;
     $album->description = $description;
     $album->name = $name;
     $album->owner_id = $owner_id;
     $album->thumb_dirty = 1;
     $album->resize_dirty = 1;
     $album->rand_key = (double) mt_rand() / (double) mt_getrandmax();
     $album->sort_column = "weight";
     $album->sort_order = "ASC";
     while (ORM::factory("item")->where("parent_id", $parent->id)->where("name", $album->name)->find()->id) {
         $album->name = "{$name}-" . rand();
     }
     $album = $album->add_to_parent($parent);
     mkdir($album->file_path());
     mkdir(dirname($album->thumb_path()));
     mkdir(dirname($album->resize_path()));
     module::event("item_created", $album);
     return $album;
 }
 /**
  * Should we use sampleRate in message ?
  *
  * @return bool
  */
 protected function useSampleRate()
 {
     if ($this->getSampleRate() < 1 && mt_rand() / mt_getrandmax() <= $this->getSampleRate()) {
         return true;
     }
     return false;
 }
 /**
  * Instead of annoying getter setter test we test dem automatically by just providing the
  * attributes to be tested
  *
  * @return array
  */
 public function getterSetterTestDataProvider()
 {
     $testData = array();
     foreach ($this->settableAttributes as $attribute => $type) {
         switch ($type) {
             case 'string':
                 $testValue = uniqid('testString');
                 break;
             case 'int':
                 $testValue = rand(-10000, +10000);
                 break;
             case 'boolean':
                 $testValue = true;
                 break;
             case 'float':
                 $testValue = 0 + mt_rand() / mt_getrandmax() * 20;
                 break;
             case 'DateTime':
                 $testValue = new \DateTime();
         }
         $testName = 'Test setter and getter for Attribute ' . $attribute;
         $getterName = 'get' . ucfirst($attribute);
         $setterName = 'set' . ucfirst($attribute);
         $testData[$testName] = array('setterName' => $setterName, 'getterName' => $getterName, 'testValue' => $testValue);
     }
     return $testData;
 }
Exemple #26
0
 /**
  * Given an array of non-normalised probabilities, this function will select
  * an element and return the appropriate key
  *
  * @param array $weights
  * @return bool|int|string
  */
 public static function pickRandom($weights)
 {
     if (!is_array($weights) || count($weights) == 0) {
         return false;
     }
     $sum = array_sum($weights);
     if ($sum == 0) {
         # No loads on any of them
         # In previous versions, this triggered an unweighted random selection,
         # but this feature has been removed as of April 2006 to allow for strict
         # separation of query groups.
         return false;
     }
     $max = mt_getrandmax();
     $rand = mt_rand(0, $max) / $max * $sum;
     $sum = 0;
     foreach ($weights as $i => $w) {
         $sum += $w;
         # Do not return keys if they have 0 weight.
         # Note that the "all 0 weight" case is handed above
         if ($w > 0 && $sum >= $rand) {
             break;
         }
     }
     return $i;
 }
Exemple #27
0
 public function setDefaults($defaultsArray = [])
 {
     $defaultsArray['fixed'] = 4;
     $defaultsArray['min'] = 0;
     $defaultsArray['max'] = mt_getrandmax();
     return $defaultsArray;
 }
Exemple #28
0
 /**
  * Sends the stat(s) using UDP protocol
  * @param $data
  * @param int $sampleRate
  */
 protected function send($data, $sampleRate = 1)
 {
     $sampledData = array();
     if ($sampleRate < 1) {
         foreach ($data as $stat => $value) {
             if (mt_rand() / mt_getrandmax() <= $sampleRate) {
                 $sampledData[$stat] = "{$value}|@{$sampleRate}";
             }
         }
     } else {
         $sampledData = $data;
     }
     if (empty($sampledData)) {
         return;
     }
     try {
         if (!empty($this->host)) {
             $fp = fsockopen("udp://{$this->host}", $this->port);
             if (!$fp) {
                 return;
             }
             foreach ($sampledData as $stat => $value) {
                 if (is_array($value)) {
                     foreach ($value as $v) {
                         fwrite($fp, "{$stat}:{$v}");
                     }
                 } else {
                     fwrite($fp, "{$stat}:{$value}");
                 }
             }
             fclose($fp);
         }
     } catch (\Exception $e) {
     }
 }
Exemple #29
0
function registerUser($mail, $password, $db)
{
    // Create random salt
    $randomSalt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
    // Create salted password
    //$hashedPassword = hash('sha512', $password . $randomSalt);
    $hashedPassword = hash('sha512', $password . $randomSalt);
    // Create randomHash to salt mail for validation-process
    $randomHash = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
    // Created salted mail for validation-process
    $validationHash = hash('sha512', $mail . $randomHash);
    try {
        $db->beginTransaction();
        $stmt = $db->prepare('INSERT INTO users(user_mail, ' . 'user_hash, ' . 'user_salt, ' . 'user_validation, ' . 'user_regDate, ' . 'user_lastLogin, ' . 'user_role, ' . 'user_status, ' . 'user_newsletter) ' . 'VALUES (:mail, :hash, :salt, :validation, NOW(), NOW(), :role, :status, :newsletter)');
        $stmt->execute(array(':mail' => $mail, ':hash' => $hashedPassword, ':salt' => $randomSalt, ':validation' => $validationHash, ':role' => 0, ':status' => 'pending', ':newsletter' => 1));
        $lastUserId = $db->lastInsertId();
        $stmt = $db->query('INSERT INTO contacts (contact_name) VALUES (NULL)');
        $lastContactId = $db->lastInsertId();
        $stmt = $db->prepare('INSERT INTO user_has_contacts (user_id, contact_id) VALUES (:user, :contact)');
        $stmt->execute(array($lastUserId, $lastContactId));
        $db->commit();
    } catch (PDOException $e) {
        $e->getMessage();
        $db->rollBack();
    }
    if (empty($e)) {
        if (sendValidationMail($mail, $validationHash)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
 protected function setUp()
 {
     parent::setUp();
     $num = 1000;
     $probability_purchased = 0.007;
     $my_user_ids = array();
     $my_item_ids = array();
     for ($i = 0; $i < $num; $i++) {
         array_push($my_user_ids, "user-{$i}");
         array_push($my_item_ids, "item-{$i}");
     }
     $my_purchases = array();
     foreach ($my_user_ids as $user_id) {
         foreach ($my_item_ids as $item_id) {
             if (mt_rand() / mt_getrandmax() < $probability_purchased) {
                 array_push($my_purchases, new Reqs\AddPurchase($user_id, $item_id));
             }
         }
     }
     $client = new Client('client-test', 'jGGQ6ZKa8rQ1zTAyxTc0EMn55YPF7FJLUtaMLhbsGxmvwxgTwXYqmUk5xVZFw98L');
     $user_requests = array_map(function ($userId) {
         return new Reqs\AddUser($userId);
     }, $my_user_ids);
     $client->send(new Reqs\Batch($user_requests));
     $client->send(new Reqs\Batch([new Reqs\AddItemProperty('answer', 'int'), new Reqs\AddItemProperty('id2', 'string'), new Reqs\AddItemProperty('empty', 'string')]));
     $item_requests = array_map(function ($itemId) {
         return new Reqs\SetItemValues($itemId, ['answer' => 42, 'id2' => $itemId, '!cascadeCreate' => true]);
     }, $my_item_ids);
     $client->send(new Reqs\Batch($item_requests));
     $client->send(new Reqs\Batch($my_purchases));
 }