PageRenderTime 37ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/resources/classes/Utils.class.php

https://gitlab.com/adamlwalker/generatedata
PHP | 415 lines | 282 code | 43 blank | 90 comment | 58 complexity | 0ebe105fcb8c5e87662913aa8e85b9c0 MD5 | raw file
  1. <?php
  2. /**
  3. * Utility functions for use throughout the script.
  4. * @author Ben Keen <ben.keen@gmail.com>
  5. * @package Core
  6. */
  7. class Utils {
  8. // the Utils class memoizes a bunch of stuff to improve speed
  9. static $charLengthMemoized = false;
  10. static $letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  11. static $consonants = "BCDFGHJKLMNPQRSTVWXYZ";
  12. static $vowels = "AEIOU";
  13. static $hex = "0123456789ABCDEF";
  14. static $lettersLen;
  15. static $consonantsLen;
  16. static $vowelsLen;
  17. static $hexLen;
  18. static $lipsumMemoized = false;
  19. static $lipsum;
  20. public static function cleanHash($hash) {
  21. $cleanHash = $hash;
  22. if (get_magic_quotes_gpc()) {
  23. while (list($key, $value) = each($hash)) {
  24. if (!is_array($value)) {
  25. $cleanHash[$key] = stripslashes($value);
  26. } else {
  27. $cleanArray = array();
  28. foreach ($value as $val) {
  29. $cleanArray[] = stripslashes($val);
  30. }
  31. $cleanHash[$key] = $cleanArray;
  32. }
  33. }
  34. }
  35. return $cleanHash;
  36. }
  37. /**
  38. * A generic assertion function used to confirm the existence of things like the existence of values in $_POST,
  39. * $_GET, $_SESSIONS, whether the user is logged in and so on. If it fails anything, it throws a GDException,
  40. * otherwise it does nothing.
  41. * @param $statements
  42. * @throws GDException
  43. */
  44. public static function assert($statements) {
  45. if (empty($statements)) {
  46. return;
  47. }
  48. while (list($test, $values) = each($statements)) {
  49. switch ($test) {
  50. case "loggedIn":
  51. if (empty(Core::$user)) {
  52. throw new GDException(Exceptions::NOTLOGGEDIN);
  53. return;
  54. }
  55. break;
  56. case "noSettingsFile":
  57. $settingsFileAndPath = realpath(__DIR__ . "/../settings.php");
  58. $settingsFileExists = file_exists($settingsFileAndPath);
  59. if ($values === true && $settingsFileExists) {
  60. throw new GDException(Exceptions::SETTINGSFILEEXISTS);
  61. }
  62. break;
  63. }
  64. }
  65. }
  66. /**
  67. * Recursively sanitizes data stored in any non-object data format, preparing it
  68. * for safe use in SQL statements.
  69. */
  70. public static function sanitize($input) {
  71. if (is_array($input)) {
  72. $output = array();
  73. foreach ($input as $k=>$i) {
  74. $output[$k] = Utils::sanitize($i);
  75. }
  76. } else {
  77. if (get_magic_quotes_gpc()) {
  78. $output = stripslashes($input);
  79. } else {
  80. $output = $input;
  81. }
  82. }
  83. return $output;
  84. }
  85. /**
  86. * Returns a random subset of an array. The result may be empty, or the same set.
  87. *
  88. * @param array $set set of items
  89. * @param integer $num the number of items in the set to return
  90. * @return array
  91. * @throws Exception
  92. */
  93. public static function returnRandomSubset($set, $num) {
  94. if (!is_array($set) || !is_numeric($num)) {
  95. throw new Exception(ErrorCodes::INVALID_PARAMS);
  96. return;
  97. }
  98. // check $num is no greater than the total set
  99. $numInSet = count($set);
  100. if ($num > $numInSet) {
  101. $num = $numInSet;
  102. }
  103. shuffle($set);
  104. return array_slice($set, 0, $num);
  105. }
  106. /**
  107. * Converts a datetime to a timestamp.
  108. * @param $datetime
  109. * @return int
  110. */
  111. public static function convertDatetimeToTimestamp($datetime) {
  112. list($date, $time) = explode(" ", $datetime);
  113. list($year, $month, $day) = explode("-", $date);
  114. list($hours, $minutes, $seconds) = explode(":", $time);
  115. return mktime($hours, $minutes, $seconds, $month, $day, $year);
  116. }
  117. /**
  118. * @return string
  119. */
  120. public static function getCurrentDatetime() {
  121. return date("Y-m-d H:i:s");
  122. }
  123. /**
  124. * Adds years to a MySQL datetime & returns a UNIX timestamp of the new date
  125. */
  126. public static function addYearsToDatetime($datetime, $yearsToAdd) {
  127. list($date, $time) = explode(" ", $datetime);
  128. list($year, $month, $day) = explode("-", $date);
  129. list($hours, $minutes, $seconds) = explode(":", $time);
  130. return mktime($hours, $minutes, $seconds, $month, $day, $year+$yearsToAdd);
  131. }
  132. /**
  133. * This function is like rand, only allows it to be weighted.
  134. *
  135. * @param $weightedValues
  136. * @return int|string
  137. */
  138. public static function weightedRand($weightedValues) {
  139. $rand = mt_rand(1, (int) array_sum($weightedValues));
  140. foreach ($weightedValues as $key => $value) {
  141. $rand -= $value;
  142. if ($rand <= 0) {
  143. return $key;
  144. }
  145. }
  146. }
  147. /**
  148. * A security-related function. This returns a clean version of PHP_SELF for use in the templates. This wards
  149. * against URI Cross-site scripting attacks.
  150. *
  151. * @return the cleaned $_SERVER["PHP_SELF"]
  152. */
  153. public static function getCleanPhpSelf() {
  154. return htmlspecialchars(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES);
  155. }
  156. /**
  157. * Converts the following characters in the parameter string and returns it:
  158. *
  159. * C, c, A - any consonant (Upper case, lower case, any)
  160. * V, v, B - any vowel (Upper case, lower case, any)
  161. * L, l, D - any letter (Upper case, lower case, any)
  162. * X - 1-9
  163. * x - 0-9
  164. * H - 0-F
  165. *
  166. * @param string
  167. * @return string
  168. */
  169. static public function generateRandomAlphanumericStr($str) {
  170. // simple memoization to GREATLY increase speed for this heavily-relied on function
  171. if (!self::$charLengthMemoized) {
  172. self::$lettersLen = strlen(self::$letters);
  173. self::$consonantsLen = strlen(self::$consonants);
  174. self::$vowelsLen = strlen(self::$vowels);
  175. self::$hexLen = strlen(self::$hex);
  176. self::$charLengthMemoized = true;
  177. }
  178. // loop through each character and convert all unescaped X's to 1-9 and
  179. // unescaped x's to 0-9.
  180. $new_str = "";
  181. $strlen = strlen($str);
  182. for ($i=0; $i<$strlen; $i++) {
  183. switch ($str[$i]) {
  184. // Numbers
  185. case "X": $new_str .= mt_rand(1, 9); break;
  186. case "x": $new_str .= mt_rand(0, 9); break;
  187. // Letters
  188. case "L": $new_str .= self::$letters[mt_rand(0, self::$lettersLen-1)]; break;
  189. case "l": $new_str .= strtolower(self::$letters[mt_rand(0, self::$lettersLen-1)]); break;
  190. case "D":
  191. $bool = mt_rand()&1;
  192. if ($bool) {
  193. $new_str .= self::$letters[mt_rand(0, self::$lettersLen-1)];
  194. } else {
  195. $new_str .= strtolower(self::$letters[mt_rand(0, self::$lettersLen-1)]);
  196. }
  197. break;
  198. // Consonants
  199. case "C": $new_str .= self::$consonants[mt_rand(0, self::$consonantsLen-1)]; break;
  200. case "c": $new_str .= strtolower(self::$consonants[mt_rand(0, self::$consonantsLen-1)]); break;
  201. case "E":
  202. $bool = mt_rand()&1;
  203. if ($bool) {
  204. $new_str .= self::$consonants[mt_rand(0, self::$consonantsLen-1)];
  205. } else {
  206. $new_str .= strtolower(self::$consonants[mt_rand(0, self::$consonantsLen-1)]);
  207. }
  208. break;
  209. // Vowels
  210. case "V": $new_str .= self::$vowels[mt_rand(0, self::$vowelsLen-1)]; break;
  211. case "v": $new_str .= strtolower(self::$vowels[mt_rand(0, self::$vowelsLen-1)]); break;
  212. case "F":
  213. $bool = mt_rand()&1;
  214. if ($bool) {
  215. $new_str .= self::$vowels[mt_rand(0, self::$vowelsLen-1)];
  216. } else {
  217. $new_str .= strtolower(self::$vowels[mt_rand(0, self::$vowelsLen-1)]);
  218. }
  219. break;
  220. case "H":
  221. $new_str .= self::$hex[mt_rand(0, self::$hexLen-1)];
  222. break;
  223. default:
  224. $new_str .= $str[$i];
  225. break;
  226. }
  227. }
  228. return trim($new_str);
  229. }
  230. /**
  231. * Returns an array of lorem ipsum words. Assumes that a file exists in a misc/ subfolder called
  232. * loremipsum.txt, containing lorem ipsum text.
  233. *
  234. * @return array a large array of words
  235. */
  236. public static function getLipsum() {
  237. if (!self::$lipsumMemoized) {
  238. $prefix = Core::getDbTablePrefix();
  239. // grab all the words in the text files & put them in an array (1 word per index)
  240. $response = Core::$db->query("
  241. SELECT *
  242. FROM {$prefix}settings
  243. WHERE setting_name = 'lipsum'
  244. ");
  245. if ($response["success"]) {
  246. $info = mysqli_fetch_assoc($response["results"]);
  247. self::$lipsum = preg_split("/\s+/", $info["setting_value"]);
  248. }
  249. self::$lipsumMemoized = true;
  250. }
  251. return self::$lipsum;
  252. }
  253. /**
  254. * Generates a string of lorem ipsum words.
  255. *
  256. * @param string $starts_with_lipsum - true/false
  257. * @param string $type - "fixed"/"range"
  258. * @param integer $min - the minimum # of words to return OR the total number
  259. * @param integer $max - the max # of words to return (or null for "fixed" type)
  260. */
  261. public static function generateRandomTextStr($words, $startsWithLipsum, $type, $min, $max = "") {
  262. // determine the number of words to return
  263. if ($type == "fixed") {
  264. $numWords = $min;
  265. } else if ($type == "range") {
  266. $numWords = mt_rand($min, $max);
  267. }
  268. $totalWords = count($words);
  269. if ($numWords > $totalWords) {
  270. $numWords = $totalWords;
  271. }
  272. // determine the offset
  273. $offset = 0;
  274. if (!$startsWithLipsum) {
  275. $offset = mt_rand(2, $totalWords - ($numWords + 1));
  276. }
  277. $wordArray = array_slice($words, $offset, $numWords);
  278. return join(" ", $wordArray);
  279. }
  280. /**
  281. * Converts all x's and X's in a string with a random digit. X's: 1-9, x's: 0-9.
  282. */
  283. public static function generateRandomNumStr($str) {
  284. // loop through each character and convert all unescaped X's to 1-9 and unescaped x's to 0-9.
  285. $new_str = "";
  286. $strlen = strlen($str);
  287. for ($i=0; $i<$strlen; $i++) {
  288. if ($str[$i] == '\\' && ($str[$i+1] == "X" || $str[$i+1] == "x")) {
  289. continue;
  290. } else if ($str[$i] == "X") {
  291. if ($i != 0 && ($str[$i-1] == '\\')) {
  292. $new_str .= "X";
  293. } else {
  294. $new_str .= mt_rand(1, 9);
  295. }
  296. } else if ($str[$i] == "x") {
  297. if ($i != 0 && ($str[$i-1] == '\\')) {
  298. $new_str .= "x";
  299. } else {
  300. $new_str .= mt_rand(0, 9);
  301. }
  302. } else {
  303. $new_str .= $str[$i];
  304. }
  305. }
  306. return trim($new_str);
  307. }
  308. public static function maybeShowInstallationPage() {
  309. if (!Core::checkIsInstalled()) {
  310. $query_string = (isset($_GET["source"]) && in_array($_GET["source"], array("fromerrorpage"))) ?
  311. "?source={$_GET["source"]}" : "";
  312. header("location: install.php{$query_string}");
  313. exit;
  314. }
  315. }
  316. public static function enquoteArray($arr, $char = "\"") {
  317. $newArr = array();
  318. foreach ($arr as $item) {
  319. $newArr[] = "{$char}$item{$char}";
  320. }
  321. return $newArr;
  322. }
  323. public static function isHash($var) {
  324. if (!is_array($var)) {
  325. return false;
  326. }
  327. return array_keys($var) !== range(0, sizeof($var) - 1);
  328. }
  329. /**
  330. * A method to recursively encode an array (associative or indexed).
  331. * @param $array
  332. */
  333. public static function utf8_encode_array($array) {
  334. // if the parameter wasn't an array, explicitly return false
  335. if (!is_array($array)) {
  336. return false;
  337. }
  338. $resultArray = array();
  339. foreach ($array as $key => $value) {
  340. if (Utils::isHash($array)) {
  341. if (is_array($value)) {
  342. $resultArray[utf8_encode($key)] = Utils::utf8_encode_array($value);
  343. } else {
  344. if (is_string($value)) {
  345. $resultArray[utf8_encode($key)] = utf8_encode($value);
  346. } else {
  347. $resultArray[utf8_encode($key)] = $value;
  348. }
  349. }
  350. } else {
  351. if (is_array($value)) {
  352. $resultArray[$key] = Utils::utf8_encode_array($value);
  353. } else {
  354. if (is_string($value)) {
  355. $resultArray[$key] = utf8_encode($value);
  356. } else {
  357. $resultArray[$key] = $value;
  358. }
  359. }
  360. }
  361. }
  362. return $resultArray;
  363. }
  364. }