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

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

Disabled header output when _CLI is defined.

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