PageRenderTime 48ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/app/common/utils.php

https://bitbucket.org/pontikis/tolc
PHP | 340 lines | 150 code | 37 blank | 153 comment | 15 complexity | 09bc77a5cc54d6a63d0f7d04b824bb9d MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * Converts current time for given timezone (considering DST) to 14-digit UTC timestamp (YYYYMMDDHHMMSS)
  4. *
  5. * DateTime requires PHP >= 5.2
  6. *
  7. * @param $str_user_timezone
  8. * @param string $str_server_timezone
  9. * @param string $str_server_dateformat
  10. * @return string
  11. */
  12. function now($str_user_timezone,
  13. $str_server_timezone = CONST_SERVER_TIMEZONE,
  14. $str_server_dateformat = CONST_SERVER_DATEFORMAT) {
  15. // set timezone to user timezone
  16. date_default_timezone_set($str_user_timezone);
  17. $date = new DateTime('now');
  18. $date->setTimezone(new DateTimeZone($str_server_timezone));
  19. $str_server_now = $date->format($str_server_dateformat);
  20. // return timezone to server default
  21. date_default_timezone_set($str_server_timezone);
  22. return $str_server_now;
  23. }
  24. /**
  25. * Converts a UTC timestamp to date string of given timezone (considering DST) and given dateformat
  26. *
  27. * DateTime requires PHP >= 5.2
  28. *
  29. * @param $str_server_datetime
  30. *
  31. * <li>Normally is a 14-digit UTC timestamp (YYYYMMDDHHMMSS). It can also be 8-digit (date), 12-digit (datetime without seconds).
  32. * If given dateformat (<var>$str_user_dateformat</var>) is longer than <var>$str_server_datetime</var>,
  33. * the missing digits of input value are filled with zero,
  34. * so (YYYYMMDD is equivalent to YYYYMMDD000000 and YYYYMMDDHHMM is equivalent to YYYYMMDDHHMM00).
  35. *
  36. * <li>It can also be 'now', null or empty string. In this case returns the current time.
  37. *
  38. * <li>Other values (invalid datetime strings) throw an error. Milliseconds are not supported.
  39. *
  40. * @param string $str_user_timezone
  41. * @param $str_user_dateformat
  42. * @return string
  43. */
  44. function date_decode($str_server_datetime,
  45. $str_user_timezone,
  46. $str_user_dateformat) {
  47. // create date object
  48. try {
  49. $date = new DateTime($str_server_datetime);
  50. } catch(Exception $e) {
  51. trigger_error('date_decode: Invalid datetime: ' . $e->getMessage(), E_USER_ERROR);
  52. }
  53. // convert to user timezone
  54. $userTimeZone = new DateTimeZone($str_user_timezone);
  55. $date->setTimeZone($userTimeZone);
  56. // convert to user dateformat
  57. $str_user_datetime = $date->format($str_user_dateformat);
  58. return $str_user_datetime;
  59. }
  60. /**
  61. * Converts a date string of given timezone (considering DST) and format to 14-digit UTC timestamp (YYYYMMDDHHMMSS)
  62. *
  63. * DateTime::createFromFormat requires PHP >= 5.3
  64. *
  65. * <li><b>Note about strtotime</b>: Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components:
  66. * if the separator is a slash (/), then the American m/d/y is assumed;
  67. * whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
  68. *
  69. * To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
  70. *
  71. * @param $str_user_datetime
  72. *
  73. * <li><var>$str_user_timezone</var> and <var>$str_user_dateformat</var> must match. Otherwise error occurs.
  74. *
  75. * <li>If <var>$str_server_dateformat</var> is longer than <var>$str_user_dateformat</var>,
  76. * the missing time digits filled with zero, but if all times digits are missing current time is returned.
  77. *
  78. * <li>Other values (invalid datetime strings) throw an error. Milliseconds are not supported.
  79. *
  80. * @param $str_user_timezone
  81. * @param $str_user_dateformat
  82. * @param string $str_server_timezone
  83. * @param string $str_server_dateformat
  84. * @param string $str_safe_dateformat_strtotime
  85. * @return string
  86. *
  87. * @link http://www.php.net/manual/en/function.strtotime.php
  88. * @link http://stackoverflow.com/questions/4163641/php-using-strtotime-with-a-uk-date-format-dd-mm-yy
  89. * @link http://derickrethans.nl/british-date-format-parsing.html
  90. */
  91. function date_encode($str_user_datetime,
  92. $str_user_timezone,
  93. $str_user_dateformat,
  94. $str_server_timezone = CONST_SERVER_TIMEZONE,
  95. $str_server_dateformat = CONST_SERVER_DATEFORMAT,
  96. $str_safe_dateformat_strtotime = CONST_SAFE_DATEFORMAT_STRTOTIME) {
  97. // set timezone to user timezone
  98. date_default_timezone_set($str_user_timezone);
  99. // create date object using any given format
  100. if($str_user_datetime == 'now' || !$str_user_datetime) {
  101. $date = new DateTime('', new DateTimeZone($str_user_timezone));
  102. } else {
  103. $date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime, new DateTimeZone($str_user_timezone));
  104. if($date === false) {
  105. trigger_error('date_encode: Invalid date', E_USER_ERROR);
  106. }
  107. }
  108. // convert given datetime to safe format for strtotime
  109. $str_user_datetime = $date->format($str_safe_dateformat_strtotime);
  110. // convert to UTC
  111. $str_server_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));
  112. // return timezone to server default
  113. date_default_timezone_set($str_server_timezone);
  114. return $str_server_datetime;
  115. }
  116. /**
  117. * Return the offset (in seconds) from UTC of a given timezone timestring (considering DST)
  118. *
  119. * @param $str_datetime
  120. * @param $str_timezone
  121. * @return int
  122. */
  123. function get_time_offset($str_datetime, $str_timezone) {
  124. $timezone = new DateTimeZone($str_timezone);
  125. $offset = $timezone->getOffset(new DateTime($str_datetime));
  126. return $offset;
  127. }
  128. /**
  129. * * Multi-byte CASE INSENSITIVE str_replace
  130. *
  131. * @param $co
  132. * @param $naCo
  133. * @param $wCzym
  134. * @return string
  135. * @link http://www.php.net/manual/en/function.mb-ereg-replace.php#55659
  136. */
  137. function mb_str_ireplace($co, $naCo, $wCzym) {
  138. $wCzymM = mb_strtolower($wCzym);
  139. $coM = mb_strtolower($co);
  140. $offset = 0;
  141. while(!is_bool($poz = mb_strpos($wCzymM, $coM, $offset))) {
  142. $offset = $poz + mb_strlen($naCo);
  143. $wCzym = mb_substr($wCzym, 0, $poz) . $naCo . mb_substr($wCzym, $poz + mb_strlen($co));
  144. $wCzymM = mb_strtolower($wCzym);
  145. }
  146. return $wCzym;
  147. }
  148. /**
  149. * Timezones list with GMT offset
  150. *
  151. * @return array
  152. * @link http://stackoverflow.com/a/9328760
  153. */
  154. function tz_list() {
  155. $zones_array = array();
  156. $timestamp = time();
  157. foreach(timezone_identifiers_list() as $key => $zone) {
  158. date_default_timezone_set($zone);
  159. $zones_array[$key]['zone'] = $zone;
  160. $zones_array[$key]['diff_from_GMT'] = 'UTC/GMT ' . date('P', $timestamp);
  161. }
  162. return $zones_array;
  163. }
  164. /**
  165. * Create dateformat array
  166. *
  167. * @param $a_df
  168. * @param $tz
  169. * @return array
  170. */
  171. function df_list($a_df, $tz = CONST_SERVER_TIMEZONE) {
  172. $df_array = array();
  173. $tz = new DateTimeZone($tz);
  174. $date = new DateTime('');
  175. $date->setTimeZone($tz);
  176. foreach($a_df as $df_key => $df_val) {
  177. $df = $df_val['php_datetime'];
  178. $df_example = $date->format($df);
  179. $df_array[$df_key] = array('dateformat' => $df, 'example' => $df_example);
  180. }
  181. return $df_array;
  182. }
  183. /**
  184. * Get either a Gravatar URL or complete image tag for a specified email address.
  185. *
  186. * @param string $email The email address
  187. * @param int|string $s Size in pixels, defaults to 80px [ 1 - 2048 ]
  188. * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  189. * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
  190. * @param bool|\boole $img True to return a complete IMG tag False for just the URL
  191. * @param array $atts Optional, additional key/value attributes to include in the IMG tag
  192. * @return String containing either just a URL or a complete image tag
  193. * @link http://gravatar.com/site/implement/images/php/
  194. */
  195. function get_gravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array()) {
  196. $url = 'http://www.gravatar.com/avatar/';
  197. $url .= md5(strtolower(trim($email)));
  198. $url .= "?s=$s&d=$d&r=$r";
  199. if($img) {
  200. $url = '<img src="' . $url . '"';
  201. foreach($atts as $key => $val)
  202. $url .= ' ' . $key . '="' . $val . '"';
  203. $url .= ' />';
  204. }
  205. return $url;
  206. }
  207. /**
  208. * Get Gravatar profile url
  209. *
  210. * @param $email
  211. * @param bool $decode_url
  212. * @return string
  213. * @link https://en.gravatar.com/site/implement/profiles/php/
  214. */
  215. function get_gravatar_profile($email, $decode_url = false) {
  216. $url_encoded = 'http://www.gravatar.com/' . md5(strtolower(trim($email)));
  217. if(!$decode_url) {
  218. return $url_encoded;
  219. } else {
  220. $url = $url_encoded . '.php';
  221. $str = file_get_contents($url);
  222. if($str === false) {
  223. return $url_encoded;
  224. } else {
  225. $profile = unserialize($str);
  226. if(is_array($profile) && isset($profile['entry'])) {
  227. return $profile['entry'][0]['profileUrl'];
  228. } else {
  229. return $url_encoded;
  230. }
  231. }
  232. }
  233. }
  234. /**
  235. * @param $str
  236. * @return mixed
  237. * @link http://myshadowself.com/coding/php-function-to-convert-accented-characters-to-their-non-accented-equivalant/
  238. */
  239. function removeAccents($str) {
  240. $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', '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', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o', 'Α', 'α', 'Ε', 'ε', 'Ο', 'ο', 'Ω', 'ω', 'Ι', 'ι', 'ι', 'ι', 'Υ', 'υ', 'υ', 'υ', 'Η', 'η');
  242. return str_replace($a, $b, $str);
  243. }
  244. /**
  245. * @param $url
  246. * @param $url_length
  247. * @param bool $remove_accents
  248. * @param bool $convert_to_lower_case
  249. * @param bool $replace_space_between_words_with_dash
  250. * @return mixed|string
  251. */
  252. function sanitize_url($url,
  253. $url_length,
  254. $remove_accents = true,
  255. $convert_to_lower_case = true,
  256. $replace_space_between_words_with_dash = true) {
  257. $url = trim($url);
  258. $url = preg_replace('/\-+/', '-', $url); //replace multiple dashes with one
  259. $url = preg_replace('/\s+/', ' ', $url); //replace multiple spaces with one
  260. $url = preg_replace('/_+/', '.', $url); //replace multiple underscore with one
  261. $url = preg_replace('/\/+/', '/', $url); //replace multiple slashes with one
  262. $url = preg_replace('/\:+/', ':', $url); //replace multiple colon with one
  263. $url = preg_replace('/\.+/', '.', $url); //replace multiple dots with one
  264. $url = $remove_accents ? removeAccents($url) : $url; // remove accented characters
  265. $url = $convert_to_lower_case ? mb_strtolower($url) : $url; // convert to lower case
  266. $url = $replace_space_between_words_with_dash ? preg_replace('/ /', '-', $url) : $url; //replace space between words with dash
  267. $url = mb_substr($url, 0, $url_length); // truncate to max length
  268. return $url;
  269. }
  270. /**
  271. * Check for valid URL
  272. *
  273. * preg_match \w (unicode word characters) does not work with php < 5.3.10
  274. *
  275. * @param $url
  276. * @param $str_regex
  277. * @param $str_regex_php_legacy
  278. * @return bool
  279. *
  280. * @link http://stackoverflow.com/questions/8915713/php5-3-preg-match-with-umlaute-utf-8-modifier
  281. */
  282. function valid_url($url, $str_regex, $str_regex_php_legacy) {
  283. $res = true;
  284. if(version_compare(phpversion(), '5.3.10', 'ge')) {
  285. $res = preg_match($str_regex, $url) ? false : true;
  286. } else {
  287. $res = preg_match($str_regex_php_legacy, $url) ? false : true;
  288. }
  289. return $res;
  290. }
  291. /**
  292. * Check if a string is a valid date(time)
  293. *
  294. * @param $str_dt
  295. * @param $str_dateformat
  296. * @param $str_timezone
  297. * @return bool
  298. */
  299. function isValidDateTimeString($str_dt, $str_dateformat, $str_timezone) {
  300. $date = DateTime::createFromFormat($str_dateformat, $str_dt, new DateTimeZone($str_timezone));
  301. return ($date === false ? false : true);
  302. }
  303. ?>