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

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

Q - fixed a few PEdit glitches. Reformatted PHP source correctly :-\.

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