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

Last change on this file since 363 was 363, checked in by quinn, 15 years ago

Fixed a bug in the humanTime() function.

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