source: trunk/lib/Utilities.inc.php @ 394

Last change on this file since 394 was 394, checked in by anonymous, 12 years ago

sc-msg CSS update, minor adjustments.

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