1 | <?php |
---|
2 | /** |
---|
3 | * The Strangecode Codebase - a general application development framework for PHP |
---|
4 | * For details visit the project site: <http://trac.strangecode.com/codebase/> |
---|
5 | * Copyright 2001-2012 Strangecode, LLC |
---|
6 | * |
---|
7 | * This file is part of The Strangecode Codebase. |
---|
8 | * |
---|
9 | * The Strangecode Codebase is free software: you can redistribute it and/or |
---|
10 | * modify it under the terms of the GNU General Public License as published by the |
---|
11 | * Free Software Foundation, either version 3 of the License, or (at your option) |
---|
12 | * any later version. |
---|
13 | * |
---|
14 | * The Strangecode Codebase is distributed in the hope that it will be useful, but |
---|
15 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
---|
16 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
---|
17 | * details. |
---|
18 | * |
---|
19 | * You should have received a copy of the GNU General Public License along with |
---|
20 | * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>. |
---|
21 | */ |
---|
22 | |
---|
23 | /** |
---|
24 | * Utilities.inc.php |
---|
25 | */ |
---|
26 | |
---|
27 | |
---|
28 | /** |
---|
29 | * Print variable dump. |
---|
30 | * |
---|
31 | * @param mixed $var The variable to dump. |
---|
32 | * @param bool $display Print the dump in <pre> tags or hide it in html comments (non-CLI only). |
---|
33 | * @param bool $dump_method Dump method. See SC_DUMP_* constants. |
---|
34 | * @param string $file Value of __FILE__. |
---|
35 | * @param string $line Value of __LINE__ |
---|
36 | */ |
---|
37 | define('SC_DUMP_PRINT_R', 0); |
---|
38 | define('SC_DUMP_VAR_DUMP', 1); |
---|
39 | define('SC_DUMP_VAR_EXPORT', 2); |
---|
40 | function dump($var, $display=false, $dump_method=SC_DUMP_PRINT_R, $file='', $line='') |
---|
41 | { |
---|
42 | $app =& App::getInstance(); |
---|
43 | |
---|
44 | if ($app->cli) { |
---|
45 | echo "DUMP FROM: $file $line\n"; |
---|
46 | } else { |
---|
47 | echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n"; |
---|
48 | } |
---|
49 | |
---|
50 | switch ($dump_method) { |
---|
51 | case SC_DUMP_PRINT_R: |
---|
52 | default: |
---|
53 | // Print human-readable descriptions of invisible types. |
---|
54 | if (null === $var) { |
---|
55 | echo '(null)'; |
---|
56 | } else if (true === $var) { |
---|
57 | echo '(bool: true)'; |
---|
58 | } else if (false === $var) { |
---|
59 | echo '(bool: false)'; |
---|
60 | } else if (is_scalar($var) && '' === $var) { |
---|
61 | echo '(empty string)'; |
---|
62 | } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) { |
---|
63 | echo '(only white space)'; |
---|
64 | } else { |
---|
65 | print_r($var); |
---|
66 | } |
---|
67 | break; |
---|
68 | |
---|
69 | case SC_DUMP_VAR_DUMP: |
---|
70 | var_dump($var); |
---|
71 | break; |
---|
72 | |
---|
73 | case SC_DUMP_VAR_EXPORT: |
---|
74 | var_export($var); |
---|
75 | break; |
---|
76 | } |
---|
77 | |
---|
78 | if ($app->cli) { |
---|
79 | echo "\n"; |
---|
80 | } else { |
---|
81 | echo $display ? "\n</pre><br />\n" : "\n-->\n"; |
---|
82 | } |
---|
83 | } |
---|
84 | |
---|
85 | /* |
---|
86 | * Log a PHP variable to javascript console. Relies on getDump(), below. |
---|
87 | * |
---|
88 | * @access public |
---|
89 | * @param mixed $var The variable to dump. |
---|
90 | * @param string $prefix A short note to print before the output to make identifying output easier. |
---|
91 | * @param string $file The value of __FILE__. |
---|
92 | * @param string $line The value of __LINE__. |
---|
93 | * @return null |
---|
94 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
95 | */ |
---|
96 | function jsDump($var, $prefix='jsDump', $file='-', $line='-') |
---|
97 | { |
---|
98 | if (!empty($var)) { |
---|
99 | ?> |
---|
100 | <script type="text/javascript"> |
---|
101 | /* <![CDATA[ */ |
---|
102 | console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>'); |
---|
103 | /* ]]> */ |
---|
104 | </script> |
---|
105 | <?php |
---|
106 | } |
---|
107 | } |
---|
108 | |
---|
109 | /* |
---|
110 | * Return a string version of any variable, optionally serialized on one line. |
---|
111 | * |
---|
112 | * @access public |
---|
113 | * @param mixed $var The variable to dump. |
---|
114 | * @param bool $serialize If true, remove line-endings. Useful for logging variables. |
---|
115 | * @return string The dumped variable. |
---|
116 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
117 | */ |
---|
118 | function getDump($var, $serialize=false) |
---|
119 | { |
---|
120 | ob_start(); |
---|
121 | print_r($var); |
---|
122 | $d = ob_get_contents(); |
---|
123 | ob_end_clean(); |
---|
124 | return $serialize ? preg_replace('/\s+/m', ' ', $d) : $d; |
---|
125 | } |
---|
126 | |
---|
127 | /** |
---|
128 | * Return dump as cleaned text. Useful for dumping data into emails. |
---|
129 | * |
---|
130 | * @param array $var Variable to dump. |
---|
131 | * @param strong $indent A string to prepend indented lines (tab for example). |
---|
132 | * @return string Dump of var. |
---|
133 | */ |
---|
134 | function fancyDump($var, $indent='') |
---|
135 | { |
---|
136 | $output = ''; |
---|
137 | if (is_array($var)) { |
---|
138 | foreach ($var as $k=>$v) { |
---|
139 | $k = ucfirst(mb_strtolower(str_replace(array('_', ' '), ' ', $k))); |
---|
140 | if (is_array($v)) { |
---|
141 | $output .= sprintf("\n%s%s: %s\n", $indent, $k, fancyDump($v, $indent . $indent)); |
---|
142 | } else { |
---|
143 | $output .= sprintf("%s%s: %s\n", $indent, $k, $v); |
---|
144 | } |
---|
145 | } |
---|
146 | } else { |
---|
147 | $output .= sprintf("%s%s\n", $indent, $var); |
---|
148 | } |
---|
149 | return preg_replace(['/^[ \t]+$/', '/\n\n\n+/'], ['', "\n\n"], $output); |
---|
150 | } |
---|
151 | |
---|
152 | /** |
---|
153 | * @param string|mixed $value A string to UTF8-encode. |
---|
154 | * |
---|
155 | * @returns string|mixed The UTF8-encoded string, or the object passed in if |
---|
156 | * it wasn't a string. |
---|
157 | */ |
---|
158 | function conditionalUTF8Encode($value) |
---|
159 | { |
---|
160 | if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') { |
---|
161 | return utf8_encode($value); |
---|
162 | } else { |
---|
163 | return $value; |
---|
164 | } |
---|
165 | } |
---|
166 | |
---|
167 | |
---|
168 | /** |
---|
169 | * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()). |
---|
170 | * |
---|
171 | * @param string $text Text to clean. |
---|
172 | * @param bool $preserve_html If set to true, oTxt will not translate <, >, ", or ' |
---|
173 | * characters into HTML entities. This allows HTML to pass through undisturbed. |
---|
174 | * @return string HTML-safe text. |
---|
175 | */ |
---|
176 | function oTxt($text, $preserve_html=false) |
---|
177 | { |
---|
178 | $app =& App::getInstance(); |
---|
179 | |
---|
180 | $search = array(); |
---|
181 | $replace = array(); |
---|
182 | |
---|
183 | // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities. |
---|
184 | $search['retain_ampersand'] = '/&/'; |
---|
185 | $replace['retain_ampersand'] = '&'; |
---|
186 | |
---|
187 | if ($preserve_html) { |
---|
188 | // Convert characters that must remain non-entities for displaying HTML. |
---|
189 | $search['retain_left_angle'] = '/</'; |
---|
190 | $replace['retain_left_angle'] = '<'; |
---|
191 | |
---|
192 | $search['retain_right_angle'] = '/>/'; |
---|
193 | $replace['retain_right_angle'] = '>'; |
---|
194 | |
---|
195 | $search['retain_single_quote'] = '/'/'; |
---|
196 | $replace['retain_single_quote'] = "'"; |
---|
197 | |
---|
198 | $search['retain_double_quote'] = '/"/'; |
---|
199 | $replace['retain_double_quote'] = '"'; |
---|
200 | } |
---|
201 | |
---|
202 | // & becomes &. Exclude any occurrence where the & is followed by a alphanum or unicode character. |
---|
203 | $search['ampersand'] = '/&(?![\w\d#]{1,10};)/'; |
---|
204 | $replace['ampersand'] = '&'; |
---|
205 | |
---|
206 | return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set'))); |
---|
207 | } |
---|
208 | |
---|
209 | /** |
---|
210 | * Returns text with stylistic modifications. Warning: this will break some HTML attributes! |
---|
211 | * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a> |
---|
212 | * |
---|
213 | * @param string $text Text to clean. |
---|
214 | * @return string Cleaned text. |
---|
215 | */ |
---|
216 | function fancyTxt($text) |
---|
217 | { |
---|
218 | $search = array(); |
---|
219 | $replace = array(); |
---|
220 | |
---|
221 | // "double quoted text" becomes “double quoted text” |
---|
222 | $search['double_quotes'] = '/(^|[^\w=])(?:"|"|"|"|“)([^"]+?)(?:"|"|"|"|”)([^\w]|$)/ms'; // " is the same as " and " and " |
---|
223 | $replace['double_quotes'] = '$1“$2”$3'; |
---|
224 | |
---|
225 | // text's apostrophes become text’s apostrophes |
---|
226 | $search['apostrophe'] = '/(\w)(?:\'|'|')(\w)/ms'; |
---|
227 | $replace['apostrophe'] = '$1’$2'; |
---|
228 | |
---|
229 | // 'single quoted text' becomes ‘single quoted text’ |
---|
230 | $search['single_quotes'] = '/(^|[^\w=])(?:\'|'|‘)([^\']+?)(?:\'|'|’)([^\w]|$)/ms'; |
---|
231 | $replace['single_quotes'] = '$1‘$2’$3'; |
---|
232 | |
---|
233 | // plural posessives' apostrophes become posessives’ |
---|
234 | $search['apostrophes'] = '/(s)(?:\'|'|')(\s)/ms'; |
---|
235 | $replace['apostrophes'] = '$1’$2'; |
---|
236 | |
---|
237 | // em--dashes become em—dashes |
---|
238 | $search['em_dash'] = '/(\s*[^!<-])--([^>-]\s*)/'; |
---|
239 | $replace['em_dash'] = '$1—$2'; |
---|
240 | |
---|
241 | return preg_replace($search, $replace, $text); |
---|
242 | } |
---|
243 | |
---|
244 | /* |
---|
245 | * Finds all URLs in text and hyperlinks them. |
---|
246 | * |
---|
247 | * @access public |
---|
248 | * @param string $text Text to search for URLs. |
---|
249 | * @param bool $strict True to only include URLs starting with a scheme (http:// ftp:// im://), or false to include URLs starting with 'www.'. |
---|
250 | * @param mixed $length Number of characters to truncate URL, or NULL to disable truncating. |
---|
251 | * @param string $delim Delimiter to append, indicate truncation. |
---|
252 | * @return string Same input text, but URLs hyperlinked. |
---|
253 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
254 | * @version 2.2 |
---|
255 | * @since 22 Mar 2015 23:29:04 |
---|
256 | */ |
---|
257 | function hyperlinkTxt($text, $strict=false, $length=null, $delim='âŠ') |
---|
258 | { |
---|
259 | // A list of schemes we allow at the beginning of a URL. |
---|
260 | $schemes = 'mailto:|tel:|skype:|callto:|facetime:|bitcoin:|geo:|magnet:\?|sip:|sms:|xmpp:|view-source:(?:https?://)?|[\w-]{2,}://'; |
---|
261 | |
---|
262 | // Capture the full URL into the first match and only the first X characters into the second match. |
---|
263 | // This will match URLs not preceded by " ' or = (URLs inside an attribute) or ` (Markdown quoted) or double-scheme (http://http://www.asdf.com) |
---|
264 | // Valid URL characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;= |
---|
265 | $regex = '@ |
---|
266 | \b # Start with a word-boundary. |
---|
267 | (?<!"|\'|=|>|`|\]\(|\[\d\] |[:/]/) # Negative look-behind to exclude URLs already in <a> tag, <tags>beween</tags>, `Markdown quoted`, [Markdown](link), [1] www.markdown.footnotes, and avoid broken:/ and doubled://schemes:// |
---|
268 | ( # Begin match 1 |
---|
269 | ( # Begin match 2 |
---|
270 | (?:%s) # URL starts with known scheme or www. if strict = false |
---|
271 | [^\s/$.?#]+ # Any domain-valid characters |
---|
272 | [^\s"`<>]{1,%s} # Match 2 is limited to a maximum of LENGTH valid URL characters |
---|
273 | ) |
---|
274 | [^\s"`<>]* # Match 1 continues with any further valid URL characters |
---|
275 | ([^\P{Any}\sâŠ<>«»"ââ%s]) # Final character not a space or common end-of-sentence punctuation (.,:;?!, etc). Using double negation set, see http://stackoverflow.com/a/4786560/277303 |
---|
276 | ) |
---|
277 | @Suxi |
---|
278 | '; |
---|
279 | $regex = sprintf($regex, |
---|
280 | ($strict ? $schemes : $schemes . '|www\.'), // Strict=false adds "www." to the list of allowed start-of-URL. |
---|
281 | ($length ? $length : ''), |
---|
282 | ($strict ? '' : '?!.,:;)\'-') // Strict=false excludes some "URL-valid" characters from the last character of URL. (Hyphen must remain last character in this class.) |
---|
283 | ); |
---|
284 | |
---|
285 | // Use a callback function to decide when to append the delim. |
---|
286 | // Also encode special chars with oTxt(). |
---|
287 | return preg_replace_callback($regex, function ($m) use ($length, $delim) { |
---|
288 | $url = $m[1]; |
---|
289 | $truncated_url = $m[2] . $m[3]; |
---|
290 | $absolute_url = preg_replace('!^www\.!', 'http://www.', $url); |
---|
291 | if (is_null($length) || $url == $truncated_url) { |
---|
292 | // If not truncating, or URL was not truncated. |
---|
293 | // Remove http schemas, and any single trailing / to make the display URL. |
---|
294 | $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], $url); |
---|
295 | return sprintf('<a href="%s">%s</a>', oTxt($absolute_url), $display_url); |
---|
296 | } else { |
---|
297 | // Truncated URL. |
---|
298 | // Remove http schemas, and any single trailing / to make the display URL. |
---|
299 | $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], trim($truncated_url)); |
---|
300 | return sprintf('<a href="%s">%s%s</a>', oTxt($absolute_url), $display_url, $delim); |
---|
301 | } |
---|
302 | }, $text); |
---|
303 | } |
---|
304 | |
---|
305 | /** |
---|
306 | * Applies a class to search terms to highlight them ala google results. |
---|
307 | * |
---|
308 | * @param string $text Input text to search. |
---|
309 | * @param string $search String of word(s) that will be highlighted. |
---|
310 | * @param string $class CSS class to apply. |
---|
311 | * @return string Text with searched words wrapped in <span>. |
---|
312 | */ |
---|
313 | function highlightWords($text, $search, $class='sc-highlightwords') |
---|
314 | { |
---|
315 | $words = preg_split('/[^\w]/', $search, -1, PREG_SPLIT_NO_EMPTY); |
---|
316 | |
---|
317 | $search = array(); |
---|
318 | $replace = array(); |
---|
319 | |
---|
320 | foreach ($words as $w) { |
---|
321 | if ('' != trim($w)) { |
---|
322 | $search[] = '/\b(' . preg_quote($w) . ')\b/i'; |
---|
323 | $replace[] = '<span class="' . $class . '">$1</span>'; |
---|
324 | } |
---|
325 | } |
---|
326 | |
---|
327 | return empty($replace) ? $text : preg_replace($search, $replace, $text); |
---|
328 | } |
---|
329 | |
---|
330 | /** |
---|
331 | * Generates a hexadecimal html color based on provided word. |
---|
332 | * |
---|
333 | * @access public |
---|
334 | * @param string $text A string for which to convert to color. |
---|
335 | * @return string A hexadecimal html color. |
---|
336 | */ |
---|
337 | function getTextColor($text, $method=1, $n=0.87) |
---|
338 | { |
---|
339 | $hash = md5($text); |
---|
340 | $rgb = array( |
---|
341 | mb_substr($hash, 0, 1), |
---|
342 | mb_substr($hash, 1, 1), |
---|
343 | mb_substr($hash, 2, 1), |
---|
344 | mb_substr($hash, 3, 1), |
---|
345 | mb_substr($hash, 4, 1), |
---|
346 | mb_substr($hash, 5, 1), |
---|
347 | ); |
---|
348 | |
---|
349 | switch ($method) { |
---|
350 | case 1 : |
---|
351 | default : |
---|
352 | // Reduce all hex values slightly to avoid all white. |
---|
353 | array_walk($rgb, create_function('&$v', "\$v = dechex(round(hexdec(\$v) * $n));")); |
---|
354 | break; |
---|
355 | case 2 : |
---|
356 | foreach ($rgb as $i => $v) { |
---|
357 | if (hexdec($v) > hexdec('c')) { |
---|
358 | $rgb[$i] = dechex(hexdec('f') - hexdec($v)); |
---|
359 | } |
---|
360 | } |
---|
361 | break; |
---|
362 | } |
---|
363 | |
---|
364 | return join('', $rgb); |
---|
365 | } |
---|
366 | |
---|
367 | /** |
---|
368 | * Encodes a string into unicode values 128-255. |
---|
369 | * Useful for hiding an email address from spambots. |
---|
370 | * |
---|
371 | * @access public |
---|
372 | * @param string $text A line of text to encode. |
---|
373 | * @return string Encoded text. |
---|
374 | */ |
---|
375 | function encodeAscii($text) |
---|
376 | { |
---|
377 | $output = ''; |
---|
378 | $num = mb_strlen($text); |
---|
379 | for ($i=0; $i<$num; $i++) { |
---|
380 | $output .= sprintf('&#%03s', ord($text{$i})); |
---|
381 | } |
---|
382 | return $output; |
---|
383 | } |
---|
384 | |
---|
385 | /** |
---|
386 | * Encodes an email into a "user at domain dot com" format. |
---|
387 | * |
---|
388 | * @access public |
---|
389 | * @param string $email An email to encode. |
---|
390 | * @param string $at Replaces the @. |
---|
391 | * @param string $dot Replaces the .. |
---|
392 | * @return string Encoded email. |
---|
393 | */ |
---|
394 | function encodeEmail($email, $at=' at ', $dot=' dot ') |
---|
395 | { |
---|
396 | $search = array('/@/', '/\./'); |
---|
397 | $replace = array($at, $dot); |
---|
398 | return preg_replace($search, $replace, $email); |
---|
399 | } |
---|
400 | |
---|
401 | /** |
---|
402 | * Truncates "a really long string" into a string of specified length |
---|
403 | * at the beginning: "âŠlong string" |
---|
404 | * at the middle: "a reaâŠstring" |
---|
405 | * or at the end: "a reallyâŠ". |
---|
406 | * |
---|
407 | * The regular expressions below first match and replace the string to the specified length and position, |
---|
408 | * and secondly they remove any whitespace from around the delimiter (to avoid "this ⊠" from happening). |
---|
409 | * |
---|
410 | * @access public |
---|
411 | * @param string $str Input string |
---|
412 | * @param int $len Maximum string length. |
---|
413 | * @param string $where Where to cut the string. One of: 'start', 'middle', or 'end'. |
---|
414 | * @return string Truncated output string. |
---|
415 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
416 | * @since 29 Mar 2006 13:48:49 |
---|
417 | */ |
---|
418 | function truncate($str, $len=50, $where='end', $delim='âŠ') |
---|
419 | { |
---|
420 | $dlen = mb_strlen($delim); |
---|
421 | if ($len <= $dlen || mb_strlen($str) <= $dlen) { |
---|
422 | return substr($str, 0, $len); |
---|
423 | } |
---|
424 | $part1 = floor(($len - $dlen) / 2); |
---|
425 | $part2 = ceil(($len - $dlen) / 2); |
---|
426 | |
---|
427 | if ($len > ini_get('pcre.backtrack_limit')) { |
---|
428 | $app =& App::getInstance(); |
---|
429 | $app->logMsg(sprintf('Asked to truncate string len of %s > pcre.backtrack_limit of %s', $len, ini_get('pcre.backtrack_limit')), LOG_DEBUG, __FILE__, __LINE__); |
---|
430 | ini_set('pcre.backtrack_limit', $len); |
---|
431 | } |
---|
432 | |
---|
433 | switch ($where) { |
---|
434 | case 'start' : |
---|
435 | return preg_replace(array(sprintf('/^.{%s,}(.{%s})$/su', $dlen + 1, $part1 + $part2), sprintf('/\s*%s{%s,}\s*/su', preg_quote($delim), $dlen)), array($delim . '$1', $delim), $str); |
---|
436 | |
---|
437 | case 'middle' : |
---|
438 | return preg_replace(array(sprintf('/^(.{%s}).{%s,}(.{%s})$/su', $part1, $dlen + 1, $part2), sprintf('/\s*%s{%s,}\s*/su', preg_quote($delim), $dlen)), array('$1' . $delim . '$2', $delim), $str); |
---|
439 | |
---|
440 | case 'end' : |
---|
441 | default : |
---|
442 | return preg_replace(array(sprintf('/^(.{%s}).{%s,}$/su', $part1 + $part2, $dlen + 1), sprintf('/\s*%s{%s,}\s*/su', preg_quote($delim), $dlen)), array('$1' . $delim, $delim), $str); |
---|
443 | } |
---|
444 | } |
---|
445 | |
---|
446 | /* |
---|
447 | * A substitution for the missing mb_ucfirst function. |
---|
448 | * |
---|
449 | * @access public |
---|
450 | * @param string $string The string |
---|
451 | * @return string String with upper-cased first character. |
---|
452 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
453 | * @version 1.0 |
---|
454 | * @since 06 Dec 2008 17:04:01 |
---|
455 | */ |
---|
456 | if (!function_exists('mb_ucfirst')) { |
---|
457 | function mb_ucfirst($string) |
---|
458 | { |
---|
459 | return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1, mb_strlen($string)); |
---|
460 | } |
---|
461 | } |
---|
462 | |
---|
463 | /* |
---|
464 | * A substitution for the missing mb_strtr function. |
---|
465 | * |
---|
466 | * @access public |
---|
467 | * @param string $string The string |
---|
468 | * @param string $from String of characters to translate from |
---|
469 | * @param string $to String of characters to translate to |
---|
470 | * @return string String with translated characters. |
---|
471 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
472 | * @version 1.0 |
---|
473 | * @since 20 Jan 2013 12:33:26 |
---|
474 | */ |
---|
475 | if (!function_exists('mb_strtr')) { |
---|
476 | function mb_strtr($string, $from, $to) |
---|
477 | { |
---|
478 | return str_replace(mb_split('.', $from), mb_split('.', $to), $string); |
---|
479 | } |
---|
480 | } |
---|
481 | |
---|
482 | /* |
---|
483 | * A substitution for the missing mb_str_pad function. |
---|
484 | * |
---|
485 | * @access public |
---|
486 | * @param string $input The string that receives padding. |
---|
487 | * @param string $pad_length Total length of resultant string. |
---|
488 | * @param string $pad_string The string to use for padding |
---|
489 | * @param string $pad_type Flags STR_PAD_RIGHT or STR_PAD_LEFT or STR_PAD_BOTH |
---|
490 | * @return string String with translated characters. |
---|
491 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
492 | * @version 1.0 |
---|
493 | * @since 20 Jan 2013 12:33:26 |
---|
494 | */ |
---|
495 | if (!function_exists('mb_str_pad')) { |
---|
496 | function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) { |
---|
497 | $diff = strlen($input) - mb_strlen($input); |
---|
498 | return str_pad($input, $pad_length + $diff, $pad_string, $pad_type); |
---|
499 | } |
---|
500 | } |
---|
501 | |
---|
502 | /* |
---|
503 | * Converts a string into a URL-safe slug, removing spaces and non word characters. |
---|
504 | * |
---|
505 | * @access public |
---|
506 | * @param string $str String to convert. |
---|
507 | * @return string URL-safe slug. |
---|
508 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
509 | * @version 1.0 |
---|
510 | * @since 18 Aug 2014 12:54:29 |
---|
511 | */ |
---|
512 | function URLSlug($str) |
---|
513 | { |
---|
514 | $slug = preg_replace(array('/\W+/u', '/^-+|-+$/'), array('-', ''), $str); |
---|
515 | $slug = strtolower($slug); |
---|
516 | return $slug; |
---|
517 | } |
---|
518 | |
---|
519 | /** |
---|
520 | * Return a human readable disk space measurement. Input value measured in bytes. |
---|
521 | * |
---|
522 | * @param int $size Size in bytes. |
---|
523 | * @param int $unit The maximum unit |
---|
524 | * @param int $format The return string format |
---|
525 | * @author Aidan Lister <aidan@php.net> |
---|
526 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
527 | * @version 1.2.0 |
---|
528 | */ |
---|
529 | function humanFileSize($size, $format='%01.2f %s', $max_unit=null, $multiplier=1024) |
---|
530 | { |
---|
531 | // Units |
---|
532 | $units = array('B', 'KB', 'MB', 'GB', 'TB'); |
---|
533 | $ii = count($units) - 1; |
---|
534 | |
---|
535 | // Max unit |
---|
536 | $max_unit = array_search((string) $max_unit, $units); |
---|
537 | if ($max_unit === null || $max_unit === false) { |
---|
538 | $max_unit = $ii; |
---|
539 | } |
---|
540 | |
---|
541 | // Loop |
---|
542 | $i = 0; |
---|
543 | while ($max_unit != $i && $size >= $multiplier && $i < $ii) { |
---|
544 | $size /= $multiplier; |
---|
545 | $i++; |
---|
546 | } |
---|
547 | |
---|
548 | return sprintf($format, $size, $units[$i]); |
---|
549 | } |
---|
550 | |
---|
551 | /* |
---|
552 | * Returns a human readable amount of time for the given amount of seconds. |
---|
553 | * |
---|
554 | * 45 seconds |
---|
555 | * 12 minutes |
---|
556 | * 3.5 hours |
---|
557 | * 2 days |
---|
558 | * 1 week |
---|
559 | * 4 months |
---|
560 | * |
---|
561 | * Months are calculated using the real number of days in a year: 365.2422 / 12. |
---|
562 | * |
---|
563 | * @access public |
---|
564 | * @param int $seconds Seconds of time. |
---|
565 | * @param string $max_unit Key value from the $units array. |
---|
566 | * @param string $format Sprintf formatting string. |
---|
567 | * @return string Value of units elapsed. |
---|
568 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
569 | * @version 1.0 |
---|
570 | * @since 23 Jun 2006 12:15:19 |
---|
571 | */ |
---|
572 | function humanTime($seconds, $max_unit=null, $format='%01.1f') |
---|
573 | { |
---|
574 | // Units: array of seconds in the unit, singular and plural unit names. |
---|
575 | $units = array( |
---|
576 | 'second' => array(1, _("second"), _("seconds")), |
---|
577 | 'minute' => array(60, _("minute"), _("minutes")), |
---|
578 | 'hour' => array(3600, _("hour"), _("hours")), |
---|
579 | 'day' => array(86400, _("day"), _("days")), |
---|
580 | 'week' => array(604800, _("week"), _("weeks")), |
---|
581 | 'month' => array(2629743.84, _("month"), _("months")), |
---|
582 | 'year' => array(31556926.08, _("year"), _("years")), |
---|
583 | 'decade' => array(315569260.8, _("decade"), _("decades")), |
---|
584 | 'century' => array(3155692608, _("century"), _("centuries")), |
---|
585 | ); |
---|
586 | |
---|
587 | // Max unit to calculate. |
---|
588 | $max_unit = isset($units[$max_unit]) ? $max_unit : 'year'; |
---|
589 | |
---|
590 | $final_time = $seconds; |
---|
591 | $final_unit = 'second'; |
---|
592 | foreach ($units as $k => $v) { |
---|
593 | if ($seconds >= $v[0]) { |
---|
594 | $final_time = $seconds / $v[0]; |
---|
595 | $final_unit = $k; |
---|
596 | } |
---|
597 | if ($max_unit == $final_unit) { |
---|
598 | break; |
---|
599 | } |
---|
600 | } |
---|
601 | $final_time = sprintf($format, $final_time); |
---|
602 | return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2])); |
---|
603 | } |
---|
604 | |
---|
605 | /** |
---|
606 | * Removes non-latin characters from file name, using htmlentities to convert known weirdos into regular squares. |
---|
607 | * |
---|
608 | * @access public |
---|
609 | * @param string $file_name A name of a file. |
---|
610 | * @return string The same name, but cleaned. |
---|
611 | */ |
---|
612 | function cleanFileName($file_name) |
---|
613 | { |
---|
614 | $app =& App::getInstance(); |
---|
615 | |
---|
616 | $file_name = preg_replace(array( |
---|
617 | '/&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml|caron);/ui', |
---|
618 | '/&(?:amp);/ui', |
---|
619 | '/[&;]+/u', |
---|
620 | '/[^a-zA-Z0-9()@._=+-]+/u', |
---|
621 | '/^_+|_+$/u' |
---|
622 | ), array( |
---|
623 | '$1', |
---|
624 | 'and', |
---|
625 | '', |
---|
626 | '_', |
---|
627 | '' |
---|
628 | ), htmlentities($file_name, ENT_NOQUOTES | ENT_IGNORE, $app->getParam('character_set'))); |
---|
629 | return mb_substr($file_name, 0, 250); |
---|
630 | } |
---|
631 | |
---|
632 | /** |
---|
633 | * Returns the extension of a file name, or an empty string if none exists. |
---|
634 | * |
---|
635 | * @access public |
---|
636 | * @param string $file_name A name of a file, with extension after a dot. |
---|
637 | * @return string The value found after the dot |
---|
638 | */ |
---|
639 | function getFilenameExtension($file_name) |
---|
640 | { |
---|
641 | preg_match('/.*?\.(\w+)$/i', trim($file_name), $ext); |
---|
642 | return isset($ext[1]) ? $ext[1] : ''; |
---|
643 | } |
---|
644 | |
---|
645 | /* |
---|
646 | * Convert a php.ini value (8M, 512K, etc), into integer value of bytes. |
---|
647 | * |
---|
648 | * @access public |
---|
649 | * @param string $val Value from php config, e.g., upload_max_filesize. |
---|
650 | * @return int Value converted to bytes as an integer. |
---|
651 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
652 | * @version 1.0 |
---|
653 | * @since 20 Aug 2014 14:32:41 |
---|
654 | */ |
---|
655 | function phpIniGetBytes($val) |
---|
656 | { |
---|
657 | $val = trim(ini_get($val)); |
---|
658 | if ($val != '') { |
---|
659 | $last = strtolower($val{strlen($val) - 1}); |
---|
660 | } else { |
---|
661 | $last = ''; |
---|
662 | } |
---|
663 | switch ($last) { |
---|
664 | // The 'G' modifier is available since PHP 5.1.0 |
---|
665 | case 'g': |
---|
666 | $val *= 1024; |
---|
667 | case 'm': |
---|
668 | $val *= 1024; |
---|
669 | case 'k': |
---|
670 | $val *= 1024; |
---|
671 | } |
---|
672 | |
---|
673 | return (int)$val; |
---|
674 | } |
---|
675 | |
---|
676 | /** |
---|
677 | * Tests the existence of a file anywhere in the include path. |
---|
678 | * Replaced by stream_resolve_include_path() in PHP 5 >= 5.3.2 |
---|
679 | * |
---|
680 | * @param string $file File in include path. |
---|
681 | * @return mixed False if file not found, the path of the file if it is found. |
---|
682 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
683 | * @since 03 Dec 2005 14:23:26 |
---|
684 | */ |
---|
685 | function fileExistsIncludePath($file) |
---|
686 | { |
---|
687 | $app =& App::getInstance(); |
---|
688 | |
---|
689 | foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) { |
---|
690 | $fullpath = $path . DIRECTORY_SEPARATOR . $file; |
---|
691 | if (file_exists($fullpath)) { |
---|
692 | $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__); |
---|
693 | return $fullpath; |
---|
694 | } else { |
---|
695 | $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__); |
---|
696 | return false; |
---|
697 | } |
---|
698 | } |
---|
699 | } |
---|
700 | |
---|
701 | /** |
---|
702 | * Returns stats of a file from the include path. |
---|
703 | * |
---|
704 | * @param string $file File in include path. |
---|
705 | * @param mixed $stat Which statistic to return (or null to return all). |
---|
706 | * @return mixed Value of requested key from fstat(), or false on error. |
---|
707 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
708 | * @since 03 Dec 2005 14:23:26 |
---|
709 | */ |
---|
710 | function statIncludePath($file, $stat=null) |
---|
711 | { |
---|
712 | // Open file pointer read-only using include path. |
---|
713 | if ($fp = fopen($file, 'r', true)) { |
---|
714 | // File opened successfully, get stats. |
---|
715 | $stats = fstat($fp); |
---|
716 | fclose($fp); |
---|
717 | // Return specified stats. |
---|
718 | return is_null($stat) ? $stats : $stats[$stat]; |
---|
719 | } else { |
---|
720 | return false; |
---|
721 | } |
---|
722 | } |
---|
723 | |
---|
724 | /* |
---|
725 | * Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5. |
---|
726 | * It makes an exclusive lock on the file while writing. |
---|
727 | * |
---|
728 | * @access public |
---|
729 | * @param string $filename Path to file. |
---|
730 | * @param string $content Data to write into file. |
---|
731 | * @return bool Success or failure. |
---|
732 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
733 | * @since 11 Apr 2006 22:48:30 |
---|
734 | */ |
---|
735 | function filePutContents($filename, $content) |
---|
736 | { |
---|
737 | $app =& App::getInstance(); |
---|
738 | |
---|
739 | // Open file for writing and truncate to zero length. |
---|
740 | if ($fp = fopen($filename, 'w')) { |
---|
741 | if (flock($fp, LOCK_EX)) { |
---|
742 | if (!fwrite($fp, $content, mb_strlen($content))) { |
---|
743 | $app->logMsg(sprintf('Failed writing to file: %s', $filename), LOG_ERR, __FILE__, __LINE__); |
---|
744 | fclose($fp); |
---|
745 | return false; |
---|
746 | } |
---|
747 | flock($fp, LOCK_UN); |
---|
748 | } else { |
---|
749 | $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__); |
---|
750 | fclose($fp); |
---|
751 | return false; |
---|
752 | } |
---|
753 | fclose($fp); |
---|
754 | // Success! |
---|
755 | $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__); |
---|
756 | return true; |
---|
757 | } else { |
---|
758 | $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__); |
---|
759 | return false; |
---|
760 | } |
---|
761 | } |
---|
762 | |
---|
763 | /** |
---|
764 | * If $var is net set or null, set it to $default. Otherwise leave it alone. |
---|
765 | * Returns the final value of $var. Use to find a default value of one is not available. |
---|
766 | * |
---|
767 | * @param mixed $var The variable that is being set. |
---|
768 | * @param mixed $default What to set it to if $val is not currently set. |
---|
769 | * @return mixed The resulting value of $var. |
---|
770 | */ |
---|
771 | function setDefault(&$var, $default='') |
---|
772 | { |
---|
773 | if (!isset($var)) { |
---|
774 | $var = $default; |
---|
775 | } |
---|
776 | return $var; |
---|
777 | } |
---|
778 | |
---|
779 | /** |
---|
780 | * Like preg_quote() except for arrays, it takes an array of strings and puts |
---|
781 | * a backslash in front of every character that is part of the regular |
---|
782 | * expression syntax. |
---|
783 | * |
---|
784 | * @param array $array input array |
---|
785 | * @param array $delim optional character that will also be escaped. |
---|
786 | * @return array an array with the same values as $array1 but shuffled |
---|
787 | */ |
---|
788 | function pregQuoteArray($array, $delim='/') |
---|
789 | { |
---|
790 | if (!empty($array)) { |
---|
791 | if (is_array($array)) { |
---|
792 | foreach ($array as $key=>$val) { |
---|
793 | $quoted_array[$key] = preg_quote($val, $delim); |
---|
794 | } |
---|
795 | return $quoted_array; |
---|
796 | } else { |
---|
797 | return preg_quote($array, $delim); |
---|
798 | } |
---|
799 | } |
---|
800 | } |
---|
801 | |
---|
802 | /** |
---|
803 | * Converts a PHP Array into encoded URL arguments and return them as an array. |
---|
804 | * |
---|
805 | * @param mixed $data An array to transverse recursively, or a string |
---|
806 | * to use directly to create url arguments. |
---|
807 | * @param string $prefix The name of the first dimension of the array. |
---|
808 | * If not specified, the first keys of the array will be used. |
---|
809 | * @return array URL with array elements as URL key=value arguments. |
---|
810 | */ |
---|
811 | function urlEncodeArray($data, $prefix='', $_return=true) |
---|
812 | { |
---|
813 | // Data is stored in static variable. |
---|
814 | static $args = array(); |
---|
815 | |
---|
816 | if (is_array($data)) { |
---|
817 | foreach ($data as $key => $val) { |
---|
818 | // If the prefix is empty, use the $key as the name of the first dimension of the "array". |
---|
819 | // ...otherwise, append the key as a new dimension of the "array". |
---|
820 | $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']'; |
---|
821 | // Enter recursion. |
---|
822 | urlEncodeArray($val, $new_prefix, false); |
---|
823 | } |
---|
824 | } else { |
---|
825 | // We've come to the last dimension of the array, save the "array" and its value. |
---|
826 | $args[$prefix] = urlencode($data); |
---|
827 | } |
---|
828 | |
---|
829 | if ($_return) { |
---|
830 | // This is not a recursive execution. All recursion is complete. |
---|
831 | // Reset static var and return the result. |
---|
832 | $ret = $args; |
---|
833 | $args = array(); |
---|
834 | return is_array($ret) ? $ret : array(); |
---|
835 | } |
---|
836 | } |
---|
837 | |
---|
838 | /** |
---|
839 | * Converts a PHP Array into encoded URL arguments and return them in a string. |
---|
840 | * |
---|
841 | * Todo: probably update to use the built-in http_build_query(). |
---|
842 | * |
---|
843 | * @param mixed $data An array to transverse recursively, or a string |
---|
844 | * to use directly to create url arguments. |
---|
845 | * @param string $prefix The name of the first dimension of the array. |
---|
846 | * If not specified, the first keys of the array will be used. |
---|
847 | * @return string url A string ready to append to a url. |
---|
848 | */ |
---|
849 | function urlEncodeArrayToString($data, $prefix='') |
---|
850 | { |
---|
851 | |
---|
852 | $array_args = urlEncodeArray($data, $prefix); |
---|
853 | $url_args = ''; |
---|
854 | $delim = ''; |
---|
855 | foreach ($array_args as $key=>$val) { |
---|
856 | $url_args .= $delim . $key . '=' . $val; |
---|
857 | $delim = ini_get('arg_separator.output'); |
---|
858 | } |
---|
859 | return $url_args; |
---|
860 | } |
---|
861 | |
---|
862 | /** |
---|
863 | * Fills an array with the result from a multiple ereg search. |
---|
864 | * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001 |
---|
865 | * |
---|
866 | * @param mixed $pattern regular expression needle |
---|
867 | * @param mixed $string haystack |
---|
868 | * @return array populated with each found result |
---|
869 | */ |
---|
870 | function eregAll($pattern, $string) |
---|
871 | { |
---|
872 | do { |
---|
873 | if (!mb_ereg($pattern, $string, $temp)) { |
---|
874 | continue; |
---|
875 | } |
---|
876 | $string = str_replace($temp[0], '', $string); |
---|
877 | $results[] = $temp; |
---|
878 | } while (mb_ereg($pattern, $string, $temp)); |
---|
879 | return $results; |
---|
880 | } |
---|
881 | |
---|
882 | /** |
---|
883 | * Prints the word "checked" if a variable is set, and optionally matches |
---|
884 | * the desired value, otherwise prints nothing, |
---|
885 | * used for printing the word "checked" in a checkbox form input. |
---|
886 | * |
---|
887 | * @param mixed $var the variable to compare |
---|
888 | * @param mixed $value optional, what to compare with if a specific value is required. |
---|
889 | */ |
---|
890 | function frmChecked($var, $value=null) |
---|
891 | { |
---|
892 | if (func_num_args() == 1 && $var) { |
---|
893 | // 'Checked' if var is true. |
---|
894 | echo ' checked="checked" '; |
---|
895 | } else if (func_num_args() == 2 && $var == $value) { |
---|
896 | // 'Checked' if var and value match. |
---|
897 | echo ' checked="checked" '; |
---|
898 | } else if (func_num_args() == 2 && is_array($var)) { |
---|
899 | // 'Checked' if the value is in the key or the value of an array. |
---|
900 | if (isset($var[$value])) { |
---|
901 | echo ' checked="checked" '; |
---|
902 | } else if (in_array($value, $var)) { |
---|
903 | echo ' checked="checked" '; |
---|
904 | } |
---|
905 | } |
---|
906 | } |
---|
907 | |
---|
908 | /** |
---|
909 | * prints the word "selected" if a variable is set, and optionally matches |
---|
910 | * the desired value, otherwise prints nothing, |
---|
911 | * otherwise prints nothing, used for printing the word "checked" in a |
---|
912 | * select form input |
---|
913 | * |
---|
914 | * @param mixed $var the variable to compare |
---|
915 | * @param mixed $value optional, what to compare with if a specific value is required. |
---|
916 | */ |
---|
917 | function frmSelected($var, $value=null) |
---|
918 | { |
---|
919 | if (func_num_args() == 1 && $var) { |
---|
920 | // 'selected' if var is true. |
---|
921 | echo ' selected="selected" '; |
---|
922 | } else if (func_num_args() == 2 && $var == $value) { |
---|
923 | // 'selected' if var and value match. |
---|
924 | echo ' selected="selected" '; |
---|
925 | } else if (func_num_args() == 2 && is_array($var)) { |
---|
926 | // 'selected' if the value is in the key or the value of an array. |
---|
927 | if (isset($var[$value])) { |
---|
928 | echo ' selected="selected" '; |
---|
929 | } else if (in_array($value, $var)) { |
---|
930 | echo ' selected="selected" '; |
---|
931 | } |
---|
932 | } |
---|
933 | } |
---|
934 | |
---|
935 | /** |
---|
936 | * Adds slashes to values of an array and converts the array to a comma |
---|
937 | * delimited list. If value provided is a string return the string |
---|
938 | * escaped. This is useful for putting values coming in from posted |
---|
939 | * checkboxes into a SET column of a database. |
---|
940 | * |
---|
941 | * |
---|
942 | * @param array $in Array to convert. |
---|
943 | * @return string Comma list of array values. |
---|
944 | */ |
---|
945 | function escapedList($in, $separator="', '") |
---|
946 | { |
---|
947 | require_once dirname(__FILE__) . '/DB.inc.php'; |
---|
948 | $db =& DB::getInstance(); |
---|
949 | |
---|
950 | if (is_array($in) && !empty($in)) { |
---|
951 | return join($separator, array_map(array($db, 'escapeString'), $in)); |
---|
952 | } else { |
---|
953 | return $db->escapeString($in); |
---|
954 | } |
---|
955 | } |
---|
956 | |
---|
957 | /** |
---|
958 | * Converts a human string date into a SQL-safe date. Dates nearing |
---|
959 | * infinity use the date 2038-01-01 so conversion to unix time format |
---|
960 | * remain within valid range. |
---|
961 | * |
---|
962 | * @param array $date String date to convert. |
---|
963 | * @param array $format Date format to pass to date(). Default produces MySQL datetime: YYYY-MM-DD hh:mm:ss |
---|
964 | * @return string SQL-safe date. |
---|
965 | */ |
---|
966 | function strToSQLDate($date, $format='Y-m-d H:i:s') |
---|
967 | { |
---|
968 | require_once dirname(__FILE__) . '/DB.inc.php'; |
---|
969 | $db =& DB::getInstance(); |
---|
970 | |
---|
971 | if ($db->isConnected() && mb_strpos($db->getParam('zero_date'), '-') !== false) { |
---|
972 | // Mysql version >= 5.7.4 stopped allowing a "zero" date of 0000-00-00. |
---|
973 | // https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_date |
---|
974 | $zero_date_parts = explode('-', $db->getParam('zero_date')); |
---|
975 | $zero_y = $zero_date_parts[0]; |
---|
976 | $zero_m = $zero_date_parts[1]; |
---|
977 | $zero_d = $zero_date_parts[2]; |
---|
978 | } else { |
---|
979 | $zero_y = '0000'; |
---|
980 | $zero_m = '00'; |
---|
981 | $zero_d = '00'; |
---|
982 | } |
---|
983 | // Translate the human string date into SQL-safe date format. |
---|
984 | if (empty($date) || mb_strpos($date, sprintf('%s-%s-%s', $zero_y, $zero_m, $zero_d)) !== false || strtotime($date) === -1 || strtotime($date) === false || strtotime($date) === null) { |
---|
985 | // Return a string of zero time, formatted the same as $format. |
---|
986 | return strtr($format, array( |
---|
987 | 'Y' => $zero_y, |
---|
988 | 'm' => $zero_m, |
---|
989 | 'd' => $zero_d, |
---|
990 | 'H' => '00', |
---|
991 | 'i' => '00', |
---|
992 | 's' => '00', |
---|
993 | )); |
---|
994 | } else { |
---|
995 | return date($format, strtotime($date)); |
---|
996 | } |
---|
997 | } |
---|
998 | |
---|
999 | /** |
---|
1000 | * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an |
---|
1001 | * array, stripslashes is run on each value, recursively, and the stripped |
---|
1002 | * array is returned. |
---|
1003 | * |
---|
1004 | * @param mixed $var The string or array to un-quote, if necessary. |
---|
1005 | * @return mixed $var, minus any magic quotes. |
---|
1006 | */ |
---|
1007 | function dispelMagicQuotes($var, $always=false) |
---|
1008 | { |
---|
1009 | static $magic_quotes_gpc; |
---|
1010 | |
---|
1011 | if (!isset($magic_quotes_gpc)) { |
---|
1012 | $magic_quotes_gpc = get_magic_quotes_gpc(); |
---|
1013 | } |
---|
1014 | |
---|
1015 | if ($always || $magic_quotes_gpc) { |
---|
1016 | if (!is_array($var)) { |
---|
1017 | $var = stripslashes($var); |
---|
1018 | } else { |
---|
1019 | foreach ($var as $key=>$val) { |
---|
1020 | if (is_array($val)) { |
---|
1021 | $var[$key] = dispelMagicQuotes($val, $always); |
---|
1022 | } else { |
---|
1023 | $var[$key] = stripslashes($val); |
---|
1024 | } |
---|
1025 | } |
---|
1026 | } |
---|
1027 | } |
---|
1028 | return $var; |
---|
1029 | } |
---|
1030 | |
---|
1031 | /** |
---|
1032 | * Get a form variable from GET or POST data, stripped of magic |
---|
1033 | * quotes if necessary. |
---|
1034 | * |
---|
1035 | * @param string $var (optional) The name of the form variable to look for. |
---|
1036 | * @param string $default (optional) The value to return if the |
---|
1037 | * variable is not there. |
---|
1038 | * @return mixed A cleaned GET or POST if no $var specified. |
---|
1039 | * @return string A cleaned form $var if found, or $default. |
---|
1040 | */ |
---|
1041 | function getFormData($var=null, $default=null) |
---|
1042 | { |
---|
1043 | $app =& App::getInstance(); |
---|
1044 | |
---|
1045 | if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) { |
---|
1046 | return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes')); |
---|
1047 | } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) { |
---|
1048 | return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes')); |
---|
1049 | } |
---|
1050 | if (isset($_POST[$var])) { |
---|
1051 | return dispelMagicQuotes($_POST[$var], $app->getParam('always_dispel_magicquotes')); |
---|
1052 | } else if (isset($_GET[$var])) { |
---|
1053 | return dispelMagicQuotes($_GET[$var], $app->getParam('always_dispel_magicquotes')); |
---|
1054 | } else { |
---|
1055 | return $default; |
---|
1056 | } |
---|
1057 | } |
---|
1058 | |
---|
1059 | function getPost($var=null, $default=null) |
---|
1060 | { |
---|
1061 | $app =& App::getInstance(); |
---|
1062 | |
---|
1063 | if (is_null($var)) { |
---|
1064 | return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes')); |
---|
1065 | } |
---|
1066 | if (isset($_POST[$var])) { |
---|
1067 | return dispelMagicQuotes($_POST[$var], $app->getParam('always_dispel_magicquotes')); |
---|
1068 | } else { |
---|
1069 | return $default; |
---|
1070 | } |
---|
1071 | } |
---|
1072 | |
---|
1073 | function getGet($var=null, $default=null) |
---|
1074 | { |
---|
1075 | $app =& App::getInstance(); |
---|
1076 | if (is_null($var)) { |
---|
1077 | return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes')); |
---|
1078 | } |
---|
1079 | if (isset($_GET[$var])) { |
---|
1080 | return dispelMagicQuotes($_GET[$var], $app->getParam('always_dispel_magicquotes')); |
---|
1081 | } else { |
---|
1082 | return $default; |
---|
1083 | } |
---|
1084 | } |
---|
1085 | |
---|
1086 | /* |
---|
1087 | * Sets a $_GET or $_POST variable. |
---|
1088 | * |
---|
1089 | * @access public |
---|
1090 | * @param string $key The key of the request array to set. |
---|
1091 | * @param mixed $val The value to save in the request array. |
---|
1092 | * @return void |
---|
1093 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
1094 | * @version 1.0 |
---|
1095 | * @since 01 Nov 2009 12:25:29 |
---|
1096 | */ |
---|
1097 | function putFormData($key, $val) |
---|
1098 | { |
---|
1099 | switch (strtoupper(getenv('REQUEST_METHOD'))) { |
---|
1100 | case 'POST': |
---|
1101 | $_POST[$key] = $val; |
---|
1102 | break; |
---|
1103 | |
---|
1104 | case 'GET': |
---|
1105 | $_GET[$key] = $val; |
---|
1106 | break; |
---|
1107 | } |
---|
1108 | } |
---|
1109 | |
---|
1110 | /* |
---|
1111 | * Generates a base-65-encoded sha512 hash of $string truncated to $length. |
---|
1112 | * |
---|
1113 | * @access public |
---|
1114 | * @param string $string Input string to hash. |
---|
1115 | * @param int $length Length of output hash string. |
---|
1116 | * @return string String of hash. |
---|
1117 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
1118 | * @version 1.0 |
---|
1119 | * @since 03 Apr 2016 19:48:49 |
---|
1120 | */ |
---|
1121 | function hash64($string, $length=18) |
---|
1122 | { |
---|
1123 | return mb_substr(preg_replace('/[^\w]/', '', base64_encode(hash('sha512', $string, true))), 0, $length); |
---|
1124 | } |
---|
1125 | |
---|
1126 | /** |
---|
1127 | * Signs a value using md5 and a simple text key. In order for this |
---|
1128 | * function to be useful (i.e. secure) the salt must be kept secret, which |
---|
1129 | * means keeping it as safe as database credentials. Putting it into an |
---|
1130 | * environment variable set in httpd.conf is a good place. |
---|
1131 | * |
---|
1132 | * @access public |
---|
1133 | * @param string $val The string to sign. |
---|
1134 | * @param string $salt (Optional) A text key to use for computing the signature. |
---|
1135 | * @param string $length (Optional) The length of the added signature. Longer signatures are safer. Must match the length passed to verifySignature() for the signatures to match. |
---|
1136 | * @return string The original value with a signature appended. |
---|
1137 | */ |
---|
1138 | function addSignature($val, $salt=null, $length=18) |
---|
1139 | { |
---|
1140 | $app =& App::getInstance(); |
---|
1141 | |
---|
1142 | if ('' == trim($val)) { |
---|
1143 | $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__); |
---|
1144 | return ''; |
---|
1145 | } |
---|
1146 | |
---|
1147 | if (!isset($salt)) { |
---|
1148 | $salt = $app->getParam('signing_key'); |
---|
1149 | } |
---|
1150 | |
---|
1151 | switch ($app->getParam('signing_method')) { |
---|
1152 | case 'sha512+base64': |
---|
1153 | return $val . '-' . mb_substr(preg_replace('/[^\w]/', '', base64_encode(hash('sha512', $val . $salt, true))), 0, $length); |
---|
1154 | |
---|
1155 | case 'md5': |
---|
1156 | default: |
---|
1157 | return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length)); |
---|
1158 | } |
---|
1159 | } |
---|
1160 | |
---|
1161 | /** |
---|
1162 | * Strips off the signature appended by addSignature(). |
---|
1163 | * |
---|
1164 | * @access public |
---|
1165 | * @param string $signed_val The string to sign. |
---|
1166 | * @return string The original value with a signature removed. |
---|
1167 | */ |
---|
1168 | function removeSignature($signed_val) |
---|
1169 | { |
---|
1170 | if (empty($signed_val) || mb_strpos($signed_val, '-') === false) { |
---|
1171 | return ''; |
---|
1172 | } |
---|
1173 | return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-')); |
---|
1174 | } |
---|
1175 | |
---|
1176 | /** |
---|
1177 | * Verifies a signature appended to a value by addSignature(). |
---|
1178 | * |
---|
1179 | * @access public |
---|
1180 | * @param string $signed_val A value with appended signature. |
---|
1181 | * @param string $salt (Optional) A text key to use for computing the signature. |
---|
1182 | * @param string $length (Optional) The length of the added signature. |
---|
1183 | * @return bool True if the signature matches the var. |
---|
1184 | */ |
---|
1185 | function verifySignature($signed_val, $salt=null, $length=18) |
---|
1186 | { |
---|
1187 | // Strip the value from the signed value. |
---|
1188 | $val = removeSignature($signed_val); |
---|
1189 | // If the signed value matches the original signed value we consider the value safe. |
---|
1190 | if ('' != $signed_val && $signed_val == addSignature($val, $salt, $length)) { |
---|
1191 | // Signature verified. |
---|
1192 | return true; |
---|
1193 | } else { |
---|
1194 | $app =& App::getInstance(); |
---|
1195 | $app->logMsg(sprintf('Failed signature (%s should be %s)', $signed_val, addSignature($val, $salt, $length)), LOG_DEBUG, __FILE__, __LINE__); |
---|
1196 | return false; |
---|
1197 | } |
---|
1198 | } |
---|
1199 | |
---|
1200 | /** |
---|
1201 | * Sends empty output to the browser and flushes the php buffer so the client |
---|
1202 | * will see data before the page is finished processing. |
---|
1203 | */ |
---|
1204 | function flushBuffer() |
---|
1205 | { |
---|
1206 | echo str_repeat(' ', 205); |
---|
1207 | flush(); |
---|
1208 | } |
---|
1209 | |
---|
1210 | /** |
---|
1211 | * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members. |
---|
1212 | * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin". |
---|
1213 | * |
---|
1214 | * @access public |
---|
1215 | * @param string $email Email address to add. |
---|
1216 | * @param string $list Name of list to add to. |
---|
1217 | * @param bool $send_welcome_message True to send welcome message to subscriber. |
---|
1218 | * @return bool True on success, false on failure. |
---|
1219 | */ |
---|
1220 | function mailmanAddMember($email, $list, $send_welcome_message=false) |
---|
1221 | { |
---|
1222 | $app =& App::getInstance(); |
---|
1223 | |
---|
1224 | $add_members = '/usr/lib/mailman/bin/add_members'; |
---|
1225 | if (@is_executable($add_members)) { |
---|
1226 | $welcome_msg = $send_welcome_message ? 'y' : 'n'; |
---|
1227 | exec(sprintf("/bin/echo '%s' | /usr/bin/sudo %s -r - --welcome-msg=%s --admin-notify=n '%s'", escapeshellarg($email), escapeshellarg($add_members), $welcome_msg, escapeshellarg($list)), $stdout, $return_code); |
---|
1228 | if (0 == $return_code) { |
---|
1229 | $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__); |
---|
1230 | return true; |
---|
1231 | } else { |
---|
1232 | $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, getDump($stdout)), LOG_WARNING, __FILE__, __LINE__); |
---|
1233 | return false; |
---|
1234 | } |
---|
1235 | } else { |
---|
1236 | $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_WARNING, __FILE__, __LINE__); |
---|
1237 | return false; |
---|
1238 | } |
---|
1239 | } |
---|
1240 | |
---|
1241 | /** |
---|
1242 | * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members. |
---|
1243 | * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin". |
---|
1244 | * |
---|
1245 | * @access public |
---|
1246 | * @param string $email Email address to add. |
---|
1247 | * @param string $list Name of list to add to. |
---|
1248 | * @param bool $send_user_ack True to send goodbye message to subscriber. |
---|
1249 | * @return bool True on success, false on failure. |
---|
1250 | */ |
---|
1251 | function mailmanRemoveMember($email, $list, $send_user_ack=false) |
---|
1252 | { |
---|
1253 | $app =& App::getInstance(); |
---|
1254 | |
---|
1255 | $remove_members = '/usr/lib/mailman/bin/remove_members'; |
---|
1256 | if (@is_executable($remove_members)) { |
---|
1257 | $userack = $send_user_ack ? '' : '--nouserack'; |
---|
1258 | exec(sprintf("/usr/bin/sudo %s %s --noadminack '%s' '%s'", escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code); |
---|
1259 | if (0 == $return_code) { |
---|
1260 | $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__); |
---|
1261 | return true; |
---|
1262 | } else { |
---|
1263 | $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, getDump($stdout)), LOG_WARNING, __FILE__, __LINE__); |
---|
1264 | return false; |
---|
1265 | } |
---|
1266 | } else { |
---|
1267 | // $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_WARNING, __FILE__, __LINE__); |
---|
1268 | return false; |
---|
1269 | } |
---|
1270 | } |
---|
1271 | |
---|
1272 | /* |
---|
1273 | * Returns the remote IP address, taking into consideration proxy servers. |
---|
1274 | * |
---|
1275 | * If strict checking is enabled, we will only trust REMOTE_ADDR or an HTTP header |
---|
1276 | * value if REMOTE_ADDR is a trusted proxy (configured as an array in $cfg['trusted_proxies']). |
---|
1277 | * |
---|
1278 | * @access public |
---|
1279 | * @param bool $dolookup Resolve to IP to a hostname? |
---|
1280 | * @param bool $trust_all_proxies Should we trust any IP address set in HTTP_* variables? Set to FALSE for secure usage. |
---|
1281 | * @return mixed Canonicalized IP address (or a corresponding hostname if $dolookup is true), or false if no IP was found. |
---|
1282 | * @author Alix Axel <http://stackoverflow.com/a/2031935/277303> |
---|
1283 | * @author Corey Ballou <http://blackbe.lt/advanced-method-to-obtain-the-client-ip-in-php/> |
---|
1284 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
1285 | * @version 1.0 |
---|
1286 | * @since 12 Sep 2014 19:07:46 |
---|
1287 | */ |
---|
1288 | function getRemoteAddr($dolookup=false, $trust_all_proxies=true) |
---|
1289 | { |
---|
1290 | global $cfg; |
---|
1291 | |
---|
1292 | if (!isset($_SERVER['REMOTE_ADDR'])) { |
---|
1293 | // In some cases this won't be set, e.g., CLI scripts. |
---|
1294 | return null; |
---|
1295 | } |
---|
1296 | |
---|
1297 | // Use an HTTP header value only if $trust_all_proxies is true or when REMOTE_ADDR is in our $cfg['trusted_proxies'] array. |
---|
1298 | // $cfg['trusted_proxies'] is an array of proxy server addresses we expect to see in REMOTE_ADDR. |
---|
1299 | if ($trust_all_proxies || isset($cfg['trusted_proxies']) && is_array($cfg['trusted_proxies']) && in_array($_SERVER['REMOTE_ADDR'], $cfg['trusted_proxies'], true)) { |
---|
1300 | // Then it's probably safe to use an IP address value set in an HTTP header. |
---|
1301 | // Loop through possible IP address headers. |
---|
1302 | foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED') as $key) { |
---|
1303 | // Loop through and if |
---|
1304 | if (array_key_exists($key, $_SERVER)) { |
---|
1305 | foreach (explode(',', $_SERVER[$key]) as $addr) { |
---|
1306 | // Strip non-address data to avoid "PHP Warning: inet_pton(): Unrecognized address for=189.211.197.173 in ./Utilities.inc.php on line 1293" |
---|
1307 | $addr = preg_replace('/[^=]=/', '', $addr); |
---|
1308 | $addr = canonicalIPAddr(trim($addr)); |
---|
1309 | if (false !== filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { |
---|
1310 | return $dolookup && '' != $addr ? gethostbyaddr($addr) : $addr; |
---|
1311 | } |
---|
1312 | } |
---|
1313 | } |
---|
1314 | } |
---|
1315 | } |
---|
1316 | |
---|
1317 | $addr = canonicalIPAddr(trim($_SERVER['REMOTE_ADDR'])); |
---|
1318 | return $dolookup && $addr ? gethostbyaddr($addr) : $addr; |
---|
1319 | } |
---|
1320 | |
---|
1321 | /* |
---|
1322 | * Converts an ipv4 IP address in hexadecimal form into canonical form (i.e., it removes the prefix). |
---|
1323 | * |
---|
1324 | * @access public |
---|
1325 | * @param string $addr IP address. |
---|
1326 | * @return string Canonical IP address. |
---|
1327 | * @author Sander Steffann <http://stackoverflow.com/a/12436099/277303> |
---|
1328 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
1329 | * @version 1.0 |
---|
1330 | * @since 15 Sep 2012 |
---|
1331 | */ |
---|
1332 | function canonicalIPAddr($addr) |
---|
1333 | { |
---|
1334 | // Known prefix |
---|
1335 | $v4mapped_prefix_bin = pack('H*', '00000000000000000000ffff'); |
---|
1336 | |
---|
1337 | // Parse |
---|
1338 | $addr_bin = inet_pton($addr); |
---|
1339 | |
---|
1340 | // Check prefix |
---|
1341 | if (substr($addr_bin, 0, strlen($v4mapped_prefix_bin)) == $v4mapped_prefix_bin) { |
---|
1342 | // Strip prefix |
---|
1343 | $addr_bin = substr($addr_bin, strlen($v4mapped_prefix_bin)); |
---|
1344 | } |
---|
1345 | |
---|
1346 | // Convert back to printable address in canonical form |
---|
1347 | return inet_ntop($addr_bin); |
---|
1348 | } |
---|
1349 | |
---|
1350 | /** |
---|
1351 | * Tests whether a given IP address can be found in an array of IP address networks. |
---|
1352 | * Elements of networks array can be single IP addresses or an IP address range in CIDR notation |
---|
1353 | * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing |
---|
1354 | * |
---|
1355 | * @access public |
---|
1356 | * @param string IP address to search for. |
---|
1357 | * @param array Array of networks to search within. |
---|
1358 | * @return mixed Returns the network that matched on success, false on failure. |
---|
1359 | */ |
---|
1360 | function ipInRange($addr, $networks) |
---|
1361 | { |
---|
1362 | if (!is_array($networks)) { |
---|
1363 | $networks = array($networks); |
---|
1364 | } |
---|
1365 | |
---|
1366 | $addr_binary = sprintf('%032b', ip2long($addr)); |
---|
1367 | foreach ($networks as $network) { |
---|
1368 | if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) { |
---|
1369 | // IP is in CIDR notation. |
---|
1370 | list($cidr_ip, $cidr_bitmask) = explode('/', $network); |
---|
1371 | $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip)); |
---|
1372 | if (mb_substr($addr_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) { |
---|
1373 | // IP address is within the specified IP range. |
---|
1374 | return $network; |
---|
1375 | } |
---|
1376 | } else { |
---|
1377 | if ($addr === $network) { |
---|
1378 | // IP address exactly matches. |
---|
1379 | return $network; |
---|
1380 | } |
---|
1381 | } |
---|
1382 | } |
---|
1383 | |
---|
1384 | return false; |
---|
1385 | } |
---|
1386 | |
---|
1387 | /** |
---|
1388 | * If the given $url is on the same web site, return true. This can be used to |
---|
1389 | * prevent from sending sensitive info in a get query (like the SID) to another |
---|
1390 | * domain. |
---|
1391 | * |
---|
1392 | * @param string $url the URI to test. |
---|
1393 | * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another. |
---|
1394 | */ |
---|
1395 | function isMyDomain($url) |
---|
1396 | { |
---|
1397 | static $urls = array(); |
---|
1398 | |
---|
1399 | if (!isset($urls[$url])) { |
---|
1400 | if (!preg_match('|https?://[\w.]+/|', $url)) { |
---|
1401 | // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg"). |
---|
1402 | $urls[$url] = true; |
---|
1403 | } else { |
---|
1404 | $urls[$url] = preg_match('|https?://[\w.]*' . preg_quote(getenv('HTTP_HOST'), '|') . '|i', $url); |
---|
1405 | } |
---|
1406 | } |
---|
1407 | return $urls[$url]; |
---|
1408 | } |
---|
1409 | |
---|
1410 | /** |
---|
1411 | * Takes a URL and returns it without the query or anchor portion |
---|
1412 | * |
---|
1413 | * @param string $url any kind of URI |
---|
1414 | * @return string the URI with ? or # and everything after removed |
---|
1415 | */ |
---|
1416 | function stripQuery($url) |
---|
1417 | { |
---|
1418 | return preg_replace('/[?#].*$/', '', $url); |
---|
1419 | } |
---|
1420 | |
---|
1421 | /** |
---|
1422 | * Returns a fully qualified URL to the current script, including the query. |
---|
1423 | * |
---|
1424 | * @return string a full url to the current script |
---|
1425 | */ |
---|
1426 | function absoluteMe() |
---|
1427 | { |
---|
1428 | return sprintf('%s://%s%s', (getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'), getenv('REQUEST_URI')); |
---|
1429 | } |
---|
1430 | |
---|
1431 | /** |
---|
1432 | * Compares the current url with the referring url. |
---|
1433 | * |
---|
1434 | * @param bool $exclude_query Remove the query string first before comparing. |
---|
1435 | * @return bool True if the current URL is the same as the referring URL, false otherwise. |
---|
1436 | */ |
---|
1437 | function refererIsMe($exclude_query=false) |
---|
1438 | { |
---|
1439 | $current_url = absoluteMe(); |
---|
1440 | $referrer_url = getenv('HTTP_REFERER'); |
---|
1441 | |
---|
1442 | // If one of the hostnames is an IP address, compare only the path of both. |
---|
1443 | if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', parse_url($current_url, PHP_URL_HOST)) || preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', parse_url($referrer_url, PHP_URL_HOST))) { |
---|
1444 | $current_url = preg_replace('@^https?://[^/]+@', '', $current_url); |
---|
1445 | $referrer_url = preg_replace('@^https?://[^/]+@', '', $referrer_url); |
---|
1446 | } |
---|
1447 | |
---|
1448 | if ($exclude_query) { |
---|
1449 | return (stripQuery($current_url) == stripQuery($referrer_url)); |
---|
1450 | } else { |
---|
1451 | $app =& App::getInstance(); |
---|
1452 | $app->logMsg(sprintf('refererIsMe comparison: %s == %s', $current_url, $referrer_url), LOG_DEBUG, __FILE__, __LINE__); |
---|
1453 | return ($current_url == $referrer_url); |
---|
1454 | } |
---|
1455 | } |
---|
1456 | |
---|
1457 | /* |
---|
1458 | * Returns true if the given URL resolves to a resource with a HTTP 2xx or 3xx header response. |
---|
1459 | * The download will abort if it retrieves >= 10KB of data to avoid downloading large files. |
---|
1460 | * We couldn't use CURLOPT_NOBODY (a HEAD request) because some services don't behave without a GET request (ahem, BBC). |
---|
1461 | * This function may not be very portable, if the server doesn't support CURLOPT_PROGRESSFUNCTION. |
---|
1462 | * |
---|
1463 | * @access public |
---|
1464 | * @param string $url URL to a file. |
---|
1465 | * @return bool True if the resource exists, false otherwise. |
---|
1466 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
1467 | * @version 2.0 |
---|
1468 | * @since 02 May 2015 15:10:09 |
---|
1469 | */ |
---|
1470 | function httpExists($url) |
---|
1471 | { |
---|
1472 | $ch = curl_init($url); |
---|
1473 | curl_setopt($ch, CURLOPT_TIMEOUT, 5); |
---|
1474 | curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); |
---|
1475 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
---|
1476 | curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); |
---|
1477 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Don't pass through data to the browser. |
---|
1478 | curl_setopt($ch, CURLOPT_BUFFERSIZE, 128); // Frequent progress function calls. |
---|
1479 | curl_setopt($ch, CURLOPT_NOPROGRESS, false); // Required to use CURLOPT_PROGRESSFUNCTION. |
---|
1480 | // Function arguments for CURLOPT_PROGRESSFUNCTION changed with php 5.5.0. |
---|
1481 | if (version_compare(PHP_VERSION, '5.5.0', '>=')) { |
---|
1482 | curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($ch, $dltot, $dlcur, $ultot, $ulcur){ |
---|
1483 | // Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error |
---|
1484 | // 10KB should be enough to catch a few 302 redirect headers and get to the actual content. |
---|
1485 | return ($dlcur > 10*1024) ? 1 : 0; |
---|
1486 | }); |
---|
1487 | } else { |
---|
1488 | curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($dltot, $dlcur, $ultot, $ulcur){ |
---|
1489 | // Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error |
---|
1490 | // 10KB should be enough to catch a few 302 redirect headers and get to the actual content. |
---|
1491 | return ($dlcur > 10*1024) ? 1 : 0; |
---|
1492 | }); |
---|
1493 | } |
---|
1494 | curl_exec($ch); |
---|
1495 | $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
---|
1496 | return preg_match('/^[23]\d\d$/', $http_code); |
---|
1497 | } |
---|