RandomLib.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. /**
  3. * Random Lib
  4. *
  5. * @author Mark Scherer
  6. * @license MIT
  7. */
  8. class RandomLib {
  9. /**
  10. * @param integer $min
  11. * @param integer $max
  12. * @return random int value
  13. */
  14. public static function int($min = 0, $max = 999) {
  15. return mt_rand($min, $max);
  16. }
  17. /**
  18. * @param float $min
  19. * @param float $max
  20. * @return random float value
  21. */
  22. public static function float($min = 0.0, $max = 999.0) {
  23. $rand = rand(1, 358);
  24. return $rand * cos($rand);
  25. }
  26. /**
  27. * Randomly return one of the values provided
  28. * careful: only works with numerical keys (0 based!)
  29. *
  30. * @return mixed
  31. */
  32. public static function arrayValue($array, $minPosition = null, $maxPosition = null, $integerKeys = false) {
  33. if (empty($array)) {
  34. return null;
  35. }
  36. if ($integerKeys) {
  37. $max = count($array) - 1;
  38. return $array[self::int(0, $max)];
  39. }
  40. $keys = array_keys($array);
  41. $values = array_values($array);
  42. $max = count($keys) - 1;
  43. return $values[self::int(0, $max)];
  44. }
  45. public static function arrayValues($array, $minAmount = null, $maxAmount = null) {
  46. //NOT IMPORTANT
  47. }
  48. /**
  49. * 1950-01-01 - 2050-12-31
  50. */
  51. public static function date($min = null, $max = null, $formatReturn = null) {
  52. if ($min === null && $max === null)
  53. $res = time();
  54. elseif ($min > 0 && $max === null)
  55. $res = $min;
  56. elseif ($min > 0 && $max > 0)
  57. $res = self::int($min, $max);
  58. else
  59. $res = time();
  60. $res = 0;
  61. $formatReturnAs = FORMAT_DB_DATETIME;
  62. if ($formatReturn !== null) {
  63. if ($formatReturn === false) {
  64. return $res;
  65. }
  66. $formatReturnAs = $formatReturn;
  67. }
  68. return date($formatReturnAs);
  69. }
  70. //TODO
  71. /**
  72. * 00:00:00 - 23:59:59
  73. */
  74. public static function time($min = null, $max = null, $formatReturn = null) {
  75. $res = 0;
  76. //$returnValueAs = FORMAT_DB_TIME;
  77. if ($formatReturn !== null) {
  78. if ($formatReturn === false) {
  79. return $res;
  80. }
  81. }
  82. }
  83. /**
  84. * Returns a date of birth within the specified age range
  85. *
  86. * @param (int) $min minimum age in years
  87. * @param (int) $max maximum age in years
  88. * @return (string) $dob a db (ISO) format datetime string
  89. */
  90. public static function dob($min = 18, $max = 100) {
  91. $dobYear = date('Y') - (self::int($min, $max));
  92. $dobMonth = self::int(1, 12);
  93. if ($dobMonth == 2) {
  94. // leap year?
  95. if ($ageYears % 4 || $ageYears % 400)
  96. $maxDays = 29;
  97. else
  98. $maxDays = 28;
  99. } elseif (in_array($dobMonth, array(4, 6, 9, 11)))
  100. $maxDays = 30;
  101. else
  102. $maxDays = 31;
  103. $dobDay = self::int(1, $maxDays);
  104. $dob = sprintf("%4d-%02d-%02d", $dobYear, $dobMonth, $dobDay);
  105. return $dob;
  106. }
  107. /**
  108. * Generates a password
  109. *
  110. * @param integer $length Password length
  111. * @return string
  112. * @link https://github.com/CakeDC/users/blob/master/models/user.php#L498
  113. */
  114. public static function pronounceablePwd($length = 10) {
  115. srand((double)microtime() * 1000000);
  116. $password = '';
  117. $vowels = array("a", "e", "i", "o", "u");
  118. $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
  119. "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl");
  120. for ($i = 0; $i < $length; $i++) {
  121. $password .= $cons[mt_rand(0, 31)] . $vowels[mt_rand(0, 4)];
  122. }
  123. return substr($password, 0, $length);
  124. }
  125. /**
  126. * @deprecated!
  127. */
  128. public static function pwd($type = null, $length = null) {
  129. return self::randomPwd($type, $length);
  130. }
  131. /**
  132. * Returns auto-generated password
  133. *
  134. * @param string $type: user, ...
  135. * @param integer $length (if no type is submitted)
  136. * @return pwd on success, empty string otherwise
  137. */
  138. public static function randomPwd($type = null, $length = null) {
  139. if (!empty($type) && $type === 'user') {
  140. return self::generatePassword(6);
  141. }
  142. if (!empty($length)) {
  143. return self::generatePassword($length);
  144. }
  145. return '';
  146. }
  147. /**
  148. * //TODO: move to password lib?
  149. * Generate random passwords
  150. *
  151. * @param integer $lenght (necessary!)
  152. * @return string Password
  153. */
  154. public static function generatePassword($length, $chars = null) {
  155. if ($chars === null) {
  156. $chars = '234567890abcdefghijkmnopqrstuvwxyz'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
  157. }
  158. $i = 0;
  159. $password = '';
  160. $max = strlen($chars) - 1;
  161. while ($i < $length) {
  162. $password .= $chars[mt_rand(0, $max)];
  163. $i++;
  164. }
  165. return $password;
  166. }
  167. /**
  168. * Few years ago i had written Joomla component AutoContent. That component generates new unique content and add it to Joomla site. In general, this is not good tool, because it does black SEO things. If search engine (ex. Google) finds that there is autogenerated text without sense then site can be banned
  169. * @link http://www.gelembjuk.com/index.php?option=com_content&view=article&id=60&catid=37:php&Itemid=56
  170. */
  171. public static function sentences($sentences, $wordscount = 2) {
  172. $hash = array();
  173. $resultsentences = array();
  174. for ($i = 0; $i < count($sentences); $i++) {
  175. $words = split(' ', trim($sentences[$i]));
  176. for ($k = 0; $k < count($words) - $wordscount; $k++) {
  177. $prefix = trim(join(' ', array_slice($words, $k, $wordscount)));
  178. if ($prefix === '')
  179. continue;
  180. if (empty($hash[$prefix])) {
  181. $hash[$prefix] = array($words[$k + $wordscount]);
  182. for ($j = $i + 1; $j < count($sentences); $j++) {
  183. if (preg_match('/' . ereg_replace('/', '\/', preg_quote($prefix)) . '(.*)$/', $sentences[$j], $m)) {
  184. $w = split(' ', trim($m[1]));
  185. if (count($w) > 0 && trim($w[0]) !== '')
  186. array_push($hash[$prefix], trim($w[0]));
  187. }
  188. }
  189. }
  190. }
  191. }
  192. $prefixes = array_keys($hash);
  193. $stpr = array();
  194. foreach ($prefixes as $pr) {
  195. if ($pr[0] == strtoupper($pr[0]))
  196. array_push($stpr, $pr);
  197. }
  198. for ($i = 0; $i < count($sentences); $i++) {
  199. $p = $stpr[rand(0, count($stpr) - 1)];
  200. $sent = split(' ', $p);
  201. $cc = count(split(' ', $sentences[$i]));
  202. $j = 0;
  203. do {
  204. $w = $hash[$p][rand(0, count($hash[$p]) - 1)];
  205. array_push($sent, $w);
  206. $j++;
  207. $p = join(' ', array_slice($sent, $j, $wordscount));
  208. } while (strrpos($w, '.') != strlen($w) - 1 && $j < $cc * 2);
  209. $sn = join(' ', $sent);
  210. if ($sn[strlen($sn) - 1] !== '.')
  211. $sn .= '.';
  212. array_push($resultsentences, $sn);
  213. }
  214. return $resultsentences;
  215. }
  216. /**
  217. * Other implemantations
  218. */
  219. /**
  220. * Generates a random string of a given type and length.
  221. * $str = Text::random(); // 8 character random string
  222. *
  223. * The following types are supported:
  224. *
  225. * alnum
  226. * : Upper and lower case a-z, 0-9
  227. *
  228. * alpha
  229. * : Upper and lower case a-z
  230. *
  231. * hexdec
  232. * : Hexadecimal characters a-f, 0-9
  233. *
  234. * distinct
  235. * : Uppercase characters and numbers that cannot be confused
  236. *
  237. * You can also create a custom type by providing the "pool" of characters
  238. * as the type.
  239. *
  240. * @param string a type of pool, or a string of characters to use as the pool
  241. * @param integer length of string to return
  242. * @return string
  243. */
  244. public static function random($type = 'alnum', $length = 8) {
  245. switch ($type) {
  246. case 'alnum':
  247. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  248. break;
  249. case 'alpha':
  250. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  251. break;
  252. case 'hexdec':
  253. $pool = '0123456789abcdef';
  254. break;
  255. case 'numeric':
  256. $pool = '0123456789';
  257. break;
  258. case 'nozero':
  259. $pool = '123456789';
  260. break;
  261. case 'distinct':
  262. $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
  263. break;
  264. default:
  265. $pool = (string )$type;
  266. //$utf8 = ! UTF8::is_ascii($pool);
  267. break;
  268. }
  269. // Split the pool into an array of characters
  270. $pool = ($utf8 === true) ? str_split($pool, 1) : str_split($pool, 1);
  271. // Largest pool key
  272. $max = count($pool) - 1;
  273. $str = '';
  274. for ($i = 0; $i < $length; $i++) {
  275. // Select a random character from the pool and add it to the string
  276. $str .= $pool[mt_rand(0, $max)];
  277. }
  278. // Make sure alnum strings contain at least one letter and one digit
  279. if ($type === 'alnum' && $length > 1) {
  280. if (ctype_alpha($str)) {
  281. // Add a random digit
  282. $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57));
  283. } elseif (ctype_digit($str)) {
  284. // Add a random letter
  285. $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90));
  286. }
  287. }
  288. return $str;
  289. }
  290. }