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