source: branches/eli_branch/lib/App.inc.php @ 442

Last change on this file since 442 was 442, checked in by anonymous, 11 years ago

phpunit tests now work with phpunit 3.7

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