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