source: tags/1.0.0/lib/App.inc.php @ 1

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

Initial import.

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