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

Last change on this file since 1 was 1, checked in by scdev, 19 years ago

Initial import.

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