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

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

Better defaults for setCookie()

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