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

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

Added nonexistant mb_str_pad function

File size: 38.3 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* A substitution for the missing mb_str_pad function.
372*
373* @access   public
374* @param    string  $input      The string that receives padding.
375* @param    string  $pad_length Total length of resultant string.
376* @param    string  $pad_string The string to use for padding
377* @param    string  $pad_type   Flags STR_PAD_RIGHT or STR_PAD_LEFT or STR_PAD_BOTH
378* @return   string          String with translated characters.
379* @author   Quinn Comendant <quinn@strangecode.com>
380* @version  1.0
381* @since    20 Jan 2013 12:33:26
382*/
383if (!function_exists('mb_str_pad')) {
384    function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
385        $diff = strlen($input) - mb_strlen($input);
386        return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
387    }
388}
389
390/**
391 * Return a human readable disk space measurement. Input value measured in bytes.
392 *
393 * @param       int    $size        Size in bytes.
394 * @param       int    $unit        The maximum unit
395 * @param       int    $format      The return string format
396 * @author      Aidan Lister <aidan@php.net>
397 * @author      Quinn Comendant <quinn@strangecode.com>
398 * @version     1.2.0
399 */
400function humanFileSize($size, $format='%01.2f %s', $max_unit=null, $multiplier=1024)
401{
402    // Units
403    $units = array('B', 'KB', 'MB', 'GB', 'TB');
404    $ii = count($units) - 1;
405
406    // Max unit
407    $max_unit = array_search((string) $max_unit, $units);
408    if ($max_unit === null || $max_unit === false) {
409        $max_unit = $ii;
410    }
411
412    // Loop
413    $i = 0;
414    while ($max_unit != $i && $size >= $multiplier && $i < $ii) {
415        $size /= $multiplier;
416        $i++;
417    }
418
419    return sprintf($format, $size, $units[$i]);
420}
421
422/*
423* Returns a human readable amount of time for the given amount of seconds.
424*
425* 45 seconds
426* 12 minutes
427* 3.5 hours
428* 2 days
429* 1 week
430* 4 months
431*
432* Months are calculated using the real number of days in a year: 365.2422 / 12.
433*
434* @access   public
435* @param    int $seconds Seconds of time.
436* @param    string $max_unit Key value from the $units array.
437* @param    string $format Sprintf formatting string.
438* @return   string Value of units elapsed.
439* @author   Quinn Comendant <quinn@strangecode.com>
440* @version  1.0
441* @since    23 Jun 2006 12:15:19
442*/
443function humanTime($seconds, $max_unit=null, $format='%01.1f')
444{
445    // Units: array of seconds in the unit, singular and plural unit names.
446    $units = array(
447        'second' => array(1, _("second"), _("seconds")),
448        'minute' => array(60, _("minute"), _("minutes")),
449        'hour' => array(3600, _("hour"), _("hours")),
450        'day' => array(86400, _("day"), _("days")),
451        'week' => array(604800, _("week"), _("weeks")),
452        'month' => array(2629743.84, _("month"), _("months")),
453        'year' => array(31556926.08, _("year"), _("years")),
454        'decade' => array(315569260.8, _("decade"), _("decades")),
455        'century' => array(3155692608, _("century"), _("centuries")),
456    );
457
458    // Max unit to calculate.
459    $max_unit = isset($units[$max_unit]) ? $max_unit : 'year';
460
461    $final_time = $seconds;
462    $final_unit = 'second';
463    foreach ($units as $k => $v) {
464        if ($seconds >= $v[0]) {
465            $final_time = $seconds / $v[0];
466            $final_unit = $k;
467        }
468        if ($max_unit == $final_unit) {
469            break;
470        }
471    }
472    $final_time = sprintf($format, $final_time);
473    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2]));
474}
475
476/**
477 * Tests the existence of a file anywhere in the include path.
478 *
479 * @param   string  $file   File in include path.
480 * @return  mixed           False if file not found, the path of the file if it is found.
481 * @author  Quinn Comendant <quinn@strangecode.com>
482 * @since   03 Dec 2005 14:23:26
483 */
484function fileExistsIncludePath($file)
485{
486    $app =& App::getInstance();
487
488    foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) {
489        $fullpath = $path . DIRECTORY_SEPARATOR . $file;
490        if (file_exists($fullpath)) {
491            $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__);
492            return $fullpath;
493        } else {
494            $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__);
495            return false;
496        }
497    }
498}
499
500/**
501 * Returns stats of a file from the include path.
502 *
503 * @param   string  $file   File in include path.
504 * @param   mixed   $stat   Which statistic to return (or null to return all).
505 * @return  mixed           Value of requested key from fstat(), or false on error.
506 * @author  Quinn Comendant <quinn@strangecode.com>
507 * @since   03 Dec 2005 14:23:26
508 */
509function statIncludePath($file, $stat=null)
510{
511    // Open file pointer read-only using include path.
512    if ($fp = fopen($file, 'r', true)) {
513        // File opened successfully, get stats.
514        $stats = fstat($fp);
515        fclose($fp);
516        // Return specified stats.
517        return is_null($stat) ? $stats : $stats[$stat];
518    } else {
519        return false;
520    }
521}
522
523/*
524* Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5.
525* It makes an exclusive lock on the file while writing.
526*
527* @access   public
528* @param    string  $filename   Path to file.
529* @param    string  $content    Data to write into file.
530* @return   bool                Success or failure.
531* @author   Quinn Comendant <quinn@strangecode.com>
532* @since    11 Apr 2006 22:48:30
533*/
534function filePutContents($filename, $content)
535{
536    $app =& App::getInstance();
537
538    // Open file for writing and truncate to zero length.
539    if ($fp = fopen($filename, 'w')) {
540        if (flock($fp, LOCK_EX)) {
541            if (!fwrite($fp, $content, mb_strlen($content))) {
542                $app->logMsg(sprintf('Failed writing to file: %s', $filename), LOG_ERR, __FILE__, __LINE__);
543                fclose($fp);
544                return false;
545            }
546            flock($fp, LOCK_UN);
547        } else {
548            $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
549            fclose($fp);
550            return false;
551        }
552        fclose($fp);
553        // Success!
554        $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
555        return true;
556    } else {
557        $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
558        return false;
559    }
560}
561
562/**
563 * If $var is net set or null, set it to $default. Otherwise leave it alone.
564 * Returns the final value of $var. Use to find a default value of one is not available.
565 *
566 * @param  mixed $var       The variable that is being set.
567 * @param  mixed $default   What to set it to if $val is not currently set.
568 * @return mixed            The resulting value of $var.
569 */
570function setDefault(&$var, $default='')
571{
572    if (!isset($var)) {
573        $var = $default;
574    }
575    return $var;
576}
577
578/**
579 * Like preg_quote() except for arrays, it takes an array of strings and puts
580 * a backslash in front of every character that is part of the regular
581 * expression syntax.
582 *
583 * @param  array $array    input array
584 * @param  array $delim    optional character that will also be escaped.
585 * @return array    an array with the same values as $array1 but shuffled
586 */
587function pregQuoteArray($array, $delim='/')
588{
589    if (!empty($array)) {
590        if (is_array($array)) {
591            foreach ($array as $key=>$val) {
592                $quoted_array[$key] = preg_quote($val, $delim);
593            }
594            return $quoted_array;
595        } else {
596            return preg_quote($array, $delim);
597        }
598    }
599}
600
601/**
602 * Converts a PHP Array into encoded URL arguments and return them as an array.
603 *
604 * @param  mixed $data        An array to transverse recursively, or a string
605 *                            to use directly to create url arguments.
606 * @param  string $prefix     The name of the first dimension of the array.
607 *                            If not specified, the first keys of the array will be used.
608 * @return array              URL with array elements as URL key=value arguments.
609 */
610function urlEncodeArray($data, $prefix='', $_return=true)
611{
612    // Data is stored in static variable.
613    static $args;
614
615    if (is_array($data)) {
616        foreach ($data as $key => $val) {
617            // If the prefix is empty, use the $key as the name of the first dimension of the "array".
618            // ...otherwise, append the key as a new dimension of the "array".
619            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
620            // Enter recursion.
621            urlEncodeArray($val, $new_prefix, false);
622        }
623    } else {
624        // We've come to the last dimension of the array, save the "array" and its value.
625        $args[$prefix] = urlencode($data);
626    }
627
628    if ($_return) {
629        // This is not a recursive execution. All recursion is complete.
630        // Reset static var and return the result.
631        $ret = $args;
632        $args = array();
633        return is_array($ret) ? $ret : array();
634    }
635}
636
637/**
638 * Converts a PHP Array into encoded URL arguments and return them in a string.
639 *
640 * @param  mixed $data        An array to transverse recursively, or a string
641 *                            to use directly to create url arguments.
642 * @param  string $prefix     The name of the first dimension of the array.
643 *                            If not specified, the first keys of the array will be used.
644 * @return string url         A string ready to append to a url.
645 */
646function urlEncodeArrayToString($data, $prefix='')
647{
648
649    $array_args = urlEncodeArray($data, $prefix);
650    $url_args = '';
651    $delim = '';
652    foreach ($array_args as $key=>$val) {
653        $url_args .= $delim . $key . '=' . $val;
654        $delim = ini_get('arg_separator.output');
655    }
656    return $url_args;
657}
658
659/**
660 * Fills an array with the result from a multiple ereg search.
661 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
662 *
663 * @param  mixed $pattern   regular expression needle
664 * @param  mixed $string   haystack
665 * @return array    populated with each found result
666 */
667function eregAll($pattern, $string)
668{
669    do {
670        if (!mb_ereg($pattern, $string, $temp)) {
671             continue;
672        }
673        $string = str_replace($temp[0], '', $string);
674        $results[] = $temp;
675    } while (mb_ereg($pattern, $string, $temp));
676    return $results;
677}
678
679/**
680 * Prints the word "checked" if a variable is set, and optionally matches
681 * the desired value, otherwise prints nothing,
682 * used for printing the word "checked" in a checkbox form input.
683 *
684 * @param  mixed $var     the variable to compare
685 * @param  mixed $value   optional, what to compare with if a specific value is required.
686 */
687function frmChecked($var, $value=null)
688{
689    if (func_num_args() == 1 && $var) {
690        // 'Checked' if var is true.
691        echo ' checked="checked" ';
692    } else if (func_num_args() == 2 && $var == $value) {
693        // 'Checked' if var and value match.
694        echo ' checked="checked" ';
695    } else if (func_num_args() == 2 && is_array($var)) {
696        // 'Checked' if the value is in the key or the value of an array.
697        if (isset($var[$value])) {
698            echo ' checked="checked" ';
699        } else if (in_array($value, $var)) {
700            echo ' checked="checked" ';
701        }
702    }
703}
704
705/**
706 * prints the word "selected" if a variable is set, and optionally matches
707 * the desired value, otherwise prints nothing,
708 * otherwise prints nothing, used for printing the word "checked" in a
709 * select form input
710 *
711 * @param  mixed $var     the variable to compare
712 * @param  mixed $value   optional, what to compare with if a specific value is required.
713 */
714function frmSelected($var, $value=null)
715{
716    if (func_num_args() == 1 && $var) {
717        // 'selected' if var is true.
718        echo ' selected="selected" ';
719    } else if (func_num_args() == 2 && $var == $value) {
720        // 'selected' if var and value match.
721        echo ' selected="selected" ';
722    } else if (func_num_args() == 2 && is_array($var)) {
723        // 'selected' if the value is in the key or the value of an array.
724        if (isset($var[$value])) {
725            echo ' selected="selected" ';
726        } else if (in_array($value, $var)) {
727            echo ' selected="selected" ';
728        }
729    }
730}
731
732/**
733 * Adds slashes to values of an array and converts the array to a comma
734 * delimited list. If value provided is a string return the string
735 * escaped.  This is useful for putting values coming in from posted
736 * checkboxes into a SET column of a database.
737 *
738 *
739 * @param  array $in      Array to convert.
740 * @return string         Comma list of array values.
741 */
742function escapedList($in, $separator="', '")
743{
744    $db =& DB::getInstance();
745
746    if (is_array($in) && !empty($in)) {
747        return join($separator, array_map(array($db, 'escapeString'), $in));
748    } else {
749        return $db->escapeString($in);
750    }
751}
752
753/**
754 * Converts a human string date into a SQL-safe date.  Dates nearing
755 * infinity use the date 2038-01-01 so conversion to unix time format
756 * remain within valid range.
757 *
758 * @param  array $date     String date to convert.
759 * @param  array $format   Date format to pass to date().
760 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
761 * @return string          SQL-safe date.
762 */
763function strToSQLDate($date, $format='Y-m-d H:i:s')
764{
765    // Translate the human string date into SQL-safe date format.
766    if (empty($date) || mb_strpos($date, '0000-00-00') !== false || strtotime($date) === -1 || strtotime($date) === false) {
767        // Return a string of zero time, formatted the same as $format.
768        return strtr($format, array(
769            'Y' => '0000',
770            'm' => '00',
771            'd' => '00',
772            'H' => '00',
773            'i' => '00',
774            's' => '00',
775        ));
776    } else {
777        return date($format, strtotime($date));
778    }
779}
780
781/**
782 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
783 * array, stripslashes is run on each value, recursively, and the stripped
784 * array is returned.
785 *
786 * @param  mixed $var   The string or array to un-quote, if necessary.
787 * @return mixed        $var, minus any magic quotes.
788 */
789function dispelMagicQuotes($var)
790{
791    static $magic_quotes_gpc;
792
793    if (!isset($magic_quotes_gpc)) {
794        $magic_quotes_gpc = get_magic_quotes_gpc();
795    }
796
797    if ($magic_quotes_gpc) {
798        if (!is_array($var)) {
799            $var = stripslashes($var);
800        } else {
801            foreach ($var as $key=>$val) {
802                if (is_array($val)) {
803                    $var[$key] = dispelMagicQuotes($val);
804                } else {
805                    $var[$key] = stripslashes($val);
806                }
807            }
808        }
809    }
810    return $var;
811}
812
813/**
814 * Get a form variable from GET or POST data, stripped of magic
815 * quotes if necessary.
816 *
817 * @param string $var (optional) The name of the form variable to look for.
818 * @param string $default (optional) The value to return if the
819 *                                   variable is not there.
820 * @return mixed      A cleaned GET or POST if no $var specified.
821 * @return string     A cleaned form $var if found, or $default.
822 */
823function getFormData($var=null, $default=null)
824{
825    if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) {
826        return dispelMagicQuotes($_POST);
827    } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) {
828        return dispelMagicQuotes($_GET);
829    }
830    if (isset($_POST[$var])) {
831        return dispelMagicQuotes($_POST[$var]);
832    } else if (isset($_GET[$var])) {
833        return dispelMagicQuotes($_GET[$var]);
834    } else {
835        return $default;
836    }
837}
838function getPost($var=null, $default=null)
839{
840    if (is_null($var)) {
841        return dispelMagicQuotes($_POST);
842    }
843    if (isset($_POST[$var])) {
844        return dispelMagicQuotes($_POST[$var]);
845    } else {
846        return $default;
847    }
848}
849function getGet($var=null, $default=null)
850{
851    if (is_null($var)) {
852        return dispelMagicQuotes($_GET);
853    }
854    if (isset($_GET[$var])) {
855        return dispelMagicQuotes($_GET[$var]);
856    } else {
857        return $default;
858    }
859}
860
861/*
862* Sets a $_GET or $_POST variable.
863*
864* @access   public
865* @param    string  $key    The key of the request array to set.
866* @param    mixed   $val    The value to save in the request array.
867* @return   void
868* @author   Quinn Comendant <quinn@strangecode.com>
869* @version  1.0
870* @since    01 Nov 2009 12:25:29
871*/
872function putFormData($key, $val)
873{
874    if ('POST' == getenv('REQUEST_METHOD')) {
875        $_POST[$key] = $val;
876    } else if ('GET' == getenv('REQUEST_METHOD')) {
877        $_GET[$key] = $val;
878    }
879}
880
881/**
882 * Signs a value using md5 and a simple text key. In order for this
883 * function to be useful (i.e. secure) the key must be kept secret, which
884 * means keeping it as safe as database credentials. Putting it into an
885 * environment variable set in httpd.conf is a good place.
886 *
887 * @access  public
888 * @param   string  $val    The string to sign.
889 * @param   string  $salt   (Optional) A text key to use for computing the signature.
890 * @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.
891 * @return  string  The original value with a signature appended.
892 */
893function addSignature($val, $salt=null, $length=18)
894{
895    $app =& App::getInstance();
896
897    if ('' == trim($val)) {
898        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
899        return '';
900    }
901
902    if (!isset($salt)) {
903        $salt = $app->getParam('signing_key');
904    }
905
906    // TODO: consider using more bits-per-character, such as done with:
907    // http://www.php.net/manual/en/function.sha1.php#86239
908    // http://blog.kevburnsjr.com/php-unique-hash
909    return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
910}
911
912/**
913 * Strips off the signature appended by addSignature().
914 *
915 * @access  public
916 * @param   string  $signed_val     The string to sign.
917 * @return  string  The original value with a signature removed.
918 */
919function removeSignature($signed_val)
920{
921    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
922        return '';
923    }
924    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
925}
926
927/**
928 * Verifies a signature appened to a value by addSignature().
929 *
930 * @access  public
931 * @param   string  $signed_val A value with appended signature.
932 * @param   string  $salt       (Optional) A text key to use for computing the signature.
933 * @return  bool    True if the signature matches the var.
934 */
935function verifySignature($signed_val, $salt=null, $length=18)
936{
937    // All comparisons are done using lower-case strings.
938    $signed_val = mb_strtolower($signed_val);
939    // Strip the value from the signed value.
940    $val = removeSignature($signed_val);
941    // If the signed value matches the original signed value we consider the value safe.
942    if ($signed_val == addSignature($val, $salt, $length)) {
943        // Signature verified.
944        return true;
945    } else {
946        return false;
947    }
948}
949
950/**
951 * Sends empty output to the browser and flushes the php buffer so the client
952 * will see data before the page is finished processing.
953 */
954function flushBuffer()
955{
956    echo str_repeat('          ', 205);
957    flush();
958}
959
960/**
961 * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
962 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
963 *
964 * @access  public
965 * @param   string  $email     Email address to add.
966 * @param   string  $list      Name of list to add to.
967 * @param   bool    $send_welcome_message   True to send welcome message to subscriber.
968 * @return  bool    True on success, false on failure.
969 */
970function mailmanAddMember($email, $list, $send_welcome_message=false)
971{
972    $app =& App::getInstance();
973
974    $add_members = '/usr/lib/mailman/bin/add_members';
975    // FIXME: checking of executable is disabled.
976    if (true || is_executable($add_members) && is_readable($add_members)) {
977        $welcome_msg = $send_welcome_message ? 'y' : 'n';
978        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);
979        if (0 == $return_code) {
980            $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
981            return true;
982        } else {
983            $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, getDump($stdout)), LOG_WARNING, __FILE__, __LINE__);
984            return false;
985        }
986    } else {
987        $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
988        return false;
989    }
990}
991
992/**
993 * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
994 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
995 *
996 * @access  public
997 * @param   string  $email     Email address to add.
998 * @param   string  $list      Name of list to add to.
999 * @param   bool    $send_user_ack   True to send goodbye message to subscriber.
1000 * @return  bool    True on success, false on failure.
1001 */
1002function mailmanRemoveMember($email, $list, $send_user_ack=false)
1003{
1004    $app =& App::getInstance();
1005
1006    $remove_members = '/usr/lib/mailman/bin/remove_members';
1007    // FIXME: checking of executable is disabled.
1008    if (true || is_executable($remove_members) && is_readable($remove_members)) {
1009        $userack = $send_user_ack ? '' : '--nouserack';
1010        exec(sprintf("/usr/bin/sudo %s %s --noadminack '%s' '%s'", escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
1011        if (0 == $return_code) {
1012            $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
1013            return true;
1014        } else {
1015            $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
1016            return false;
1017        }
1018    } else {
1019        $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
1020        return false;
1021    }
1022}
1023
1024/**
1025 * Returns the remote IP address, taking into consideration proxy servers.
1026 *
1027 * @param  bool $dolookup   If true we resolve to IP to a host name,
1028 *                          if false we don't.
1029 * @return string    IP address if $dolookup is false or no arg
1030 *                   Hostname if $dolookup is true
1031 */
1032function getRemoteAddr($dolookup=false)
1033{
1034    $ip = getenv('HTTP_CLIENT_IP');
1035    if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) {
1036        $ip = getenv('HTTP_X_FORWARDED_FOR');
1037        if (mb_strpos($ip, ',') !== false) {
1038            // If HTTP_X_FORWARDED_FOR returns a comma-delimited list of IPs then return the first one (assuming the first is the original).
1039            $ips = explode(',', $ip, 2);
1040            $ip = $ips[0];
1041        }
1042        if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) {
1043            $ip = getenv('REMOTE_ADDR');
1044        }
1045    }
1046    return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip;
1047}
1048
1049/**
1050 * Tests whether a given IP address can be found in an array of IP address networks.
1051 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
1052 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
1053 *
1054 * @access  public
1055 * @param   string  IP address to search for.
1056 * @param   array   Array of networks to search within.
1057 * @return  mixed   Returns the network that matched on success, false on failure.
1058 */
1059function ipInRange($ip, $networks)
1060{
1061    if (!is_array($networks)) {
1062        $networks = array($networks);
1063    }
1064
1065    $ip_binary = sprintf('%032b', ip2long($ip));
1066    foreach ($networks as $network) {
1067        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) {
1068            // IP is in CIDR notation.
1069            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
1070            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
1071            if (mb_substr($ip_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
1072               // IP address is within the specified IP range.
1073               return $network;
1074            }
1075        } else {
1076            if ($ip === $network) {
1077               // IP address exactly matches.
1078               return $network;
1079            }
1080        }
1081    }
1082
1083    return false;
1084}
1085
1086/**
1087 * If the given $url is on the same web site, return true. This can be used to
1088 * prevent from sending sensitive info in a get query (like the SID) to another
1089 * domain.
1090 *
1091 * @param  string $url    the URI to test.
1092 * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another.
1093 */
1094function isMyDomain($url)
1095{
1096    static $urls = array();
1097
1098    if (!isset($urls[$url])) {
1099        if (!preg_match('|https?://[\w.]+/|', $url)) {
1100            // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg").
1101            $urls[$url] = true;
1102        } else {
1103            $urls[$url] = preg_match('|https?://[\w.]*' . preg_quote(getenv('HTTP_HOST'), '|') . '|i', $url);
1104        }
1105    }
1106    return $urls[$url];
1107}
1108
1109/**
1110 * Takes a URL and returns it without the query or anchor portion
1111 *
1112 * @param  string $url   any kind of URI
1113 * @return string        the URI with ? or # and everything after removed
1114 */
1115function stripQuery($url)
1116{
1117    return preg_replace('/[?#].*$/', '', $url);
1118}
1119
1120/**
1121 * Returns a fully qualified URL to the current script, including the query.
1122 *
1123 * @return string    a full url to the current script
1124 */
1125function absoluteMe()
1126{
1127    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
1128    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
1129}
1130
1131/**
1132 * Compares the current url with the referring url.
1133 *
1134 * @param  bool $exclude_query  Remove the query string first before comparing.
1135 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
1136 */
1137function refererIsMe($exclude_query=false)
1138{
1139    if ($exclude_query) {
1140        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
1141    } else {
1142        return (absoluteMe() == getenv('HTTP_REFERER'));
1143    }
1144}
1145
Note: See TracBrowser for help on using the repository browser.