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

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

${1}

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