source: branches/1.1dev/lib/App.inc.php @ 109

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

axis-out checkin

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