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

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

Removed some legacy files. Improved use of array_key_exists.

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