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

Last change on this file since 392 was 380, checked in by anonymous, 13 years ago

Begin using PHP 5 class features ('public static...'); updated Currency.inc.php to support Xurrency's JSON API

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