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

Last change on this file since 550 was 550, checked in by anonymous, 8 years ago

Escaped quotes from email from names.
Changed logMsg string truncation method and added version to email log msg.
Better variable testing in carry queries.
Spelling errors.
Added runtime cache to Currency.
Added logging to form validation.
More robust form validation.
Added json serialization methond to Version.

File size: 73.0 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    // Array of query arguments will be carried persistently between requests.
60    protected $_carry_queries = array();
61
62    // Array of raised message counters.
63    protected $_raised_msg_counter = array(MSG_NOTICE => 0, MSG_SUCCESS => 0, MSG_WARNING => 0, MSG_ERR => 0);
64
65    // We're running as CLI. Public becuase we must force this as false when testing sessions via CLI.
66    public $cli = false;
67
68    // Dictionary of global application parameters.
69    protected $_params = array();
70
71    // Default parameters.
72    protected $_param_defaults = array(
73
74        // Public name and email address for this application.
75        'site_name' => null,
76        'site_email' => '', // Set to no-reply@HTTP_HOST if not set here.
77        'site_url' => '', // URL to the root of the site (created during App->start()).
78        'page_url' => '', // URL to the current page (created during App->start()).
79        'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i").
80        'site_version' => '', // Version of this application (set automatically during start() if site_version_file is used).
81        'site_version_file' => 'docs/version.txt', // File containing version number of this app, relative to the include path.
82
83        // The location the user will go if the system doesn't know where else to send them.
84        'redirect_home_url' => '/',
85
86        // SSL URL used when redirecting with $app->sslOn().
87        'ssl_domain' => null,
88        'ssl_enabled' => false,
89
90        // Use CSRF tokens. See notes in the getCSRFToken() method.
91        'csrf_token_enabled' => true,
92        // Form tokens will expire after this duration, in seconds.
93        'csrf_token_timeout' => 259200, // 259200 seconds = 3 days.
94        'csrf_token_name' => 'csrf_token',
95
96        // HMAC signing method
97        'signing_method' => 'sha512+base64',
98
99        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
100        'character_set' => 'utf-8',
101
102        // Human-readable format used to display dates.
103        'date_format' => 'd M Y',
104        'time_format' => 'h:i:s A',
105        'sql_date_format' => '%e %b %Y',
106        'sql_time_format' => '%k:%i',
107
108        // Use php sessions?
109        'enable_session' => false,
110        'session_name' => '_session',
111        'session_use_cookies' => true,
112
113        // Pass the session-id through URLs if cookies are not enabled?
114        // Disable this to prevent session ID theft.
115        'session_use_trans_sid' => false,
116
117        // Use database?
118        'enable_db' => false,
119
120        // Use db-based sessions?
121        'enable_db_session_handler' => false,
122
123        // DB credentials should be set as apache environment variables in httpd.conf, readable only by root.
124        'db_server' => 'localhost',
125        'db_name' => null,
126        'db_user' => null,
127        'db_pass' => null,
128
129        // And for CLI scripts, which should include a JSON file at this specified location in the include path.
130        'db_auth_file' => 'db_auth.json',
131
132        // Database debugging.
133        'db_always_debug' => false, // TRUE = display all SQL queries.
134        'db_debug' => false, // TRUE = display db errors.
135        'db_die_on_failure' => false, // TRUE = script stops on db error.
136
137        // For classes that require db tables, do we check that a table exists and create if missing?
138        'db_create_tables' => true,
139
140        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
141        'error_reporting' => E_ALL,
142
143        // Don't display errors by default; it is preferable to log them to a file. For CLI scripts, set this to the string 'stderr'.
144        'display_errors' => false,
145
146        // Directory in which to store log files.
147        'log_directory' => '',
148
149        // PHP error log.
150        'php_error_log' => 'php_error_log',
151
152        // General application log.
153        'log_filename' => 'app_log',
154
155        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
156        'log_multiple_timeout' => 3600, // Hourly
157
158        // Logging priority can be any of the following, or false to deactivate:
159        // LOG_EMERG     system is unusable
160        // LOG_ALERT     action must be taken immediately
161        // LOG_CRIT      critical conditions
162        // LOG_ERR       error conditions
163        // LOG_WARNING   warning conditions
164        // LOG_NOTICE    normal, but significant, condition
165        // LOG_INFO      informational message
166        // LOG_DEBUG     debug-level message
167        'log_file_priority' => LOG_INFO,
168        'log_email_priority' => false,
169        'log_sms_priority' => false,
170        'log_screen_priority' => false,
171
172        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
173        'log_to_email_address' => null,
174
175        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
176        'log_to_sms_address' => null,
177
178        // 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.
179        'log_ignore_repeated_events' => true,
180
181        // Temporary files directory.
182        'tmp_dir' => '/tmp',
183
184        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
185        // Existing password hashes rely on the same key/salt being used to compare encryptions.
186        // Don't change this unless you know existing hashes or signatures will not be affected!
187        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
188
189        // Force getFormData, getPost, and getGet to always run dispelMagicQuotes() with stripslashes().
190        // This should be set to 'true' when using the codebase with Wordpress because
191        // WP forcefully adds slashes to all input despite the setting of magic_quotes_gpc.
192        'always_dispel_magicquotes' => false,
193    );
194
195    /**
196     * Constructor.
197     */
198    public function __construct($namespace='')
199    {
200        // Set namespace of application instance.
201        $this->_ns = $namespace;
202
203        // Initialize default parameters.
204        $this->_params = array_merge($this->_params, $this->_param_defaults);
205
206        // Begin timing script.
207        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
208        $this->timer = new ScriptTimer();
209        $this->timer->start('_app');
210
211        // Are we running as a CLI?
212        $this->cli = ('cli' === php_sapi_name() || defined('_CLI'));
213    }
214
215    /**
216     * This method enforces the singleton pattern for this class. Only one application is running at a time.
217     *
218     * $param   string  $namespace  Name of this application.
219     * @return  object  Reference to the global Cache object.
220     * @access  public
221     * @static
222     */
223    public static function &getInstance($namespace='')
224    {
225        if (self::$instance === null) {
226            // TODO: Yep, having a namespace with one singletone instance is not very useful.
227            self::$instance = new self($namespace);
228        }
229
230        return self::$instance;
231    }
232
233    /**
234     * Set (or overwrite existing) parameters by passing an array of new parameters.
235     *
236     * @access public
237     * @param  array    $param     Array of parameters (key => val pairs).
238     */
239    public function setParam($param=null)
240    {
241        if (isset($param) && is_array($param)) {
242            // Merge new parameters with old overriding old ones that are passed.
243            $this->_params = array_merge($this->_params, $param);
244
245            if ($this->running) {
246                // Params that require additional processing if set during runtime.
247                foreach ($param as $key => $val) {
248                    switch ($key) {
249                    case 'session_name':
250                        session_name($val);
251                        break;
252
253                    case 'session_use_cookies':
254                        ini_set('session.use_cookies', $val);
255                        break;
256
257                    case 'error_reporting':
258                        ini_set('error_reporting', $val);
259                        break;
260
261                    case 'display_errors':
262                        ini_set('display_errors', $val);
263                        break;
264
265                    case 'log_errors':
266                        ini_set('log_errors', true);
267                        break;
268
269                    case 'log_directory':
270                        if (is_dir($val) && is_writable($val)) {
271                            ini_set('error_log', $val . '/' . $this->getParam('php_error_log'));
272                        }
273                        break;
274                    }
275                }
276            }
277        }
278    }
279
280    /**
281     * Return the value of a parameter.
282     *
283     * @access  public
284     * @param   string  $param      The key of the parameter to return.
285     * @return  mixed               Parameter value, or null if not existing.
286     */
287    public function getParam($param=null)
288    {
289        if ($param === null) {
290            return $this->_params;
291        } else if (array_key_exists($param, $this->_params)) {
292            return $this->_params[$param];
293        } else {
294            return null;
295        }
296    }
297
298    /**
299     * Begin running this application.
300     *
301     * @access  public
302     * @author  Quinn Comendant <quinn@strangecode.com>
303     * @since   15 Jul 2005 00:32:21
304     */
305    public function start()
306    {
307        if ($this->running) {
308            return false;
309        }
310
311        // Error reporting.
312        ini_set('error_reporting', $this->getParam('error_reporting'));
313        ini_set('display_errors', $this->getParam('display_errors'));
314        ini_set('log_errors', true);
315        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
316            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
317        }
318
319        // Set character set to use for multi-byte string functions.
320        mb_internal_encoding($this->getParam('character_set'));
321        switch (mb_strtolower($this->getParam('character_set'))) {
322        case 'utf-8' :
323            mb_language('uni');
324            break;
325
326        case 'iso-2022-jp' :
327            mb_language('ja');
328            break;
329
330        case 'iso-8859-1' :
331        default :
332            mb_language('en');
333            break;
334        }
335
336        /**
337         * 1. Start Database.
338         */
339
340        if (true === $this->getParam('enable_db')) {
341
342            // DB connection parameters taken from environment variables in the server httpd.conf file (readable only by root)

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