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

Last change on this file since 497 was 497, checked in by anonymous, 10 years ago

Beginning the process of adapting codebase to foundation styles.

File size: 59.7 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    // Dictionary of global application parameters.
63    protected $_params = array();
64
65    // Default parameters.
66    protected $_param_defaults = array(
67
68        // Public name and email address for this application.
69        'site_name' => null,
70        'site_email' => '', // Set to no-reply@HTTP_HOST if not set here.
71        'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here.
72        'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i").
73        'site_version_file' => 'docs/version.txt', // File containing version number of this app, relative to the include path.
74
75        // The location the user will go if the system doesn't know where else to send them.
76        'redirect_home_url' => '/',
77
78        // SSL URL used when redirecting with $app->sslOn().
79        'ssl_domain' => null,
80        'ssl_enabled' => false,
81
82        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
83        'character_set' => 'utf-8',
84
85        // Human-readable format used to display dates.
86        'date_format' => 'd M Y',
87        'time_format' => 'h:i:s A',
88        'sql_date_format' => '%e %b %Y',
89        'sql_time_format' => '%k:%i',
90
91        // Use php sessions?
92        'enable_session' => false,
93        'session_name' => '_session',
94        'session_use_cookies' => true,
95
96        // Pass the session-id through URLs if cookies are not enabled?
97        // Disable this to prevent session ID theft.
98        'session_use_trans_sid' => false,
99
100        // Use database?
101        'enable_db' => false,
102
103        // Use db-based sessions?
104        'enable_db_session_handler' => false,
105
106        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
107        'db_server' => 'localhost',
108        'db_name' => null,
109        'db_user' => null,
110        'db_pass' => null,
111
112        // Database debugging.
113        'db_always_debug' => false, // TRUE = display all SQL queries.
114        'db_debug' => false, // TRUE = display db errors.
115        'db_die_on_failure' => false, // TRUE = script stops on db error.
116
117        // For classes that require db tables, do we check that a table exists and create if missing?
118        'db_create_tables' => true,
119
120        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
121        'error_reporting' => E_ALL,
122
123        // Don't display errors by default; it is preferable to log them to a file.
124        'display_errors' => false,
125
126        // Directory in which to store log files.
127        'log_directory' => '',
128
129        // PHP error log.
130        'php_error_log' => 'php_error_log',
131
132        // General application log.
133        'log_filename' => 'app_log',
134
135        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
136        'log_multiple_timeout' => 3600, // Hourly
137
138        // Logging priority can be any of the following, or false to deactivate:
139        // LOG_EMERG     system is unusable
140        // LOG_ALERT     action must be taken immediately
141        // LOG_CRIT      critical conditions
142        // LOG_ERR       error conditions
143        // LOG_WARNING   warning conditions
144        // LOG_NOTICE    normal, but significant, condition
145        // LOG_INFO      informational message
146        // LOG_DEBUG     debug-level message
147        'log_file_priority' => LOG_INFO,
148        'log_email_priority' => false,
149        'log_sms_priority' => false,
150        'log_screen_priority' => false,
151
152        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
153        'log_to_email_address' => null,
154
155        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
156        'log_to_sms_address' => null,
157
158        // 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.
159        'log_ignore_repeated_events' => true,
160
161        // Temporary files directory.
162        'tmp_dir' => '/tmp',
163
164        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
165        // Existing password hashes rely on the same key/salt being used to compare encryptions.
166        // Don't change this unless you know existing hashes or signatures will not be affected!
167        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
168    );
169
170    /**
171     * Constructor.
172     */
173    public function __construct($namespace='')
174    {
175        // Set namespace of application instance.
176        $this->_ns = $namespace;
177
178        // Initialize default parameters.
179        $this->_params = array_merge($this->_params, $this->_param_defaults);
180
181        // Begin timing script.
182        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
183        $this->timer = new ScriptTimer();
184        $this->timer->start('_app');
185    }
186
187    /**
188     * This method enforces the singleton pattern for this class. Only one application is running at a time.
189     *
190     * $param   string  $namespace  Name of this application.
191     * @return  object  Reference to the global Cache object.
192     * @access  public
193     * @static
194     */
195    public static function &getInstance($namespace='')
196    {
197        if (self::$instance === null) {
198            // TODO: Yep, having a namespace with one singletone instance is not very useful.
199            self::$instance = new self($namespace);
200        }
201
202        return self::$instance;
203    }
204
205    /**
206     * Set (or overwrite existing) parameters by passing an array of new parameters.
207     *
208     * @access public
209     * @param  array    $param     Array of parameters (key => val pairs).
210     */
211    public function setParam($param=null)
212    {
213        if (isset($param) && is_array($param)) {
214            // Merge new parameters with old overriding only those passed.
215            $this->_params = array_merge($this->_params, $param);
216        }
217    }
218
219    /**
220     * Return the value of a parameter.
221     *
222     * @access  public
223     * @param   string  $param      The key of the parameter to return.
224     * @return  mixed               Parameter value, or null if not existing.
225     */
226    public function getParam($param=null)
227    {
228        if ($param === null) {
229            return $this->_params;
230        } else if (array_key_exists($param, $this->_params)) {
231            return $this->_params[$param];
232        } else {
233            return null;
234        }
235    }
236
237    /**
238     * Begin running this application.
239     *
240     * @access  public
241     * @author  Quinn Comendant <quinn@strangecode.com>
242     * @since   15 Jul 2005 00:32:21
243     */
244    public function start()
245    {
246        if ($this->running) {
247            return false;
248        }
249
250        // Error reporting.
251        ini_set('error_reporting', $this->getParam('error_reporting'));
252        ini_set('display_errors', $this->getParam('display_errors'));
253        ini_set('log_errors', true);
254        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
255            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
256        }
257
258        // Set character set to use for multi-byte string functions.
259        mb_internal_encoding($this->getParam('character_set'));
260        switch (mb_strtolower($this->getParam('character_set'))) {
261        case 'utf-8' :
262            mb_language('uni');
263            break;
264
265        case 'iso-2022-jp' :
266            mb_language('ja');
267            break;
268
269        case 'iso-8859-1' :
270        default :
271            mb_language('en');
272            break;
273        }
274
275        /**
276         * 1. Start Database.
277         */
278
279        if (true === $this->getParam('enable_db')) {
280
281            // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root.
282            if (!empty($_SERVER['DB_SERVER']) && !$this->getParam('db_server')) {
283                $this->setParam(array('db_server' => $_SERVER['DB_SERVER']));
284            }
285            if (!empty($_SERVER['DB_NAME']) && !$this->getParam('db_name')) {
286                $this->setParam(array('db_name' => $_SERVER['DB_NAME']));
287            }
288            if (!empty($_SERVER['DB_USER']) && !$this->getParam('db_user')) {
289                $this->setParam(array('db_user' => $_SERVER['DB_USER']));
290            }
291            if (!empty($_SERVER['DB_PASS']) && !$this->getParam('db_pass')) {
292                $this->setParam(array('db_pass' => $_SERVER['DB_PASS']));
293            }
294
295            // There will ever only be one instance of the DB object, and here is where it is instantiated.
296            require_once dirname(__FILE__) . '/DB.inc.php';
297            $this->db =& DB::getInstance();
298            $this->db->setParam(array(
299                'db_server' => $this->getParam('db_server'),
300                'db_name' => $this->getParam('db_name'),
301                'db_user' => $this->getParam('db_user'),
302                'db_pass' => $this->getParam('db_pass'),
303                'db_always_debug' => $this->getParam('db_always_debug'),
304                'db_debug' => $this->getParam('db_debug'),
305                'db_die_on_failure' => $this->getParam('db_die_on_failure'),
306            ));
307
308            // Connect to database.
309            $this->db->connect();
310        }
311
312
313        /**
314         * 2. Start PHP session.
315         */
316
317        // Skip sessions if disabled or automatically skip if run in a CLI script.
318        if (true === $this->getParam('enable_session') && !defined('_CLI')) {
319
320            // Session parameters.
321            ini_set('session.gc_probability', 1);
322            ini_set('session.gc_divisor', 1000);
323            ini_set('session.gc_maxlifetime', 43200); // 12 hours
324            ini_set('session.use_cookies', $this->getParam('session_use_cookies'));
325            ini_set('session.use_trans_sid', false);
326            ini_set('session.entropy_file', '/dev/urandom');
327            ini_set('session.entropy_length', '512');
328            ini_set('session.cookie_httponly', true);
329            session_name($this->getParam('session_name'));
330
331            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
332                // Database session handling.
333                require_once dirname(__FILE__) . '/DBSessionHandler.inc.php';
334                $db_save_handler = new DBSessionHandler($this->db, array(
335                    'db_table' => 'session_tbl',
336                    'create_table' => $this->getParam('db_create_tables'),
337                ));
338            }
339
340            // Start the session.
341            session_start();
342
343            if (!isset($_SESSION['_app'][$this->_ns])) {
344                // Access session data using: $_SESSION['...'].
345                // Initialize here _after_ session has started.
346                $_SESSION['_app'][$this->_ns] = array(
347                    'messages' => array(),
348                    'boomerang' => array('url'),
349                );
350            }
351        }
352
353
354        /**
355         * 3. Misc setup.
356         */
357
358        // Script URI will be something like http://host.name.tld (no ending slash)
359        // and is used whenever a URL need be used to the current site.
360        // Not available on cli scripts obviously.
361        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) {
362            $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'))));
363        }
364
365        // In case site_email isn't set, use something halfway presentable.
366        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_email')) {
367            $this->setParam(array('site_email' => sprintf('no-reply@%s', getenv('HTTP_HOST'))));
368        }
369
370        // A key for calculating simple cryptographic signatures.
371        if (isset($_SERVER['SIGNING_KEY'])) {
372            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
373        }
374
375        // Character set. This should also be printed in the html header template.
376        if (!defined('_CLI')) {
377            header('Content-type: text/html; charset=' . $this->getParam('character_set'));
378        }
379
380        // Set the version of the codebase we're using.
381        $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
382        $codebase_version = '';
383        if (is_readable($codebase_version_file) && !is_dir($codebase_version_file)) {
384            $codebase_version = trim(file_get_contents($codebase_version_file));
385            $this->setParam(array('codebase_version' => $codebase_version));
386            if (!defined('_CLI')) {
387                header('X-Codebase-Version: ' . $codebase_version);
388            }
389        }
390
391        if (version_compare(PHP_VERSION, self::CODEBASE_MIN_PHP_VERSION, '<')) {
392            $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__);
393        }
394
395        // Set the application version if defined.
396        if (is_readable($this->getParam('site_version_file')) && !is_dir($this->getParam('site_version_file'))) {
397            $site_version = trim(file_get_contents($this->getParam('site_version_file'), true));
398            $app->setParam(array('site_version' => $site_version));
399            header('X-Site-Version: ' . $site_version);
400        }
401
402        $this->running = true;
403    }
404
405    /**
406     * Stop running this application.
407     *
408     * @access  public
409     * @author  Quinn Comendant <quinn@strangecode.com>
410     * @since   17 Jul 2005 17:20:18
411     */
412    public function stop()
413    {
414        session_write_close();
415        $this->running = false;
416        $num_queries = 0;
417        if (true === $this->getParam('enable_db')) {
418            $num_queries = $this->db->numQueries();
419            $this->db->close();
420        }
421        $mem_current = memory_get_usage();
422        $mem_peak = memory_get_peak_usage();
423        $this->timer->stop('_app');
424        $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__);
425    }
426
427
428    /**
429     * Add a message to the session, which is printed in the header.
430     * Just a simple way to print messages to the user.
431     *
432     * @access public
433     *
434     * @param string $message The text description of the message.
435     * @param int    $type    The type of message: MSG_NOTICE,
436     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
437     * @param string $file    __FILE__.
438     * @param string $line    __LINE__.
439     */
440    public function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
441    {
442        $message = trim($message);
443
444        if (!$this->running) {
445            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
446            return false;
447        }
448
449        if ('' == trim($message)) {
450            $this->logMsg(sprintf('Raised message is an empty string.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
451            return false;
452        }
453
454        // Avoid duplicate full-stops..
455        $message = trim(preg_replace('/\.{2}$/', '.', $message));
456
457        // Save message in session under unique key to avoid duplicate messages.
458        $msg_id = md5($type . $message);
459        if (!isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id])) {
460            $_SESSION['_app'][$this->_ns]['messages'][$msg_id] = array(
461                'type'    => $type,
462                'message' => $message,
463                'file'    => $file,
464                'line'    => $line,
465                'count'   => (isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) : 1)
466            );
467        }
468
469        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
470            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__);
471        }
472    }
473
474    /**
475     * Returns an array of the raised messages.
476     *
477     * @access  public
478     * @return  array   List of messages in FIFO order.
479     * @author  Quinn Comendant <quinn@strangecode.com>
480     * @since   21 Dec 2005 13:09:20
481     */
482    public function getRaisedMessages()
483    {
484        if (!$this->running) {
485            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
486            return false;
487        }
488        return isset($_SESSION['_app'][$this->_ns]['messages']) ? $_SESSION['_app'][$this->_ns]['messages'] : array();
489    }
490
491    /**
492     * Resets the message list.
493     *
494     * @access  public
495     * @author  Quinn Comendant <quinn@strangecode.com>
496     * @since   21 Dec 2005 13:21:54
497     */
498    public function clearRaisedMessages()
499    {
500        if (!$this->running) {
501            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
502            return false;
503        }
504
505        $_SESSION['_app'][$this->_ns]['messages'] = array();
506    }
507
508    /**
509     * Prints the HTML for displaying raised messages.
510     *
511     * @param   string  $above    Additional message to print above error messages (e.g. "Oops!").
512     * @param   string  $below    Additional message to print below error messages (e.g. "Please fix and resubmit").
513     * @param   string  $print_gotohash_js  Print a line of javascript that scrolls the browser window down to view any error messages.
514     * @param   string  $hash     The #hashtag to scroll to.
515     * @access  public
516     * @author  Quinn Comendant <quinn@strangecode.com>
517     * @since   15 Jul 2005 01:39:14
518     */
519    public function printRaisedMessages($above='', $below='', $print_gotohash_js=false, $hash='sc-msg')
520    {
521
522        if (!$this->running) {
523            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
524            return false;
525        }
526
527        $messages = $this->getRaisedMessages();
528        if (!empty($messages)) {
529            ?><div id="sc-msg" class="sc-msg"><?php
530            if ('' != $above) {
531                ?><div class="sc-above"><?php echo oTxt($above); ?></div><?php
532            }
533            foreach ($messages as $m) {
534                if (error_reporting() > 0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) {
535                    echo "\n<!-- [" . $m['file'] . ' : ' . $m['line'] . '] -->';
536                }
537                switch ($m['type']) {
538                case MSG_ERR:
539                    echo '<div data-alert class="sc-msg-error alert-box alert">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
540                    break;
541
542                case MSG_WARNING:
543                    echo '<div data-alert class="sc-msg-warning alert-box warning">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
544                    break;
545
546                case MSG_SUCCESS:
547                    echo '<div data-alert class="sc-msg-success alert-box success">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
548                    break;
549
550                case MSG_NOTICE:
551                default:
552                    echo '<div data-alert class="sc-msg-notice alert-box info">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
553                    break;
554                }
555            }
556            if ('' != $below) {
557                ?><div class="sc-below"><?php echo oTxt($below); ?></div><?php
558            }
559            ?></div><?php
560            if ($print_gotohash_js) {
561                ?>
562                <script type="text/javascript">
563                /* <![CDATA[ */
564                window.location.hash = '#<?php echo urlencode($hash); ?>';
565                /* ]]> */
566                </script>
567                <?php
568            }
569        }
570        $this->clearRaisedMessages();
571    }
572
573    /**
574     * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are
575     * not repeated but printed once with count. Log events that match a sendable channel (email or SMS)
576     * are sent once per 'log_multiple_timeout' setting (to avoid a flood of error emails).
577     *
578     * @access public
579     * @param string $message   The text description of the message.
580     * @param int    $priority  The type of message priority (in descending order):
581     *                          LOG_EMERG     0 system is unusable
582     *                          LOG_ALERT     1 action must be taken immediately
583     *                          LOG_CRIT      2 critical conditions
584     *                          LOG_ERR       3 error conditions
585     *                          LOG_WARNING   4 warning conditions
586     *                          LOG_NOTICE    5 normal, but significant, condition
587     *                          LOG_INFO      6 informational message
588     *                          LOG_DEBUG     7 debug-level message
589     * @param string $file      The file where the log event occurs.
590     * @param string $line      The line of the file where the log event occurs.
591     */
592    public function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
593    {
594        static $previous_events = array();
595
596        // If priority is not specified, assume the worst.
597        if (!$this->logPriorityToString($priority)) {
598            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
599            $priority = LOG_EMERG;
600        }
601
602        // If log file is not specified, don't log to a file.
603        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
604            $this->setParam(array('log_file_priority' => false));
605            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
606            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
607        }
608
609        // Before we get any further, let's see if ANY log events are configured to be reported.
610        if ((false === $this->getParam('log_file_priority') || $priority > $this->getParam('log_file_priority'))
611        && (false === $this->getParam('log_email_priority') || $priority > $this->getParam('log_email_priority'))
612        && (false === $this->getParam('log_sms_priority') || $priority > $this->getParam('log_sms_priority'))
613        && (false === $this->getParam('log_screen_priority') || $priority > $this->getParam('log_screen_priority'))) {
614            // This event would not be recorded, skip it entirely.
615            return false;
616        }
617
618        // Make sure to log in the system's locale.
619        $locale = setlocale(LC_TIME, 0);
620        setlocale(LC_TIME, 'C');
621
622        // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>.
623        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow);
624        $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
625
626        // Serialize multi-line messages.
627        $message = preg_replace('/\s+/m', ' ', $message);
628
629        // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times.
630        $msg_id = md5($message . $priority . $file . $line);
631        if ($this->getParam('log_ignore_repeated_events') && isset($previous_events[$msg_id])) {
632            $previous_events[$msg_id]++;
633            if ($previous_events[$msg_id] == 2) {
634                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
635            }
636            return false;
637        } else {
638            $previous_events[$msg_id] = 1;
639        }
640
641        // For email and SMS notification types use "lock" files to prevent sending email and SMS notices ad infinitum.
642        if ((false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority'))
643        || (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority'))) {
644            // This event will generate a "send" notification. Prepare lock file.
645            $site_hash = md5(empty($_SERVER['SERVER_NAME']) ? $_SERVER['SCRIPT_FILENAME'] : $_SERVER['SERVER_NAME']);
646            $lock_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/";
647            // Just use the file and line for the msg_id to limit the number of possible messages
648            // (the message string itself shan't be used as it may contain innumerable combinations).
649            $lock_file = $lock_dir . md5($file . ':' . $line);
650            if (!is_dir($lock_dir)) {
651                mkdir($lock_dir);
652            }
653            $send_notifications = true;
654            if (is_file($lock_file)) {
655                $msg_last_sent = filectime($lock_file);
656                // Has this message been sent more recently than the timeout?
657                if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) {
658                    // This message was already sent recently.
659                    $send_notifications = false;
660                } else {
661                    // Timeout has expired; send notifications again and reset timeout.
662                    touch($lock_file);
663                }
664            } else {
665                touch($lock_file);
666            }
667        }
668
669        // Data to be stored for a log event.
670        $event = array(
671            'date'      => date('Y-m-d H:i:s'),
672            'remote ip' => getRemoteAddr(),
673            'pid'       => getmypid(),
674            'type'      => $this->logPriorityToString($priority),
675            'file:line' => "$file : $line",
676            'url'       => mb_substr(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 0, 1024),
677            'message'   => $message
678        );
679        // Here's a shortened version of event data.
680        $event_short = $event;
681        $event_short['url'] = truncate($event_short['url'], 120);
682
683
684        // FILE ACTION
685        if (false !== $this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
686            $event_str = '[' . join('] [', $event_short) . ']';
687            error_log(mb_substr($event_str, 0, 1024) . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
688        }
689
690        // EMAIL ACTION
691        if (false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority') && $send_notifications) {
692            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
693            $subject = sprintf('[%s %s] %s', $hostname, $event['type'], mb_substr($message, 0, 64));
694            $email_msg = sprintf("A %s log event occurred on %s\n\n", $event['type'], $hostname);
695            $headers = 'From: ' . $this->getParam('site_email');
696            foreach ($event as $k=>$v) {
697                $email_msg .= sprintf("%-11s%s\n", $k, $v);
698            }
699            mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers);
700        }
701
702        // SMS ACTION
703        if (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority') && $send_notifications) {
704            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
705            $subject = sprintf('[%s %s]', $hostname, $priority);
706            $sms_msg = sprintf('%s [%s:%s]', mb_substr($event_short['message'], 0, 64), basename($file), $line);
707            $headers = 'From: ' . $this->getParam('site_email');
708            mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers);
709        }
710
711        // SCREEN ACTION
712        if (false !== $this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
713            file_put_contents('php://stderr', "[{$event['type']}] [{$event['message']}]\n", FILE_APPEND);
714        }
715
716        // Restore original locale.
717        setlocale(LC_TIME, $locale);
718
719        unset($event, $event_short);
720
721        return true;
722    }
723
724    /**
725     * Returns the string representation of a LOG_* integer constant.
726     *
727     * @param int  $priority  The LOG_* integer constant.
728     *
729     * @return                The string representation of $priority.
730     */
731    public function logPriorityToString($priority) {
732        $priorities = array(
733            LOG_EMERG   => 'emergency',
734            LOG_ALERT   => 'alert',
735            LOG_CRIT    => 'critical',
736            LOG_ERR     => 'error',
737            LOG_WARNING => 'warning',
738            LOG_NOTICE  => 'notice',
739            LOG_INFO    => 'info',
740            LOG_DEBUG   => 'debug'
741        );
742        if (isset($priorities[$priority])) {
743            return $priorities[$priority];
744        } else {
745            return false;
746        }
747    }
748
749    /**
750     * Forcefully set a query argument even if one currently exists in the request.
751     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
752     * to hidden input values (via printHiddenSession()).
753     *
754     * @access  public
755     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to save.
756     * @param   mixed   $val        The new value of the argument key.
757     * @author  Quinn Comendant <quinn@strangecode.com>
758     * @since   13 Oct 2007 11:34:51
759     */
760    public function setQuery($query_key, $val)
761    {
762        if (!is_array($query_key)) {
763            $query_key = array($query_key);
764        }
765        foreach ($query_key as $k) {
766            // Set the value of the specified query argument into the _carry_queries array.
767            $this->_carry_queries[$k] = $val;
768        }
769    }
770
771    /**
772     * Specify which query arguments will be carried persistently between requests.
773     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
774     * to hidden input values (via printHiddenSession()).
775     *
776     * @access  public
777     * @param   mixed   $query_key   The key (or keys, as an array) of the query argument to save.
778     * @param   mixed   $default    If the key is not available, set to this default value.
779     * @author  Quinn Comendant <quinn@strangecode.com>
780     * @since   14 Nov 2005 19:24:52
781     */
782    public function carryQuery($query_key, $default=false)
783    {
784        if (!is_array($query_key)) {
785            $query_key = array($query_key);
786        }
787        foreach ($query_key as $k) {
788            // If not already set, and there is a non-empty value provided in the request...
789            if (!isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) {
790                // Copy the value of the specified query argument into the _carry_queries array.
791                $this->_carry_queries[$k] = getFormData($k, $default);
792                $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__);
793            }
794        }
795    }
796
797    /**
798     * dropQuery() is the opposite of carryQuery(). The specified value will not appear in
799     * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in.
800     *
801     * @access  public
802     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to remove.
803     * @param   bool    $unset      Remove any values set in the request matching the given $query_key.
804     * @author  Quinn Comendant <quinn@strangecode.com>
805     * @since   18 Jun 2007 20:57:29
806     */
807    public function dropQuery($query_key, $unset=false)
808    {
809        if (!is_array($query_key)) {
810            $query_key = array($query_key);
811        }
812        foreach ($query_key as $k) {
813            if (array_key_exists($k, $this->_carry_queries)) {
814                // Remove the value of the specified query argument from the _carry_queries array.
815                $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__);
816                unset($this->_carry_queries[$k]);
817            }
818            if ($unset && (isset($_REQUEST) && array_key_exists($k, $_REQUEST))) {
819                unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]);
820            }
821        }
822    }
823
824    /**
825     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
826     * keys and values, including optional queries. This allows mindless retention
827     * of query arguments across page requests. If cookies are not
828     * used, the session id will be propagated in the URL.
829     *
830     * @param  string $url              The initial url
831     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
832     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
833     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
834     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
835     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
836     *
837     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
838     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
839     *                                     header('Location...') redirections.
840     *
841     * @return string url with attached queries and, if not using cookies, the session id
842     */
843    public function url($url, $carry_args=null, $always_include_sid=false)
844    {
845        if (!$this->running) {
846            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
847            return false;
848        }
849
850        // Get any provided query arguments to include in the final URL.
851        // If FALSE is a provided here, DO NOT carry the queries.
852        $do_carry_queries = true;
853        $one_time_carry_queries = array();
854        if (!is_null($carry_args)) {
855            if (is_array($carry_args) && !empty($carry_args)) {
856                foreach ($carry_args as $key=>$arg) {
857                    // Get query from appropriate source.
858                    if (false === $arg) {
859                        $do_carry_queries = false;
860                    } else if (false !== getFormData($arg, false)) {
861                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
862                    } else if (!is_numeric($key) && '' != $arg) {
863                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
864                    }
865                }
866            } else if (false !== getFormData($carry_args, false)) {
867                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
868            } else if (false === $carry_args) {
869                $do_carry_queries = false;
870            }
871        }
872
873        // Get the first delimiter that is needed in the url.
874        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
875
876        $q = '';
877        if ($do_carry_queries) {
878            // Join the global _carry_queries and local one_time_carry_queries.
879            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
880            foreach ($query_args as $key=>$val) {
881                // Check value is set and value does not already exist in the url.
882                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
883                    $q .= $delim . $key . '=' . $val;
884                    $delim = ini_get('arg_separator.output');
885                }
886            }
887        }
888
889        // Include the necessary SID if the following is true:
890        // - no cookie in http request OR cookies disabled in App
891        // - sessions are enabled
892        // - the link stays on our site
893        // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
894        // OR
895        // - 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)
896        // AND
897        // - the SID is not already in the query.
898        if (
899            (
900                (
901                    (
902                        !isset($_COOKIE[session_name()])
903                        || !$this->getParam('session_use_cookies')
904                    )
905                    && $this->getParam('session_use_trans_sid')
906                    && $this->getParam('enable_session')
907                    && isMyDomain($url)
908                    && (
909                        !ini_get('session.use_trans_sid')
910                        || preg_match('!^(http|https)://!i', $url)
911                    )
912                )
913                || $always_include_sid
914            )
915            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
916        ) {
917            $url .= $q . $delim . session_name() . '=' . session_id();
918        } else {
919            $url .= $q;
920        }
921
922        return $url;
923    }
924
925    /**
926     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
927     *
928     * @access  public
929     * @param   string  $url    Input URL to parse.
930     * @return  string          URL passed through $app->url() and then & turned to $amp;.
931     * @author  Quinn Comendant <quinn@strangecode.com>
932     * @since   09 Dec 2005 17:58:45
933     */
934    public function oHREF($url, $carry_args=null, $always_include_sid=false)
935    {
936        $url = $this->url($url, $carry_args, $always_include_sid);
937
938        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
939        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
940
941        return $url;
942    }
943
944    /*
945    * 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
946    *
947    * @access   public
948    * @param    string  $url    URL to media (e.g., /foo.js)
949    * @return   string          URL with cache-busting version appended (/foo.js?v=1234567890)
950    * @author   Quinn Comendant <quinn@strangecode.com>
951    * @version  1.0
952    * @since    03 Sep 2014 22:40:24
953    */
954    public function cacheBustURL($url)
955    {
956        // Get the first delimiter that is needed in the url.
957        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
958        $v = crc32($this->getParam('codebase_version') . '|' . $this->getParam('site_version'));
959        return sprintf('%s%sv=%s', $url, $delim, $v);
960    }
961
962    /**
963     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
964     * as hidden form elements for GET_VARS that might be in use.
965     *
966     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
967     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
968     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
969     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
970     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
971     */
972    public function printHiddenSession($carry_args=null)
973    {
974        if (!$this->running) {
975            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
976            return false;
977        }
978
979        // Get any provided query arguments to include in the final hidden form data.
980        // If FALSE is a provided here, DO NOT carry the queries.
981        $do_carry_queries = true;
982        $one_time_carry_queries = array();
983        if (!is_null($carry_args)) {
984            if (is_array($carry_args) && !empty($carry_args)) {
985                foreach ($carry_args as $key=>$arg) {
986                    // Get query from appropriate source.
987                    if (false === $arg) {
988                        $do_carry_queries = false;
989                    } else if (false !== getFormData($arg, false)) {
990                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
991                    } else if (!is_numeric($key) && '' != $arg) {
992                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
993                    }
994                }
995            } else if (false !== getFormData($carry_args, false)) {
996                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
997            } else if (false === $carry_args) {
998                $do_carry_queries = false;
999            }
1000        }
1001
1002        // For each existing request value, we create a hidden input to carry it through a form.
1003        if ($do_carry_queries) {
1004            // Join the global _carry_queries and local one_time_carry_queries.
1005            // urlencode is not used here, not for form data!
1006            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
1007            foreach ($query_args as $key => $val) {
1008                if (is_array($val)) {
1009                    foreach ($val as $subval) {
1010                        printf('<input type="hidden" name="%s[]" value="%s" />', $key, $subval);
1011                    }
1012                } else {
1013                    printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
1014                }
1015            }
1016            unset($query_args, $key, $val, $subval);
1017        }
1018
1019        // Include the SID if cookies are disabled.
1020        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
1021            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
1022        }
1023    }
1024
1025    /**
1026     * Uses an http header to redirect the client to the given $url. If sessions are not used
1027     * and the session is not already defined in the given $url, the SID is appended as a URI query.
1028     * As with all header generating functions, make sure this is called before any other output.
1029     *
1030     * @param   string  $url                    The URL the client will be redirected to.
1031     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
1032     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
1033     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
1034     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
1035     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
1036     * @param   bool    $always_include_sid     Force session id to be added to Location header.
1037     */
1038    public function dieURL($url, $carry_args=null, $always_include_sid=false)
1039    {
1040        if (!$this->running) {
1041            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1042            return false;
1043        }
1044
1045        if ('' == $url) {
1046            // If URL is not specified, use the redirect_home_url.
1047            $url = $this->getParam('redirect_home_url');
1048        }
1049
1050        if (preg_match('!^/!', $url)) {
1051            // If relative URL is given, prepend correct local hostname.
1052            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
1053            $host = getenv('HTTP_HOST');
1054            $url = sprintf('%s://%s%s', $scheme, $host, $url);
1055        }
1056
1057        $url = $this->url($url, $carry_args, $always_include_sid);
1058
1059        // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP?
1060        header(sprintf('Location: %s', $url));
1061        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
1062
1063        // End application.
1064        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
1065        $this->stop();
1066        die;
1067    }
1068
1069    /*
1070    * Redirects a user by calling $app->dieURL(). It will use:
1071    * 1. the stored boomerang URL, it it exists
1072    * 2. a specified $default_url, it it exists
1073    * 3. the referring URL, it it exists.
1074    * 4. redirect_home_url configuration variable.
1075    *
1076    * @access   public
1077    * @param    string  $id             Identifier for this script.
1078    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->oHREF()).
1079    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
1080    * @param    bool    $queryless_referrer_comparison   Exclude the URL query from the refererIsMe() comparison.
1081    * @return   bool                    False if the session is not running. No return otherwise.
1082    * @author   Quinn Comendant <quinn@strangecode.com>
1083    * @since    31 Mar 2006 19:17:00
1084    */
1085    public function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false)
1086    {
1087        if (!$this->running) {
1088            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1089            return false;
1090        }
1091
1092        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
1093        if ($this->validBoomerangURL($id, true)) {
1094            if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1095                $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
1096                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1097            } else {
1098                $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1099                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1100            }
1101            // Delete stored boomerang.
1102            $this->deleteBoomerangURL($id);
1103        } else if (isset($default_url)) {
1104            $url = $default_url;
1105        } else if (!refererIsMe(true === $queryless_referrer_comparison)) {
1106            // Ensure that the redirecting page is not also the referrer.
1107            $url = getenv('HTTP_REFERER');
1108            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1109        } else {
1110            // If URL is not specified, use the redirect_home_url.
1111            $url = $this->getParam('redirect_home_url');
1112            $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1113        }
1114
1115        // A redirection will never happen immediately twice.
1116        // Set the time so ensure this doesn't happen.
1117        $_SESSION['_app'][$this->_ns]['boomerang']['time'] = time();
1118        $this->dieURL($url, $carry_args);
1119    }
1120
1121    /**
1122     * Set the URL to return to when $app->dieBoomerangURL() is called.
1123     *
1124     * @param string  $url  A fully validated URL.
1125     * @param bool  $id     An identification tag for this url.
1126     * FIXME: url garbage collection?
1127     */
1128    public function setBoomerangURL($url=null, $id=null)
1129    {
1130        if (!$this->running) {
1131            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1132            return false;
1133        }
1134        // A redirection will never happen immediately after setting the boomerangURL.
1135        // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
1136
1137        if ('' != $url && is_string($url)) {
1138            // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion).
1139            $url = preg_replace(array('/([&?])boomerang=\w+[&?]?/', '/[&?]$/'), array('$1', ''), $url);
1140
1141            if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']['url']) && !empty($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1142                // If the URL currently exists in the boomerang array, delete.
1143                while ($existing_key = array_search($url, $_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1144                    unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$existing_key]);
1145                }
1146            }
1147
1148            if (isset($id)) {
1149                $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id] = $url;
1150            } else {
1151                $_SESSION['_app'][$this->_ns]['boomerang']['url'][] = $url;
1152            }
1153            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1154            return true;
1155        } else {
1156            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
1157            return false;
1158        }
1159    }
1160
1161    /**
1162     * Return the URL set for the specified $id, or an empty string if one isn't set.
1163     *
1164     * @param string  $id     An identification tag for this url.
1165     */
1166    public function getBoomerangURL($id=null)
1167    {
1168        if (!$this->running) {
1169            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1170            return false;
1171        }
1172
1173        if (isset($id)) {
1174            if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1175                return $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
1176            } else {
1177                return '';
1178            }
1179        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1180            return end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1181        } else {
1182            return false;
1183        }
1184    }
1185
1186    /**
1187     * Delete the URL set for the specified $id.
1188     *
1189     * @param string  $id     An identification tag for this url.
1190     */
1191    public function deleteBoomerangURL($id=null)
1192    {
1193        if (!$this->running) {
1194            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1195            return false;
1196        }
1197
1198        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
1199
1200        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1201            unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]);
1202        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1203            array_pop($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1204        }
1205    }
1206
1207    /**
1208     * Check if a valid boomerang URL value has been set. A boomerang URL is considered
1209     * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds.
1210     *
1211     * @return bool  True if it is set and valid, false otherwise.
1212     */
1213    public function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
1214    {
1215        if (!$this->running) {
1216            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
1217            return false;
1218        }
1219
1220        if (!isset($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1221            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__);
1222            return false;
1223        }
1224
1225        // Time is the time stamp of a boomerangURL redirection, or setting of a boomerangURL.
1226        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
1227        // or a boomerang being set.
1228        $boomerang_time = isset($_SESSION['_app'][$this->_ns]['boomerang']['time']) ? $_SESSION['_app'][$this->_ns]['boomerang']['time'] : 0;
1229
1230        $url = '';
1231        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1232            $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
1233        } else if (!isset($id) || $use_nonspecificboomerang) {
1234            // Use non specific boomerang if available.
1235            $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
1236        }
1237
1238        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1239
1240        if ('' == $url) {
1241            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
1242            return false;
1243        }
1244        if ($url == absoluteMe()) {
1245            // The URL we are directing to is the current page.
1246            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1247            return false;
1248        }
1249        if ($boomerang_time >= (time() - 2)) {
1250            // Last boomerang direction was less than 2 seconds ago.
1251            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s seconds', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
1252            return false;
1253        }
1254
1255        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
1256        return true;
1257    }
1258
1259    /**
1260     * Force the user to connect via https (port 443) by redirecting them to
1261     * the same page but with https.
1262     */
1263    public function sslOn()
1264    {
1265        if (function_exists('apache_get_modules')) {
1266            $modules = apache_get_modules();
1267        } else {
1268            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1269            $modules = array('mod_ssl');
1270        }
1271
1272        if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1273            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1274            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1275            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1276        }
1277    }
1278
1279    /**
1280     * to enforce the user to connect via http (port 80) by redirecting them to
1281     * a http version of the current url.
1282     */
1283    public function sslOff()
1284    {
1285        if ('' != getenv('HTTPS')) {
1286            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1287        }
1288    }
1289
1290    /*
1291    * Sets a cookie, with error checking and some sane defaults.
1292    *
1293    * @access   public
1294    * @param    string  $name       The name of the cookie.
1295    * @param    string  $value      The value of the cookie.
1296    * @param    string  $expire     The time the cookie expires, as a unix timestamp or string value passed to strtotime.
1297    * @param    string  $path       The path on the server in which the cookie will be available on.
1298    * @param    string  $domain     The domain that the cookie is available to.
1299    * @param    bool    $secure     Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
1300    * @param    bool    $httponly   When TRUE the cookie will be made accessible only through the HTTP protocol (makes cookies unreadable to javascript).
1301    * @return   bool                True on success, false on error.
1302    * @author   Quinn Comendant <quinn@strangecode.com>
1303    * @version  1.0
1304    * @since    02 May 2014 16:36:34
1305    */
1306    public function setCookie($name, $value, $expire='+10 years', $path='/', $domain=null, $secure=null, $httponly=null)
1307    {
1308        if (!is_scalar($name)) {
1309            $this->logMsg(sprintf('Cookie name must be scalar, is not: %s', getDump($name)), LOG_NOTICE, __FILE__, __LINE__);
1310            return false;
1311        }
1312        if (!is_scalar($value)) {
1313            $this->logMsg(sprintf('Cookie "%s" value must be scalar, is not: %s', $name, getDump($value)), LOG_NOTICE, __FILE__, __LINE__);
1314            return false;
1315        }
1316
1317        // Defaults.
1318        $expire = (is_numeric($expire) ? $expire : (is_string($expire) ? strtotime($expire) : $expire));
1319        $secure = $secure ?: ('' != getenv('HTTPS') && $this->getParam('ssl_enabled'));
1320        $httponly = $httponly ?: true;
1321
1322        // Make sure the expiration date is a valid 32bit integer.
1323        if (is_int($expire) && $expire > 2147483647) {
1324            $this->logMsg(sprintf('Cookie "%s" expire time exceeds a 32bit integer (%s)', $key, date('r', $expire)), LOG_NOTICE, __FILE__, __LINE__);
1325        }
1326
1327        // Measure total cookie length and warn if larger than max recommended size of 4093.
1328        // https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key
1329        // The date the header name include 51 bytes: Set-Cookie: ; expires=Fri, 03-May-2024 00:04:47 GMT
1330        $cookielen = strlen($name . $value . $path . $domain . ($secure ? '; secure' : '') . ($httponly ? '; httponly' : '')) + 51;
1331        if ($cookielen > 4093) {
1332            $this->logMsg(sprintf('Cookie "%s" has a size greater than 4093 bytes (is %s bytes)', $key, $cookielen), LOG_NOTICE, __FILE__, __LINE__);
1333        }
1334
1335        // Ensure PHP version allow use of httponly.
1336        if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
1337            $ret = setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
1338        } else {
1339            $ret = setcookie($name, $value, $expire, $path, $domain, $secure);
1340        }
1341
1342        if (false === $ret) {
1343            $this->logMsg(sprintf('Failed to set cookie (%s=%s) probably due to output before headers.', $name, $value), LOG_NOTICE, __FILE__, __LINE__);
1344        }
1345        return $ret;
1346    }
1347} // End.
Note: See TracBrowser for help on using the repository browser.