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