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

Last change on this file since 674 was 671, checked in by anonymous, 5 years ago

Add Auth_SQL->isLoggedIn(CLIENT_ID) return seconds until session expiry. Add humanTime() JS function. Fix site_hostname port separator.

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

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