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

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

Added use of httponly for PHP session

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