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

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

Q - Improved hashing algorithms in Auth_SQL, added more sc- css selectors, misc bug fixes

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