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

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

Renamed function arguments to improve readability; added missing param comments.

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