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

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

detabbed all files ;P

File size: 39.6 KB
Line 
1<?php
2/**
3 * App.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Primary application framework class.
7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
9 * @version 1.0
10 */
11
12// Message Types.
13define('MSG_ERR', 1);
14define('MSG_ERROR', MSG_ERR);
15define('MSG_WARNING', 2);
16define('MSG_NOTICE', 4);
17define('MSG_SUCCESS', 8);
18
19require_once dirname(__FILE__) . '/Utilities.inc.php';
20
21class App {
22
23    // Name of this application.
24    var $app = '_app_';
25
26    // If App::start has run successfully.
27    var $running = false;
28
29    // Instance of database object.
30    var $db;
31
32    // Array of query arguments will be carried persistently between requests.
33    var $_carry_queries = array();
34
35    // Hash of global application parameters.
36    var $_params = array();
37
38    // Default parameters.
39    var $_param_defaults = array(
40
41        // Public name and email address for this application.
42        'site_name' => null,
43        'site_email' => null,
44        'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here.
45
46        // The location the user will go if the system doesn't knew where else to send them.
47        'redirect_home_url' => '/',
48
49        // SSL URL used when redirecting with App::sslOn().
50        'ssl_domain' => null,
51        'ssl_enabled' => false,
52
53        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
54        'character_set' => 'utf-8',
55
56        // Human-readable format used to display dates.
57        'date_format' => 'd M Y',
58        'sql_date_format' => '%e %b %Y',
59        'sql_time_format' => '%k:%i',
60
61        // Use php sessions?
62        'enable_session' => false,
63        'session_name' => 'Strangecode',
64        'session_use_cookies' => true,
65
66        // Use database?
67        'enable_db' => false,
68
69        // Use db-based sessions?
70        'enable_db_session_handler' => false,
71
72        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
73        'db_server' => 'localhost',
74        'db_name' => null,
75        'db_user' => null,
76        'db_pass' => null,
77
78        // Database debugging.
79        'db_always_debug' => false, // TRUE = display all SQL queries.
80        'db_debug' => false, // TRUE = display db errors.
81        'db_die_on_failure' => false, // TRUE = script stops on db error.
82
83        // For classes that require db tables, do we check that a table exists and create if missing?
84        'db_create_tables' => true,
85
86        // The level of error reporting. Don't set this to 0 to suppress messages, instead use display_errors to control display.
87        'error_reporting' => E_ALL,
88
89        // Don't display errors by default; it is preferable to log them to a file.
90        'display_errors' => false,
91
92        // Directory in which to store log files.
93        'log_directory' => '',
94
95        // PHP error log.
96        'php_error_log' => 'php_error_log',
97
98        // General application log.
99        'log_filename' => 'app_error_log',
100
101        // Logging priority can be any of the following, or false to deactivate:
102        // LOG_EMERG     system is unusable
103        // LOG_ALERT     action must be taken immediately
104        // LOG_CRIT      critical conditions
105        // LOG_ERR       error conditions
106        // LOG_WARNING   warning conditions
107        // LOG_NOTICE    normal, but significant, condition
108        // LOG_INFO      informational message
109        // LOG_DEBUG     debug-level message
110        'log_file_priority' => false,
111        'log_email_priority' => false,
112        'log_sms_priority' => false,
113        'log_screen_priority' => false,
114
115        // Email address to receive log event emails.
116        'log_to_email_address' => null,
117
118        // SMS Email address to receive log event SMS messages.
119        'log_to_sms_address' => null,
120
121        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
122        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
123    );
124
125    /**
126     * This method enforces the singleton pattern for this class. Only one application is running at a time.
127     *
128     * @return  object  Reference to the global SessionCache object.
129     * @access  public
130     * @static
131     */
132    function &getInstance($app=null)
133    {
134        static $instance = null;
135
136        if ($instance === null) {
137            $instance = new App($app);
138        }
139
140        return $instance;
141    }
142
143    /**
144     * Constructor.
145     */
146    function App($app=null)
147    {
148        if (isset($app)) {
149            $this->app .= $app;
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            trigger_error(sprintf('Parameter is not set: %s', $param), E_USER_NOTICE);
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.
293            session_start();
294
295            if (!isset($_SESSION[$this->app])) {
296                // Access session data using: $_SESSION['...'].
297                // Initialize here _after_ session has started.
298                $_SESSION[$this->app] = array(
299                    'messages' => array(),
300                    'boomerang' => array('url'),
301                );
302            }
303        }
304
305
306        /**
307         * 3. Misc setup.
308         */
309
310        // Script URI will be something like http://host.name.tld (no ending slash)
311        // and is used whenever a URL need be used to the current site.
312        // Not available on cli scripts obviously.
313        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) {
314            $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'))));
315        }
316
317        // A key for calculating simple cryptographic signatures.
318        if (isset($_SERVER['SIGNING_KEY'])) {
319            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
320        }
321
322        // Character set. This should also be printed in the html header template.
323        header('Content-type: text/html; charset=' . $this->getParam('character_set'));
324
325        $this->running = true;
326    }
327
328    /**
329     * Stop running this application.
330     *
331     * @access  public
332     * @author  Quinn Comendant <quinn@strangecode.com>
333     * @since   17 Jul 2005 17:20:18
334     */
335    function stop()
336    {
337        session_write_close();
338        $this->db->close();
339        restore_include_path();
340        $this->running = false;
341    }
342
343
344    /**
345     * Add a message to the string globalmessage, which is printed in the header.
346     * Just a simple way to print messages to the user.
347     *
348     * @access public
349     *
350     * @param string $message The text description of the message.
351     * @param int    $type    The type of message: MSG_NOTICE,
352     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
353     * @param string $file    __FILE__.
354     * @param string $line    __LINE__.
355     */
356    function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
357    {
358        if (!isset($this) || !is_a($this, 'App')) {
359            $this =& App::getInstance();
360        }
361
362        $message = trim($message);
363
364        if (!$this->running || '' == $message) {
365            return false;
366        }
367
368        // Save message in session under unique key to avoid duplicate messages.
369        $_SESSION[$this->app]['messages'][md5($type . $message . $file . $line)] = array(
370            'type'    => $type,
371            'message' => $message,
372            'file'    => $file,
373            'line'    => $line
374        );
375
376        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
377            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_DEBUG, __FILE__, __LINE__);
378        }
379    }
380
381    /**
382     * Prints the HTML for displaying raised messages.
383     *
384     * @access  public
385     * @author  Quinn Comendant <quinn@strangecode.com>
386     * @since   15 Jul 2005 01:39:14
387     */
388    function printRaisedMessages()
389    {
390        if (!isset($this) || !is_a($this, 'App')) {
391            $this =& App::getInstance();
392        }
393
394        if (!$this->running) {
395            return false;
396        }
397
398        while (isset($_SESSION[$this->app]['messages']) && $message = array_shift($_SESSION[$this->app]['messages'])) {
399            ?><div class="codebasemsg"><?php
400            if (error_reporting() > 0 && $this->getParam('display_errors')) {
401                echo "\n<!-- [" . $message['file'] . ' : ' . $message['line'] . '] -->';
402            }
403            switch ($message['type']) {
404            case MSG_ERR:
405                echo '<div class="error">' . $message['message'] . '</div>';
406                break;
407
408            case MSG_WARNING:
409                echo '<div class="warning">' . $message['message'] . '</div>';
410                break;
411
412            case MSG_SUCCESS:
413                echo '<div class="success">' . $message['message'] . '</div>';
414                break;
415
416            case MSG_NOTICE:
417            default:
418                echo '<div class="notice">' . $message['message'] . '</div>';
419                break;
420
421            }
422            ?></div><?php
423        }
424    }
425
426    /**
427     * Logs a message to a user defined log file. Additional actions to take for
428     * different types of message types can be specified (ERROR, NOTICE, etc).
429     *
430     * @access public
431     *
432     * @param string $message   The text description of the message.
433     * @param int    $priority  The type of message priority (in descending order):
434     *                          LOG_EMERG     system is unusable
435     *                          LOG_ALERT     action must be taken immediately
436     *                          LOG_CRIT      critical conditions
437     *                          LOG_ERR       error conditions
438     *                          LOG_WARNING   warning conditions
439     *                          LOG_NOTICE    normal, but significant, condition
440     *                          LOG_INFO      informational message
441     *                          LOG_DEBUG     debug-level message
442     * @param string $file      The file where the log event occurs.
443     * @param string $line      The line of the file where the log event occurs.
444     */
445    function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
446    {
447        if (!isset($this) || !is_a($this, 'App')) {
448            $this =& App::getInstance();
449        }
450
451        // If priority is not specified, assume the worst.
452        if (!$this->logPriorityToString($priority)) {
453            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
454            $priority = LOG_EMERG;
455        }
456
457        // If log file is not specified, don't log to a file.
458        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
459            $this->setParam(array('log_file_priority' => false));
460            // We must use trigger_error to report this problem rather than calling App::logMsg, which might lead to an infinite loop.
461            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
462        }
463
464        // Make sure to log in the system's locale.
465        $locale = setlocale(LC_TIME, 0);
466        setlocale(LC_TIME, 'C');
467
468        // Data to be stored for a log event.
469        $event = array();
470        $event['date'] = date('Y-m-d H:i:s');
471        $event['remote ip'] = getRemoteAddr();
472        if (substr(PHP_OS, 0, 3) != 'WIN') {
473            $event['pid'] = posix_getpid();
474        }
475        $event['type'] = $this->logPriorityToString($priority);
476        $event['file:line'] = "$file : $line";
477        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow); // <...> with lots of chars maybe we don't want stripped.
478        $event['message'] = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
479        $event_str = '[' . join('] [', $event) . ']';
480
481        // FILE ACTION
482        if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
483            error_log($event_str . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
484        }
485
486        // EMAIL ACTION
487        if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) {
488            $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message);
489            $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST'));
490            $headers = "From: codebase@strangecode.com";
491            foreach ($event as $k=>$v) {
492                $email_msg .= sprintf("%-11s%s\n", $k, $v);
493            }
494            mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
495        }
496
497        // SMS ACTION
498        if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) {
499            $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority);
500            $sms_msg = sprintf('%s [%s:%s]', $event['message'], basename($file), $line);
501            $headers = "From: codebase@strangecode.com";
502            mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
503        }
504
505        // SCREEN ACTION
506        if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
507            echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
508        }
509
510        // Restore original locale.
511        setlocale(LC_TIME, $locale);
512    }
513
514    /**
515     * Returns the string representation of a LOG_* integer constant.
516     *
517     * @param int  $priority  The LOG_* integer constant.
518     *
519     * @return                The string representation of $priority.
520     */
521    function logPriorityToString ($priority) {
522        $priorities = array(
523            LOG_EMERG   => 'emergency',
524            LOG_ALERT   => 'alert',
525            LOG_CRIT    => 'critical',
526            LOG_ERR     => 'error',
527            LOG_WARNING => 'warning',
528            LOG_NOTICE  => 'notice',
529            LOG_INFO    => 'info',
530            LOG_DEBUG   => 'debug'
531        );
532        if (isset($priorities[$priority])) {
533            return $priorities[$priority];
534        } else {
535            return false;
536        }
537    }
538
539    /**
540     * Sets which query arguments will be carried persistently between requests.
541     * Values in the _carry_queries array will be copied to URLs (via App::url()) and
542     * to hidden input values (via printHiddenSession()).
543     *
544     * @access  public
545     * @param   string  $query_key  The key of the query argument to save.
546     * @author  Quinn Comendant <quinn@strangecode.com>
547     * @since   14 Nov 2005 19:24:52
548     */
549    function carryQuery($query_key)
550    {
551        if (!isset($this) || !is_a($this, 'App')) {
552            $this =& App::getInstance();
553        }
554
555        // If not already set, and there is a non-empty value provided in the request...
556        if (!isset($this->_carry_queries[$query_key]) && getFormData($query_key, false)) {
557            // Copy the value of the specified query argument into the _carry_queries array.
558            $this->_carry_queries[$query_key] = getFormData($query_key);
559        }
560    }
561
562    /**
563     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
564     * keys and values, including optional queries. This allows mindless retention
565     * of query arguments across page requests. If cookies are not
566     * used, the session id will be propogated in the URL.
567     *
568     * @param  string $url              The initial url
569     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
570     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
571     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
572     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
573     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
574     *
575     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
576     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
577     *                                     header('Location...') redirections.
578     *
579     * @return string url with attached queries and, if not using cookies, the session id
580     */
581    function url($url, $carry_args=null, $always_include_sid=false)
582    {
583        if (!isset($this) || !is_a($this, 'App')) {
584            $this =& App::getInstance();
585        }
586
587        if (!$this->running) {
588            return false;
589        }
590
591        // Get any provided query arguments to include in the final URL.
592        // If FALSE is a provided here, 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 = strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
616
617
618        $q = '';
619        if ($do_carry_queries) {
620            // Join the global _carry_queries and local one_time_carry_queries.
621            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
622            foreach ($query_args as $key=>$val) {
623                // Check value is set and value does not already exist in the url.
624                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
625                    $q .= $delim . $key . '=' . $val;
626                    $delim = ini_get('arg_separator.output');
627                }
628            }
629        }
630
631        // Include the necessary SID if the following is true:
632        // - no cookie in http request OR cookies disabled in App
633        // - sessions are enabled
634        // - the link stays on our site
635        // - transparent SID propogation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
636        // OR
637        // - 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)
638        // AND
639        // - the SID is not already in the query.
640        if (
641            (
642                (
643                    (
644                        !isset($_COOKIE[session_name()])
645                        || !$this->getParam('session_use_cookies')
646                    )
647                    && $this->getParam('enable_session')
648                    && isMyDomain($url)
649                    &&
650                    (
651                        !ini_get('session.use_trans_sid')
652                        || preg_match('!^(http|https)://!i', $url)
653                    )
654                )
655                || $always_include_sid
656            )
657            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
658        ) {
659            $url .= $q . $delim . session_name() . '=' . session_id();
660            return $url;
661        } else {
662            $url .= $q;
663            return $url;
664        }
665    }
666
667    /**
668     * Returns a HTML-friendly URL processed with App::url and & replaced with &amp;
669     *
670     * @access  public
671     * @param   string  $url    Input URL to parse.
672     * @return  string          URL with App::url() and htmlentities() applied.
673     * @author  Quinn Comendant <quinn@strangecode.com>
674     * @since   09 Dec 2005 17:58:45
675     */
676    function oHREF($url, $carry_args=null, $always_include_sid=false)
677    {
678        if (!isset($this) || !is_a($this, 'App')) {
679            $this =& App::getInstance();
680        }
681
682        $url = $this->url($url, $carry_args, $always_include_sid);
683
684        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
685        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
686
687        return $url;
688    }
689
690    /**
691     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
692     * as hidden form elements for GET_VARS that might be in use.
693     *
694     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
695     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
696     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
697     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
698     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
699     */
700    function printHiddenSession($carry_args=null)
701    {
702        if (!isset($this) || !is_a($this, 'App')) {
703            $this =& App::getInstance();
704        }
705
706        if (!$this->running) {
707            return false;
708        }
709
710        // Get any provided query arguments to include in the final hidden form data.
711        // If FALSE is a provided here, DO NOT carry the queries.
712        $do_carry_queries = true;
713        $one_time_carry_queries = array();
714        if (!is_null($carry_args)) {
715            if (is_array($carry_args) && !empty($carry_args)) {
716                foreach ($carry_args as $key=>$arg) {
717                    // Get query from appropriate source.
718                    if (false === $arg) {
719                        $do_carry_queries = false;
720                    } else if (false !== getFormData($arg, false)) {
721                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
722                    } else if (!is_numeric($key) && '' != $arg) {
723                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
724                    }
725                }
726            } else if (false !== getFormData($carry_args, false)) {
727                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
728            } else if (false === $carry_args) {
729                $do_carry_queries = false;
730            }
731        }
732
733        // For each existing POST value, we create a hidden input to carry it through a form.
734        if ($do_carry_queries) {
735            // Join the global _carry_queries and local one_time_carry_queries.
736            // urlencode is not used here, not for form data!
737            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
738            foreach ($query_args as $key=>$val) {
739                echo '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
740            }
741        }
742
743        // Include the SID if cookies are disabled.
744        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
745            echo '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
746        }
747    }
748
749    /**
750     * Uses an http header to redirect the client to the given $url. If sessions are not used
751     * and the session is not already defined in the given $url, the SID is appended as a URI query.
752     * As with all header generating functions, make sure this is called before any other output.
753     *
754     * @param   string  $url                    The URL the client will be redirected to.
755     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
756     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
757     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
758     *                                          -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
759     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
760     * @param   bool    $always_include_sid     Force session id to be added to Location header.
761     */
762    function dieURL($url, $carry_args=null, $always_include_sid=false)
763    {
764        if (!isset($this) || !is_a($this, 'App')) {
765            $this =& App::getInstance();
766        }
767
768        if (!$this->running) {
769            return false;
770        }
771
772        if ('' == $url) {
773            // If URL is not specified, use the redirect_home_url.
774            $url = $this->getParam('redirect_home_url');
775        }
776
777        if (preg_match('!^/!', $url)) {
778            // If relative URL is given, prepend correct local hostname.
779            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
780            $host = getenv('HTTP_HOST');
781            $url = sprintf('%s://%s%s', $scheme, $host, $url);
782        }
783
784        $url = $this->url($url, $carry_args, $always_include_sid);
785
786        header(sprintf('Location: %s', $url));
787        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
788
789        // End this application.
790        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
791        $this->stop();
792        die;
793    }
794
795    /**
796     * Redirects a user by calling the App::dieURL(). It will use:
797     * 1. the stored boomerang URL, it it exists
798     * 2. the referring URL, it it exists.
799     * 3. an empty string, which will force App::dieURL to use the default URL.
800     */
801    function dieBoomerangURL($id=null, $carry_args=null)
802    {
803        if (!isset($this) || !is_a($this, 'App')) {
804            $this =& App::getInstance();
805        }
806
807        if (!$this->running) {
808            return false;
809        }
810
811        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
812        if ($this->validBoomerangURL($id, true)) {
813            if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
814                $url = $_SESSION[$this->app]['boomerang']['url'][$id];
815                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
816            } else {
817                $url = end($_SESSION[$this->app]['boomerang']['url']);
818                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
819            }
820            // Delete stored boomerang.
821            $this->deleteBoomerangURL($id);
822        } else if (!refererIsMe()) {
823            // Ensure that the redirecting page is not also the referrer.
824            $url = getenv('HTTP_REFERER');
825            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
826        } else {
827            // If URL is not specified, use the redirect_home_url.
828            $url = $this->getParam('redirect_home_url');
829            $this->logMsg(sprintf('dieBoomerangURL(%s) not found, using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
830        }
831
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        // A redirection will never happen immediatly after setting the boomerangURL.
856        // Set the time so ensure this doesn't happen. See App::validBoomerangURL for more.
857
858        if ('' != $url && is_string($url)) {
859            // Delete any boomerang request keys in the query string.
860            $url = preg_replace('/boomerang=[\w]+/', '', $url);
861
862            if (isset($_SESSION[$this->app]['boomerang']['url']) && is_array($_SESSION[$this->app]['boomerang']['url']) && !empty($_SESSION[$this->app]['boomerang']['url'])) {
863                // If the URL currently exists in the boomerang array, delete.
864                while ($existing_key = array_search($url, $_SESSION[$this->app]['boomerang']['url'])) {
865                    unset($_SESSION[$this->app]['boomerang']['url'][$existing_key]);
866                }
867            }
868
869            if (isset($id)) {
870                $_SESSION[$this->app]['boomerang']['url'][$id] = $url;
871            } else {
872                $_SESSION[$this->app]['boomerang']['url'][] = $url;
873            }
874            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
875            return true;
876        } else {
877            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
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        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
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        $url = '';
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(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
968
969        if ('' == $url) {
970            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_NOTICE, __FILE__, __LINE__);
971            return false;
972        }
973        if ($url == absoluteMe()) {
974            // The URL we are directing to is the current page.
975            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
976            return false;
977        }
978        if ($boomerang_time >= (time() - 2)) {
979            // Last boomerang direction was more than 2 seconds ago.
980            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s', $id, time() - $boomerang_time), LOG_NOTICE, __FILE__, __LINE__);
981            return false;
982        }
983
984        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
985        return true;
986    }
987
988    /**
989     * Force the user to connect via https (port 443) by redirecting them to
990     * the same page but with https.
991     */
992    function sslOn()
993    {
994        if (!isset($this) || !is_a($this, 'App')) {
995            $this =& App::getInstance();
996        }
997
998        if (function_exists('apache_get_modules')) {
999            $modules = apache_get_modules();
1000        } else {
1001            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1002            $modules = array('mod_ssl');
1003        }
1004
1005        if ('on' != getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1006            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
1007            // Always append session because some browsers do not send cookie when crossing to SSL URL.
1008            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
1009        }
1010    }
1011
1012
1013    /**
1014     * to enforce the user to connect via http (port 80) by redirecting them to
1015     * a http version of the current url.
1016     */
1017    function sslOff()
1018    {
1019        if ('on' == getenv('HTTPS')) {
1020            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1021        }
1022    }
1023
1024
1025} // End.
1026
1027?>
Note: See TracBrowser for help on using the repository browser.