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

Last change on this file since 103 was 103, checked in by scdev, 18 years ago

Q - Cleaned up Auth_File to work more like Auth_SQL, and fixed a few bugs here and there.

File size: 28.3 KB
Line 
1<?php
2/**
3 * Utilities.inc.php
4 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
5 */
6
7
8/**
9 * Print variable dump.
10 *
11 * @param  mixed $var      Variable to dump.
12 * @param  bool  $display   Hide the dump in HTML comments?
13 * @param  bool  $var_dump Use var_dump instead of print_r.
14 */
15function dump($var, $display=false, $var_dump=false)
16{
17    echo $display ? "\n<br /><pre>\n" : "\n\n\n<!--\n";
18    if ($var_dump) {
19        var_dump($var);
20    } else {
21        print_r($var);
22    }
23    echo $display ?  "\n</pre><br />\n" : "\n-->\n\n\n";
24}
25
26/**
27 * Return dump as variable.
28 *
29 * @param  mixed $var      Variable to dump.
30 * @return string Dump of var.
31 */
32function getDump($var)
33{
34    ob_start();
35    print_r($var);
36    $d = ob_get_contents();
37    ob_end_clean();
38    return $d;
39}
40
41/**
42 * Return dump as cleaned text. Useful for dumping data into emails.
43 *
44 * @param  mixed $var      Variable to dump.
45 * @return string Dump of var.
46 */
47function fancyDump($var, $indent='')
48{
49    $output = '';
50    if (is_array($var)) {
51        foreach ($var as $k=>$v) {
52            $k = ucfirst(strtolower(str_replace(array('_', '  '), ' ', $k)));
53            if (is_array($v)) {
54                $output .= sprintf("\n%s%s: %s\n", $indent, $k, fancyDump($v, $indent . $indent));
55            } else {
56                $output .= sprintf("%s%s: %s\n", $indent, $k, $v);
57            }
58        }
59    } else {
60        $output .= sprintf("%s%s\n", $indent, $var);
61    }
62    return $output;
63}
64
65/**
66 * Returns text with appropriate html translations.
67 *
68 * @param  string $txt              Text to clean.
69 * @param  bool   $preserve_html    If set to true, oTxt will not translage <, >, ", or '
70 *                                  characters into HTML entities. This allows HTML to pass
71 *                                  through unmunged.
72 * @return string                   Cleaned text.
73 */
74function oTxt($txt, $preserve_html=false)
75{
76    $search = array();
77    $replace = array();
78
79    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
80    $search['retain_ampersand']     = '/&amp;/';
81    $replace['retain_ampersand']    = '&';
82
83    if ($preserve_html) {
84        // Convert characters that must remain non-entities for displaying HTML.
85        $search['retain_left_angle']       = '/&lt;/';
86        $replace['retain_left_angle']      = '<';
87
88        $search['retain_right_angle']      = '/&gt;/';
89        $replace['retain_right_angle']     = '>';
90
91        $search['retain_single_quote']     = '/&#039;/';
92        $replace['retain_single_quote']    = "'";
93
94        $search['retain_double_quote']     = '/&quot;/';
95        $replace['retain_double_quote']    = '"';
96    }
97
98    // & becomes &amp;. Exclude any occurance where the & is followed by a alphanum or unicode caracter.
99    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
100    $replace['ampersand']       = '&amp;';
101
102    return preg_replace($search, $replace, htmlentities($txt, ENT_QUOTES, App::getParam('character_set')));
103}
104
105/**
106 * Returns text with stylistic modifications. Warning: this will break some HTML attibutes!
107 * FIXME: Allow a string such as this to be passted: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
108 *
109 * @param  string   $txt  Text to clean.
110 * @return string         Cleaned text.
111 */
112function fancyTxt($txt)
113{
114    $search = array();
115    $replace = array();
116
117    // "double quoted text"  becomes  &ldquo;double quoted text&rdquo;
118    $search['double_quotes']    = '/(^|[^\w=])(?:"|&quot;|&#34;|&#x22;|&ldquo;)([^"]+?)(?:"|&quot;|&#34;|&#x22;|&rdquo;)([^\w]|$)/ms'; // " is the same as &quot; and &#34; and &#x22;
119    $replace['double_quotes']   = '$1&ldquo;$2&rdquo;$3';
120
121    // text's apostrophes  become  text&rsquo;s apostrophes
122    $search['apostrophe']       = '/(\w)(?:\'|&#39;|&#039;)(\w)/ms';
123    $replace['apostrophe']      = '$1&rsquo;$2';
124
125    // 'single quoted text'  becomes  &lsquo;single quoted text&rsquo;
126    $search['single_quotes']    = '/(^|[^\w=])(?:\'|&#39;|&lsquo;)([^\']+?)(?:\'|&#39;|&rsquo;)([^\w]|$)/ms';
127    $replace['single_quotes']   = '$1&lsquo;$2&rsquo;$3';
128
129    // plural posessives' apostrophes become posessives&rsquo;
130    $search['apostrophes']      = '/(s)(?:\'|&#39;|&#039;)(\s)/ms';
131    $replace['apostrophes']     = '$1&rsquo;$2';
132
133    // em--dashes  become em&mdash;dashes
134    $search['em_dash']          = '/(\s*[^!<-])--([^>-]\s*)/';
135    $replace['em_dash']         = '$1&mdash;$2';
136
137    return preg_replace($search, $replace, $txt);
138}
139
140
141/**
142 * Generates a hexadecibal html color based on provided word.
143 *
144 * @access public
145 * @param  string $text  A string for which to convert to color.
146 * @return string  A hexadecimal html color.
147 */
148function getTextColor($text, $method=1)
149{
150    $r = substr(md5($text), 0, 1);
151    $g = substr(md5($text), 1, 1);
152    $b = substr(md5($text), 2, 1);
153
154    switch ($method) {
155    case 2 :
156        if (hexdec($r) > hexdec('c')) {
157            $r = dechex(hexdec('f') - hexdec($r));
158        }
159        if (hexdec($g) > hexdec('c')) {
160            $g = dechex(hexdec('f') - hexdec($g));
161        }
162        if (hexdec($b) > hexdec('c')) {
163            $b = dechex(hexdec('f') - hexdec($b));
164        }
165        break;
166
167    case 1 :
168    default :
169        $r = dechex(round(hexdec($r) * .8));
170        $g = dechex(round(hexdec($g) * .8));
171        $b = dechex(round(hexdec($b) * .6));
172        break;
173    }
174
175    return $r . $r . $g . $g . $b . $b;
176}
177
178/**
179 * Encodes a string into unicode values 128-255.
180 * Useful for hiding an email address from spambots.
181 *
182 * @access  public
183 * @param   string   $text   A line of text to encode.
184 * @return  string   Encoded text.
185 */
186function encodeAscii($text)
187{
188    $ouput = '';
189    $num = strlen($text);
190    for ($i=0; $i<$num; $i++) {
191        $output .= sprintf('&#%03s', ord($text{$i}));
192    }
193    return $output;
194}
195
196/**
197 * Encodes an email into a "user at domain dot com" format.
198 *
199 * @access  public
200 * @param   string   $email   An email to encode.
201 * @param   string   $at      Replaces the @.
202 * @param   string   $dot     Replaces the ..
203 * @return  string   Encoded email.
204 */
205function encodeEmail($email, $at=' at ', $dot=' dot ')
206{
207    $search = array('/@/', '/\./');
208    $replace = array($at, $dot);
209    return preg_replace($search, $replace, $email);
210}
211
212/**
213 * Turns "a really long string" into "a rea...string"
214 *
215 * @access  public
216 * @param   string  $str    Input string
217 * @param   int     $len    Maximum string length.
218 * @param   string  $where  Where to cut the string. One of: 'start', 'middle', or 'end'.
219 * @return  string          Truncated output string
220 * @author  Quinn Comendant <quinn@strangecode.com>
221 * @since   29 Mar 2006 13:48:49
222 */
223function truncate($str, $len, $where='middle')
224{
225    $part1 = floor(($len - 3) / 2);
226    $part2 = ceil(($len - 3) / 2);
227    switch ($where) {
228    case 'start' :
229        return preg_replace(array(sprintf('/^.{4,}(.{%s})$/', $part1 + $part2), '/\s*\.{3,}\s*/'), array('...$1', '...'), $str);
230        break;
231    default :
232    case 'middle' :
233        return preg_replace(array(sprintf('/^(.{%s}).{4,}(.{%s})$/', $part1, $part2), '/\s*\.{3,}\s*/'), array('$1...$2', '...'), $str);
234        break;   
235    case 'end' :
236        return preg_replace(array(sprintf('/^(.{%s}).{4,}$/', $part1 + $part2), '/\s*\.{3,}\s*/'), array('$1...', '...'), $str);
237        break;   
238    }
239}
240
241/**
242 * Return a human readable filesize.
243 *
244 * @param       int    $size        Size
245 * @param       int    $unit        The maximum unit
246 * @param       int    $format      The return string format
247 * @author      Aidan Lister <aidan@php.net>
248 * @version     1.1.0
249 */
250function humanFileSize($size, $unit=null, $format='%01.2f %s')
251{
252    // Units
253    $units = array('B', 'KB', 'MB', 'GB', 'TB');
254    $ii = count($units) - 1;
255
256    // Max unit
257    $unit = array_search((string) $unit, $units);
258    if ($unit === null || $unit === false) {
259        $unit = $ii;
260    }
261
262    // Loop
263    $i = 0;
264    while ($unit != $i && $size >= 1024 && $i < $ii) {
265        $size /= 1024;
266        $i++;
267    }
268
269    return sprintf($format, $size, $units[$i]);
270}
271
272/**
273 * Returns stats of a file from the include path.
274 *
275 * @param   string  $file   File in include path.
276 * @return  mixed   Value of requested key from fstat(), or false on error.
277 * @author  Quinn Comendant <quinn@strangecode.com>
278 * @since   03 Dec 2005 14:23:26
279 */
280function statIncludePath($file, $stat)
281{
282    // Open file pointer read-only using include path.
283    if ($fp = fopen($file, 'r', true)) {
284        // File opend successfully, get stats.
285        $stats = fstat($fp);
286        fclose($fp);
287        // Return specified stats.
288        return $stats[$stat];
289    } else {
290        return false;
291    }
292}
293
294/**
295 * If $var is net set or null, set it to $default. Otherwise leave it alone.
296 * Returns the final value of $var. Use to find a default value of one is not avilable.
297 *
298 * @param  mixed $var       The variable that is being set.
299 * @param  mixed $default   What to set it to if $val is not currently set.
300 * @return mixed            The resulting value of $var.
301 */
302function setDefault(&$var, $default='')
303{
304    if (!isset($var)) {
305        $var = $default;
306    }
307    return $var;
308}
309
310/**
311 * Like preg_quote() except for arrays, it takes an array of strings and puts
312 * a backslash in front of every character that is part of the regular
313 * expression syntax.
314 *
315 * @param  array $array    input array
316 * @param  array $delim    optional character that will also be excaped.
317 * @return array    an array with the same values as $array1 but shuffled
318 */
319function pregQuoteArray($array, $delim='/')
320{
321    if (!empty($array)) {
322        if (is_array($array)) {
323            foreach ($array as $key=>$val) {
324                $quoted_array[$key] = preg_quote($val, $delim);
325            }
326            return $quoted_array;
327        } else {
328            return preg_quote($array, $delim);
329        }
330    }
331}
332
333/**
334 * Converts a PHP Array into encoded URL arguments and return them as an array.
335 *
336 * @param  mixed $data        An array to transverse recursivly, or a string
337 *                            to use directly to create url arguments.
338 * @param  string $prefix     The name of the first dimension of the array.
339 *                            If not specified, the first keys of the array will be used.
340 * @return array              URL with array elements as URL key=value arguments.
341 */
342function urlEncodeArray($data, $prefix='', $_return=true) {
343
344    // Data is stored in static variable.
345    static $args;
346
347    if (is_array($data)) {
348        foreach ($data as $key => $val) {
349            // If the prefix is empty, use the $key as the name of the first dimention of the "array".
350            // ...otherwise, append the key as a new dimention of the "array".
351            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
352            // Enter recursion.
353            urlEncodeArray($val, $new_prefix, false);
354        }
355    } else {
356        // We've come to the last dimention of the array, save the "array" and its value.
357        $args[$prefix] = urlencode($data);
358    }
359
360    if ($_return) {
361        // This is not a recursive execution. All recursion is complete.
362        // Reset static var and return the result.
363        $ret = $args;
364        $args = array();
365        return is_array($ret) ? $ret : array();
366    }
367}
368
369/**
370 * Converts a PHP Array into encoded URL arguments and return them in a string.
371 *
372 * @param  mixed $data        An array to transverse recursivly, or a string
373 *                            to use directly to create url arguments.
374 * @param  string $prefix     The name of the first dimention of the array.
375 *                            If not specified, the first keys of the array will be used.
376 * @return string url         A string ready to append to a url.
377 */
378function urlEncodeArrayToString($data, $prefix='') {
379
380    $array_args = urlEncodeArray($data, $prefix);
381    $url_args = '';
382    $delim = '';
383    foreach ($array_args as $key=>$val) {
384        $url_args .= $delim . $key . '=' . $val;
385        $delim = ini_get('arg_separator.output');
386    }
387    return $url_args;
388}
389
390/**
391 * Fills an arrray with the result from a multiple ereg search.
392 * Curtesy of Bruno - rbronosky@mac.com - 10-May-2001
393 * Blame him for the funky do...while loop.
394 *
395 * @param  mixed $pattern   regular expression needle
396 * @param  mixed $string   haystack
397 * @return array    populated with each found result
398 */
399function eregAll($pattern, $string)
400{
401    do {
402        if (!ereg($pattern, $string, $temp)) {
403             continue;
404        }
405        $string = str_replace($temp[0], '', $string);
406        $results[] = $temp;
407    } while (ereg($pattern, $string, $temp));
408    return $results;
409}
410
411/**
412 * Prints the word "checked" if a variable is set, and optionally matches
413 * the desired value, otherwise prints nothing,
414 * used for printing the word "checked" in a checkbox form input.
415 *
416 * @param  mixed $var     the variable to compare
417 * @param  mixed $value   optional, what to compare with if a specific value is required.
418 */
419function frmChecked($var, $value=null)
420{
421    if (func_num_args() == 1 && $var) {
422        // 'Checked' if var is true.
423        echo ' checked="checked" ';
424    } else if (func_num_args() == 2 && $var == $value) {
425        // 'Checked' if var and value match.
426        echo ' checked="checked" ';
427    } else if (func_num_args() == 2 && is_array($var)) {
428        // 'Checked' if the value is in the key or the value of an array.
429        if (isset($var[$value])) {
430            echo ' checked="checked" ';
431        } else if (in_array($value, $var)) {
432            echo ' checked="checked" ';
433        }
434    }
435}
436
437/**
438 * prints the word "selected" if a variable is set, and optionally matches
439 * the desired value, otherwise prints nothing,
440 * otherwise prints nothing, used for printing the word "checked" in a
441 * select form input
442 *
443 * @param  mixed $var     the variable to compare
444 * @param  mixed $value   optional, what to compare with if a specific value is required.
445 */
446function frmSelected($var, $value=null)
447{
448    if (func_num_args() == 1 && $var) {
449        // 'selected' if var is true.
450        echo ' selected="selected" ';
451    } else if (func_num_args() == 2 && $var == $value) {
452        // 'selected' if var and value match.
453        echo ' selected="selected" ';
454    } else if (func_num_args() == 2 && is_array($var)) {
455        // 'selected' if the value is in the key or the value of an array.
456        if (isset($var[$value])) {
457            echo ' selected="selected" ';
458        } else if (in_array($value, $var)) {
459            echo ' selected="selected" ';
460        }
461    }
462}
463
464/**
465 * Adds slashes to values of an array and converts the array to a
466 * comma delimited list. If value provided is not an array or is empty
467 * return nothing. This is useful for putting values coming in from
468 * posted checkboxes into a SET column of a database.
469 *
470 * @param  array $array   Array to convert.
471 * @return string         Comma list of array values.
472 */
473function dbArrayToList($array)
474{
475    if (is_array($array) && !empty($array)) {
476        return join(',', array_map('addslashes', array_keys($array)));
477    }
478}
479
480/**
481 * Converts a human string date into a SQL-safe date.
482 * Dates nearing infinity use the date 2038-01-01 so conversion to unix time
483 * format remain within valid range.
484 *
485 * @param  array $date     String date to convert.
486 * @param  array $format   Date format to pass to date().
487 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
488 * @return string          SQL-safe date.
489 */
490function strToSQLDate($date, $format='Y-m-d H:i:s')
491{
492    // Translate the human string date into SQL-safe date format.
493    if (empty($date) || '0000-00-00' == $date || strtotime($date) === -1) {
494        $sql_date = '0000-00-00';
495    } else {
496        $sql_date = date($format, strtotime($date));
497    }
498
499    return $sql_date;
500}
501
502/**
503 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
504 * array, stripslashes is run on each value, recursivly, and the stripped
505 * array is returned.
506 *
507 * @param  mixed $var   The string or array to un-quote, if necessary.
508 * @return mixed        $var, minus any magic quotes.
509 */
510function dispelMagicQuotes($var)
511{
512    static $magic_quotes_gpc;
513
514    if (!isset($magic_quotes_gpc)) {
515        $magic_quotes_gpc = get_magic_quotes_gpc();
516    }
517
518    if ($magic_quotes_gpc) {
519        if (!is_array($var)) {
520            $var = stripslashes($var);
521        } else {
522            foreach ($var as $key=>$val) {
523                if (is_array($val)) {
524                    $var[$key] = dispelMagicQuotes($val);
525                } else {
526                    $var[$key] = stripslashes($val);
527                }
528            }
529        }
530    }
531    return $var;
532}
533
534/**
535 * Get a form variable from GET or POST data, stripped of magic
536 * quotes if necessary.
537 *
538 * @param string $var (optional) The name of the form variable to look for.
539 * @param string $default (optional) The value to return if the
540 *                                   variable is not there.
541 * @return mixed      A cleaned GET or POST if no $var specified.
542 * @return string     A cleaned form $var if found, or $default.
543 */
544function getFormData($var=null, $default=null)
545{
546    if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) {
547        return dispelMagicQuotes($_POST);
548    } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) {
549        return dispelMagicQuotes($_GET);
550    }
551    if (isset($_POST[$var])) {
552        return dispelMagicQuotes($_POST[$var]);
553    } else if (isset($_GET[$var])) {
554        return dispelMagicQuotes($_GET[$var]);
555    } else {
556        return $default;
557    }
558}
559function getPost($var=null, $default=null)
560{
561    if (is_null($var)) {
562        return dispelMagicQuotes($_POST);
563    }
564    if (isset($_POST[$var])) {
565        return dispelMagicQuotes($_POST[$var]);
566    } else {
567        return $default;
568    }
569}
570function getGet($var=null, $default=null)
571{
572    if (is_null($var)) {
573        return dispelMagicQuotes($_GET);
574    }
575    if (isset($_GET[$var])) {
576        return dispelMagicQuotes($_GET[$var]);
577    } else {
578        return $default;
579    }
580}
581
582/**
583 * Signs a value using md5 and a simple text key. In order for this
584 * function to be useful (i.e. secure) the key must be kept secret, which
585 * means keeping it as safe as database credentials. Putting it into an
586 * environment variable set in httpd.conf is a good place.
587 *
588 * @access  public
589 * @param   string  $val    The string to sign.
590 * @param   string  $seed_key   (Optional) A text key to use for computing the signature.
591 * @return  string  The original value with a signature appended.
592 */
593function addSignature($val, $seed_key=null)
594{
595    if ('' == $val) {
596        App::logMsg(sprintf('Adding signature to empty string.', null), LOG_NOTICE, __FILE__, __LINE__);
597    }
598
599    if (!isset($seed_key)) {
600        $seed_key = App::getParam('signing_key');
601    }
602
603    return $val . '-' . substr(md5($val . $seed_key), 0, 18);
604}
605
606/**
607 * Strips off the signature appended by addSignature().
608 *
609 * @access  public
610 * @param   string  $signed_val     The string to sign.
611 * @return  string  The original value with a signature removed.
612 */
613function removeSignature($signed_val)
614{
615    return substr($signed_val, 0, strrpos($signed_val, '-'));
616}
617
618
619/**
620 * Verifies a signature appened to a value by addSignature().
621 *
622 * @access  public
623 * @param   string  $signed_val A value with appended signature.
624 * @param   string  $seed_key       (Optional) A text key to use for computing the signature.
625 * @return  bool    True if the signature matches the var.
626 */
627function verifySignature($signed_val, $seed_key=null)
628{
629    // Strip the value from the signed value.
630    $val = removeSignature($signed_val);
631    // If the signed value matches the original signed value we consider the value safe.
632    if ($signed_val == addSignature($val, $seed_key)) {
633        // Signature verified.
634        return true;
635    } else {
636        return false;
637    }
638}
639
640/**
641 * Sends empty output to the browser and flushes the php buffer so the client
642 * will see data before the page is finished processing.
643 */
644function flushBuffer() {
645    echo str_repeat('          ', 205);
646    flush();
647}
648
649/**
650 * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
651 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
652 *
653 * @access  public
654 * @param   string  $email     Email address to add.
655 * @param   string  $list      Name of list to add to.
656 * @param   bool    $send_welcome_message   True to send welcome message to subscriber.
657 * @return  bool    True on success, false on failure.
658 */
659function mailmanAddMember($email, $list, $send_welcome_message=false)
660{
661   $add_members = '/var/mailman/bin/add_members';
662    if (is_executable($add_members) && is_readable($add_members)) {
663        $welcome_msg = $send_welcome_message ? 'y' : 'n';
664        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);
665        if (0 == $return_code) {
666            App::logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
667            return true;
668        } else {
669            App::logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
670            return false;
671        }
672    } else {
673        App::logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
674        return false;
675    }
676}
677
678/**
679 * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
680 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
681 *
682 * @access  public
683 * @param   string  $email     Email address to add.
684 * @param   string  $list      Name of list to add to.
685 * @param   bool    $send_user_ack   True to send goodbye message to subscriber.
686 * @return  bool    True on success, false on failure.
687 */
688function mailmanRemoveMember($email, $list, $send_user_ack=false)
689{
690    $remove_members = '/var/mailman/bin/remove_members';
691    if (is_executable($remove_members) && is_readable($remove_members)) {
692        $userack = $send_user_ack ? '' : '--nouserack';
693        exec(sprintf('/usr/bin/sudo %s %s --noadminack %s %s', escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
694        if (0 == $return_code) {
695            App::logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
696            return true;
697        } else {
698            App::logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
699            return false;
700        }
701    } else {
702        App::logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
703        return false;
704    }
705}
706
707/**
708 * If the given $url is on the same web site, return true. This can be used to
709 * prevent from sending sensitive info in a get query (like the SID) to another
710 * domain.
711 *
712 * @param  string $url    the URI to test.
713 * @return bool True if given $url is this domain or has no domain (is a relative url), false if it's another.
714 */
715function isMyDomain($url)
716{
717    static $urls = array();
718
719    if (!isset($urls[$url])) {
720        if (!preg_match('|\w{1,}\.\w{2,5}/|', $url)) {
721            // If we can't find a domain we assume the URL is relative.
722            $urls[$url] = true;
723        } else {
724            $urls[$url] = preg_match('/' . preg_quote(getenv('HTTP_HOST')) . '/', $url);
725        }
726    }
727    return $urls[$url];
728}
729
730/**
731 * Takes a URL and returns it without the query or anchor portion
732 *
733 * @param  string $url   any kind of URI
734 * @return string        the URI with ? or # and everything after removed
735 */
736function stripQuery($url)
737{
738    return preg_replace('![?#].*!', '', $url);
739}
740
741/**
742 * Returns the remote IP address, taking into consideration proxy servers.
743 *
744 * @param  bool $dolookup   If true we resolve to IP to a host name,
745 *                          if false we don't.
746 * @return string    IP address if $dolookup is false or no arg
747 *                   Hostname if $dolookup is true
748 */
749function getRemoteAddr($dolookup=false)
750{
751    $ip = getenv('HTTP_CLIENT_IP');
752    if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') {
753        $ip = getenv('HTTP_X_FORWARDED_FOR');
754        if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') {
755            $ip = getenv('REMOTE_ADDR');
756        }
757    }
758    return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip;
759}
760
761/**
762 * Tests whether a given IP address can be found in an array of IP address networks.
763 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
764 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
765 *
766 * @access  public
767 * @param   string  IP address to search for.
768 * @param   array   Array of networks to search within.
769 * @return  mixed   Returns the network that matched on success, false on failure.
770 */
771function ipInRange($ip, $networks)
772{
773    if (!is_array($networks)) {
774        $networks = array($networks);
775    }
776
777    $ip_binary = sprintf('%032b', ip2long($ip));
778    foreach ($networks as $network) {
779        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) {
780            // IP is in CIDR notation.
781            list($cidr_ip, $cidr_bitmask) = split('/', $network);
782            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
783            if (substr($ip_binary, 0, $cidr_bitmask) === substr($cidr_ip_binary, 0, $cidr_bitmask)) {
784               // IP address is within the specified IP range.
785               return $network;
786            }
787        } else {
788            if ($ip === $network) {
789               // IP address exactly matches.
790               return $network;
791            }
792        }
793    }
794
795    return false;
796}
797
798/**
799 * Returns a fully qualified URL to the current script, including the query.
800 *
801 * @return string    a full url to the current script
802 */
803function absoluteMe()
804{
805    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
806    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
807}
808
809/**
810 * Compares the current url with the referring url.
811 *
812 * @param  string  $compary_query  Include the query string in the comparison.
813 * @return bool    true if the current script (or specified valid_referer)
814 *                 is the referrer. false otherwise.
815 */
816function refererIsMe($exclude_query=false)
817{
818    if ($exclude_query) {
819        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
820    } else {
821        return (absoluteMe() == getenv('HTTP_REFERER'));
822    }
823}
824
825/**
826 * Stub functions used when installation does not have
827 * GNU gettext extension installed
828 */
829if (!extension_loaded('gettext')) {
830    /**
831    * Translates text
832    *
833    * @access public
834    * @param string $text the text to be translated
835    * @return string translated text
836    */
837    function gettext($text) {
838        return $text;
839    }
840
841    /**
842    * Translates text
843    *
844    * @access public
845    * @param string $text the text to be translated
846    * @return string translated text
847    */
848    function _($text) {
849        return $text;
850    }
851
852    /**
853    * Translates text by domain
854    *
855    * @access public
856    * @param string $domain the language to translate the text into
857    * @param string $text the text to be translated
858    * @return string translated text
859    */
860    function dgettext($domain, $text) {
861        return $text;
862    }
863
864    /**
865    * Translates text by domain and category
866    *
867    * @access public
868    * @param string $domain the language to translate the text into
869    * @param string $text the text to be translated
870    * @param string $category the language dialect to use
871    * @return string translated text
872    */
873    function dcgettext($domain, $text, $category) {
874        return $text;
875    }
876
877    /**
878    * Binds the text domain
879    *
880    * @access public
881    * @param string $domain the language to translate the text into
882    * @param string
883    * @return string translated text
884    */
885    function bindtextdomain($domain, $directory) {
886        return $domain;
887    }
888
889    /**
890    * Sets the text domain
891    *
892    * @access public
893    * @param string $domain the language to translate the text into
894    * @return string translated text
895    */
896    function textdomain($domain) {
897        return $domain;
898    }
899}
900
901
902
903?>
Note: See TracBrowser for help on using the repository browser.