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

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

Tons of little updates and bugfixes. CSS updates to templates and core css files. File upload ability to module_maker. Remade Upload interface to use setParam/getParam.

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