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

Last change on this file since 690 was 690, checked in by anonymous, 5 years ago

Remove App's 'ssl_domain' and 'ssl_enabled' parameters; determine SSL usage by detecting the presence of HTTPS env var (or HTTP_X_FORWARDED_PROTO). Update Session parameters for greater logevity and security. Add 'session_dir' to store site-specific sess_* files with a longer gc_maxlifetime duration.

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

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