/app/lib/Spaph/Fn.php
PHP | 295 lines | 183 code | 25 blank | 87 comment | 43 complexity | d8c8a85f5c14338e562326c2d83e7ee6 MD5 | raw file
Possible License(s): BSD-3-Clause
- <?php
- /**
- * This is a simple collection of helpful functions.
- *
- *
- */
- class Spaph_Fn {
- /**
- * var_export a variable as preformatted html.
- *
- * @input mixed $data
- * @return string
- */
- public static function dump($data)
- {
- return sprintf('<pre class="spaph-dump">%s</pre>',htmlspecialchars(var_export($data,true)));
- }
- /**
- * This is from memic post at php.net uniqid.
- *
- * @param string $separate
- * @return string
- */
- public static function uuid4($separate='')
- {
- return sprintf( "%04x%04x%s%04x%s%04x%s%04x%s%04x%04x%04x",
- mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), $separate, mt_rand( 0, 0xffff ), $separate,
- mt_rand( 0, 0x0fff ) | 0x4000, $separate,
- mt_rand( 0, 0x3fff ) | 0x8000, $separate,
- mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
- }
- /**
- * Wrapper around uuid functions.
- */
- public static function uuid()
- {
- return new Spaph_Fn_UUID();
- }
- /**
- * The returned string can be stored in a database.
- *
- * @param string $password
- * @return string
- */
- public static function hashpwd($password,$salt=null)
- {
- if(!isset($salt)) {
- $salt = '$2a$16$'.substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22);
- }
- return crypt($password,$salt);
- }
- /**
- * Check pwd against stored pwd.
- *
- * @param string $check_pwd
- * @param string $store_pwd
- * @return boolean
- */
- public static function checkpwd($check_pwd,$store_pwd)
- {
- return ( crypt($check_pwd,$store_pwd) == $store_pwd );
- }
- public static function shard($hex,$num_of_domains=2)
- {
- // Spread Users across domains. The domains must start with zero. So, if $num_of_domains
- // is 16 then there ought to be Domain0, Domain1, ...Domain15 (16 Domains total).
- // This must be a number that as binary has all its bits set to 1: 2,4,16...
- // num_of_domains 16; // 2^2, 2^4, 2^5, 2^6, 2^7, 2^8, ...
- // Convert the number of available domains (minus 1) into binary
- $num_of_domains_binary = base_convert($num_of_domains-1,10,2);
- // Sanity check
- if(!preg_match('/^1+$/',$num_of_domains_binary)) {
- throw new Exception("The number of domains ($num_of_domains), as binary, does not have all bits set to 1 ($num_of_domains_binary).");
- }
- // Get the 8 right most hexadecimal digits and convert it to a zero padded binary number.
- // for example, 6b4cc7b2 = 01101011010011001100011110110010
- $lsb_32 = sprintf("%032s",base_convert(substr($hex, -8),16,2));
- // Grab the right most binary digits we are interested in and convert that to decimal.
- // The decimal number must be between 0 and $num_of_domains-1
- $domain = base_convert(substr($lsb_32, -strlen($num_of_domains_binary)),2,10);
- // Here is the Domain!
- return $domain;
- }
- /**
- * http://stackoverflow.com/questions/997078/email-regular-expression
- */
- public static function validEmail($email, $skipDNS = false)
- {
- $isValid = true;
- $atIndex = strrpos($email, "@");
- if (is_bool($atIndex) && !$atIndex)
- {
- $isValid = false;
- }
- else
- {
- $domain = substr($email, $atIndex+1);
- $local = substr($email, 0, $atIndex);
- $localLen = strlen($local);
- $domainLen = strlen($domain);
- if ($localLen < 1 || $localLen > 64)
- {
- // local part length exceeded
- $isValid = false;
- }
- else if ($domainLen < 1 || $domainLen > 255)
- {
- // domain part length exceeded
- $isValid = false;
- }
- else if ($local[0] == '.' || $local[$localLen-1] == '.')
- {
- // local part starts or ends with '.'
- $isValid = false;
- }
- else if (preg_match('/\\.\\./', $local))
- {
- // local part has two consecutive dots
- $isValid = false;
- }
- else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
- {
- // character not valid in domain part
- $isValid = false;
- }
- else if (preg_match('/\\.\\./', $domain))
- {
- // domain part has two consecutive dots
- $isValid = false;
- }
- else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
- {
- // character not valid in local part unless
- // local part is quoted
- if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
- {
- $isValid = false;
- }
- }
-
- if(!$skipDNS)
- {
- if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
- {
- // domain not found in DNS
- $isValid = false;
- }
- }
- }
- return $isValid;
- }
- public static function randomStr($length=8)
- {
- $chars = '=bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ23456789%';
- $num_chars = strlen($chars);
- $result = '';
- for($i=0; $i<$length; $i++) {
- $result .= $chars[rand(0,$num_chars-1)];
- }
- return $result;
- }
-
- /**
- * Destroy php session convincingly.
- */
- public static function dSession()
- {
- $_SESSION = array();
- $ck = session_get_cookie_params();
- setcookie(session_name(), '', time()-2592000, $ck['path'], $ck['domain'], $ck['secure']);
- unset($_COOKIE[session_name()]);
- session_destroy();
- }
-
- /**
- * getBytes
- *
- * Convert G,M,K to bytes. Call like Spaph_Fn::getBytes('20M');
- *
- * @param string
- * @return integer
- */
- public static function getBytes($val) {
- $val = trim($val);
- $val = str_ireplace('B', '', $val); // Remove B from instances of KB,MB,GB
-
- if(!$val) {
- return;
- }
-
- $last = strtolower($val[strlen($val)-1]);
- switch($last) {
- // The 'G' modifier is available since PHP 5.1.0
- case 'g':
- $val *= 1024;
- case 'm':
- $val *= 1024;
- case 'k':
- $val *= 1024;
- }
- return $val;
- }
- /**
- * FormatByteSize
- *
- * Convert bytes into KB,MB,GB.
- *
- * @param integer
- * @return string
- */
- public static function FormatByteSize($bytes)
- {
- $size = $bytes / 1024;
- $sig = '';
- if($size < 1024) {
- $size = number_format($size, 2);
- $sig = 'KB';
- }
- else {
- if($size / 1024 < 1024) {
- $size = number_format($size / 1024, 2);
- $sig = 'MB';
- }
- else if ($size / 1024 / 1024 < 1024) {
- $size = number_format($size / 1024 / 1024, 2);
- $sig = 'GB';
- }
- }
- return floor($size).$sig;
- //$size = preg_replace('/\.00/','',$size);
- }
- /**
- * http://www.technischedaten.de/pmwiki2/pmwiki.php?n=Php.BaseConvert
- *
- * // Convert number from base 10 to base 36.
- * bc_base_convert(232456,10,36)
- *
- * @param integer $value
- * @param integer $quellformat 2-62
- * @param integer $zielformat 2-62
- */
- function bc_base_convert($value,$quellformat,$zielformat)
- {
- $vorrat = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- if(max($quellformat,$zielformat) > strlen($vorrat))
- trigger_error('Bad Format max: '.strlen($vorrat),E_USER_ERROR);
- if(min($quellformat,$zielformat) < 2)
- trigger_error('Bad Format min: 2',E_USER_ERROR);
- $dezi = '0';
- $level = 0;
- $result = '';
- $value = trim((string)$value,"\r\n\t +");
- $vorzeichen = '-' === $value{0}?'-':'';
- $value = ltrim($value,"-0");
- $len = strlen($value);
- for($i=0;$i<$len;$i++)
- {
- $wert = strpos($vorrat,$value{$len-1-$i});
- if(FALSE === $wert) trigger_error('Bad Char in input 1',E_USER_ERROR);
- if($wert >= $quellformat) trigger_error('Bad Char in input 2',E_USER_ERROR);
- $dezi = bcadd($dezi,bcmul(bcpow($quellformat,$i),$wert));
- }
- if(10 == $zielformat) return $vorzeichen.$dezi; // abk?
- while(1 !== bccomp(bcpow($zielformat,$level++),$dezi));
- for($i=$level-2;$i>=0;$i--)
- {
- $factor = bcpow($zielformat,$i);
- $zahl = bcdiv($dezi,$factor,0);
- $dezi = bcmod($dezi,$factor);
- $result .= $vorrat{$zahl};
- }
- $result = empty($result)?'0':$result;
- return $vorzeichen.$result ;
- }
- }