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

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

B - added js to hide success msg after 5 seconds

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