source: branches/1.0.1/lib/App.inc.php @ 73

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

using priorityToString with old codebase!

File size: 28.5 KB
Line 
1<?php
2/**
3 * App.inc.php
4 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
5 */
6
7/******************************************************************************
8 * CONFIG
9 ******************************************************************************
10 
11 This library has some functions that require globally defined values.
12 These are defined here.
13 */
14
15//  Message Types
16/** @constant MSG_NOTICE
17    An informational message: Welcome to asdf, Logout successful, etc. */
18define('MSG_NOTICE', 0);
19
20/** @constant MSG_SUCCESS
21    A success message: Message sent, You are logged-in, etc. */
22define('MSG_SUCCESS', 1);
23
24/** @constant MSG_WARNING
25    A warning message: Access denied, Email address invalid, Article not found, etc. */
26define('MSG_WARNING', 2);
27
28/** @constant MSG_ERR
29    Unrecoverable failure: Message could not be sent, File not found, etc. */
30define('MSG_ERR', 4); // PHP user error style.
31define('MSG_ERROR', 4);
32
33
34
35/******************************************************************************
36 * FUNCTIONS
37 ******************************************************************************
38
39/**
40 * Add a message to the string globalmessage, which is printed in the header.
41 * Just a simple way to print messages to the user.
42 *
43 * @access public
44 *
45 * @param string $message The text description of the message.
46 * @param int    $type    The type of message: MSG_NOTICE,
47 *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
48 * @param string $file    __FILE__.
49 * @param string $line    __LINE__.
50 */
51function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
52{
53    $_SESSION['_messages'][] = array(
54        'type'    => $type, 
55        'message' => $message,
56        'file'    => $file,
57        'line'    => $line
58    );
59   
60    switch ($type) {
61        case MSG_NOTICE :
62            break;
63        case MSG_SUCCESS :
64            break;
65        case MSG_WARNING :
66            break;
67        case MSG_ERROR :
68        case MSG_ERR :
69        default :
70            break;
71    }
72}
73
74/**
75 * Logs a message to a user defined log file. Additional actions to take for
76 * different types of message types can be specified (ERROR, NOTICE, etc).
77 *
78 * @access public
79 *
80 * @param string $message   The text description of the message.
81 * @param int    $priority  The type of message priority (in descending order):
82 *                          LOG_EMERG     system is unusable
83 *                          LOG_ALERT     action must be taken immediately
84 *                          LOG_CRIT      critical conditions
85 *                          LOG_ERR       error conditions
86 *                          LOG_WARNING   warning conditions
87 *                          LOG_NOTICE    normal, but significant, condition
88 *                          LOG_INFO      informational message
89 *                          LOG_DEBUG     debug-level message
90 * @param string $file      The file where the log event occurs.
91 * @param string $line      The line of the file where the log event occurs.
92 */
93function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
94{
95    global $CFG;
96
97    // If priority is not specified, assume the worst.
98    if (!priorityToString($priority)) {
99        logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
100        $priority = LOG_EMERG;
101    }
102
103    // If log file is not specified, create one in the codebase root.
104    if (!is_dir($CFG->log_directory) || !is_writable($CFG->log_directory)) {
105        // We must use trigger_error rather than calling logMsg, which might lead to an infinite loop.
106        trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $CFG->log_directory), E_USER_ERROR);
107    }
108   
109    // Data to be stored for a log event.
110    $event = array(
111        'date'      => date('Y-m-d H:i:s'),
112        'remote ip' => getRemoteAddr(),
113        'pid'       => (substr(PHP_OS, 0, 3) != 'WIN' ? posix_getpid() : ''),
114        'type'      => priorityToString($priority),
115        'file:line' => "$file : $line",
116        'url'       => (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''),
117        'message'   => $message
118    );
119
120    $event_str = strip_tags('[' . preg_replace('/\s{2,}/', ' ', join('] [', $event)) . ']');
121   
122    // FILE ACTION
123    if ($priority <= $CFG->log_file_priority && $CFG->log_file_priority) {
124        error_log($event_str . "\n", 3, $CFG->log_directory . '/' . $CFG->log_filename);
125    }
126
127    // EMAIL ACTION
128    if ($priority <= $CFG->log_email_priority && $CFG->log_email_priority) {
129        if (empty($CFG->log_to_email)) {
130            $CFG->log_to_email = 'bug@strangecode.com';
131        }
132        $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message);
133        $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST'));
134        $headers = "From: codebase@strangecode.com\r\n";
135        foreach ($event as $k=>$v) {
136            $email_msg .= sprintf("%-11s%s\n", $k, $v);
137        }
138        mail($CFG->log_to_email, $subject, $email_msg, $headers, '-f codebase@strangecode.com');
139    }
140   
141    // SMS ACTION
142    if ($priority <= $CFG->log_sms_priority && $CFG->log_sms_priority) {
143        if (empty($CFG->log_to_email)) {
144            $CFG->log_to_sms = 'bug@strangecode.com';
145        }
146        $subject = '[' . getenv('HTTP_HOST') . ' log event]';
147        $headers = "From: codebase@strangecode.com\r\n";
148        mail($CFG->log_to_sms, $subject, $event_str, $headers, '-f codebase@strangecode.com');
149    }
150
151    // SCREEN ACTION
152    if ($priority <= $CFG->log_screen_priority && $CFG->log_screen_priority) {
153        echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
154    }
155}
156
157/**
158 * Returns the string representation of a LOG_* integer constant.
159 *
160 * @param int  $priority  The LOG_* integer constant.
161 *
162 * @return                The string representation of $priority.
163 */
164function priorityToString ($priority) {
165    $priorities = array(
166        LOG_EMERG   => 'emergency',
167        LOG_ALERT   => 'alert',
168        LOG_CRIT    => 'critical',
169        LOG_ERR     => 'error',
170        LOG_WARNING => 'warning',
171        LOG_NOTICE  => 'notice',
172        LOG_INFO    => 'info',
173        LOG_DEBUG   => 'debug'
174    );
175    if (isset($priorities[$priority])) {
176        return $priorities[$priority];
177    } else {
178        return false;
179    }
180}
181
182/**
183 * Set the URL to return to when dieBoomerangURL() is called.
184 *
185 * @param string  $url  A fully validated URL.
186 * @param bool  $id     An identification tag for this url.
187 * FIXME: url garbage collection?
188 */
189function setBoomerangURL($url=null, $id=null)
190{
191    // A redirection will never happen immediatly after setting the boomerangURL.
192    // Set the time so ensure this doesn't happen. See validBoomerangURL for more.
193
194    if (isset($url) && is_string($url)) {
195        // Delete any boomerang request keys in the query string.
196        $url = preg_replace('/boomerang=[\w]+/', '', $url);
197       
198        if (is_array($_SESSION['_boomerang']['url']) && !empty($_SESSION['_boomerang']['url'])) {
199            // If the URL currently exists in the boomerang array, delete.
200            while ($existing_key = array_search($url, $_SESSION['_boomerang']['url'])) {
201                unset($_SESSION['_boomerang']['url'][$existing_key]);
202            }
203        }
204       
205        if (isset($id)) {
206            $_SESSION['_boomerang']['url'][$id] = $url;
207        } else {
208            $_SESSION['_boomerang']['url'][] = $url;
209        }
210        logMsg(sprintf('setBoomerangURL added URL %s to session %s=%s', $url, session_name(), session_id()), LOG_DEBUG, __FILE__, __LINE__);
211        return true;
212    } else {
213        return false;
214    }
215}
216
217/**
218 * Return the URL set for the specified $id.
219 *
220 * @param string  $id     An identification tag for this url.
221 */
222function getBoomerangURL($id=null)
223{
224    if (isset($id)) {
225        if (isset($_SESSION['_boomerang']['url'][$id])) {
226            return $_SESSION['_boomerang']['url'][$id];
227        } else {
228            return '';
229        }
230    } else if (is_array($_SESSION['_boomerang']['url'])) {
231        return end($_SESSION['_boomerang']['url']);
232    } else {
233        return false;
234    }
235}
236
237/**
238 * Delete the URL set for the specified $id.
239 *
240 * @param string  $id     An identification tag for this url.
241 */
242function deleteBoomerangURL($id=null)
243{
244    if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) {
245        unset($_SESSION['_boomerang']['url'][$id]);
246    } else if (is_array($_SESSION['_boomerang']['url'])) {
247        array_pop($_SESSION['_boomerang']['url']);
248    }
249}
250
251/**
252 * Check if a valid boomerang URL value has been set.
253 * if it is not the current url, and has not been accessed within n seconds.
254 *
255 * @return bool  True if it is set and not the current URL.
256 */
257function validBoomerangURL($id=null, $use_nonspecific_boomerang=false)
258{
259    if (!isset($_SESSION['_boomerang']['url'])) {
260        logMsg(sprintf('validBoomerangURL no URL set in session %s=%s %s', session_name(), session_id(), getDump($_SESSION)), LOG_DEBUG, __FILE__, __LINE__);
261        return false;
262    }
263
264    // Time is the timestamp of a boomerangURL redirection, or setting of a boomerangURL.
265    // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
266    // or a boomerang being set.
267    $boomerang_time = isset($_SESSION['_boomerang']['time']) ? $_SESSION['_boomerang']['time'] : 0;
268   
269    if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) {
270        $url = $_SESSION['_boomerang']['url'][$id];
271    } else if (!isset($id) || $use_nonspecific_boomerang) {
272        // Use non specific boomerang if available.
273        $url = end($_SESSION['_boomerang']['url']);
274    }
275
276    logMsg(sprintf('validBoomerangURL testing url: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
277    if (empty($url)) {
278        return false;
279    }
280    if ($url == absoluteMe()) {
281        // The URL we are directing to is not the current page.
282        logMsg(sprintf('Boomerang URL not valid, same as absoluteMe: %s', $url), LOG_WARNING, __FILE__, __LINE__);
283        return false;
284    }
285    if ($boomerang_time >= (time() - 2)) {
286        // Last boomerang direction was more than 2 seconds ago.
287        logMsg(sprintf('Boomerang URL not valid, boomerang_time too short: %s', time() - $boomerang_time), LOG_WARNING, __FILE__, __LINE__);
288        return false;
289    }
290   
291    return true;
292}
293
294/**
295 * Redirects a user by calling the dieURL(). It will use:
296 * 1. the stored boomerang URL, it it exists
297 * 2. the referring URL, it it exists.
298 * 3. an empty string, which will force dieURL to use the default URL.
299 */
300function dieBoomerangURL($id=null, $carry_args=null)
301{
302    // Get URL from stored boomerang. Allow non specific URL if ID not valid.
303    if (validBoomerangURL($id, true)) {
304        if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) {
305            $url = $_SESSION['_boomerang']['url'][$id];
306        } else {
307            $url = end($_SESSION['_boomerang']['url']);
308        }
309    } else if (!refererIsMe() && !preg_match('/admin_common/', getenv('SCRIPT_NAME'))) {
310        // Ensure that the redirecting page is not also the referrer.
311        // admin_common is an alias of 'admin', which confuses this function. Just here for local testing.
312        $url = getenv('HTTP_REFERER');
313    } else {
314        $url = '';
315    }
316
317    logMsg(sprintf('dieBoomerangURL found URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
318
319    // Delete stored boomerang.
320    deleteBoomerangURL($id);
321       
322    // A redirection will never happen immediatly twice.
323    // Set the time so ensure this doesn't happen.
324    $_SESSION['_boomerang']['time'] = time();
325    dieURL($url, $carry_args);
326}
327
328/**
329 * Uses an http header to redirect the client to the given $url. If sessions are not used
330 * and the session is not already defined in the given $url, the SID is appended as a URI query.
331 * As with all header generating functions, make sure this is called before any other output.
332 *
333 * @param   string  $url                    The URL the client will be redirected to.
334 * @param   mixed   $carry_args             Additional url arguments to carry in the query,
335 *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
336 *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
337 *                                          -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
338 *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
339 * @param   bool    $always_include_sid     Force session id to be added to Location header.
340 */
341function dieURL($url, $carry_args=null, $always_include_sid=false)
342{ 
343    global $CFG;
344
345    if ('' == $url) {
346        // If URL is not specified, use the redirect_home.
347        $url = $CFG->redirect_home;
348    }
349
350    if (preg_match('!^/!', $url)) {
351        // If relative URL is given, prepend correct local hostname.
352        $hostname = ('on' == getenv('HTTPS')) ? 'https://' . getenv('HTTP_HOST') : 'http://' . getenv('HTTP_HOST');
353        $url = $hostname . $url;
354    }
355
356    $url = url($url, $carry_args, $always_include_sid);
357   
358    header(sprintf('Location: %s', $url));
359    logMsg(sprintf('dieURL dying to URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
360    die;
361}
362
363/**
364 * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
365 * as hidden form elements for GET_VARS that might be in use.
366 *
367 * @global string $carry_queries     An array of keys to define which values to
368 *                                   carry through from the POST or GET.
369 *                                   $carry_queries = array('qry'); for example
370 *
371 * @param  mixed  $carry_args        Additional url arguments to carry in the query,
372 *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
373 *                                   -array('key1', key2', key3')  <-- to save these keys if in the form data.
374 *                                   -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
375 *                                   -false  <-- To not carry any queries. If URL already has queries those will be retained.
376 */
377function printHiddenSession($carry_args=null)
378{
379    static $_using_trans_sid;
380    global $carry_queries;
381
382    // Save the trans_sid setting.
383    if (!isset($_using_trans_sid)) {
384        $_using_trans_sid = ini_get('session.use_trans_sid');
385    }
386   
387    // Initialize the carried queries.
388    if (!isset($carry_queries['_carry_queries_init'])) {
389        if (!is_array($carry_queries)) {
390            $carry_queries = array($carry_queries);
391        }
392        $tmp = $carry_queries;
393        $carry_queries = array();
394        foreach ($tmp as $key) {
395            if (!empty($key) && getFormData($key, false)) {
396                $carry_queries[$key] = getFormData($key);
397            }
398        }
399        $carry_queries['_carry_queries_init'] = true;
400    }
401
402    // Get any additional query names to add to the $carry_queries array
403    // that are found as function arguments.
404    // If FALSE is a function argument, DO NOT carry the queries.
405    $do_carry_queries = true;
406    if (!is_null($carry_args)) {
407        if (is_array($carry_args) && !empty($carry_args)) {
408            foreach ($carry_args as $key=>$arg) {
409                // Get query from appropriate source.
410                if (false === $arg) {
411                    $do_carry_queries = false;
412                } else if (false !== getFormData($arg, false)) {
413                    $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
414                } else if (!is_numeric($key) && '' != $arg) {
415                    $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
416                }
417            }
418        } else if (false !== getFormData($carry_args, false)) {
419            $one_time_carry_queries[$carry_args] = getFormData($carry_args);
420        } else if (false === $carry_args) {
421            $do_carry_queries = false;
422        }
423    }
424   
425    // For each existing POST value, we create a hidden input to carry it through a form.
426    if ($do_carry_queries) {
427        // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args.
428        $query_args = array_diff_assoc(urlEncodeArray(array_merge($carry_queries, $one_time_carry_queries)), array('_carry_queries_init' => true));
429        foreach ($query_args as $key=>$val) {
430            echo '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
431        }
432    }
433   
434    // Include the SID if cookies are disabled.
435    if (!isset($_COOKIE[session_name()]) && !$_using_trans_sid) {
436        echo '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
437    }
438}
439
440/**
441 * Outputs a fully qualified URL with a query of all the used (ie: not empty)
442 * keys and values, including optional queries. This allows simple printing of
443 * links without needing to know which queries to add to it. If cookies are not
444 * used, the session id will be propogated in the URL.
445 *
446 * @global string $carry_queries       An array of keys to define which values to
447 *                                     carry through from the POST or GET.
448 *                                     $carry_queries = array('qry'); for example.
449 *
450 * @param  string $url                 The initial url
451 * @param  mixed  $carry_args          Additional url arguments to carry in the query,
452 *                                     or FALSE to prevent carrying queries. Can be any of the following formats:
453 *                                     -array('key1', key2', key3')  <-- to save these keys if in the form data.
454 *                                     -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
455 *                                     -false  <-- To not carry any queries. If URL already has queries those will be retained.
456 *
457 * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
458 *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
459 *                                     header('Location...') redirections.
460 *
461 * @return string url with attached queries and, if not using cookies, the session id
462 */
463function url($url='', $carry_args=null, $always_include_sid=false)
464{
465    static $_using_trans_sid;
466    global $carry_queries;
467    global $CFG;
468
469    // Save the trans_sid setting.
470    if (!isset($_using_trans_sid)) {
471        $_using_trans_sid = ini_get('session.use_trans_sid');
472    }
473
474    // Initialize the carried queries.
475    if (!isset($carry_queries['_carry_queries_init'])) {
476        if (!is_array($carry_queries)) {
477            $carry_queries = array($carry_queries);
478        }
479        $tmp = $carry_queries;
480        $carry_queries = array();
481        foreach ($tmp as $key) {
482            if (!empty($key) && getFormData($key, false)) {
483                $carry_queries[$key] = getFormData($key);
484            }
485        }
486        $carry_queries['_carry_queries_init'] = true;
487    }
488
489    // Get any additional query arguments to add to the $carry_queries array.
490    // If FALSE is a function argument, DO NOT carry the queries.
491    $do_carry_queries = true;
492    if (!is_null($carry_args)) {
493        if (is_array($carry_args) && !empty($carry_args)) {
494            foreach ($carry_args as $key=>$arg) {
495                // Get query from appropriate source.
496                if (false === $arg) {
497                    $do_carry_queries = false;
498                } else if (false !== getFormData($arg, false)) {
499                    $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
500                } else if (!is_numeric($key) && '' != $arg) {
501                    $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
502                }
503            }
504        } else if (false !== getFormData($carry_args, false)) {
505            $one_time_carry_queries[$carry_args] = getFormData($carry_args);
506        } else if (false === $carry_args) {
507            $do_carry_queries = false;
508        }
509    }
510
511    // Get the first delimiter that is needed in the url.
512    $delim = preg_match('/\?/', $url) ? ini_get('arg_separator.output') : '?';
513
514    $q = '';
515    if ($do_carry_queries) {
516        // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args.
517        $query_args = array_diff_assoc(urlEncodeArray(array_merge($carry_queries, $one_time_carry_queries)), array('_carry_queries_init' => true));
518        foreach ($query_args as $key=>$val) {
519            // Check value is set and value does not already exist in the url.
520            if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
521                $q .= $delim . $key . '=' . $val;
522                $delim = ini_get('arg_separator.output');
523            }
524        }
525    }
526
527    // Include the necessary SID if the following is true:
528    // - no cookie in http request OR cookies disabled in config
529    // - sessions are enabled
530    // - the link stays on our site
531    // - transparent SID propogation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
532    // OR
533    // - we must include the SID because we say so (it's used in a context where cookies will not be effective, ie. moving from http to https)
534    // AND
535    // - the SID is not already in the query.
536    if (
537        (
538            (
539                (
540                    !isset($_COOKIE[session_name()]) 
541                    || !$CFG->session_use_cookies
542                ) 
543                && $CFG->enable_session
544                && isMyDomain($url) 
545                && 
546                (
547                    !$_using_trans_sid
548                    || preg_match('!^(http|https)://!i', $url)
549                )
550            ) 
551            || $always_include_sid
552        )
553        && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
554    ) {
555        $url .= $q . $delim . session_name() . '=' . session_id();
556//         logMsg(sprintf('oHREF appending session id to URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
557    } else {
558        $url .= $q;
559    }
560
561    return $url;
562}
563
564/**
565 * Returns a URL processed with App::url and htmlentities for printing in html.
566 *
567 * @access  public
568 * @param   string  $url    Input URL to parse.
569 * @return  string          URL with App::url() and htmlentities() applied.
570 * @author  Quinn Comendant <quinn@strangecode.com>
571 * @since   09 Dec 2005 17:58:45
572 */
573function oHREF($url, $carry_args=null, $always_include_sid=false)
574{
575    $url = url($url, $carry_args, $always_include_sid);
576    // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
577    $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
578    return $url;
579}
580
581/**
582 * Force the user to connect via https (port 443) by redirecting them to
583 * the same page but with https.
584 */
585function sslOn()
586{
587    global $CFG;
588
589    if (function_exists('apache_get_modules')) {
590        $modules = apache_get_modules();
591    } else {
592        // It's safe to assume we have mod_ssl if we can't determine otherwise.
593        $modules = array('mod_ssl');
594    }
595   
596    if ('on' != getenv('HTTPS') && $CFG->ssl_enabled && in_array('mod_ssl', $modules)) {
597        raiseMsg(sprintf(_("Secure SSL connection made to %s"), $CFG->ssl_domain), MSG_NOTICE, __FILE__, __LINE__);
598        // Always append session because some browsers do not send cookie when crossing to SSL URL.
599        dieURL('https://' . $CFG->ssl_domain . getenv('REQUEST_URI'), null, true);
600    }
601}
602   
603
604/**
605 * to enforce the user to connect via http (port 80) by redirecting them to
606 * a http version of the current url.
607 */
608function sslOff()
609{
610    if ('on' == getenv('HTTPS')) {
611        dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
612    }
613}
614
615/**
616 * If the given $url is on the same web site, return true. This can be used to
617 * prevent from sending sensitive info in a get query (like the SID) to another
618 * domain. $method can be "ip" or "domain". The domain method might be preferred
619 * if your domain spans mutiple IP's (load sharing servers)
620 *
621 * @param  string $url    the URI to test.
622 * @param  mixed $method  the method to use. Either 'domain' or 'ip'.
623 *
624 * @return bool    true if given $url is this domain or has no domain (is a
625 *                 relative url), false if it's another
626 */
627function isMyDomain($url)
628{   
629    if (!preg_match('|\w{1,}\.\w{2,5}/|', $url)) {
630        // If we can't find a domain we assume the URL is relative.
631        return true;
632    } else {
633        return preg_match('/' . preg_quote(getenv('HTTP_HOST')) . '/', $url);
634    }
635}
636
637/**
638 * Loads a list of tables in the current database into an array, and returns
639 * true if the requested table is found. Use this function to enable/disable
640 * funtionality based upon the current available db tables.
641 *
642 * @param  string $table    The name of the table to search.
643 *
644 * @return bool    true if given $table exists.
645 */
646function dbTableExists($table)
647{   
648    static $existing_tables;
649   
650    // Save the trans_sid setting.
651    if (!isset($existing_tables)) {
652        // Get DB tables.
653        $existing_tables = array();
654        $qid = dbQuery("SHOW TABLES");
655        while (list($row) = mysql_fetch_row($qid)) {
656            $existing_tables[] = $row;
657        }
658    }
659       
660    // Test if requested table is in database.
661    return in_array($table, $existing_tables);
662}
663
664/**
665 * Takes a URL and returns it without the query or anchor portion
666 *
667 * @param  string $url   any kind of URI
668 *
669 * @return string        the URI with ? or # and everything after removed
670 */
671function stripQuery($url)
672{
673    return preg_replace('![?#].*!', '', $url);
674}
675
676/**
677 * Returns the remote IP address, taking into consideration proxy servers.
678 *
679 * @param  bool $dolookup   If true we resolve to IP to a host name,
680 *                          if false we don't.
681 *
682 * @return string    IP address if $dolookup is false or no arg
683 *                   Hostname if $dolookup is true
684 */
685function getRemoteAddr($dolookup=false)
686{
687    $ip = getenv('HTTP_CLIENT_IP');
688    if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') {
689        $ip = getenv('HTTP_X_FORWARDED_FOR');
690        if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') {
691            $ip = getenv('REMOTE_ADDR');
692        }
693    }
694    return $dolookup ? gethostbyaddr($ip) : $ip;
695}
696
697/**
698 * Tests whether a given iP address can be found in an array of IP address networks.
699 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
700 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
701 *
702 * @access  public
703 *
704 * @param   string  IP address to search for.
705 * @param   array   Array of networks to search within.
706 *
707 * @return  mixed   Returns the network that matched on success, false on failure.
708 */
709function ipInRange($my_ip, $ip_pool)
710{
711    if (!is_array($ip_pool)) {
712        $ip_pool = array($ip_pool);
713    }
714   
715    $my_ip_binary = sprintf('%032b', ip2long($my_ip));
716    foreach ($ip_pool as $ip) {
717        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $ip)) {
718            // IP is in CIDR notation.
719            list($cidr_ip, $cidr_bitmask) = split('/', $ip);
720            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
721            if (substr($my_ip_binary, 0, $cidr_bitmask) === substr($cidr_ip_binary, 0, $cidr_bitmask)) {
722               // IP address is within the specified IP range.
723               return $ip;
724            }
725        } else {
726            if ($my_ip === $ip) {
727               // IP address exactly matches.
728               return $ip;
729            }
730        }
731    }
732   
733    return false;
734}
735
736/**
737 * Returns a fully qualified URL to the current script, including the query.
738 *
739 * @return string    a full url to the current script
740 */
741function absoluteMe()
742{
743    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
744    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
745}
746
747/**
748 * Compares the current url with the referring url.
749 *
750 * @param  string  $compary_query  Include the query string in the comparison.
751 *
752 * @return bool    true if the current script (or specified valid_referer)
753 *                 is the referrer. false otherwise.
754 */
755function refererIsMe($exclude_query=false)
756{
757    if ($exclude_query) {
758        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
759    } else {
760        return (absoluteMe() == getenv('HTTP_REFERER'));
761    }
762}
763
764?>
Note: See TracBrowser for help on using the repository browser.