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

Last change on this file since 623 was 623, checked in by anonymous, 6 years ago

Simplify HTTPS detection

File size: 78.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    // Instance of database session handler object.
60    public $db_session;
61
62    // Array of query arguments will be carried persistently between requests.
63    protected $_carry_queries = array();
64
65    // Array of raised message counters.
66    protected $_raised_msg_counter = array(MSG_NOTICE => 0, MSG_SUCCESS => 0, MSG_WARNING => 0, MSG_ERR => 0);
67
68    // We're running as CLI. Public because we must force this as false when testing sessions via CLI.
69    public $cli = false;
70
71    // Dictionary of global application parameters.
72    protected $_params = array();
73
74    // Default parameters.
75    protected $_param_defaults = array(
76
77        // Public name and email address for this application.
78        'site_name' => null,
79        'site_email' => '', // Set to no-reply@HTTP_HOST if not set here.
80        'site_url' => '', // URL to the root of the site (created during App->start()).
81        'page_url' => '', // URL to the current page (created during App->start()).
82        'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i").
83        'site_version' => '', // Version of this application (set automatically during start() if site_version_file is used).
84        'site_version_file' => 'docs/version.txt', // File containing version number of this app, relative to the include path.
85
86        // The location the user will go if the system doesn't know where else to send them.
87        'redirect_home_url' => '/',
88
89        // SSL URL used when redirecting with $app->sslOn().
90        'ssl_domain' => null,
91        'ssl_enabled' => false,
92
93        // Use CSRF tokens. See notes in the getCSRFToken() method.
94        'csrf_token_enabled' => true,
95        // Form tokens will expire after this duration, in seconds.
96        'csrf_token_timeout' => 259200, // 259200 seconds = 3 days.
97        'csrf_token_name' => 'csrf_token',
98
99        // HMAC signing method
100        'signing_method' => 'sha512+base64',
101
102        // Content type of output sent in the Content-type: http header.
103        'content_type' => 'text/html',
104
105        // Allow HTTP caching with max-age setting. Possible values:
106        //  >= 1    Allow HTTP caching with this value set as the max-age (in seconds, i.e., 3600 = 1 hour).
107        //  0       Disallow HTTP caching.
108        //  false   Don't send any cache-related HTTP headers (if you want to control this via server config or custom headers)
109        // This should be '0' for websites that use authentication or have frequently changing dynamic content.
110        'http_cache_headers' => 0,
111
112        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
113        'character_set' => 'utf-8',
114
115        // Human-readable format used to display dates.
116        'date_format' => 'd M Y',
117        'time_format' => 'h:i:s A',
118        'sql_date_format' => '%e %b %Y',
119        'sql_time_format' => '%k:%i',
120
121        // Use php sessions?
122        'enable_session' => false,
123        'session_name' => '_session',
124        'session_use_cookies' => true,
125
126        // Pass the session-id through URLs if cookies are not enabled?
127        // Disable this to prevent session ID theft.
128        'session_use_trans_sid' => false,
129
130        // Use database?
131        'enable_db' => false,
132
133        // Use db-based sessions?
134        'enable_db_session_handler' => false,
135
136        // DB credentials should be set as apache environment variables in httpd.conf, readable only by root.
137        'db_server' => null,
138        'db_name' => null,
139        'db_user' => null,
140        'db_pass' => null,
141
142        // And for CLI scripts, which should include a JSON file at this specified location in the include path.
143        'db_auth_file' => 'db_auth.json',
144
145        // Database debugging.
146        'db_always_debug' => false, // TRUE = display all SQL queries.
147        'db_debug' => false, // TRUE = display db errors.
148        'db_die_on_failure' => false, // TRUE = script stops on db error.
149
150        // For classes that require db tables, do we check that a table exists and create if missing?
151        'db_create_tables' => true,
152
153        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
154        'error_reporting' => E_ALL,
155
156        // Don't display errors by default; it is preferable to log them to a file. For CLI scripts, set this to the string 'stderr'.
157        'display_errors' => false,
158
159        // Directory in which to store log files.
160        'log_directory' => '',
161
162        // PHP error log.
163        'php_error_log' => 'php_error_log',
164
165        // General application log.
166        'log_filename' => 'app_log',
167
168        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
169        'log_multiple_timeout' => 3600, // Hourly
170
171        // Logging priority can be any of the following, or false to deactivate:
172        // LOG_EMERG     system is unusable
173        // LOG_ALERT     action must be taken immediately
174        // LOG_CRIT      critical conditions
175        // LOG_ERR       error conditions
176        // LOG_WARNING   warning conditions
177        // LOG_NOTICE    normal, but significant, condition
178        // LOG_INFO      informational message
179        // LOG_DEBUG     debug-level message
180        'log_file_priority' => LOG_INFO,
181        'log_email_priority' => false,
182        'log_sms_priority' => false,
183        'log_screen_priority' => false,
184
185        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
186        'log_to_email_address' => null,
187
188        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
189        'log_to_sms_address' => null,
190
191        // 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.
192        'log_ignore_repeated_events' => true,
193
194        // Maximum length of log messages, in bytes.
195        'log_message_max_length' => 1024,
196
197        // Temporary files directory.
198        'tmp_dir' => '/tmp',
199
200        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
201        // Existing password hashes rely on the same key/salt being used to compare encryptions.
202        // Don't change this unless you know existing hashes or signatures will not be affected!
203        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
204
205        // Force getFormData, getPost, and getGet to always run dispelMagicQuotes() with stripslashes().
206        // This should be set to 'true' when using the codebase with Wordpress because
207        // WP forcefully adds slashes to all input despite the setting of magic_quotes_gpc.
208        'always_dispel_magicquotes' => false,
209    );
210
211    /**
212     * Constructor.
213     */
214    public function __construct($namespace='')
215    {
216        // Initialize default parameters.
217        $this->_params = array_merge($this->_params, array('namespace' => $namespace), $this->_param_defaults);
218
219        // Begin timing script.
220        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
221        $this->timer = new ScriptTimer();
222        $this->timer->start('_app');
223
224        // Are we running as a CLI?
225        $this->cli = ('cli' === php_sapi_name() || defined('_CLI'));
226    }
227
228    /**
229     * This method enforces the singleton pattern for this class. Only one application is running at a time.
230     *
231     * $param   string  $namespace  Name of this application.
232     * @return  object  Reference to the global Cache object.
233     * @access  public
234     * @static
235     */
236    public static function &getInstance($namespace='')
237    {
238        if (self::$instance === null) {
239            // FIXME: Yep, having a namespace with one singleton instance is not very useful. This is a design flaw with the Codebase.
240            // We're currently getting instances of App throughout the codebase using `$app =& App::getInstance();`
241            // with no way to determine what the namespace of the containing application is (e.g., `public` vs. `admin`).
242            // Option 1: provide the project namespace to all classes that use App, and then instantiate with `$app =& App::getInstance($this->_ns);`.
243            // In this case the namespace of the App and the namespace of the auxiliary class must match.
244            // Option 2: may be to clone a specific instance to the "default" instance, so, e.g., `$app =& App::getInstance();`
245            // refers to the same namespace as `$app =& App::getInstance('admin');`
246            // Option 3: is to check if there is only one instance, and return it if an unspecified namespace is requested.
247            // However, in the case when multiple namespaces are in play at the same time, this will fail; unspecified namespaces
248            // would cause the creation of an additional instance, since there would not be an obvious named instance to return.
249            self::$instance = new self($namespace);
250        }
251
252        if ('' != $namespace) {
253            // We may not be able to request a specific instance, but we can specify a specific namespace.
254            // We're ignoring all instance requests with a blank namespace, so we use the last given one.
255            self::$instance->_ns = $namespace;
256        }
257
258        return self::$instance;
259    }
260
261    /**
262     * Set (or overwrite existing) parameters by passing an array of new parameters.
263     *
264     * @access public
265     * @param  array    $param     Array of parameters (key => val pairs).
266     */
267    public function setParam($param=null)
268    {
269        if (isset($param) && is_array($param)) {
270            // Merge new parameters with old overriding old ones that are passed.
271            $this->_params = array_merge($this->_params, $param);
272
273            if ($this->running) {
274                // Params that require additional processing if set during runtime.
275                foreach ($param as $key => $val) {
276                    switch ($key) {
277                    case 'namespace':
278                        $this->logMsg(sprintf('Setting namespace not allowed', null), LOG_WARNING, __FILE__, __LINE__);
279                        return false;
280
281                    case 'session_name':
282                        session_name($val);
283                        return true;
284
285                    case 'session_use_cookies':
286                        ini_set('session.use_cookies', $val);
287                        return true;
288
289                    case 'error_reporting':
290                        ini_set('error_reporting', $val);
291                        return true;
292
293                    case 'display_errors':
294                        ini_set('display_errors', $val);
295                        return true;
296
297                    case 'log_errors':
298                        ini_set('log_errors', true);
299                        return true;
300
301                    case 'log_directory':
302                        if (is_dir($val) && is_writable($val)) {
303                            ini_set('error_log', $val . '/' . $this->getParam('php_error_log'));
304                        }
305                        return true;
306                    }
307                }
308            }
309        }
310    }
311
312    /**
313     * Return the value of a parameter.
314     *
315     * @access  public
316     * @param   string  $param      The key of the parameter to return.
317     * @return  mixed               Parameter value, or null if not existing.
318     */
319    public function getParam($param=null)
320    {
321        if ($param === null) {
322            return $this->_params;
323        } else if (array_key_exists($param, $this->_params)) {
324            return $this->_params[$param];
325        } else {
326            return null;
327        }
328    }
329
330    /**
331     * Begin running this application.
332     *
333     * @access  public
334     * @author  Quinn Comendant <quinn@strangecode.com>
335     * @since   15 Jul 2005 00:32:21
336     */
337    public function start()
338    {
339        if ($this->running) {
340            return false;
341        }
342
343        // Error reporting.
344        ini_set('error_reporting', $this->getParam('error_reporting'));
345        ini_set('display_errors', $this->getParam('display_errors'));
346        ini_set('log_errors', true);
347        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
348            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
349        }
350
351        // Set character set to use for multi-byte string functions.
352        mb_internal_encoding($this->getParam('character_set'));
353        ini_set('default_charset', $this->getParam('character_set'));
354        switch (mb_strtolower($this->getParam('character_set'))) {
355        case 'utf-8' :
356            mb_language('uni');
357            break;
358
359        case 'iso-2022-jp' :
360            mb_language('ja');
361            break;
362
363        case 'iso-8859-1' :
364        default :
365            mb_language('en');
366            break;
367        }
368
369        /**
370         * 1. Start Database.
371         */
372
373        if (true === $this->getParam('enable_db')) {
374
375            // DB connection parameters taken from environment variables in the server httpd.conf file (readable only by root)

376            if (!empty($_SERVER['DB_SERVER']) && !$this->getParam('db_server')) {
377                $this->setParam(array('db_server' => $_SERVER['DB_SERVER']));
378            }
379            if (!empty($_SERVER['DB_NAME']) && !$this->getParam('db_name')) {
380                $this->setParam(array('db_name' => $_SERVER['DB_NAME']));
381            }
382            if (!empty($_SERVER['DB_USER']) && !$this->getParam('db_user')) {
383                $this->setParam(array('db_user' => $_SERVER['DB_USER']));
384            }
385            if (!empty($_SERVER['DB_PASS']) && !$this->getParam('db_pass')) {
386                $this->setParam(array('db_pass' => $_SERVER['DB_PASS']));
387            }
388
389            // DB credentials for CLI scripts stored in a JSON file with read rights given only to the user who will be executing the scripts: -r--------
390            // But not if all DB credentials have been defined already by other means.
391            if ($this->cli && (!$this->getParam('db_server') || !$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass'))) {
392                if (false !== $db_auth_file = stream_resolve_include_path($this->getParam('db_auth_file'))) {
393                    if (is_readable($db_auth_file)) {
394                        $this->setParam(json_decode(file_get_contents($db_auth_file), true));
395                    } else {
396                        $this->logMsg(sprintf('Unable to read DB auth file: %s', $db_auth_file), LOG_ALERT, __FILE__, __LINE__);
397                    }
398                } else {
399                    $this->logMsg(sprintf('DB auth file not found: %s', $this->getParam('db_auth_file')), LOG_ALERT, __FILE__, __LINE__);
400                }
401            }
402
403            // There will ever only be one instance of the DB object, and here is where it is instantiated.
404            require_once dirname(__FILE__) . '/DB.inc.php';
405            $this->db =& DB::getInstance();
406            $this->db->setParam(array(
407                'db_server' => $this->getParam('db_server'),
408                'db_name' => $this->getParam('db_name'),
409                'db_user' => $this->getParam('db_user'),
410                'db_pass' => $this->getParam('db_pass'),
411                'db_always_debug' => $this->getParam('db_always_debug'),
412                'db_debug' => $this->getParam('db_debug'),
413                'db_die_on_failure' => $this->getParam('db_die_on_failure'),
414            ));
415
416            // Connect to database.
417            $this->db->connect();
418        }
419
420
421        /**
422         * 2. Start PHP session.
423         */
424
425        // Use sessions if enabled and not a CLI script.
426        if (true === $this->getParam('enable_session') && !$this->cli) {
427
428            // Session parameters.
429            ini_set('session.gc_probability', 1);
430            ini_set('session.gc_divisor', 1000);
431            ini_set('session.gc_maxlifetime', 43200); // 12 hours
432            ini_set('session.use_cookies', $this->getParam('session_use_cookies'));
433            ini_set('session.use_trans_sid', false);
434            ini_set('session.entropy_file', '/dev/urandom');
435            ini_set('session.entropy_length', '512');
436            ini_set('session.cookie_httponly', true);
437            session_name($this->getParam('session_name'));
438
439            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
440                // Database session handling.
441                require_once dirname(__FILE__) . '/DBSessionHandler.inc.php';
442                $this->db_session = new DBSessionHandler($this->db, array(
443                    'db_table' => 'session_tbl',
444                    'create_table' => $this->getParam('db_create_tables'),
445                ));
446            }
447
448            // Start the session.
449            session_start();
450
451            if (!isset($_SESSION['_app'][$this->_ns])) {
452                // Access session data using: $_SESSION['...'].
453                // Initialize here _after_ session has started.
454                $_SESSION['_app'][$this->_ns] = array(
455                    'messages' => array(),
456                    'boomerang' => array(),
457                );
458            }
459        }
460
461
462        /**
463         * 3. Misc setup.
464         */
465
466        // Site URL will become something like http://host.name.tld (no ending slash)
467        // and is used whenever a URL need be used to the current site.
468        // Not available on CLI scripts obviously.
469        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) {
470            $this->setParam(array('site_url' => sprintf('%s://%s', (getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'))));
471        }
472
473        // Page URL will become a permalink to the current page.
474        // Also not available on CLI scripts obviously.
475        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) {
476            $this->setParam(array('page_url' => sprintf('%s://%s%s', (getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'), getenv('REQUEST_URI'))));
477        }
478
479        // In case site_email isn't set, use something halfway presentable.
480        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_email')) {
481            $this->setParam(array('site_email' => sprintf('no-reply@%s', getenv('HTTP_HOST'))));
482        }
483
484        // A key for calculating simple cryptographic signatures.
485        if (isset($_SERVER['SIGNING_KEY'])) {
486            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
487        }
488
489        // Character set. This should also be printed in the html header template.
490        if (!$this->cli) {
491            if (!headers_sent($h_file, $h_line)) {
492                header(sprintf('Content-type: %s; charset=%s', $this->getParam('content_type'), $this->getParam('character_set')));
493            } else {
494                $this->logMsg(sprintf('Unable to set Content-type; headers already sent (output started in %s : %s)', $h_file, $h_line), LOG_DEBUG, __FILE__, __LINE__);
495            }
496        }
497
498        // Cache control headers.
499        if (!$this->cli && false !== $this->getParam('http_cache_headers')) {
500            if (!headers_sent($h_file, $h_line)) {
501                if ($this->getParam('http_cache_headers') > 0) {
502                    // Allow HTTP caching, for this many seconds.
503                    header(sprintf('Cache-Control: no-transform, public, max-age=%d', $this->getParam('http_cache_headers')));
504                    header('Vary: Accept-Encoding');
505                } else {
506                    // Disallow HTTP caching entirely. http://stackoverflow.com/a/2068407
507                    header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
508                    header('Pragma: no-cache'); // HTTP 1.0.
509                    header('Expires: 0'); // Proxies.
510                }
511            } else {
512                $this->logMsg(sprintf('Unable to set Cache-Control; headers already sent (output started in %s : %s)', $h_file, $h_line), LOG_DEBUG, __FILE__, __LINE__);
513            }
514        }
515
516        // Set the version of the codebase we're using.
517        $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
518        $codebase_version = '';
519        if (is_readable($codebase_version_file) && !is_dir($codebase_version_file)) {
520            $codebase_version = trim(file_get_contents($codebase_version_file));
521            $this->setParam(array('codebase_version' => $codebase_version));
522            if (!$this->cli && $this->getParam('codebase_version')) {
523                if (!headers_sent($h_file, $h_line)) {
524                    header(sprintf('X-Codebase-Version: %s', $this->getParam('codebase_version')));
525                } else {
526                    $this->logMsg(sprintf('Unable to set X-Codebase-Version; headers already sent (output started in %s : %s)', $h_file, $h_line), LOG_DEBUG, __FILE__, __LINE__);
527                }
528            }
529        }
530
531        if (version_compare(PHP_VERSION, self::CODEBASE_MIN_PHP_VERSION, '<')) {
532            $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__);
533        }
534
535        // Set the application version if defined.
536        if (false !== $site_version_file = stream_resolve_include_path($this->getParam('site_version_file'))) {
537            if (mb_strpos($site_version_file, '.json') !== false) {
538                $version_json = json_decode(trim(file_get_contents($site_version_file)), true);
539                $site_version = isset($version_json['version']) ? $version_json['version'] : null;
540            } else {
541                $site_version = trim(file_get_contents($site_version_file));
542            }
543            $this->setParam(array('site_version' => $site_version));
544        }
545        if (!$this->cli && $this->getParam('site_version')) {
546            if (!headers_sent($h_file, $h_line)) {
547                header(sprintf('X-Site-Version: %s', $this->getParam('site_version')));
548            } else {
549                $this->logMsg(sprintf('Unable to set X-Site-Version; headers already sent (output started in %s : %s)', $h_file, $h_line), LOG_DEBUG, __FILE__, __LINE__);
550            }
551        }
552
553        // Unset environment variables we're done with.
554        unset($_SERVER['DB_SERVER'], $_SERVER['DB_NAME'], $_SERVER['DB_USER'], $_SERVER['DB_PASS'], $_SERVER['SIGNING_KEY']);
555
556        $this->running = true;
557        return true;
558    }
559
560    /**
561     * Stop running this application.
562     *
563     * @access  public
564     * @author  Quinn Comendant <quinn@strangecode.com>
565     * @since   17 Jul 2005 17:20:18
566     */
567    public function stop()
568    {
569        session_write_close();
570        $this->running = false;
571        $num_queries = 0;
572        if (is_a($this->db, 'DB') && true === $this->getParam('enable_db')) {
573            $num_queries = $this->db->numQueries();
574            $this->db->close();
575        }
576        $mem_current = memory_get_usage();
577        $mem_peak = memory_get_peak_usage();
578        $this->timer->stop('_app');
579        $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__);
580    }
581
582
583    /**
584     * Add a message to the session, which is printed in the header.
585     * Just a simple way to print messages to the user.
586     *
587     * @access public
588     *
589     * @param string $message The text description of the message.
590     * @param int    $type    The type of message: MSG_NOTICE,
591     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
592     * @param string $file    __FILE__.
593     * @param string $line    __LINE__.
594     */
595    public function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
596    {
597        $message = trim($message);
598
599        if (!$this->running) {
600            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
601            return false;
602        }
603
604        if (!$this->getParam('enable_session')) {
605            $this->logMsg(sprintf('Canceled %s, session not enabled.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
606            return false;
607        }
608
609        if ('' == trim($message)) {
610            $this->logMsg(sprintf('Raised message is an empty string.', null), LOG_NOTICE, __FILE__, __LINE__);
611            return false;
612        }
613
614        // Avoid duplicate full-stops..
615        $message = trim(preg_replace('/\.{2}$/', '.', $message));
616
617        // Save message in session under unique key to avoid duplicate messages.
618        $msg_id = md5($type . $message);
619        if (!isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id])) {
620            $_SESSION['_app'][$this->_ns]['messages'][$msg_id] = array(
621                'type'    => $type,
622                'message' => $message,
623                'file'    => $file,
624                'line'    => $line,
625                'count'   => (isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) : 1)
626            );
627        }
628
629        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
630            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__);
631        }
632
633        // Increment the counter for this message type.
634        $this->_raised_msg_counter[$type] += 1;
635    }
636
637    /*
638    * Returns the number of raised message (all, or by type) for the current script execution (this number may not match the total number of messages stored in session for multiple script executions)
639    *
640    * @access   public
641    * @param
642    * @return
643    * @author   Quinn Comendant <quinn@strangecode.com>
644    * @version  1.0
645    * @since    30 Apr 2015 17:13:03
646    */
647    public function getRaisedMessageCount($type='all')
648    {
649        if ('all' == $type) {
650            return array_sum($this->_raised_msg_counter);
651        } else if (isset($this->_raised_msg_counter[$type])) {
652            return $this->_raised_msg_counter[$type];
653        } else {
654            $this->logMsg(sprintf('Cannot return count of unknown raised message type: %s', $type), LOG_WARNING, __FILE__, __LINE__);
655            return false;
656        }
657    }
658
659    /**
660     * Returns an array of the raised messages.
661     *
662     * @access  public
663     * @return  array   List of messages in FIFO order.
664     * @author  Quinn Comendant <quinn@strangecode.com>
665     * @since   21 Dec 2005 13:09:20
666     */
667    public function getRaisedMessages()
668    {
669        if (!$this->running) {
670            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
671            return false;
672        }
673        return isset($_SESSION['_app'][$this->_ns]['messages']) ? $_SESSION['_app'][$this->_ns]['messages'] : array();
674    }
675
676    /**
677     * Resets the message list.
678     *
679     * @access  public
680     * @author  Quinn Comendant <quinn@strangecode.com>
681     * @since   21 Dec 2005 13:21:54
682     */
683    public function clearRaisedMessages()
684    {
685        if (!$this->running) {
686            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
687            return false;
688        }
689
690        $_SESSION['_app'][$this->_ns]['messages'] = array();
691    }
692
693    /**
694     * Prints the HTML for displaying raised messages.
695     *
696     * @param   string  $above    Additional message to print above error messages (e.g. "Oops!").
697     * @param   string  $below    Additional message to print below error messages (e.g. "Please fix and resubmit").
698     * @param   string  $print_gotohash_js  Print a line of javascript that scrolls the browser window down to view any error messages.
699     * @param   string  $hash     The #hashtag to scroll to.
700     * @access  public
701     * @author  Quinn Comendant <quinn@strangecode.com>
702     * @since   15 Jul 2005 01:39:14
703     */
704    public function printRaisedMessages($above='', $below='', $print_gotohash_js=false, $hash='sc-msg')
705    {
706
707        if (!$this->running) {
708            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
709            return false;
710        }
711
712        $messages = $this->getRaisedMessages();
713        if (!empty($messages)) {
714            ?><div id="sc-msg" class="sc-msg"><?php
715            if ('' != $above) {
716                ?><div class="sc-above"><?php echo oTxt($above); ?></div><?php
717            }
718            foreach ($messages as $m) {
719                if (error_reporting() > 0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) {
720                    echo "\n<!-- [" . $m['file'] . ' : ' . $m['line'] . '] -->';
721                }
722                switch ($m['type']) {
723                case MSG_ERR:
724                    echo '<div data-alert class="sc-msg-error alert-box alert">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
725                    break;
726
727                case MSG_WARNING:
728                    echo '<div data-alert class="sc-msg-warning alert-box warning">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
729                    break;
730
731                case MSG_SUCCESS:
732                    echo '<div data-alert class="sc-msg-success alert-box success">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
733                    break;
734
735                case MSG_NOTICE:
736                default:
737                    echo '<div data-alert class="sc-msg-notice alert-box info">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
738                    break;
739                }
740            }
741            if ('' != $below) {
742                ?><div class="sc-below"><?php echo oTxt($below); ?></div><?php
743            }
744            ?></div><?php
745            if ($print_gotohash_js) {
746                ?>
747                <script type="text/javascript">
748                /* <![CDATA[ */
749                window.location.hash = '#<?php echo urlencode($hash); ?>';
750                /* ]]> */
751                </script>
752                <?php
753            }
754        }
755        $this->clearRaisedMessages();
756    }
757
758    /**
759     * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are
760     * not repeated but printed once with count. Log events that match a sendable channel (email or SMS)
761     * are sent once per 'log_multiple_timeout' setting (to avoid a flood of error emails).
762     *
763     * @access public
764     * @param string $message   The text description of the message.
765     * @param int    $priority  The type of message priority (in descending order):
766     *                          LOG_EMERG     0 system is unusable
767     *                          LOG_ALERT     1 action must be taken immediately
768     *                          LOG_CRIT      2 critical conditions
769     *                          LOG_ERR       3 error conditions
770     *                          LOG_WARNING   4 warning conditions
771     *                          LOG_NOTICE    5 normal, but significant, condition
772     *                          LOG_INFO      6 informational message
773     *                          LOG_DEBUG     7 debug-level message
774     * @param string $file      The file where the log event occurs.
775     * @param string $line      The line of the file where the log event occurs.
776     * @param string $url       The URL where the log event occurs ($_SERVER['REQUEST_URI'] will be used if left null).
777     */
778    public function logMsg($message, $priority=LOG_INFO, $file=null, $line=null, $url=null)
779    {
780        static $previous_events = array();
781
782        // If priority is not specified, assume the worst.
783        if (!$this->logPriorityToString($priority)) {
784            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
785            $priority = LOG_EMERG;
786        }
787
788        // In case __FILE__ and __LINE__ are not provided, note that fact.
789        $file = '' == $file ? 'unknown-file' : $file;
790        $line = '' == $line ? 'unknown-line' : $line;
791
792        // Get the URL, or used the provided value.
793        if (!isset($url)) {
794            $url = isset($_SERVER['REQUEST_URI']) ? mb_substr($_SERVER['REQUEST_URI'], 0, $this->getParam('log_message_max_length')) : '';
795        }
796
797        // If log file is not specified, don't log to a file.
798        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
799            $this->setParam(array('log_file_priority' => false));
800            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
801            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
802        }
803
804        // Before we get any further, let's see if ANY log events are configured to be reported.
805        if ((false === $this->getParam('log_file_priority') || $priority > $this->getParam('log_file_priority'))
806        && (false === $this->getParam('log_email_priority') || $priority > $this->getParam('log_email_priority'))
807        && (false === $this->getParam('log_sms_priority') || $priority > $this->getParam('log_sms_priority'))
808        && (false === $this->getParam('log_screen_priority') || $priority > $this->getParam('log_screen_priority'))) {
809            // This event would not be recorded, skip it entirely.
810            return false;
811        }
812
813        // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>.
814        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow);
815        $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
816
817        // Serialize multi-line messages.
818        $message = preg_replace('/\s+/m', ' ', trim($message));
819
820        // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times.
821        $msg_id = md5($message . $priority . $file . $line);
822        if ($this->getParam('log_ignore_repeated_events') && isset($previous_events[$msg_id])) {
823            $previous_events[$msg_id]++;
824            if ($previous_events[$msg_id] == 2) {
825                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
826            }
827            return false;
828        } else {
829            $previous_events[$msg_id] = 1;
830        }
831
832        // For email and SMS notification types use "lock" files to prevent sending email and SMS notices ad infinitum.
833        if ((false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority'))
834        || (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority'))) {
835            // This event will generate a "send" notification. Prepare lock file.
836            $site_hash = md5(empty($_SERVER['SERVER_NAME']) ? $_SERVER['SCRIPT_FILENAME'] : $_SERVER['SERVER_NAME']);
837            $lock_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/";
838            // Just use the file and line for the msg_id to limit the number of possible messages
839            // (the message string itself shan't be used as it may contain innumerable combinations).
840            $lock_file = $lock_dir . md5($file . ':' . $line);
841            if (!is_dir($lock_dir)) {
842                mkdir($lock_dir);
843            }
844            $send_notifications = true;
845            if (is_file($lock_file)) {
846                $msg_last_sent = filectime($lock_file);
847                // Has this message been sent more recently than the timeout?
848                if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) {
849                    // This message was already sent recently.
850                    $send_notifications = false;
851                } else {
852                    // Timeout has expired; send notifications again and reset timeout.
853                    touch($lock_file);
854                }
855            } else {
856                touch($lock_file);
857            }
858        }
859
860        // Make sure to log in the system's locale.
861        $locale = setlocale(LC_TIME, 0);
862        setlocale(LC_TIME, 'C');
863
864        // Data to be stored for a log event.
865        $event = array(
866            'date'      => date('Y-m-d H:i:s'),
867            'remote ip' => getRemoteAddr(),
868            'pid'       => getmypid(),
869            'type'      => $this->logPriorityToString($priority),
870            'file:line' => "$file : $line",
871            'url'       => $url,
872            'message'   => mb_substr($message, 0, $this->getParam('log_message_max_length')),
873        );
874        // Here's a shortened version of event data.
875        $event_short = $event;
876        $event_short['url'] = truncate($event_short['url'], 120);
877
878        // Restore original locale.
879        setlocale(LC_TIME, $locale);
880
881        // FILE ACTION
882        if (false !== $this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
883            $event_str = '[' . join('] [', $event_short) . ']';
884            error_log("$event_str\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
885        }
886
887        // EMAIL ACTION
888        if (false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority') && $send_notifications) {
889            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
890            $subject = sprintf('[%s %s] %s', $hostname, $event['type'], mb_substr($event['message'], 0, 64));
891            $email_msg = sprintf("A log event of type '%s' occurred on %s\n\n", $event['type'], $hostname);
892            $headers = 'From: ' . $this->getParam('site_email');
893            foreach ($event as $k=>$v) {
894                $email_msg .= sprintf("%-16s %s\n", $k, $v);
895            }
896            $email_msg .= sprintf("%-16s %s\n", 'codebase version', $this->getParam('codebase_version'));
897            $email_msg .= sprintf("%-16s %s\n", 'site version', $this->getParam('site_version'));
898            mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers);
899        }
900
901        // SMS ACTION
902        if (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority') && $send_notifications) {
903            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
904            $subject = sprintf('[%s %s]', $hostname, $priority);
905            $sms_msg = sprintf('%s [%s:%s]', mb_substr($event_short['message'], 0, 64), basename($file), $line);
906            $headers = 'From: ' . $this->getParam('site_email');
907            mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers);
908        }
909
910        // SCREEN ACTION
911        if (false !== $this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
912            file_put_contents('php://stderr', "[{$event['type']}] [{$event['message']}]\n", FILE_APPEND);
913        }
914
915        return true;
916    }
917
918    /**
919     * Returns the string representation of a LOG_* integer constant.
920     * Updated: also returns the LOG_* integer constant if passed a string log value ('info' returns 6).
921     *
922     * @param int  $priority  The LOG_* integer constant (to return the string name), or a string name of a log priority to return the integer LOG_* value..
923     *
924     * @return                The string representation of $priority (if integer given), or integer representation (if string given).
925     */
926    public function logPriorityToString($priority) {
927        $priorities = array(
928            LOG_EMERG   => 'emergency',
929            LOG_ALERT   => 'alert',
930            LOG_CRIT    => 'critical',
931            LOG_ERR     => 'error',
932            LOG_WARNING => 'warning',
933            LOG_NOTICE  => 'notice',
934            LOG_INFO    => 'info',
935            LOG_DEBUG   => 'debug'
936        );
937        if (isset($priorities[$priority])) {
938            return $priorities[$priority];
939        } else if (is_string($priority) && false !== ($key = array_search($priority, $priorities))) {
940            return $key;
941        } else {
942            return false;
943        }
944    }
945
946    /**
947     * Forcefully set a query argument even if one currently exists in the request.
948     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
949     * to hidden input values (via printHiddenSession()).
950     *
951     * @access  public
952     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to save.
953     * @param   mixed   $val        The new value of the argument key.
954     * @author  Quinn Comendant <quinn@strangecode.com>
955     * @since   13 Oct 2007 11:34:51
956     */
957    public function setQuery($query_key, $val)
958    {
959        if (!is_array($query_key)) {
960            $query_key = array($query_key);
961        }
962        foreach ($query_key as $k) {
963            // Set the value of the specified query argument into the _carry_queries array.
964            $this->_carry_queries[$k] = $val;
965        }
966    }
967
968    /**
969     * Specify which query arguments will be carried persistently between requests.
970     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
971     * to hidden input values (via printHiddenSession()).
972     *
973     * @access  public
974     * @param   mixed   $query_key   The key (or keys, as an array) of the query argument to save.
975     * @param   mixed   $default    If the key is not available, set to this default value.
976     * @author  Quinn Comendant <quinn@strangecode.com>
977     * @since   14 Nov 2005 19:24:52
978     */
979    public function carryQuery($query_key, $default=false)
980    {
981        if (!is_array($query_key)) {
982            $query_key = array($query_key);
983        }
984        foreach ($query_key as $k) {
985            // If not already set, and there is a non-empty value provided in the request...
986            if (isset($k) && '' != $k && !isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) {
987                // Copy the value of the specified query argument into the _carry_queries array.
988                $this->_carry_queries[$k] = getFormData($k, $default);
989                $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__);
990            }
991        }
992    }
993
994    /**
995     * dropQuery() is the opposite of carryQuery(). The specified value will not appear in
996     * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in.
997     *
998     * @access  public
999     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to remove.
1000     * @param   bool    $unset      Remove any values set in the request matching the given $query_key.
1001     * @author  Quinn Comendant <quinn@strangecode.com>
1002     * @since   18 Jun 2007 20:57:29
1003     */
1004    public function dropQuery($query_key, $unset=false)
1005    {
1006        if (!is_array($query_key)) {
1007            $query_key = array($query_key);
1008        }
1009        foreach ($query_key as $k) {
1010            if (array_key_exists($k, $this->_carry_queries)) {
1011                // Remove the value of the specified query argument from the _carry_queries array.
1012                $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__);
1013                unset($this->_carry_queries[$k]);
1014            }
1015            if ($unset && (isset($_REQUEST) && array_key_exists($k, $_REQUEST))) {
1016                unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]);
1017            }
1018        }
1019    }
1020
1021    /**
1022     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
1023     * keys and values, including optional queries. This allows mindless retention
1024     * of query arguments across page requests. If cookies are not
1025     * used and session_use_trans_sid=true the session id will be propagated in the URL.
1026     *
1027     * @param  string $url              The initial url
1028     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
1029     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
1030     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
1031     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
1032     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
1033     *
1034     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
1035     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
1036     *                                     header('Location...') redirections.
1037     *
1038     * @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.
1039     * @return string url with attached queries and, if not using cookies, the session id
1040     */
1041    public function url($url, $carry_args=null, $always_include_sid=false, $include_csrf_token=false)
1042    {
1043        if (!$this->running) {
1044            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1045            return false;
1046        }
1047
1048        if ($this->getParam('csrf_token_enabled') && $include_csrf_token) {
1049            // Include the csrf_token as a carried query argument.
1050            // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken()
1051            $carry_args = is_array($carry_args) ? $carry_args : array();
1052            $carry_args = array_merge($carry_args, array($this->getParam('csrf_token_name') => $this->getCSRFToken()));
1053        }
1054
1055        // Get any provided query arguments to include in the final URL.
1056        // If FALSE is a provided here, DO NOT carry the queries.
1057        $do_carry_queries = true;
1058        $one_time_carry_queries = array();
1059        if (!is_null($carry_args)) {
1060            if (is_array($carry_args)) {
1061                if (!empty($carry_args)) {
1062                    foreach ($carry_args as $key=>$arg) {
1063                        // Get query from appropriate source.
1064                        if (false === $arg) {
1065                            $do_carry_queries = false;
1066                        } else if (false !== getFormData($arg, false)) {
1067                            $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
1068                        } else if (!is_numeric($key) && '' != $arg) {
1069                            $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
1070                        }
1071                    }
1072                }
1073            } else if (false !== getFormData($carry_args, false)) {
1074                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
1075            } else if (false === $carry_args) {
1076                $do_carry_queries = false;
1077            }
1078        }
1079
1080        // Get the first delimiter that is needed in the url.
1081        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
1082
1083        $q = '';
1084        if ($do_carry_queries) {
1085            // Join the global _carry_queries and local one_time_carry_queries.
1086            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
1087            foreach ($query_args as $key=>$val) {
1088                // Avoid indexed-array query params because in a URL array param keys should all match.
1089                // I.e, we want to use `array[]=A&array[]=B` instead of `array[0]=A&array[1]=B`.
1090                $key = preg_replace('/\[\d+\]$/', '[]', $key);
1091                // Check value is set and value does not already exist in the url.
1092                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
1093                    $q .= $delim . $key . '=' . $val;
1094                    $delim = ini_get('arg_separator.output');
1095                }
1096            }
1097        }
1098
1099        // Pop off any named anchors to push them back on after appending additional query args.
1100        $parts = explode('#', $url, 2);
1101        $url = $parts[0];
1102        $anchor = isset($parts[1]) ? $parts[1] : '';
1103
1104        // $anchor =
1105
1106        // Include the necessary SID if the following is true:
1107        // - no cookie in http request OR cookies disabled in App
1108        // - sessions are enabled
1109        // - the link stays on our site
1110        // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
1111        // OR
1112        // - 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)
1113        // AND
1114        // - the SID is not already in the query.
1115        if (
1116            (
1117                (
1118                    (
1119                        !isset($_COOKIE[session_name()])
1120                        || !$this->getParam('session_use_cookies')
1121                    )
1122                    && $this->getParam('session_use_trans_sid')
1123                    && $this->getParam('enable_session')
1124                    && isMyDomain($url)
1125                    && (
1126                        !ini_get('session.use_trans_sid')
1127                        || preg_match('!^(http|https)://!i', $url)
1128                    )
1129                )
1130                || $always_include_sid
1131            )
1132            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
1133        ) {
1134            $url = sprintf('%s%s%s%s=%s%s', $url, $q, $delim, session_name(), session_id(), ('' == $anchor ? '' : "#$anchor"));
1135        } else {
1136            $url = sprintf('%s%s%s', $url, $q, ('' == $anchor ? '' : "#$anchor"));
1137        }
1138
1139        return $url;
1140    }
1141
1142    /**
1143     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
1144     *
1145     * @access  public
1146     * @param   (see param reference for url() method)
1147     * @return  string          URL passed through $app->url() with ampersands transformed to $amp;
1148     * @author  Quinn Comendant <quinn@strangecode.com>
1149     * @since   09 Dec 2005 17:58:45
1150     */
1151    public function oHREF($url, $carry_args=null, $always_include_sid=false, $include_csrf_token=false)
1152    {
1153        // Process the URL.
1154        $url = $this->url($url, $carry_args, $always_include_sid, $include_csrf_token);
1155
1156        // Replace any & not followed by an html or unicode entity with its &amp; equivalent.
1157        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
1158
1159        return $url;
1160    }
1161
1162    /**
1163     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
1164     * as hidden form elements for GET_VARS that might be in use.
1165     *
1166     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
1167     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
1168     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
1169     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
1170     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
1171     * @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.
1172     */
1173    public function printHiddenSession($carry_args=null, $include_csrf_token=false)
1174    {
1175        if (!$this->running) {
1176            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1177            return false;
1178        }
1179
1180        // Get any provided query arguments to include in the final hidden form data.
1181        // If FALSE is a provided here, DO NOT carry the queries.
1182        $do_carry_queries = true;
1183        $one_time_carry_queries = array();
1184        if (!is_null($carry_args)) {
1185            if (is_array($carry_args)) {
1186                if (!empty($carry_args)) {
1187                    foreach ($carry_args as $key=>$arg) {
1188                        // Get query from appropriate source.
1189                        if (false === $arg) {
1190                            $do_carry_queries = false;
1191                        } else if (false !== getFormData($arg, false)) {
1192                            $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
1193                        } else if (!is_numeric($key) && '' != $arg) {
1194                            $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
1195                        }
1196                    }
1197                }
1198            } else if (false !== getFormData($carry_args, false)) {
1199                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
1200            } else if (false === $carry_args) {
1201                $do_carry_queries = false;
1202            }
1203        }
1204
1205        // For each existing request value, we create a hidden input to carry it through a form.
1206        if ($do_carry_queries) {
1207            // Join the global _carry_queries and local one_time_carry_queries.
1208            // urlencode is not used here, not for form data!
1209            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
1210            foreach ($query_args as $key => $val) {
1211                if (is_array($val)) {
1212                    foreach ($val as $subval) {
1213                        if ('' != $key && '' != $subval) {
1214                            printf('<input type="hidden" name="%s[]" value="%s" />', $key, $subval);
1215                        }
1216                    }
1217                } else if ('' != $key && '' != $val) {
1218                    printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
1219                }
1220            }
1221            unset($query_args, $key, $val, $subval);
1222        }
1223
1224        // Include the SID if:
1225        // * cookies are disabled
1226        // * the system isn't automatically adding trans_sid
1227        // * the session is enabled
1228        // * and we're configured to use trans_sid
1229        if (!isset($_COOKIE[session_name()])
1230        && !ini_get('session.use_trans_sid')
1231        && $this->getParam('enable_session')
1232        && $this->getParam('session_use_trans_sid')
1233        ) {
1234            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
1235        }
1236
1237        // Include the csrf_token in the form.
1238        // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken()
1239        if ($this->getParam('csrf_token_enabled') && $include_csrf_token) {
1240            printf('<input type="hidden" name="%s" value="%s" />', $this->getParam('csrf_token_name'), $this->getCSRFToken());
1241        }
1242    }
1243
1244    /*
1245    * 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
1246    *
1247    * @access   public
1248    * @param    string  $url    URL to media (e.g., /foo.js)
1249    * @return   string          URL with cache-busting version appended (/foo.js?v=1234567890)
1250    * @author   Quinn Comendant <quinn@strangecode.com>
1251    * @version  1.0
1252    * @since    03 Sep 2014 22:40:24
1253    */
1254    public function cacheBustURL($url)
1255    {
1256        // Get the first delimiter that is needed in the url.
1257        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
1258        $v = crc32($this->getParam('codebase_version') . '|' . $this->getParam('site_version'));
1259        return sprintf('%s%sv=%s', $url, $delim, $v);
1260    }
1261
1262    /*
1263    * Generate a csrf_token if it doesn't exist or is expired, save it to the session and return its value.
1264    * Otherwise just return the current token.
1265    * Details on the synchronizer token pattern:
1266    * https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern
1267    *
1268    * @access   public
1269    * @return   string The new or current csrf_token
1270    * @author   Quinn Comendant <quinn@strangecode.com>
1271    * @version  1.0
1272    * @since    15 Nov 2014 17:57:17
1273    */
1274    public function getCSRFToken()
1275    {
1276        if (!isset($_SESSION['_app'][$this->_ns]['csrf_token']) || (removeSignature($_SESSION['_app'][$this->_ns]['csrf_token']) + $this->getParam('csrf_token_timeout') < time())) {
1277            // No token, or token is expired; generate one and return it.
1278            return $_SESSION['_app'][$this->_ns]['csrf_token'] = addSignature(time(), null, 64);
1279        }
1280        // Current token is not expired; return it.
1281        return $_SESSION['_app'][$this->_ns]['csrf_token'];
1282    }
1283
1284    /*
1285    * Compares the given csrf_token with the current or previous one saved in the session.
1286    *
1287    * @access   public
1288    * @param    string  $user_submitted_csrf_token The user-submitted token to compare with the session token.
1289    * @param    string  $csrf_token     The token to compare with the session token.
1290    * @return   bool    True if the tokens match, false otherwise.
1291    * @author   Quinn Comendant <quinn@strangecode.com>
1292    * @version  1.0
1293    * @since    15 Nov 2014 18:06:55
1294    */
1295    public function verifyCSRFToken($user_submitted_csrf_token)
1296    {
1297
1298        if (!$this->getParam('csrf_token_enabled')) {
1299            $this->logMsg(sprintf('%s called, but csrf_token_enabled=false', __METHOD__), LOG_ERR, __FILE__, __LINE__);
1300            return true;
1301        }
1302        if ('' == trim($user_submitted_csrf_token)) {
1303            $this->logMsg(sprintf('Empty string failed CSRF verification.', null), LOG_NOTICE, __FILE__, __LINE__);
1304            return false;
1305        }
1306        if (!verifySignature($user_submitted_csrf_token, null, 64)) {
1307            $this->logMsg(sprintf('Input failed CSRF verification (invalid signature in %s).', $user_submitted_csrf_token), LOG_WARNING, __FILE__, __LINE__);
1308            return false;
1309        }
1310        $csrf_token = $this->getCSRFToken();
1311        if ($user_submitted_csrf_token != $csrf_token) {
1312            $this->logMsg(sprintf('Input failed CSRF verification (%s not in %s).', $user_submitted_csrf_token, $csrf_token), LOG_WARNING, __FILE__, __LINE__);
1313            return false;
1314        }
1315        $this->logMsg(sprintf('Verified CSRF token %s', $user_submitted_csrf_token), LOG_DEBUG, __FILE__, __LINE__);
1316        return true;
1317    }
1318
1319    /*
1320    * Bounce user if they submit a token that doesn't match the one saved in the session.
1321    * Because this function calls dieURL() it must be called before any other HTTP header output.
1322    *
1323    * @access   public
1324    * @param    string  $message    Optional message to display to the user (otherwise default message will display). Set to an empty string to display no message.
1325    * @param    int    $type    The type of message: MSG_NOTICE,
1326    *                           MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
1327    * @param    string $file    __FILE__.
1328    * @param    string $line    __LINE__.
1329    * @return   void
1330    * @author   Quinn Comendant <quinn@strangecode.com>
1331    * @version  1.0
1332    * @since    15 Nov 2014 18:10:17
1333    */
1334    public function requireValidCSRFToken($message=null, $type=MSG_NOTICE, $file=null, $line=null)
1335    {
1336        if (!$this->verifyCSRFToken(getFormData($this->getParam('csrf_token_name')))) {
1337            $message = isset($message) ? $message : _("Sorry, the form token expired. Please try again.");
1338            $this->raiseMsg($message, $type, $file, $line);
1339            $this->dieBoomerangURL();
1340        }
1341    }
1342
1343    /**
1344     * Uses an http header to redirect the client to the given $url. If sessions are not used
1345     * and the session is not already defined in the given $url, the SID is appended as a URI query.
1346     * As with all header generating functions, make sure this is called before any other output.
1347     *
1348     * @param   string  $url                    The URL the client will be redirected to.
1349     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
1350     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
1351     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
1352     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
1353     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
1354     * @param   bool    $always_include_sid     Force session id to be added to Location header.
1355     */
1356    public function dieURL($url, $carry_args=null, $always_include_sid=false)
1357    {
1358        if (!$this->running) {
1359            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1360            return false;
1361        }
1362
1363        if (!$url) {
1364            // If URL is not specified, use the redirect_home_url.
1365            $url = $this->getParam('redirect_home_url');
1366        }
1367
1368        if (preg_match('!^/!', $url)) {
1369            // If relative URL is given, prepend correct local hostname.
1370            $scheme = getenv('HTTPS') ? 'https' : 'http';
1371            $host = getenv('HTTP_HOST');
1372            $url = sprintf('%s://%s%s', $scheme, $host, $url);
1373        }
1374
1375        $url = $this->url($url, $carry_args, $always_include_sid);
1376
1377        // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP?
1378        if (!headers_sent($h_file, $h_line)) {
1379            header(sprintf('Location: %s', $url));
1380            $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
1381        } else {
1382            // Fallback: die using meta refresh instead.
1383            printf('<meta http-equiv="refresh" content="0;url=%s" />', $url);
1384            $this->logMsg(sprintf('dieURL (refresh): %s; headers already sent (output started in %s : %s)', $url, $h_file, $h_line), LOG_NOTICE, __FILE__, __LINE__);
1385        }
1386
1387        // End application.
1388        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
1389        $this->stop();
1390        die;
1391    }
1392
1393    /*
1394    * Redirects a user by calling $app->dieURL(). It will use:
1395    * 1. the stored boomerang URL, it it exists
1396    * 2. a specified $default_url, it it exists
1397    * 3. the referring URL, it it exists.
1398    * 4. redirect_home_url configuration variable.
1399    *
1400    * @access   public
1401    * @param    string  $id             Identifier for this script.
1402    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->url()).
1403    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
1404    * @param    bool    $queryless_referrer_comparison   Exclude the URL query from the refererIsMe() comparison.
1405    * @return   bool                    False if the session is not running. No return otherwise.
1406    * @author   Quinn Comendant <quinn@strangecode.com>
1407    * @since    31 Mar 2006 19:17:00
1408    */
1409    public function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false)
1410    {
1411        if (!$this->running) {
1412            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1413            return false;
1414        }
1415
1416        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
1417        if ($this->validBoomerangURL($id, true)) {
1418            if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1419                $url = $_SESSION['_app'][$this->_ns]['boomerang'][$id]['url'];
1420                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1421            } else {
1422                $url = end($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1423                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1424            }
1425            // Delete stored boomerang.
1426            $this->deleteBoomerangURL($id);
1427        } else if (isset($default_url)) {
1428            $url = $default_url;
1429        } else if (!refererIsMe(true === $queryless_referrer_comparison) && '' != ($url = getenv('HTTP_REFERER'))) {
1430            // Ensure that the redirecting page is not also the referrer.
1431            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1432        } else {
1433            // If URL is not specified, use the redirect_home_url.
1434            $url = $this->getParam('redirect_home_url');
1435            $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1436        }
1437
1438        // A redirection will never happen immediately twice. Set the time so we can ensure this doesn't happen.
1439        $_SESSION['_app'][$this->_ns]['boomerang_last_redirect_time'] = time();
1440
1441        // Do it.
1442        $this->dieURL($url, $carry_args);
1443    }
1444
1445    /**
1446     * Set the URL to return to when $app->dieBoomerangURL() is called.
1447     *
1448     * @param string  $url  A fully validated URL.
1449     * @param bool  $id     An identification tag for this url.
1450     * FIXME: url garbage collection?
1451     */
1452    public function setBoomerangURL($url=null, $id=null)
1453    {
1454        if (!$this->running) {
1455            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1456            return false;
1457        }
1458
1459        if ('' != $url && is_string($url)) {
1460            // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion).
1461            $url = preg_replace(array('/([&?])boomerang=[^&?]+[&?]?/', '/[&?]$/'), array('$1', ''), $url);
1462
1463            if (isset($_SESSION['_app'][$this->_ns]['boomerang']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']) && !empty($_SESSION['_app'][$this->_ns]['boomerang'])) {
1464                // If the ID already exists in the boomerang array, delete it.
1465                foreach (array_keys($_SESSION['_app'][$this->_ns]['boomerang']) as $existing_id) {
1466                    // $existing_id could be null if existing boomerang URL was set without an ID.
1467                    if ($existing_id === $id) {
1468                        $this->logMsg(sprintf('Deleted existing boomerang URL matching ID: %s=>%s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1469                        unset($_SESSION['_app'][$this->_ns]['boomerang'][$existing_id]);
1470                    }
1471                }
1472            }
1473
1474            // A redirection will never happen immediately after setting the boomerang URL.
1475            // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
1476            if (isset($id)) {
1477                $_SESSION['_app'][$this->_ns]['boomerang'][$id] = array(
1478                    'url' => $url,
1479                    'added_time' => time(),
1480                );
1481            } else {
1482                $_SESSION['_app'][$this->_ns]['boomerang'][] = array(
1483                    'url' => $url,
1484                    'added_time' => time(),
1485                );
1486            }
1487
1488            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1489            return true;
1490        } else {
1491            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
1492            return false;
1493        }
1494    }
1495
1496    /**
1497     * Return the URL set for the specified $id, or an empty string if one isn't set.
1498     *
1499     * @param string  $id     An identification tag for this url.
1500     */
1501    public function getBoomerangURL($id=null)
1502    {
1503        if (!$this->running) {
1504            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1505            return false;
1506        }
1507
1508        if (isset($id)) {
1509            if (isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1510                return $_SESSION['_app'][$this->_ns]['boomerang'][$id]['url'];
1511            } else {
1512                return '';
1513            }
1514        } else if (isset($_SESSION['_app'][$this->_ns]['boomerang']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']) && !empty($_SESSION['_app'][$this->_ns]['boomerang'])) {
1515            return end($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1516        } else {
1517            return false;
1518        }
1519    }
1520
1521    /**
1522     * Delete the URL set for the specified $id.
1523     *
1524     * @param string  $id     An identification tag for this url.
1525     */
1526    public function deleteBoomerangURL($id=null)
1527    {
1528        if (!$this->running) {
1529            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1530            return false;
1531        }
1532
1533        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1534            $url = $this->getBoomerangURL($id);
1535            unset($_SESSION['_app'][$this->_ns]['boomerang'][$id]);
1536        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang'])) {
1537            $url = array_pop($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1538        }
1539        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1540    }
1541
1542    /**
1543     * Check if a valid boomerang URL value has been set. A boomerang URL is considered
1544     * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds.
1545     *
1546     * @return bool  True if it is set and valid, false otherwise.
1547     */
1548    public function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
1549    {
1550        if (!$this->running) {
1551            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1552            return false;
1553        }
1554
1555        if (!isset($_SESSION['_app'][$this->_ns]['boomerang']) || !is_array($_SESSION['_app'][$this->_ns]['boomerang']) || empty($_SESSION['_app'][$this->_ns]['boomerang'])) {
1556            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set, not an array, or empty.', $id), LOG_DEBUG, __FILE__, __LINE__);
1557            return false;
1558        }
1559
1560        $url = '';
1561        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1562            $url = $_SESSION['_app'][$this->_ns]['boomerang'][$id]['url'];
1563            $added_time = $_SESSION['_app'][$this->_ns]['boomerang'][$id]['added_time'];
1564        } else if (!isset($id) || $use_nonspecificboomerang) {
1565            // Use most recent, non-specific boomerang if available.
1566            $url = end($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1567            $added_time = end($_SESSION['_app'][$this->_ns]['boomerang'])['added_time'];
1568        }
1569
1570        if ('' == trim($url)) {
1571            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
1572            return false;
1573        }
1574
1575        if ($url == absoluteMe()) {
1576            // The URL we are directing to is the current page.
1577            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1578            return false;
1579        }
1580
1581        // Last redirect time is the time stamp of the last boomerangURL redirection, if any. A boomerang redirection should always occur at least several seconds after the last boomerang redirect (time it takes to load a page and receive user interaction).
1582        $boomerang_last_redirect_time = isset($_SESSION['_app'][$this->_ns]['boomerang_last_redirect_time']) ? $_SESSION['_app'][$this->_ns]['boomerang_last_redirect_time'] : null;
1583        if (isset($boomerang_last_redirect_time) && $boomerang_last_redirect_time >= (time() - 2)) {
1584            // Last boomerang direction was less than 2 seconds ago.
1585            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_last_redirect_time too short: %s seconds', $id, time() - $boomerang_last_redirect_time), LOG_DEBUG, __FILE__, __LINE__);
1586            return false;
1587        }
1588
1589        if (isset($added_time) && $added_time < (time() - 72000)) {
1590            // Last boomerang direction was more than 20 hours ago.
1591            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, added_time too old: %s seconds', $id, time() - $added_time), LOG_DEBUG, __FILE__, __LINE__);
1592            // Delete this defunct boomerang.
1593            $this->deleteBoomerangURL($id);
1594            return false;
1595        }
1596
1597        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1598        return true;
1599    }
1600
1601    /**
1602     * Force the user to connect via https (port 443) by redirecting them to
1603     * the same page but with https.
1604     */
1605    public function sslOn()
1606    {
1607        if (function_exists('apache_get_modules')) {
1608            $modules = apache_get_modules();
1609        } else {
1610            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1611            $modules = array('mod_ssl');
1612        }
1613
1614        if (!getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1615            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1616            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1617            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1618        }
1619    }
1620
1621    /**
1622     * This function has changed to do nothing. There is no reason to prefer a non-SSL connection, and doing so may result in a redirect loop.
1623     */
1624    public function sslOff()
1625    {
1626        $app =& App::getInstance();
1627        $app->logMsg(sprintf('sslOff was called and ignored.', null), LOG_INFO, __FILE__, __LINE__);
1628    }
1629
1630    /*
1631    * Sets a cookie, with error checking and some sane defaults.
1632    *
1633    * @access   public
1634    * @param    string  $name       The name of the cookie.
1635    * @param    string  $value      The value of the cookie.
1636    * @param    string  $expire     The time the cookie expires, as a unix timestamp or string value passed to strtotime.
1637    * @param    string  $path       The path on the server in which the cookie will be available on.
1638    * @param    string  $domain     The domain that the cookie is available to.
1639    * @param    bool    $secure     Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
1640    * @param    bool    $httponly   When TRUE the cookie will be made accessible only through the HTTP protocol (makes cookies unreadable to javascript).
1641    * @return   bool                True on success, false on error.
1642    * @author   Quinn Comendant <quinn@strangecode.com>
1643    * @version  1.0
1644    * @since    02 May 2014 16:36:34
1645    */
1646    public function setCookie($name, $value, $expire='+10 years', $path='/', $domain=null, $secure=null, $httponly=null)
1647    {
1648        if (!is_scalar($name)) {
1649            $this->logMsg(sprintf('Cookie name must be scalar, is not: %s', getDump($name)), LOG_NOTICE, __FILE__, __LINE__);
1650            return false;
1651        }
1652        if (!is_scalar($value)) {
1653            $this->logMsg(sprintf('Cookie "%s" value must be scalar, is not: %s', $name, getDump($value)), LOG_NOTICE, __FILE__, __LINE__);
1654            return false;
1655        }
1656
1657        // Defaults.
1658        $expire = (is_numeric($expire) ? $expire : (is_string($expire) ? strtotime($expire) : $expire));
1659        $secure = $secure ?: (getenv('HTTPS') && $this->getParam('ssl_enabled'));
1660        $httponly = $httponly ?: true;
1661
1662        // Make sure the expiration date is a valid 32bit integer.
1663        if (is_int($expire) && $expire > 2147483647) {
1664            $this->logMsg(sprintf('Cookie "%s" expire time exceeds a 32bit integer (%s)', $key, date('r', $expire)), LOG_NOTICE, __FILE__, __LINE__);
1665        }
1666
1667        // Measure total cookie length and warn if larger than max recommended size of 4093.
1668        // https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key
1669        // The date the header name include 51 bytes: Set-Cookie: ; expires=Fri, 03-May-2024 00:04:47 GMT
1670        $cookielen = strlen($name . $value . $path . $domain . ($secure ? '; secure' : '') . ($httponly ? '; httponly' : '')) + 51;
1671        if ($cookielen > 4093) {
1672            $this->logMsg(sprintf('Cookie "%s" has a size greater than 4093 bytes (is %s bytes)', $key, $cookielen), LOG_NOTICE, __FILE__, __LINE__);
1673        }
1674
1675        // Ensure PHP version allow use of httponly.
1676        if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
1677            $ret = setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
1678        } else {
1679            $ret = setcookie($name, $value, $expire, $path, $domain, $secure);
1680        }
1681
1682        if (false === $ret) {
1683            $this->logMsg(sprintf('Failed to set cookie (%s=%s) probably due to output before headers.', $name, $value), LOG_NOTICE, __FILE__, __LINE__);
1684        }
1685        return $ret;
1686    }
1687} // End.
Note: See TracBrowser for help on using the repository browser.