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

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

Optimizing auth and csrf token.

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