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

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

little bits

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