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

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

Add PDO class. (And add a few /u unicode flags to preg functions in App - more of those coming in the next commit).

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

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