source: trunk/lib/App.inc.php @ 396

Last change on this file since 396 was 396, checked in by anonymous, 12 years ago

Updated copyright date; comments elaboration; spelling fixes.

File size: 51.8 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * App.inc.php
25 *
26 * Primary application framework class.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @version 2.1
30 */
31
32// Message Types.
33define('MSG_ERR', 1);
34define('MSG_ERROR', MSG_ERR);
35define('MSG_WARNING', 2);
36define('MSG_NOTICE', 4);
37define('MSG_SUCCESS', 8);
38define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR);
39
40require_once dirname(__FILE__) . '/Utilities.inc.php';
41
42class App {
43
44    // Namespace of this application instance.
45    var $_ns;
46
47    // If $app->start has run successfully.
48    var $running = false;
49
50    // Instance of database object.
51    var $db;
52
53    // Array of query arguments will be carried persistently between requests.
54    var $_carry_queries = array();
55
56    // Dictionary of global application parameters.
57    var $_params = array();
58
59    // Default parameters.
60    var $_param_defaults = array(
61
62        // Public name and email address for this application.
63        'site_name' => null,
64        'site_email' => '', // Set to no-reply@HTTP_HOST if not set here.
65        'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here.
66        'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i").
67
68        // The location the user will go if the system doesn't know where else to send them.
69        'redirect_home_url' => '/',
70
71        // SSL URL used when redirecting with $app->sslOn().
72        'ssl_domain' => null,
73        'ssl_enabled' => false,
74
75        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
76        'character_set' => 'utf-8',
77
78        // Human-readable format used to display dates.
79        'date_format' => 'd M Y',
80        'time_format' => 'h:i:s A',
81        'sql_date_format' => '%e %b %Y',
82        'sql_time_format' => '%k:%i',
83
84        // Use php sessions?
85        'enable_session' => false,
86        'session_name' => '_session',
87        'session_use_cookies' => true,
88       
89        // Pass the session-id through URLs if cookies are not enabled?
90        // Disable this to prevent session ID theft.
91        'session_use_trans_sid' => false,
92
93        // Use database?
94        'enable_db' => false,
95
96        // Use db-based sessions?
97        'enable_db_session_handler' => false,
98
99        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
100        'db_server' => 'localhost',
101        'db_name' => null,
102        'db_user' => null,
103        'db_pass' => null,
104
105        // Database debugging.
106        'db_always_debug' => false, // TRUE = display all SQL queries.
107        'db_debug' => false, // TRUE = display db errors.
108        'db_die_on_failure' => false, // TRUE = script stops on db error.
109
110        // For classes that require db tables, do we check that a table exists and create if missing?
111        'db_create_tables' => true,
112
113        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
114        'error_reporting' => E_ALL,
115
116        // Don't display errors by default; it is preferable to log them to a file.
117        'display_errors' => false,
118
119        // Directory in which to store log files.
120        'log_directory' => '',
121
122        // PHP error log.
123        'php_error_log' => 'php_error_log',
124
125        // General application log.
126        'log_filename' => 'app_log',
127
128        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
129        'log_multiple_timeout' => 3600, // Hourly
130
131        // Logging priority can be any of the following, or false to deactivate:
132        // LOG_EMERG     system is unusable
133        // LOG_ALERT     action must be taken immediately
134        // LOG_CRIT      critical conditions
135        // LOG_ERR       error conditions
136        // LOG_WARNING   warning conditions
137        // LOG_NOTICE    normal, but significant, condition
138        // LOG_INFO      informational message
139        // LOG_DEBUG     debug-level message
140        'log_file_priority' => LOG_INFO,
141        'log_email_priority' => false,
142        'log_sms_priority' => false,
143        'log_screen_priority' => false,
144
145        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
146        'log_to_email_address' => null,
147
148        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
149        'log_to_sms_address' => null,
150
151        // Temporary files directory.
152        'tmp_dir' => '/tmp',
153
154        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
155        // Existing password hashes rely on the same key/salt being used to compare encryptions.
156        // Don't change this unless you know existing hashes or signatures will not be affected!
157        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
158    );
159
160    /**
161     * This method enforces the singleton pattern for this class. Only one application is running at a time.
162     *
163     * $param   string  $namespace  Name of this application.
164     * @return  object  Reference to the global Cache object.
165     * @access  public
166     * @static
167     */
168    static function &getInstance($namespace='')
169    {
170        static $instance = null;
171
172        if ($instance === null) {
173            $instance = new App($namespace);
174        }
175
176        return $instance;
177    }
178
179    /**
180     * Constructor.
181     */
182    function App($namespace='')
183    {
184        // Set namespace of application instance.
185        $this->_ns = $namespace;
186
187        // Initialize default parameters.
188        $this->_params = array_merge($this->_params, $this->_param_defaults);
189       
190        // Begin timing script.
191        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
192        $this->timer = new ScriptTimer();
193        $this->timer->start('_app');
194    }
195
196    /**
197     * Set (or overwrite existing) parameters by passing an array of new parameters.
198     *
199     * @access public
200     * @param  array    $param     Array of parameters (key => val pairs).
201     */
202    function setParam($param=null)
203    {
204        if (isset($param) && is_array($param)) {
205            // Merge new parameters with old overriding only those passed.
206            $this->_params = array_merge($this->_params, $param);
207        }
208    }
209
210    /**
211     * Return the value of a parameter.
212     *
213     * @access  public
214     * @param   string  $param      The key of the parameter to return.
215     * @return  mixed               Parameter value, or null if not existing.
216     */
217    function getParam($param=null)
218    {
219        if ($param === null) {
220            return $this->_params;
221        } else if (isset($this->_params[$param])) {
222            return $this->_params[$param];
223        } else {
224            trigger_error(sprintf('Parameter is not set: %s', $param), E_USER_NOTICE);
225            return null;
226        }
227    }
228
229    /**
230     * Begin running this application.
231     *
232     * @access  public
233     * @author  Quinn Comendant <quinn@strangecode.com>
234     * @since   15 Jul 2005 00:32:21
235     */
236    function start()
237    {
238        if ($this->running) {
239            return false;
240        }
241
242        // Error reporting.
243        ini_set('error_reporting', $this->getParam('error_reporting'));
244        ini_set('display_errors', $this->getParam('display_errors'));
245        ini_set('log_errors', true);
246        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
247            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
248        }
249
250        // Set character set to use for multi-byte string functions.
251        mb_internal_encoding($this->getParam('character_set'));
252        switch (mb_strtolower($this->getParam('character_set'))) {
253        case 'utf-8' :
254            mb_language('uni');
255            break;
256
257        case 'iso-2022-jp' :
258            mb_language('ja');
259            break;
260
261        case 'iso-8859-1' :
262        default :
263            mb_language('en');
264            break;
265        }
266
267        /**
268         * 1. Start Database.
269         */
270
271        if (true === $this->getParam('enable_db')) {
272
273            // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root.
274            if (!empty($_SERVER['DB_SERVER'])) {
275                $this->setParam(array('db_server' => $_SERVER['DB_SERVER']));
276            }
277            if (!empty($_SERVER['DB_NAME'])) {
278                $this->setParam(array('db_name' => $_SERVER['DB_NAME']));
279            }
280            if (!empty($_SERVER['DB_USER'])) {
281                $this->setParam(array('db_user' => $_SERVER['DB_USER']));
282            }
283            if (!empty($_SERVER['DB_PASS'])) {
284                $this->setParam(array('db_pass' => $_SERVER['DB_PASS']));
285            }
286
287            // There will ever only be one instance of the DB object, and here is where it is instantiated.
288            require_once dirname(__FILE__) . '/DB.inc.php';
289            $this->db =& DB::getInstance();
290            $this->db->setParam(array(
291                'db_server' => $this->getParam('db_server'),
292                'db_name' => $this->getParam('db_name'),
293                'db_user' => $this->getParam('db_user'),
294                'db_pass' => $this->getParam('db_pass'),
295                'db_always_debug' => $this->getParam('db_always_debug'),
296                'db_debug' => $this->getParam('db_debug'),
297                'db_die_on_failure' => $this->getParam('db_die_on_failure'),
298            ));
299
300            // Connect to database.
301            $this->db->connect();
302        }
303
304
305        /**
306         * 2. Start PHP session.
307         */
308
309        // Skip session for some user agents.
310        if (preg_match('/Atomz|ApacheBench|Wget/i', getenv('HTTP_USER_AGENT'))) {
311            $this->setParam(array('enable_session' => false));
312        }
313
314        if (true === $this->getParam('enable_session')) {
315
316            // Session parameters.
317            ini_set('session.gc_probability', 1);
318            ini_set('session.gc_divisor', 1000);
319            ini_set('session.gc_maxlifetime', 43200); // 12 hours
320            ini_set('session.use_cookies', $this->getParam('session_use_cookies'));
321            ini_set('session.use_trans_sid', false);
322            ini_set('session.entropy_file', '/dev/urandom');
323            ini_set('session.entropy_length', '512');
324            session_name($this->getParam('session_name'));
325
326            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
327                // Database session handling.
328                require_once dirname(__FILE__) . '/DBSessionHandler.inc.php';
329                $db_save_handler = new DBSessionHandler($this->db, array(
330                    'db_table' => 'session_tbl',
331                    'create_table' => $this->getParam('db_create_tables'),
332                ));
333            }
334
335            // Start the session.
336            session_start();
337
338            if (!isset($_SESSION['_app'][$this->_ns])) {
339                // Access session data using: $_SESSION['...'].
340                // Initialize here _after_ session has started.
341                $_SESSION['_app'][$this->_ns] = array(
342                    'messages' => array(),
343                    'boomerang' => array('url'),
344                );
345            }
346        }
347
348
349        /**
350         * 3. Misc setup.
351         */
352
353        // Script URI will be something like http://host.name.tld (no ending slash)
354        // and is used whenever a URL need be used to the current site.
355        // Not available on cli scripts obviously.
356        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) {
357            $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'))));
358        }
359       
360        // In case site_email isn't set, use something halfway presentable.
361        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_email')) {
362            $this->setParam(array('site_email' => sprintf('no-reply@%s', getenv('HTTP_HOST'))));
363        }
364
365        // A key for calculating simple cryptographic signatures.
366        if (isset($_SERVER['SIGNING_KEY'])) {
367            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
368        }
369
370        // Character set. This should also be printed in the html header template.
371        header('Content-type: text/html; charset=' . $this->getParam('character_set'));
372       
373        // Set the version of the codebase we're using.
374        $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
375        if (is_readable($codebase_version_file)) {
376            $codebase_version = trim(file_get_contents($codebase_version_file));
377            $this->setParam(array('codebase_version' => $codebase_version));
378            header('X-Codebase-Version: ' . $codebase_version);
379        }
380
381        $this->running = true;
382    }
383
384    /**
385     * Stop running this application.
386     *
387     * @access  public
388     * @author  Quinn Comendant <quinn@strangecode.com>
389     * @since   17 Jul 2005 17:20:18
390     */
391    function stop()
392    {
393        session_write_close();
394        restore_include_path();
395        $this->running = false;
396        $num_queries = 0;
397        if (true === $this->getParam('enable_db')) {
398            $num_queries = $this->db->numQueries();
399            $this->db->close();
400        }
401        $this->timer->stop('_app');
402        $this->logMsg(sprintf('Script ended gracefully. Execution time: %s. Number of db queries: %s.', $this->timer->getTime('_app'), $num_queries), LOG_DEBUG, __FILE__, __LINE__);
403    }
404
405
406    /**
407     * Add a message to the session, which is printed in the header.
408     * Just a simple way to print messages to the user.
409     *
410     * @access public
411     *
412     * @param string $message The text description of the message.
413     * @param int    $type    The type of message: MSG_NOTICE,
414     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
415     * @param string $file    __FILE__.
416     * @param string $line    __LINE__.
417     */
418    function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
419    {
420        $message = trim($message);
421
422        if (!$this->running) {
423            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
424            return false;
425        }
426
427        if ('' == trim($message)) {
428            $this->logMsg(sprintf('Raised message is an empty string.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
429            return false;
430        }
431
432        // Save message in session under unique key to avoid duplicate messages.
433        $msg_id = md5($type . $message);
434        if (!isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id])) {
435            $_SESSION['_app'][$this->_ns]['messages'][$msg_id] = array(
436                'type'    => $type,
437                'message' => $message,
438                'file'    => $file,
439                'line'    => $line,
440                'count'   => (isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) : 1)
441            );
442        }
443
444        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
445            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__);
446        }
447    }
448   
449    /**
450     * Returns an array of the raised messages.
451     *
452     * @access  public
453     * @return  array   List of messages in FIFO order.
454     * @author  Quinn Comendant <quinn@strangecode.com>
455     * @since   21 Dec 2005 13:09:20
456     */
457    function getRaisedMessages()
458    {
459        if (!$this->running) {
460            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
461            return false;
462        }
463
464        return isset($_SESSION['_app'][$this->_ns]['messages']) ? $_SESSION['_app'][$this->_ns]['messages'] : array();
465    }
466   
467    /**
468     * Resets the message list.
469     *
470     * @access  public
471     * @author  Quinn Comendant <quinn@strangecode.com>
472     * @since   21 Dec 2005 13:21:54
473     */
474    function clearRaisedMessages()
475    {
476        if (!$this->running) {
477            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
478            return false;
479        }
480       
481        $_SESSION['_app'][$this->_ns]['messages'] = array();
482    }
483
484    /**
485     * Prints the HTML for displaying raised messages.
486     *
487     * @access  public
488     * @author  Quinn Comendant <quinn@strangecode.com>
489     * @since   15 Jul 2005 01:39:14
490     */
491    function printRaisedMessages()
492    {
493        if (!$this->running) {
494            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
495            return false;
496        }
497       
498        $messages = $this->getRaisedMessages();
499        if (!empty($messages)) {
500            ?><div id="sc-msg" class="sc-msg"><?php
501            foreach ($messages as $m) {
502                if (error_reporting() > 0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) {
503                    echo "\n<!-- [" . $m['file'] . ' : ' . $m['line'] . '] -->';
504                }
505                switch ($m['type']) {
506                case MSG_ERR:
507                    echo '<div class="sc-msg-error">' . $m['message'] . '</div>';
508                    break;
509
510                case MSG_WARNING:
511                    echo '<div class="sc-msg-warning">' . $m['message'] . '</div>';
512                    break;
513
514                case MSG_SUCCESS:
515                    echo '<div class="sc-msg-success">' . $m['message'] . '</div>';
516                    break;
517
518                case MSG_NOTICE:
519                default:
520                    echo '<div class="sc-msg-notice">' . $m['message'] . '</div>';
521                    break;
522
523                }
524            }
525            ?></div><?php
526        }
527        $this->clearRaisedMessages();
528    }
529
530    /**
531     * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are
532     * not repeated but printed once with count. Log events that match a sendable channel (email or SMS)
533     * are sent once per 'log_multiple_timeout' setting (to avoid a flood of error emails).
534     *
535     * @access public
536     * @param string $message   The text description of the message.
537     * @param int    $priority  The type of message priority (in descending order):
538     *                          LOG_EMERG     0 system is unusable
539     *                          LOG_ALERT     1 action must be taken immediately
540     *                          LOG_CRIT      2 critical conditions
541     *                          LOG_ERR       3 error conditions
542     *                          LOG_WARNING   4 warning conditions
543     *                          LOG_NOTICE    5 normal, but significant, condition
544     *                          LOG_INFO      6 informational message
545     *                          LOG_DEBUG     7 debug-level message
546     * @param string $file      The file where the log event occurs.
547     * @param string $line      The line of the file where the log event occurs.
548     */
549    function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
550    {
551        static $previous_events = array();
552
553        // If priority is not specified, assume the worst.
554        if (!$this->logPriorityToString($priority)) {
555            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
556            $priority = LOG_EMERG;
557        }
558
559        // If log file is not specified, don't log to a file.
560        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
561            $this->setParam(array('log_file_priority' => false));
562            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
563            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
564        }
565       
566        // Before we get any further, let's see if ANY log events are configured to be reported.
567        if ((false === $this->getParam('log_file_priority') || $priority > $this->getParam('log_file_priority'))
568        && (false === $this->getParam('log_email_priority') || $priority > $this->getParam('log_email_priority'))
569        && (false === $this->getParam('log_sms_priority') || $priority > $this->getParam('log_sms_priority'))
570        && (false === $this->getParam('log_screen_priority') || $priority > $this->getParam('log_screen_priority'))) {
571            // This event would not be recorded, skip it entirely.
572            return false;
573        }
574
575        // Make sure to log in the system's locale.
576        $locale = setlocale(LC_TIME, 0);
577        setlocale(LC_TIME, 'C');
578
579        // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>.
580        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow);
581        $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
582
583        // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times.
584        $msg_id = md5($message . $priority . $file . $line);
585        if (isset($previous_events[$msg_id])) {
586            $previous_events[$msg_id]++;
587            if ($previous_events[$msg_id] == 2) {
588                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
589            }
590            return false;
591        } else {
592            $previous_events[$msg_id] = 1;
593        }
594
595        // For email and SMS notification types use "lock" files to prevent sending email and SMS notices ad infinitum.
596        if ((false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority'))
597        || (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority'))) {
598            // This event will generate a "send" notification. Prepare lock file.
599            $site_hash = md5(empty($_SERVER['SERVER_NAME']) ? $_SERVER['SCRIPT_FILENAME'] : $_SERVER['SERVER_NAME']);
600            $lock_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/";
601            // Just use the file and line for the msg_id to limit the number of possible messages
602            // (the message string itself shan't be used as it may contain innumerable combinations).
603            $lock_file = $lock_dir . md5($file . ':' . $line);
604            if (!is_dir($lock_dir)) {
605                mkdir($lock_dir);
606            }
607            $send_notifications = true;
608            if (is_file($lock_file)) {
609                $msg_last_sent = filectime($lock_file);
610                // Has this message been sent more recently than the timeout?
611                if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) {
612                    // This message was already sent recently.
613                    $send_notifications = false;
614                } else {
615                    // Timeout has expired; send notifications again and reset timeout.
616                    touch($lock_file);
617                }
618            } else {
619                touch($lock_file);
620            }
621        }
622       
623        // Data to be stored for a log event.
624        $event = array(
625            'date'      => date('Y-m-d H:i:s'),
626            'remote ip' => getRemoteAddr(),
627            'pid'       => (mb_substr(PHP_OS, 0, 3) != 'WIN' ? posix_getpid() : ''),
628            'type'      => $this->logPriorityToString($priority),
629            'file:line' => "$file : $line",
630            'url'       => mb_substr(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 0, 128),
631            'message'   => $message
632        );
633
634        // FILE ACTION
635        if (false !== $this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
636            $event_str = '[' . join('] [', $event) . ']';
637            error_log(mb_substr($event_str, 0, 1024) . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
638        }
639
640        // EMAIL ACTION
641        if (false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority') && $send_notifications) {
642            $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], mb_substr($message, 0, 64));
643            $email_msg = sprintf("A %s log event occurred on %s\n\n", $event['type'], getenv('HTTP_HOST'));
644            $headers = 'From: ' . $this->getParam('site_email');
645            foreach ($event as $k=>$v) {
646                $email_msg .= sprintf("%-11s%s\n", $k, $v);
647            }
648            mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers);
649        }
650
651        // SMS ACTION
652        if (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority') && $send_notifications) {
653            $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority);
654            $sms_msg = sprintf('%s [%s:%s]', mb_substr($event['message'], 0, 64), basename($file), $line);
655            $headers = 'From: ' . $this->getParam('site_email');
656            mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers);
657        }
658   
659        // SCREEN ACTION
660        if (false !== $this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
661            echo "[{$event['type']}] [{$event['message']}]\n";
662        }
663
664        // Restore original locale.
665        setlocale(LC_TIME, $locale);
666       
667        return true;
668    }
669
670    /**
671     * Returns the string representation of a LOG_* integer constant.
672     *
673     * @param int  $priority  The LOG_* integer constant.
674     *
675     * @return                The string representation of $priority.
676     */
677    function logPriorityToString($priority) {
678        $priorities = array(
679            LOG_EMERG   => 'emergency',
680            LOG_ALERT   => 'alert',
681            LOG_CRIT    => 'critical',
682            LOG_ERR     => 'error',
683            LOG_WARNING => 'warning',
684            LOG_NOTICE  => 'notice',
685            LOG_INFO    => 'info',
686            LOG_DEBUG   => 'debug'
687        );
688        if (isset($priorities[$priority])) {
689            return $priorities[$priority];
690        } else {
691            return false;
692        }
693    }
694
695    /**
696     * Forcefully set a query argument even if one currently exists in the request.
697     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
698     * to hidden input values (via printHiddenSession()).
699     *
700     * @access  public
701     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to save.
702     * @param   mixed   $val        The new value of the argument key.
703     * @author  Quinn Comendant <quinn@strangecode.com>
704     * @since   13 Oct 2007 11:34:51
705     */
706    function setQuery($query_key, $val)
707    {
708        if (!is_array($query_key)) {
709            $query_key = array($query_key);
710        }
711        foreach ($query_key as $k) {
712            // Set the value of the specified query argument into the _carry_queries array.
713            $this->_carry_queries[$k] = $val;
714        }
715    }
716
717    /**
718     * Specify which query arguments will be carried persistently between requests.
719     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
720     * to hidden input values (via printHiddenSession()).
721     *
722     * @access  public
723     * @param   mixed   $query_key   The key (or keys, as an array) of the query argument to save.
724     * @param   mixed   $default    If the key is not available, set to this default value.
725     * @author  Quinn Comendant <quinn@strangecode.com>
726     * @since   14 Nov 2005 19:24:52
727     */
728    function carryQuery($query_key, $default=false)
729    {
730        if (!is_array($query_key)) {
731            $query_key = array($query_key);
732        }
733        foreach ($query_key as $k) {
734            // If not already set, and there is a non-empty value provided in the request...
735            if (!isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) {
736                // Copy the value of the specified query argument into the _carry_queries array.
737                $this->_carry_queries[$k] = getFormData($k, $default);
738                $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__);
739            }
740        }
741    }
742
743    /**
744     * dropQuery() is the opposite of carryQuery(). The specified value will not appear in
745     * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in.
746     *
747     * @access  public
748     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to remove.
749     * @author  Quinn Comendant <quinn@strangecode.com>
750     * @since   18 Jun 2007 20:57:29
751     */
752    function dropQuery($query_key, $unset=false)
753    {
754        if (!is_array($query_key)) {
755            $query_key = array($query_key);
756        }
757        foreach ($query_key as $k) {
758            if (isset($this->_carry_queries[$k])) {
759                // Remove the value of the specified query argument from the _carry_queries array.
760                $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__);
761                unset($this->_carry_queries[$k]);
762            }
763            if ($unset && isset($_REQUEST[$k])) {
764                unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]);
765            }
766        }
767    }
768
769    /**
770     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
771     * keys and values, including optional queries. This allows mindless retention
772     * of query arguments across page requests. If cookies are not
773     * used, the session id will be propagated in the URL.
774     *
775     * @param  string $url              The initial url
776     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
777     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
778     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
779     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
780     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
781     *
782     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
783     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
784     *                                     header('Location...') redirections.
785     *
786     * @return string url with attached queries and, if not using cookies, the session id
787     */
788    function url($url, $carry_args=null, $always_include_sid=false)
789    {
790        if (!$this->running) {
791            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
792            return false;
793        }
794
795        // Get any provided query arguments to include in the final URL.
796        // If FALSE is a provided here, DO NOT carry the queries.
797        $do_carry_queries = true;
798        $one_time_carry_queries = array();
799        if (!is_null($carry_args)) {
800            if (is_array($carry_args) && !empty($carry_args)) {
801                foreach ($carry_args as $key=>$arg) {
802                    // Get query from appropriate source.
803                    if (false === $arg) {
804                        $do_carry_queries = false;
805                    } else if (false !== getFormData($arg, false)) {
806                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
807                    } else if (!is_numeric($key) && '' != $arg) {
808                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
809                    }
810                }
811            } else if (false !== getFormData($carry_args, false)) {
812                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
813            } else if (false === $carry_args) {
814                $do_carry_queries = false;
815            }
816        }
817
818        // Get the first delimiter that is needed in the url.
819        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
820
821        $q = '';
822        if ($do_carry_queries) {
823            // Join the global _carry_queries and local one_time_carry_queries.
824            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
825            foreach ($query_args as $key=>$val) {
826                // Check value is set and value does not already exist in the url.
827                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
828                    $q .= $delim . $key . '=' . $val;
829                    $delim = ini_get('arg_separator.output');
830                }
831            }
832        }
833
834        // Include the necessary SID if the following is true:
835        // - no cookie in http request OR cookies disabled in App
836        // - sessions are enabled
837        // - the link stays on our site
838        // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
839        // OR
840        // - 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)
841        // AND
842        // - the SID is not already in the query.
843        if (
844            (
845                (
846                    (
847                        !isset($_COOKIE[session_name()])
848                        || !$this->getParam('session_use_cookies')
849                    )
850                    && $this->getParam('session_use_trans_sid')
851                    && $this->getParam('enable_session')
852                    && isMyDomain($url)
853                    && (
854                        !ini_get('session.use_trans_sid')
855                        || preg_match('!^(http|https)://!i', $url)
856                    )
857                )
858                || $always_include_sid
859            )
860            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
861        ) {
862            $url .= $q . $delim . session_name() . '=' . session_id();
863            return $url;
864        } else {
865            $url .= $q;
866            return $url;
867        }
868    }
869
870    /**
871     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
872     *
873     * @access  public
874     * @param   string  $url    Input URL to parse.
875     * @return  string          URL passed through $app->url() and then & turned to $amp;.
876     * @author  Quinn Comendant <quinn@strangecode.com>
877     * @since   09 Dec 2005 17:58:45
878     */
879    function oHREF($url, $carry_args=null, $always_include_sid=false)
880    {
881        $url = $this->url($url, $carry_args, $always_include_sid);
882
883        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
884        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
885
886        return $url;
887    }
888
889    /**
890     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
891     * as hidden form elements for GET_VARS that might be in use.
892     *
893     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
894     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
895     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
896     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
897     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
898     */
899    function printHiddenSession($carry_args=null)
900    {
901        if (!$this->running) {
902            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
903            return false;
904        }
905
906        // Get any provided query arguments to include in the final hidden form data.
907        // If FALSE is a provided here, DO NOT carry the queries.
908        $do_carry_queries = true;
909        $one_time_carry_queries = array();
910        if (!is_null($carry_args)) {
911            if (is_array($carry_args) && !empty($carry_args)) {
912                foreach ($carry_args as $key=>$arg) {
913                    // Get query from appropriate source.
914                    if (false === $arg) {
915                        $do_carry_queries = false;
916                    } else if (false !== getFormData($arg, false)) {
917                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
918                    } else if (!is_numeric($key) && '' != $arg) {
919                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
920                    }
921                }
922            } else if (false !== getFormData($carry_args, false)) {
923                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
924            } else if (false === $carry_args) {
925                $do_carry_queries = false;
926            }
927        }
928
929        // For each existing request value, we create a hidden input to carry it through a form.
930        if ($do_carry_queries) {
931            // Join the global _carry_queries and local one_time_carry_queries.
932            // urlencode is not used here, not for form data!
933            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
934            foreach ($query_args as $key=>$val) {
935                printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
936            }
937        }
938
939        // Include the SID if cookies are disabled.
940        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
941            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
942        }
943    }
944
945    /**
946     * Uses an http header to redirect the client to the given $url. If sessions are not used
947     * and the session is not already defined in the given $url, the SID is appended as a URI query.
948     * As with all header generating functions, make sure this is called before any other output.
949     *
950     * @param   string  $url                    The URL the client will be redirected to.
951     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
952     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
953     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
954     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
955     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
956     * @param   bool    $always_include_sid     Force session id to be added to Location header.
957     */
958    function dieURL($url, $carry_args=null, $always_include_sid=false)
959    {
960        if (!$this->running) {
961            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
962            return false;
963        }
964
965        if ('' == $url) {
966            // If URL is not specified, use the redirect_home_url.
967            $url = $this->getParam('redirect_home_url');
968        }
969
970        if (preg_match('!^/!', $url)) {
971            // If relative URL is given, prepend correct local hostname.
972            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
973            $host = getenv('HTTP_HOST');
974            $url = sprintf('%s://%s%s', $scheme, $host, $url);
975        }
976
977        $url = $this->url($url, $carry_args, $always_include_sid);
978
979        // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP?
980        header(sprintf('Location: %s', $url));
981        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
982
983        // End application.
984        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
985        $this->stop();
986        die;
987    }
988
989    /*
990    * Redirects a user by calling $app->dieURL(). It will use:
991    * 1. the stored boomerang URL, it it exists
992    * 2. a specified $default_url, it it exists
993    * 3. the referring URL, it it exists.
994    * 4. redirect_home_url configuration variable.
995    *
996    * @access   public
997    * @param    string  $id             Identifier for this script.
998    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->oHREF()).
999    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
1000    * @param    bool    $queryless_referrer_comparison   Exclude the URL query from the refererIsMe() comparison.
1001    * @return   bool                    False if the session is not running. No return otherwise.
1002    * @author   Quinn Comendant <quinn@strangecode.com>
1003    * @since    31 Mar 2006 19:17:00
1004    */
1005    function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false)
1006    {
1007        if (!$this->running) {
1008            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1009            return false;
1010        }
1011
1012        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
1013        if ($this->validBoomerangURL($id, true)) {
1014            if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1015                $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
1016                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1017            } else {
1018                $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1019                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1020            }
1021            // Delete stored boomerang.
1022            $this->deleteBoomerangURL($id);
1023        } else if (isset($default_url)) {
1024            $url = $default_url;
1025        } else if (!refererIsMe(true === $queryless_referrer_comparison)) {
1026            // Ensure that the redirecting page is not also the referrer.
1027            $url = getenv('HTTP_REFERER');
1028            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1029        } else {
1030            // If URL is not specified, use the redirect_home_url.
1031            $url = $this->getParam('redirect_home_url');
1032            $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1033        }
1034
1035        // A redirection will never happen immediately twice.
1036        // Set the time so ensure this doesn't happen.
1037        $_SESSION['_app'][$this->_ns]['boomerang']['time'] = time();
1038        $this->dieURL($url, $carry_args);
1039    }
1040
1041    /**
1042     * Set the URL to return to when $app->dieBoomerangURL() is called.
1043     *
1044     * @param string  $url  A fully validated URL.
1045     * @param bool  $id     An identification tag for this url.
1046     * FIXME: url garbage collection?
1047     */
1048    function setBoomerangURL($url=null, $id=null)
1049    {
1050        if (!$this->running) {
1051            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1052            return false;
1053        }
1054        // A redirection will never happen immediately after setting the boomerangURL.
1055        // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
1056        /// FIXME: Why isn't the time set here under setBoomerangURL() and only under dieBoomerangURL()?
1057
1058        if ('' != $url && is_string($url)) {
1059            // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion).
1060            $url = preg_replace(array('/([&?])boomerang=\w+[&?]?/', '/[&?]$/'), array('$1', ''), $url);
1061
1062            if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']['url']) && !empty($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1063                // If the URL currently exists in the boomerang array, delete.
1064                while ($existing_key = array_search($url, $_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1065                    unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$existing_key]);
1066                }
1067            }
1068
1069            if (isset($id)) {
1070                $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id] = $url;
1071            } else {
1072                $_SESSION['_app'][$this->_ns]['boomerang']['url'][] = $url;
1073            }
1074            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1075            return true;
1076        } else {
1077            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
1078            return false;
1079        }
1080    }
1081
1082    /**
1083     * Return the URL set for the specified $id, or an empty string if one isn't set.
1084     *
1085     * @param string  $id     An identification tag for this url.
1086     */
1087    function getBoomerangURL($id=null)
1088    {
1089        if (!$this->running) {
1090            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1091            return false;
1092        }
1093
1094        if (isset($id)) {
1095            if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1096                return $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
1097            } else {
1098                return '';
1099            }
1100        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1101            return end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1102        } else {
1103            return false;
1104        }
1105    }
1106
1107    /**
1108     * Delete the URL set for the specified $id.
1109     *
1110     * @param string  $id     An identification tag for this url.
1111     */
1112    function deleteBoomerangURL($id=null)
1113    {
1114        if (!$this->running) {
1115            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1116            return false;
1117        }
1118
1119        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
1120
1121        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1122            unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]);
1123        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1124            array_pop($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1125        }
1126    }
1127
1128    /**
1129     * Check if a valid boomerang URL value has been set. A boomerang URL is considered
1130     * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds.
1131     *
1132     * @return bool  True if it is set and valid, false otherwise.
1133     */
1134    function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
1135    {
1136        if (!$this->running) {
1137            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1138            return false;
1139        }
1140
1141        if (!isset($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1142            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__);
1143            return false;
1144        }
1145
1146        // Time is the time stamp of a boomerangURL redirection, or setting of a boomerangURL.
1147        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
1148        // or a boomerang being set.
1149        $boomerang_time = isset($_SESSION['_app'][$this->_ns]['boomerang']['time']) ? $_SESSION['_app'][$this->_ns]['boomerang']['time'] : 0;
1150
1151        $url = '';
1152        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1153            $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
1154        } else if (!isset($id) || $use_nonspecificboomerang) {
1155            // Use non specific boomerang if available.
1156            $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1157        }
1158
1159        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1160
1161        if ('' == $url) {
1162            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
1163            return false;
1164        }
1165        if ($url == absoluteMe()) {
1166            // The URL we are directing to is the current page.
1167            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1168            return false;
1169        }
1170        if ($boomerang_time >= (time() - 2)) {
1171            // Last boomerang direction was less than 2 seconds ago.
1172            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s seconds', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
1173            return false;
1174        }
1175
1176        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1177        return true;
1178    }
1179
1180    /**
1181     * Force the user to connect via https (port 443) by redirecting them to
1182     * the same page but with https.
1183     */
1184    function sslOn()
1185    {
1186        if (function_exists('apache_get_modules')) {
1187            $modules = apache_get_modules();
1188        } else {
1189            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1190            $modules = array('mod_ssl');
1191        }
1192
1193        if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1194            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1195            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1196            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1197        }
1198    }
1199
1200
1201    /**
1202     * to enforce the user to connect via http (port 80) by redirecting them to
1203     * a http version of the current url.
1204     */
1205    function sslOff()
1206    {
1207        if ('' != getenv('HTTPS')) {
1208            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1209        }
1210    }
1211
1212
1213} // End.
1214
1215?>
Note: See TracBrowser for help on using the repository browser.