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

Last change on this file since 37 was 37, checked in by scdev, 19 years ago

updated messaging functionality in Upload::

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_ERR', 1);
14define('MSG_ERROR', MSG_ERR);
15define('MSG_WARNING', 2);
16define('MSG_NOTICE', 4);
17define('MSG_SUCCESS', 8);
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        // Save message in session under unique key to avoid duplicate messages.
376        $_SESSION[$this->app]['messages'][md5($type . $message . $file . $line)] = array(
377            'type'    => $type, 
378            'message' => $message,
379            'file'    => $file,
380            'line'    => $line
381        );
382       
383        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
384            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_DEBUG, __FILE__, __LINE__);
385        }
386    }
387   
388    /**
389     * Prints the HTML for displaying raised messages.
390     *
391     * @access  public
392     * @author  Quinn Comendant <quinn@strangecode.com>
393     * @since   15 Jul 2005 01:39:14
394     */
395    function printRaisedMessages()
396    {
397        if (!isset($this) || !is_a($this, 'App')) {
398            $this =& App::getInstance();
399        }
400
401        if (!$this->running) {
402            return false;
403        }
404
405        while (isset($_SESSION[$this->app]['messages']) && $message = array_shift($_SESSION[$this->app]['messages'])) {
406            ?><div class="codebasemsg"><?php
407            if (error_reporting() > 0 && $this->getParam('display_errors')) {
408                echo "\n<!-- [" . $message['file'] . ' : ' . $message['line'] . '] -->';
409            }
410            switch ($message['type']) {
411            case MSG_ERR:
412                echo '<div class="error">' . $message['message'] . '</div>';
413                break;
414   
415            case MSG_WARNING:
416                echo '<div class="warning">' . $message['message'] . '</div>';
417                break;
418   
419            case MSG_SUCCESS:
420                echo '<div class="success">' . $message['message'] . '</div>';
421                break;
422   
423            case MSG_NOTICE:
424            default:
425                echo '<div class="notice">' . $message['message'] . '</div>';
426                break;
427   
428            }
429            ?></div><?php
430        }
431    }
432   
433    /**
434     * Logs a message to a user defined log file. Additional actions to take for
435     * different types of message types can be specified (ERROR, NOTICE, etc).
436     *
437     * @access public
438     *
439     * @param string $message   The text description of the message.
440     * @param int    $priority  The type of message priority (in descending order):
441     *                          LOG_EMERG     system is unusable
442     *                          LOG_ALERT     action must be taken immediately
443     *                          LOG_CRIT      critical conditions
444     *                          LOG_ERR       error conditions
445     *                          LOG_WARNING   warning conditions
446     *                          LOG_NOTICE    normal, but significant, condition
447     *                          LOG_INFO      informational message
448     *                          LOG_DEBUG     debug-level message
449     * @param string $file      The file where the log event occurs.
450     * @param string $line      The line of the file where the log event occurs.
451     */
452    function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
453    {
454        if (!isset($this) || !is_a($this, 'App')) {
455            $this =& App::getInstance();
456        }
457       
458        // If priority is not specified, assume the worst.
459        if (!$this->logPriorityToString($priority)) {
460            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
461            $priority = LOG_EMERG;
462        }
463   
464        // If log file is not specified, don't log to a file.
465        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
466            $this->setParam(array('log_file_priority' => false));
467            // We must use trigger_error to report this problem rather than calling App::logMsg, which might lead to an infinite loop.
468            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
469        }
470       
471        // Make sure to log in the system's locale.
472        $locale = setlocale(LC_TIME, 0);
473        setlocale(LC_TIME, 'C');
474       
475        // Data to be stored for a log event.
476        $event = array();
477        $event['date'] = date('Y-m-d H:i:s');
478        $event['remote ip'] = getRemoteAddr();
479        if (substr(PHP_OS, 0, 3) != 'WIN') {
480            $event['pid'] = posix_getpid();
481        }
482        $event['type'] = $this->logPriorityToString($priority);
483        $event['file:line'] = "$file : $line";
484        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow); // <...> with lots of chars maybe we don't want stripped.
485        $event['message'] = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
486        $event_str = '[' . join('] [', $event) . ']';
487       
488        // FILE ACTION
489        if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
490            error_log($event_str . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
491        }
492   
493        // EMAIL ACTION
494        if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) {
495            $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message);
496            $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST'));
497            $headers = "From: codebase@strangecode.com\r\n";
498            foreach ($event as $k=>$v) {
499                $email_msg .= sprintf("%-11s%s\n", $k, $v);
500            }
501            mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
502        }
503       
504        // SMS ACTION
505        if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) {
506            $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority);
507            $sms_msg = sprintf('%s:%s %s', basename($file), $line, $event['message']);
508            $headers = "From: codebase@strangecode.com\r\n";
509            mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
510        }
511   
512        // SCREEN ACTION
513        if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
514            echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
515        }
516   
517        // Restore original locale.
518        setlocale(LC_TIME, $locale);
519    }
520   
521    /**
522     * Returns the string representation of a LOG_* integer constant.
523     *
524     * @param int  $priority  The LOG_* integer constant.
525     *
526     * @return                The string representation of $priority.
527     */
528    function logPriorityToString ($priority) {
529        $priorities = array(
530            LOG_EMERG   => 'emergency',
531            LOG_ALERT   => 'alert',
532            LOG_CRIT    => 'critical',
533            LOG_ERR     => 'error',
534            LOG_WARNING => 'warning',
535            LOG_NOTICE  => 'notice',
536            LOG_INFO    => 'info',
537            LOG_DEBUG   => 'debug'
538        );
539        if (isset($priorities[$priority])) {
540            return $priorities[$priority];
541        } else {
542            return false;
543        }
544    }
545   
546    /**
547     * Sets which query arguments will be carried persistently between requests.
548     * Values in the _carry_queries array will be copied to URLs (via App::url()) and
549     * to hidden input values (via printHiddenSession()).
550     *
551     * @access  public
552     * @param   string  $query_key  The key of the query argument to save. 
553     * @author  Quinn Comendant <quinn@strangecode.com>
554     * @since   14 Nov 2005 19:24:52
555     */
556    function carryQuery($query_key)
557    {
558        if (!isset($this) || !is_a($this, 'App')) {
559            $this =& App::getInstance();
560        }
561       
562        // If not already set, and there is a non-empty value provided in the request...
563        if (!isset($this->_carry_queries[$query_key]) && getFormData($query_key, false)) {
564            // Copy the value of the specified query argument into the _carry_queries array.
565            $this->_carry_queries[$query_key] = getFormData($query_key);
566        }
567    }
568   
569    /**
570     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
571     * keys and values, including optional queries. This allows mindless retention
572     * of query arguments across page requests. If cookies are not
573     * used, the session id will be propogated in the URL.
574     *
575     * @param  string $url              The initial url
576     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
577     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
578     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
579     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
580     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
581     *
582     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
583     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
584     *                                     header('Location...') redirections.
585     *
586     * @return string url with attached queries and, if not using cookies, the session id
587     */
588    function url($url, $carry_args=null, $always_include_sid=false)
589    {
590        if (!isset($this) || !is_a($this, 'App')) {
591            $this =& App::getInstance();
592        }
593
594        if (!$this->running) {
595            return false;
596        }
597   
598        // Get any provided query arguments to include in the final URL.
599        // If FALSE is a provided here, DO NOT carry the queries.
600        $do_carry_queries = true;
601        $one_time_carry_queries = array();
602        if (!is_null($carry_args)) {
603            if (is_array($carry_args) && !empty($carry_args)) {
604                foreach ($carry_args as $key=>$arg) {
605                    // Get query from appropriate source.
606                    if (false === $arg) {
607                        $do_carry_queries = false;
608                    } else if (false !== getFormData($arg, false)) {
609                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
610                    } else if (!is_numeric($key) && '' != $arg) {
611                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
612                    }
613                }
614            } else if (false !== getFormData($carry_args, false)) {
615                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
616            } else if (false === $carry_args) {
617                $do_carry_queries = false;
618            }
619        }
620       
621        // Get the first delimiter that is needed in the url.
622        $delim = strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
623
624       
625        $q = '';
626        if ($do_carry_queries) {
627            // Join the global _carry_queries and local one_time_carry_queries.
628            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
629            foreach ($query_args as $key=>$val) {
630                // Check value is set and value does not already exist in the url.
631                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
632                    $q .= $delim . $key . '=' . $val;
633                    $delim = ini_get('arg_separator.output');
634                }
635            }
636        }
637   
638        // Include the necessary SID if the following is true:
639        // - no cookie in http request OR cookies disabled in App
640        // - sessions are enabled
641        // - the link stays on our site
642        // - transparent SID propogation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
643        // OR
644        // - 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)
645        // AND
646        // - the SID is not already in the query.
647        if (
648            (
649                (
650                    (
651                        !isset($_COOKIE[session_name()]) 
652                        || !$this->getParam('session_use_cookies')
653                    ) 
654                    && $this->getParam('enable_session')
655                    && isMyDomain($url) 
656                    && 
657                    (
658                        !ini_get('session.use_trans_sid')
659                        || preg_match('!^(http|https)://!i', $url)
660                    )
661                ) 
662                || $always_include_sid
663            )
664            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
665        ) {
666            $url .= $q . $delim . session_name() . '=' . session_id();
667            return $url;
668        } else {
669            $url .= $q;
670            return $url;
671        }
672    }
673
674    /**
675     * Returns a HTML-friendly URL processed with App::url and & replaced with &amp;
676     *
677     * @access  public
678     * @param   string  $url    Input URL to parse.
679     * @return  string          URL with App::url() and htmlentities() applied.
680     * @author  Quinn Comendant <quinn@strangecode.com>
681     * @since   09 Dec 2005 17:58:45
682     */
683    function oHREF($url, $carry_args=null, $always_include_sid=false)
684    {
685        if (!isset($this) || !is_a($this, 'App')) {
686            $this =& App::getInstance();
687        }
688       
689        $url = $this->url($url, $carry_args, $always_include_sid);
690       
691        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
692        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
693       
694        return $url;
695    }
696   
697    /**
698     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
699     * as hidden form elements for GET_VARS that might be in use.
700     *
701     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
702     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
703     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
704     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
705     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
706     */
707    function printHiddenSession($carry_args=null)
708    {
709        if (!isset($this) || !is_a($this, 'App')) {
710            $this =& App::getInstance();
711        }
712
713        if (!$this->running) {
714            return false;
715        }
716   
717        // Get any provided query arguments to include in the final hidden form data.
718        // If FALSE is a provided here, DO NOT carry the queries.
719        $do_carry_queries = true;
720        $one_time_carry_queries = array();
721        if (!is_null($carry_args)) {
722            if (is_array($carry_args) && !empty($carry_args)) {
723                foreach ($carry_args as $key=>$arg) {
724                    // Get query from appropriate source.
725                    if (false === $arg) {
726                        $do_carry_queries = false;
727                    } else if (false !== getFormData($arg, false)) {
728                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
729                    } else if (!is_numeric($key) && '' != $arg) {
730                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
731                    }
732                }
733            } else if (false !== getFormData($carry_args, false)) {
734                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
735            } else if (false === $carry_args) {
736                $do_carry_queries = false;
737            }
738        }
739       
740        // For each existing POST value, we create a hidden input to carry it through a form.
741        if ($do_carry_queries) {
742            // Join the global _carry_queries and local one_time_carry_queries.
743            // urlencode is not used here, not for form data!
744            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
745            foreach ($query_args as $key=>$val) {
746                echo '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
747            }
748        }
749       
750        // Include the SID if cookies are disabled.
751        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
752            echo '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
753        }
754    }
755   
756    /**
757     * Uses an http header to redirect the client to the given $url. If sessions are not used
758     * and the session is not already defined in the given $url, the SID is appended as a URI query.
759     * As with all header generating functions, make sure this is called before any other output.
760     *
761     * @param   string  $url                    The URL the client will be redirected to.
762     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
763     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
764     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
765     *                                          -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
766     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
767     * @param   bool    $always_include_sid     Force session id to be added to Location header.
768     */
769    function dieURL($url, $carry_args=null, $always_include_sid=false)
770    {
771        if (!isset($this) || !is_a($this, 'App')) {
772            $this =& App::getInstance();
773        }
774
775        if (!$this->running) {
776            return false;
777        }
778       
779        if ('' == $url) {
780            // If URL is not specified, use the redirect_home_url.
781            $url = $this->getParam('redirect_home_url');
782        }
783   
784        if (preg_match('!^/!', $url)) {
785            // If relative URL is given, prepend correct local hostname.
786            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
787            $host = getenv('HTTP_HOST');
788            $url = sprintf('%s://%s%s', $scheme, $host, $url);
789        }
790
791        $url = $this->url($url, $carry_args, $always_include_sid);
792       
793        header(sprintf('Location: %s', $url));
794        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
795       
796        // End this application.
797        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
798        $this->stop();
799        die;
800    }
801   
802    /**
803     * Redirects a user by calling the App::dieURL(). It will use:
804     * 1. the stored boomerang URL, it it exists
805     * 2. the referring URL, it it exists.
806     * 3. an empty string, which will force App::dieURL to use the default URL.
807     */
808    function dieBoomerangURL($id=null, $carry_args=null)
809    {
810        if (!isset($this) || !is_a($this, 'App')) {
811            $this =& App::getInstance();
812        }
813
814        if (!$this->running) {
815            return false;
816        }
817       
818        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
819        if ($this->validBoomerangURL($id, true)) {
820            if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
821                $url = $_SESSION[$this->app]['boomerang']['url'][$id];
822                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
823            } else {
824                $url = end($_SESSION[$this->app]['boomerang']['url']);
825                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
826            }
827            // Delete stored boomerang.
828            $this->deleteBoomerangURL($id);
829        } else if (!refererIsMe()) {
830            // Ensure that the redirecting page is not also the referrer.
831            $url = getenv('HTTP_REFERER');
832            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
833        } else {
834            // If URL is not specified, use the redirect_home_url.
835            $url = $this->getParam('redirect_home_url');
836            $this->logMsg(sprintf('dieBoomerangURL(%s) not found, using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
837        }
838   
839           
840        // A redirection will never happen immediatly twice.
841        // Set the time so ensure this doesn't happen.
842        $_SESSION[$this->app]['boomerang']['time'] = time();
843        $this->dieURL($url, $carry_args);
844    }
845   
846    /**
847     * Set the URL to return to when App::dieBoomerangURL() is called.
848     *
849     * @param string  $url  A fully validated URL.
850     * @param bool  $id     An identification tag for this url.
851     * FIXME: url garbage collection?
852     */
853    function setBoomerangURL($url=null, $id=null)
854    {
855        if (!isset($this) || !is_a($this, 'App')) {
856            $this =& App::getInstance();
857        }
858
859        if (!$this->running) {
860            return false;
861        }
862        // A redirection will never happen immediatly after setting the boomerangURL.
863        // Set the time so ensure this doesn't happen. See App::validBoomerangURL for more.
864   
865        if ('' != $url && is_string($url)) {
866            // Delete any boomerang request keys in the query string.
867            $url = preg_replace('/boomerang=[\w]+/', '', $url);
868           
869            if (isset($_SESSION[$this->app]['boomerang']['url']) && is_array($_SESSION[$this->app]['boomerang']['url']) && !empty($_SESSION[$this->app]['boomerang']['url'])) {
870                // If the URL currently exists in the boomerang array, delete.
871                while ($existing_key = array_search($url, $_SESSION[$this->app]['boomerang']['url'])) {
872                    unset($_SESSION[$this->app]['boomerang']['url'][$existing_key]);
873                }
874            }
875           
876            if (isset($id)) {
877                $_SESSION[$this->app]['boomerang']['url'][$id] = $url;
878            } else {
879                $_SESSION[$this->app]['boomerang']['url'][] = $url;
880            }
881            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
882            return true;
883        } else {
884            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
885            return false;
886        }
887    }
888   
889    /**
890     * Return the URL set for the specified $id.
891     *
892     * @param string  $id     An identification tag for this url.
893     */
894    function getBoomerangURL($id=null)
895    {
896        if (!isset($this) || !is_a($this, 'App')) {
897            $this =& App::getInstance();
898        }
899
900        if (!$this->running) {
901            return false;
902        }
903       
904        if (isset($id)) {
905            if (isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
906                return $_SESSION[$this->app]['boomerang']['url'][$id];
907            } else {
908                return '';
909            }
910        } else if (is_array($_SESSION[$this->app]['boomerang']['url'])) {
911            return end($_SESSION[$this->app]['boomerang']['url']);
912        } else {
913            return false;
914        }
915    }
916   
917    /**
918     * Delete the URL set for the specified $id.
919     *
920     * @param string  $id     An identification tag for this url.
921     */
922    function deleteBoomerangURL($id=null)
923    {
924        if (!isset($this) || !is_a($this, 'App')) {
925            $this =& App::getInstance();
926        }
927
928        if (!$this->running) {
929            return false;
930        }
931       
932        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
933
934        if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
935            unset($_SESSION[$this->app]['boomerang']['url'][$id]);
936        } else if (is_array($_SESSION[$this->app]['boomerang']['url'])) {
937            array_pop($_SESSION[$this->app]['boomerang']['url']);
938        }
939    }
940   
941    /**
942     * Check if a valid boomerang URL value has been set.
943     * if it is not the current url, and has not been accessed within n seconds.
944     *
945     * @return bool  True if it is set and not the current URL.
946     */
947    function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
948    {
949        if (!isset($this) || !is_a($this, 'App')) {
950            $this =& App::getInstance();
951        }
952
953        if (!$this->running) {
954            return false;
955        }
956       
957        if (!isset($_SESSION[$this->app]['boomerang']['url'])) {
958            return false;
959        }
960   
961        // Time is the timestamp of a boomerangURL redirection, or setting of a boomerangURL.
962        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
963        // or a boomerang being set.
964        $boomerang_time = isset($_SESSION[$this->app]['boomerang']['time']) ? $_SESSION[$this->app]['boomerang']['time'] : 0;
965       
966        $url = '';
967        if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
968            $url = $_SESSION[$this->app]['boomerang']['url'][$id];
969        } else if (!isset($id) || $use_nonspecificboomerang) {
970            // Use non specific boomerang if available.
971            $url = end($_SESSION[$this->app]['boomerang']['url']);
972        }
973   
974        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
975
976        if ('' == $url) {
977            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_NOTICE, __FILE__, __LINE__);
978            return false;
979        }
980        if ($url == absoluteMe()) {
981            // The URL we are directing to is the current page.
982            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
983            return false;
984        }
985        if ($boomerang_time >= (time() - 2)) {
986            // Last boomerang direction was more than 2 seconds ago.
987            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s', $id, time() - $boomerang_time), LOG_NOTICE, __FILE__, __LINE__);
988            return false;
989        }
990       
991        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
992        return true;
993    }
994
995    /**
996     * Force the user to connect via https (port 443) by redirecting them to
997     * the same page but with https.
998     */
999    function sslOn()
1000    {
1001        if (!isset($this) || !is_a($this, 'App')) {
1002            $this =& App::getInstance();
1003        }
1004       
1005        if ('on' != getenv('HTTPS') && $this->getParam('ssl_enabled') && preg_match('/mod_ssl/i', getenv('SERVER_SOFTWARE'))) {
1006            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1007            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1008            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1009        }
1010    }
1011       
1012   
1013    /**
1014     * to enforce the user to connect via http (port 80) by redirecting them to
1015     * a http version of the current url.
1016     */
1017    function sslOff()
1018    {
1019        if ('on' == getenv('HTTPS')) {
1020            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1021        }
1022    }
1023
1024   
1025} // End.
1026
1027?>
Note: See TracBrowser for help on using the repository browser.