PageRenderTime 39ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/environment/functions/general.php

https://github.com/cj/Project-Pier
PHP | 513 lines | 246 code | 46 blank | 221 comment | 45 complexity | 761fa814729b8dbced3571134ee1d6c3 MD5 | raw file
  1. <?php
  2. /**
  3. * Check if $object is valid $class instance
  4. *
  5. * @access public
  6. * @param mixed $object Variable that need to be checked agains classname
  7. * @param string $class Classname
  8. * @return null
  9. */
  10. function instance_of($object, $class) {
  11. return $object instanceof $class;
  12. } // instance_of
  13. /**
  14. * Show var dump. pre_var_dump() is used for testing only!
  15. *
  16. * @access public
  17. * @param mixed $var
  18. * @return null
  19. */
  20. function pre_var_dump($var) {
  21. print '<pre>';
  22. var_dump($var);
  23. print '</pre>';
  24. } // pre_var_dump
  25. /**
  26. * This function will return clean variable info
  27. *
  28. * @param mixed $var
  29. * @param string $indent Indent is used when dumping arrays recursivly
  30. * @param string $indent_close_bracet Indent close bracket param is used
  31. * internally for array output. It is shorter that var indent for 2 spaces
  32. * @return null
  33. */
  34. function clean_var_info($var, $indent = '&nbsp;&nbsp;', $indent_close_bracet = '') {
  35. if (is_object($var)) {
  36. return 'Object (class: ' . get_class($var) . ')';
  37. } elseif (is_resource($var)) {
  38. return 'Resource (type: ' . get_resource_type($var) . ')';
  39. } elseif (is_array($var)) {
  40. $result = 'Array (';
  41. if (count($var)) {
  42. foreach ($var as $k => $v) {
  43. $k_for_display = is_integer($k) ? $k : "'" . clean($k) . "'";
  44. $result .= "\n" . $indent . '[' . $k_for_display . '] => ' . clean_var_info($v, $indent . '&nbsp;&nbsp;', $indent_close_bracet . $indent);
  45. } // foreach
  46. } // if
  47. return $result . "\n$indent_close_bracet)";
  48. } elseif (is_int($var)) {
  49. return '(int)' . $var;
  50. } elseif (is_float($var)) {
  51. return '(float)' . $var;
  52. } elseif (is_bool($var)) {
  53. return $var ? 'true' : 'false';
  54. } elseif (is_null($var)) {
  55. return 'NULL';
  56. } else {
  57. return "(string) '" . clean($var) . "'";
  58. } // if
  59. } // clean_var_info
  60. /**
  61. * Equivalent to htmlspecialchars(), but allows &#[0-9]+ (for unicode)
  62. *
  63. * This function was taken from punBB codebase <http://www.punbb.org/>
  64. *
  65. * @param string $str
  66. * @return string
  67. */
  68. function clean($str) {
  69. $str = preg_replace('/&(?!#[0-9]+;)/s', '&amp;', $str);
  70. $str = str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $str);
  71. return $str;
  72. } // clean
  73. /**
  74. * Convert entities back to valid characters
  75. *
  76. * @param string $escaped_string
  77. * @return string
  78. */
  79. function undo_htmlspecialchars($escaped_string) {
  80. $search = array('&amp;', '&lt;', '&gt;');
  81. $replace = array('&', '<', '>');
  82. return str_replace($search, $replace, $escaped_string);
  83. } // undo_htmlspecialchars
  84. /**
  85. * This function will return true if $str is valid function name (made out of alpha numeric characters + underscore)
  86. *
  87. * @param string $str
  88. * @return boolean
  89. */
  90. function is_valid_function_name($str) {
  91. $check_str = trim($str);
  92. if ($check_str == '') {
  93. return false; // empty string
  94. }
  95. $first_char = substr_utf($check_str, 0, 1);
  96. if (is_numeric($first_char)) return false; // first char can't be number
  97. return (boolean) preg_match("/^([a-zA-Z0-9_]*)$/", $check_str);
  98. } // is_valid_function_name
  99. /**
  100. * Check if specific string is valid sha1() hash
  101. *
  102. * @param string $hash
  103. * @return boolean
  104. */
  105. function is_valid_hash($hash) {
  106. return ((strlen($hash) == 32) || (strlen($hash) == 40)) && (boolean) preg_match("/^([a-f0-9]*)$/", $hash);
  107. } // is_valid_hash
  108. /**
  109. * Return variable from hash (associative array). If value does not exists
  110. * return default value
  111. *
  112. * @access public
  113. * @param array $from Hash
  114. * @param string $name
  115. * @param mixed $default
  116. * @return mixed
  117. */
  118. function array_var(&$from, $name, $default = null) {
  119. if (is_array($from)) {
  120. return isset($from[$name]) ? $from[$name] : $default;
  121. }
  122. return $default;
  123. } // array_var
  124. /**
  125. * This function will return $str as an array
  126. *
  127. * @param string $str
  128. * @return array
  129. */
  130. function string_to_array($str) {
  131. if (!is_string($str) || (strlen($str) == 0)) {
  132. return array();
  133. }
  134. $result = array();
  135. for ($i = 0, $strlen = strlen($str); $i < $strlen; $i++) {
  136. $result[] = $str[$i];
  137. } // if
  138. return $result;
  139. } // string_to_array
  140. /**
  141. * This function will return ID from array variables. Default settings will get 'id'
  142. * variable from $_GET. If ID is not found function will return NULL
  143. *
  144. * @param string $var_name Variable name. Default is 'id'
  145. * @param array $from Extract ID from this array. If NULL $_GET will be used
  146. * @param mixed $default Default value is returned in case of any error
  147. * @return integer
  148. */
  149. function get_id($var_name = 'id', $from = null, $default = null) {
  150. $var_name = trim($var_name);
  151. if ($var_name == '') return $default; // empty varname?
  152. if (is_null($from)) {
  153. $from = $_GET;
  154. }
  155. if (!is_array($from)) return $default; // $from is array?
  156. if (!is_valid_function_name($var_name)) return $default; // $var_name is valid?
  157. $value = array_var($from, $var_name, $default);
  158. return is_numeric($value) ? (integer) $value : $default;
  159. } // get_id
  160. /**
  161. * Flattens the array. This function does not preserve keys, it just returns
  162. * array indexed form 0 .. count - 1
  163. *
  164. * @access public
  165. * @param array $array If this value is not array it will be returned as one
  166. * @return array
  167. */
  168. function array_flat($array) {
  169. // Not an array
  170. if (!is_array($array)) {
  171. return array($array);
  172. }
  173. // Prepare result
  174. $result = array();
  175. // Loop elements
  176. foreach ($array as $value) {
  177. // Subelement is array? Flat it
  178. if (is_array($value)) {
  179. $value = array_flat($value);
  180. foreach ($value as $subvalue) {
  181. $result[] = $subvalue;
  182. }
  183. } else {
  184. $result[] = $value;
  185. } // if
  186. } // if
  187. // Return result
  188. return $result;
  189. } // array_flat
  190. /**
  191. * Replace first $search_for with $replace_with in $in. If $search_for is not found
  192. * original $in string will be returned...
  193. *
  194. * @access public
  195. * @param string $search_for Search for this string
  196. * @param string $replace_with Replace it with this value
  197. * @param string $in Haystack
  198. * @return string
  199. */
  200. function str_replace_first($search_for, $replace_with, $in) {
  201. $pos = strpos($in, $search_for);
  202. if ($pos === false) {
  203. return $in;
  204. } else {
  205. return substr($in, 0, $pos) . $replace_with . substr($in, $pos + strlen($search_for), strlen($in));
  206. } // if
  207. } // str_replace_first
  208. /**
  209. * String starts with something
  210. *
  211. * This function will return true only if input string starts with
  212. * niddle
  213. *
  214. * @param string $string Input string
  215. * @param string $niddle Needle string
  216. * @return boolean
  217. */
  218. function str_starts_with($string, $niddle) {
  219. return substr($string, 0, strlen($niddle)) == $niddle;
  220. } // end func str_starts with
  221. /**
  222. * String ends with something
  223. *
  224. * This function will return true only if input string ends with
  225. * niddle
  226. *
  227. * @param string $string Input string
  228. * @param string $niddle Needle string
  229. * @return boolean
  230. */
  231. function str_ends_with($string, $niddle) {
  232. return substr($string, strlen($string) - strlen($niddle), strlen($niddle)) == $niddle;
  233. } // end func str_ends_with
  234. /**
  235. * Return path with trailing slash
  236. *
  237. * @param string $path Input path
  238. * @return string Path with trailing slash
  239. */
  240. function with_slash($path) {
  241. return str_ends_with($path, '/') ? $path : $path . '/';
  242. } // end func with_slash
  243. /**
  244. * Remove trailing slash from the end of the path (if exists)
  245. *
  246. * @param string $path File path that need to be handled
  247. * @return string
  248. */
  249. function without_slash($path) {
  250. return str_ends_with($path, '/') ? substr($path, 0, strlen($path) - 1) : $path;
  251. } // without_slash
  252. /**
  253. * Check if selected email has valid email format
  254. *
  255. * @param string $user_email Email address
  256. * @return boolean
  257. */
  258. function is_valid_email($user_email) {
  259. $chars = EMAIL_FORMAT;
  260. if (strstr($user_email, '@') && strstr($user_email, '.')) {
  261. return (boolean) preg_match($chars, $user_email);
  262. } else {
  263. return false;
  264. } // if
  265. } // end func is_valid_email
  266. /**
  267. * Verify the syntax of the given URL.
  268. *
  269. * @access public
  270. * @param $url The URL to verify.
  271. * @return boolean
  272. */
  273. function is_valid_url($url) {
  274. return preg_match(URL_FORMAT, $url);
  275. } // end func is_valid_url
  276. /**
  277. * Redirect to specific URL (header redirection)
  278. *
  279. * @access public
  280. * @param string $to Redirect to this URL
  281. * @param boolean $die Die when finished
  282. * @return void
  283. */
  284. function redirect_to($to, $die = true) {
  285. if (headers_sent($filename, $linenum)) {
  286. echo "Headers already sent in $filename on line $linenum\n" .
  287. "Click this <a href=\"".ROOT_URL."\">link</a> to continue\n";
  288. session_write_close();
  289. die();
  290. }
  291. trace('redirect_to', "($to, $die)");
  292. $to = trim($to);
  293. if (strpos($to, '&amp;') !== false) {
  294. $to = str_replace('&amp;', '&', $to);
  295. } // if
  296. if(ob_get_level()>0) while(@ob_end_clean());
  297. header('Location: ' . $to);
  298. if ($die) {
  299. session_write_close();
  300. die();
  301. }
  302. } // end redirect_to
  303. /**
  304. * Redirect to referer
  305. *
  306. * @access public
  307. * @param string $alternative Alternative URL is used if referer is not valid URL
  308. * @return null
  309. */
  310. function redirect_to_referer($alternative = null) {
  311. $referer = get_referer();
  312. if (!is_valid_url($referer)) {
  313. redirect_to($alternative);
  314. } else {
  315. redirect_to($referer);
  316. } // if
  317. } // redirect_to_referer
  318. /**
  319. * Return referer URL
  320. *
  321. * @param string $default This value is returned if referer is not found or is empty
  322. * @return string
  323. */
  324. function get_referer($default = null) {
  325. return array_var($_SERVER, 'HTTP_REFERER', $default);
  326. } // get_referer
  327. /**
  328. * This function will return max upload size in bytes
  329. *
  330. * @param void
  331. * @return integer
  332. */
  333. function get_max_upload_size() {
  334. return min(
  335. php_config_value_to_bytes(ini_get('upload_max_filesize')),
  336. php_config_value_to_bytes(ini_get('post_max_size'))
  337. ); // max
  338. } // get_max_upload_size
  339. /**
  340. * Convert PHP config value (2M, 8M, 200K...) to bytes
  341. *
  342. * This function was taken from PHP documentation
  343. *
  344. * @param string $val
  345. * @return integer
  346. */
  347. function php_config_value_to_bytes($val) {
  348. $val = trim($val);
  349. $last = strtolower($val{strlen($val)-1});
  350. switch ($last) {
  351. // The 'G' modifier is available since PHP 5.1.0
  352. case 'g':
  353. $val *= 1024;
  354. case 'm':
  355. $val *= 1024;
  356. case 'k':
  357. $val *= 1024;
  358. } // if
  359. return $val;
  360. } // php_config_value_to_bytes
  361. // ==========================================================
  362. // POST and GET
  363. // ==========================================================
  364. /**
  365. * This function will strip slashes if magic quotes is enabled so
  366. * all input data ($_GET, $_POST, $_COOKIE) is free of slashes
  367. *
  368. * @access public
  369. * @param void
  370. * @return null
  371. */
  372. function fix_input_quotes() {
  373. if (get_magic_quotes_gpc()) {
  374. array_stripslashes($_GET);
  375. array_stripslashes($_POST);
  376. array_stripslashes($_COOKIE);
  377. } // if
  378. } // fix_input_quotes
  379. /**
  380. * This function will walk recursivly thorugh array and strip slashes from scalar values
  381. *
  382. * @param array $array
  383. * @return null
  384. */
  385. function array_stripslashes(&$array) {
  386. if (!is_array($array)) {
  387. return;
  388. }
  389. foreach ($array as $k => $v) {
  390. if (is_array($array[$k])) {
  391. array_stripslashes($array[$k]);
  392. } else {
  393. $array[$k] = stripslashes($array[$k]);
  394. } // if
  395. } // foreach
  396. return $array;
  397. } // array_stripslashes
  398. /**
  399. * This function will add hyperlinks to strings that look like links
  400. *
  401. * @param string $text
  402. * @return $text with possibly hyperlinks
  403. */
  404. function add_links(&$text) {
  405. // The following searches for strings that look like links and auto-links them
  406. $search = array(
  407. '/(?<!")(http:\/\/[^\s\"<]*)/',
  408. '/[^\/](www\.[^\s<]*)/'
  409. );
  410. $replace = array(
  411. "<a href=\"$1\" rel=\"nofollow\">$1</a>",
  412. " <a href=\"http://$1\" rel=\"nofollow\">$1</a>"
  413. );
  414. $text = preg_replace($search,$replace,$text);
  415. return $text;
  416. }
  417. /**
  418. * This function will return string in lowercase
  419. *
  420. * @param string $string
  421. * @return $string in lower case
  422. */
  423. function lc($string) {
  424. if (function_exists('mb_convert_case')) {
  425. return mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
  426. }
  427. $uc = "ĄÇČĆĘŁŃÑÓŚŹŻABCDÐEFTGĞHIMJKLNOŒÖPRSŠŞUÜWYÝZŽQXVЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮÆÅÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖØÛÙÚÜİ";
  428. $lc = "ąçčćęłńñóśźżabcdðeftgğhimjklnoœöprsšşuüwyýzžqxvёйцукенгшщзхъфывапролджэячсмитьбюæåâàáäãêèéëîíìïôõòóöøûùúüi";
  429. return strtr($string, $uc, $lc);
  430. }
  431. /**
  432. * This function will return string normalized
  433. *
  434. * @param string $string
  435. * @return $string normalized
  436. */
  437. function normalize ($string) {
  438. $table = array(
  439. 'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
  440. 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
  441. 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
  442. 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
  443. 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
  444. 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
  445. 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
  446. 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
  447. );
  448. return strtr($string, $table);
  449. }
  450. /**
  451. * This function will return external url
  452. *
  453. * @param string $relative_url
  454. * @return $string with http:// etc. added
  455. */
  456. function externalUrl($relative_url) {
  457. $protocol = 'http://';
  458. if (isset($_SERVER['HTTPS'])) {
  459. if ($_SERVER['HTTPS']!='off') { // IIS
  460. if ($_SERVER['HTTPS']!='') {
  461. $protocol = 'https://';
  462. }
  463. }
  464. }
  465. return $protocol . $_SERVER['HTTP_HOST'] . $relative_url;
  466. }
  467. ?>