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