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

Last change on this file since 527 was 467, checked in by anonymous, 10 years ago

Merged in changes from trunk to finish Eli's branch.

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