[1] | 1 | <?php |
---|
| 2 | /** |
---|
[362] | 3 | * The Strangecode Codebase - a general application development framework for PHP |
---|
| 4 | * For details visit the project site: <http://trac.strangecode.com/codebase/> |
---|
[396] | 5 | * Copyright 2001-2012 Strangecode, LLC |
---|
[452] | 6 | * |
---|
[362] | 7 | * This file is part of The Strangecode Codebase. |
---|
| 8 | * |
---|
| 9 | * The Strangecode Codebase is free software: you can redistribute it and/or |
---|
| 10 | * modify it under the terms of the GNU General Public License as published by the |
---|
| 11 | * Free Software Foundation, either version 3 of the License, or (at your option) |
---|
| 12 | * any later version. |
---|
[452] | 13 | * |
---|
[362] | 14 | * The Strangecode Codebase is distributed in the hope that it will be useful, but |
---|
| 15 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
---|
| 16 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
---|
| 17 | * details. |
---|
[452] | 18 | * |
---|
[362] | 19 | * You should have received a copy of the GNU General Public License along with |
---|
| 20 | * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>. |
---|
| 21 | */ |
---|
| 22 | |
---|
| 23 | /** |
---|
[1] | 24 | * App.inc.php |
---|
| 25 | * |
---|
| 26 | * Primary application framework class. |
---|
| 27 | * |
---|
| 28 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
[136] | 29 | * @version 2.1 |
---|
[1] | 30 | */ |
---|
[42] | 31 | |
---|
[37] | 32 | // Message Types. |
---|
| 33 | define('MSG_ERR', 1); |
---|
| 34 | define('MSG_ERROR', MSG_ERR); |
---|
[1] | 35 | define('MSG_WARNING', 2); |
---|
[37] | 36 | define('MSG_NOTICE', 4); |
---|
| 37 | define('MSG_SUCCESS', 8); |
---|
[119] | 38 | define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR); |
---|
[1] | 39 | |
---|
| 40 | require_once dirname(__FILE__) . '/Utilities.inc.php'; |
---|
| 41 | |
---|
[502] | 42 | class App |
---|
| 43 | { |
---|
[42] | 44 | |
---|
[487] | 45 | // Minimum version of PHP required for this version of the Codebase. |
---|
| 46 | const CODEBASE_MIN_PHP_VERSION = '5.3.0'; |
---|
| 47 | |
---|
[468] | 48 | // A place to keep an object instance for the singleton pattern. |
---|
[484] | 49 | protected static $instance = null; |
---|
[468] | 50 | |
---|
[136] | 51 | // Namespace of this application instance. |
---|
[484] | 52 | protected $_ns; |
---|
[1] | 53 | |
---|
[136] | 54 | // If $app->start has run successfully. |
---|
[468] | 55 | public $running = false; |
---|
[1] | 56 | |
---|
| 57 | // Instance of database object. |
---|
[468] | 58 | public $db; |
---|
[42] | 59 | |
---|
[20] | 60 | // Array of query arguments will be carried persistently between requests. |
---|
[484] | 61 | protected $_carry_queries = array(); |
---|
[1] | 62 | |
---|
[136] | 63 | // Dictionary of global application parameters. |
---|
[484] | 64 | protected $_params = array(); |
---|
[1] | 65 | |
---|
| 66 | // Default parameters. |
---|
[484] | 67 | protected $_param_defaults = array( |
---|
[1] | 68 | |
---|
| 69 | // Public name and email address for this application. |
---|
| 70 | 'site_name' => null, |
---|
[390] | 71 | 'site_email' => '', // Set to no-reply@HTTP_HOST if not set here. |
---|
[39] | 72 | 'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here. |
---|
[318] | 73 | 'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i"). |
---|
[491] | 74 | 'site_version_file' => 'docs/version.txt', // File containing version number of this app, relative to the include path. |
---|
[1] | 75 | |
---|
[136] | 76 | // The location the user will go if the system doesn't know where else to send them. |
---|
[1] | 77 | 'redirect_home_url' => '/', |
---|
[42] | 78 | |
---|
[136] | 79 | // SSL URL used when redirecting with $app->sslOn(). |
---|
[1] | 80 | 'ssl_domain' => null, |
---|
| 81 | 'ssl_enabled' => false, |
---|
[42] | 82 | |
---|
[501] | 83 | // Use CSRF tokens. See notes in the getCSRFToken() method. |
---|
[500] | 84 | 'csrf_token_enabled' => true, |
---|
[501] | 85 | // Form tokens will expire after this duration, in seconds. |
---|
| 86 | 'csrf_token_timeout' => 259200, // 259200 seconds = 3 days. |
---|
[500] | 87 | 'csrf_token_name' => 'csrf_token', |
---|
| 88 | |
---|
| 89 | // HMAC signing method |
---|
| 90 | 'signing_method' => 'sha512+base64', |
---|
| 91 | |
---|
[20] | 92 | // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag. |
---|
[1] | 93 | 'character_set' => 'utf-8', |
---|
| 94 | |
---|
| 95 | // Human-readable format used to display dates. |
---|
| 96 | 'date_format' => 'd M Y', |
---|
[101] | 97 | 'time_format' => 'h:i:s A', |
---|
[1] | 98 | 'sql_date_format' => '%e %b %Y', |
---|
| 99 | 'sql_time_format' => '%k:%i', |
---|
| 100 | |
---|
| 101 | // Use php sessions? |
---|
| 102 | 'enable_session' => false, |
---|
[242] | 103 | 'session_name' => '_session', |
---|
[1] | 104 | 'session_use_cookies' => true, |
---|
[452] | 105 | |
---|
[293] | 106 | // Pass the session-id through URLs if cookies are not enabled? |
---|
| 107 | // Disable this to prevent session ID theft. |
---|
[242] | 108 | 'session_use_trans_sid' => false, |
---|
[42] | 109 | |
---|
[1] | 110 | // Use database? |
---|
| 111 | 'enable_db' => false, |
---|
| 112 | |
---|
| 113 | // Use db-based sessions? |
---|
| 114 | 'enable_db_session_handler' => false, |
---|
[42] | 115 | |
---|
[1] | 116 | // DB passwords should be set as apache environment variables in httpd.conf, readable only by root. |
---|
| 117 | 'db_server' => 'localhost', |
---|
| 118 | 'db_name' => null, |
---|
| 119 | 'db_user' => null, |
---|
| 120 | 'db_pass' => null, |
---|
| 121 | |
---|
| 122 | // Database debugging. |
---|
| 123 | 'db_always_debug' => false, // TRUE = display all SQL queries. |
---|
| 124 | 'db_debug' => false, // TRUE = display db errors. |
---|
| 125 | 'db_die_on_failure' => false, // TRUE = script stops on db error. |
---|
[42] | 126 | |
---|
[1] | 127 | // For classes that require db tables, do we check that a table exists and create if missing? |
---|
[32] | 128 | 'db_create_tables' => true, |
---|
[1] | 129 | |
---|
[136] | 130 | // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display. |
---|
[1] | 131 | 'error_reporting' => E_ALL, |
---|
| 132 | |
---|
| 133 | // Don't display errors by default; it is preferable to log them to a file. |
---|
| 134 | 'display_errors' => false, |
---|
[42] | 135 | |
---|
[1] | 136 | // Directory in which to store log files. |
---|
[19] | 137 | 'log_directory' => '', |
---|
[1] | 138 | |
---|
| 139 | // PHP error log. |
---|
| 140 | 'php_error_log' => 'php_error_log', |
---|
| 141 | |
---|
| 142 | // General application log. |
---|
[136] | 143 | 'log_filename' => 'app_log', |
---|
[1] | 144 | |
---|
[390] | 145 | // Don't email or SMS duplicate messages that happen more often than this value (in seconds). |
---|
| 146 | 'log_multiple_timeout' => 3600, // Hourly |
---|
[341] | 147 | |
---|
[1] | 148 | // Logging priority can be any of the following, or false to deactivate: |
---|
| 149 | // LOG_EMERG system is unusable |
---|
| 150 | // LOG_ALERT action must be taken immediately |
---|
| 151 | // LOG_CRIT critical conditions |
---|
| 152 | // LOG_ERR error conditions |
---|
| 153 | // LOG_WARNING warning conditions |
---|
| 154 | // LOG_NOTICE normal, but significant, condition |
---|
| 155 | // LOG_INFO informational message |
---|
| 156 | // LOG_DEBUG debug-level message |
---|
[174] | 157 | 'log_file_priority' => LOG_INFO, |
---|
[342] | 158 | 'log_email_priority' => false, |
---|
[1] | 159 | 'log_sms_priority' => false, |
---|
| 160 | 'log_screen_priority' => false, |
---|
[42] | 161 | |
---|
[390] | 162 | // Email address to receive log event emails. Use multiple addresses by separating them with commas. |
---|
[342] | 163 | 'log_to_email_address' => null, |
---|
[42] | 164 | |
---|
[392] | 165 | // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas. |
---|
[1] | 166 | 'log_to_sms_address' => null, |
---|
[42] | 167 | |
---|
[406] | 168 | // Should we avoid logging repeated logMsg() events? You might want to set this false if you need to see more accurate logging, particularly for long-running scripts. |
---|
| 169 | 'log_ignore_repeated_events' => true, |
---|
| 170 | |
---|
[348] | 171 | // Temporary files directory. |
---|
| 172 | 'tmp_dir' => '/tmp', |
---|
[343] | 173 | |
---|
[19] | 174 | // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'. |
---|
[136] | 175 | // Existing password hashes rely on the same key/salt being used to compare encryptions. |
---|
| 176 | // Don't change this unless you know existing hashes or signatures will not be affected! |
---|
[1] | 177 | 'signing_key' => 'aae6abd6209d82a691a9f96384a7634a', |
---|
| 178 | ); |
---|
[42] | 179 | |
---|
[1] | 180 | /** |
---|
| 181 | * Constructor. |
---|
| 182 | */ |
---|
[468] | 183 | public function __construct($namespace='') |
---|
[1] | 184 | { |
---|
[136] | 185 | // Set namespace of application instance. |
---|
[154] | 186 | $this->_ns = $namespace; |
---|
[42] | 187 | |
---|
[1] | 188 | // Initialize default parameters. |
---|
| 189 | $this->_params = array_merge($this->_params, $this->_param_defaults); |
---|
[452] | 190 | |
---|
[172] | 191 | // Begin timing script. |
---|
| 192 | require_once dirname(__FILE__) . '/ScriptTimer.inc.php'; |
---|
| 193 | $this->timer = new ScriptTimer(); |
---|
| 194 | $this->timer->start('_app'); |
---|
[1] | 195 | } |
---|
| 196 | |
---|
| 197 | /** |
---|
[468] | 198 | * This method enforces the singleton pattern for this class. Only one application is running at a time. |
---|
| 199 | * |
---|
| 200 | * $param string $namespace Name of this application. |
---|
| 201 | * @return object Reference to the global Cache object. |
---|
| 202 | * @access public |
---|
| 203 | * @static |
---|
| 204 | */ |
---|
| 205 | public static function &getInstance($namespace='') |
---|
| 206 | { |
---|
| 207 | if (self::$instance === null) { |
---|
| 208 | // TODO: Yep, having a namespace with one singletone instance is not very useful. |
---|
| 209 | self::$instance = new self($namespace); |
---|
| 210 | } |
---|
| 211 | |
---|
| 212 | return self::$instance; |
---|
| 213 | } |
---|
| 214 | |
---|
| 215 | /** |
---|
[1] | 216 | * Set (or overwrite existing) parameters by passing an array of new parameters. |
---|
| 217 | * |
---|
| 218 | * @access public |
---|
| 219 | * @param array $param Array of parameters (key => val pairs). |
---|
| 220 | */ |
---|
[468] | 221 | public function setParam($param=null) |
---|
[1] | 222 | { |
---|
| 223 | if (isset($param) && is_array($param)) { |
---|
| 224 | // Merge new parameters with old overriding only those passed. |
---|
[136] | 225 | $this->_params = array_merge($this->_params, $param); |
---|
[1] | 226 | } |
---|
| 227 | } |
---|
| 228 | |
---|
| 229 | /** |
---|
| 230 | * Return the value of a parameter. |
---|
| 231 | * |
---|
| 232 | * @access public |
---|
| 233 | * @param string $param The key of the parameter to return. |
---|
| 234 | * @return mixed Parameter value, or null if not existing. |
---|
| 235 | */ |
---|
[468] | 236 | public function getParam($param=null) |
---|
[1] | 237 | { |
---|
| 238 | if ($param === null) { |
---|
[136] | 239 | return $this->_params; |
---|
[478] | 240 | } else if (array_key_exists($param, $this->_params)) { |
---|
[136] | 241 | return $this->_params[$param]; |
---|
[1] | 242 | } else { |
---|
| 243 | return null; |
---|
| 244 | } |
---|
| 245 | } |
---|
[42] | 246 | |
---|
[1] | 247 | /** |
---|
| 248 | * Begin running this application. |
---|
| 249 | * |
---|
| 250 | * @access public |
---|
| 251 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 252 | * @since 15 Jul 2005 00:32:21 |
---|
| 253 | */ |
---|
[468] | 254 | public function start() |
---|
[1] | 255 | { |
---|
| 256 | if ($this->running) { |
---|
| 257 | return false; |
---|
| 258 | } |
---|
[42] | 259 | |
---|
[1] | 260 | // Error reporting. |
---|
| 261 | ini_set('error_reporting', $this->getParam('error_reporting')); |
---|
| 262 | ini_set('display_errors', $this->getParam('display_errors')); |
---|
| 263 | ini_set('log_errors', true); |
---|
| 264 | if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) { |
---|
| 265 | ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log')); |
---|
| 266 | } |
---|
[42] | 267 | |
---|
[248] | 268 | // Set character set to use for multi-byte string functions. |
---|
| 269 | mb_internal_encoding($this->getParam('character_set')); |
---|
[249] | 270 | switch (mb_strtolower($this->getParam('character_set'))) { |
---|
| 271 | case 'utf-8' : |
---|
| 272 | mb_language('uni'); |
---|
| 273 | break; |
---|
[42] | 274 | |
---|
[249] | 275 | case 'iso-2022-jp' : |
---|
| 276 | mb_language('ja'); |
---|
| 277 | break; |
---|
| 278 | |
---|
| 279 | case 'iso-8859-1' : |
---|
| 280 | default : |
---|
| 281 | mb_language('en'); |
---|
| 282 | break; |
---|
| 283 | } |
---|
| 284 | |
---|
[1] | 285 | /** |
---|
| 286 | * 1. Start Database. |
---|
| 287 | */ |
---|
[42] | 288 | |
---|
[103] | 289 | if (true === $this->getParam('enable_db')) { |
---|
[42] | 290 | |
---|
[1] | 291 | // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root. |
---|
[468] | 292 | if (!empty($_SERVER['DB_SERVER']) && !$this->getParam('db_server')) { |
---|
[1] | 293 | $this->setParam(array('db_server' => $_SERVER['DB_SERVER'])); |
---|
| 294 | } |
---|
[468] | 295 | if (!empty($_SERVER['DB_NAME']) && !$this->getParam('db_name')) { |
---|
[1] | 296 | $this->setParam(array('db_name' => $_SERVER['DB_NAME'])); |
---|
| 297 | } |
---|
[468] | 298 | if (!empty($_SERVER['DB_USER']) && !$this->getParam('db_user')) { |
---|
[1] | 299 | $this->setParam(array('db_user' => $_SERVER['DB_USER'])); |
---|
| 300 | } |
---|
[468] | 301 | if (!empty($_SERVER['DB_PASS']) && !$this->getParam('db_pass')) { |
---|
[1] | 302 | $this->setParam(array('db_pass' => $_SERVER['DB_PASS'])); |
---|
| 303 | } |
---|
[42] | 304 | |
---|
[136] | 305 | // There will ever only be one instance of the DB object, and here is where it is instantiated. |
---|
[1] | 306 | require_once dirname(__FILE__) . '/DB.inc.php'; |
---|
| 307 | $this->db =& DB::getInstance(); |
---|
| 308 | $this->db->setParam(array( |
---|
| 309 | 'db_server' => $this->getParam('db_server'), |
---|
| 310 | 'db_name' => $this->getParam('db_name'), |
---|
| 311 | 'db_user' => $this->getParam('db_user'), |
---|
| 312 | 'db_pass' => $this->getParam('db_pass'), |
---|
| 313 | 'db_always_debug' => $this->getParam('db_always_debug'), |
---|
| 314 | 'db_debug' => $this->getParam('db_debug'), |
---|
| 315 | 'db_die_on_failure' => $this->getParam('db_die_on_failure'), |
---|
| 316 | )); |
---|
| 317 | |
---|
| 318 | // Connect to database. |
---|
| 319 | $this->db->connect(); |
---|
| 320 | } |
---|
[42] | 321 | |
---|
| 322 | |
---|
[1] | 323 | /** |
---|
| 324 | * 2. Start PHP session. |
---|
| 325 | */ |
---|
[42] | 326 | |
---|
[433] | 327 | // Skip sessions if disabled or automatically skip if run in a CLI script. |
---|
| 328 | if (true === $this->getParam('enable_session') && !defined('_CLI')) { |
---|
[42] | 329 | |
---|
[373] | 330 | // Session parameters. |
---|
| 331 | ini_set('session.gc_probability', 1); |
---|
| 332 | ini_set('session.gc_divisor', 1000); |
---|
| 333 | ini_set('session.gc_maxlifetime', 43200); // 12 hours |
---|
| 334 | ini_set('session.use_cookies', $this->getParam('session_use_cookies')); |
---|
| 335 | ini_set('session.use_trans_sid', false); |
---|
| 336 | ini_set('session.entropy_file', '/dev/urandom'); |
---|
| 337 | ini_set('session.entropy_length', '512'); |
---|
[410] | 338 | ini_set('session.cookie_httponly', true); |
---|
[373] | 339 | session_name($this->getParam('session_name')); |
---|
| 340 | |
---|
[1] | 341 | if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) { |
---|
| 342 | // Database session handling. |
---|
| 343 | require_once dirname(__FILE__) . '/DBSessionHandler.inc.php'; |
---|
| 344 | $db_save_handler = new DBSessionHandler($this->db, array( |
---|
| 345 | 'db_table' => 'session_tbl', |
---|
| 346 | 'create_table' => $this->getParam('db_create_tables'), |
---|
| 347 | )); |
---|
| 348 | } |
---|
[42] | 349 | |
---|
[22] | 350 | // Start the session. |
---|
[1] | 351 | session_start(); |
---|
[42] | 352 | |
---|
[154] | 353 | if (!isset($_SESSION['_app'][$this->_ns])) { |
---|
[22] | 354 | // Access session data using: $_SESSION['...']. |
---|
| 355 | // Initialize here _after_ session has started. |
---|
[154] | 356 | $_SESSION['_app'][$this->_ns] = array( |
---|
[22] | 357 | 'messages' => array(), |
---|
| 358 | 'boomerang' => array('url'), |
---|
| 359 | ); |
---|
| 360 | } |
---|
[1] | 361 | } |
---|
[42] | 362 | |
---|
| 363 | |
---|
[1] | 364 | /** |
---|
| 365 | * 3. Misc setup. |
---|
| 366 | */ |
---|
| 367 | |
---|
| 368 | // Script URI will be something like http://host.name.tld (no ending slash) |
---|
| 369 | // and is used whenever a URL need be used to the current site. |
---|
| 370 | // Not available on cli scripts obviously. |
---|
[41] | 371 | if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) { |
---|
[14] | 372 | $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST')))); |
---|
[1] | 373 | } |
---|
[452] | 374 | |
---|
[390] | 375 | // In case site_email isn't set, use something halfway presentable. |
---|
| 376 | if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_email')) { |
---|
| 377 | $this->setParam(array('site_email' => sprintf('no-reply@%s', getenv('HTTP_HOST')))); |
---|
| 378 | } |
---|
[1] | 379 | |
---|
| 380 | // A key for calculating simple cryptographic signatures. |
---|
| 381 | if (isset($_SERVER['SIGNING_KEY'])) { |
---|
| 382 | $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY'])); |
---|
| 383 | } |
---|
[42] | 384 | |
---|
[1] | 385 | // Character set. This should also be printed in the html header template. |
---|
[476] | 386 | if (!defined('_CLI')) { |
---|
| 387 | header('Content-type: text/html; charset=' . $this->getParam('character_set')); |
---|
| 388 | } |
---|
[452] | 389 | |
---|
[136] | 390 | // Set the version of the codebase we're using. |
---|
| 391 | $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt'; |
---|
[487] | 392 | $codebase_version = ''; |
---|
[491] | 393 | if (is_readable($codebase_version_file) && !is_dir($codebase_version_file)) { |
---|
[136] | 394 | $codebase_version = trim(file_get_contents($codebase_version_file)); |
---|
[144] | 395 | $this->setParam(array('codebase_version' => $codebase_version)); |
---|
[476] | 396 | if (!defined('_CLI')) { |
---|
| 397 | header('X-Codebase-Version: ' . $codebase_version); |
---|
| 398 | } |
---|
[136] | 399 | } |
---|
[42] | 400 | |
---|
[487] | 401 | if (version_compare(PHP_VERSION, self::CODEBASE_MIN_PHP_VERSION, '<')) { |
---|
| 402 | $this->logMsg(sprintf('PHP %s required for Codebase %s, using %s; some things will break.', self::CODEBASE_MIN_PHP_VERSION, $codebase_version, PHP_VERSION), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 403 | } |
---|
| 404 | |
---|
[491] | 405 | // Set the application version if defined. |
---|
[499] | 406 | if (false !== stream_resolve_include_path($this->getParam('site_version_file'))) { |
---|
[491] | 407 | $site_version = trim(file_get_contents($this->getParam('site_version_file'), true)); |
---|
[499] | 408 | $this->setParam(array('site_version' => $site_version)); |
---|
| 409 | if (!defined('_CLI')) { |
---|
| 410 | header('X-Site-Version: ' . $site_version); |
---|
| 411 | } |
---|
[491] | 412 | } |
---|
| 413 | |
---|
[1] | 414 | $this->running = true; |
---|
| 415 | } |
---|
[42] | 416 | |
---|
[1] | 417 | /** |
---|
| 418 | * Stop running this application. |
---|
| 419 | * |
---|
| 420 | * @access public |
---|
| 421 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 422 | * @since 17 Jul 2005 17:20:18 |
---|
| 423 | */ |
---|
[468] | 424 | public function stop() |
---|
[1] | 425 | { |
---|
| 426 | session_write_close(); |
---|
| 427 | $this->running = false; |
---|
[172] | 428 | $num_queries = 0; |
---|
[103] | 429 | if (true === $this->getParam('enable_db')) { |
---|
[172] | 430 | $num_queries = $this->db->numQueries(); |
---|
[103] | 431 | $this->db->close(); |
---|
| 432 | } |
---|
[452] | 433 | $mem_current = memory_get_usage(); |
---|
| 434 | $mem_peak = memory_get_peak_usage(); |
---|
[172] | 435 | $this->timer->stop('_app'); |
---|
[452] | 436 | $this->logMsg(sprintf('Script ended gracefully. Execution time: %s. Number of db queries: %s. Memory usage: %s. Peak memory: %s.', $this->timer->getTime('_app'), $num_queries, $mem_current, $mem_peak), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 437 | } |
---|
[42] | 438 | |
---|
| 439 | |
---|
[1] | 440 | /** |
---|
[84] | 441 | * Add a message to the session, which is printed in the header. |
---|
[1] | 442 | * Just a simple way to print messages to the user. |
---|
| 443 | * |
---|
| 444 | * @access public |
---|
| 445 | * |
---|
| 446 | * @param string $message The text description of the message. |
---|
| 447 | * @param int $type The type of message: MSG_NOTICE, |
---|
| 448 | * MSG_SUCCESS, MSG_WARNING, or MSG_ERR. |
---|
| 449 | * @param string $file __FILE__. |
---|
| 450 | * @param string $line __LINE__. |
---|
| 451 | */ |
---|
[468] | 452 | public function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null) |
---|
[1] | 453 | { |
---|
[32] | 454 | $message = trim($message); |
---|
[1] | 455 | |
---|
[203] | 456 | if (!$this->running) { |
---|
| 457 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 458 | return false; |
---|
| 459 | } |
---|
[42] | 460 | |
---|
[203] | 461 | if ('' == trim($message)) { |
---|
[500] | 462 | $this->logMsg(sprintf('Raised message is an empty string.', null), LOG_NOTICE, __FILE__, __LINE__); |
---|
[203] | 463 | return false; |
---|
| 464 | } |
---|
[452] | 465 | |
---|
[406] | 466 | // Avoid duplicate full-stops.. |
---|
| 467 | $message = trim(preg_replace('/\.{2}$/', '.', $message)); |
---|
[203] | 468 | |
---|
[37] | 469 | // Save message in session under unique key to avoid duplicate messages. |
---|
[177] | 470 | $msg_id = md5($type . $message); |
---|
| 471 | if (!isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id])) { |
---|
| 472 | $_SESSION['_app'][$this->_ns]['messages'][$msg_id] = array( |
---|
| 473 | 'type' => $type, |
---|
| 474 | 'message' => $message, |
---|
| 475 | 'file' => $file, |
---|
| 476 | 'line' => $line, |
---|
| 477 | 'count' => (isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) : 1) |
---|
| 478 | ); |
---|
| 479 | } |
---|
[42] | 480 | |
---|
[1] | 481 | if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) { |
---|
[136] | 482 | $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 483 | } |
---|
| 484 | } |
---|
[452] | 485 | |
---|
[46] | 486 | /** |
---|
| 487 | * Returns an array of the raised messages. |
---|
| 488 | * |
---|
| 489 | * @access public |
---|
[334] | 490 | * @return array List of messages in FIFO order. |
---|
[46] | 491 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 492 | * @since 21 Dec 2005 13:09:20 |
---|
| 493 | */ |
---|
[468] | 494 | public function getRaisedMessages() |
---|
[46] | 495 | { |
---|
[136] | 496 | if (!$this->running) { |
---|
| 497 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 498 | return false; |
---|
[46] | 499 | } |
---|
[154] | 500 | return isset($_SESSION['_app'][$this->_ns]['messages']) ? $_SESSION['_app'][$this->_ns]['messages'] : array(); |
---|
[46] | 501 | } |
---|
[452] | 502 | |
---|
[1] | 503 | /** |
---|
[46] | 504 | * Resets the message list. |
---|
| 505 | * |
---|
| 506 | * @access public |
---|
| 507 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 508 | * @since 21 Dec 2005 13:21:54 |
---|
| 509 | */ |
---|
[468] | 510 | public function clearRaisedMessages() |
---|
[46] | 511 | { |
---|
[136] | 512 | if (!$this->running) { |
---|
| 513 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[46] | 514 | return false; |
---|
| 515 | } |
---|
[452] | 516 | |
---|
[154] | 517 | $_SESSION['_app'][$this->_ns]['messages'] = array(); |
---|
[46] | 518 | } |
---|
| 519 | |
---|
| 520 | /** |
---|
[1] | 521 | * Prints the HTML for displaying raised messages. |
---|
| 522 | * |
---|
[413] | 523 | * @param string $above Additional message to print above error messages (e.g. "Oops!"). |
---|
| 524 | * @param string $below Additional message to print below error messages (e.g. "Please fix and resubmit"). |
---|
| 525 | * @param string $print_gotohash_js Print a line of javascript that scrolls the browser window down to view any error messages. |
---|
| 526 | * @param string $hash The #hashtag to scroll to. |
---|
[1] | 527 | * @access public |
---|
| 528 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 529 | * @since 15 Jul 2005 01:39:14 |
---|
| 530 | */ |
---|
[468] | 531 | public function printRaisedMessages($above='', $below='', $print_gotohash_js=false, $hash='sc-msg') |
---|
[1] | 532 | { |
---|
[468] | 533 | |
---|
[136] | 534 | if (!$this->running) { |
---|
| 535 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 536 | return false; |
---|
| 537 | } |
---|
[452] | 538 | |
---|
[136] | 539 | $messages = $this->getRaisedMessages(); |
---|
[167] | 540 | if (!empty($messages)) { |
---|
[163] | 541 | ?><div id="sc-msg" class="sc-msg"><?php |
---|
[413] | 542 | if ('' != $above) { |
---|
| 543 | ?><div class="sc-above"><?php echo oTxt($above); ?></div><?php |
---|
| 544 | } |
---|
[167] | 545 | foreach ($messages as $m) { |
---|
| 546 | if (error_reporting() > 0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) { |
---|
| 547 | echo "\n<!-- [" . $m['file'] . ' : ' . $m['line'] . '] -->'; |
---|
| 548 | } |
---|
| 549 | switch ($m['type']) { |
---|
| 550 | case MSG_ERR: |
---|
[497] | 551 | echo '<div data-alert class="sc-msg-error alert-box alert">' . $m['message'] . '<a href="#" class="close">×</a></div>'; |
---|
[167] | 552 | break; |
---|
[42] | 553 | |
---|
[167] | 554 | case MSG_WARNING: |
---|
[497] | 555 | echo '<div data-alert class="sc-msg-warning alert-box warning">' . $m['message'] . '<a href="#" class="close">×</a></div>'; |
---|
[167] | 556 | break; |
---|
[42] | 557 | |
---|
[167] | 558 | case MSG_SUCCESS: |
---|
[497] | 559 | echo '<div data-alert class="sc-msg-success alert-box success">' . $m['message'] . '<a href="#" class="close">×</a></div>'; |
---|
[167] | 560 | break; |
---|
[42] | 561 | |
---|
[167] | 562 | case MSG_NOTICE: |
---|
| 563 | default: |
---|
[497] | 564 | echo '<div data-alert class="sc-msg-notice alert-box info">' . $m['message'] . '<a href="#" class="close">×</a></div>'; |
---|
[167] | 565 | break; |
---|
| 566 | } |
---|
[1] | 567 | } |
---|
[413] | 568 | if ('' != $below) { |
---|
| 569 | ?><div class="sc-below"><?php echo oTxt($below); ?></div><?php |
---|
| 570 | } |
---|
[1] | 571 | ?></div><?php |
---|
[413] | 572 | if ($print_gotohash_js) { |
---|
| 573 | ?> |
---|
| 574 | <script type="text/javascript"> |
---|
| 575 | /* <![CDATA[ */ |
---|
| 576 | window.location.hash = '#<?php echo urlencode($hash); ?>'; |
---|
| 577 | /* ]]> */ |
---|
| 578 | </script> |
---|
| 579 | <?php |
---|
| 580 | } |
---|
[1] | 581 | } |
---|
[136] | 582 | $this->clearRaisedMessages(); |
---|
[1] | 583 | } |
---|
[42] | 584 | |
---|
[1] | 585 | /** |
---|
[44] | 586 | * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are |
---|
[390] | 587 | * not repeated but printed once with count. Log events that match a sendable channel (email or SMS) |
---|
| 588 | * are sent once per 'log_multiple_timeout' setting (to avoid a flood of error emails). |
---|
[1] | 589 | * |
---|
| 590 | * @access public |
---|
| 591 | * @param string $message The text description of the message. |
---|
| 592 | * @param int $priority The type of message priority (in descending order): |
---|
[390] | 593 | * LOG_EMERG 0 system is unusable |
---|
| 594 | * LOG_ALERT 1 action must be taken immediately |
---|
| 595 | * LOG_CRIT 2 critical conditions |
---|
| 596 | * LOG_ERR 3 error conditions |
---|
| 597 | * LOG_WARNING 4 warning conditions |
---|
| 598 | * LOG_NOTICE 5 normal, but significant, condition |
---|
| 599 | * LOG_INFO 6 informational message |
---|
| 600 | * LOG_DEBUG 7 debug-level message |
---|
[1] | 601 | * @param string $file The file where the log event occurs. |
---|
| 602 | * @param string $line The line of the file where the log event occurs. |
---|
| 603 | */ |
---|
[468] | 604 | public function logMsg($message, $priority=LOG_INFO, $file=null, $line=null) |
---|
[1] | 605 | { |
---|
[44] | 606 | static $previous_events = array(); |
---|
| 607 | |
---|
[1] | 608 | // If priority is not specified, assume the worst. |
---|
[136] | 609 | if (!$this->logPriorityToString($priority)) { |
---|
| 610 | $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line); |
---|
[1] | 611 | $priority = LOG_EMERG; |
---|
| 612 | } |
---|
[42] | 613 | |
---|
[15] | 614 | // If log file is not specified, don't log to a file. |
---|
[136] | 615 | if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) { |
---|
| 616 | $this->setParam(array('log_file_priority' => false)); |
---|
| 617 | // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop. |
---|
| 618 | trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE); |
---|
[1] | 619 | } |
---|
[452] | 620 | |
---|
[390] | 621 | // Before we get any further, let's see if ANY log events are configured to be reported. |
---|
| 622 | if ((false === $this->getParam('log_file_priority') || $priority > $this->getParam('log_file_priority')) |
---|
| 623 | && (false === $this->getParam('log_email_priority') || $priority > $this->getParam('log_email_priority')) |
---|
| 624 | && (false === $this->getParam('log_sms_priority') || $priority > $this->getParam('log_sms_priority')) |
---|
| 625 | && (false === $this->getParam('log_screen_priority') || $priority > $this->getParam('log_screen_priority'))) { |
---|
| 626 | // This event would not be recorded, skip it entirely. |
---|
| 627 | return false; |
---|
| 628 | } |
---|
[42] | 629 | |
---|
[44] | 630 | // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>. |
---|
| 631 | preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow); |
---|
| 632 | $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null)); |
---|
| 633 | |
---|
[479] | 634 | // Serialize multi-line messages. |
---|
| 635 | $message = preg_replace('/\s+/m', ' ', $message); |
---|
[477] | 636 | |
---|
[44] | 637 | // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times. |
---|
| 638 | $msg_id = md5($message . $priority . $file . $line); |
---|
[406] | 639 | if ($this->getParam('log_ignore_repeated_events') && isset($previous_events[$msg_id])) { |
---|
[44] | 640 | $previous_events[$msg_id]++; |
---|
| 641 | if ($previous_events[$msg_id] == 2) { |
---|
[136] | 642 | $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line); |
---|
[44] | 643 | } |
---|
| 644 | return false; |
---|
| 645 | } else { |
---|
| 646 | $previous_events[$msg_id] = 1; |
---|
| 647 | } |
---|
[341] | 648 | |
---|
[390] | 649 | // For email and SMS notification types use "lock" files to prevent sending email and SMS notices ad infinitum. |
---|
| 650 | if ((false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) |
---|
| 651 | || (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority'))) { |
---|
| 652 | // This event will generate a "send" notification. Prepare lock file. |
---|
| 653 | $site_hash = md5(empty($_SERVER['SERVER_NAME']) ? $_SERVER['SCRIPT_FILENAME'] : $_SERVER['SERVER_NAME']); |
---|
| 654 | $lock_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/"; |
---|
[452] | 655 | // Just use the file and line for the msg_id to limit the number of possible messages |
---|
[390] | 656 | // (the message string itself shan't be used as it may contain innumerable combinations). |
---|
| 657 | $lock_file = $lock_dir . md5($file . ':' . $line); |
---|
| 658 | if (!is_dir($lock_dir)) { |
---|
| 659 | mkdir($lock_dir); |
---|
| 660 | } |
---|
| 661 | $send_notifications = true; |
---|
| 662 | if (is_file($lock_file)) { |
---|
| 663 | $msg_last_sent = filectime($lock_file); |
---|
| 664 | // Has this message been sent more recently than the timeout? |
---|
| 665 | if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) { |
---|
| 666 | // This message was already sent recently. |
---|
| 667 | $send_notifications = false; |
---|
| 668 | } else { |
---|
| 669 | // Timeout has expired; send notifications again and reset timeout. |
---|
| 670 | touch($lock_file); |
---|
| 671 | } |
---|
[341] | 672 | } else { |
---|
[390] | 673 | touch($lock_file); |
---|
[341] | 674 | } |
---|
| 675 | } |
---|
[452] | 676 | |
---|
[502] | 677 | // Make sure to log in the system's locale. |
---|
| 678 | $locale = setlocale(LC_TIME, 0); |
---|
| 679 | setlocale(LC_TIME, 'C'); |
---|
| 680 | |
---|
[1] | 681 | // Data to be stored for a log event. |
---|
[44] | 682 | $event = array( |
---|
| 683 | 'date' => date('Y-m-d H:i:s'), |
---|
| 684 | 'remote ip' => getRemoteAddr(), |
---|
[414] | 685 | 'pid' => getmypid(), |
---|
[136] | 686 | 'type' => $this->logPriorityToString($priority), |
---|
[44] | 687 | 'file:line' => "$file : $line", |
---|
[475] | 688 | 'url' => mb_substr(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 0, 1024), |
---|
[44] | 689 | 'message' => $message |
---|
| 690 | ); |
---|
[475] | 691 | // Here's a shortened version of event data. |
---|
| 692 | $event_short = $event; |
---|
| 693 | $event_short['url'] = truncate($event_short['url'], 120); |
---|
[42] | 694 | |
---|
[502] | 695 | // Restore original locale. |
---|
| 696 | setlocale(LC_TIME, $locale); |
---|
[475] | 697 | |
---|
[1] | 698 | // FILE ACTION |
---|
[390] | 699 | if (false !== $this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) { |
---|
[475] | 700 | $event_str = '[' . join('] [', $event_short) . ']'; |
---|
[247] | 701 | error_log(mb_substr($event_str, 0, 1024) . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename')); |
---|
[1] | 702 | } |
---|
[42] | 703 | |
---|
[390] | 704 | // EMAIL ACTION |
---|
| 705 | if (false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority') && $send_notifications) { |
---|
[422] | 706 | $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'); |
---|
[502] | 707 | $subject = sprintf('[%s %s] %s', $hostname, $event['type'], mb_substr($event['message'], 0, 64)); |
---|
[422] | 708 | $email_msg = sprintf("A %s log event occurred on %s\n\n", $event['type'], $hostname); |
---|
[390] | 709 | $headers = 'From: ' . $this->getParam('site_email'); |
---|
| 710 | foreach ($event as $k=>$v) { |
---|
| 711 | $email_msg .= sprintf("%-11s%s\n", $k, $v); |
---|
[1] | 712 | } |
---|
[390] | 713 | mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers); |
---|
[1] | 714 | } |
---|
[390] | 715 | |
---|
| 716 | // SMS ACTION |
---|
| 717 | if (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority') && $send_notifications) { |
---|
[422] | 718 | $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'); |
---|
| 719 | $subject = sprintf('[%s %s]', $hostname, $priority); |
---|
[475] | 720 | $sms_msg = sprintf('%s [%s:%s]', mb_substr($event_short['message'], 0, 64), basename($file), $line); |
---|
[390] | 721 | $headers = 'From: ' . $this->getParam('site_email'); |
---|
| 722 | mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers); |
---|
| 723 | } |
---|
[452] | 724 | |
---|
[1] | 725 | // SCREEN ACTION |
---|
[390] | 726 | if (false !== $this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) { |
---|
[468] | 727 | file_put_contents('php://stderr', "[{$event['type']}] [{$event['message']}]\n", FILE_APPEND); |
---|
[1] | 728 | } |
---|
[42] | 729 | |
---|
[390] | 730 | return true; |
---|
[1] | 731 | } |
---|
[42] | 732 | |
---|
[1] | 733 | /** |
---|
| 734 | * Returns the string representation of a LOG_* integer constant. |
---|
| 735 | * |
---|
| 736 | * @param int $priority The LOG_* integer constant. |
---|
| 737 | * |
---|
| 738 | * @return The string representation of $priority. |
---|
| 739 | */ |
---|
[468] | 740 | public function logPriorityToString($priority) { |
---|
[1] | 741 | $priorities = array( |
---|
| 742 | LOG_EMERG => 'emergency', |
---|
| 743 | LOG_ALERT => 'alert', |
---|
| 744 | LOG_CRIT => 'critical', |
---|
| 745 | LOG_ERR => 'error', |
---|
| 746 | LOG_WARNING => 'warning', |
---|
| 747 | LOG_NOTICE => 'notice', |
---|
| 748 | LOG_INFO => 'info', |
---|
| 749 | LOG_DEBUG => 'debug' |
---|
| 750 | ); |
---|
| 751 | if (isset($priorities[$priority])) { |
---|
| 752 | return $priorities[$priority]; |
---|
| 753 | } else { |
---|
| 754 | return false; |
---|
| 755 | } |
---|
| 756 | } |
---|
[42] | 757 | |
---|
[1] | 758 | /** |
---|
[334] | 759 | * Forcefully set a query argument even if one currently exists in the request. |
---|
[136] | 760 | * Values in the _carry_queries array will be copied to URLs (via $app->url()) and |
---|
[20] | 761 | * to hidden input values (via printHiddenSession()). |
---|
| 762 | * |
---|
| 763 | * @access public |
---|
[282] | 764 | * @param mixed $query_key The key (or keys, as an array) of the query argument to save. |
---|
| 765 | * @param mixed $val The new value of the argument key. |
---|
| 766 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 767 | * @since 13 Oct 2007 11:34:51 |
---|
| 768 | */ |
---|
[468] | 769 | public function setQuery($query_key, $val) |
---|
[282] | 770 | { |
---|
| 771 | if (!is_array($query_key)) { |
---|
| 772 | $query_key = array($query_key); |
---|
| 773 | } |
---|
| 774 | foreach ($query_key as $k) { |
---|
| 775 | // Set the value of the specified query argument into the _carry_queries array. |
---|
| 776 | $this->_carry_queries[$k] = $val; |
---|
| 777 | } |
---|
| 778 | } |
---|
| 779 | |
---|
| 780 | /** |
---|
| 781 | * Specify which query arguments will be carried persistently between requests. |
---|
| 782 | * Values in the _carry_queries array will be copied to URLs (via $app->url()) and |
---|
| 783 | * to hidden input values (via printHiddenSession()). |
---|
| 784 | * |
---|
| 785 | * @access public |
---|
[259] | 786 | * @param mixed $query_key The key (or keys, as an array) of the query argument to save. |
---|
[170] | 787 | * @param mixed $default If the key is not available, set to this default value. |
---|
[20] | 788 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 789 | * @since 14 Nov 2005 19:24:52 |
---|
| 790 | */ |
---|
[468] | 791 | public function carryQuery($query_key, $default=false) |
---|
[20] | 792 | { |
---|
[259] | 793 | if (!is_array($query_key)) { |
---|
| 794 | $query_key = array($query_key); |
---|
[20] | 795 | } |
---|
[259] | 796 | foreach ($query_key as $k) { |
---|
| 797 | // If not already set, and there is a non-empty value provided in the request... |
---|
| 798 | if (!isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) { |
---|
| 799 | // Copy the value of the specified query argument into the _carry_queries array. |
---|
| 800 | $this->_carry_queries[$k] = getFormData($k, $default); |
---|
[331] | 801 | $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__); |
---|
[259] | 802 | } |
---|
| 803 | } |
---|
[20] | 804 | } |
---|
[42] | 805 | |
---|
[20] | 806 | /** |
---|
[452] | 807 | * dropQuery() is the opposite of carryQuery(). The specified value will not appear in |
---|
[259] | 808 | * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in. |
---|
[452] | 809 | * |
---|
[259] | 810 | * @access public |
---|
| 811 | * @param mixed $query_key The key (or keys, as an array) of the query argument to remove. |
---|
[407] | 812 | * @param bool $unset Remove any values set in the request matching the given $query_key. |
---|
[259] | 813 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 814 | * @since 18 Jun 2007 20:57:29 |
---|
| 815 | */ |
---|
[468] | 816 | public function dropQuery($query_key, $unset=false) |
---|
[259] | 817 | { |
---|
| 818 | if (!is_array($query_key)) { |
---|
| 819 | $query_key = array($query_key); |
---|
| 820 | } |
---|
| 821 | foreach ($query_key as $k) { |
---|
[478] | 822 | if (array_key_exists($k, $this->_carry_queries)) { |
---|
[259] | 823 | // Remove the value of the specified query argument from the _carry_queries array. |
---|
[325] | 824 | $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__); |
---|
[260] | 825 | unset($this->_carry_queries[$k]); |
---|
[259] | 826 | } |
---|
[480] | 827 | if ($unset && (isset($_REQUEST) && array_key_exists($k, $_REQUEST))) { |
---|
[325] | 828 | unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]); |
---|
| 829 | } |
---|
[259] | 830 | } |
---|
| 831 | } |
---|
| 832 | |
---|
| 833 | /** |
---|
[1] | 834 | * Outputs a fully qualified URL with a query of all the used (ie: not empty) |
---|
[42] | 835 | * keys and values, including optional queries. This allows mindless retention |
---|
[32] | 836 | * of query arguments across page requests. If cookies are not |
---|
[325] | 837 | * used, the session id will be propagated in the URL. |
---|
[1] | 838 | * |
---|
[32] | 839 | * @param string $url The initial url |
---|
| 840 | * @param mixed $carry_args Additional url arguments to carry in the query, |
---|
| 841 | * or FALSE to prevent carrying queries. Can be any of the following formats: |
---|
| 842 | * array('key1', key2', key3') <-- to save these keys if in the form data. |
---|
| 843 | * array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. |
---|
| 844 | * false <-- To not carry any queries. If URL already has queries those will be retained. |
---|
[1] | 845 | * |
---|
| 846 | * @param mixed $always_include_sid Always add the session id, even if using_trans_sid = true. This is required when |
---|
| 847 | * URL starts with http, since PHP using_trans_sid doesn't do those and also for |
---|
| 848 | * header('Location...') redirections. |
---|
| 849 | * |
---|
[502] | 850 | * @param bool $include_csrf_token Set to true to include the csrf_token in the form. Only use this for forms with action="post" to prevent the token from being revealed in the URL. |
---|
[1] | 851 | * @return string url with attached queries and, if not using cookies, the session id |
---|
| 852 | */ |
---|
[502] | 853 | public function url($url, $carry_args=null, $always_include_sid=false, $include_csrf_token=false) |
---|
[1] | 854 | { |
---|
[136] | 855 | if (!$this->running) { |
---|
| 856 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 857 | return false; |
---|
| 858 | } |
---|
[42] | 859 | |
---|
[502] | 860 | if ($this->getParam('csrf_token_enabled') && $include_csrf_token) { |
---|
| 861 | // Include the csrf_token as a carried query argument. |
---|
| 862 | // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken() |
---|
| 863 | $carry_args = is_array($carry_args) ? $carry_args : array(); |
---|
| 864 | $carry_args = array_merge($carry_args, array($this->getParam('csrf_token_name') => $this->getCSRFToken())); |
---|
| 865 | } |
---|
| 866 | |
---|
[20] | 867 | // Get any provided query arguments to include in the final URL. |
---|
| 868 | // If FALSE is a provided here, DO NOT carry the queries. |
---|
[1] | 869 | $do_carry_queries = true; |
---|
| 870 | $one_time_carry_queries = array(); |
---|
| 871 | if (!is_null($carry_args)) { |
---|
| 872 | if (is_array($carry_args) && !empty($carry_args)) { |
---|
| 873 | foreach ($carry_args as $key=>$arg) { |
---|
| 874 | // Get query from appropriate source. |
---|
| 875 | if (false === $arg) { |
---|
| 876 | $do_carry_queries = false; |
---|
| 877 | } else if (false !== getFormData($arg, false)) { |
---|
| 878 | $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available. |
---|
| 879 | } else if (!is_numeric($key) && '' != $arg) { |
---|
| 880 | $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data). |
---|
| 881 | } |
---|
| 882 | } |
---|
| 883 | } else if (false !== getFormData($carry_args, false)) { |
---|
| 884 | $one_time_carry_queries[$carry_args] = getFormData($carry_args); |
---|
| 885 | } else if (false === $carry_args) { |
---|
| 886 | $do_carry_queries = false; |
---|
| 887 | } |
---|
| 888 | } |
---|
[42] | 889 | |
---|
[1] | 890 | // Get the first delimiter that is needed in the url. |
---|
[247] | 891 | $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?'; |
---|
[32] | 892 | |
---|
[1] | 893 | $q = ''; |
---|
| 894 | if ($do_carry_queries) { |
---|
[20] | 895 | // Join the global _carry_queries and local one_time_carry_queries. |
---|
[136] | 896 | $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries)); |
---|
[1] | 897 | foreach ($query_args as $key=>$val) { |
---|
| 898 | // Check value is set and value does not already exist in the url. |
---|
| 899 | if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) { |
---|
| 900 | $q .= $delim . $key . '=' . $val; |
---|
| 901 | $delim = ini_get('arg_separator.output'); |
---|
| 902 | } |
---|
| 903 | } |
---|
| 904 | } |
---|
[42] | 905 | |
---|
[1] | 906 | // Include the necessary SID if the following is true: |
---|
| 907 | // - no cookie in http request OR cookies disabled in App |
---|
| 908 | // - sessions are enabled |
---|
| 909 | // - the link stays on our site |
---|
[334] | 910 | // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here) |
---|
[42] | 911 | // OR |
---|
[1] | 912 | // - 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) |
---|
| 913 | // AND |
---|
| 914 | // - the SID is not already in the query. |
---|
| 915 | if ( |
---|
| 916 | ( |
---|
| 917 | ( |
---|
| 918 | ( |
---|
[42] | 919 | !isset($_COOKIE[session_name()]) |
---|
[136] | 920 | || !$this->getParam('session_use_cookies') |
---|
[42] | 921 | ) |
---|
[242] | 922 | && $this->getParam('session_use_trans_sid') |
---|
[136] | 923 | && $this->getParam('enable_session') |
---|
[42] | 924 | && isMyDomain($url) |
---|
[242] | 925 | && ( |
---|
[20] | 926 | !ini_get('session.use_trans_sid') |
---|
[1] | 927 | || preg_match('!^(http|https)://!i', $url) |
---|
| 928 | ) |
---|
[42] | 929 | ) |
---|
[1] | 930 | || $always_include_sid |
---|
| 931 | ) |
---|
| 932 | && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url) |
---|
| 933 | ) { |
---|
| 934 | $url .= $q . $delim . session_name() . '=' . session_id(); |
---|
| 935 | } else { |
---|
| 936 | $url .= $q; |
---|
| 937 | } |
---|
[492] | 938 | |
---|
| 939 | return $url; |
---|
[1] | 940 | } |
---|
[32] | 941 | |
---|
| 942 | /** |
---|
[136] | 943 | * Returns a HTML-friendly URL processed with $app->url and & replaced with & |
---|
[32] | 944 | * |
---|
| 945 | * @access public |
---|
[502] | 946 | * @param (see param reference for url() method) |
---|
| 947 | * @return string URL passed through $app->url() with ampersamds transformed to $amp; |
---|
[32] | 948 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 949 | * @since 09 Dec 2005 17:58:45 |
---|
| 950 | */ |
---|
[502] | 951 | public function oHREF($url, $carry_args=null, $always_include_sid=false, $include_csrf_token=false) |
---|
[32] | 952 | { |
---|
[502] | 953 | // Process the URL. |
---|
| 954 | $url = $this->url($url, $carry_args, $always_include_sid, $include_csrf_token); |
---|
[42] | 955 | |
---|
[502] | 956 | // Replace any & not followed by an html or unicode entity with its & equivalent. |
---|
[32] | 957 | $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&', $url); |
---|
[42] | 958 | |
---|
[32] | 959 | return $url; |
---|
| 960 | } |
---|
[42] | 961 | |
---|
[1] | 962 | /** |
---|
| 963 | * Prints a hidden form element with the PHPSESSID when cookies are not used, as well |
---|
[42] | 964 | * as hidden form elements for GET_VARS that might be in use. |
---|
[1] | 965 | * |
---|
| 966 | * @param mixed $carry_args Additional url arguments to carry in the query, |
---|
| 967 | * or FALSE to prevent carrying queries. Can be any of the following formats: |
---|
[32] | 968 | * array('key1', key2', key3') <-- to save these keys if in the form data. |
---|
| 969 | * array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. |
---|
| 970 | * false <-- To not carry any queries. If URL already has queries those will be retained. |
---|
[500] | 971 | * @param bool $include_csrf_token Set to true to include the csrf_token in the form. Only use this for forms with action="post" to prevent the token from being revealed in the URL. |
---|
[1] | 972 | */ |
---|
[500] | 973 | public function printHiddenSession($carry_args=null, $include_csrf_token=false) |
---|
[32] | 974 | { |
---|
[136] | 975 | if (!$this->running) { |
---|
| 976 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 977 | return false; |
---|
| 978 | } |
---|
[42] | 979 | |
---|
[20] | 980 | // Get any provided query arguments to include in the final hidden form data. |
---|
| 981 | // If FALSE is a provided here, DO NOT carry the queries. |
---|
[1] | 982 | $do_carry_queries = true; |
---|
| 983 | $one_time_carry_queries = array(); |
---|
| 984 | if (!is_null($carry_args)) { |
---|
| 985 | if (is_array($carry_args) && !empty($carry_args)) { |
---|
| 986 | foreach ($carry_args as $key=>$arg) { |
---|
| 987 | // Get query from appropriate source. |
---|
| 988 | if (false === $arg) { |
---|
| 989 | $do_carry_queries = false; |
---|
| 990 | } else if (false !== getFormData($arg, false)) { |
---|
| 991 | $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available. |
---|
| 992 | } else if (!is_numeric($key) && '' != $arg) { |
---|
| 993 | $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data). |
---|
| 994 | } |
---|
| 995 | } |
---|
| 996 | } else if (false !== getFormData($carry_args, false)) { |
---|
| 997 | $one_time_carry_queries[$carry_args] = getFormData($carry_args); |
---|
| 998 | } else if (false === $carry_args) { |
---|
| 999 | $do_carry_queries = false; |
---|
| 1000 | } |
---|
| 1001 | } |
---|
[42] | 1002 | |
---|
[313] | 1003 | // For each existing request value, we create a hidden input to carry it through a form. |
---|
[1] | 1004 | if ($do_carry_queries) { |
---|
[20] | 1005 | // Join the global _carry_queries and local one_time_carry_queries. |
---|
| 1006 | // urlencode is not used here, not for form data! |
---|
[136] | 1007 | $query_args = array_merge($this->_carry_queries, $one_time_carry_queries); |
---|
[453] | 1008 | foreach ($query_args as $key => $val) { |
---|
| 1009 | if (is_array($val)) { |
---|
| 1010 | foreach ($val as $subval) { |
---|
| 1011 | printf('<input type="hidden" name="%s[]" value="%s" />', $key, $subval); |
---|
| 1012 | } |
---|
| 1013 | } else { |
---|
| 1014 | printf('<input type="hidden" name="%s" value="%s" />', $key, $val); |
---|
| 1015 | } |
---|
[1] | 1016 | } |
---|
[453] | 1017 | unset($query_args, $key, $val, $subval); |
---|
[1] | 1018 | } |
---|
[42] | 1019 | |
---|
[1] | 1020 | // Include the SID if cookies are disabled. |
---|
[20] | 1021 | if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) { |
---|
[136] | 1022 | printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id()); |
---|
[1] | 1023 | } |
---|
[500] | 1024 | |
---|
| 1025 | // Include the csrf_token in the form. |
---|
| 1026 | // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken() |
---|
| 1027 | if ($this->getParam('csrf_token_enabled') && $include_csrf_token) { |
---|
[501] | 1028 | printf('<input type="hidden" name="%s" value="%s" />', $this->getParam('csrf_token_name'), $this->getCSRFToken()); |
---|
[500] | 1029 | } |
---|
[1] | 1030 | } |
---|
[42] | 1031 | |
---|
[500] | 1032 | /* |
---|
| 1033 | * Return a URL with a version number attached. This is useful for overriding network caches ("cache buster") for sourced media, e.g., /style.css?812763482 |
---|
| 1034 | * |
---|
| 1035 | * @access public |
---|
| 1036 | * @param string $url URL to media (e.g., /foo.js) |
---|
| 1037 | * @return string URL with cache-busting version appended (/foo.js?v=1234567890) |
---|
| 1038 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 1039 | * @version 1.0 |
---|
| 1040 | * @since 03 Sep 2014 22:40:24 |
---|
| 1041 | */ |
---|
| 1042 | public function cacheBustURL($url) |
---|
| 1043 | { |
---|
| 1044 | // Get the first delimiter that is needed in the url. |
---|
| 1045 | $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?'; |
---|
| 1046 | $v = crc32($this->getParam('codebase_version') . '|' . $this->getParam('site_version')); |
---|
| 1047 | return sprintf('%s%sv=%s', $url, $delim, $v); |
---|
| 1048 | } |
---|
| 1049 | |
---|
| 1050 | /* |
---|
[501] | 1051 | * Generate a csrf_token if it doesn't exist or is expired, save it to the session and return its value. |
---|
| 1052 | * Otherwise just return the current token. |
---|
| 1053 | * Details on the synchronizer token pattern: |
---|
[500] | 1054 | * https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern |
---|
| 1055 | * |
---|
| 1056 | * @access public |
---|
[501] | 1057 | * @return string The new or current csrf_token |
---|
[500] | 1058 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 1059 | * @version 1.0 |
---|
| 1060 | * @since 15 Nov 2014 17:57:17 |
---|
| 1061 | */ |
---|
[501] | 1062 | public function getCSRFToken() |
---|
[500] | 1063 | { |
---|
[501] | 1064 | if (!isset($_SESSION['_app'][$this->_ns]['csrf_token']) || (removeSignature($_SESSION['_app'][$this->_ns]['csrf_token']) + $this->getParam('csrf_token_timeout') < time())) { |
---|
| 1065 | // No token, or token is expired; generate one and return it. |
---|
| 1066 | return $_SESSION['_app'][$this->_ns]['csrf_token'] = addSignature(time(), null, 64); |
---|
[500] | 1067 | } |
---|
| 1068 | // Current token is not expired; return it. |
---|
[501] | 1069 | return $_SESSION['_app'][$this->_ns]['csrf_token']; |
---|
[500] | 1070 | } |
---|
| 1071 | |
---|
| 1072 | /* |
---|
| 1073 | * Compares the given csrf_token with the current or previous one saved in the session. |
---|
| 1074 | * |
---|
| 1075 | * @access public |
---|
| 1076 | * @param string $csrf_token The token to compare with the session token. |
---|
| 1077 | * @return bool True if the tokens match, false otherwise. |
---|
| 1078 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 1079 | * @version 1.0 |
---|
| 1080 | * @since 15 Nov 2014 18:06:55 |
---|
| 1081 | */ |
---|
[501] | 1082 | public function verifyCSRFToken($user_submitted_csrf_token) |
---|
[500] | 1083 | { |
---|
| 1084 | |
---|
| 1085 | if (!$this->getParam('csrf_token_enabled')) { |
---|
[501] | 1086 | $this->logMsg(sprintf('%s method called, but csrf_token_enabled=false', __FUNCTION__), LOG_ERR, __FILE__, __LINE__); |
---|
| 1087 | return true; |
---|
[500] | 1088 | } |
---|
[501] | 1089 | if ('' == trim($user_submitted_csrf_token)) { |
---|
| 1090 | $this->logMsg(sprintf('Empty string failed CSRF verification.', null), LOG_NOTICE, __FILE__, __LINE__); |
---|
[500] | 1091 | return false; |
---|
| 1092 | } |
---|
[501] | 1093 | if (!verifySignature($user_submitted_csrf_token, null, 64)) { |
---|
| 1094 | $this->logMsg(sprintf('Input failed CSRF verification (invalid signature in %s).', $user_submitted_csrf_token), LOG_WARNING, __FILE__, __LINE__); |
---|
[500] | 1095 | return false; |
---|
| 1096 | } |
---|
[501] | 1097 | $csrf_token = $this->getCSRFToken(); |
---|
| 1098 | if ($user_submitted_csrf_token != $csrf_token) { |
---|
| 1099 | $this->logMsg(sprintf('Input failed CSRF verification (%s not in %s).', $user_submitted_csrf_token, $csrf_token), LOG_WARNING, __FILE__, __LINE__); |
---|
[500] | 1100 | return false; |
---|
| 1101 | } |
---|
[502] | 1102 | $this->logMsg(sprintf('Verified CSRF token %s', $user_submitted_csrf_token), LOG_DEBUG, __FILE__, __LINE__); |
---|
[500] | 1103 | return true; |
---|
| 1104 | } |
---|
| 1105 | |
---|
| 1106 | /* |
---|
| 1107 | * Bounce user if they submit a token that doesn't match the one saved in the session. |
---|
| 1108 | * Because this function calls dieURL() it must be called before any other HTTP header output. |
---|
| 1109 | * |
---|
| 1110 | * @access public |
---|
[501] | 1111 | * @param string $user_submitted_csrf_token The user-submitted token to compare with the session token. |
---|
[500] | 1112 | * @param string $message Optional message to display to the user (otherwise default message will display). Set to an empty string to display no message. |
---|
| 1113 | * @param int $type The type of message: MSG_NOTICE, |
---|
| 1114 | * MSG_SUCCESS, MSG_WARNING, or MSG_ERR. |
---|
| 1115 | * @param string $file __FILE__. |
---|
| 1116 | * @param string $line __LINE__. |
---|
| 1117 | * @return void |
---|
| 1118 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 1119 | * @version 1.0 |
---|
| 1120 | * @since 15 Nov 2014 18:10:17 |
---|
| 1121 | */ |
---|
[501] | 1122 | public function requireValidCSRFToken($message=null, $type=MSG_NOTICE, $file=null, $line=null) |
---|
[500] | 1123 | { |
---|
[501] | 1124 | if (!$this->verifyCSRFToken(getFormData($this->getParam('csrf_token_name')))) { |
---|
| 1125 | $message = isset($message) ? $message : _("Sorry, the form token expired. Please try again."); |
---|
| 1126 | $this->raiseMsg($message, $type, $file, $line); |
---|
| 1127 | $this->dieBoomerangURL(); |
---|
[500] | 1128 | } |
---|
| 1129 | } |
---|
| 1130 | |
---|
[1] | 1131 | /** |
---|
| 1132 | * Uses an http header to redirect the client to the given $url. If sessions are not used |
---|
| 1133 | * and the session is not already defined in the given $url, the SID is appended as a URI query. |
---|
| 1134 | * As with all header generating functions, make sure this is called before any other output. |
---|
| 1135 | * |
---|
| 1136 | * @param string $url The URL the client will be redirected to. |
---|
| 1137 | * @param mixed $carry_args Additional url arguments to carry in the query, |
---|
| 1138 | * or FALSE to prevent carrying queries. Can be any of the following formats: |
---|
| 1139 | * -array('key1', key2', key3') <-- to save these keys if in the form data. |
---|
[136] | 1140 | * -array('key1' => 'value', key2' => 'value') <-- to set keys to default values if not present in form data. |
---|
[1] | 1141 | * -false <-- To not carry any queries. If URL already has queries those will be retained. |
---|
| 1142 | * @param bool $always_include_sid Force session id to be added to Location header. |
---|
| 1143 | */ |
---|
[468] | 1144 | public function dieURL($url, $carry_args=null, $always_include_sid=false) |
---|
[1] | 1145 | { |
---|
[136] | 1146 | if (!$this->running) { |
---|
| 1147 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1148 | return false; |
---|
| 1149 | } |
---|
[42] | 1150 | |
---|
[502] | 1151 | if (!$url) { |
---|
[1] | 1152 | // If URL is not specified, use the redirect_home_url. |
---|
[136] | 1153 | $url = $this->getParam('redirect_home_url'); |
---|
[1] | 1154 | } |
---|
[42] | 1155 | |
---|
[1] | 1156 | if (preg_match('!^/!', $url)) { |
---|
| 1157 | // If relative URL is given, prepend correct local hostname. |
---|
[22] | 1158 | $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http'; |
---|
| 1159 | $host = getenv('HTTP_HOST'); |
---|
| 1160 | $url = sprintf('%s://%s%s', $scheme, $host, $url); |
---|
[1] | 1161 | } |
---|
[22] | 1162 | |
---|
[136] | 1163 | $url = $this->url($url, $carry_args, $always_include_sid); |
---|
[42] | 1164 | |
---|
[202] | 1165 | // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP? |
---|
[1] | 1166 | header(sprintf('Location: %s', $url)); |
---|
[136] | 1167 | $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[42] | 1168 | |
---|
[202] | 1169 | // End application. |
---|
[1] | 1170 | // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close |
---|
[136] | 1171 | $this->stop(); |
---|
[1] | 1172 | die; |
---|
| 1173 | } |
---|
[42] | 1174 | |
---|
[84] | 1175 | /* |
---|
[136] | 1176 | * Redirects a user by calling $app->dieURL(). It will use: |
---|
[84] | 1177 | * 1. the stored boomerang URL, it it exists |
---|
| 1178 | * 2. a specified $default_url, it it exists |
---|
| 1179 | * 3. the referring URL, it it exists. |
---|
| 1180 | * 4. redirect_home_url configuration variable. |
---|
| 1181 | * |
---|
| 1182 | * @access public |
---|
| 1183 | * @param string $id Identifier for this script. |
---|
[136] | 1184 | * @param mixed $carry_args Additional arguments to carry in the URL automatically (see $app->oHREF()). |
---|
[84] | 1185 | * @param string $default_url A default URL if there is not a valid specified boomerang URL. |
---|
[159] | 1186 | * @param bool $queryless_referrer_comparison Exclude the URL query from the refererIsMe() comparison. |
---|
[84] | 1187 | * @return bool False if the session is not running. No return otherwise. |
---|
| 1188 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 1189 | * @since 31 Mar 2006 19:17:00 |
---|
| 1190 | */ |
---|
[468] | 1191 | public function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false) |
---|
[1] | 1192 | { |
---|
[136] | 1193 | if (!$this->running) { |
---|
| 1194 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1195 | return false; |
---|
| 1196 | } |
---|
[42] | 1197 | |
---|
[1] | 1198 | // Get URL from stored boomerang. Allow non specific URL if ID not valid. |
---|
[136] | 1199 | if ($this->validBoomerangURL($id, true)) { |
---|
[154] | 1200 | if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { |
---|
| 1201 | $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]; |
---|
[136] | 1202 | $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1203 | } else { |
---|
[154] | 1204 | $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']); |
---|
[136] | 1205 | $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1206 | } |
---|
[22] | 1207 | // Delete stored boomerang. |
---|
[136] | 1208 | $this->deleteBoomerangURL($id); |
---|
[84] | 1209 | } else if (isset($default_url)) { |
---|
| 1210 | $url = $default_url; |
---|
[159] | 1211 | } else if (!refererIsMe(true === $queryless_referrer_comparison)) { |
---|
[1] | 1212 | // Ensure that the redirecting page is not also the referrer. |
---|
| 1213 | $url = getenv('HTTP_REFERER'); |
---|
[136] | 1214 | $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1215 | } else { |
---|
[22] | 1216 | // If URL is not specified, use the redirect_home_url. |
---|
[136] | 1217 | $url = $this->getParam('redirect_home_url'); |
---|
[203] | 1218 | $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1219 | } |
---|
[42] | 1220 | |
---|
[84] | 1221 | // A redirection will never happen immediately twice. |
---|
[1] | 1222 | // Set the time so ensure this doesn't happen. |
---|
[154] | 1223 | $_SESSION['_app'][$this->_ns]['boomerang']['time'] = time(); |
---|
[136] | 1224 | $this->dieURL($url, $carry_args); |
---|
[1] | 1225 | } |
---|
[42] | 1226 | |
---|
[1] | 1227 | /** |
---|
[136] | 1228 | * Set the URL to return to when $app->dieBoomerangURL() is called. |
---|
[1] | 1229 | * |
---|
| 1230 | * @param string $url A fully validated URL. |
---|
| 1231 | * @param bool $id An identification tag for this url. |
---|
| 1232 | * FIXME: url garbage collection? |
---|
| 1233 | */ |
---|
[468] | 1234 | public function setBoomerangURL($url=null, $id=null) |
---|
[1] | 1235 | { |
---|
[136] | 1236 | if (!$this->running) { |
---|
| 1237 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1238 | return false; |
---|
| 1239 | } |
---|
[84] | 1240 | // A redirection will never happen immediately after setting the boomerangURL. |
---|
[136] | 1241 | // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more. |
---|
[42] | 1242 | |
---|
[22] | 1243 | if ('' != $url && is_string($url)) { |
---|
[242] | 1244 | // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion). |
---|
| 1245 | $url = preg_replace(array('/([&?])boomerang=\w+[&?]?/', '/[&?]$/'), array('$1', ''), $url); |
---|
[42] | 1246 | |
---|
[154] | 1247 | if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']['url']) && !empty($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { |
---|
[1] | 1248 | // If the URL currently exists in the boomerang array, delete. |
---|
[154] | 1249 | while ($existing_key = array_search($url, $_SESSION['_app'][$this->_ns]['boomerang']['url'])) { |
---|
| 1250 | unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$existing_key]); |
---|
[1] | 1251 | } |
---|
| 1252 | } |
---|
[42] | 1253 | |
---|
[1] | 1254 | if (isset($id)) { |
---|
[154] | 1255 | $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id] = $url; |
---|
[1] | 1256 | } else { |
---|
[154] | 1257 | $_SESSION['_app'][$this->_ns]['boomerang']['url'][] = $url; |
---|
[1] | 1258 | } |
---|
[136] | 1259 | $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1260 | return true; |
---|
| 1261 | } else { |
---|
[136] | 1262 | $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1263 | return false; |
---|
| 1264 | } |
---|
| 1265 | } |
---|
[42] | 1266 | |
---|
[1] | 1267 | /** |
---|
[333] | 1268 | * Return the URL set for the specified $id, or an empty string if one isn't set. |
---|
[1] | 1269 | * |
---|
| 1270 | * @param string $id An identification tag for this url. |
---|
| 1271 | */ |
---|
[468] | 1272 | public function getBoomerangURL($id=null) |
---|
[1] | 1273 | { |
---|
[136] | 1274 | if (!$this->running) { |
---|
| 1275 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1276 | return false; |
---|
| 1277 | } |
---|
[42] | 1278 | |
---|
[1] | 1279 | if (isset($id)) { |
---|
[154] | 1280 | if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { |
---|
| 1281 | return $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]; |
---|
[1] | 1282 | } else { |
---|
| 1283 | return ''; |
---|
| 1284 | } |
---|
[154] | 1285 | } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { |
---|
| 1286 | return end($_SESSION['_app'][$this->_ns]['boomerang']['url']); |
---|
[1] | 1287 | } else { |
---|
| 1288 | return false; |
---|
| 1289 | } |
---|
| 1290 | } |
---|
[42] | 1291 | |
---|
[1] | 1292 | /** |
---|
| 1293 | * Delete the URL set for the specified $id. |
---|
| 1294 | * |
---|
| 1295 | * @param string $id An identification tag for this url. |
---|
| 1296 | */ |
---|
[468] | 1297 | public function deleteBoomerangURL($id=null) |
---|
[1] | 1298 | { |
---|
[136] | 1299 | if (!$this->running) { |
---|
| 1300 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1301 | return false; |
---|
| 1302 | } |
---|
[42] | 1303 | |
---|
[154] | 1304 | if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { |
---|
[502] | 1305 | $url = $this->getBoomerangURL($id); |
---|
[154] | 1306 | unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]); |
---|
| 1307 | } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { |
---|
[502] | 1308 | $url = array_pop($_SESSION['_app'][$this->_ns]['boomerang']['url']); |
---|
[1] | 1309 | } |
---|
[502] | 1310 | $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1311 | } |
---|
[42] | 1312 | |
---|
[1] | 1313 | /** |
---|
[103] | 1314 | * Check if a valid boomerang URL value has been set. A boomerang URL is considered |
---|
| 1315 | * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds. |
---|
[1] | 1316 | * |
---|
[103] | 1317 | * @return bool True if it is set and valid, false otherwise. |
---|
[1] | 1318 | */ |
---|
[468] | 1319 | public function validBoomerangURL($id=null, $use_nonspecificboomerang=false) |
---|
[1] | 1320 | { |
---|
[136] | 1321 | if (!$this->running) { |
---|
| 1322 | $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1323 | return false; |
---|
| 1324 | } |
---|
[42] | 1325 | |
---|
[154] | 1326 | if (!isset($_SESSION['_app'][$this->_ns]['boomerang']['url'])) { |
---|
[136] | 1327 | $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1328 | return false; |
---|
| 1329 | } |
---|
[42] | 1330 | |
---|
[334] | 1331 | // Time is the time stamp of a boomerangURL redirection, or setting of a boomerangURL. |
---|
[1] | 1332 | // a boomerang redirection will always occur at least several seconds after the last boomerang redirect |
---|
| 1333 | // or a boomerang being set. |
---|
[154] | 1334 | $boomerang_time = isset($_SESSION['_app'][$this->_ns]['boomerang']['time']) ? $_SESSION['_app'][$this->_ns]['boomerang']['time'] : 0; |
---|
[42] | 1335 | |
---|
[22] | 1336 | $url = ''; |
---|
[154] | 1337 | if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) { |
---|
| 1338 | $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]; |
---|
[1] | 1339 | } else if (!isset($id) || $use_nonspecificboomerang) { |
---|
| 1340 | // Use non specific boomerang if available. |
---|
[154] | 1341 | $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']); |
---|
[1] | 1342 | } |
---|
[42] | 1343 | |
---|
[136] | 1344 | $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[22] | 1345 | |
---|
| 1346 | if ('' == $url) { |
---|
[136] | 1347 | $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1348 | return false; |
---|
| 1349 | } |
---|
| 1350 | if ($url == absoluteMe()) { |
---|
| 1351 | // The URL we are directing to is the current page. |
---|
[136] | 1352 | $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1353 | return false; |
---|
| 1354 | } |
---|
| 1355 | if ($boomerang_time >= (time() - 2)) { |
---|
[159] | 1356 | // Last boomerang direction was less than 2 seconds ago. |
---|
| 1357 | $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s seconds', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1358 | return false; |
---|
| 1359 | } |
---|
[42] | 1360 | |
---|
[136] | 1361 | $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 1362 | return true; |
---|
| 1363 | } |
---|
| 1364 | |
---|
| 1365 | /** |
---|
| 1366 | * Force the user to connect via https (port 443) by redirecting them to |
---|
| 1367 | * the same page but with https. |
---|
| 1368 | */ |
---|
[468] | 1369 | public function sslOn() |
---|
[1] | 1370 | { |
---|
[38] | 1371 | if (function_exists('apache_get_modules')) { |
---|
[42] | 1372 | $modules = apache_get_modules(); |
---|
[38] | 1373 | } else { |
---|
| 1374 | // It's safe to assume we have mod_ssl if we can't determine otherwise. |
---|
| 1375 | $modules = array('mod_ssl'); |
---|
| 1376 | } |
---|
[42] | 1377 | |
---|
[136] | 1378 | if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) { |
---|
| 1379 | $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 1380 | // Always append session because some browsers do not send cookie when crossing to SSL URL. |
---|
[136] | 1381 | $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true); |
---|
[1] | 1382 | } |
---|
| 1383 | } |
---|
[42] | 1384 | |
---|
[1] | 1385 | /** |
---|
| 1386 | * to enforce the user to connect via http (port 80) by redirecting them to |
---|
| 1387 | * a http version of the current url. |
---|
| 1388 | */ |
---|
[468] | 1389 | public function sslOff() |
---|
[1] | 1390 | { |
---|
[53] | 1391 | if ('' != getenv('HTTPS')) { |
---|
[1] | 1392 | $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true); |
---|
| 1393 | } |
---|
| 1394 | } |
---|
[477] | 1395 | |
---|
[479] | 1396 | /* |
---|
| 1397 | * Sets a cookie, with error checking and some sane defaults. |
---|
| 1398 | * |
---|
| 1399 | * @access public |
---|
| 1400 | * @param string $name The name of the cookie. |
---|
| 1401 | * @param string $value The value of the cookie. |
---|
| 1402 | * @param string $expire The time the cookie expires, as a unix timestamp or string value passed to strtotime. |
---|
[489] | 1403 | * @param string $path The path on the server in which the cookie will be available on. |
---|
| 1404 | * @param string $domain The domain that the cookie is available to. |
---|
[479] | 1405 | * @param bool $secure Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. |
---|
| 1406 | * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol (makes cookies unreadable to javascript). |
---|
| 1407 | * @return bool True on success, false on error. |
---|
| 1408 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 1409 | * @version 1.0 |
---|
| 1410 | * @since 02 May 2014 16:36:34 |
---|
| 1411 | */ |
---|
[489] | 1412 | public function setCookie($name, $value, $expire='+10 years', $path='/', $domain=null, $secure=null, $httponly=null) |
---|
[479] | 1413 | { |
---|
| 1414 | if (!is_scalar($name)) { |
---|
| 1415 | $this->logMsg(sprintf('Cookie name must be scalar, is not: %s', getDump($name)), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 1416 | return false; |
---|
| 1417 | } |
---|
| 1418 | if (!is_scalar($value)) { |
---|
| 1419 | $this->logMsg(sprintf('Cookie "%s" value must be scalar, is not: %s', $name, getDump($value)), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 1420 | return false; |
---|
| 1421 | } |
---|
[477] | 1422 | |
---|
[479] | 1423 | // Defaults. |
---|
| 1424 | $expire = (is_numeric($expire) ? $expire : (is_string($expire) ? strtotime($expire) : $expire)); |
---|
| 1425 | $secure = $secure ?: ('' != getenv('HTTPS') && $this->getParam('ssl_enabled')); |
---|
| 1426 | $httponly = $httponly ?: true; |
---|
[477] | 1427 | |
---|
[479] | 1428 | // Make sure the expiration date is a valid 32bit integer. |
---|
| 1429 | if (is_int($expire) && $expire > 2147483647) { |
---|
| 1430 | $this->logMsg(sprintf('Cookie "%s" expire time exceeds a 32bit integer (%s)', $key, date('r', $expire)), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 1431 | } |
---|
[477] | 1432 | |
---|
[479] | 1433 | // Measure total cookie length and warn if larger than max recommended size of 4093. |
---|
| 1434 | // https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key |
---|
| 1435 | // The date the header name include 51 bytes: Set-Cookie: ; expires=Fri, 03-May-2024 00:04:47 GMT |
---|
| 1436 | $cookielen = strlen($name . $value . $path . $domain . ($secure ? '; secure' : '') . ($httponly ? '; httponly' : '')) + 51; |
---|
| 1437 | if ($cookielen > 4093) { |
---|
| 1438 | $this->logMsg(sprintf('Cookie "%s" has a size greater than 4093 bytes (is %s bytes)', $key, $cookielen), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 1439 | } |
---|
[477] | 1440 | |
---|
[479] | 1441 | // Ensure PHP version allow use of httponly. |
---|
| 1442 | if (version_compare(PHP_VERSION, '5.2.0', '>=')) { |
---|
| 1443 | $ret = setcookie($name, $value, $expire, $path, $domain, $secure, $httponly); |
---|
| 1444 | } else { |
---|
| 1445 | $ret = setcookie($name, $value, $expire, $path, $domain, $secure); |
---|
| 1446 | } |
---|
[477] | 1447 | |
---|
[479] | 1448 | if (false === $ret) { |
---|
| 1449 | $this->logMsg(sprintf('Failed to set cookie (%s=%s) probably due to output before headers.', $name, $value), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 1450 | } |
---|
| 1451 | return $ret; |
---|
| 1452 | } |
---|
[1] | 1453 | } // End. |
---|