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

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

Removed use of requireAccessClearance(). Adjusted sequence of sslOn() and requireLogin(). Added ACL::requireAllow() method. Added arguments to SortOrder::set(). Changed behavior of Validator::validateStrDate(). Added use of Validator::validateStrDate() to module maker templates.

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