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

Last change on this file since 527 was 527, checked in by anonymous, 9 years ago

Added page_url calculation to App->start()

File size: 71.7 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[452]6 *
[362]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.
[452]13 *
[362]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.
[452]18 *
[362]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/**
[1]24 * App.inc.php
25 *
26 * Primary application framework class.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
[136]29 * @version 2.1
[1]30 */
[42]31
[37]32// Message Types.
33define('MSG_ERR', 1);
34define('MSG_ERROR', MSG_ERR);
[1]35define('MSG_WARNING', 2);
[37]36define('MSG_NOTICE', 4);
37define('MSG_SUCCESS', 8);
[119]38define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR);
[1]39
40require_once dirname(__FILE__) . '/Utilities.inc.php';
41
[502]42class App
43{
[42]44
[487]45    // Minimum version of PHP required for this version of the Codebase.
46    const CODEBASE_MIN_PHP_VERSION = '5.3.0';
47
[468]48    // A place to keep an object instance for the singleton pattern.
[484]49    protected static $instance = null;
[468]50
[136]51    // Namespace of this application instance.
[484]52    protected $_ns;
[1]53
[136]54    // If $app->start has run successfully.
[468]55    public $running = false;
[1]56
57    // Instance of database object.
[468]58    public $db;
[42]59
[20]60    // Array of query arguments will be carried persistently between requests.
[484]61    protected $_carry_queries = array();
[1]62
[518]63    // Array of raised message counters.
64    protected $_raised_msg_counter = array(MSG_NOTICE => 0, MSG_SUCCESS => 0, MSG_WARNING => 0, MSG_ERR => 0);
65
[136]66    // Dictionary of global application parameters.
[484]67    protected $_params = array();
[1]68
69    // Default parameters.
[484]70    protected $_param_defaults = array(
[1]71
72        // Public name and email address for this application.
73        'site_name' => null,
[390]74        'site_email' => '', // Set to no-reply@HTTP_HOST if not set here.
[527]75        'site_url' => '', // URL to the root of the site (created during App->start()).
76        'page_url' => '', // URL to the current page (created during App->start()).
[318]77        'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i").
[526]78        'site_version' => '', // Version of this application (set automatically during start() if site_version_file is used).
[491]79        'site_version_file' => 'docs/version.txt', // File containing version number of this app, relative to the include path.
[1]80
[136]81        // The location the user will go if the system doesn't know where else to send them.
[1]82        'redirect_home_url' => '/',
[42]83
[136]84        // SSL URL used when redirecting with $app->sslOn().
[1]85        'ssl_domain' => null,
86        'ssl_enabled' => false,
[42]87
[501]88        // Use CSRF tokens. See notes in the getCSRFToken() method.
[500]89        'csrf_token_enabled' => true,
[501]90        // Form tokens will expire after this duration, in seconds.
91        'csrf_token_timeout' => 259200, // 259200 seconds = 3 days.
[500]92        'csrf_token_name' => 'csrf_token',
93
94        // HMAC signing method
95        'signing_method' => 'sha512+base64',
96
[20]97        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
[1]98        'character_set' => 'utf-8',
99
100        // Human-readable format used to display dates.
101        'date_format' => 'd M Y',
[101]102        'time_format' => 'h:i:s A',
[1]103        'sql_date_format' => '%e %b %Y',
104        'sql_time_format' => '%k:%i',
105
106        // Use php sessions?
107        'enable_session' => false,
[242]108        'session_name' => '_session',
[1]109        'session_use_cookies' => true,
[452]110
[293]111        // Pass the session-id through URLs if cookies are not enabled?
112        // Disable this to prevent session ID theft.
[242]113        'session_use_trans_sid' => false,
[42]114
[1]115        // Use database?
116        'enable_db' => false,
117
118        // Use db-based sessions?
119        'enable_db_session_handler' => false,
[42]120
[523]121        // DB credentials should be set as apache environment variables in httpd.conf, readable only by root.
[1]122        'db_server' => 'localhost',
123        'db_name' => null,
124        'db_user' => null,
125        'db_pass' => null,
126
[523]127        // And for CLI scripts, which should include a JSON file at this specified location in the include path.
128        'db_auth_file' => 'db_auth.json',
129
[1]130        // Database debugging.
131        'db_always_debug' => false, // TRUE = display all SQL queries.
132        'db_debug' => false, // TRUE = display db errors.
133        'db_die_on_failure' => false, // TRUE = script stops on db error.
[42]134
[1]135        // For classes that require db tables, do we check that a table exists and create if missing?
[32]136        'db_create_tables' => true,
[1]137
[136]138        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
[1]139        'error_reporting' => E_ALL,
140
[505]141        // Don't display errors by default; it is preferable to log them to a file. For CLI scripts, set this to the string 'stderr'.
[1]142        'display_errors' => false,
[42]143
[1]144        // Directory in which to store log files.
[19]145        'log_directory' => '',
[1]146
147        // PHP error log.
148        'php_error_log' => 'php_error_log',
149
150        // General application log.
[136]151        'log_filename' => 'app_log',
[1]152
[390]153        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
154        'log_multiple_timeout' => 3600, // Hourly
[341]155
[1]156        // Logging priority can be any of the following, or false to deactivate:
157        // LOG_EMERG     system is unusable
158        // LOG_ALERT     action must be taken immediately
159        // LOG_CRIT      critical conditions
160        // LOG_ERR       error conditions
161        // LOG_WARNING   warning conditions
162        // LOG_NOTICE    normal, but significant, condition
163        // LOG_INFO      informational message
164        // LOG_DEBUG     debug-level message
[174]165        'log_file_priority' => LOG_INFO,
[342]166        'log_email_priority' => false,
[1]167        'log_sms_priority' => false,
168        'log_screen_priority' => false,
[42]169
[390]170        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
[342]171        'log_to_email_address' => null,
[42]172
[392]173        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
[1]174        'log_to_sms_address' => null,
[42]175
[406]176        // 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.
177        'log_ignore_repeated_events' => true,
178
[348]179        // Temporary files directory.
180        'tmp_dir' => '/tmp',
[343]181
[19]182        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
[136]183        // Existing password hashes rely on the same key/salt being used to compare encryptions.
184        // Don't change this unless you know existing hashes or signatures will not be affected!
[1]185        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
[523]186
187        // Force getFormData, getPost, and getGet to always run dispelMagicQuotes() with stripslashes().
188        // This should be set to 'true' when using the codebase with Wordpress because
189        // WP forcefully adds slashes to all input despite the setting of magic_quotes_gpc.
190        'always_dispel_magicquotes' => false,
[1]191    );
[42]192
[1]193    /**
194     * Constructor.
195     */
[468]196    public function __construct($namespace='')
[1]197    {
[136]198        // Set namespace of application instance.
[154]199        $this->_ns = $namespace;
[42]200
[1]201        // Initialize default parameters.
202        $this->_params = array_merge($this->_params, $this->_param_defaults);
[452]203
[172]204        // Begin timing script.
205        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
206        $this->timer = new ScriptTimer();
207        $this->timer->start('_app');
[1]208    }
209
210    /**
[468]211     * This method enforces the singleton pattern for this class. Only one application is running at a time.
212     *
213     * $param   string  $namespace  Name of this application.
214     * @return  object  Reference to the global Cache object.
215     * @access  public
216     * @static
217     */
218    public static function &getInstance($namespace='')
219    {
220        if (self::$instance === null) {
221            // TODO: Yep, having a namespace with one singletone instance is not very useful.
222            self::$instance = new self($namespace);
223        }
224
225        return self::$instance;
226    }
227
228    /**
[1]229     * Set (or overwrite existing) parameters by passing an array of new parameters.
230     *
231     * @access public
232     * @param  array    $param     Array of parameters (key => val pairs).
233     */
[468]234    public function setParam($param=null)
[1]235    {
236        if (isset($param) && is_array($param)) {
[523]237            // Merge new parameters with old overriding old ones that are passed.
[136]238            $this->_params = array_merge($this->_params, $param);
[505]239
240            if ($this->running) {
[523]241                // Params that require additional processing if set during runtime.
[505]242                foreach ($param as $key => $val) {
243                    switch ($key) {
244                    case 'session_name':
245                        session_name($val);
246                        break;
247
248                    case 'session_use_cookies':
249                        ini_set('session.use_cookies', $val);
250                        break;
251
252                    case 'error_reporting':
253                        ini_set('error_reporting', $val);
254                        break;
255
256                    case 'display_errors':
257                        ini_set('display_errors', $val);
258                        break;
259
260                    case 'log_errors':
261                        ini_set('log_errors', true);
262                        break;
263
264                    case 'log_directory':
265                        if (is_dir($val) && is_writable($val)) {
266                            ini_set('error_log', $val . '/' . $this->getParam('php_error_log'));
267                        }
268                        break;
269                    }
270                }
271            }
[1]272        }
273    }
274
275    /**
276     * Return the value of a parameter.
277     *
278     * @access  public
279     * @param   string  $param      The key of the parameter to return.
280     * @return  mixed               Parameter value, or null if not existing.
281     */
[468]282    public function getParam($param=null)
[1]283    {
284        if ($param === null) {
[136]285            return $this->_params;
[478]286        } else if (array_key_exists($param, $this->_params)) {
[136]287            return $this->_params[$param];
[1]288        } else {
289            return null;
290        }
291    }
[42]292
[1]293    /**
294     * Begin running this application.
295     *
296     * @access  public
297     * @author  Quinn Comendant <quinn@strangecode.com>
298     * @since   15 Jul 2005 00:32:21
299     */
[468]300    public function start()
[1]301    {
302        if ($this->running) {
303            return false;
304        }
[42]305
[1]306        // Error reporting.
307        ini_set('error_reporting', $this->getParam('error_reporting'));
308        ini_set('display_errors', $this->getParam('display_errors'));
309        ini_set('log_errors', true);
310        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
311            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
312        }
[42]313
[248]314        // Set character set to use for multi-byte string functions.
315        mb_internal_encoding($this->getParam('character_set'));
[249]316        switch (mb_strtolower($this->getParam('character_set'))) {
317        case 'utf-8' :
318            mb_language('uni');
319            break;
[42]320
[249]321        case 'iso-2022-jp' :
322            mb_language('ja');
323            break;
324
325        case 'iso-8859-1' :
326        default :
327            mb_language('en');
328            break;
329        }
330
[1]331        /**
332         * 1. Start Database.
333         */
[42]334
[103]335        if (true === $this->getParam('enable_db')) {
[42]336
[523]337            // DB connection parameters taken from environment variables in the server httpd.conf file (readable only by root)

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