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

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

Minor fixes

File size: 73.8 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        // In case __FILE__ and __LINE__ are not provided, note that fact.
734        $file = '' == $file ? 'unknown-file' : $file;
735        $line = '' == $line ? 'unknown-line' : $line;
736
737        // If log file is not specified, don't log to a file.
738        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
739            $this->setParam(array('log_file_priority' => false));
740            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
741            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
742        }
743
744        // Before we get any further, let's see if ANY log events are configured to be reported.
745        if ((false === $this->getParam('log_file_priority') || $priority > $this->getParam('log_file_priority'))
746        && (false === $this->getParam('log_email_priority') || $priority > $this->getParam('log_email_priority'))
747        && (false === $this->getParam('log_sms_priority') || $priority > $this->getParam('log_sms_priority'))
748        && (false === $this->getParam('log_screen_priority') || $priority > $this->getParam('log_screen_priority'))) {
749            // This event would not be recorded, skip it entirely.
750            return false;
751        }
752
753        // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>.
754        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow);
755        $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
756
757        // Serialize multi-line messages.
758        $message = preg_replace('/\s+/m', ' ', trim($message));
759
760        // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times.
761        $msg_id = md5($message . $priority . $file . $line);
762        if ($this->getParam('log_ignore_repeated_events') && isset($previous_events[$msg_id])) {
763            $previous_events[$msg_id]++;
764            if ($previous_events[$msg_id] == 2) {
765                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
766            }
767            return false;
768        } else {
769            $previous_events[$msg_id] = 1;
770        }
771
772        // For email and SMS notification types use "lock" files to prevent sending email and SMS notices ad infinitum.
773        if ((false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority'))
774        || (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority'))) {
775            // This event will generate a "send" notification. Prepare lock file.
776            $site_hash = md5(empty($_SERVER['SERVER_NAME']) ? $_SERVER['SCRIPT_FILENAME'] : $_SERVER['SERVER_NAME']);
777            $lock_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/";
778            // Just use the file and line for the msg_id to limit the number of possible messages
779            // (the message string itself shan't be used as it may contain innumerable combinations).
780            $lock_file = $lock_dir . md5($file . ':' . $line);
781            if (!is_dir($lock_dir)) {
782                mkdir($lock_dir);
783            }
784            $send_notifications = true;
785            if (is_file($lock_file)) {
786                $msg_last_sent = filectime($lock_file);
787                // Has this message been sent more recently than the timeout?
788                if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) {
789                    // This message was already sent recently.
790                    $send_notifications = false;
791                } else {
792                    // Timeout has expired; send notifications again and reset timeout.
793                    touch($lock_file);
794                }
795            } else {
796                touch($lock_file);
797            }
798        }
799
800        // Make sure to log in the system's locale.
801        $locale = setlocale(LC_TIME, 0);
802        setlocale(LC_TIME, 'C');
803
804        // Data to be stored for a log event.
805        $event = array(
806            'date'      => date('Y-m-d H:i:s'),
807            'remote ip' => getRemoteAddr(),
808            'pid'       => getmypid(),
809            'type'      => $this->logPriorityToString($priority),
810            'file:line' => "$file : $line",
811            'url'       => mb_substr(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 0, 1024),
812            'message'   => mb_substr($message, 0, 1024),
813        );
814        // Here's a shortened version of event data.
815        $event_short = $event;
816        $event_short['url'] = truncate($event_short['url'], 120);
817
818        // Restore original locale.
819        setlocale(LC_TIME, $locale);
820
821        // FILE ACTION
822        if (false !== $this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
823            $event_str = '[' . join('] [', $event_short) . ']';
824            error_log("$event_str\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
825        }
826
827        // EMAIL ACTION
828        if (false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority') && $send_notifications) {
829            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
830            $subject = sprintf('[%s %s] %s', $hostname, $event['type'], mb_substr($event['message'], 0, 64));
831            $email_msg = sprintf("A log event of type '%s' occurred on %s\n\n", $event['type'], $hostname);
832            $headers = 'From: ' . $this->getParam('site_email');
833            foreach ($event as $k=>$v) {
834                $email_msg .= sprintf("%-16s %s\n", $k, $v);
835            }
836            $email_msg .= sprintf("%-16s %s\n", 'codebase version', $this->getParam('codebase_version'));
837            $email_msg .= sprintf("%-16s %s\n", 'site version', $this->getParam('site_version'));
838            mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers);
839        }
840
841        // SMS ACTION
842        if (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority') && $send_notifications) {
843            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
844            $subject = sprintf('[%s %s]', $hostname, $priority);
845            $sms_msg = sprintf('%s [%s:%s]', mb_substr($event_short['message'], 0, 64), basename($file), $line);
846            $headers = 'From: ' . $this->getParam('site_email');
847            mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers);
848        }
849
850        // SCREEN ACTION
851        if (false !== $this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
852            file_put_contents('php://stderr', "[{$event['type']}] [{$event['message']}]\n", FILE_APPEND);
853        }
854
855        return true;
856    }
857
858    /**
859     * Returns the string representation of a LOG_* integer constant.
860     *
861     * @param int  $priority  The LOG_* integer constant.
862     *
863     * @return                The string representation of $priority.
864     */
865    public function logPriorityToString($priority) {
866        $priorities = array(
867            LOG_EMERG   => 'emergency',
868            LOG_ALERT   => 'alert',
869            LOG_CRIT    => 'critical',
870            LOG_ERR     => 'error',
871            LOG_WARNING => 'warning',
872            LOG_NOTICE  => 'notice',
873            LOG_INFO    => 'info',
874            LOG_DEBUG   => 'debug'
875        );
876        if (isset($priorities[$priority])) {
877            return $priorities[$priority];
878        } else {
879            return false;
880        }
881    }
882
883    /**
884     * Forcefully set a query argument even if one currently exists in the request.
885     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
886     * to hidden input values (via printHiddenSession()).
887     *
888     * @access  public
889     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to save.
890     * @param   mixed   $val        The new value of the argument key.
891     * @author  Quinn Comendant <quinn@strangecode.com>
892     * @since   13 Oct 2007 11:34:51
893     */
894    public function setQuery($query_key, $val)
895    {
896        if (!is_array($query_key)) {
897            $query_key = array($query_key);
898        }
899        foreach ($query_key as $k) {
900            // Set the value of the specified query argument into the _carry_queries array.
901            $this->_carry_queries[$k] = $val;
902        }
903    }
904
905    /**
906     * Specify which query arguments will be carried persistently between requests.
907     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
908     * to hidden input values (via printHiddenSession()).
909     *
910     * @access  public
911     * @param   mixed   $query_key   The key (or keys, as an array) of the query argument to save.
912     * @param   mixed   $default    If the key is not available, set to this default value.
913     * @author  Quinn Comendant <quinn@strangecode.com>
914     * @since   14 Nov 2005 19:24:52
915     */
916    public function carryQuery($query_key, $default=false)
917    {
918        if (!is_array($query_key)) {
919            $query_key = array($query_key);
920        }
921        foreach ($query_key as $k) {
922            // If not already set, and there is a non-empty value provided in the request...
923            if (isset($k) && '' != $k && !isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) {
924                // Copy the value of the specified query argument into the _carry_queries array.
925                $this->_carry_queries[$k] = getFormData($k, $default);
926                $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__);
927            }
928        }
929    }
930
931    /**
932     * dropQuery() is the opposite of carryQuery(). The specified value will not appear in
933     * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in.
934     *
935     * @access  public
936     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to remove.
937     * @param   bool    $unset      Remove any values set in the request matching the given $query_key.
938     * @author  Quinn Comendant <quinn@strangecode.com>
939     * @since   18 Jun 2007 20:57:29
940     */
941    public function dropQuery($query_key, $unset=false)
942    {
943        if (!is_array($query_key)) {
944            $query_key = array($query_key);
945        }
946        foreach ($query_key as $k) {
947            if (array_key_exists($k, $this->_carry_queries)) {
948                // Remove the value of the specified query argument from the _carry_queries array.
949                $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__);
950                unset($this->_carry_queries[$k]);
951            }
952            if ($unset && (isset($_REQUEST) && array_key_exists($k, $_REQUEST))) {
953                unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]);
954            }
955        }
956    }
957
958    /**
959     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
960     * keys and values, including optional queries. This allows mindless retention
961     * of query arguments across page requests. If cookies are not
962     * used and session_use_trans_sid=true the session id will be propagated in the URL.
963     *
964     * @param  string $url              The initial url
965     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
966     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
967     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
968     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
969     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
970     *
971     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
972     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
973     *                                     header('Location...') redirections.
974     *
975     * @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.
976     * @return string url with attached queries and, if not using cookies, the session id
977     */
978    public function url($url, $carry_args=null, $always_include_sid=false, $include_csrf_token=false)
979    {
980        if (!$this->running) {
981            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
982            return false;
983        }
984
985        if ($this->getParam('csrf_token_enabled') && $include_csrf_token) {
986            // Include the csrf_token as a carried query argument.
987            // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken()
988            $carry_args = is_array($carry_args) ? $carry_args : array();
989            $carry_args = array_merge($carry_args, array($this->getParam('csrf_token_name') => $this->getCSRFToken()));
990        }
991
992        // Get any provided query arguments to include in the final URL.
993        // If FALSE is a provided here, DO NOT carry the queries.
994        $do_carry_queries = true;
995        $one_time_carry_queries = array();
996        if (!is_null($carry_args)) {
997            if (is_array($carry_args)) {
998                if (!empty($carry_args)) {
999                    foreach ($carry_args as $key=>$arg) {
1000                        // Get query from appropriate source.
1001                        if (false === $arg) {
1002                            $do_carry_queries = false;
1003                        } else if (false !== getFormData($arg, false)) {
1004                            $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
1005                        } else if (!is_numeric($key) && '' != $arg) {
1006                            $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
1007                        }
1008                    }
1009                }
1010            } else if (false !== getFormData($carry_args, false)) {
1011                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
1012            } else if (false === $carry_args) {
1013                $do_carry_queries = false;
1014            }
1015        }
1016
1017        // Get the first delimiter that is needed in the url.
1018        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
1019
1020        $q = '';
1021        if ($do_carry_queries) {
1022            // Join the global _carry_queries and local one_time_carry_queries.
1023            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
1024            foreach ($query_args as $key=>$val) {
1025                // Check value is set and value does not already exist in the url.
1026                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
1027                    $q .= $delim . $key . '=' . $val;
1028                    $delim = ini_get('arg_separator.output');
1029                }
1030            }
1031        }
1032
1033        // Pop off any named anchors to push them back on after appending additional query args.
1034        $parts = explode('#', $url, 2);
1035        $url = $parts[0];
1036        $anchor = isset($parts[1]) ? $parts[1] : '';
1037
1038        // $anchor =
1039
1040        // Include the necessary SID if the following is true:
1041        // - no cookie in http request OR cookies disabled in App
1042        // - sessions are enabled
1043        // - the link stays on our site
1044        // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
1045        // OR
1046        // - 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)
1047        // AND
1048        // - the SID is not already in the query.
1049        if (
1050            (
1051                (
1052                    (
1053                        !isset($_COOKIE[session_name()])
1054                        || !$this->getParam('session_use_cookies')
1055                    )
1056                    && $this->getParam('session_use_trans_sid')
1057                    && $this->getParam('enable_session')
1058                    && isMyDomain($url)
1059                    && (
1060                        !ini_get('session.use_trans_sid')
1061                        || preg_match('!^(http|https)://!i', $url)
1062                    )
1063                )
1064                || $always_include_sid
1065            )
1066            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
1067        ) {
1068            $url = sprintf('%s%s%s%s=%s%s', $url, $q, $delim, session_name(), session_id(), ('' == $anchor ? '' : "#$anchor"));
1069        } else {
1070            $url = sprintf('%s%s%s', $url, $q, ('' == $anchor ? '' : "#$anchor"));
1071        }
1072
1073        return $url;
1074    }
1075
1076    /**
1077     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
1078     *
1079     * @access  public
1080     * @param   (see param reference for url() method)
1081     * @return  string          URL passed through $app->url() with ampersands transformed to $amp;
1082     * @author  Quinn Comendant <quinn@strangecode.com>
1083     * @since   09 Dec 2005 17:58:45
1084     */
1085    public function oHREF($url, $carry_args=null, $always_include_sid=false, $include_csrf_token=false)
1086    {
1087        // Process the URL.
1088        $url = $this->url($url, $carry_args, $always_include_sid, $include_csrf_token);
1089
1090        // Replace any & not followed by an html or unicode entity with its &amp; equivalent.
1091        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
1092
1093        return $url;
1094    }
1095
1096    /**
1097     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
1098     * as hidden form elements for GET_VARS that might be in use.
1099     *
1100     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
1101     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
1102     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
1103     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
1104     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
1105     * @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.
1106     */
1107    public function printHiddenSession($carry_args=null, $include_csrf_token=false)
1108    {
1109        if (!$this->running) {
1110            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1111            return false;
1112        }
1113
1114        // Get any provided query arguments to include in the final hidden form data.
1115        // If FALSE is a provided here, DO NOT carry the queries.
1116        $do_carry_queries = true;
1117        $one_time_carry_queries = array();
1118        if (!is_null($carry_args)) {
1119            if (is_array($carry_args)) {
1120                if (!empty($carry_args)) {
1121                    foreach ($carry_args as $key=>$arg) {
1122                        // Get query from appropriate source.
1123                        if (false === $arg) {
1124                            $do_carry_queries = false;
1125                        } else if (false !== getFormData($arg, false)) {
1126                            $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
1127                        } else if (!is_numeric($key) && '' != $arg) {
1128                            $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
1129                        }
1130                    }
1131                }
1132            } else if (false !== getFormData($carry_args, false)) {
1133                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
1134            } else if (false === $carry_args) {
1135                $do_carry_queries = false;
1136            }
1137        }
1138
1139        // For each existing request value, we create a hidden input to carry it through a form.
1140        if ($do_carry_queries) {
1141            // Join the global _carry_queries and local one_time_carry_queries.
1142            // urlencode is not used here, not for form data!
1143            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
1144            foreach ($query_args as $key => $val) {
1145                if (is_array($val)) {
1146                    foreach ($val as $subval) {
1147                        if ('' != $key && '' != $subval) {
1148                            printf('<input type="hidden" name="%s[]" value="%s" />', $key, $subval);
1149                        }
1150                    }
1151                } else if ('' != $key && '' != $val) {
1152                    printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
1153                }
1154            }
1155            unset($query_args, $key, $val, $subval);
1156        }
1157
1158        // Include the SID if:
1159        // * cookies are disabled
1160        // * the system isn't automatically adding trans_sid
1161        // * the session is enabled
1162        // * and we're configured to use trans_sid
1163        if (!isset($_COOKIE[session_name()])
1164        && !ini_get('session.use_trans_sid')
1165        && $this->getParam('enable_session')
1166        && $this->getParam('session_use_trans_sid')
1167        ) {
1168            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
1169        }
1170
1171        // Include the csrf_token in the form.
1172        // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken()
1173        if ($this->getParam('csrf_token_enabled') && $include_csrf_token) {
1174            printf('<input type="hidden" name="%s" value="%s" />', $this->getParam('csrf_token_name'), $this->getCSRFToken());
1175        }
1176    }
1177
1178    /*
1179    * 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
1180    *
1181    * @access   public
1182    * @param    string  $url    URL to media (e.g., /foo.js)
1183    * @return   string          URL with cache-busting version appended (/foo.js?v=1234567890)
1184    * @author   Quinn Comendant <quinn@strangecode.com>
1185    * @version  1.0
1186    * @since    03 Sep 2014 22:40:24
1187    */
1188    public function cacheBustURL($url)
1189    {
1190        // Get the first delimiter that is needed in the url.
1191        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
1192        $v = crc32($this->getParam('codebase_version') . '|' . $this->getParam('site_version'));
1193        return sprintf('%s%sv=%s', $url, $delim, $v);
1194    }
1195
1196    /*
1197    * Generate a csrf_token if it doesn't exist or is expired, save it to the session and return its value.
1198    * Otherwise just return the current token.
1199    * Details on the synchronizer token pattern:
1200    * https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern
1201    *
1202    * @access   public
1203    * @return   string The new or current csrf_token
1204    * @author   Quinn Comendant <quinn@strangecode.com>
1205    * @version  1.0
1206    * @since    15 Nov 2014 17:57:17
1207    */
1208    public function getCSRFToken()
1209    {
1210        if (!isset($_SESSION['_app'][$this->_ns]['csrf_token']) || (removeSignature($_SESSION['_app'][$this->_ns]['csrf_token']) + $this->getParam('csrf_token_timeout') < time())) {
1211            // No token, or token is expired; generate one and return it.
1212            return $_SESSION['_app'][$this->_ns]['csrf_token'] = addSignature(time(), null, 64);
1213        }
1214        // Current token is not expired; return it.
1215        return $_SESSION['_app'][$this->_ns]['csrf_token'];
1216    }
1217
1218    /*
1219    * Compares the given csrf_token with the current or previous one saved in the session.
1220    *
1221    * @access   public
1222    * @param    string  $user_submitted_csrf_token The user-submitted token to compare with the session token.
1223    * @param    string  $csrf_token     The token to compare with the session token.
1224    * @return   bool    True if the tokens match, false otherwise.
1225    * @author   Quinn Comendant <quinn@strangecode.com>
1226    * @version  1.0
1227    * @since    15 Nov 2014 18:06:55
1228    */
1229    public function verifyCSRFToken($user_submitted_csrf_token)
1230    {
1231
1232        if (!$this->getParam('csrf_token_enabled')) {
1233            $this->logMsg(sprintf('%s called, but csrf_token_enabled=false', __METHOD__), LOG_ERR, __FILE__, __LINE__);
1234            return true;
1235        }
1236        if ('' == trim($user_submitted_csrf_token)) {
1237            $this->logMsg(sprintf('Empty string failed CSRF verification.', null), LOG_NOTICE, __FILE__, __LINE__);
1238            return false;
1239        }
1240        if (!verifySignature($user_submitted_csrf_token, null, 64)) {
1241            $this->logMsg(sprintf('Input failed CSRF verification (invalid signature in %s).', $user_submitted_csrf_token), LOG_WARNING, __FILE__, __LINE__);
1242            return false;
1243        }
1244        $csrf_token = $this->getCSRFToken();
1245        if ($user_submitted_csrf_token != $csrf_token) {
1246            $this->logMsg(sprintf('Input failed CSRF verification (%s not in %s).', $user_submitted_csrf_token, $csrf_token), LOG_WARNING, __FILE__, __LINE__);
1247            return false;
1248        }
1249        $this->logMsg(sprintf('Verified CSRF token %s', $user_submitted_csrf_token), LOG_DEBUG, __FILE__, __LINE__);
1250        return true;
1251    }
1252
1253    /*
1254    * Bounce user if they submit a token that doesn't match the one saved in the session.
1255    * Because this function calls dieURL() it must be called before any other HTTP header output.
1256    *
1257    * @access   public
1258    * @param    string  $message    Optional message to display to the user (otherwise default message will display). Set to an empty string to display no message.
1259    * @param    int    $type    The type of message: MSG_NOTICE,
1260    *                           MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
1261    * @param    string $file    __FILE__.
1262    * @param    string $line    __LINE__.
1263    * @return   void
1264    * @author   Quinn Comendant <quinn@strangecode.com>
1265    * @version  1.0
1266    * @since    15 Nov 2014 18:10:17
1267    */
1268    public function requireValidCSRFToken($message=null, $type=MSG_NOTICE, $file=null, $line=null)
1269    {
1270        if (!$this->verifyCSRFToken(getFormData($this->getParam('csrf_token_name')))) {
1271            $message = isset($message) ? $message : _("Sorry, the form token expired. Please try again.");
1272            $this->raiseMsg($message, $type, $file, $line);
1273            $this->dieBoomerangURL();
1274        }
1275    }
1276
1277    /**
1278     * Uses an http header to redirect the client to the given $url. If sessions are not used
1279     * and the session is not already defined in the given $url, the SID is appended as a URI query.
1280     * As with all header generating functions, make sure this is called before any other output.
1281     *
1282     * @param   string  $url                    The URL the client will be redirected to.
1283     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
1284     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
1285     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
1286     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
1287     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
1288     * @param   bool    $always_include_sid     Force session id to be added to Location header.
1289     */
1290    public function dieURL($url, $carry_args=null, $always_include_sid=false)
1291    {
1292        if (!$this->running) {
1293            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1294            return false;
1295        }
1296
1297        if (!$url) {
1298            // If URL is not specified, use the redirect_home_url.
1299            $url = $this->getParam('redirect_home_url');
1300        }
1301
1302        if (preg_match('!^/!', $url)) {
1303            // If relative URL is given, prepend correct local hostname.
1304            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
1305            $host = getenv('HTTP_HOST');
1306            $url = sprintf('%s://%s%s', $scheme, $host, $url);
1307        }
1308
1309        $url = $this->url($url, $carry_args, $always_include_sid);
1310
1311        // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP?
1312        if (!headers_sent($h_file, $h_line)) {
1313            header(sprintf('Location: %s', $url));
1314            $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
1315        } else {
1316            // Fallback: die using meta refresh instead.
1317            printf('<meta http-equiv="refresh" content="0;url=%s" />', $url);
1318            $this->logMsg(sprintf('dieURL (refresh): %s; headers already sent (output started in %s : %s)', $url, $h_file, $h_line), LOG_NOTICE, __FILE__, __LINE__);
1319        }
1320
1321        // End application.
1322        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
1323        $this->stop();
1324        die;
1325    }
1326
1327    /*
1328    * Redirects a user by calling $app->dieURL(). It will use:
1329    * 1. the stored boomerang URL, it it exists
1330    * 2. a specified $default_url, it it exists
1331    * 3. the referring URL, it it exists.
1332    * 4. redirect_home_url configuration variable.
1333    *
1334    * @access   public
1335    * @param    string  $id             Identifier for this script.
1336    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->url()).
1337    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
1338    * @param    bool    $queryless_referrer_comparison   Exclude the URL query from the refererIsMe() comparison.
1339    * @return   bool                    False if the session is not running. No return otherwise.
1340    * @author   Quinn Comendant <quinn@strangecode.com>
1341    * @since    31 Mar 2006 19:17:00
1342    */
1343    public function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false)
1344    {
1345        if (!$this->running) {
1346            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1347            return false;
1348        }
1349
1350        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
1351        if ($this->validBoomerangURL($id, true)) {
1352            if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1353                $url = $_SESSION['_app'][$this->_ns]['boomerang'][$id]['url'];
1354                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1355            } else {
1356                $url = end($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1357                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1358            }
1359            // Delete stored boomerang.
1360            $this->deleteBoomerangURL($id);
1361        } else if (isset($default_url)) {
1362            $url = $default_url;
1363        } else if (!refererIsMe(true === $queryless_referrer_comparison) && '' != ($url = getenv('HTTP_REFERER'))) {
1364            // Ensure that the redirecting page is not also the referrer.
1365            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1366        } else {
1367            // If URL is not specified, use the redirect_home_url.
1368            $url = $this->getParam('redirect_home_url');
1369            $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1370        }
1371
1372        // A redirection will never happen immediately twice. Set the time so we can ensure this doesn't happen.
1373        $_SESSION['_app'][$this->_ns]['boomerang_last_redirect_time'] = time();
1374
1375        // Do it.
1376        $this->dieURL($url, $carry_args);
1377    }
1378
1379    /**
1380     * Set the URL to return to when $app->dieBoomerangURL() is called.
1381     *
1382     * @param string  $url  A fully validated URL.
1383     * @param bool  $id     An identification tag for this url.
1384     * FIXME: url garbage collection?
1385     */
1386    public function setBoomerangURL($url=null, $id=null)
1387    {
1388        if (!$this->running) {
1389            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1390            return false;
1391        }
1392        // A redirection will never happen immediately after setting the boomerangURL.
1393        // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
1394
1395        if ('' != $url && is_string($url)) {
1396            // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion).
1397            $url = preg_replace(array('/([&?])boomerang=[^&?]+[&?]?/', '/[&?]$/'), array('$1', ''), $url);
1398
1399            if (isset($_SESSION['_app'][$this->_ns]['boomerang']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']) && !empty($_SESSION['_app'][$this->_ns]['boomerang'])) {
1400                // If the ID=>URL pair currently exists in the boomerang array, delete.
1401                foreach (array_keys($_SESSION['_app'][$this->_ns]['boomerang']) as $existing_id) {
1402                    if ($existing_id === $id) {
1403                        $this->logMsg(sprintf('Found and deleting existing ID=>URL pair: %s=>%s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1404                        unset($_SESSION['_app'][$this->_ns]['boomerang'][$existing_id]);
1405                    }
1406                }
1407            }
1408
1409            if (isset($id)) {
1410                $_SESSION['_app'][$this->_ns]['boomerang'][$id] = array(
1411                    'url' => $url,
1412                    'added_time' => time(),
1413                );
1414            } else {
1415                $_SESSION['_app'][$this->_ns]['boomerang'][] = array(
1416                    'url' => $url,
1417                    'added_time' => time(),
1418                );
1419            }
1420
1421            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1422            return true;
1423        } else {
1424            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
1425            return false;
1426        }
1427    }
1428
1429    /**
1430     * Return the URL set for the specified $id, or an empty string if one isn't set.
1431     *
1432     * @param string  $id     An identification tag for this url.
1433     */
1434    public function getBoomerangURL($id=null)
1435    {
1436        if (!$this->running) {
1437            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1438            return false;
1439        }
1440
1441        if (isset($id)) {
1442            if (isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1443                return $_SESSION['_app'][$this->_ns]['boomerang'][$id]['url'];
1444            } else {
1445                return '';
1446            }
1447        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']) && !empty($_SESSION['_app'][$this->_ns]['boomerang'])) {
1448            return end($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1449        } else {
1450            return false;
1451        }
1452    }
1453
1454    /**
1455     * Delete the URL set for the specified $id.
1456     *
1457     * @param string  $id     An identification tag for this url.
1458     */
1459    public function deleteBoomerangURL($id=null)
1460    {
1461        if (!$this->running) {
1462            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1463            return false;
1464        }
1465
1466        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1467            $url = $this->getBoomerangURL($id);
1468            unset($_SESSION['_app'][$this->_ns]['boomerang'][$id]);
1469        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang'])) {
1470            $url = array_pop($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1471        }
1472        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1473    }
1474
1475    /**
1476     * Check if a valid boomerang URL value has been set. A boomerang URL is considered
1477     * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds.
1478     *
1479     * @return bool  True if it is set and valid, false otherwise.
1480     */
1481    public function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
1482    {
1483        if (!$this->running) {
1484            $this->logMsg(sprintf('Canceled %s, application not running.', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
1485            return false;
1486        }
1487
1488        if (!isset($_SESSION['_app'][$this->_ns]['boomerang']) || !is_array($_SESSION['_app'][$this->_ns]['boomerang']) || empty($_SESSION['_app'][$this->_ns]['boomerang'])) {
1489            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set, not an array, or empty.', $id), LOG_DEBUG, __FILE__, __LINE__);
1490            return false;
1491        }
1492
1493        $url = '';
1494        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang'][$id])) {
1495            $url = $_SESSION['_app'][$this->_ns]['boomerang'][$id]['url'];
1496            $added_time = $_SESSION['_app'][$this->_ns]['boomerang'][$id]['added_time'];
1497        } else if (!isset($id) || $use_nonspecificboomerang) {
1498            // Use most recent, non-specific boomerang if available.
1499            $url = end($_SESSION['_app'][$this->_ns]['boomerang'])['url'];
1500            $added_time = end($_SESSION['_app'][$this->_ns]['boomerang'])['added_time'];
1501        }
1502
1503        if ('' == trim($url)) {
1504            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
1505            return false;
1506        }
1507
1508        if ($url == absoluteMe()) {
1509            // The URL we are directing to is the current page.
1510            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1511            return false;
1512        }
1513
1514        // 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).
1515        $boomerang_last_redirect_time = isset($_SESSION['_app'][$this->_ns]['boomerang_last_redirect_time']) ? $_SESSION['_app'][$this->_ns]['boomerang_last_redirect_time'] : null;
1516        if (isset($boomerang_last_redirect_time) && $boomerang_last_redirect_time >= (time() - 2)) {
1517            // Last boomerang direction was less than 2 seconds ago.
1518            $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__);
1519            return false;
1520        }
1521
1522        if (isset($added_time) && $added_time < (time() - 72000)) {
1523            // Last boomerang direction was more than 20 hours ago.
1524            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, added_time too old: %s seconds', $id, time() - $added_time), LOG_DEBUG, __FILE__, __LINE__);
1525            // Delete this defunct boomerang.
1526            $this->deleteBoomerangURL($id);
1527            return false;
1528        }
1529
1530        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1531        return true;
1532    }
1533
1534    /**
1535     * Force the user to connect via https (port 443) by redirecting them to
1536     * the same page but with https.
1537     */
1538    public function sslOn()
1539    {
1540        if (function_exists('apache_get_modules')) {
1541            $modules = apache_get_modules();
1542        } else {
1543            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1544            $modules = array('mod_ssl');
1545        }
1546
1547        if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1548            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1549            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1550            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1551        }
1552    }
1553
1554    /**
1555     * to enforce the user to connect via http (port 80) by redirecting them to
1556     * a http version of the current url.
1557     */
1558    public function sslOff()
1559    {
1560        if ('' != getenv('HTTPS')) {
1561            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1562        }
1563    }
1564
1565    /*
1566    * Sets a cookie, with error checking and some sane defaults.
1567    *
1568    * @access   public
1569    * @param    string  $name       The name of the cookie.
1570    * @param    string  $value      The value of the cookie.
1571    * @param    string  $expire     The time the cookie expires, as a unix timestamp or string value passed to strtotime.
1572    * @param    string  $path       The path on the server in which the cookie will be available on.
1573    * @param    string  $domain     The domain that the cookie is available to.
1574    * @param    bool    $secure     Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
1575    * @param    bool    $httponly   When TRUE the cookie will be made accessible only through the HTTP protocol (makes cookies unreadable to javascript).
1576    * @return   bool                True on success, false on error.
1577    * @author   Quinn Comendant <quinn@strangecode.com>
1578    * @version  1.0
1579    * @since    02 May 2014 16:36:34
1580    */
1581    public function setCookie($name, $value, $expire='+10 years', $path='/', $domain=null, $secure=null, $httponly=null)
1582    {
1583        if (!is_scalar($name)) {
1584            $this->logMsg(sprintf('Cookie name must be scalar, is not: %s', getDump($name)), LOG_NOTICE, __FILE__, __LINE__);
1585            return false;
1586        }
1587        if (!is_scalar($value)) {
1588            $this->logMsg(sprintf('Cookie "%s" value must be scalar, is not: %s', $name, getDump($value)), LOG_NOTICE, __FILE__, __LINE__);
1589            return false;
1590        }
1591
1592        // Defaults.
1593        $expire = (is_numeric($expire) ? $expire : (is_string($expire) ? strtotime($expire) : $expire));
1594        $secure = $secure ?: ('' != getenv('HTTPS') && $this->getParam('ssl_enabled'));
1595        $httponly = $httponly ?: true;
1596
1597        // Make sure the expiration date is a valid 32bit integer.
1598        if (is_int($expire) && $expire > 2147483647) {
1599            $this->logMsg(sprintf('Cookie "%s" expire time exceeds a 32bit integer (%s)', $key, date('r', $expire)), LOG_NOTICE, __FILE__, __LINE__);
1600        }
1601
1602        // Measure total cookie length and warn if larger than max recommended size of 4093.
1603        // https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key
1604        // The date the header name include 51 bytes: Set-Cookie: ; expires=Fri, 03-May-2024 00:04:47 GMT
1605        $cookielen = strlen($name . $value . $path . $domain . ($secure ? '; secure' : '') . ($httponly ? '; httponly' : '')) + 51;
1606        if ($cookielen > 4093) {
1607            $this->logMsg(sprintf('Cookie "%s" has a size greater than 4093 bytes (is %s bytes)', $key, $cookielen), LOG_NOTICE, __FILE__, __LINE__);
1608        }
1609
1610        // Ensure PHP version allow use of httponly.
1611        if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
1612            $ret = setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
1613        } else {
1614            $ret = setcookie($name, $value, $expire, $path, $domain, $secure);
1615        }
1616
1617        if (false === $ret) {
1618            $this->logMsg(sprintf('Failed to set cookie (%s=%s) probably due to output before headers.', $name, $value), LOG_NOTICE, __FILE__, __LINE__);
1619        }
1620        return $ret;
1621    }
1622} // End.
Note: See TracBrowser for help on using the repository browser.