source: tags/2.1.5/lib/Utilities.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

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