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

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

Initial import.

File size: 39.2 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' => false,
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 (!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 (!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['SCRIPT_URI']) && '' != $_SERVER['SCRIPT_URI']) {
305            $site_url = parse_url($_SERVER['SCRIPT_URI']);
306            $this->setParam(array('site_url' => sprintf('%s://%s', $site_url['scheme'], $site_url['host'])));
307        }
308
309        // A key for calculating simple cryptographic signatures.
310        if (isset($_SERVER['SIGNING_KEY'])) {
311            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
312        }
313       
314        // Used as the fifth parameter to mail() to set the return address for sent messages. Requires safe_mode off.
315        if ('' != $this->getParam('site_email') && !$this->getParam('envelope_sender_address')) {
316            $this->setParam(array('envelope_sender_address' => '-f ' . $this->getParam('site_email')));
317        }
318
319        // Character set. This should also be printed in the html header template.
320        header('Content-type: text/html; charset=' . $this->getParam('character_set'));
321       
322        $this->running = true;
323    }
324   
325    /**
326     * Stop running this application.
327     *
328     * @access  public
329     * @author  Quinn Comendant <quinn@strangecode.com>
330     * @since   17 Jul 2005 17:20:18
331     */
332    function stop()
333    {
334        session_write_close();
335        $this->db->close();
336        restore_include_path();
337        $this->running = false;
338    }
339   
340   
341    /**
342     * Add a message to the string globalmessage, which is printed in the header.
343     * Just a simple way to print messages to the user.
344     *
345     * @access public
346     *
347     * @param string $message The text description of the message.
348     * @param int    $type    The type of message: MSG_NOTICE,
349     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
350     * @param string $file    __FILE__.
351     * @param string $line    __LINE__.
352     */
353    function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
354    {
355        if (!is_a($this, 'App')) {
356            $this =& App::getInstance();
357        }
358
359        if (!$this->running) {
360            return false;
361        }
362       
363        $_SESSION[$this->app]['messages'][] = array(
364            'type'    => $type, 
365            'message' => $message,
366            'file'    => $file,
367            'line'    => $line
368        );
369       
370        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
371            App::logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_DEBUG, __FILE__, __LINE__);
372        }
373    }
374   
375    /**
376     * Prints the HTML for displaying raised messages.
377     *
378     * @access  public
379     * @author  Quinn Comendant <quinn@strangecode.com>
380     * @since   15 Jul 2005 01:39:14
381     */
382    function printRaisedMessages()
383    {
384        if (!is_a($this, 'App')) {
385            $this =& App::getInstance();
386        }
387
388        if (!$this->running) {
389            return false;
390        }
391
392        while (isset($_SESSION[$this->app]['messages']) && $message = array_shift($_SESSION[$this->app]['messages'])) {
393            ?><div class="codebasemsg"><?php
394            if (error_reporting() > 0 && $this->getParam('display_errors')) {
395                echo "\n<!-- [" . $message['file'] . ' : ' . $message['line'] . '] -->';
396            }
397            switch ($message['type']) {
398            case MSG_ERR:
399                echo '<div class="error">' . $message['message'] . '</div>';
400                break;
401   
402            case MSG_WARNING:
403                echo '<div class="warning">' . $message['message'] . '</div>';
404                break;
405   
406            case MSG_SUCCESS:
407                echo '<div class="success">' . $message['message'] . '</div>';
408                break;
409   
410            case MSG_NOTICE:
411            default:
412                echo '<div class="notice">' . $message['message'] . '</div>';
413                break;
414   
415            }
416            ?></div><?php
417        }
418    }
419   
420    /**
421     * Logs a message to a user defined log file. Additional actions to take for
422     * different types of message types can be specified (ERROR, NOTICE, etc).
423     *
424     * @access public
425     *
426     * @param string $message   The text description of the message.
427     * @param int    $priority  The type of message priority (in descending order):
428     *                          LOG_EMERG     system is unusable
429     *                          LOG_ALERT     action must be taken immediately
430     *                          LOG_CRIT      critical conditions
431     *                          LOG_ERR       error conditions
432     *                          LOG_WARNING   warning conditions
433     *                          LOG_NOTICE    normal, but significant, condition
434     *                          LOG_INFO      informational message
435     *                          LOG_DEBUG     debug-level message
436     * @param string $file      The file where the log event occurs.
437     * @param string $line      The line of the file where the log event occurs.
438     */
439    function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
440    {
441        if (!is_a($this, 'App')) {
442            $this =& App::getInstance();
443        }
444
445        if (!$this->running) {
446            return false;
447        }
448       
449        // If priority is not specified, assume the worst.
450        if (!$this->logPriorityToString($priority)) {
451            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
452            $priority = LOG_EMERG;
453        }
454   
455        // If log file is not specified, create one in the codebase root.
456        if ($this->getParam('log_directory') === null || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
457            // If log file is not specified, don't log to a file.
458            $this->setParam(array('log_file_priority' => false));
459            // We must use trigger_error rather than calling App::logMsg, which might lead to an infinite loop.
460            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
461        }
462       
463        // Make sure to log in the system's locale.
464        $locale = setlocale(LC_TIME, 0);
465        setlocale(LC_TIME, 'C');
466       
467        // Data to be stored for a log event.
468        $event = array();
469        $event['date'] = date('Y-m-d H:i:s');
470        $event['remote ip'] = getRemoteAddr();
471        if (substr(PHP_OS, 0, 3) != 'WIN') {
472            $event['pid'] = posix_getpid();
473        }
474        $event['type'] = $this->logPriorityToString($priority);
475        $event['file:line'] = "$file : $line";
476        $event['message'] = strip_tags(preg_replace('/\s{2,}/', ' ', $message));
477   
478        $event_str = '[' . join('] [', $event) . ']';
479       
480        // FILE ACTION
481        if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
482            error_log($event_str . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
483        }
484   
485        // EMAIL ACTION
486        if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) {
487            $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message);
488            $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST'));
489            $headers = "From: codebase@strangecode.com\r\n";
490            foreach ($event as $k=>$v) {
491                $email_msg .= sprintf("%-11s%s\n", $k, $v);
492            }
493            mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
494        }
495       
496        // SMS ACTION
497        if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) {
498            $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority);
499            $sms_msg = sprintf('%s:%s %s', basename($file), $line, $event['message']);
500            $headers = "From: codebase@strangecode.com\r\n";
501            mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
502        }
503   
504        // SCREEN ACTION
505        if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
506            echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
507        }
508   
509        // Restore original locale.
510        setlocale(LC_TIME, $locale);
511    }
512   
513    /**
514     * Returns the string representation of a LOG_* integer constant.
515     *
516     * @param int  $priority  The LOG_* integer constant.
517     *
518     * @return                The string representation of $priority.
519     */
520    function logPriorityToString ($priority) {
521        $priorities = array(
522            LOG_EMERG   => 'emergency',
523            LOG_ALERT   => 'alert',
524            LOG_CRIT    => 'critical',
525            LOG_ERR     => 'error',
526            LOG_WARNING => 'warning',
527            LOG_NOTICE  => 'notice',
528            LOG_INFO    => 'info',
529            LOG_DEBUG   => 'debug'
530        );
531        if (isset($priorities[$priority])) {
532            return $priorities[$priority];
533        } else {
534            return false;
535        }
536    }
537   
538    /**
539     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
540     * keys and values, including optional queries. This allows simple printing of
541     * links without needing to know which queries to add to it. If cookies are not
542     * used, the session id will be propogated in the URL.
543     *
544     * @global string $carry_queries       An array of keys to define which values to
545     *                                     carry through from the POST or GET.
546     *                                     $carry_queries = array('qry'); for example.
547     *
548     * @param  string $url                 The initial url
549     * @param  mixed  $carry_args          Additional url arguments to carry in the query,
550     *                                     or FALSE to prevent carrying queries. Can be any of the following formats:
551     *                                     -array('key1', key2', key3')  <-- to save these keys if in the form data.
552     *                                     -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
553     *                                     -false  <-- To not carry any queries. If URL already has queries those will be retained.
554     *
555     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
556     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
557     *                                     header('Location...') redirections.
558     *
559     * @return string url with attached queries and, if not using cookies, the session id
560     */
561    function oHREF($url='', $carry_args=null, $always_include_sid=false)
562    {
563        if (!is_a($this, 'App')) {
564            $this =& App::getInstance();
565        }
566
567        if (!$this->running) {
568            return false;
569        }
570       
571        static $_using_trans_sid;
572        global $carry_queries;
573   
574        // Save the trans_sid setting.
575        if (!isset($_using_trans_sid)) {
576            $_using_trans_sid = ini_get('session.use_trans_sid');
577        }
578   
579        // Initialize the carried queries.
580        if (!isset($carry_queries['_carry_queries_init'])) {
581            if (!is_array($carry_queries)) {
582                $carry_queries = array($carry_queries);
583            }
584            $tmp = $carry_queries;
585            $carry_queries = array();
586            foreach ($tmp as $key) {
587                if (!empty($key) && getFormData($key, false)) {
588                    $carry_queries[$key] = getFormData($key);
589                }
590            }
591            $carry_queries['_carry_queries_init'] = true;
592        }
593   
594        // Get any additional query arguments to add to the $carry_queries array.
595        // If FALSE is a function argument, DO NOT carry the queries.
596        $do_carry_queries = true;
597        $one_time_carry_queries = array();
598        if (!is_null($carry_args)) {
599            if (is_array($carry_args) && !empty($carry_args)) {
600                foreach ($carry_args as $key=>$arg) {
601                    // Get query from appropriate source.
602                    if (false === $arg) {
603                        $do_carry_queries = false;
604                    } else if (false !== getFormData($arg, false)) {
605                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
606                    } else if (!is_numeric($key) && '' != $arg) {
607                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
608                    }
609                }
610            } else if (false !== getFormData($carry_args, false)) {
611                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
612            } else if (false === $carry_args) {
613                $do_carry_queries = false;
614            }
615        }
616   
617        // Get the first delimiter that is needed in the url.
618        $delim = preg_match('/\?/', $url) ? ini_get('arg_separator.output') : '?';
619       
620        $q = '';
621        if ($do_carry_queries) {
622            // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args.
623            $query_args = array_diff_assoc(urlEncodeArray(array_merge($carry_queries, $one_time_carry_queries)), array('_carry_queries_init' => true));
624            foreach ($query_args as $key=>$val) {
625                // Check value is set and value does not already exist in the url.
626                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
627                    $q .= $delim . $key . '=' . $val;
628                    $delim = ini_get('arg_separator.output');
629                }
630            }
631        }
632   
633        // Include the necessary SID if the following is true:
634        // - no cookie in http request OR cookies disabled in App
635        // - sessions are enabled
636        // - the link stays on our site
637        // - transparent SID propogation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
638        // OR
639        // - 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)
640        // AND
641        // - the SID is not already in the query.
642        if (
643            (
644                (
645                    (
646                        !isset($_COOKIE[session_name()]) 
647                        || !$this->getParam('session_use_cookies')
648                    ) 
649                    && $this->getParam('enable_session')
650                    && isMyDomain($url) 
651                    && 
652                    (
653                        !$_using_trans_sid
654                        || preg_match('!^(http|https)://!i', $url)
655                    )
656                ) 
657                || $always_include_sid
658            )
659            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
660        ) {
661            $url .= $q . $delim . session_name() . '=' . session_id();
662            return $url;
663        } else {
664            $url .= $q;
665            return $url;
666        }
667    }
668   
669    /**
670     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
671     * as hidden form elements for GET_VARS that might be in use.
672     *
673     * @global string $carry_queries     An array of keys to define which values to
674     *                                   carry through from the POST or GET.
675     *                                   $carry_queries = array('qry'); for example
676     *
677     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
678     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
679     *                                   -array('key1', key2', key3')  <-- to save these keys if in the form data.
680     *                                   -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
681     *                                   -false  <-- To not carry any queries. If URL already has queries those will be retained.
682     */
683    function printHiddenSession($carry_args=null)
684    {
685        if (!is_a($this, 'App')) {
686            $this =& App::getInstance();
687        }
688
689        if (!$this->running) {
690            return false;
691        }
692       
693        static $_using_trans_sid;
694        global $carry_queries;
695   
696        // Save the trans_sid setting.
697        if (!isset($_using_trans_sid)) {
698            $_using_trans_sid = ini_get('session.use_trans_sid');
699        }
700       
701        // Initialize the carried queries.
702        if (!isset($carry_queries['_carry_queries_init'])) {
703            if (!is_array($carry_queries)) {
704                $carry_queries = array($carry_queries);
705            }
706            $tmp = $carry_queries;
707            $carry_queries = array();
708            foreach ($tmp as $key) {
709                if (!empty($key) && getFormData($key, false)) {
710                    $carry_queries[$key] = getFormData($key);
711                }
712            }
713            $carry_queries['_carry_queries_init'] = true;
714        }
715   
716        // Get any additional query names to add to the $carry_queries array
717        // that are found as function arguments.
718        // If FALSE is a function argument, 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 perm and temp carry_queries and filter out the _carry_queries_init element for the final query args.
743            $query_args = array_diff_assoc(urlEncodeArray(array_merge($carry_queries, $one_time_carry_queries)), array('_carry_queries_init' => true));
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()]) && !$_using_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 (!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            $my_url = parse_url($_SERVER['SCRIPT_URI']);
786            $url = sprintf('%s://%s%s', $my_url['scheme'], $my_url['host'], $url);
787        }
788   
789        $url = $this->oHREF($url, $carry_args, $always_include_sid);
790       
791        header(sprintf('Location: %s', $url));
792        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
793       
794        // End this application.
795        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
796        $this->stop();
797        die;
798    }
799   
800    /**
801     * Redirects a user by calling the App::dieURL(). It will use:
802     * 1. the stored boomerang URL, it it exists
803     * 2. the referring URL, it it exists.
804     * 3. an empty string, which will force App::dieURL to use the default URL.
805     */
806    function dieBoomerangURL($id=null, $carry_args=null)
807    {
808        if (!is_a($this, 'App')) {
809            $this =& App::getInstance();
810        }
811
812        if (!$this->running) {
813            return false;
814        }
815       
816        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
817        if ($this->validBoomerangURL($id, true)) {
818            if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
819                $url = $_SESSION[$this->app]['boomerang']['url'][$id];
820            } else {
821                $url = end($_SESSION[$this->app]['boomerang']['url']);
822            }
823        } else if (!refererIsMe() && !preg_match('/admin_common/', getenv('SCRIPT_NAME'))) {
824            // Ensure that the redirecting page is not also the referrer.
825            // admin_common is an alias of 'admin', which confuses this function. Just here for local testing.
826            $url = getenv('HTTP_REFERER');
827        } else {
828            $url = '';
829        }
830   
831        $this->logMsg(sprintf('dieBoomerangURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
832   
833        // Delete stored boomerang.
834        $this->deleteBoomerangURL($id);
835           
836        // A redirection will never happen immediatly twice.
837        // Set the time so ensure this doesn't happen.
838        $_SESSION[$this->app]['boomerang']['time'] = time();
839        $this->dieURL($url, $carry_args);
840    }
841   
842    /**
843     * Set the URL to return to when App::dieBoomerangURL() is called.
844     *
845     * @param string  $url  A fully validated URL.
846     * @param bool  $id     An identification tag for this url.
847     * FIXME: url garbage collection?
848     */
849    function setBoomerangURL($url=null, $id=null)
850    {
851        if (!is_a($this, 'App')) {
852            $this =& App::getInstance();
853        }
854
855        if (!$this->running) {
856            return false;
857        }
858       
859        // A redirection will never happen immediatly after setting the boomerangURL.
860        // Set the time so ensure this doesn't happen. See App::validBoomerangURL for more.
861   
862        if (isset($url) && is_string($url)) {
863            // Delete any boomerang request keys in the query string.
864            $url = preg_replace('/boomerang=[\w]+/', '', $url);
865           
866            if (is_array($_SESSION[$this->app]['boomerang']['url']) && !empty($_SESSION[$this->app]['boomerang']['url'])) {
867                // If the URL currently exists in the boomerang array, delete.
868                while ($existing_key = array_search($url, $_SESSION[$this->app]['boomerang']['url'])) {
869                    unset($_SESSION[$this->app]['boomerang']['url'][$existing_key]);
870                }
871            }
872           
873            if (isset($id)) {
874                $_SESSION[$this->app]['boomerang']['url'][$id] = $url;
875            } else {
876                $_SESSION[$this->app]['boomerang']['url'][] = $url;
877            }
878            $this->logMsg(sprintf('setBoomerangURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
879            return true;
880        } else {
881            return false;
882        }
883    }
884   
885    /**
886     * Return the URL set for the specified $id.
887     *
888     * @param string  $id     An identification tag for this url.
889     */
890    function getBoomerangURL($id=null)
891    {
892        if (!is_a($this, 'App')) {
893            $this =& App::getInstance();
894        }
895
896        if (!$this->running) {
897            return false;
898        }
899       
900        if (isset($id)) {
901            if (isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
902                return $_SESSION[$this->app]['boomerang']['url'][$id];
903            } else {
904                return '';
905            }
906        } else if (is_array($_SESSION[$this->app]['boomerang']['url'])) {
907            return end($_SESSION[$this->app]['boomerang']['url']);
908        } else {
909            return false;
910        }
911    }
912   
913    /**
914     * Delete the URL set for the specified $id.
915     *
916     * @param string  $id     An identification tag for this url.
917     */
918    function deleteBoomerangURL($id=null)
919    {
920        if (!is_a($this, 'App')) {
921            $this =& App::getInstance();
922        }
923
924        if (!$this->running) {
925            return false;
926        }
927       
928        if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
929            unset($_SESSION[$this->app]['boomerang']['url'][$id]);
930        } else if (is_array($_SESSION[$this->app]['boomerang']['url'])) {
931            array_pop($_SESSION[$this->app]['boomerang']['url']);
932        }
933    }
934   
935    /**
936     * Check if a valid boomerang URL value has been set.
937     * if it is not the current url, and has not been accessed within n seconds.
938     *
939     * @return bool  True if it is set and not the current URL.
940     */
941    function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
942    {
943        if (!is_a($this, 'App')) {
944            $this =& App::getInstance();
945        }
946
947        if (!$this->running) {
948            return false;
949        }
950       
951        if (!isset($_SESSION[$this->app]['boomerang']['url'])) {
952            return false;
953        }
954   
955        // Time is the timestamp of a boomerangURL redirection, or setting of a boomerangURL.
956        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
957        // or a boomerang being set.
958        $boomerang_time = isset($_SESSION[$this->app]['boomerang']['time']) ? $_SESSION[$this->app]['boomerang']['time'] : 0;
959       
960        if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
961            $url = $_SESSION[$this->app]['boomerang']['url'][$id];
962        } else if (!isset($id) || $use_nonspecificboomerang) {
963            // Use non specific boomerang if available.
964            $url = end($_SESSION[$this->app]['boomerang']['url']);
965        }
966   
967        $this->logMsg(sprintf('validBoomerangURL testing url: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
968        if (empty($url)) {
969            return false;
970        }
971        if ($url == absoluteMe()) {
972            // The URL we are directing to is the current page.
973            $this->logMsg(sprintf('Boomerang URL not valid, same as absoluteMe: %s', $url), LOG_WARNING, __FILE__, __LINE__);
974            return false;
975        }
976        if ($boomerang_time >= (time() - 2)) {
977            // Last boomerang direction was more than 2 seconds ago.
978            $this->logMsg(sprintf('Boomerang URL not valid, boomerang_time too short: %s', time() - $boomerang_time), LOG_WARNING, __FILE__, __LINE__);
979            return false;
980        }
981       
982        $this->logMsg(sprintf('validBoomerangURL found: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
983        return true;
984    }
985
986    /**
987     * Force the user to connect via https (port 443) by redirecting them to
988     * the same page but with https.
989     */
990    function sslOn()
991    {
992        if (!is_a($this, 'App')) {
993            $this =& App::getInstance();
994        }
995       
996        if ('on' != getenv('HTTPS') && $this->getParam('ssl_enabled') && preg_match('/mod_ssl/i', getenv('SERVER_SOFTWARE'))) {
997            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
998            // Always append session because some browsers do not send cookie when crossing to SSL URL.
999            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1000        }
1001    }
1002       
1003   
1004    /**
1005     * to enforce the user to connect via http (port 80) by redirecting them to
1006     * a http version of the current url.
1007     */
1008    function sslOff()
1009    {
1010        if ('on' == getenv('HTTPS')) {
1011            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1012        }
1013    }
1014
1015   
1016} // End.
1017
1018?>
Note: See TracBrowser for help on using the repository browser.