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

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

${1}

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