* Copyright 2001-2010 Strangecode, LLC * * This file is part of The Strangecode Codebase. * * The Strangecode Codebase is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * The Strangecode Codebase is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * The Strangecode Codebase. If not, see . */ /** * App.inc.php * * Primary application framework class. * * @author Quinn Comendant * @version 2.1 */ // Message Types. define('MSG_ERR', 1); define('MSG_ERROR', MSG_ERR); define('MSG_WARNING', 2); define('MSG_NOTICE', 4); define('MSG_SUCCESS', 8); define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR); require_once dirname(__FILE__) . '/Utilities.inc.php'; class App { // Namespace of this application instance. var $_ns; // If $app->start has run successfully. var $running = false; // Instance of database object. var $db; // Array of query arguments will be carried persistently between requests. var $_carry_queries = array(); // Dictionary of global application parameters. var $_params = array(); // Default parameters. var $_param_defaults = array( // Public name and email address for this application. 'site_name' => null, 'site_email' => null, 'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here. 'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i"). // The location the user will go if the system doesn't know where else to send them. 'redirect_home_url' => '/', // SSL URL used when redirecting with $app->sslOn(). 'ssl_domain' => null, 'ssl_enabled' => false, // Character set for page output. Used in the Content-Type header and the HTML tag. 'character_set' => 'utf-8', // Human-readable format used to display dates. 'date_format' => 'd M Y', 'time_format' => 'h:i:s A', 'sql_date_format' => '%e %b %Y', 'sql_time_format' => '%k:%i', // Use php sessions? 'enable_session' => false, 'session_name' => '_session', 'session_use_cookies' => true, // Pass the session-id through URLs if cookies are not enabled? // Disable this to prevent session ID theft. 'session_use_trans_sid' => false, // Use database? 'enable_db' => false, // Use db-based sessions? 'enable_db_session_handler' => false, // DB passwords should be set as apache environment variables in httpd.conf, readable only by root. 'db_server' => 'localhost', 'db_name' => null, 'db_user' => null, 'db_pass' => null, // Database debugging. 'db_always_debug' => false, // TRUE = display all SQL queries. 'db_debug' => false, // TRUE = display db errors. 'db_die_on_failure' => false, // TRUE = script stops on db error. // For classes that require db tables, do we check that a table exists and create if missing? 'db_create_tables' => true, // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display. 'error_reporting' => E_ALL, // Don't display errors by default; it is preferable to log them to a file. 'display_errors' => false, // Directory in which to store log files. 'log_directory' => '', // PHP error log. 'php_error_log' => 'php_error_log', // General application log. 'log_filename' => 'app_log', // Don't email or sms duplicate messages that happen more often than this value (in seconds). 'log_multiple_timeout' => 300, // Logging priority can be any of the following, or false to deactivate: // LOG_EMERG system is unusable // LOG_ALERT action must be taken immediately // LOG_CRIT critical conditions // LOG_ERR error conditions // LOG_WARNING warning conditions // LOG_NOTICE normal, but significant, condition // LOG_INFO informational message // LOG_DEBUG debug-level message 'log_file_priority' => LOG_INFO, 'log_email_priority' => false, 'log_sms_priority' => false, 'log_screen_priority' => false, // Email address to receive log event emails. 'log_to_email_address' => null, // SMS Email address to receive log event SMS messages. 'log_to_sms_address' => null, // Temporary files directory. 'tmp_dir' => '/tmp', // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY '. // Existing password hashes rely on the same key/salt being used to compare encryptions. // Don't change this unless you know existing hashes or signatures will not be affected! 'signing_key' => 'aae6abd6209d82a691a9f96384a7634a', ); /** * This method enforces the singleton pattern for this class. Only one application is running at a time. * * $param string $namespace Name of this application. * @return object Reference to the global Cache object. * @access public * @static */ function &getInstance($namespace='') { static $instance = null; if ($instance === null) { $instance = new App($namespace); } return $instance; } /** * Constructor. */ function App($namespace='') { // Set namespace of application instance. $this->_ns = $namespace; // Initialize default parameters. $this->_params = array_merge($this->_params, $this->_param_defaults); // Begin timing script. require_once dirname(__FILE__) . '/ScriptTimer.inc.php'; $this->timer = new ScriptTimer(); $this->timer->start('_app'); } /** * Set (or overwrite existing) parameters by passing an array of new parameters. * * @access public * @param array $param Array of parameters (key => val pairs). */ function setParam($param=null) { if (isset($param) && is_array($param)) { // Merge new parameters with old overriding only those passed. $this->_params = array_merge($this->_params, $param); } } /** * Return the value of a parameter. * * @access public * @param string $param The key of the parameter to return. * @return mixed Parameter value, or null if not existing. */ function getParam($param=null) { if ($param === null) { return $this->_params; } else if (isset($this->_params[$param])) { return $this->_params[$param]; } else { trigger_error(sprintf('Parameter is not set: %s', $param), E_USER_NOTICE); return null; } } /** * Begin running this application. * * @access public * @author Quinn Comendant * @since 15 Jul 2005 00:32:21 */ function start() { if ($this->running) { return false; } // Error reporting. ini_set('error_reporting', $this->getParam('error_reporting')); ini_set('display_errors', $this->getParam('display_errors')); ini_set('log_errors', true); if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) { ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log')); } // Set character set to use for multi-byte string functions. mb_internal_encoding($this->getParam('character_set')); switch (mb_strtolower($this->getParam('character_set'))) { case 'utf-8' : mb_language('uni'); break; case 'iso-2022-jp' : mb_language('ja'); break; case 'iso-8859-1' : default : mb_language('en'); break; } /** * 1. Start Database. */ if (true === $this->getParam('enable_db')) { // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root. if (!empty($_SERVER['DB_SERVER'])) { $this->setParam(array('db_server' => $_SERVER['DB_SERVER'])); } if (!empty($_SERVER['DB_NAME'])) { $this->setParam(array('db_name' => $_SERVER['DB_NAME'])); } if (!empty($_SERVER['DB_USER'])) { $this->setParam(array('db_user' => $_SERVER['DB_USER'])); } if (!empty($_SERVER['DB_PASS'])) { $this->setParam(array('db_pass' => $_SERVER['DB_PASS'])); } // There will ever only be one instance of the DB object, and here is where it is instantiated. require_once dirname(__FILE__) . '/DB.inc.php'; $this->db =& DB::getInstance(); $this->db->setParam(array( 'db_server' => $this->getParam('db_server'), 'db_name' => $this->getParam('db_name'), 'db_user' => $this->getParam('db_user'), 'db_pass' => $this->getParam('db_pass'), 'db_always_debug' => $this->getParam('db_always_debug'), 'db_debug' => $this->getParam('db_debug'), 'db_die_on_failure' => $this->getParam('db_die_on_failure'), )); // Connect to database. $this->db->connect(); } /** * 2. Start PHP session. */ // Skip session for some user agents. if (preg_match('/Atomz|ApacheBench|Wget/i', getenv('HTTP_USER_AGENT'))) { $this->setParam(array('enable_session' => false)); } if (true === $this->getParam('enable_session')) { // Session parameters. ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 1000); ini_set('session.gc_maxlifetime', 43200); // 12 hours ini_set('session.use_cookies', $this->getParam('session_use_cookies')); ini_set('session.use_trans_sid', false); ini_set('session.entropy_file', '/dev/urandom'); ini_set('session.entropy_length', '512'); session_name($this->getParam('session_name')); if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) { // Database session handling. require_once dirname(__FILE__) . '/DBSessionHandler.inc.php'; $db_save_handler = new DBSessionHandler($this->db, array( 'db_table' => 'session_tbl', 'create_table' => $this->getParam('db_create_tables'), )); } // Start the session. session_start(); if (!isset($_SESSION['_app'][$this->_ns])) { // Access session data using: $_SESSION['...']. // Initialize here _after_ session has started. $_SESSION['_app'][$this->_ns] = array( 'messages' => array(), 'boomerang' => array('url'), ); } } /** * 3. Misc setup. */ // Script URI will be something like http://host.name.tld (no ending slash) // and is used whenever a URL need be used to the current site. // Not available on cli scripts obviously. if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) { $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST')))); } // A key for calculating simple cryptographic signatures. if (isset($_SERVER['SIGNING_KEY'])) { $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY'])); } // Character set. This should also be printed in the html header template. header('Content-type: text/html; charset=' . $this->getParam('character_set')); // Set the version of the codebase we're using. $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt'; if (is_readable($codebase_version_file)) { $codebase_version = trim(file_get_contents($codebase_version_file)); $this->setParam(array('codebase_version' => $codebase_version)); header('X-Codebase-Version: ' . $codebase_version); } $this->running = true; } /** * Stop running this application. * * @access public * @author Quinn Comendant * @since 17 Jul 2005 17:20:18 */ function stop() { session_write_close(); restore_include_path(); $this->running = false; $num_queries = 0; if (true === $this->getParam('enable_db')) { $num_queries = $this->db->numQueries(); $this->db->close(); } $this->timer->stop('_app'); $this->logMsg(sprintf('Script ended gracefully. Execution time: %s. Number of db queries: %s.', $this->timer->getTime('_app'), $num_queries), LOG_DEBUG, __FILE__, __LINE__); } /** * Add a message to the session, which is printed in the header. * Just a simple way to print messages to the user. * * @access public * * @param string $message The text description of the message. * @param int $type The type of message: MSG_NOTICE, * MSG_SUCCESS, MSG_WARNING, or MSG_ERR. * @param string $file __FILE__. * @param string $line __LINE__. */ function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null) { $message = trim($message); if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } if ('' == trim($message)) { $this->logMsg(sprintf('Raised message is an empty string.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } // Save message in session under unique key to avoid duplicate messages. $msg_id = md5($type . $message); if (!isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id])) { $_SESSION['_app'][$this->_ns]['messages'][$msg_id] = array( 'type' => $type, 'message' => $message, 'file' => $file, 'line' => $line, 'count' => (isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) : 1) ); } if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) { $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__); } } /** * Returns an array of the raised messages. * * @access public * @return array List of messages in FIFO order. * @author Quinn Comendant * @since 21 Dec 2005 13:09:20 */ function getRaisedMessages() { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } return isset($_SESSION['_app'][$this->_ns]['messages']) ? $_SESSION['_app'][$this->_ns]['messages'] : array(); } /** * Resets the message list. * * @access public * @author Quinn Comendant * @since 21 Dec 2005 13:21:54 */ function clearRaisedMessages() { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } $_SESSION['_app'][$this->_ns]['messages'] = array(); } /** * Prints the HTML for displaying raised messages. * * @access public * @author Quinn Comendant * @since 15 Jul 2005 01:39:14 */ function printRaisedMessages() { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } $messages = $this->getRaisedMessages(); if (!empty($messages)) { ?>
0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) { echo "\n'; } switch ($m['type']) { case MSG_ERR: echo '
' . $m['message'] . '
'; break; case MSG_WARNING: echo '
' . $m['message'] . '
'; break; case MSG_SUCCESS: echo '
' . $m['message'] . '
'; break; case MSG_NOTICE: default: echo '
' . $m['message'] . '
'; break; } } ?>
clearRaisedMessages(); } /** * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are * not repeated but printed once with count. * * @access public * @param string $message The text description of the message. * @param int $priority The type of message priority (in descending order): * LOG_EMERG system is unusable * LOG_ALERT action must be taken immediately * LOG_CRIT critical conditions * LOG_ERR error conditions * LOG_WARNING warning conditions * LOG_NOTICE normal, but significant, condition * LOG_INFO informational message * LOG_DEBUG debug-level message * @param string $file The file where the log event occurs. * @param string $line The line of the file where the log event occurs. */ function logMsg($message, $priority=LOG_INFO, $file=null, $line=null) { static $previous_events = array(); // If priority is not specified, assume the worst. if (!$this->logPriorityToString($priority)) { $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line); $priority = LOG_EMERG; } // If log file is not specified, don't log to a file. if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) { $this->setParam(array('log_file_priority' => false)); // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop. trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE); } // Make sure to log in the system's locale. $locale = setlocale(LC_TIME, 0); setlocale(LC_TIME, 'C'); // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. . preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow); $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null)); // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times. $msg_id = md5($message . $priority . $file . $line); if (isset($previous_events[$msg_id])) { $previous_events[$msg_id]++; if ($previous_events[$msg_id] == 2) { $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line); } return false; } else { $previous_events[$msg_id] = 1; } // Use "lock" files to prevent sending email and sms notices ad infinitum. $site_hash = md5($_SERVER['SCRIPT_NAME']); $temp_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/"; $temp_file = $temp_dir . md5($file . $line); // Just use the file and line for the msg_id to limit the number of possible messages. if (!is_dir($temp_dir)) { mkdir($temp_dir); } $send_notifications = true; if (is_file($temp_file)) { $msg_last_sent = filectime($temp_file); // Has this message been sent more recently than the timeout? if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) { // This message was already sent recently. $send_notifications = false; } else { // Timeout has expired go ahead and send notifications again. if (file_exists($temp_file)) { unlink($temp_file); } } } else { touch($temp_file); } // Data to be stored for a log event. $event = array( 'date' => date('Y-m-d H:i:s'), 'remote ip' => getRemoteAddr(), 'pid' => (mb_substr(PHP_OS, 0, 3) != 'WIN' ? posix_getpid() : ''), 'type' => $this->logPriorityToString($priority), 'file:line' => "$file : $line", 'url' => mb_substr(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 0, 128), 'message' => $message ); // FILE ACTION if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) { $event_str = '[' . join('] [', $event) . ']'; error_log(mb_substr($event_str, 0, 1024) . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename')); } // NOTIFY SOMEONE if ($send_notifications) { // EMAIL ACTION if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) { $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message); $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST')); $headers = "From: codebase@strangecode.com"; foreach ($event as $k=>$v) { $email_msg .= sprintf("%-11s%s\n", $k, $v); } mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers); } // SMS ACTION if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) { $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority); $sms_msg = sprintf('%s [%s:%s]', mb_substr($event['message'], 0, 64), basename($file), $line); $headers = "From: codebase@strangecode.com"; mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers); } } // SCREEN ACTION if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) { echo "[{$event['type']}] [{$event['message']}]\n"; } // Restore original locale. setlocale(LC_TIME, $locale); } /** * Returns the string representation of a LOG_* integer constant. * * @param int $priority The LOG_* integer constant. * * @return The string representation of $priority. */ function logPriorityToString($priority) { $priorities = array( LOG_EMERG => 'emergency', LOG_ALERT => 'alert', LOG_CRIT => 'critical', LOG_ERR => 'error', LOG_WARNING => 'warning', LOG_NOTICE => 'notice', LOG_INFO => 'info', LOG_DEBUG => 'debug' ); if (isset($priorities[$priority])) { return $priorities[$priority]; } else { return false; } } /** * Forcefully set a query argument even if one currently exists in the request. * Values in the _carry_queries array will be copied to URLs (via $app->url()) and * to hidden input values (via printHiddenSession()). * * @access public * @param mixed $query_key The key (or keys, as an array) of the query argument to save. * @param mixed $val The new value of the argument key. * @author Quinn Comendant * @since 13 Oct 2007 11:34:51 */ function setQuery($query_key, $val) { if (!is_array($query_key)) { $query_key = array($query_key); } foreach ($query_key as $k) { // Set the value of the specified query argument into the _carry_queries array. $this->_carry_queries[$k] = $val; } } /** * Specify which query arguments will be carried persistently between requests. * Values in the _carry_queries array will be copied to URLs (via $app->url()) and * to hidden input values (via printHiddenSession()). * * @access public * @param mixed $query_key The key (or keys, as an array) of the query argument to save. * @param mixed $default If the key is not available, set to this default value. * @author Quinn Comendant * @since 14 Nov 2005 19:24:52 */ function carryQuery($query_key, $default=false) { if (!is_array($query_key)) { $query_key = array($query_key); } foreach ($query_key as $k) { // If not already set, and there is a non-empty value provided in the request... if (!isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) { // Copy the value of the specified query argument into the _carry_queries array. $this->_carry_queries[$k] = getFormData($k, $default); $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__); } } } /** * dropQuery() is the opposite of carryQuery(). The specified value will not appear in * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in. * * @access public * @param mixed $query_key The key (or keys, as an array) of the query argument to remove. * @author Quinn Comendant * @since 18 Jun 2007 20:57:29 */ function dropQuery($query_key, $unset=false) { if (!is_array($query_key)) { $query_key = array($query_key); } foreach ($query_key as $k) { if (isset($this->_carry_queries[$k])) { // Remove the value of the specified query argument from the _carry_queries array. $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__); unset($this->_carry_queries[$k]); } if ($unset && isset($_REQUEST[$k])) { unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]); } } } /** * Outputs a fully qualified URL with a query of all the used (ie: not empty) * keys and values, including optional queries. This allows mindless retention * of query arguments across page requests. If cookies are not * used, the session id will be propagated in the URL. * * @param string $url The initial url * @param mixed $carry_args Additional url arguments to carry in the query, * or FALSE to prevent carrying queries. Can be any of the following formats: * array('key1', key2', key3') <-- to save these keys if in the form data. * array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. * false <-- To not carry any queries. If URL already has queries those will be retained. * * @param mixed $always_include_sid Always add the session id, even if using_trans_sid = true. This is required when * URL starts with http, since PHP using_trans_sid doesn't do those and also for * header('Location...') redirections. * * @return string url with attached queries and, if not using cookies, the session id */ function url($url, $carry_args=null, $always_include_sid=false) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } // Get any provided query arguments to include in the final URL. // If FALSE is a provided here, DO NOT carry the queries. $do_carry_queries = true; $one_time_carry_queries = array(); if (!is_null($carry_args)) { if (is_array($carry_args) && !empty($carry_args)) { foreach ($carry_args as $key=>$arg) { // Get query from appropriate source. if (false === $arg) { $do_carry_queries = false; } else if (false !== getFormData($arg, false)) { $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available. } else if (!is_numeric($key) && '' != $arg) { $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data). } } } else if (false !== getFormData($carry_args, false)) { $one_time_carry_queries[$carry_args] = getFormData($carry_args); } else if (false === $carry_args) { $do_carry_queries = false; } } // Get the first delimiter that is needed in the url. $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?'; $q = ''; if ($do_carry_queries) { // Join the global _carry_queries and local one_time_carry_queries. $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries)); foreach ($query_args as $key=>$val) { // Check value is set and value does not already exist in the url. if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) { $q .= $delim . $key . '=' . $val; $delim = ini_get('arg_separator.output'); } } } // Include the necessary SID if the following is true: // - no cookie in http request OR cookies disabled in App // - sessions are enabled // - the link stays on our site // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here) // OR // - 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) // AND // - the SID is not already in the query. if ( ( ( ( !isset($_COOKIE[session_name()]) || !$this->getParam('session_use_cookies') ) && $this->getParam('session_use_trans_sid') && $this->getParam('enable_session') && isMyDomain($url) && ( !ini_get('session.use_trans_sid') || preg_match('!^(http|https)://!i', $url) ) ) || $always_include_sid ) && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url) ) { $url .= $q . $delim . session_name() . '=' . session_id(); return $url; } else { $url .= $q; return $url; } } /** * Returns a HTML-friendly URL processed with $app->url and & replaced with & * * @access public * @param string $url Input URL to parse. * @return string URL passed through $app->url() and then & turned to $amp;. * @author Quinn Comendant * @since 09 Dec 2005 17:58:45 */ function oHREF($url, $carry_args=null, $always_include_sid=false) { $url = $this->url($url, $carry_args, $always_include_sid); // Replace any & not followed by an html or unicode entity with it's & equivalent. $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&', $url); return $url; } /** * Prints a hidden form element with the PHPSESSID when cookies are not used, as well * as hidden form elements for GET_VARS that might be in use. * * @param mixed $carry_args Additional url arguments to carry in the query, * or FALSE to prevent carrying queries. Can be any of the following formats: * array('key1', key2', key3') <-- to save these keys if in the form data. * array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. * false <-- To not carry any queries. If URL already has queries those will be retained. */ function printHiddenSession($carry_args=null) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } // Get any provided query arguments to include in the final hidden form data. // If FALSE is a provided here, DO NOT carry the queries. $do_carry_queries = true; $one_time_carry_queries = array(); if (!is_null($carry_args)) { if (is_array($carry_args) && !empty($carry_args)) { foreach ($carry_args as $key=>$arg) { // Get query from appropriate source. if (false === $arg) { $do_carry_queries = false; } else if (false !== getFormData($arg, false)) { $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available. } else if (!is_numeric($key) && '' != $arg) { $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data). } } } else if (false !== getFormData($carry_args, false)) { $one_time_carry_queries[$carry_args] = getFormData($carry_args); } else if (false === $carry_args) { $do_carry_queries = false; } } // For each existing request value, we create a hidden input to carry it through a form. if ($do_carry_queries) { // Join the global _carry_queries and local one_time_carry_queries. // urlencode is not used here, not for form data! $query_args = array_merge($this->_carry_queries, $one_time_carry_queries); foreach ($query_args as $key=>$val) { printf('', $key, $val); } } // Include the SID if cookies are disabled. if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) { printf('', session_name(), session_id()); } } /** * Uses an http header to redirect the client to the given $url. If sessions are not used * and the session is not already defined in the given $url, the SID is appended as a URI query. * As with all header generating functions, make sure this is called before any other output. * * @param string $url The URL the client will be redirected to. * @param mixed $carry_args Additional url arguments to carry in the query, * or FALSE to prevent carrying queries. Can be any of the following formats: * -array('key1', key2', key3') <-- to save these keys if in the form data. * -array('key1' => 'value', key2' => 'value') <-- to set keys to default values if not present in form data. * -false <-- To not carry any queries. If URL already has queries those will be retained. * @param bool $always_include_sid Force session id to be added to Location header. */ function dieURL($url, $carry_args=null, $always_include_sid=false) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } if ('' == $url) { // If URL is not specified, use the redirect_home_url. $url = $this->getParam('redirect_home_url'); } if (preg_match('!^/!', $url)) { // If relative URL is given, prepend correct local hostname. $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http'; $host = getenv('HTTP_HOST'); $url = sprintf('%s://%s%s', $scheme, $host, $url); } $url = $this->url($url, $carry_args, $always_include_sid); // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP? header(sprintf('Location: %s', $url)); $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__); // End application. // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close $this->stop(); die; } /* * Redirects a user by calling $app->dieURL(). It will use: * 1. the stored boomerang URL, it it exists * 2. a specified $default_url, it it exists * 3. the referring URL, it it exists. * 4. redirect_home_url configuration variable. * * @access public * @param string $id Identifier for this script. * @param mixed $carry_args Additional arguments to carry in the URL automatically (see $app->oHREF()). * @param string $default_url A default URL if there is not a valid specified boomerang URL. * @param bool $queryless_referrer_comparison Exclude the URL query from the refererIsMe() comparison. * @return bool False if the session is not running. No return otherwise. * @author Quinn Comendant * @since 31 Mar 2006 19:17:00 */ function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } // Get URL from stored boomerang. Allow non specific URL if ID not valid. if ($this->validBoomerangURL($id, true)) { if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]; $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); } else { $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']); $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); } // Delete stored boomerang. $this->deleteBoomerangURL($id); } else if (isset($default_url)) { $url = $default_url; } else if (!refererIsMe(true === $queryless_referrer_comparison)) { // Ensure that the redirecting page is not also the referrer. $url = getenv('HTTP_REFERER'); $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); } else { // If URL is not specified, use the redirect_home_url. $url = $this->getParam('redirect_home_url'); $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); } // A redirection will never happen immediately twice. // Set the time so ensure this doesn't happen. $_SESSION['_app'][$this->_ns]['boomerang']['time'] = time(); $this->dieURL($url, $carry_args); } /** * Set the URL to return to when $app->dieBoomerangURL() is called. * * @param string $url A fully validated URL. * @param bool $id An identification tag for this url. * FIXME: url garbage collection? */ function setBoomerangURL($url=null, $id=null) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } // A redirection will never happen immediately after setting the boomerangURL. // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more. /// FIXME: Why isn't the time set here under setBoomerangURL() and only under dieBoomerangURL()? if ('' != $url && is_string($url)) { // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion). $url = preg_replace(array('/([&?])boomerang=\w+[&?]?/', '/[&?]$/'), array('$1', ''), $url); if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']['url']) && !empty($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { // If the URL currently exists in the boomerang array, delete. while ($existing_key = array_search($url, $_SESSION['_app'][$this->_ns]['boomerang']['url'])) { unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$existing_key]); } } if (isset($id)) { $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id] = $url; } else { $_SESSION['_app'][$this->_ns]['boomerang']['url'][] = $url; } $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); return true; } else { $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__); return false; } } /** * Return the URL set for the specified $id, or an empty string if one isn't set. * * @param string $id An identification tag for this url. */ function getBoomerangURL($id=null) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } if (isset($id)) { if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { return $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]; } else { return ''; } } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { return end($_SESSION['_app'][$this->_ns]['boomerang']['url']); } else { return false; } } /** * Delete the URL set for the specified $id. * * @param string $id An identification tag for this url. */ function deleteBoomerangURL($id=null) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__); if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]); } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { array_pop($_SESSION['_app'][$this->_ns]['boomerang']['url']); } } /** * Check if a valid boomerang URL value has been set. A boomerang URL is considered * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds. * * @return bool True if it is set and valid, false otherwise. */ function validBoomerangURL($id=null, $use_nonspecificboomerang=false) { if (!$this->running) { $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); return false; } if (!isset($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__); return false; } // Time is the time stamp of a boomerangURL redirection, or setting of a boomerangURL. // a boomerang redirection will always occur at least several seconds after the last boomerang redirect // or a boomerang being set. $boomerang_time = isset($_SESSION['_app'][$this->_ns]['boomerang']['time']) ? $_SESSION['_app'][$this->_ns]['boomerang']['time'] : 0; $url = ''; if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]; } else if (!isset($id) || $use_nonspecificboomerang) { // Use non specific boomerang if available. $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']); } $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); if ('' == $url) { $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__); return false; } if ($url == absoluteMe()) { // The URL we are directing to is the current page. $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); return false; } if ($boomerang_time >= (time() - 2)) { // Last boomerang direction was less than 2 seconds ago. $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s seconds', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__); return false; } $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); return true; } /** * Force the user to connect via https (port 443) by redirecting them to * the same page but with https. */ function sslOn() { if (function_exists('apache_get_modules')) { $modules = apache_get_modules(); } else { // It's safe to assume we have mod_ssl if we can't determine otherwise. $modules = array('mod_ssl'); } if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) { $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__); // Always append session because some browsers do not send cookie when crossing to SSL URL. $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true); } } /** * to enforce the user to connect via http (port 80) by redirecting them to * a http version of the current url. */ function sslOff() { if ('' != getenv('HTTPS')) { $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true); } } } // End. ?>