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

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