RandomLib.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. /**
  3. * Random Lib
  4. *
  5. * @author Mark Scherer
  6. * @license 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. $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') - (static::int($min, $max));
  92. $dobMonth = static::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 = static::int(1, $maxDays);
  104. $dob = sprintf("%4d-%02d-%02d", $dobYear, $dobMonth, $dobDay);
  105. return $dob;
  106. }
  107. /**
  108. * Generates a password
  109. *
  110. * @param int $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. * Returns auto-generated password
  127. *
  128. * @param string $type: user, ...
  129. * @param int $length (if no type is submitted)
  130. * @return pwd on success, empty string otherwise
  131. */
  132. public static function pwd($type = null, $length = null) {
  133. if (!empty($type) && $type === 'user') {
  134. return static::generatePassword(6);
  135. }
  136. if (!empty($length)) {
  137. return static::generatePassword($length);
  138. }
  139. return '';
  140. }
  141. /**
  142. * Returns auto-generated password
  143. *
  144. * @param string $type: user, ...
  145. * @param int $length (if no type is submitted)
  146. * @return pwd on success, empty string otherwise
  147. * @deprecated Use pwd() instead
  148. */
  149. public static function randomPwd($type = null, $length = null) {
  150. return static::pwd($type, $length);
  151. }
  152. /**
  153. * Generates random passwords.
  154. * //TODO: move to password lib?
  155. *
  156. * @param int $lenght (necessary!)
  157. * @return string Password
  158. */
  159. public static function generatePassword($length, $chars = null) {
  160. if ($chars === null) {
  161. $chars = '234567890abcdefghijkmnopqrstuvwxyz'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
  162. }
  163. $i = 0;
  164. $password = '';
  165. $max = strlen($chars) - 1;
  166. while ($i < $length) {
  167. $password .= $chars[mt_rand(0, $max)];
  168. $i++;
  169. }
  170. return $password;
  171. }
  172. /**
  173. * 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
  174. * @link http://www.gelembjuk.com/index.php?option=com_content&view=article&id=60&catid=37:php&Itemid=56
  175. */
  176. public static function sentences($sentences, $wordscount = 2) {
  177. $hash = array();
  178. $resultsentences = array();
  179. for ($i = 0; $i < count($sentences); $i++) {
  180. $words = split(' ', trim($sentences[$i]));
  181. for ($k = 0; $k < count($words) - $wordscount; $k++) {
  182. $prefix = trim(join(' ', array_slice($words, $k, $wordscount)));
  183. if ($prefix === '')
  184. continue;
  185. if (empty($hash[$prefix])) {
  186. $hash[$prefix] = array($words[$k + $wordscount]);
  187. for ($j = $i + 1; $j < count($sentences); $j++) {
  188. if (preg_match('/' . ereg_replace('/', '\/', preg_quote($prefix)) . '(.*)$/', $sentences[$j], $m)) {
  189. $w = split(' ', trim($m[1]));
  190. if (count($w) > 0 && trim($w[0]) !== '')
  191. array_push($hash[$prefix], trim($w[0]));
  192. }
  193. }
  194. }
  195. }
  196. }
  197. $prefixes = array_keys($hash);
  198. $stpr = array();
  199. foreach ($prefixes as $pr) {
  200. if ($pr[0] == strtoupper($pr[0]))
  201. array_push($stpr, $pr);
  202. }
  203. for ($i = 0; $i < count($sentences); $i++) {
  204. $p = $stpr[rand(0, count($stpr) - 1)];
  205. $sent = split(' ', $p);
  206. $cc = count(split(' ', $sentences[$i]));
  207. $j = 0;
  208. do {
  209. $w = $hash[$p][rand(0, count($hash[$p]) - 1)];
  210. array_push($sent, $w);
  211. $j++;
  212. $p = join(' ', array_slice($sent, $j, $wordscount));
  213. } while (strrpos($w, '.') != strlen($w) - 1 && $j < $cc * 2);
  214. $sn = join(' ', $sent);
  215. if ($sn[strlen($sn) - 1] !== '.')
  216. $sn .= '.';
  217. array_push($resultsentences, $sn);
  218. }
  219. return $resultsentences;
  220. }
  221. /**
  222. * Other implemantations
  223. */
  224. /**
  225. * Generates a random string of a given type and length.
  226. * $str = Text::random(); // 8 character random string
  227. *
  228. * The following types are supported:
  229. *
  230. * alnum
  231. * : Upper and lower case a-z, 0-9
  232. *
  233. * alpha
  234. * : Upper and lower case a-z
  235. *
  236. * hexdec
  237. * : Hexadecimal characters a-f, 0-9
  238. *
  239. * distinct
  240. * : Uppercase characters and numbers that cannot be confused
  241. *
  242. * You can also create a custom type by providing the "pool" of characters
  243. * as the type.
  244. *
  245. * @param string a type of pool, or a string of characters to use as the pool
  246. * @param int length of string to return
  247. * @return string
  248. */
  249. public static function random($type = 'alnum', $length = 8) {
  250. switch ($type) {
  251. case 'alnum':
  252. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  253. break;
  254. case 'alpha':
  255. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  256. break;
  257. case 'hexdec':
  258. $pool = '0123456789abcdef';
  259. break;
  260. case 'numeric':
  261. $pool = '0123456789';
  262. break;
  263. case 'nozero':
  264. $pool = '123456789';
  265. break;
  266. case 'distinct':
  267. $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
  268. break;
  269. default:
  270. $pool = (string)$type;
  271. break;
  272. }
  273. // Split the pool into an array of characters
  274. $pool = str_split($pool, 1);
  275. // Largest pool key
  276. $max = count($pool) - 1;
  277. $str = '';
  278. for ($i = 0; $i < $length; $i++) {
  279. // Select a random character from the pool and add it to the string
  280. $str .= $pool[mt_rand(0, $max)];
  281. }
  282. // Make sure alnum strings contain at least one letter and one digit
  283. if ($type === 'alnum' && $length > 1) {
  284. if (ctype_alpha($str)) {
  285. // Add a random digit
  286. $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57));
  287. } elseif (ctype_digit($str)) {
  288. // Add a random letter
  289. $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90));
  290. }
  291. }
  292. return $str;
  293. }
  294. }