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. //TODO
  49. /**
  50. * 1950-01-01 - 2050-12-31
  51. */
  52. public static function date($min = null, $max = null, $formatReturn = null) {
  53. if ($min === null && $max === null)
  54. $res = time();
  55. elseif ($min > 0 && $max === null)
  56. $res = $min;
  57. elseif ($min > 0 && $max > 0)
  58. $res = self::int($min, $max);
  59. else
  60. $res = time();
  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') - (self::int($min, $max));
  93. $dobMonth = self::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. } elseif (in_array($dobMonth, array(4, 6, 9, 11)))
  101. $maxDays = 30;
  102. else
  103. $maxDays = 31;
  104. $dobDay = self::int(1, $maxDays);
  105. $dob = sprintf("%4d-%02d-%02d", $dobYear, $dobMonth, $dobDay);
  106. return $dob;
  107. }
  108. /**
  109. * Generates a password
  110. *
  111. * @param integer $length Password length
  112. * @return string
  113. * @link https://github.com/CakeDC/users/blob/master/models/user.php#L498
  114. */
  115. public static function pronounceablePwd($length = 10) {
  116. srand((double)microtime() * 1000000);
  117. $password = '';
  118. $vowels = array("a", "e", "i", "o", "u");
  119. $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
  120. "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl");
  121. for ($i = 0; $i < $length; $i++) {
  122. $password .= $cons[mt_rand(0, 31)] . $vowels[mt_rand(0, 4)];
  123. }
  124. return substr($password, 0, $length);
  125. }
  126. /**
  127. * @deprecated!
  128. */
  129. public static function pwd($type = null, $length = null) {
  130. return self::randomPwd($type, $length);
  131. }
  132. /**
  133. * Returns auto-generated password
  134. *
  135. * @param string $type: user, ...
  136. * @param integer $length (if no type is submitted)
  137. * @return pwd on success, empty string otherwise
  138. */
  139. public static function randomPwd($type = null, $length = null) {
  140. if (!empty($type) && $type === 'user') {
  141. return self::generatePassword(6);
  142. }
  143. if (!empty($length)) {
  144. return self::generatePassword($length);
  145. }
  146. return '';
  147. }
  148. /**
  149. * //TODO: move to password lib?
  150. * Generate random passwords
  151. *
  152. * @param integer $lenght (necessary!)
  153. * @return string Password
  154. */
  155. public static function generatePassword($length, $chars = null) {
  156. if ($chars === null) {
  157. $chars = '234567890abcdefghijkmnopqrstuvwxyz'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
  158. }
  159. $i = 0;
  160. $password = '';
  161. $max = strlen($chars) - 1;
  162. while ($i < $length) {
  163. $password .= $chars[mt_rand(0, $max)];
  164. $i++;
  165. }
  166. return $password;
  167. }
  168. /**
  169. * 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
  170. * @link http://www.gelembjuk.com/index.php?option=com_content&view=article&id=60&catid=37:php&Itemid=56
  171. */
  172. public static function sentences($sentences, $wordscount = 2) {
  173. $hash = array();
  174. $resultsentences = array();
  175. for ($i = 0; $i < count($sentences); $i++) {
  176. $words = split(' ', trim($sentences[$i]));
  177. for ($k = 0; $k < count($words) - $wordscount; $k++) {
  178. $prefix = trim(join(' ', array_slice($words, $k, $wordscount)));
  179. if ($prefix === '')
  180. continue;
  181. if (empty($hash[$prefix])) {
  182. $hash[$prefix] = array($words[$k + $wordscount]);
  183. for ($j = $i + 1; $j < count($sentences); $j++) {
  184. if (preg_match('/' . ereg_replace('/', '\/', preg_quote($prefix)) . '(.*)$/', $sentences[$j], $m)) {
  185. $w = split(' ', trim($m[1]));
  186. if (count($w) > 0 && trim($w[0]) !== '')
  187. array_push($hash[$prefix], trim($w[0]));
  188. }
  189. }
  190. }
  191. }
  192. }
  193. $prefixes = array_keys($hash);
  194. $stpr = array();
  195. foreach ($prefixes as $pr) {
  196. if ($pr[0] == strtoupper($pr[0]))
  197. array_push($stpr, $pr);
  198. }
  199. for ($i = 0; $i < count($sentences); $i++) {
  200. $p = $stpr[rand(0, count($stpr) - 1)];
  201. $sent = split(' ', $p);
  202. $cc = count(split(' ', $sentences[$i]));
  203. $j = 0;
  204. do {
  205. $w = $hash[$p][rand(0, count($hash[$p]) - 1)];
  206. array_push($sent, $w);
  207. $j++;
  208. $p = join(' ', array_slice($sent, $j, $wordscount));
  209. } while (strrpos($w, '.') != strlen($w) - 1 && $j < $cc * 2);
  210. $sn = join(' ', $sent);
  211. if ($sn[strlen($sn) - 1] !== '.')
  212. $sn .= '.';
  213. array_push($resultsentences, $sn);
  214. }
  215. return $resultsentences;
  216. }
  217. /**
  218. * Other implemantations
  219. */
  220. /**
  221. * Generates a random string of a given type and length.
  222. * $str = Text::random(); // 8 character random string
  223. *
  224. * The following types are supported:
  225. *
  226. * alnum
  227. * : Upper and lower case a-z, 0-9
  228. *
  229. * alpha
  230. * : Upper and lower case a-z
  231. *
  232. * hexdec
  233. * : Hexadecimal characters a-f, 0-9
  234. *
  235. * distinct
  236. * : Uppercase characters and numbers that cannot be confused
  237. *
  238. * You can also create a custom type by providing the "pool" of characters
  239. * as the type.
  240. *
  241. * @param string a type of pool, or a string of characters to use as the pool
  242. * @param integer length of string to return
  243. * @return string
  244. */
  245. public static function random($type = 'alnum', $length = 8) {
  246. switch ($type) {
  247. case 'alnum':
  248. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  249. break;
  250. case 'alpha':
  251. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  252. break;
  253. case 'hexdec':
  254. $pool = '0123456789abcdef';
  255. break;
  256. case 'numeric':
  257. $pool = '0123456789';
  258. break;
  259. case 'nozero':
  260. $pool = '123456789';
  261. break;
  262. case 'distinct':
  263. $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
  264. break;
  265. default:
  266. $pool = (string )$type;
  267. //$utf8 = ! UTF8::is_ascii($pool);
  268. break;
  269. }
  270. // Split the pool into an array of characters
  271. $pool = ($utf8 === true) ? str_split($pool, 1) : str_split($pool, 1);
  272. // Largest pool key
  273. $max = count($pool) - 1;
  274. $str = '';
  275. for ($i = 0; $i < $length; $i++) {
  276. // Select a random character from the pool and add it to the string
  277. $str .= $pool[mt_rand(0, $max)];
  278. }
  279. // Make sure alnum strings contain at least one letter and one digit
  280. if ($type === 'alnum' && $length > 1) {
  281. if (ctype_alpha($str)) {
  282. // Add a random digit
  283. $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57));
  284. } elseif (ctype_digit($str)) {
  285. // Add a random letter
  286. $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90));
  287. }
  288. }
  289. return $str;
  290. }
  291. }