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

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

minor improvements

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