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

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

Q - increased some LOG_DEBUG messages to LOG_INFO so we can run with debugging off and still get the important ones.

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