source: branches/2.0singleton/lib/App.inc.php @ 154

Last change on this file since 154 was 135, checked in by scdev, 18 years ago

Q - Finished integrating singleton methods into existing code. Renamed SessionCache? to Cache, and renamed methods in Cache and Prefs

File size: 42.3 KB
Line 
1<?php
2/**
3 * App.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Primary application framework class.
7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
9 * @version 2.1
10 */
11
12// Message Types.
13define('MSG_ERR', 1);
14define('MSG_ERROR', MSG_ERR);
15define('MSG_WARNING', 2);
16define('MSG_NOTICE', 4);
17define('MSG_SUCCESS', 8);
18define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR);
19
20require_once dirname(__FILE__) . '/Utilities.inc.php';
21
22class App {
23
24    // Namespace of this application instance.
25    var $ns;
26
27    // If $app->start has run successfully.
28    var $running = false;
29
30    // Instance of database object.
31    var $db;
32
33    // Array of query arguments will be carried persistently between requests.
34    var $_carry_queries = array();
35
36    // Dictionary of global application parameters.
37    var $_params = array();
38
39    // Default parameters.
40    var $_param_defaults = array(
41
42        // Public name and email address for this application.
43        'site_name' => null,
44        'site_email' => null,
45        'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here.
46
47        // The location the user will go if the system doesn't know where else to send them.
48        'redirect_home_url' => '/',
49
50        // SSL URL used when redirecting with $app->sslOn().
51        'ssl_domain' => null,
52        'ssl_enabled' => false,
53
54        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
55        'character_set' => 'utf-8',
56
57        // Human-readable format used to display dates.
58        'date_format' => 'd M Y',
59        'time_format' => 'h:i:s A',
60        'sql_date_format' => '%e %b %Y',
61        'sql_time_format' => '%k:%i',
62
63        // Use php sessions?
64        'enable_session' => false,
65        'session_name' => 'Strangecode',
66        'session_use_cookies' => true,
67
68        // Use database?
69        'enable_db' => false,
70
71        // Use db-based sessions?
72        'enable_db_session_handler' => false,
73
74        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
75        'db_server' => 'localhost',
76        'db_name' => null,
77        'db_user' => null,
78        'db_pass' => null,
79
80        // Database debugging.
81        'db_always_debug' => false, // TRUE = display all SQL queries.
82        'db_debug' => false, // TRUE = display db errors.
83        'db_die_on_failure' => false, // TRUE = script stops on db error.
84
85        // For classes that require db tables, do we check that a table exists and create if missing?
86        'db_create_tables' => true,
87
88        // The level of error reporting. Don't set this to 0 to suppress messages, instead use display_errors to control display.
89        'error_reporting' => E_ALL,
90
91        // Don't display errors by default; it is preferable to log them to a file.
92        'display_errors' => false,
93
94        // Directory in which to store log files.
95        'log_directory' => '',
96
97        // PHP error log.
98        'php_error_log' => 'php_error_log',
99
100        // General application log.
101        'log_filename' => 'app_log',
102
103        // Logging priority can be any of the following, or false to deactivate:
104        // LOG_EMERG     system is unusable
105        // LOG_ALERT     action must be taken immediately
106        // LOG_CRIT      critical conditions
107        // LOG_ERR       error conditions
108        // LOG_WARNING   warning conditions
109        // LOG_NOTICE    normal, but significant, condition
110        // LOG_INFO      informational message
111        // LOG_DEBUG     debug-level message
112        'log_file_priority' => false,
113        'log_email_priority' => false,
114        'log_sms_priority' => false,
115        'log_screen_priority' => false,
116
117        // Email address to receive log event emails.
118        'log_to_email_address' => null,
119
120        // SMS Email address to receive log event SMS messages.
121        'log_to_sms_address' => null,
122
123        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
124        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
125    );
126
127    /**
128     * This method enforces the singleton pattern for this class. Only one application is running at a time.
129     *
130     * $param   string  $namespace  Name of this application.
131     * @return  object  Reference to the global Cache object.
132     * @access  public
133     * @static
134     */
135    function &getInstance($namespace='')
136    {
137        static $instance = null;
138
139        if ($instance === null) {
140            $instance = new App($namespace);
141        }
142
143        return $instance;
144    }
145
146    /**
147     * Constructor.
148     */
149    function App($namespace='')
150    {
151        // Set namespace of application instance.
152        $this->ns = '_app_' . $namespace;
153
154        // Initialize default parameters.
155        $this->_params = array_merge($this->_params, $this->_param_defaults);
156    }
157
158    /**
159     * Set (or overwrite existing) parameters by passing an array of new parameters.
160     *
161     * @access public
162     * @param  array    $param     Array of parameters (key => val pairs).
163     */
164    function setParam($param=null)
165    {
166        if (isset($param) && is_array($param)) {
167            // Merge new parameters with old overriding only those passed.
168            $this->_params = array_merge($this->_params, $param);
169        }
170    }
171
172    /**
173     * Return the value of a parameter.
174     *
175     * @access  public
176     * @param   string  $param      The key of the parameter to return.
177     * @return  mixed               Parameter value, or null if not existing.
178     */
179    function getParam($param=null)
180    {
181        if ($param === null) {
182            return $this->_params;
183        } else if (isset($this->_params[$param])) {
184            return $this->_params[$param];
185        } else {
186            trigger_error(sprintf('Parameter is not set: %s', $param), E_USER_NOTICE);
187            return null;
188        }
189    }
190
191    /**
192     * Begin running this application.
193     *
194     * @access  public
195     * @author  Quinn Comendant <quinn@strangecode.com>
196     * @since   15 Jul 2005 00:32:21
197     */
198    function start()
199    {
200        if ($this->running) {
201            return false;
202        }
203
204        // Error reporting.
205        ini_set('error_reporting', $this->getParam('error_reporting'));
206        ini_set('display_errors', $this->getParam('display_errors'));
207        ini_set('log_errors', true);
208        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
209            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
210        }
211
212
213        /**
214         * 1. Start Database.
215         */
216
217        if (true === $this->getParam('enable_db')) {
218
219            // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root.
220            if (!empty($_SERVER['DB_SERVER'])) {
221                $this->setParam(array('db_server' => $_SERVER['DB_SERVER']));
222            }
223            if (!empty($_SERVER['DB_NAME'])) {
224                $this->setParam(array('db_name' => $_SERVER['DB_NAME']));
225            }
226            if (!empty($_SERVER['DB_USER'])) {
227                $this->setParam(array('db_user' => $_SERVER['DB_USER']));
228            }
229            if (!empty($_SERVER['DB_PASS'])) {
230                $this->setParam(array('db_pass' => $_SERVER['DB_PASS']));
231            }
232
233            // There will ever only be one instance of the DB object, and here is where it is instantiated.
234            require_once dirname(__FILE__) . '/DB.inc.php';
235            $this->db =& DB::getInstance();
236            $this->db->setParam(array(
237                'db_server' => $this->getParam('db_server'),
238                'db_name' => $this->getParam('db_name'),
239                'db_user' => $this->getParam('db_user'),
240                'db_pass' => $this->getParam('db_pass'),
241                'db_always_debug' => $this->getParam('db_always_debug'),
242                'db_debug' => $this->getParam('db_debug'),
243                'db_die_on_failure' => $this->getParam('db_die_on_failure'),
244            ));
245
246            // Connect to database.
247            $this->db->connect();
248        }
249
250
251        /**
252         * 2. Start PHP session.
253         */
254
255        // Skip session for some user agents.
256        if (preg_match('/Atomz|ApacheBench|Wget/i', getenv('HTTP_USER_AGENT'))) {
257            $this->setParam(array('enable_session' => false));
258        }
259
260        if (true === $this->getParam('enable_session')) {
261
262            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
263                // Database session handling.
264                require_once dirname(__FILE__) . '/DBSessionHandler.inc.php';
265                $db_save_handler = new DBSessionHandler($this->db, array(
266                    'db_table' => 'session_tbl',
267                    'create_table' => $this->getParam('db_create_tables'),
268                ));
269            }
270
271            // Session parameters.
272            ini_set('session.use_cookies', $this->getParam('session_use_cookies'));
273            ini_set('session.use_trans_sid', false);
274            ini_set('session.entropy_file', '/dev/urandom');
275            ini_set('session.entropy_length', '512');
276            session_name($this->getParam('session_name'));
277
278            // Start the session.
279            session_start();
280
281            if (!isset($_SESSION[$this->ns])) {
282                // Access session data using: $_SESSION['...'].
283                // Initialize here _after_ session has started.
284                $_SESSION[$this->ns] = array(
285                    'messages' => array(),
286                    'boomerang' => array('url'),
287                );
288            }
289        }
290
291
292        /**
293         * 3. Misc setup.
294         */
295
296        // Script URI will be something like http://host.name.tld (no ending slash)
297        // and is used whenever a URL need be used to the current site.
298        // Not available on cli scripts obviously.
299        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) {
300            $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'))));
301        }
302
303        // A key for calculating simple cryptographic signatures.
304        if (isset($_SERVER['SIGNING_KEY'])) {
305            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
306        }
307
308        // Character set. This should also be printed in the html header template.
309        header('Content-type: text/html; charset=' . $this->getParam('character_set'));
310
311        $this->running = true;
312    }
313
314    /**
315     * Stop running this application.
316     *
317     * @access  public
318     * @author  Quinn Comendant <quinn@strangecode.com>
319     * @since   17 Jul 2005 17:20:18
320     */
321    function stop()
322    {
323        session_write_close();
324        restore_include_path();
325        $this->running = false;
326        if (true === $this->getParam('enable_db')) {
327            $this->db->close();
328        }
329    }
330
331
332    /**
333     * Add a message to the session, which is printed in the header.
334     * Just a simple way to print messages to the user.
335     *
336     * @access public
337     *
338     * @param string $message The text description of the message.
339     * @param int    $type    The type of message: MSG_NOTICE,
340     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
341     * @param string $file    __FILE__.
342     * @param string $line    __LINE__.
343     */
344    function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
345    {
346        $message = trim($message);
347
348        if (!$this->running || '' == $message) {
349            $this->logMsg(sprintf('Canceled method call %s, application not running or message is an empty string.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
350            return false;
351        }
352
353        // Save message in session under unique key to avoid duplicate messages.
354        $msg_id = md5($type . $message . $file . $line);
355        $_SESSION[$this->ns]['messages'][$msg_id] = array(
356            'type'    => $type,
357            'message' => $message,
358            'file'    => $file,
359            'line'    => $line,
360            'count'   => (isset($_SESSION[$this->ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION[$this->ns]['messages'][$msg_id]['count']) : 1)
361        );
362
363        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
364            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__);
365        }
366    }
367   
368    /**
369     * Returns an array of the raised messages.
370     *
371     * @access  public
372     * @return  array   List of messags in FIFO order.
373     * @author  Quinn Comendant <quinn@strangecode.com>
374     * @since   21 Dec 2005 13:09:20
375     */
376    function getRaisedMessages()
377    {
378        if (!$this->running) {
379            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
380            return false;
381        }
382       
383        $output = array();
384        while (isset($_SESSION[$this->ns]['messages']) && $message = array_shift($_SESSION[$this->ns]['messages'])) {
385            $output[] = $message;
386        }
387        return $output;
388    }
389   
390    /**
391     * Resets the message list.
392     *
393     * @access  public
394     * @author  Quinn Comendant <quinn@strangecode.com>
395     * @since   21 Dec 2005 13:21:54
396     */
397    function clearRaisedMessages()
398    {
399        if (!$this->running) {
400            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
401            return false;
402        }
403       
404        $_SESSION[$this->ns]['messages'] = array();
405    }
406
407    /**
408     * Prints the HTML for displaying raised messages.
409     *
410     * @access  public
411     * @author  Quinn Comendant <quinn@strangecode.com>
412     * @since   15 Jul 2005 01:39:14
413     */
414    function printRaisedMessages()
415    {
416        if (!$this->running) {
417            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
418            return false;
419        }
420
421        while (isset($_SESSION[$this->ns]['messages']) && $message = array_shift($_SESSION[$this->ns]['messages'])) {
422            ?><div class="sc-msg"><?php
423            if (error_reporting() > 0 && $this->getParam('display_errors')) {
424                echo "\n<!-- [" . $message['file'] . ' : ' . $message['line'] . '] -->';
425            }
426            switch ($message['type']) {
427            case MSG_ERR:
428                echo '<div class="sc-msg-error">' . $message['message'] . '</div>';
429                break;
430
431            case MSG_WARNING:
432                echo '<div class="sc-msg-warning">' . $message['message'] . '</div>';
433                break;
434
435            case MSG_SUCCESS:
436                echo '<div class="sc-msg-success">' . $message['message'] . '</div>';
437                break;
438
439            case MSG_NOTICE:
440            default:
441                echo '<div class="sc-msg-notice">' . $message['message'] . '</div>';
442                break;
443
444            }
445            ?></div><?php
446        }
447    }
448
449    /**
450     * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are
451     * not repeated but printed once with count.
452     *
453     * @access public
454     * @param string $message   The text description of the message.
455     * @param int    $priority  The type of message priority (in descending order):
456     *                          LOG_EMERG     system is unusable
457     *                          LOG_ALERT     action must be taken immediately
458     *                          LOG_CRIT      critical conditions
459     *                          LOG_ERR       error conditions
460     *                          LOG_WARNING   warning conditions
461     *                          LOG_NOTICE    normal, but significant, condition
462     *                          LOG_INFO      informational message
463     *                          LOG_DEBUG     debug-level message
464     * @param string $file      The file where the log event occurs.
465     * @param string $line      The line of the file where the log event occurs.
466     */
467    function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
468    {
469        static $previous_events = array();
470
471        // If priority is not specified, assume the worst.
472        if (!$this->logPriorityToString($priority)) {
473            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
474            $priority = LOG_EMERG;
475        }
476
477        // If log file is not specified, don't log to a file.
478        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
479            $this->setParam(array('log_file_priority' => false));
480            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
481            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
482        }
483
484        // Make sure to log in the system's locale.
485        $locale = setlocale(LC_TIME, 0);
486        setlocale(LC_TIME, 'C');
487
488        // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>.
489        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow);
490        $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
491
492        // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times.
493        $msg_id = md5($message . $priority . $file . $line);
494        if (isset($previous_events[$msg_id])) {
495            $previous_events[$msg_id]++;
496            if ($previous_events[$msg_id] == 2) {
497                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
498            }
499            return false;
500        } else {
501            $previous_events[$msg_id] = 1;
502        }
503       
504        // Data to be stored for a log event.
505        $event = array(
506            'date'      => date('Y-m-d H:i:s'),
507            'remote ip' => getRemoteAddr(),
508            'pid'       => (substr(PHP_OS, 0, 3) != 'WIN' ? posix_getpid() : ''),
509            'type'      => $this->logPriorityToString($priority),
510            'file:line' => "$file : $line",
511            'url'       => (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''),
512            'message'   => $message
513        );
514
515        // FILE ACTION
516        if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
517            $event_str = '[' . join('] [', $event) . ']';
518            error_log($event_str . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
519        }
520
521        // EMAIL ACTION
522        if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) {
523            $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message);
524            $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST'));
525            $headers = "From: codebase@strangecode.com";
526            foreach ($event as $k=>$v) {
527                $email_msg .= sprintf("%-11s%s\n", $k, $v);
528            }
529            mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
530        }
531
532        // SMS ACTION
533        if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) {
534            $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority);
535            $sms_msg = sprintf('%s [%s:%s]', $event['message'], basename($file), $line);
536            $headers = "From: codebase@strangecode.com";
537            mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
538        }
539
540        // SCREEN ACTION
541        if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
542            echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
543        }
544
545        // Restore original locale.
546        setlocale(LC_TIME, $locale);
547    }
548
549    /**
550     * Returns the string representation of a LOG_* integer constant.
551     *
552     * @param int  $priority  The LOG_* integer constant.
553     *
554     * @return                The string representation of $priority.
555     */
556    function logPriorityToString ($priority) {
557        $priorities = array(
558            LOG_EMERG   => 'emergency',
559            LOG_ALERT   => 'alert',
560            LOG_CRIT    => 'critical',
561            LOG_ERR     => 'error',
562            LOG_WARNING => 'warning',
563            LOG_NOTICE  => 'notice',
564            LOG_INFO    => 'info',
565            LOG_DEBUG   => 'debug'
566        );
567        if (isset($priorities[$priority])) {
568            return $priorities[$priority];
569        } else {
570            return false;
571        }
572    }
573
574    /**
575     * Sets which query arguments will be carried persistently between requests.
576     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
577     * to hidden input values (via printHiddenSession()).
578     *
579     * @access  public
580     * @param   string  $query_key  The key of the query argument to save.
581     * @author  Quinn Comendant <quinn@strangecode.com>
582     * @since   14 Nov 2005 19:24:52
583     */
584    function carryQuery($query_key)
585    {
586        // If not already set, and there is a non-empty value provided in the request...
587        if (!isset($this->_carry_queries[$query_key]) && getFormData($query_key, false)) {
588            // Copy the value of the specified query argument into the _carry_queries array.
589            $this->_carry_queries[$query_key] = getFormData($query_key);
590        }
591    }
592
593    /**
594     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
595     * keys and values, including optional queries. This allows mindless retention
596     * of query arguments across page requests. If cookies are not
597     * used, the session id will be propogated in the URL.
598     *
599     * @param  string $url              The initial url
600     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
601     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
602     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
603     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
604     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
605     *
606     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
607     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
608     *                                     header('Location...') redirections.
609     *
610     * @return string url with attached queries and, if not using cookies, the session id
611     */
612    function url($url, $carry_args=null, $always_include_sid=false)
613    {
614        if (!$this->running) {
615            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
616            return false;
617        }
618
619        // Get any provided query arguments to include in the final URL.
620        // If FALSE is a provided here, DO NOT carry the queries.
621        $do_carry_queries = true;
622        $one_time_carry_queries = array();
623        if (!is_null($carry_args)) {
624            if (is_array($carry_args) && !empty($carry_args)) {
625                foreach ($carry_args as $key=>$arg) {
626                    // Get query from appropriate source.
627                    if (false === $arg) {
628                        $do_carry_queries = false;
629                    } else if (false !== getFormData($arg, false)) {
630                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
631                    } else if (!is_numeric($key) && '' != $arg) {
632                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
633                    }
634                }
635            } else if (false !== getFormData($carry_args, false)) {
636                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
637            } else if (false === $carry_args) {
638                $do_carry_queries = false;
639            }
640        }
641
642        // Get the first delimiter that is needed in the url.
643        $delim = strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
644
645
646        $q = '';
647        if ($do_carry_queries) {
648            // Join the global _carry_queries and local one_time_carry_queries.
649            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
650            foreach ($query_args as $key=>$val) {
651                // Check value is set and value does not already exist in the url.
652                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
653                    $q .= $delim . $key . '=' . $val;
654                    $delim = ini_get('arg_separator.output');
655                }
656            }
657        }
658
659        // Include the necessary SID if the following is true:
660        // - no cookie in http request OR cookies disabled in App
661        // - sessions are enabled
662        // - the link stays on our site
663        // - transparent SID propogation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
664        // OR
665        // - 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)
666        // AND
667        // - the SID is not already in the query.
668        if (
669            (
670                (
671                    (
672                        !isset($_COOKIE[session_name()])
673                        || !$this->getParam('session_use_cookies')
674                    )
675                    && $this->getParam('enable_session')
676                    && isMyDomain($url)
677                    &&
678                    (
679                        !ini_get('session.use_trans_sid')
680                        || preg_match('!^(http|https)://!i', $url)
681                    )
682                )
683                || $always_include_sid
684            )
685            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
686        ) {
687            $url .= $q . $delim . session_name() . '=' . session_id();
688            return $url;
689        } else {
690            $url .= $q;
691            return $url;
692        }
693    }
694
695    /**
696     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
697     *
698     * @access  public
699     * @param   string  $url    Input URL to parse.
700     * @return  string          URL with $app->url() and htmlentities() applied.
701     * @author  Quinn Comendant <quinn@strangecode.com>
702     * @since   09 Dec 2005 17:58:45
703     */
704    function oHREF($url, $carry_args=null, $always_include_sid=false)
705    {
706        $url = $this->url($url, $carry_args, $always_include_sid);
707
708        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
709        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
710
711        return $url;
712    }
713
714    /**
715     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
716     * as hidden form elements for GET_VARS that might be in use.
717     *
718     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
719     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
720     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
721     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
722     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
723     */
724    function printHiddenSession($carry_args=null)
725    {
726        if (!$this->running) {
727            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
728            return false;
729        }
730
731        // Get any provided query arguments to include in the final hidden form data.
732        // If FALSE is a provided here, DO NOT carry the queries.
733        $do_carry_queries = true;
734        $one_time_carry_queries = array();
735        if (!is_null($carry_args)) {
736            if (is_array($carry_args) && !empty($carry_args)) {
737                foreach ($carry_args as $key=>$arg) {
738                    // Get query from appropriate source.
739                    if (false === $arg) {
740                        $do_carry_queries = false;
741                    } else if (false !== getFormData($arg, false)) {
742                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
743                    } else if (!is_numeric($key) && '' != $arg) {
744                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
745                    }
746                }
747            } else if (false !== getFormData($carry_args, false)) {
748                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
749            } else if (false === $carry_args) {
750                $do_carry_queries = false;
751            }
752        }
753
754        // For each existing POST value, we create a hidden input to carry it through a form.
755        if ($do_carry_queries) {
756            // Join the global _carry_queries and local one_time_carry_queries.
757            // urlencode is not used here, not for form data!
758            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
759            foreach ($query_args as $key=>$val) {
760                printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
761            }
762        }
763
764        // Include the SID if cookies are disabled.
765        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
766            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
767        }
768    }
769
770    /**
771     * Uses an http header to redirect the client to the given $url. If sessions are not used
772     * and the session is not already defined in the given $url, the SID is appended as a URI query.
773     * As with all header generating functions, make sure this is called before any other output.
774     *
775     * @param   string  $url                    The URL the client will be redirected to.
776     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
777     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
778     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
779     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
780     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
781     * @param   bool    $always_include_sid     Force session id to be added to Location header.
782     */
783    function dieURL($url, $carry_args=null, $always_include_sid=false)
784    {
785        if (!$this->running) {
786            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
787            return false;
788        }
789
790        if ('' == $url) {
791            // If URL is not specified, use the redirect_home_url.
792            $url = $this->getParam('redirect_home_url');
793        }
794
795        if (preg_match('!^/!', $url)) {
796            // If relative URL is given, prepend correct local hostname.
797            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
798            $host = getenv('HTTP_HOST');
799            $url = sprintf('%s://%s%s', $scheme, $host, $url);
800        }
801
802        $url = $this->url($url, $carry_args, $always_include_sid);
803
804        header(sprintf('Location: %s', $url));
805        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
806
807        // End this application.
808        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
809        $this->stop();
810        die;
811    }
812
813    /*
814    * Redirects a user by calling $app->dieURL(). It will use:
815    * 1. the stored boomerang URL, it it exists
816    * 2. a specified $default_url, it it exists
817    * 3. the referring URL, it it exists.
818    * 4. redirect_home_url configuration variable.
819    *
820    * @access   public
821    * @param    string  $id             Identifier for this script.
822    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->oHREF()).
823    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
824    * @return   bool                    False if the session is not running. No return otherwise.
825    * @author   Quinn Comendant <quinn@strangecode.com>
826    * @since    31 Mar 2006 19:17:00
827    */
828    function dieBoomerangURL($id=null, $carry_args=null, $default_url=null)
829    {
830        if (!$this->running) {
831            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
832            return false;
833        }
834
835        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
836        if ($this->validBoomerangURL($id, true)) {
837            if (isset($id) && isset($_SESSION[$this->ns]['boomerang']['url'][$id])) {
838                $url = $_SESSION[$this->ns]['boomerang']['url'][$id];
839                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
840            } else {
841                $url = end($_SESSION[$this->ns]['boomerang']['url']);
842                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
843            }
844            // Delete stored boomerang.
845            $this->deleteBoomerangURL($id);
846        } else if (isset($default_url)) {
847            $url = $default_url;
848        } else if (!refererIsMe()) {
849            // Ensure that the redirecting page is not also the referrer.
850            $url = getenv('HTTP_REFERER');
851            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
852        } else {
853            // If URL is not specified, use the redirect_home_url.
854            $url = $this->getParam('redirect_home_url');
855            $this->logMsg(sprintf('dieBoomerangURL(%s) not found, using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
856        }
857
858        // A redirection will never happen immediately twice.
859        // Set the time so ensure this doesn't happen.
860        $_SESSION[$this->ns]['boomerang']['time'] = time();
861        $this->dieURL($url, $carry_args);
862    }
863
864    /**
865     * Set the URL to return to when $app->dieBoomerangURL() is called.
866     *
867     * @param string  $url  A fully validated URL.
868     * @param bool  $id     An identification tag for this url.
869     * FIXME: url garbage collection?
870     */
871    function setBoomerangURL($url=null, $id=null)
872    {
873        if (!$this->running) {
874            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
875            return false;
876        }
877        // A redirection will never happen immediately after setting the boomerangURL.
878        // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
879
880        if ('' != $url && is_string($url)) {
881            // Delete any boomerang request keys in the query string.
882            $url = preg_replace('/boomerang=[\w]+/', '', $url);
883
884            if (isset($_SESSION[$this->ns]['boomerang']['url']) && is_array($_SESSION[$this->ns]['boomerang']['url']) && !empty($_SESSION[$this->ns]['boomerang']['url'])) {
885                // If the URL currently exists in the boomerang array, delete.
886                while ($existing_key = array_search($url, $_SESSION[$this->ns]['boomerang']['url'])) {
887                    unset($_SESSION[$this->ns]['boomerang']['url'][$existing_key]);
888                }
889            }
890
891            if (isset($id)) {
892                $_SESSION[$this->ns]['boomerang']['url'][$id] = $url;
893            } else {
894                $_SESSION[$this->ns]['boomerang']['url'][] = $url;
895            }
896            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
897            return true;
898        } else {
899            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
900            return false;
901        }
902    }
903
904    /**
905     * Return the URL set for the specified $id.
906     *
907     * @param string  $id     An identification tag for this url.
908     */
909    function getBoomerangURL($id=null)
910    {
911        if (!$this->running) {
912            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
913            return false;
914        }
915
916        if (isset($id)) {
917            if (isset($_SESSION[$this->ns]['boomerang']['url'][$id])) {
918                return $_SESSION[$this->ns]['boomerang']['url'][$id];
919            } else {
920                return '';
921            }
922        } else if (is_array($_SESSION[$this->ns]['boomerang']['url'])) {
923            return end($_SESSION[$this->ns]['boomerang']['url']);
924        } else {
925            return false;
926        }
927    }
928
929    /**
930     * Delete the URL set for the specified $id.
931     *
932     * @param string  $id     An identification tag for this url.
933     */
934    function deleteBoomerangURL($id=null)
935    {
936        if (!$this->running) {
937            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
938            return false;
939        }
940
941        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
942
943        if (isset($id) && isset($_SESSION[$this->ns]['boomerang']['url'][$id])) {
944            unset($_SESSION[$this->ns]['boomerang']['url'][$id]);
945        } else if (is_array($_SESSION[$this->ns]['boomerang']['url'])) {
946            array_pop($_SESSION[$this->ns]['boomerang']['url']);
947        }
948    }
949
950    /**
951     * Check if a valid boomerang URL value has been set. A boomerang URL is considered
952     * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds.
953     *
954     * @return bool  True if it is set and valid, false otherwise.
955     */
956    function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
957    {
958        if (!$this->running) {
959            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
960            return false;
961        }
962
963        if (!isset($_SESSION[$this->ns]['boomerang']['url'])) {
964            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__);
965            return false;
966        }
967
968        // Time is the timestamp of a boomerangURL redirection, or setting of a boomerangURL.
969        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
970        // or a boomerang being set.
971        $boomerang_time = isset($_SESSION[$this->ns]['boomerang']['time']) ? $_SESSION[$this->ns]['boomerang']['time'] : 0;
972
973        $url = '';
974        if (isset($id) && isset($_SESSION[$this->ns]['boomerang']['url'][$id])) {
975            $url = $_SESSION[$this->ns]['boomerang']['url'][$id];
976        } else if (!isset($id) || $use_nonspecificboomerang) {
977            // Use non specific boomerang if available.
978            $url = end($_SESSION[$this->ns]['boomerang']['url']);
979        }
980
981        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
982
983        if ('' == $url) {
984            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
985            return false;
986        }
987        if ($url == absoluteMe()) {
988            // The URL we are directing to is the current page.
989            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
990            return false;
991        }
992        if ($boomerang_time >= (time() - 2)) {
993            // Last boomerang direction was more than 2 seconds ago.
994            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
995            return false;
996        }
997
998        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
999        return true;
1000    }
1001
1002    /**
1003     * Force the user to connect via https (port 443) by redirecting them to
1004     * the same page but with https.
1005     */
1006    function sslOn()
1007    {
1008        if (function_exists('apache_get_modules')) {
1009            $modules = apache_get_modules();
1010        } else {
1011            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1012            $modules = array('mod_ssl');
1013        }
1014
1015        if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1016            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1017            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1018            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1019        }
1020    }
1021
1022
1023    /**
1024     * to enforce the user to connect via http (port 80) by redirecting them to
1025     * a http version of the current url.
1026     */
1027    function sslOff()
1028    {
1029        if ('' != getenv('HTTPS')) {
1030            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1031        }
1032    }
1033
1034
1035} // End.
1036
1037?>
Note: See TracBrowser for help on using the repository browser.