PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/app/lib/Spaph/Fn.php

https://bitbucket.org/getpsimon/spaph
PHP | 295 lines | 183 code | 25 blank | 87 comment | 43 complexity | d8c8a85f5c14338e562326c2d83e7ee6 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * This is a simple collection of helpful functions.
  4. *
  5. *
  6. */
  7. class Spaph_Fn {
  8. /**
  9. * var_export a variable as preformatted html.
  10. *
  11. * @input mixed $data
  12. * @return string
  13. */
  14. public static function dump($data)
  15. {
  16. return sprintf('<pre class="spaph-dump">%s</pre>',htmlspecialchars(var_export($data,true)));
  17. }
  18. /**
  19. * This is from memic post at php.net uniqid.
  20. *
  21. * @param string $separate
  22. * @return string
  23. */
  24. public static function uuid4($separate='')
  25. {
  26. return sprintf( "%04x%04x%s%04x%s%04x%s%04x%s%04x%04x%04x",
  27. mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), $separate, mt_rand( 0, 0xffff ), $separate,
  28. mt_rand( 0, 0x0fff ) | 0x4000, $separate,
  29. mt_rand( 0, 0x3fff ) | 0x8000, $separate,
  30. mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
  31. }
  32. /**
  33. * Wrapper around uuid functions.
  34. */
  35. public static function uuid()
  36. {
  37. return new Spaph_Fn_UUID();
  38. }
  39. /**
  40. * The returned string can be stored in a database.
  41. *
  42. * @param string $password
  43. * @return string
  44. */
  45. public static function hashpwd($password,$salt=null)
  46. {
  47. if(!isset($salt)) {
  48. $salt = '$2a$16$'.substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22);
  49. }
  50. return crypt($password,$salt);
  51. }
  52. /**
  53. * Check pwd against stored pwd.
  54. *
  55. * @param string $check_pwd
  56. * @param string $store_pwd
  57. * @return boolean
  58. */
  59. public static function checkpwd($check_pwd,$store_pwd)
  60. {
  61. return ( crypt($check_pwd,$store_pwd) == $store_pwd );
  62. }
  63. public static function shard($hex,$num_of_domains=2)
  64. {
  65. // Spread Users across domains. The domains must start with zero. So, if $num_of_domains
  66. // is 16 then there ought to be Domain0, Domain1, ...Domain15 (16 Domains total).
  67. // This must be a number that as binary has all its bits set to 1: 2,4,16...
  68. // num_of_domains 16; // 2^2, 2^4, 2^5, 2^6, 2^7, 2^8, ...
  69. // Convert the number of available domains (minus 1) into binary
  70. $num_of_domains_binary = base_convert($num_of_domains-1,10,2);
  71. // Sanity check
  72. if(!preg_match('/^1+$/',$num_of_domains_binary)) {
  73. throw new Exception("The number of domains ($num_of_domains), as binary, does not have all bits set to 1 ($num_of_domains_binary).");
  74. }
  75. // Get the 8 right most hexadecimal digits and convert it to a zero padded binary number.
  76. // for example, 6b4cc7b2 = 01101011010011001100011110110010
  77. $lsb_32 = sprintf("%032s",base_convert(substr($hex, -8),16,2));
  78. // Grab the right most binary digits we are interested in and convert that to decimal.
  79. // The decimal number must be between 0 and $num_of_domains-1
  80. $domain = base_convert(substr($lsb_32, -strlen($num_of_domains_binary)),2,10);
  81. // Here is the Domain!
  82. return $domain;
  83. }
  84. /**
  85. * http://stackoverflow.com/questions/997078/email-regular-expression
  86. */
  87. public static function validEmail($email, $skipDNS = false)
  88. {
  89. $isValid = true;
  90. $atIndex = strrpos($email, "@");
  91. if (is_bool($atIndex) && !$atIndex)
  92. {
  93. $isValid = false;
  94. }
  95. else
  96. {
  97. $domain = substr($email, $atIndex+1);
  98. $local = substr($email, 0, $atIndex);
  99. $localLen = strlen($local);
  100. $domainLen = strlen($domain);
  101. if ($localLen < 1 || $localLen > 64)
  102. {
  103. // local part length exceeded
  104. $isValid = false;
  105. }
  106. else if ($domainLen < 1 || $domainLen > 255)
  107. {
  108. // domain part length exceeded
  109. $isValid = false;
  110. }
  111. else if ($local[0] == '.' || $local[$localLen-1] == '.')
  112. {
  113. // local part starts or ends with '.'
  114. $isValid = false;
  115. }
  116. else if (preg_match('/\\.\\./', $local))
  117. {
  118. // local part has two consecutive dots
  119. $isValid = false;
  120. }
  121. else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
  122. {
  123. // character not valid in domain part
  124. $isValid = false;
  125. }
  126. else if (preg_match('/\\.\\./', $domain))
  127. {
  128. // domain part has two consecutive dots
  129. $isValid = false;
  130. }
  131. else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
  132. {
  133. // character not valid in local part unless
  134. // local part is quoted
  135. if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
  136. {
  137. $isValid = false;
  138. }
  139. }
  140. if(!$skipDNS)
  141. {
  142. if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
  143. {
  144. // domain not found in DNS
  145. $isValid = false;
  146. }
  147. }
  148. }
  149. return $isValid;
  150. }
  151. public static function randomStr($length=8)
  152. {
  153. $chars = '=bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ23456789%';
  154. $num_chars = strlen($chars);
  155. $result = '';
  156. for($i=0; $i<$length; $i++) {
  157. $result .= $chars[rand(0,$num_chars-1)];
  158. }
  159. return $result;
  160. }
  161. /**
  162. * Destroy php session convincingly.
  163. */
  164. public static function dSession()
  165. {
  166. $_SESSION = array();
  167. $ck = session_get_cookie_params();
  168. setcookie(session_name(), '', time()-2592000, $ck['path'], $ck['domain'], $ck['secure']);
  169. unset($_COOKIE[session_name()]);
  170. session_destroy();
  171. }
  172. /**
  173. * getBytes
  174. *
  175. * Convert G,M,K to bytes. Call like Spaph_Fn::getBytes('20M');
  176. *
  177. * @param string
  178. * @return integer
  179. */
  180. public static function getBytes($val) {
  181. $val = trim($val);
  182. $val = str_ireplace('B', '', $val); // Remove B from instances of KB,MB,GB
  183. if(!$val) {
  184. return;
  185. }
  186. $last = strtolower($val[strlen($val)-1]);
  187. switch($last) {
  188. // The 'G' modifier is available since PHP 5.1.0
  189. case 'g':
  190. $val *= 1024;
  191. case 'm':
  192. $val *= 1024;
  193. case 'k':
  194. $val *= 1024;
  195. }
  196. return $val;
  197. }
  198. /**
  199. * FormatByteSize
  200. *
  201. * Convert bytes into KB,MB,GB.
  202. *
  203. * @param integer
  204. * @return string
  205. */
  206. public static function FormatByteSize($bytes)
  207. {
  208. $size = $bytes / 1024;
  209. $sig = '';
  210. if($size < 1024) {
  211. $size = number_format($size, 2);
  212. $sig = 'KB';
  213. }
  214. else {
  215. if($size / 1024 < 1024) {
  216. $size = number_format($size / 1024, 2);
  217. $sig = 'MB';
  218. }
  219. else if ($size / 1024 / 1024 < 1024) {
  220. $size = number_format($size / 1024 / 1024, 2);
  221. $sig = 'GB';
  222. }
  223. }
  224. return floor($size).$sig;
  225. //$size = preg_replace('/\.00/','',$size);
  226. }
  227. /**
  228. * http://www.technischedaten.de/pmwiki2/pmwiki.php?n=Php.BaseConvert
  229. *
  230. * // Convert number from base 10 to base 36.
  231. * bc_base_convert(232456,10,36)
  232. *
  233. * @param integer $value
  234. * @param integer $quellformat 2-62
  235. * @param integer $zielformat 2-62
  236. */
  237. function bc_base_convert($value,$quellformat,$zielformat)
  238. {
  239. $vorrat = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  240. if(max($quellformat,$zielformat) > strlen($vorrat))
  241. trigger_error('Bad Format max: '.strlen($vorrat),E_USER_ERROR);
  242. if(min($quellformat,$zielformat) < 2)
  243. trigger_error('Bad Format min: 2',E_USER_ERROR);
  244. $dezi = '0';
  245. $level = 0;
  246. $result = '';
  247. $value = trim((string)$value,"\r\n\t +");
  248. $vorzeichen = '-' === $value{0}?'-':'';
  249. $value = ltrim($value,"-0");
  250. $len = strlen($value);
  251. for($i=0;$i<$len;$i++)
  252. {
  253. $wert = strpos($vorrat,$value{$len-1-$i});
  254. if(FALSE === $wert) trigger_error('Bad Char in input 1',E_USER_ERROR);
  255. if($wert >= $quellformat) trigger_error('Bad Char in input 2',E_USER_ERROR);
  256. $dezi = bcadd($dezi,bcmul(bcpow($quellformat,$i),$wert));
  257. }
  258. if(10 == $zielformat) return $vorzeichen.$dezi; // abk?
  259. while(1 !== bccomp(bcpow($zielformat,$level++),$dezi));
  260. for($i=$level-2;$i>=0;$i--)
  261. {
  262. $factor = bcpow($zielformat,$i);
  263. $zahl = bcdiv($dezi,$factor,0);
  264. $dezi = bcmod($dezi,$factor);
  265. $result .= $vorrat{$zahl};
  266. }
  267. $result = empty($result)?'0':$result;
  268. return $vorzeichen.$result ;
  269. }
  270. }