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

Last change on this file since 465 was 465, checked in by anonymous, 10 years ago

Removed 'Session not authenticated' logging

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