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

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