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

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

Q - bits!

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