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

Last change on this file since 689 was 689, checked in by anonymous, 5 years ago

Use mb_send_mail

File size: 30.7 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 immediatly 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    }
300
301    logMsg(sprintf('validBoomerangURL testing url: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
302    if (empty($url)) {
303        return false;
304    }
305    if ($url == absoluteMe()) {
306        // The URL we are directing to is not the current page.
307        logMsg(sprintf('Boomerang URL not valid, same as absoluteMe: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
308        return false;
309    }
310    if ($boomerang_time >= (time() - 2)) {
311        // Last boomerang direction was more than 2 seconds ago.
312        logMsg(sprintf('Boomerang URL not valid, boomerang_time too short: %s', time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
313        return false;
314    }
315
316    return true;
317}
318
319/*
320* Redirects a user by calling App::dieURL(). It will use:
321* 1. the stored boomerang URL, it it exists
322* 2. a specified $default_url, it it exists
323* 3. the referring URL, it it exists.
324* 4. redirect_home_url configuration variable.
325*
326* @access   public
327* @param    string  $id             Identifier for this script.
328* @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see App::oHREF()).
329* @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
330* @return   bool                    False if the session is not running. No return otherwise.
331* @author   Quinn Comendant <quinn@strangecode.com>
332* @since    31 Mar 2006 19:17:00
333*/
334function dieBoomerangURL($id=null, $carry_args=null, $default_url=null)
335{
336    // Get URL from stored boomerang. Allow non specific URL if ID not valid.
337    if (validBoomerangURL($id, true)) {
338        if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) {
339            $url = $_SESSION['_boomerang']['url'][$id];
340        } else {
341            $url = end($_SESSION['_boomerang']['url']);
342        }
343    } else if (isset($default_url)) {
344        $url = $default_url;
345    } else if (!refererIsMe()) {
346        // Ensure that the redirecting page is not also the referrer.
347        $url = getenv('HTTP_REFERER');
348    } else {
349        $url = '';
350    }
351
352    logMsg(sprintf('dieBoomerangURL found URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
353
354    // Delete stored boomerang.
355    deleteBoomerangURL($id);
356
357    // A redirection will never happen immediately twice.
358    // Set the time so ensure this doesn't happen.
359    $_SESSION['_boomerang']['time'] = time();
360    dieURL($url, $carry_args);
361}
362
363/**
364 * Uses an http header to redirect the client to the given $url. If sessions are not used
365 * and the session is not already defined in the given $url, the SID is appended as a URI query.
366 * As with all header generating functions, make sure this is called before any other output.
367 *
368 * @param   string  $url                    The URL the client will be redirected to.
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 * @param   bool    $always_include_sid     Force session id to be added to Location header.
375 */
376function dieURL($url, $carry_args=null, $always_include_sid=false)
377{
378    global $CFG;
379
380    if ('' == $url) {
381        // If URL is not specified, use the redirect_home.
382        $url = $CFG->redirect_home;
383    }
384
385    if (preg_match('!^/!', $url)) {
386        // If relative URL is given, prepend correct local hostname.
387        $hostname = ('on' == getenv('HTTPS')) ? 'https://' . getenv('HTTP_HOST') : 'http://' . getenv('HTTP_HOST');
388        $url = $hostname . $url;
389    }
390
391    $url = url($url, $carry_args, $always_include_sid);
392
393    header(sprintf('Location: %s', $url));
394    logMsg(sprintf('dieURL dying to URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
395    die;
396}
397
398/**
399 * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
400 * as hidden form elements for GET_VARS that might be in use.
401 *
402 * @global string $carry_queries     An array of keys to define which values to
403 *                                   carry through from the POST or GET.
404 *                                   $carry_queries = array('qry'); for example
405 *
406 * @param  mixed  $carry_args        Additional url arguments to carry in the query,
407 *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
408 *                                   -array('key1', key2', key3')  <-- to save these keys if in the form data.
409 *                                   -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
410 *                                   -false  <-- To not carry any queries. If URL already has queries those will be retained.
411 */
412function printHiddenSession($carry_args=null)
413{
414    static $_using_trans_sid;
415    global $carry_queries;
416
417    // Save the trans_sid setting.
418    if (!isset($_using_trans_sid)) {
419        $_using_trans_sid = ini_get('session.use_trans_sid');
420    }
421
422    // Initialize the carried queries.
423    if (!isset($carry_queries['_carry_queries_init'])) {
424        if (!is_array($carry_queries)) {
425            $carry_queries = array($carry_queries);
426        }
427        $tmp = $carry_queries;
428        $carry_queries = array();
429        foreach ($tmp as $key) {
430            if (!empty($key) && getFormData($key, false)) {
431                $carry_queries[$key] = getFormData($key);
432            }
433        }
434        $carry_queries['_carry_queries_init'] = true;
435    }
436
437    // Get any additional query names to add to the $carry_queries array
438    // that are found as function arguments.
439    // If FALSE is a function argument, DO NOT carry the queries.
440    $do_carry_queries = true;
441    $one_time_carry_queries = array();
442    if (!is_null($carry_args)) {
443        if (is_array($carry_args) && !empty($carry_args)) {
444            foreach ($carry_args as $key=>$arg) {
445                // Get query from appropriate source.
446                if (false === $arg) {
447                    $do_carry_queries = false;
448                } else if (false !== getFormData($arg, false)) {
449                    $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
450                } else if (!is_numeric($key) && '' != $arg) {
451                    $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
452                }
453            }
454        } else if (false !== getFormData($carry_args, false)) {
455            $one_time_carry_queries[$carry_args] = getFormData($carry_args);
456        } else if (false === $carry_args) {
457            $do_carry_queries = false;
458        }
459    }
460
461    // For each existing POST value, we create a hidden input to carry it through a form.
462    if ($do_carry_queries) {
463        // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args.
464        $query_args = array_diff_assoc(array_merge($carry_queries, $one_time_carry_queries), array('_carry_queries_init' => true));
465        foreach ($query_args as $key=>$val) {
466            echo '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
467        }
468    }
469
470    // Include the SID if cookies are disabled.
471    if (!isset($_COOKIE[session_name()]) && !$_using_trans_sid) {
472        echo '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
473    }
474}
475
476/**
477 * Outputs a fully qualified URL with a query of all the used (ie: not empty)
478 * keys and values, including optional queries. This allows simple printing of
479 * links without needing to know which queries to add to it. If cookies are not
480 * used, the session id will be propogated in the URL.
481 *
482 * @global string $carry_queries       An array of keys to define which values to
483 *                                     carry through from the POST or GET.
484 *                                     $carry_queries = array('qry'); for example.
485 *
486 * @param  string $url                 The initial url
487 * @param  mixed  $carry_args          Additional url arguments to carry in the query,
488 *                                     or FALSE to prevent carrying queries. Can be any of the following formats:
489 *                                     -array('key1', key2', key3')  <-- to save these keys if in the form data.
490 *                                     -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
491 *                                     -false  <-- To not carry any queries. If URL already has queries those will be retained.
492 *
493 * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
494 *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
495 *                                     header('Location...') redirections.
496 *
497 * @return string url with attached queries and, if not using cookies, the session id
498 */
499function url($url='', $carry_args=null, $always_include_sid=false)
500{
501    static $_using_trans_sid;
502    global $carry_queries;
503    global $CFG;
504
505    // Save the trans_sid setting.
506    if (!isset($_using_trans_sid)) {
507        $_using_trans_sid = ini_get('session.use_trans_sid');
508    }
509
510    // Initialize the carried queries.
511    if (!isset($carry_queries['_carry_queries_init'])) {
512        if (!is_array($carry_queries)) {
513            $carry_queries = array($carry_queries);
514        }
515        $tmp = $carry_queries;
516        $carry_queries = array();
517        foreach ($tmp as $key) {
518            if (!empty($key) && getFormData($key, false)) {
519                $carry_queries[$key] = getFormData($key);
520            }
521        }
522        $carry_queries['_carry_queries_init'] = true;
523    }
524
525    // Get any additional query arguments to add to the $carry_queries array.
526    // If FALSE is a function argument, DO NOT carry the queries.
527    $do_carry_queries = true;
528    $one_time_carry_queries = array();
529    if (!is_null($carry_args)) {
530        if (is_array($carry_args) && !empty($carry_args)) {
531            foreach ($carry_args as $key=>$arg) {
532                // Get query from appropriate source.
533                if (false === $arg) {
534                    $do_carry_queries = false;
535                } else if (false !== getFormData($arg, false)) {
536                    $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
537                } else if (!is_numeric($key) && '' != $arg) {
538                    $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
539                }
540            }
541        } else if (false !== getFormData($carry_args, false)) {
542            $one_time_carry_queries[$carry_args] = getFormData($carry_args);
543        } else if (false === $carry_args) {
544            $do_carry_queries = false;
545        }
546    }
547
548    // Get the first delimiter that is needed in the url.
549    $delim = preg_match('/\?/', $url) ? ini_get('arg_separator.output') : '?';
550
551    $q = '';
552    if ($do_carry_queries) {
553        // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args.
554        $query_args = array_diff_assoc(urlEncodeArray(array_merge($carry_queries, $one_time_carry_queries)), array('_carry_queries_init' => true));
555        foreach ($query_args as $key=>$val) {
556            // Check value is set and value does not already exist in the url.
557            if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
558                $q .= $delim . $key . '=' . $val;
559                $delim = ini_get('arg_separator.output');
560            }
561        }
562    }
563
564    // Include the necessary SID if the following is true:
565    // - no cookie in http request OR cookies disabled in config
566    // - sessions are enabled
567    // - the link stays on our site
568    // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
569    // OR
570    // - 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)
571    // AND
572    // - the SID is not already in the query.
573    if (
574        (
575            (
576                (
577                    !isset($_COOKIE[session_name()])
578                    || !$CFG->session_use_cookies
579                )
580                && $CFG->session_use_trans_sid
581                && $CFG->enable_session
582                && isMyDomain($url)
583                &&
584                (
585                    !$_using_trans_sid
586                    || preg_match('!^(http|https)://!i', $url)
587                )
588            )
589            || $always_include_sid
590        )
591        && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
592    ) {
593        $url .= $q . $delim . session_name() . '=' . session_id();
594//         logMsg(sprintf('oHREF appending session id to URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
595    } else {
596        $url .= $q;
597    }
598
599    return $url;
600}
601
602/**
603 * Returns a URL processed with App::url and htmlentities for printing in html.
604 *
605 * @access  public
606 * @param   string  $url    Input URL to parse.
607 * @return  string          URL with App::url() and htmlentities() applied.
608 * @author  Quinn Comendant <quinn@strangecode.com>
609 * @since   09 Dec 2005 17:58:45
610 */
611function oHREF($url, $carry_args=null, $always_include_sid=false)
612{
613    $url = url($url, $carry_args, $always_include_sid);
614    // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
615    $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
616    return $url;
617}
618
619/**
620 * Force the user to connect via https (port 443) by redirecting them to
621 * the same page but with https.
622 */
623function sslOn()
624{
625    global $CFG;
626
627    if (function_exists('apache_get_modules')) {
628        $modules = apache_get_modules();
629    } else {
630        // It's safe to assume we have mod_ssl if we can't determine otherwise.
631        $modules = array('mod_ssl');
632    }
633
634    if ('on' != getenv('HTTPS') && $CFG->ssl_enabled && in_array('mod_ssl', $modules)) {
635        raiseMsg(sprintf(_("Secure SSL connection made to %s"), $CFG->ssl_domain), MSG_NOTICE, __FILE__, __LINE__);
636        // Always append session because some browsers do not send cookie when crossing to SSL URL.
637        dieURL('https://' . $CFG->ssl_domain . getenv('REQUEST_URI'), null, true);
638    }
639}
640
641
642/**
643 * to enforce the user to connect via http (port 80) by redirecting them to
644 * a http version of the current url.
645 */
646function sslOff()
647{
648    if ('on' == getenv('HTTPS')) {
649        dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
650    }
651}
652
653/**
654 * If the given $url is on the same web site, return true. This can be used to
655 * prevent from sending sensitive info in a get query (like the SID) to another
656 * domain. $method can be "ip" or "domain". The domain method might be preferred
657 * if your domain spans mutiple IP's (load sharing servers)
658 *
659 * @param  string $url    the URI to test.
660 * @param  mixed $method  the method to use. Either 'domain' or 'ip'.
661 *
662 * @return bool    true if given $url is this domain or has no domain (is a
663 *                 relative url), false if it's another
664 */
665function isMyDomain($url)
666{
667    if (!preg_match('|\w{1,}\.\w{2,5}/|', $url)) {
668        // If we can't find a domain we assume the URL is relative.
669        return true;
670    } else {
671        return preg_match('/' . preg_quote(getenv('HTTP_HOST')) . '/', $url);
672    }
673}
674
675/**
676 * Loads a list of tables in the current database into an array, and returns
677 * true if the requested table is found. Use this function to enable/disable
678 * funtionality based upon the current available db tables.
679 *
680 * @param  string $table    The name of the table to search.
681 *
682 * @return bool    true if given $table exists.
683 */
684function dbTableExists($table)
685{
686    static $existing_tables;
687
688    // Save the trans_sid setting.
689    if (!isset($existing_tables)) {
690        // Get DB tables.
691        $existing_tables = array();
692        $qid = dbQuery("SHOW TABLES");
693        while (list($row) = mysql_fetch_row($qid)) {
694            $existing_tables[] = $row;
695        }
696    }
697
698    // Test if requested table is in database.
699    return in_array($table, $existing_tables);
700}
701
702/**
703 * Takes a URL and returns it without the query or anchor portion
704 *
705 * @param  string $url   any kind of URI
706 *
707 * @return string        the URI with ? or # and everything after removed
708 */
709function stripQuery($url)
710{
711    return preg_replace('![?#].*!', '', $url);
712}
713
714/**
715 * Returns the remote IP address, taking into consideration proxy servers.
716 *
717 * @param  bool $dolookup   If true we resolve to IP to a host name,
718 *                          if false we don't.
719 *
720 * @return string    IP address if $dolookup is false or no arg
721 *                   Hostname if $dolookup is true
722 */
723function getRemoteAddr($dolookup=false)
724{
725    $ip = getenv('HTTP_CLIENT_IP');
726    if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') {
727        $ip = getenv('HTTP_X_FORWARDED_FOR');
728        if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') {
729            $ip = getenv('REMOTE_ADDR');
730        }
731    }
732    return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip;
733}
734
735/**
736 * Tests whether a given iP address can be found in an array of IP address networks.
737 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
738 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
739 *
740 * @access  public
741 *
742 * @param   string  IP address to search for.
743 * @param   array   Array of networks to search within.
744 *
745 * @return  mixed   Returns the network that matched on success, false on failure.
746 */
747function ipInRange($my_ip, $ip_pool)
748{
749    if (!is_array($ip_pool)) {
750        $ip_pool = array($ip_pool);
751    }
752
753    $my_ip_binary = sprintf('%032b', ip2long($my_ip));
754    foreach ($ip_pool as $ip) {
755        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $ip)) {
756            // IP is in CIDR notation.
757            list($cidr_ip, $cidr_bitmask) = split('/', $ip);
758            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
759            if (substr($my_ip_binary, 0, $cidr_bitmask) === substr($cidr_ip_binary, 0, $cidr_bitmask)) {
760               // IP address is within the specified IP range.
761               return $ip;
762            }
763        } else {
764            if ($my_ip === $ip) {
765               // IP address exactly matches.
766               return $ip;
767            }
768        }
769    }
770
771    return false;
772}
773
774/**
775 * Returns a fully qualified URL to the current script, including the query.
776 *
777 * @return string    a full url to the current script
778 */
779function absoluteMe()
780{
781    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
782    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
783}
784
785/**
786 * Compares the current url with the referring url.
787 *
788 * @param  string  $compary_query  Include the query string in the comparison.
789 *
790 * @return bool    true if the current script (or specified valid_referer)
791 *                 is the referrer. false otherwise.
792 */
793function refererIsMe($exclude_query=false)
794{
795    if ($exclude_query) {
796        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
797    } else {
798        return (absoluteMe() == getenv('HTTP_REFERER'));
799    }
800}
801
802?>
Note: See TracBrowser for help on using the repository browser.