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

Last change on this file since 786 was 786, checked in by anonymous, 14 months ago

Fix App::unsetCookie() to match args to setCookie().

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

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