public function getAvatar($string, $widthHeight = 12, $theme = 'default') { $widthHeight = max($widthHeight, 12); $md5 = md5($string); $fileName = _TMP_DIR_ . '/' . $md5 . '.png'; if ($this->tmpFileExists($fileName)) { return $fileName; } // Create seed. $seed = intval(substr($md5, 0, 6), 16); mt_srand($seed); $body = array('legs' => mt_rand(0, count($this->availableParts[$theme]['legs']) - 1), 'hair' => mt_rand(0, count($this->availableParts[$theme]['hair']) - 1), 'arms' => mt_rand(0, count($this->availableParts[$theme]['arms']) - 1), 'body' => mt_rand(0, count($this->availableParts[$theme]['body']) - 1), 'eyes' => mt_rand(0, count($this->availableParts[$theme]['eyes']) - 1), 'mouth' => mt_rand(0, count($this->availableParts[$theme]['mouth']) - 1)); // Avatar random parts. $parts = array('legs' => $this->availableParts[$theme]['legs'][$body['legs']], 'hair' => $this->availableParts[$theme]['hair'][$body['hair']], 'arms' => $this->availableParts[$theme]['arms'][$body['arms']], 'body' => $this->availableParts[$theme]['body'][$body['body']], 'eyes' => $this->availableParts[$theme]['eyes'][$body['eyes']], 'mouth' => $this->availableParts[$theme]['mouth'][$body['mouth']]); $avatar = imagecreate($widthHeight, $widthHeight); imagesavealpha($avatar, true); imagealphablending($avatar, false); $background = imagecolorallocate($avatar, 0, 0, 0); $line_colour = imagecolorallocate($avatar, mt_rand(0, 200) + 55, mt_rand(0, 200) + 55, mt_rand(0, 200) + 55); imagecolortransparent($avatar, $background); imagefilledrectangle($avatar, 0, 0, $widthHeight, $widthHeight, $background); // Fill avatar with random parts. foreach ($parts as &$part) { $this->drawPart($part, $avatar, $widthHeight, $line_colour, $background); } imagepng($avatar, $fileName); imagecolordeallocate($avatar, $line_colour); imagecolordeallocate($avatar, $background); imagedestroy($avatar); return $fileName; }
function getverifycode() { $length = 6; PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000); $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1)); return $hash; }
public static function partitionTwo(DataSet $wholeSet, $partitionRelation, $seed = null) { if (!is_numeric($partitionRelation) || $partitionRelation <= 0 || $partitionRelation >= 1) { throw new InvalidArgumentException(); } // mt_srand(null) === mt_srand(0) if ($seed !== null) { mt_srand($seed); } $numElements = count($wholeSet->getData()); $indexes = range(0, $numElements - 1); self::shuffle($indexes); $trainingSet = []; $trainingSetLabels = []; $testSet = []; $testSetLabels = []; $data = $wholeSet->getData(); $labels = $wholeSet->getLabels(); for ($i = 0; $i < $numElements; $i++) { $index = $indexes[$i]; if ($i < $partitionRelation * $numElements) { $trainingSet[] = $data[$index]; $trainingSetLabels[] = $labels[$index]; } else { $testSet[] = $data[$index]; $testSetLabels[] = $labels[$index]; } } $trainingDataSet = new DataSet($trainingSet, $trainingSetLabels); $testDataSet = new DataSet($testSet, $testSetLabels); return new Partition($trainingDataSet, $testDataSet); }
function randNumber($len = 6, $start = false, $end = false) { mt_srand((double) microtime() * 1000000); $start = !$len && $start ? $start : str_pad(1, $len, "0", STR_PAD_RIGHT); $end = !$len && $end ? $end : str_pad(9, $len, "9", STR_PAD_RIGHT); return mt_rand($start, $end); }
function genKey($length, $type = null) { if ($length > 0) { $rand_id = ""; for ($i = 1; $i <= $length; $i++) { mt_srand((double) microtime() * 1000000); $min = 1; switch ($type) { case 'numeric': $max = 10; break; case 'alpha': $min = 11; $max = 62; break; case 'alphanumeric': $max = 62; break; default: $max = 72; break; } $num = mt_rand($min, $max); $rand_id .= assign_rand_value($num); } } return $rand_id; }
function skipdays($days) { if ($days == 1) { print "<td> </td>\n"; } else { if ($days > 3 && file_exists("Quotations")) { mt_srand((double) microtime() * 1000000); $lines = file("includes/text/quotations.txt"); $line_number = mt_rand(0, sizeof($lines) - 1); $quotation = htmlspecialchars($lines[$line_number]); $quotation = preg_replace('/^(.*)~/', '<em>$1</em><br>--', $quotation); $length = strlen($lines[$line_number]); $style = "text-align:center; color: #804000;"; if ($length / $days > 80) { $style .= "font-size: xx-small;"; } else { if ($length / $days > 50) { $style .= "font-size: x-small;"; } else { if ($length / $days > 35) { $style .= "font-size: small;"; } } } print "<td colspan={$days} style=\"{$style}\">{$quotation}</td>\n"; } else { print "<td colspan={$days}> </td>\n"; } } }
public function doMobileDetail() { global $_W, $_GPC; checkauth(); $rid = intval($_GPC['rid']); $reply = pdo_fetch("SELECT * FROM " . tablename('shake_reply') . " WHERE rid = :rid", array(':rid' => $rid)); if (empty($reply)) { message('抱歉,此活动不存在或是还未开始!', 'refresh', 'error'); } $member = pdo_fetch("SELECT * FROM " . tablename('shake_member') . " WHERE rid = :rid AND openid = :openid", array(':rid' => $reply['rid'], ':openid' => $_W['member']['uid'])); if (empty($member)) { $member = array('rid' => $rid, 'openid' => $_W['member']['uid'], 'createtime' => TIMESTAMP, 'shakecount' => 0, 'status' => 0); $maxjoin = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('shake_member') . " WHERE rid = '{$reply['rid']}' AND status = '1'"); if ($maxjoin < $reply['maxjoin']) { mt_srand((double) microtime() * 1000000); $rand = mt_rand(1, 100); if ($rand <= $reply['joinprobability']) { $member['status'] = 1; } } pdo_insert('shake_member', $member); } if (strexists(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) { $reply['speed'] = $reply['speedandroid']; } include $this->template('detail'); }
function uuid() { if (function_exists('com_create_guid')) { return com_create_guid(); } else { mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.随便数播种,4.2.0以后不需要了。 $charid = strtoupper(md5(uniqid(rand(), true))); //根据当前时间(微秒计)生成唯一id. $hyphen = chr(45); // "-" $uuid = '' . substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12); //.chr(125);// "}" return $uuid; } function createGuid($namespace = '') { static $guid = ''; $uid = uniqid("", true); $data = $namespace; $data .= $_SERVER['REQUEST_TIME']; $data .= $_SERVER['HTTP_USER_AGENT']; $data .= $_SERVER['LOCAL_ADDR']; $data .= $_SERVER['LOCAL_PORT']; $data .= $_SERVER['REMOTE_ADDR']; $data .= $_SERVER['REMOTE_PORT']; $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data))); $guid = '{' . substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12) . '}'; return $guid; } }
private function generateToken() : string { mt_srand((double) microtime() * 10000); $charid = strtoupper(md5(uniqid(rand(), true))); $retval = substr($charid, 0, 32); return $retval; }
function b_show_rmsrv_banners() { global $xoopsDB; $myts =& MyTextSanitizer::getInstance(); $block = array(); list($num) = $xoopsDB->fetchRow($xoopsDB->query("SELECT COUNT(*) FROM " . $xoopsDB->prefix("rmsrv_banners"))); if ($num <= 0) { return; } if ($num > 1) { $num = $num - 1; mt_srand((double) microtime() * 1000000); $snum = mt_rand(0, $num); } else { $snum = 0; } $sql = "SELECT * FROM " . $xoopsDB->prefix("rmsrv_banners") . " LIMIT {$snum}, 1"; $result = $xoopsDB->query($sql); $row = $xoopsDB->fetchArray($result); $rtn = array(); include_once XOOPS_ROOT_PATH . "/modules/rmservices/include/functions.php"; if ($row['buy']) { $form = FormBuy(ServiceData($row['id_srv'], "nombre"), ServiceData($row['id_srv'], "codigo"), ServiceData($row['id_srv'], "precio"), 'srv'); } $rtn['id'] = $row['id_ban']; $rtn['img'] = str_replace('{servicio}', $row['id_srv'], $row['img']); $rtn['desc'] = $myts->makeTareaData4Show($row['desc']); $rtn['border'] = $row['showborder']; $rtn['ids'] = $row['id_srv']; $rtn['form'] = $form; $block['bann'][] = $rtn; return $block; }
/** * @param float $ratioMin * @param float $ratioMax * @param int $seed * * @return float */ private function randomRatio($ratioMin, $ratioMax, $seed) { $precision = 100; mt_srand($seed); //so that values are same across tests return mt_rand($ratioMin * $precision, $ratioMax * $precision) / $precision; }
/** * generates a random int * * @param int $length * * @return int */ public static function getRandomInt($length = 10) : int { $time = time(); mt_srand($time); $tmp = mt_rand(); return (int) substr(number_format($tmp, 0, '', ''), 0, $length); }
function __construct() { global $cfg; $my_dir = dirname(__FILE__); $this->auto_lower = false; $this->auto_upper = true; $this->color = array(); $this->color['background'] = array('FFF1EA'); $this->color['grid'] = array('000000'); $this->color['text'] = array('000000'); //#000000 =>black $this->draw_ellipse = false; $this->font_array = array(); $this->font_dir = $cfg['path']['fonts']; $this->font_size = 16; $this->frame_delay = 80; $this->frame_number = 3; $this->grid_density = 10; $this->magic_words = ''; $this->overlap_text = true; $this->overlap_text_factor = array(0, 2); $this->random_angle_factor = 10; $this->random_y_factor = 3; $this->randomize_grid = true; $this->session_name = 'turing_string'; $this->string_length = 6; $this->temp_dir = $cfg['path']['temp']; $this->text_space = 10; mt_srand((int) ((double) microtime() * 1000003)); }
public function setClient($login, $psw, $email, $phone, $code, $firstname, $surname) { $data = array('data' => array('login' => $login, 'psw' => $psw, $email, $phone, 'SC' => $code, 'sesSC' => $_SESSION["secret_number"]), 'CID' => NULL, 'query' => NULL); if (intval($_SESSION["secret_number"]) < 1000) { mt_srand(time() + (double) microtime() * 1000000); $_SESSION["secret_number"] = mt_rand(1000, 9999); } if ($_SERVER["REQUEST_METHOD"] === "POST") { $error = 0; if (intval($code) !== $_SESSION["secret_number"] || intval($code) === 0) { $data['msg'] = 'Число з картинки введене невірно!'; } else { $salt = $this->getSalt(); $password = hash('sha256', $psw . $salt); $log = hash('sha256', $login); $data['sha256'] = $log; $query = "INSERT INTO `users`(`login`, `password`, `salt`, `firstname`, `surname`, `email`, `phone`) VALUES ('{$log}','{$password}','{$salt}','{$firstname}','{$surname}','{$email}','{$phone}')"; $data['query'] = $query; if (mysql_query($query)) { $this->_mail($email, $login, $password); $cid = mysql_insert_id(); $_SESSION['CID'] = $cid; $data["CID"] = $cid; } } // оновлюємо "таємне" число mt_srand(time() + (double) microtime() * 1000000); $_SESSION["secret_number"] = mt_rand(1000, 9999); } return $data; }
public function getAllImageData() { $iData = array('text' => '', 'images' => array()); if (!isset($this->images) || !is_array($this->images) || sizeof($this->images) < SimpleCaptcha::MIN_IMAGES) { throw new InvalidArgumentException("There aren\\'t enough images on the server!", 400); } $numImages = SimpleCaptcha::DEFAULT_NUM_IMAGES; if (isset($_REQUEST['numImages']) && intval($_REQUEST['numImages']) && intval($_REQUEST['numImages']) > SimpleCaptcha::MIN_IMAGES) { $numImages = intval($_REQUEST['numImages']); } $totalSize = sizeof($this->images); $numImages = min(array($totalSize, $numImages)); $keys = array_keys($this->images); $used = array(); mt_srand((double) microtime() * 587 / 33); // add some randomness for ($i = 0; $i < $numImages; ++$i) { $r = rand(0, $totalSize - 1); while (array_search($keys[$r], $used) !== false) { $r = rand(0, $totalSize - 1); } array_push($used, $keys[$r]); } $iData['text'] = $used[rand(0, $numImages - 1)]; $this->answer = sha1($iData['text'] . $this->sessionData['salt']); shuffle($used); for ($i = 0; $i < sizeof($used); ++$i) { $hash = sha1($used[$i] . $this->sessionData['salt']); array_push($iData['images'], $hash); $this->sessionData['images'][$hash] = $this->images[$used[$i]]; } return $iData; }
function guid() { mt_srand((double) microtime() * 10000); $charid = strtoupper(md5(uniqid(rand(), true))); $guid = substr($charid, 0, 8) . '-' . substr($charid, 8, 4) . '-' . substr($charid, 12, 4) . '-' . substr($charid, 16, 4) . '-' . substr($charid, 20, 12); return $guid; }
function son() { $son = "^°!\"§\$%&/()=?`²³{[]}\\´@+*~#'-_.:,;<>|µ"; mt_srand((double) microtime() * 10000); $return = $son[rand(0, strlen($son))]; return $return; }
static function genToken($len = 32, $md5 = true) { # Seed random number generator # Only needed for PHP versions prior to 4.2 mt_srand((double) microtime() * 1000000); # Array of characters, adjust as desired $chars = array('Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`', 'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.', '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a', 'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')', '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n', '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T', 'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'); # Array indice friendly number of chars; $numChars = count($chars) - 1; $token = ''; # Create random token at the specified length for ($i = 0; $i < $len; $i++) { $token .= $chars[mt_rand(0, $numChars)]; } # Should token be run through md5? if ($md5) { # Number of 32 char chunks $chunks = ceil(strlen($token) / 32); $md5token = ''; # Run each chunk through md5 for ($i = 1; $i <= $chunks; $i++) { $md5token .= md5(substr($token, $i * 32 - 32, 32)); } # Trim the token $token = substr($md5token, 0, $len); } return $token; }
function update() { global $xoopsUser, $xoopsModuleConfig, $xoopsModule; mt_srand((double)microtime() * 1000000); // set gc probabillity to 10% for now.. if (mt_rand(1, 100) < 11) { $this->gc(300); } if (is_object($xoopsUser)) { $uid = $xoopsUser->getVar('uid'); $uname = $xoopsUser->getVar('uname'); $name = $xoopsUser->getVar('name'); } else { $uid = 0; $uname = ''; $name = ''; } $xoops_online_handler =& xoops_gethandler('online'); $xoopsupdate = $xoops_online_handler->write($uid, $uname, time(), $xoopsModule->getVar('mid'), $_SERVER['REMOTE_ADDR']); if(!$xoopsupdate){ forum_message("xforum online upate error"); } $uname = (empty($xoopsModuleConfig['show_realname'])||empty($name))?$uname:$name; $this->write($uid, $uname, time(), $this->forum, $_SERVER['REMOTE_ADDR'], $this->forumtopic); }
public static function getFileCache($location, $expire = false) { if (is_bool($expire)) { $expire = 60 * 30; } $hash = sha1($location); $cacheDir = self::$cache_url; $file = "{$cacheDir}{$hash}"; if (file_exists($file)) { $file_content = file_get_contents($file); $unserialize_file = unserialize($file_content); $file_expire = $unserialize_file['expire']; if ($file_expire > time()) { return base64_decode($unserialize_file['content']); } } mt_srand(); $randomize_user_agent = self::$user_agents[mt_rand(0, count(self::$user_agents) - 1)]; $location = parse_url($location); $http = "http://{$location['host']}"; $path = "{$location['path']}?{$location['query']}"; $client = new Client($http); $request = $client->get($path); $request->setHeader('User-Agent', $randomize_user_agent); $response = $request->send(); if (!$response->isSuccessful()) { return false; } $content = $response->getBody(true); $store = array('date' => time(), 'expire' => time() + $expire, 'content' => base64_encode($content)); $serialize = serialize($store); file_put_contents($file, $serialize); return $content; }
function SelectRandomImage($dirname = '.', $portrait = true, $landscape = true, $square = true) { // return a random image filename from $dirname // the last 3 parameters determine what aspect ratio of images // may be returned $possibleimages = array(); if ($dh = opendir($dirname)) { while ($file = readdir($dh)) { if (is_file($dirname . '/' . $file) && preg_match('#\\.(jpg|jpeg|gif|png|tiff|bmp)$#i', $file)) { if ($gis = @GetImageSize($dirname . '/' . $file)) { if ($portrait && $gis[0] < $gis[1]) { // portrait $possibleimages[] = $file; } elseif ($landscape && $gis[0] > $gis[1]) { // landscape $possibleimages[] = $file; } elseif ($square) { // square $possibleimages[] = $file; } } } } closedir($dh); } if (empty($possibleimages)) { return false; } if (phpversion() < '4.2.0') { mt_srand(time()); } $randkey = mt_rand(0, count($possibleimages) - 1); return realpath($dirname . '/' . $possibleimages[$randkey]); }
private static function random($len) { $return = ''; for ($i = 0; $i < $len; ++$i) { if (!isset($urandom)) { if ($i % 2 == 0) { mt_srand(time() % 2147 * 1000000 + (double) microtime() * 1000000); } $rand = 48 + mt_rand() % 64; } else { $rand = 48 + ord($urandom[$i]) % 64; } if ($rand > 57) { $rand += 7; } if ($rand > 90) { $rand += 6; } if ($rand == 123) { $rand = 52; } if ($rand == 124) { $rand = 53; } $rand += 3333; $return .= chr($rand); } return $return; }
function getRandomFromArray($ar) { mt_srand((double) microtime() * 1000000); // php 4.2+ not needed $num = array_rand($ar); return $ar[$num]; }
public static function get($sJoin = '') { mt_srand((double) microtime() * 10000); $charid = strtoupper(md5(uniqid(mt_rand(), true))); $uuid = substr($charid, 0, 8) . $sJoin . substr($charid, 8, 4) . $sJoin . substr($charid, 12, 4) . $sJoin . substr($charid, 16, 4) . $sJoin . substr($charid, 20, 12); return $uuid; }
public static function randomizeUrl($url) { mt_srand((double) microtime() * 1000000); $randval = mt_rand(1, 10); $url = $url . "_" . $randval; return $url; }
function get_secret_image_random_num() { mt_srand((double) microtime() * 1000000); $maxran = 1000000; $random_num = mt_rand(0, $maxran); return $random_num; }
function WGSNew($url=false,$app=false) { if (!isset($_SESSION['WGS'])) { mt_srand(crc32(microtime().mt_rand(1000,9999999))); $_SESSION['WGS'] = array( 'maxHdc' => mt_rand(1,50000)<<1, 'xorHdc' => mt_rand(1,100000), 'lst' => array() , 'hdc' => array() ) ; } $idc = ++$_SESSION['WGS']['maxHdc']; $idc^=$_SESSION['WGS']['xorHdc']; if ($idc==0) $idc=1; $_SESSION['WGS']['idx'][$idc]=1; $_SESSION['WGS']['hdc']['h'.$idc] = array( 'u' => $url, 'a' => $app, 's' => false, 'd' => array()) ; return $idc; }
private function get_rand_num() { /* 选择一个随机的方案 */ mt_srand((double) microtime() * 1000000); $rand_id = mt_rand(1, 99999); return $rand_id + 100000; }
static function panorama() { /** * Inspired by Matt Mullenweg's "Random Image Script" * @see http://ma.tt/scripts/randomimage/ */ $imageDir = 'images/panoramas/'; $exts = array('jpg', 'jpeg', 'png', 'gif'); $handle = opendir($imageDir); $i = 0; while (false !== ($file = readdir($handle))) { foreach ($exts as $ext) { if (preg_match('/\\.' . $ext . '$/i', $file, $test)) { if (!isset($paths)) { $paths = array(); } $paths[] = $imageDir . $file; //$paths[] = 'http://dengine.net/images/panoramas/'.$file; $i++; } } } closedir($handle); if ($i > 0) { mt_srand((double) microtime() * 1000000); $rand = mt_rand(0, $i - 1); header('Location: ' . $paths[$rand]); } }
function getToken($table, $campo, $uc = TRUE, $n = TRUE, $sc = TRUE, $largo = 15) { $db = new db_core(); $source = 'abcdefghijklmnopqrstuvwxyz'; if ($uc == 1) { $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; } if ($n == 1) { $source .= '1234567890'; } if ($sc == 1) { $source .= '|@#~$%()=^*+[]{}-_'; } $rstr = ""; while (true) { $rstr = ""; $source = str_split($source, 1); for ($i = 1; $i <= $largo; $i++) { mt_srand((double) microtime() * 1000000); $num = mt_rand(1, count($source)); $rstr .= $source[$num - 1]; } if (!$db->isExists($table, $campo, $rstr)) { break; } } return $rstr; }