PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/resources/classes/Utils.class.php

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