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

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

First use of codebase javascript (codebase/js and codebase/lib/JS.inc.php).

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