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

/environment/functions/general.php

https://gitlab.com/x33n/ProjectPier-Core
PHP | 587 lines | 292 code | 50 blank | 245 comment | 51 complexity | da61aaca1f1a789bbd702ff8710cb1d2 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. function ignore_error($errno, $errstr, $errfile, $errline) {
  277. return true;
  278. }
  279. /**
  280. * Redirect to specific URL (header redirection)
  281. *
  282. * @access public
  283. * @param string $to Redirect to this URL
  284. * @param boolean $die Die when finished
  285. * @return void
  286. */
  287. function redirect_to($to, $die = true) {
  288. if (headers_sent($filename, $linenum)) {
  289. echo "Headers already sent in $filename on line $linenum\n" .
  290. "Click this <a href=\"".ROOT_URL."\">link</a> to continue\n";
  291. session_write_close();
  292. die();
  293. }
  294. trace('redirect_to', "($to, $die)");
  295. $to = trim($to);
  296. if (strpos($to, '&amp;') !== false) {
  297. $to = str_replace('&amp;', '&', $to);
  298. } // if
  299. if (ob_get_level()>0) {
  300. set_error_handler('ignore_error');
  301. while(@ob_end_clean());
  302. restore_error_handler();
  303. }
  304. header('Location: ' . $to);
  305. if ($die) {
  306. session_write_close();
  307. die();
  308. }
  309. } // end redirect_to
  310. /**
  311. * Redirect to referer
  312. *
  313. * @access public
  314. * @param string $alternative Alternative URL is used if referer is not valid URL
  315. * @return null
  316. */
  317. function redirect_to_referer($alternative = null) {
  318. $referer = get_referer();
  319. if (!is_valid_url($referer)) {
  320. redirect_to($alternative);
  321. } else {
  322. redirect_to($referer);
  323. } // if
  324. } // redirect_to_referer
  325. /**
  326. * Return referer URL
  327. *
  328. * @param string $default This value is returned if referer is not found or is empty
  329. * @return string
  330. */
  331. function get_referer($default = null) {
  332. return array_var($_SERVER, 'HTTP_REFERER', $default);
  333. } // get_referer
  334. /**
  335. * This function will return max upload size in bytes
  336. *
  337. * @param void
  338. * @return integer
  339. */
  340. function get_max_upload_size() {
  341. return min(
  342. php_config_value_to_bytes(ini_get('upload_max_filesize')),
  343. php_config_value_to_bytes(ini_get('post_max_size'))
  344. ); // max
  345. } // get_max_upload_size
  346. /**
  347. * Convert PHP config value (2M, 8M, 200K...) to bytes
  348. *
  349. * This function was taken from PHP documentation
  350. *
  351. * @param string $val
  352. * @return integer
  353. */
  354. function php_config_value_to_bytes($val) {
  355. $val = trim($val);
  356. $last = strtolower($val{strlen($val)-1});
  357. switch ($last) {
  358. // The 'G' modifier is available since PHP 5.1.0
  359. case 'g':
  360. $val *= 1024;
  361. case 'm':
  362. $val *= 1024;
  363. case 'k':
  364. $val *= 1024;
  365. } // if
  366. return $val;
  367. } // php_config_value_to_bytes
  368. // ==========================================================
  369. // POST and GET
  370. // ==========================================================
  371. /**
  372. * This function will strip slashes if magic quotes is enabled so
  373. * all input data ($_GET, $_POST, $_COOKIE) is free of slashes
  374. *
  375. * @access public
  376. * @param void
  377. * @return null
  378. */
  379. function fix_input_quotes() {
  380. if (get_magic_quotes_gpc()) {
  381. array_stripslashes($_GET);
  382. array_stripslashes($_POST);
  383. array_stripslashes($_COOKIE);
  384. } // if
  385. } // fix_input_quotes
  386. /**
  387. * This function will walk recursivly thorugh array and strip slashes from scalar values
  388. *
  389. * @param array $array
  390. * @return null
  391. */
  392. function array_stripslashes(&$array) {
  393. if (!is_array($array)) {
  394. return;
  395. }
  396. foreach ($array as $k => $v) {
  397. if (is_array($array[$k])) {
  398. array_stripslashes($array[$k]);
  399. } else {
  400. $array[$k] = stripslashes($array[$k]);
  401. } // if
  402. } // foreach
  403. return $array;
  404. } // array_stripslashes
  405. /**
  406. * This function will add hyperlinks to strings that look like links
  407. *
  408. * @param string $text
  409. * @return $text with possibly hyperlinks
  410. */
  411. function add_links(&$text) {
  412. // The following searches for strings that look like links and auto-links them
  413. $search = array(
  414. '/(?<!")(http:\/\/[^\s\"<]*)/',
  415. '/[^\/](www\.[^\s<]*)/'
  416. );
  417. $replace = array(
  418. "<a href=\"$1\" rel=\"nofollow\">$1</a>",
  419. " <a href=\"http://$1\" rel=\"nofollow\">$1</a>"
  420. );
  421. $text = preg_replace($search,$replace,$text);
  422. return $text;
  423. }
  424. /**
  425. * This function will return string in lowercase
  426. *
  427. * @param string $string
  428. * @return $string in lower case
  429. */
  430. function lc($string) {
  431. if (function_exists('mb_convert_case')) {
  432. return mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
  433. }
  434. $uc = "ĄÇČĆĘŁŃÑÓŚŹŻABCDÐEFTGĞHIMJKLNOŒÖPRSŠŞUÜWYÝZŽQXVЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮÆÅÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖØÛÙÚÜİ";
  435. $lc = "ąçčćęłńñóśźżabcdðeftgğhimjklnoœöprsšşuüwyýzžqxvёйцукенгшщзхъфывапролджэячсмитьбюæåâàáäãêèéëîíìïôõòóöøûùúüi";
  436. return strtr($string, $uc, $lc);
  437. }
  438. /**
  439. * This function will return string normalized
  440. *
  441. * @param string $string
  442. * @return $string normalized
  443. */
  444. function normalize ($string) {
  445. $table = array(
  446. 'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
  447. 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
  448. 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
  449. 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
  450. 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
  451. 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
  452. 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
  453. 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
  454. );
  455. return strtr($string, $table);
  456. }
  457. /**
  458. * This function will return external url
  459. *
  460. * @param string $relative_url
  461. * @return $string with http:// etc. added
  462. */
  463. function externalUrl($relative_url) {
  464. $protocol = 'http://';
  465. if (isset($_SERVER['HTTPS'])) {
  466. if ($_SERVER['HTTPS']!='off') { // IIS
  467. if ($_SERVER['HTTPS']!='') {
  468. $protocol = 'https://';
  469. }
  470. }
  471. }
  472. return $protocol . $_SERVER['HTTP_HOST'] . $relative_url;
  473. }
  474. /**
  475. * This function returns true if string begins with certain string
  476. *
  477. * @param string $string
  478. * @param string $search
  479. * @return boolean
  480. */
  481. function string_begins_with($string, $search) {
  482. return (strncmp($string, $search, strlen($search)) == 0);
  483. }
  484. /**
  485. * This function will return chunked content unchunked
  486. *
  487. * @param string $data
  488. * @return $unchunked_data
  489. * source: php.net
  490. */
  491. function http_unchunk($data) {
  492. $fp = 0;
  493. $outData = '';
  494. while ($fp < strlen($data)) {
  495. $rawnum = substr($data, $fp, strpos(substr($data, $fp), "\r\n") + 2);
  496. $num = hexdec(trim($rawnum));
  497. $fp += strlen($rawnum);
  498. $chunk = substr($data, $fp, $num);
  499. $outData .= $chunk;
  500. $fp += strlen($chunk);
  501. }
  502. return $outData;
  503. }
  504. /**
  505. * This function will return content from url
  506. * Note: Handles chunked content
  507. *
  508. * @param string $host
  509. * @param string $port
  510. * @param string $url (within host)
  511. * @return $string with content
  512. */
  513. function get_content_from_url($host, $port, $url) {
  514. $reply='';
  515. $fp = fsockopen($host, $port, $errno, $errstr, 30);
  516. if (!$fp) {
  517. //echo "$errstr ($errno)<br />\n";
  518. return false;
  519. } else {
  520. $out = "GET /$url HTTP/1.0\r\n";
  521. $out .= "Host: $host\r\n";
  522. $out .= "Connection: Close\r\n\r\n";
  523. fwrite($fp, $out);
  524. while (!feof($fp)) {
  525. $reply .= fgets($fp, 1024);
  526. }
  527. fclose($fp);
  528. }
  529. $start_of_data = strpos($reply, "\r\n\r\n")+4;
  530. $headers = substr($reply, 0, $start_of_data);
  531. $data = substr($reply, $start_of_data);
  532. if (strpos(strtolower($headers), "transfer-encoding: chunked") !== FALSE) {
  533. $data = http_unchunk($data);
  534. }
  535. return $data;
  536. }
  537. ?>