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

Last change on this file since 777 was 777, checked in by anonymous, 16 months ago

Avoid use of dynamic properties

File size: 93.6 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    protected $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', // Legacy template file send in .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_name' => '_session',
136        'session_use_cookies' => true,
137
138        // Pass the session-id through URLs if cookies are not enabled?
139        // Disable this to prevent session ID theft.
140        'session_use_trans_sid' => false,
141
142        // Use database?
143        'enable_db' => false,
144        'enable_db_pdo' => false,
145
146        // Use db-based sessions?
147        'enable_db_session_handler' => false,
148
149        // db_* parameters are passed to the DB object in $app->start().
150        // DB credentials should be set as apache environment variables in httpd.conf, readable only by root.
151        'db_server' => null,
152        'db_name' => null,
153        'db_user' => null,
154        'db_pass' => null,
155        'db_character_set' => '',
156        'db_collation' => '',
157
158        // CLI scripts will need this JSON file in the include path.
159        'db_auth_file' => 'db_auth.json',
160
161        // Database debugging.
162        'db_always_debug' => false, // TRUE = display all SQL queries.
163        'db_debug' => false, // TRUE = display db errors.
164        'db_die_on_failure' => false, // TRUE = script stops on db error.
165
166        // For classes that require db tables, do we check that a table exists and create if missing?
167        'db_create_tables' => true,
168
169        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
170        'error_reporting' => E_ALL,
171
172        // Don't display errors by default; it is preferable to log them to a file. For CLI scripts, set this to the string 'stderr'.
173        'display_errors' => false,
174
175        // Directory in which to store log files.
176        'log_directory' => '',
177
178        // PHP error log.
179        'php_error_log' => 'php_error_log',
180
181        // General application log.
182        'log_filename' => 'app_log',
183
184        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
185        'log_multiple_timeout' => 3600, // Hourly
186
187        // Logging priority can be any of the following, or false to deactivate:
188        // LOG_EMERG     system is unusable
189        // LOG_ALERT     action must be taken immediately
190        // LOG_CRIT      critical conditions
191        // LOG_ERR       error conditions
192        // LOG_WARNING   warning conditions
193        // LOG_NOTICE    normal, but significant, condition
194        // LOG_INFO      informational message
195        // LOG_DEBUG     debug-level message
196        'log_file_priority' => LOG_INFO,
197        'log_email_priority' => false,
198        'log_sms_priority' => false,
199        'log_screen_priority' => false,
200
201        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
202        'log_to_email_address' => null,
203
204        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
205        'log_to_sms_address' => null,
206
207        // 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.
208        'log_ignore_repeated_events' => true,
209
210        // Maximum length of log messages, in bytes.
211        'log_message_max_length' => 1024,
212
213        // Strip line-endings from log messages.
214        'log_serialize' => true,
215
216        // Temporary files directory.
217        'tmp_dir' => '/tmp',
218
219        // Session files directory. If not defined, the default value from php.ini will be used.
220        'session_dir' => '',
221
222        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
223        // Existing password hashes rely on the same key/salt being used to compare encryptions.
224        // Don't change this unless you know existing hashes or signatures will not be affected!
225        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
226
227        // Force getFormData, getPost, and getGet to always run dispelMagicQuotes() with stripslashes().
228        // This should be set to 'true' when using the codebase with Wordpress because
229        // WP forcefully adds slashes to all input despite the setting of magic_quotes_gpc (which was removed from PHP in v5.4).
230        'always_dispel_magicquotes' => false,
231
232        // The /u pattern modifier should only be used on UTF-8 strings. This value will be changed to `u` if character_set = `utf-8`.
233        // Use the unicode modifier like this:  preg_replace('/[^0-9]/' . $app->getParam('preg_u'), '', $str);
234        'preg_u' => '',
235    );
236
237    /**
238     * Constructor.
239     */
240    public function __construct($namespace='')
241    {
242        // Initialize default parameters.
243        $this->_params = array_merge($this->_params, array('namespace' => $namespace), $this->_param_defaults);
244
245        // Begin timing script.
246        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
247        $this->timer = new ScriptTimer();
248        $this->timer->start('_app');
249
250        // Are we running as a CLI?
251        $this->cli = ('cli' === php_sapi_name() || defined('_CLI'));
252    }
253
254    /**
255     * This method enforces the singleton pattern for this class. Only one application is running at a time.
256     *
257     * $param   string  $namespace  Name of this application.
258     * @return  object  Reference to the global Cache object.
259     * @access  public
260     * @static
261     */
262    public static function &getInstance($namespace='')
263    {
264        if (self::$instance === null) {
265            // FIXME: Yep, having a namespace with one singleton instance is not very useful. This is a design flaw with the Codebase.
266            // We're currently getting instances of App throughout the codebase using `$app =& App::getInstance();`
267            // with no way to determine what the namespace of the containing application is (e.g., `public` vs. `admin`).
268            // Option 1: provide the project namespace to all classes that use App, and then instantiate with `$app =& App::getInstance($this->_ns);`.
269            // In this case the namespace of the App and the namespace of the auxiliary class must match.
270            // Option 2: may be to clone a specific instance to the "default" instance, so, e.g., `$app =& App::getInstance();`
271            // refers to the same namespace as `$app =& App::getInstance('admin');`
272            // Option 3: is to check if there is only one instance, and return it if an unspecified namespace is requested.
273            // However, in the case when multiple namespaces are in play at the same time, this will fail; unspecified namespaces
274            // would cause the creation of an additional instance, since there would not be an obvious named instance to return.
275            self::$instance = new self($namespace);
276        }
277
278        if ('' != $namespace) {
279            // We may not be able to request a specific instance, but we can specify a specific namespace.
280            // We're ignoring all instance requests with a blank namespace, so we use the last given one.
281            self::$instance->_ns = $namespace;
282        }
283
284        return self::$instance;
285    }
286
287    /**
288     * Set (or overwrite existing) parameters by passing an array of new parameters.
289     *
290     * @access public
291     * @param  array    $param     Array of parameters (key => val pairs).
292     */
293    public function setParam($param=null)
294    {
295        if (isset($param) && is_array($param)) {
296            // Merge new parameters with old overriding old ones that are passed.
297            $this->_params = array_merge($this->_params, $param);
298
299            if ($this->running) {
300                // Params that require additional processing if set during runtime.
301                foreach ($param as $key => $val) {
302                    switch ($key) {
303                    case 'namespace':
304                        $this->logMsg(sprintf('Setting namespace not allowed', null), LOG_WARNING, __FILE__, __LINE__);
305                        return false;
306
307                    case 'session_name':
308                        session_name($val);
309                        return true;
310
311                    case 'session_use_cookies':
312                        if (session_status() !== PHP_SESSION_ACTIVE) {
313                            ini_set('session.use_cookies', $val);
314                        } else {
315                            $this->logMsg('Unable to set session_use_cookies; session is already active', LOG_NOTICE, __FILE__, __LINE__);
316                        }
317                        return true;
318
319                    case 'error_reporting':
320                        ini_set('error_reporting', $val);
321                        return true;
322
323                    case 'display_errors':
324                        ini_set('display_errors', $val);
325                        return true;
326
327                    case 'log_errors':
328                        ini_set('log_errors', true);
329                        return true;
330
331                    case 'log_directory':
332                        if (is_dir($val) && is_writable($val)) {
333                            ini_set('error_log', $val . '/' . $this->getParam('php_error_log'));
334                        }
335                        return true;
336                    }
337                }
338            }
339        }
340    }
341
342    /**
343     * Return the value of a parameter.
344     *
345     * @access  public
346     * @param   string  $param      The key of the parameter to return.
347     * @param   string  $default    The value to return if $param does not exist in $this->_params.
348     * @return  mixed               Parameter value, or null if not existing.
349     */
350    public function getParam($param=null, $default=null)
351    {
352        if ($param === null) {
353            return $this->_params;
354        } else if (array_key_exists($param, $this->_params)) {
355            return $this->_params[$param];
356        } else {
357            return $default;
358        }
359    }
360
361    /**
362     * Begin running this application.
363     *
364     * @access  public
365     * @author  Quinn Comendant <quinn@strangecode.com>
366     * @since   15 Jul 2005 00:32:21
367     */
368    public function start()
369    {
370        if ($this->running) {
371            return false;
372        }
373
374        // Error reporting.
375        ini_set('error_reporting', $this->getParam('error_reporting'));
376        ini_set('display_errors', $this->getParam('display_errors'));
377        ini_set('log_errors', true);
378        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
379            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
380        }
381
382        // Set character set to use for multi-byte string functions.
383        mb_internal_encoding($this->getParam('character_set'));
384        ini_set('default_charset', $this->getParam('character_set'));
385        switch (mb_strtolower($this->getParam('character_set'))) {
386        case 'utf-8' :
387            $this->setParam(['preg_u' => 'u']);
388            mb_language('uni');
389            break;
390
391        case 'iso-2022-jp' :
392            mb_language('ja');
393            break;
394
395        case 'iso-8859-1' :
396        default :
397            mb_language('en');
398            break;
399        }
400
401        // Server timezone used internally by PHP.
402        if ($this->getParam('php_timezone')) {
403            $this->setTimezone($this->getParam('php_timezone'));
404        }
405
406        // 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.
407        if (strtolower(getenv('HTTP_X_FORWARDED_PROTO')) == 'https' && strtolower(getenv('REQUEST_SCHEME')) == 'http') {
408            $this->logMsg(sprintf('Detected HTTPS via X-Forwarded-Proto; setting HTTPS=on', null), LOG_DEBUG, __FILE__, __LINE__);
409            putenv('HTTPS=on'); // Available via getenv(
)
410            isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] = 'on'; // Available via $_SERVER[
]
411        }
412
413        /**
414         * 1. Start Database.
415         */
416
417        if (true === $this->getParam('enable_db') || true === $this->getParam('enable_db_pdo')) {
418
419            // DB connection parameters taken from environment variables in the server httpd.conf file (readable only by root)

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