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

Last change on this file since 333 was 333, checked in by quinn, 16 years ago

Finished initial version of Cart.inc.php. Minor css changes.

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