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

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

Rebuilt the services/admins.php script and templates. Fixes since v2 conversion. Lots of bugs and more to come!

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