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

Last change on this file since 796 was 796, checked in by anonymous, 10 months ago

minor changes

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

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