RandomLib.php 8.2 KB

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