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

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

Disable App::sslOn(). Better logging on Email::send() unreplaced variables. Fix the elusive 'Database table session_tbl has invalid columns' error.

File size: 77.9 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        // Strip line-endings from log messages.
198        'log_serialize' => true,
199
200        // Temporary files directory.
201        'tmp_dir' => '/tmp',
202
203        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
204        // Existing password hashes rely on the same key/salt being used to compare encryptions.
205        // Don't change this unless you know existing hashes or signatures will not be affected!
206        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
207
208        // Force getFormData, getPost, and getGet to always run dispelMagicQuotes() with stripslashes().
209        // This should be set to 'true' when using the codebase with Wordpress because
210        // WP forcefully adds slashes to all input despite the setting of magic_quotes_gpc.
211        'always_dispel_magicquotes' => false,
212    );
213
214    /**
215     * Constructor.
216     */
217    public function __construct($namespace='')
218    {
219        // Initialize default parameters.
220        $this->_params = array_merge($this->_params, array('namespace' => $namespace), $this->_param_defaults);
221
222        // Begin timing script.
223        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
224        $this->timer = new ScriptTimer();
225        $this->timer->start('_app');
226
227        // Are we running as a CLI?
228        $this->cli = ('cli' === php_sapi_name() || defined('_CLI'));
229    }
230
231    /**
232     * This method enforces the singleton pattern for this class. Only one application is running at a time.
233     *
234     * $param   string  $namespace  Name of this application.
235     * @return  object  Reference to the global Cache object.
236     * @access  public
237     * @static
238     */
239    public static function &getInstance($namespace='')
240    {
241        if (self::$instance === null) {
242            // FIXME: Yep, having a namespace with one singleton instance is not very useful. This is a design flaw with the Codebase.
243            // We're currently getting instances of App throughout the codebase using `$app =& App::getInstance();`
244            // with no way to determine what the namespace of the containing application is (e.g., `public` vs. `admin`).
245            // Option 1: provide the project namespace to all classes that use App, and then instantiate with `$app =& App::getInstance($this->_ns);`.
246            // In this case the namespace of the App and the namespace of the auxiliary class must match.
247            // Option 2: may be to clone a specific instance to the "default" instance, so, e.g., `$app =& App::getInstance();`
248            // refers to the same namespace as `$app =& App::getInstance('admin');`
249            // Option 3: is to check if there is only one instance, and return it if an unspecified namespace is requested.
250            // However, in the case when multiple namespaces are in play at the same time, this will fail; unspecified namespaces
251            // would cause the creation of an additional instance, since there would not be an obvious named instance to return.
252            self::$instance = new self($namespace);
253        }
254
255        if ('' != $namespace) {
256            // We may not be able to request a specific instance, but we can specify a specific namespace.
257            // We're ignoring all instance requests with a blank namespace, so we use the last given one.
258            self::$instance->_ns = $namespace;
259        }
260
261        return self::$instance;
262    }
263
264    /**
265     * Set (or overwrite existing) parameters by passing an array of new parameters.
266     *
267     * @access public
268     * @param  array    $param     Array of parameters (key => val pairs).
269     */
270    public function setParam($param=null)
271    {
272        if (isset($param) && is_array($param)) {
273            // Merge new parameters with old overriding old ones that are passed.
274            $this->_params = array_merge($this->_params, $param);
275
276            if ($this->running) {
277                // Params that require additional processing if set during runtime.
278                foreach ($param as $key => $val) {
279                    switch ($key) {
280                    case 'namespace':
281                        $this->logMsg(sprintf('Setting namespace not allowed', null), LOG_WARNING, __FILE__, __LINE__);
282                        return false;
283
284                    case 'session_name':
285                        session_name($val);
286                        return true;
287
288                    case 'session_use_cookies':
289                        ini_set('session.use_cookies', $val);
290                        return true;
291
292                    case 'error_reporting':
293                        ini_set('error_reporting', $val);
294                        return true;
295
296                    case 'display_errors':
297                        ini_set('display_errors', $val);
298                        return true;
299
300                    case 'log_errors':
301                        ini_set('log_errors', true);
302                        return true;
303
304                    case 'log_directory':
305                        if (is_dir($val) && is_writable($val)) {
306                            ini_set('error_log', $val . '/' . $this->getParam('php_error_log'));
307                        }
308                        return true;
309                    }
310                }
311            }
312        }
313    }
314
315    /**
316     * Return the value of a parameter.
317     *
318     * @access  public
319     * @param   string  $param      The key of the parameter to return.
320     * @return  mixed               Parameter value, or null if not existing.
321     */
322    public function getParam($param=null)
323    {
324        if ($param === null) {
325            return $this->_params;
326        } else if (array_key_exists($param, $this->_params)) {
327            return $this->_params[$param];
328        } else {
329            return null;
330        }
331    }
332
333    /**
334     * Begin running this application.
335     *
336     * @access  public
337     * @author  Quinn Comendant <quinn@strangecode.com>
338     * @since   15 Jul 2005 00:32:21
339     */
340    public function start()
341    {
342        if ($this->running) {
343            return false;
344        }
345
346        // Error reporting.
347        ini_set('error_reporting', $this->getParam('error_reporting'));
348        ini_set('display_errors', $this->getParam('display_errors'));
349        ini_set('log_errors', true);
350        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
351            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
352        }
353
354        // Set character set to use for multi-byte string functions.
355        mb_internal_encoding($this->getParam('character_set'));
356        ini_set('default_charset', $this->getParam('character_set'));
357        switch (mb_strtolower($this->getParam('character_set'))) {
358        case 'utf-8' :
359            mb_language('uni');
360            break;
361
362        case 'iso-2022-jp' :
363            mb_language('ja');
364            break;
365
366        case 'iso-8859-1' :
367        default :
368            mb_language('en');
369            break;
370        }
371
372        /**
373         * 1. Start Database.
374         */
375
376        if (true === $this->getParam('enable_db')) {
377
378            // DB connection parameters taken from environment variables in the server httpd.conf file (readable only by root)

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