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

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

${1}

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