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

Last change on this file since 810 was 810, checked in by anonymous, 2 months ago

Enable setting db_timezone during runtime. Refactor setParam() in App, DB, and PDO.

File size: 95.9 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * App.inc.php
25 *
26 * Primary application framework class.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @version 2.1
30 */
31
32// Message Types.
33define('MSG_ERR', 1);
34define('MSG_ERROR', MSG_ERR);
35define('MSG_WARNING', 2);
36define('MSG_NOTICE', 4);
37define('MSG_SUCCESS', 8);
38define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR);
39
40require_once dirname(__FILE__) . '/Utilities.inc.php';
41
42class App
43{
44    // Minimum version of PHP required for this version of the Codebase.
45    const CODEBASE_MIN_PHP_VERSION = '5.3.0';
46
47    // A place to keep an object instance for the singleton pattern.
48    protected static $instance = null;
49
50    // Namespace of this application instance.
51    protected $_ns;
52
53    // If $app->start has run successfully.
54    public $running = false;
55
56    // 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    $params     Array of parameters (key => val pairs).
291     */
292    public function setParam(Array $params)
293    {
294        if (!isset($params) || !is_array($params)) {
295            trigger_error(sprintf('%s failed; not an array: %s', __METHOD__, getDump($params, false, SC_DUMP_PRINT_R)), E_USER_ERROR);
296        }
297
298        // Merge new parameters with old overriding old ones that are passed.
299        $this->_params = array_merge($this->_params, $params);
300
301        if ($this->running) {
302            // Params that require additional processing if set during runtime.
303            foreach ($params as $key => $val) {
304                switch ($key) {
305                case 'namespace':
306                    $this->logMsg(sprintf('Setting namespace not allowed', null), LOG_WARNING, __FILE__, __LINE__);
307                    break;
308
309                case 'session_name':
310                    session_name($val);
311                    break;
312
313                case 'session_use_cookies':
314                    if (session_status() !== PHP_SESSION_ACTIVE) {
315                        ini_set('session.use_cookies', $val);
316                    } else {
317                        $this->logMsg('Unable to set session_use_cookies; session is already active', LOG_NOTICE, __FILE__, __LINE__);
318                    }
319                    break;
320
321                case 'error_reporting':
322                    ini_set('error_reporting', $val);
323                    break;
324
325                case 'php_timezone':
326                    // Set timezone used by PHP.
327                    $this->setTimezone($val);
328                    break;
329
330                case 'db_timezone':
331                    // Set timezone used by MySQL.
332                    if (true === $this->getParam('enable_db_pdo')) {
333                        $this->pdo->setParam(['timezone' => $val]);
334                    }
335                    if (true === $this->getParam('enable_db')) {
336                        $this->db->setParam(['timezone' => $val]);
337                    }
338                    break;
339
340                case 'display_errors':
341                    ini_set('display_errors', $val);
342                    break;
343
344                case 'log_errors':
345                    ini_set('log_errors', true);
346                    break;
347
348                case 'log_directory':
349                    if (is_dir($val) && is_writable($val)) {
350                        ini_set('error_log', $val . '/' . $this->getParam('php_error_log'));
351                    }
352                    break;
353                }
354            }
355        }
356    }
357
358    /**
359     * Return the value of a parameter.
360     *
361     * @access  public
362     * @param   string  $param      The key of the parameter to return.
363     * @param   string  $default    The value to return if $param does not exist in $this->_params.
364     * @return  mixed               Parameter value, or null if not existing.
365     */
366    public function getParam($param=null, $default=null)
367    {
368        if ($param === null) {
369            return $this->_params;
370        } else if (array_key_exists($param, $this->_params)) {
371            return $this->_params[$param];
372        } else {
373            return $default;
374        }
375    }
376
377    /**
378     * Begin running this application.
379     *
380     * @access  public
381     * @author  Quinn Comendant <quinn@strangecode.com>
382     * @since   15 Jul 2005 00:32:21
383     */
384    public function start()
385    {
386        if ($this->running) {
387            return false;
388        }
389
390        // Error reporting.
391        ini_set('error_reporting', $this->getParam('error_reporting'));
392        ini_set('display_errors', $this->getParam('display_errors'));
393        ini_set('log_errors', true);
394        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
395            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
396        }
397
398        // Set character set to use for multi-byte string functions.
399        mb_internal_encoding($this->getParam('character_set'));
400        ini_set('default_charset', $this->getParam('character_set'));
401        switch (mb_strtolower($this->getParam('character_set'))) {
402        case 'utf-8' :
403            $this->setParam(['preg_u' => 'u']);
404            mb_language('uni');
405            break;
406
407        case 'iso-2022-jp' :
408            mb_language('ja');
409            break;
410
411        case 'iso-8859-1' :
412        default :
413            mb_language('en');
414            break;
415        }
416
417        // Server timezone used internally by PHP.
418        if ($this->getParam('php_timezone')) {
419            $this->setTimezone($this->getParam('php_timezone'));
420        }
421
422        // 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.
423        if (strtolower(getenv('HTTP_X_FORWARDED_PROTO')) == 'https' && strtolower(getenv('REQUEST_SCHEME')) == 'http') {
424            $this->logMsg(sprintf('Detected HTTPS via X-Forwarded-Proto; setting HTTPS=on', null), LOG_DEBUG, __FILE__, __LINE__);
425            putenv('HTTPS=on'); // Available via getenv(
)
426            isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] = 'on'; // Available via $_SERVER[
]
427        }
428
429        /**
430         * 1. Start Database.
431         */
432
433        if (true === $this->getParam('enable_db') || true === $this->getParam('enable_db_pdo')) {
434
435            // DB connection parameters taken from environment variables in the server httpd.conf file (readable only by root)

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