1 | <?php |
---|
2 | /** |
---|
3 | * Utilities.inc.php |
---|
4 | * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information |
---|
5 | */ |
---|
6 | |
---|
7 | |
---|
8 | /** |
---|
9 | * Print variable dump. |
---|
10 | * |
---|
11 | * @param mixed $var Variable to dump. |
---|
12 | * @param bool $display Hide the dump in HTML comments? |
---|
13 | * @param bool $var_dump Use var_dump instead of print_r. |
---|
14 | */ |
---|
15 | function dump($var, $display=false, $var_dump=false) |
---|
16 | { |
---|
17 | echo $display ? "\n<br /><pre>\n" : "\n\n\n<!--\n"; |
---|
18 | if ($var_dump) { |
---|
19 | var_dump($var); |
---|
20 | } else { |
---|
21 | print_r($var); |
---|
22 | } |
---|
23 | echo $display ? "\n</pre><br />\n" : "\n-->\n\n\n"; |
---|
24 | } |
---|
25 | |
---|
26 | /** |
---|
27 | * Return dump as variable. |
---|
28 | * |
---|
29 | * @param mixed $var Variable to dump. |
---|
30 | * @return string Dump of var. |
---|
31 | */ |
---|
32 | function getDump($var) |
---|
33 | { |
---|
34 | ob_start(); |
---|
35 | print_r($var); |
---|
36 | $d = ob_get_contents(); |
---|
37 | ob_end_clean(); |
---|
38 | return $d; |
---|
39 | } |
---|
40 | |
---|
41 | /** |
---|
42 | * Return dump as cleaned text. Useful for dumping data into emails. |
---|
43 | * |
---|
44 | * @param mixed $var Variable to dump. |
---|
45 | * @param strong $indent A string to prepend indented lines (tab for example). |
---|
46 | * @return string Dump of var. |
---|
47 | */ |
---|
48 | function fancyDump($var, $indent='') |
---|
49 | { |
---|
50 | $output = ''; |
---|
51 | if (is_array($var)) { |
---|
52 | foreach ($var as $k=>$v) { |
---|
53 | $k = ucfirst(mb_strtolower(str_replace(array('_', ' '), ' ', $k))); |
---|
54 | if (is_array($v)) { |
---|
55 | $output .= sprintf("\n%s%s: %s\n", $indent, $k, fancyDump($v, $indent . $indent)); |
---|
56 | } else { |
---|
57 | $output .= sprintf("%s%s: %s\n", $indent, $k, $v); |
---|
58 | } |
---|
59 | } |
---|
60 | } else { |
---|
61 | $output .= sprintf("%s%s\n", $indent, $var); |
---|
62 | } |
---|
63 | return $output; |
---|
64 | } |
---|
65 | |
---|
66 | /** |
---|
67 | * Returns text with appropriate html translations. |
---|
68 | * |
---|
69 | * @param string $text Text to clean. |
---|
70 | * @param bool $preserve_html If set to true, oTxt will not translage <, >, ", or ' |
---|
71 | * characters into HTML entities. This allows HTML to pass |
---|
72 | * through unmunged. |
---|
73 | * @return string Cleaned text. |
---|
74 | */ |
---|
75 | function oTxt($text, $preserve_html=false) |
---|
76 | { |
---|
77 | $app =& App::getInstance(); |
---|
78 | |
---|
79 | $search = array(); |
---|
80 | $replace = array(); |
---|
81 | |
---|
82 | // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities. |
---|
83 | $search['retain_ampersand'] = '/&/'; |
---|
84 | $replace['retain_ampersand'] = '&'; |
---|
85 | |
---|
86 | if ($preserve_html) { |
---|
87 | // Convert characters that must remain non-entities for displaying HTML. |
---|
88 | $search['retain_left_angle'] = '/</'; |
---|
89 | $replace['retain_left_angle'] = '<'; |
---|
90 | |
---|
91 | $search['retain_right_angle'] = '/>/'; |
---|
92 | $replace['retain_right_angle'] = '>'; |
---|
93 | |
---|
94 | $search['retain_single_quote'] = '/'/'; |
---|
95 | $replace['retain_single_quote'] = "'"; |
---|
96 | |
---|
97 | $search['retain_double_quote'] = '/"/'; |
---|
98 | $replace['retain_double_quote'] = '"'; |
---|
99 | } |
---|
100 | |
---|
101 | // & becomes &. Exclude any occurance where the & is followed by a alphanum or unicode caracter. |
---|
102 | $search['ampersand'] = '/&(?![\w\d#]{1,10};)/'; |
---|
103 | $replace['ampersand'] = '&'; |
---|
104 | |
---|
105 | return preg_replace($search, $replace, htmlentities($text, ENT_QUOTES, $app->getParam('character_set'))); |
---|
106 | } |
---|
107 | |
---|
108 | /** |
---|
109 | * Returns text with stylistic modifications. Warning: this will break some HTML attibutes! |
---|
110 | * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a> |
---|
111 | * |
---|
112 | * @param string $text Text to clean. |
---|
113 | * @return string Cleaned text. |
---|
114 | */ |
---|
115 | function fancyTxt($text) |
---|
116 | { |
---|
117 | $search = array(); |
---|
118 | $replace = array(); |
---|
119 | |
---|
120 | // "double quoted text" becomes “double quoted text” |
---|
121 | $search['double_quotes'] = '/(^|[^\w=])(?:"|"|"|"|“)([^"]+?)(?:"|"|"|"|”)([^\w]|$)/ms'; // " is the same as " and " and " |
---|
122 | $replace['double_quotes'] = '$1“$2”$3'; |
---|
123 | |
---|
124 | // text's apostrophes become text’s apostrophes |
---|
125 | $search['apostrophe'] = '/(\w)(?:\'|'|')(\w)/ms'; |
---|
126 | $replace['apostrophe'] = '$1’$2'; |
---|
127 | |
---|
128 | // 'single quoted text' becomes ‘single quoted text’ |
---|
129 | $search['single_quotes'] = '/(^|[^\w=])(?:\'|'|‘)([^\']+?)(?:\'|'|’)([^\w]|$)/ms'; |
---|
130 | $replace['single_quotes'] = '$1‘$2’$3'; |
---|
131 | |
---|
132 | // plural posessives' apostrophes become posessives’ |
---|
133 | $search['apostrophes'] = '/(s)(?:\'|'|')(\s)/ms'; |
---|
134 | $replace['apostrophes'] = '$1’$2'; |
---|
135 | |
---|
136 | // em--dashes become em—dashes |
---|
137 | $search['em_dash'] = '/(\s*[^!<-])--([^>-]\s*)/'; |
---|
138 | $replace['em_dash'] = '$1—$2'; |
---|
139 | |
---|
140 | return preg_replace($search, $replace, $text); |
---|
141 | } |
---|
142 | |
---|
143 | /** |
---|
144 | * Applies a class to search terms to highlight them ala-google results. |
---|
145 | * |
---|
146 | * @param string $text Input text to search. |
---|
147 | * @param string $search String of word(s) that will be highlighted. |
---|
148 | * @param string $class CSS class to apply. |
---|
149 | * @return string Text with searched words wrapped in <span>. |
---|
150 | */ |
---|
151 | function highlightWords($text, $search, $class='sc-highlightwords') |
---|
152 | { |
---|
153 | $words = preg_split('/[^\w]/', $search, -1, PREG_SPLIT_NO_EMPTY); |
---|
154 | |
---|
155 | $search = array(); |
---|
156 | $replace = array(); |
---|
157 | |
---|
158 | foreach ($words as $w) { |
---|
159 | if ('' != trim($w)) { |
---|
160 | $search[] = '/\b(' . preg_quote($w) . ')\b/i'; |
---|
161 | $replace[] = '<span class="' . $class . '">$1</span>'; |
---|
162 | } |
---|
163 | } |
---|
164 | |
---|
165 | return empty($replace) ? $text : preg_replace($search, $replace, $text); |
---|
166 | } |
---|
167 | |
---|
168 | |
---|
169 | /** |
---|
170 | * Generates a hexadecibal html color based on provided word. |
---|
171 | * |
---|
172 | * @access public |
---|
173 | * @param string $text A string for which to convert to color. |
---|
174 | * @return string A hexadecimal html color. |
---|
175 | */ |
---|
176 | function getTextColor($text, $method=1) |
---|
177 | { |
---|
178 | $hash = md5($text); |
---|
179 | $rgb = array( |
---|
180 | mb_substr($hash, 0, 1), |
---|
181 | mb_substr($hash, 1, 1), |
---|
182 | mb_substr($hash, 2, 1), |
---|
183 | mb_substr($hash, 3, 1), |
---|
184 | mb_substr($hash, 4, 1), |
---|
185 | mb_substr($hash, 5, 1), |
---|
186 | ); |
---|
187 | |
---|
188 | switch ($method) { |
---|
189 | case 1 : |
---|
190 | default : |
---|
191 | // Reduce all hex values slighly to avoid all white. |
---|
192 | array_walk($rgb, create_function('&$v', '$v = dechex(round(hexdec($v) * 0.87));')); |
---|
193 | break; |
---|
194 | case 2 : |
---|
195 | foreach ($rgb as $i => $v) { |
---|
196 | if (hexdec($v) > hexdec('c')) { |
---|
197 | $rgb[$i] = dechex(hexdec('f') - hexdec($v)); |
---|
198 | } |
---|
199 | } |
---|
200 | break; |
---|
201 | } |
---|
202 | |
---|
203 | return join('', $rgb); |
---|
204 | } |
---|
205 | |
---|
206 | /** |
---|
207 | * Encodes a string into unicode values 128-255. |
---|
208 | * Useful for hiding an email address from spambots. |
---|
209 | * |
---|
210 | * @access public |
---|
211 | * @param string $text A line of text to encode. |
---|
212 | * @return string Encoded text. |
---|
213 | */ |
---|
214 | function encodeAscii($text) |
---|
215 | { |
---|
216 | $output = ''; |
---|
217 | $num = mb_strlen($text); |
---|
218 | for ($i=0; $i<$num; $i++) { |
---|
219 | $output .= sprintf('&#%03s', ord($text{$i})); |
---|
220 | } |
---|
221 | return $output; |
---|
222 | } |
---|
223 | |
---|
224 | /** |
---|
225 | * Encodes an email into a "user at domain dot com" format. |
---|
226 | * |
---|
227 | * @access public |
---|
228 | * @param string $email An email to encode. |
---|
229 | * @param string $at Replaces the @. |
---|
230 | * @param string $dot Replaces the .. |
---|
231 | * @return string Encoded email. |
---|
232 | */ |
---|
233 | function encodeEmail($email, $at=' at ', $dot=' dot ') |
---|
234 | { |
---|
235 | $search = array('/@/', '/\./'); |
---|
236 | $replace = array($at, $dot); |
---|
237 | return preg_replace($search, $replace, $email); |
---|
238 | } |
---|
239 | |
---|
240 | /** |
---|
241 | * Turns "a really long string" into "a rea...string" |
---|
242 | * |
---|
243 | * @access public |
---|
244 | * @param string $str Input string |
---|
245 | * @param int $len Maximum string length. |
---|
246 | * @param string $where Where to cut the string. One of: 'start', 'middle', or 'end'. |
---|
247 | * @return string Truncated output string |
---|
248 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
249 | * @since 29 Mar 2006 13:48:49 |
---|
250 | */ |
---|
251 | function truncate($str, $len, $where='middle', $delim='…') |
---|
252 | { |
---|
253 | if ($len <= 3 || mb_strlen($str) <= 3) { |
---|
254 | return ''; |
---|
255 | } |
---|
256 | $part1 = floor(($len - 3) / 2); |
---|
257 | $part2 = ceil(($len - 3) / 2); |
---|
258 | switch ($where) { |
---|
259 | case 'start' : |
---|
260 | return preg_replace(array(sprintf('/^.{4,}(.{%s})$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array($delim . '$1', $delim), $str); |
---|
261 | break; |
---|
262 | default : |
---|
263 | case 'middle' : |
---|
264 | return preg_replace(array(sprintf('/^(.{%s}).{4,}(.{%s})$/sU', $part1, $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim . '$2', $delim), $str); |
---|
265 | break; |
---|
266 | case 'end' : |
---|
267 | return preg_replace(array(sprintf('/^(.{%s}).{4,}$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim, $delim), $str); |
---|
268 | break; |
---|
269 | } |
---|
270 | } |
---|
271 | |
---|
272 | /** |
---|
273 | * Return a human readable filesize. |
---|
274 | * |
---|
275 | * @param int $size Size |
---|
276 | * @param int $unit The maximum unit |
---|
277 | * @param int $format The return string format |
---|
278 | * @author Aidan Lister <aidan@php.net> |
---|
279 | * @version 1.1.0 |
---|
280 | */ |
---|
281 | function humanFileSize($size, $format='%01.2f %s', $max_unit=null) |
---|
282 | { |
---|
283 | // Units |
---|
284 | $units = array('B', 'KB', 'MB', 'GB', 'TB'); |
---|
285 | $ii = count($units) - 1; |
---|
286 | |
---|
287 | // Max unit |
---|
288 | $max_unit = array_search((string) $max_unit, $units); |
---|
289 | if ($max_unit === null || $max_unit === false) { |
---|
290 | $max_unit = $ii; |
---|
291 | } |
---|
292 | |
---|
293 | // Loop |
---|
294 | $i = 0; |
---|
295 | while ($max_unit != $i && $size >= 1024 && $i < $ii) { |
---|
296 | $size /= 1024; |
---|
297 | $i++; |
---|
298 | } |
---|
299 | |
---|
300 | return sprintf($format, $size, $units[$i]); |
---|
301 | } |
---|
302 | |
---|
303 | /* |
---|
304 | * Returns a human readable amount of time for the given amount of seconds. |
---|
305 | * |
---|
306 | * 45 seconds |
---|
307 | * 12 minutes |
---|
308 | * 3.5 hours |
---|
309 | * 2 days |
---|
310 | * 1 week |
---|
311 | * 4 months |
---|
312 | * |
---|
313 | * Months are calculated using the real number of days in a year: 365.2422 / 12. |
---|
314 | * |
---|
315 | * @access public |
---|
316 | * @param int $seconds Seconds of time. |
---|
317 | * @param string $max_unit Key value from the $units array. |
---|
318 | * @param string $format Sprintf formatting string. |
---|
319 | * @return string Value of units elapsed. |
---|
320 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
321 | * @version 1.0 |
---|
322 | * @since 23 Jun 2006 12:15:19 |
---|
323 | */ |
---|
324 | function humanTime($seconds, $max_unit=null, $format='%01.1f') |
---|
325 | { |
---|
326 | // Units: array of seconds in the unit, singular and plural unit names. |
---|
327 | $units = array( |
---|
328 | 'second' => array(1, _("second"), _("seconds")), |
---|
329 | 'minute' => array(60, _("minute"), _("minutes")), |
---|
330 | 'hour' => array(3600, _("hour"), _("hours")), |
---|
331 | 'day' => array(86400, _("day"), _("days")), |
---|
332 | 'week' => array(604800, _("week"), _("weeks")), |
---|
333 | 'month' => array(2629743.84, _("month"), _("months")), |
---|
334 | 'year' => array(31556926.08, _("year"), _("years")), |
---|
335 | 'decade' => array(315569260.8, _("decade"), _("decades")), |
---|
336 | ); |
---|
337 | |
---|
338 | // Max unit to calculate. |
---|
339 | $max_unit = isset($units[$max_unit]) ? $max_unit : 'decade'; |
---|
340 | |
---|
341 | $final_time = $seconds; |
---|
342 | $last_unit = 'second'; |
---|
343 | foreach ($units as $k => $v) { |
---|
344 | if ($max_unit != $k && $seconds >= $v[0]) { |
---|
345 | $final_time = $seconds / $v[0]; |
---|
346 | $last_unit = $k; |
---|
347 | } |
---|
348 | } |
---|
349 | $final_time = sprintf($format, $final_time); |
---|
350 | return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$last_unit][1] : $units[$last_unit][2])); |
---|
351 | } |
---|
352 | |
---|
353 | /** |
---|
354 | * Tests the existance of a file anywhere in the include path. |
---|
355 | * |
---|
356 | * @param string $file File in include path. |
---|
357 | * @return mixed False if file not found, the path of the file if it is found. |
---|
358 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
359 | * @since 03 Dec 2005 14:23:26 |
---|
360 | */ |
---|
361 | function fileExistsIncludePath($file) |
---|
362 | { |
---|
363 | $app =& App::getInstance(); |
---|
364 | |
---|
365 | foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) { |
---|
366 | $fullpath = $path . DIRECTORY_SEPARATOR . $file; |
---|
367 | if (file_exists($fullpath)) { |
---|
368 | $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__); |
---|
369 | return $fullpath; |
---|
370 | } else { |
---|
371 | $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__); |
---|
372 | return false; |
---|
373 | } |
---|
374 | } |
---|
375 | } |
---|
376 | |
---|
377 | /** |
---|
378 | * Returns stats of a file from the include path. |
---|
379 | * |
---|
380 | * @param string $file File in include path. |
---|
381 | * @param mixed $stat Which statistic to return (or null to return all). |
---|
382 | * @return mixed Value of requested key from fstat(), or false on error. |
---|
383 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
384 | * @since 03 Dec 2005 14:23:26 |
---|
385 | */ |
---|
386 | function statIncludePath($file, $stat=null) |
---|
387 | { |
---|
388 | // Open file pointer read-only using include path. |
---|
389 | if ($fp = fopen($file, 'r', true)) { |
---|
390 | // File opened successfully, get stats. |
---|
391 | $stats = fstat($fp); |
---|
392 | fclose($fp); |
---|
393 | // Return specified stats. |
---|
394 | return is_null($stat) ? $stats : $stats[$stat]; |
---|
395 | } else { |
---|
396 | return false; |
---|
397 | } |
---|
398 | } |
---|
399 | |
---|
400 | /** |
---|
401 | * If $var is net set or null, set it to $default. Otherwise leave it alone. |
---|
402 | * Returns the final value of $var. Use to find a default value of one is not avilable. |
---|
403 | * |
---|
404 | * @param mixed $var The variable that is being set. |
---|
405 | * @param mixed $default What to set it to if $val is not currently set. |
---|
406 | * @return mixed The resulting value of $var. |
---|
407 | */ |
---|
408 | function setDefault(&$var, $default='') |
---|
409 | { |
---|
410 | if (!isset($var)) { |
---|
411 | $var = $default; |
---|
412 | } |
---|
413 | return $var; |
---|
414 | } |
---|
415 | |
---|
416 | /** |
---|
417 | * Like preg_quote() except for arrays, it takes an array of strings and puts |
---|
418 | * a backslash in front of every character that is part of the regular |
---|
419 | * expression syntax. |
---|
420 | * |
---|
421 | * @param array $array input array |
---|
422 | * @param array $delim optional character that will also be excaped. |
---|
423 | * @return array an array with the same values as $array1 but shuffled |
---|
424 | */ |
---|
425 | function pregQuoteArray($array, $delim='/') |
---|
426 | { |
---|
427 | if (!empty($array)) { |
---|
428 | if (is_array($array)) { |
---|
429 | foreach ($array as $key=>$val) { |
---|
430 | $quoted_array[$key] = preg_quote($val, $delim); |
---|
431 | } |
---|
432 | return $quoted_array; |
---|
433 | } else { |
---|
434 | return preg_quote($array, $delim); |
---|
435 | } |
---|
436 | } |
---|
437 | } |
---|
438 | |
---|
439 | /** |
---|
440 | * Converts a PHP Array into encoded URL arguments and return them as an array. |
---|
441 | * |
---|
442 | * @param mixed $data An array to transverse recursivly, or a string |
---|
443 | * to use directly to create url arguments. |
---|
444 | * @param string $prefix The name of the first dimension of the array. |
---|
445 | * If not specified, the first keys of the array will be used. |
---|
446 | * @return array URL with array elements as URL key=value arguments. |
---|
447 | */ |
---|
448 | function urlEncodeArray($data, $prefix='', $_return=true) |
---|
449 | { |
---|
450 | |
---|
451 | // Data is stored in static variable. |
---|
452 | static $args; |
---|
453 | |
---|
454 | if (is_array($data)) { |
---|
455 | foreach ($data as $key => $val) { |
---|
456 | // If the prefix is empty, use the $key as the name of the first dimention of the "array". |
---|
457 | // ...otherwise, append the key as a new dimention of the "array". |
---|
458 | $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']'; |
---|
459 | // Enter recursion. |
---|
460 | urlEncodeArray($val, $new_prefix, false); |
---|
461 | } |
---|
462 | } else { |
---|
463 | // We've come to the last dimention of the array, save the "array" and its value. |
---|
464 | $args[$prefix] = urlencode($data); |
---|
465 | } |
---|
466 | |
---|
467 | if ($_return) { |
---|
468 | // This is not a recursive execution. All recursion is complete. |
---|
469 | // Reset static var and return the result. |
---|
470 | $ret = $args; |
---|
471 | $args = array(); |
---|
472 | return is_array($ret) ? $ret : array(); |
---|
473 | } |
---|
474 | } |
---|
475 | |
---|
476 | /** |
---|
477 | * Converts a PHP Array into encoded URL arguments and return them in a string. |
---|
478 | * |
---|
479 | * @param mixed $data An array to transverse recursivly, or a string |
---|
480 | * to use directly to create url arguments. |
---|
481 | * @param string $prefix The name of the first dimention of the array. |
---|
482 | * If not specified, the first keys of the array will be used. |
---|
483 | * @return string url A string ready to append to a url. |
---|
484 | */ |
---|
485 | function urlEncodeArrayToString($data, $prefix='') |
---|
486 | { |
---|
487 | |
---|
488 | $array_args = urlEncodeArray($data, $prefix); |
---|
489 | $url_args = ''; |
---|
490 | $delim = ''; |
---|
491 | foreach ($array_args as $key=>$val) { |
---|
492 | $url_args .= $delim . $key . '=' . $val; |
---|
493 | $delim = ini_get('arg_separator.output'); |
---|
494 | } |
---|
495 | return $url_args; |
---|
496 | } |
---|
497 | |
---|
498 | /** |
---|
499 | * Fills an arrray with the result from a multiple ereg search. |
---|
500 | * Curtesy of Bruno - rbronosky@mac.com - 10-May-2001 |
---|
501 | * Blame him for the funky do...while loop. |
---|
502 | * |
---|
503 | * @param mixed $pattern regular expression needle |
---|
504 | * @param mixed $string haystack |
---|
505 | * @return array populated with each found result |
---|
506 | */ |
---|
507 | function eregAll($pattern, $string) |
---|
508 | { |
---|
509 | do { |
---|
510 | if (!mb_ereg($pattern, $string, $temp)) { |
---|
511 | continue; |
---|
512 | } |
---|
513 | $string = str_replace($temp[0], '', $string); |
---|
514 | $results[] = $temp; |
---|
515 | } while (mb_ereg($pattern, $string, $temp)); |
---|
516 | return $results; |
---|
517 | } |
---|
518 | |
---|
519 | /** |
---|
520 | * Prints the word "checked" if a variable is set, and optionally matches |
---|
521 | * the desired value, otherwise prints nothing, |
---|
522 | * used for printing the word "checked" in a checkbox form input. |
---|
523 | * |
---|
524 | * @param mixed $var the variable to compare |
---|
525 | * @param mixed $value optional, what to compare with if a specific value is required. |
---|
526 | */ |
---|
527 | function frmChecked($var, $value=null) |
---|
528 | { |
---|
529 | if (func_num_args() == 1 && $var) { |
---|
530 | // 'Checked' if var is true. |
---|
531 | echo ' checked="checked" '; |
---|
532 | } else if (func_num_args() == 2 && $var == $value) { |
---|
533 | // 'Checked' if var and value match. |
---|
534 | echo ' checked="checked" '; |
---|
535 | } else if (func_num_args() == 2 && is_array($var)) { |
---|
536 | // 'Checked' if the value is in the key or the value of an array. |
---|
537 | if (isset($var[$value])) { |
---|
538 | echo ' checked="checked" '; |
---|
539 | } else if (in_array($value, $var)) { |
---|
540 | echo ' checked="checked" '; |
---|
541 | } |
---|
542 | } |
---|
543 | } |
---|
544 | |
---|
545 | /** |
---|
546 | * prints the word "selected" if a variable is set, and optionally matches |
---|
547 | * the desired value, otherwise prints nothing, |
---|
548 | * otherwise prints nothing, used for printing the word "checked" in a |
---|
549 | * select form input |
---|
550 | * |
---|
551 | * @param mixed $var the variable to compare |
---|
552 | * @param mixed $value optional, what to compare with if a specific value is required. |
---|
553 | */ |
---|
554 | function frmSelected($var, $value=null) |
---|
555 | { |
---|
556 | if (func_num_args() == 1 && $var) { |
---|
557 | // 'selected' if var is true. |
---|
558 | echo ' selected="selected" '; |
---|
559 | } else if (func_num_args() == 2 && $var == $value) { |
---|
560 | // 'selected' if var and value match. |
---|
561 | echo ' selected="selected" '; |
---|
562 | } else if (func_num_args() == 2 && is_array($var)) { |
---|
563 | // 'selected' if the value is in the key or the value of an array. |
---|
564 | if (isset($var[$value])) { |
---|
565 | echo ' selected="selected" '; |
---|
566 | } else if (in_array($value, $var)) { |
---|
567 | echo ' selected="selected" '; |
---|
568 | } |
---|
569 | } |
---|
570 | } |
---|
571 | |
---|
572 | /** |
---|
573 | * Adds slashes to values of an array and converts the array to a comma |
---|
574 | * delimited list. If value provided is a string return the string |
---|
575 | * escaped. This is useful for putting values coming in from posted |
---|
576 | * checkboxes into a SET column of a database. |
---|
577 | * |
---|
578 | * |
---|
579 | * @param array $in Array to convert. |
---|
580 | * @return string Comma list of array values. |
---|
581 | */ |
---|
582 | function escapedList($in, $separator="', '") |
---|
583 | { |
---|
584 | $db =& DB::getInstance(); |
---|
585 | |
---|
586 | if (is_array($in) && !empty($in)) { |
---|
587 | return join($separator, array_map(array($db, 'escapeString'), $in)); |
---|
588 | } else { |
---|
589 | return $db->escapeString($in); |
---|
590 | } |
---|
591 | } |
---|
592 | |
---|
593 | /** |
---|
594 | * Converts a human string date into a SQL-safe date. Dates nearing |
---|
595 | * infinity use the date 2038-01-01 so conversion to unix time format |
---|
596 | * remain within valid range. |
---|
597 | * |
---|
598 | * @param array $date String date to convert. |
---|
599 | * @param array $format Date format to pass to date(). |
---|
600 | * Default produces MySQL datetime: 0000-00-00 00:00:00. |
---|
601 | * @return string SQL-safe date. |
---|
602 | */ |
---|
603 | function strToSQLDate($date, $format='Y-m-d H:i:s') |
---|
604 | { |
---|
605 | // Translate the human string date into SQL-safe date format. |
---|
606 | if (empty($date) || mb_strpos($date, '0000-00-00') !== false || strtotime($date) === -1 || strtotime($date) === false) { |
---|
607 | // Return a string of zero time, formatted the same as $format. |
---|
608 | return strtr($format, array( |
---|
609 | 'Y' => '0000', |
---|
610 | 'm' => '00', |
---|
611 | 'd' => '00', |
---|
612 | 'H' => '00', |
---|
613 | 'i' => '00', |
---|
614 | 's' => '00', |
---|
615 | )); |
---|
616 | } else { |
---|
617 | return date($format, strtotime($date)); |
---|
618 | } |
---|
619 | } |
---|
620 | |
---|
621 | /** |
---|
622 | * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an |
---|
623 | * array, stripslashes is run on each value, recursivly, and the stripped |
---|
624 | * array is returned. |
---|
625 | * |
---|
626 | * @param mixed $var The string or array to un-quote, if necessary. |
---|
627 | * @return mixed $var, minus any magic quotes. |
---|
628 | */ |
---|
629 | function dispelMagicQuotes($var) |
---|
630 | { |
---|
631 | static $magic_quotes_gpc; |
---|
632 | |
---|
633 | if (!isset($magic_quotes_gpc)) { |
---|
634 | $magic_quotes_gpc = get_magic_quotes_gpc(); |
---|
635 | } |
---|
636 | |
---|
637 | if ($magic_quotes_gpc) { |
---|
638 | if (!is_array($var)) { |
---|
639 | $var = stripslashes($var); |
---|
640 | } else { |
---|
641 | foreach ($var as $key=>$val) { |
---|
642 | if (is_array($val)) { |
---|
643 | $var[$key] = dispelMagicQuotes($val); |
---|
644 | } else { |
---|
645 | $var[$key] = stripslashes($val); |
---|
646 | } |
---|
647 | } |
---|
648 | } |
---|
649 | } |
---|
650 | return $var; |
---|
651 | } |
---|
652 | |
---|
653 | /** |
---|
654 | * Get a form variable from GET or POST data, stripped of magic |
---|
655 | * quotes if necessary. |
---|
656 | * |
---|
657 | * @param string $var (optional) The name of the form variable to look for. |
---|
658 | * @param string $default (optional) The value to return if the |
---|
659 | * variable is not there. |
---|
660 | * @return mixed A cleaned GET or POST if no $var specified. |
---|
661 | * @return string A cleaned form $var if found, or $default. |
---|
662 | */ |
---|
663 | function getFormData($var=null, $default=null) |
---|
664 | { |
---|
665 | if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) { |
---|
666 | return dispelMagicQuotes($_POST); |
---|
667 | } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) { |
---|
668 | return dispelMagicQuotes($_GET); |
---|
669 | } |
---|
670 | if (isset($_POST[$var])) { |
---|
671 | return dispelMagicQuotes($_POST[$var]); |
---|
672 | } else if (isset($_GET[$var])) { |
---|
673 | return dispelMagicQuotes($_GET[$var]); |
---|
674 | } else { |
---|
675 | return $default; |
---|
676 | } |
---|
677 | } |
---|
678 | function getPost($var=null, $default=null) |
---|
679 | { |
---|
680 | if (is_null($var)) { |
---|
681 | return dispelMagicQuotes($_POST); |
---|
682 | } |
---|
683 | if (isset($_POST[$var])) { |
---|
684 | return dispelMagicQuotes($_POST[$var]); |
---|
685 | } else { |
---|
686 | return $default; |
---|
687 | } |
---|
688 | } |
---|
689 | function getGet($var=null, $default=null) |
---|
690 | { |
---|
691 | if (is_null($var)) { |
---|
692 | return dispelMagicQuotes($_GET); |
---|
693 | } |
---|
694 | if (isset($_GET[$var])) { |
---|
695 | return dispelMagicQuotes($_GET[$var]); |
---|
696 | } else { |
---|
697 | return $default; |
---|
698 | } |
---|
699 | } |
---|
700 | |
---|
701 | /** |
---|
702 | * Signs a value using md5 and a simple text key. In order for this |
---|
703 | * function to be useful (i.e. secure) the key must be kept secret, which |
---|
704 | * means keeping it as safe as database credentials. Putting it into an |
---|
705 | * environment variable set in httpd.conf is a good place. |
---|
706 | * |
---|
707 | * @access public |
---|
708 | * @param string $val The string to sign. |
---|
709 | * @param string $salt (Optional) A text key to use for computing the signature. |
---|
710 | * @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. |
---|
711 | * @return string The original value with a signature appended. |
---|
712 | */ |
---|
713 | function addSignature($val, $salt=null, $length=18) |
---|
714 | { |
---|
715 | $app =& App::getInstance(); |
---|
716 | |
---|
717 | if ('' == trim($val)) { |
---|
718 | $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__); |
---|
719 | return ''; |
---|
720 | } |
---|
721 | |
---|
722 | if (!isset($salt)) { |
---|
723 | $salt = $app->getParam('signing_key'); |
---|
724 | } |
---|
725 | |
---|
726 | return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length)); |
---|
727 | } |
---|
728 | |
---|
729 | /** |
---|
730 | * Strips off the signature appended by addSignature(). |
---|
731 | * |
---|
732 | * @access public |
---|
733 | * @param string $signed_val The string to sign. |
---|
734 | * @return string The original value with a signature removed. |
---|
735 | */ |
---|
736 | function removeSignature($signed_val) |
---|
737 | { |
---|
738 | if (empty($signed_val) || mb_strpos($signed_val, '-') === false) { |
---|
739 | return ''; |
---|
740 | } |
---|
741 | return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-')); |
---|
742 | } |
---|
743 | |
---|
744 | |
---|
745 | /** |
---|
746 | * Verifies a signature appened to a value by addSignature(). |
---|
747 | * |
---|
748 | * @access public |
---|
749 | * @param string $signed_val A value with appended signature. |
---|
750 | * @param string $salt (Optional) A text key to use for computing the signature. |
---|
751 | * @return bool True if the signature matches the var. |
---|
752 | */ |
---|
753 | function verifySignature($signed_val, $salt=null, $length=18) |
---|
754 | { |
---|
755 | // All comparisons are done using lower-case strings. |
---|
756 | $signed_val = mb_strtolower($signed_val); |
---|
757 | // Strip the value from the signed value. |
---|
758 | $val = removeSignature($signed_val); |
---|
759 | // If the signed value matches the original signed value we consider the value safe. |
---|
760 | if ($signed_val == addSignature($val, $salt, $length)) { |
---|
761 | // Signature verified. |
---|
762 | return true; |
---|
763 | } else { |
---|
764 | return false; |
---|
765 | } |
---|
766 | } |
---|
767 | |
---|
768 | /** |
---|
769 | * Sends empty output to the browser and flushes the php buffer so the client |
---|
770 | * will see data before the page is finished processing. |
---|
771 | */ |
---|
772 | function flushBuffer() |
---|
773 | { |
---|
774 | echo str_repeat(' ', 205); |
---|
775 | flush(); |
---|
776 | } |
---|
777 | |
---|
778 | /** |
---|
779 | * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members. |
---|
780 | * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin". |
---|
781 | * |
---|
782 | * @access public |
---|
783 | * @param string $email Email address to add. |
---|
784 | * @param string $list Name of list to add to. |
---|
785 | * @param bool $send_welcome_message True to send welcome message to subscriber. |
---|
786 | * @return bool True on success, false on failure. |
---|
787 | */ |
---|
788 | function mailmanAddMember($email, $list, $send_welcome_message=false) |
---|
789 | { |
---|
790 | $app =& App::getInstance(); |
---|
791 | |
---|
792 | $add_members = '/usr/lib/mailman/bin/add_members'; |
---|
793 | /// FIXME: checking of executable is disabled. |
---|
794 | if (true || is_executable($add_members) && is_readable($add_members)) { |
---|
795 | $welcome_msg = $send_welcome_message ? 'y' : 'n'; |
---|
796 | 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); |
---|
797 | if (0 == $return_code) { |
---|
798 | $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__); |
---|
799 | return true; |
---|
800 | } else { |
---|
801 | $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__); |
---|
802 | return false; |
---|
803 | } |
---|
804 | } else { |
---|
805 | $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__); |
---|
806 | return false; |
---|
807 | } |
---|
808 | } |
---|
809 | |
---|
810 | /** |
---|
811 | * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members. |
---|
812 | * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin". |
---|
813 | * |
---|
814 | * @access public |
---|
815 | * @param string $email Email address to add. |
---|
816 | * @param string $list Name of list to add to. |
---|
817 | * @param bool $send_user_ack True to send goodbye message to subscriber. |
---|
818 | * @return bool True on success, false on failure. |
---|
819 | */ |
---|
820 | function mailmanRemoveMember($email, $list, $send_user_ack=false) |
---|
821 | { |
---|
822 | $app =& App::getInstance(); |
---|
823 | |
---|
824 | $remove_members = '/usr/lib/mailman/bin/remove_members'; |
---|
825 | /// FIXME: checking of executable is disabled. |
---|
826 | if (true || is_executable($remove_members) && is_readable($remove_members)) { |
---|
827 | $userack = $send_user_ack ? '' : '--nouserack'; |
---|
828 | exec(sprintf("/usr/bin/sudo %s %s --noadminack '%s' '%s'", escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code); |
---|
829 | if (0 == $return_code) { |
---|
830 | $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__); |
---|
831 | return true; |
---|
832 | } else { |
---|
833 | $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__); |
---|
834 | return false; |
---|
835 | } |
---|
836 | } else { |
---|
837 | $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__); |
---|
838 | return false; |
---|
839 | } |
---|
840 | } |
---|
841 | |
---|
842 | /** |
---|
843 | * Returns the remote IP address, taking into consideration proxy servers. |
---|
844 | * |
---|
845 | * @param bool $dolookup If true we resolve to IP to a host name, |
---|
846 | * if false we don't. |
---|
847 | * @return string IP address if $dolookup is false or no arg |
---|
848 | * Hostname if $dolookup is true |
---|
849 | */ |
---|
850 | function getRemoteAddr($dolookup=false) |
---|
851 | { |
---|
852 | $ip = getenv('HTTP_CLIENT_IP'); |
---|
853 | if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) { |
---|
854 | $ip = getenv('HTTP_X_FORWARDED_FOR'); |
---|
855 | if (mb_strpos($ip, ',') !== false) { |
---|
856 | // If HTTP_X_FORWARDED_FOR returns a comma-delimited list of IPs then return the first one (assuming the first is the original). |
---|
857 | $ips = explode(',', $ip, 2); |
---|
858 | $ip = $ips[0]; |
---|
859 | } |
---|
860 | if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) { |
---|
861 | $ip = getenv('REMOTE_ADDR'); |
---|
862 | } |
---|
863 | } |
---|
864 | return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip; |
---|
865 | } |
---|
866 | |
---|
867 | /** |
---|
868 | * Tests whether a given IP address can be found in an array of IP address networks. |
---|
869 | * Elements of networks array can be single IP addresses or an IP address range in CIDR notation |
---|
870 | * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing |
---|
871 | * |
---|
872 | * @access public |
---|
873 | * @param string IP address to search for. |
---|
874 | * @param array Array of networks to search within. |
---|
875 | * @return mixed Returns the network that matched on success, false on failure. |
---|
876 | */ |
---|
877 | function ipInRange($ip, $networks) |
---|
878 | { |
---|
879 | if (!is_array($networks)) { |
---|
880 | $networks = array($networks); |
---|
881 | } |
---|
882 | |
---|
883 | $ip_binary = sprintf('%032b', ip2long($ip)); |
---|
884 | foreach ($networks as $network) { |
---|
885 | if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) { |
---|
886 | // IP is in CIDR notation. |
---|
887 | list($cidr_ip, $cidr_bitmask) = explode('/', $network); |
---|
888 | $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip)); |
---|
889 | if (mb_substr($ip_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) { |
---|
890 | // IP address is within the specified IP range. |
---|
891 | return $network; |
---|
892 | } |
---|
893 | } else { |
---|
894 | if ($ip === $network) { |
---|
895 | // IP address exactly matches. |
---|
896 | return $network; |
---|
897 | } |
---|
898 | } |
---|
899 | } |
---|
900 | |
---|
901 | return false; |
---|
902 | } |
---|
903 | |
---|
904 | /** |
---|
905 | * If the given $url is on the same web site, return true. This can be used to |
---|
906 | * prevent from sending sensitive info in a get query (like the SID) to another |
---|
907 | * domain. |
---|
908 | * |
---|
909 | * @param string $url the URI to test. |
---|
910 | * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another. |
---|
911 | */ |
---|
912 | function isMyDomain($url) |
---|
913 | { |
---|
914 | static $urls = array(); |
---|
915 | |
---|
916 | if (!isset($urls[$url])) { |
---|
917 | if (!preg_match('|https?://[\w.]+/|', $url)) { |
---|
918 | // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg"). |
---|
919 | $urls[$url] = true; |
---|
920 | } else { |
---|
921 | $urls[$url] = preg_match('|https?://[\w.]*' . preg_quote(getenv('HTTP_HOST'), '|') . '|i', $url); |
---|
922 | } |
---|
923 | } |
---|
924 | return $urls[$url]; |
---|
925 | } |
---|
926 | |
---|
927 | /** |
---|
928 | * Takes a URL and returns it without the query or anchor portion |
---|
929 | * |
---|
930 | * @param string $url any kind of URI |
---|
931 | * @return string the URI with ? or # and everything after removed |
---|
932 | */ |
---|
933 | function stripQuery($url) |
---|
934 | { |
---|
935 | return preg_replace('![?#].*!', '', $url); |
---|
936 | } |
---|
937 | |
---|
938 | /** |
---|
939 | * Returns a fully qualified URL to the current script, including the query. |
---|
940 | * |
---|
941 | * @return string a full url to the current script |
---|
942 | */ |
---|
943 | function absoluteMe() |
---|
944 | { |
---|
945 | $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://'; |
---|
946 | return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI'); |
---|
947 | } |
---|
948 | |
---|
949 | /** |
---|
950 | * Compares the current url with the referring url. |
---|
951 | * |
---|
952 | * @param bool $exclude_query Remove the query string first before comparing. |
---|
953 | * @return bool True if the current URL is the same as the refering URL, false otherwise. |
---|
954 | */ |
---|
955 | function refererIsMe($exclude_query=false) |
---|
956 | { |
---|
957 | if ($exclude_query) { |
---|
958 | return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER'))); |
---|
959 | } else { |
---|
960 | return (absoluteMe() == getenv('HTTP_REFERER')); |
---|
961 | } |
---|
962 | } |
---|
963 | |
---|
964 | /** |
---|
965 | * Stub functions used when installation does not have |
---|
966 | * GNU gettext extension installed |
---|
967 | */ |
---|
968 | if (!extension_loaded('gettext')) { |
---|
969 | /** |
---|
970 | * Translates text |
---|
971 | * |
---|
972 | * @access public |
---|
973 | * @param string $text the text to be translated |
---|
974 | * @return string translated text |
---|
975 | */ |
---|
976 | function gettext($text) { |
---|
977 | return $text; |
---|
978 | } |
---|
979 | |
---|
980 | /** |
---|
981 | * Translates text |
---|
982 | * |
---|
983 | * @access public |
---|
984 | * @param string $text the text to be translated |
---|
985 | * @return string translated text |
---|
986 | */ |
---|
987 | function _($text) { |
---|
988 | return $text; |
---|
989 | } |
---|
990 | |
---|
991 | /** |
---|
992 | * Translates text by domain |
---|
993 | * |
---|
994 | * @access public |
---|
995 | * @param string $domain the language to translate the text into |
---|
996 | * @param string $text the text to be translated |
---|
997 | * @return string translated text |
---|
998 | */ |
---|
999 | function dgettext($domain, $text) { |
---|
1000 | return $text; |
---|
1001 | } |
---|
1002 | |
---|
1003 | /** |
---|
1004 | * Translates text by domain and category |
---|
1005 | * |
---|
1006 | * @access public |
---|
1007 | * @param string $domain the language to translate the text into |
---|
1008 | * @param string $text the text to be translated |
---|
1009 | * @param string $category the language dialect to use |
---|
1010 | * @return string translated text |
---|
1011 | */ |
---|
1012 | function dcgettext($domain, $text, $category) { |
---|
1013 | return $text; |
---|
1014 | } |
---|
1015 | |
---|
1016 | /** |
---|
1017 | * Binds the text domain |
---|
1018 | * |
---|
1019 | * @access public |
---|
1020 | * @param string $domain the language to translate the text into |
---|
1021 | * @param string |
---|
1022 | * @return string translated text |
---|
1023 | */ |
---|
1024 | function bindtextdomain($domain, $directory) { |
---|
1025 | return $domain; |
---|
1026 | } |
---|
1027 | |
---|
1028 | /** |
---|
1029 | * Sets the text domain |
---|
1030 | * |
---|
1031 | * @access public |
---|
1032 | * @param string $domain the language to translate the text into |
---|
1033 | * @return string translated text |
---|
1034 | */ |
---|
1035 | function textdomain($domain) { |
---|
1036 | return $domain; |
---|
1037 | } |
---|
1038 | } |
---|
1039 | |
---|
1040 | |
---|
1041 | |
---|
1042 | ?> |
---|