[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 |
---|
[462] | 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. |
---|
[462] | 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. |
---|
[462] | 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 | /** |
---|
[136] | 24 | * Prefs.inc.php |
---|
[1] | 25 | * |
---|
[478] | 26 | * Prefs provides an API for saving arbitrary values in a user's session, in cookies, and in the database. |
---|
| 27 | * Prefs can be stored into a database with the optional save() and load() methods. |
---|
[136] | 28 | * |
---|
[1] | 29 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
[478] | 30 | * @version 3.0 |
---|
[481] | 31 | * @todo This class could really benefit from being refactored using the factory pattern, with backend storage mechanisms. |
---|
[462] | 32 | * |
---|
[477] | 33 | * Example of use (database storagetype): |
---|
[150] | 34 | --------------------------------------------------------------------- |
---|
[151] | 35 | // Load preferences for the user's session. |
---|
[150] | 36 | require_once 'codebase/lib/Prefs.inc.php'; |
---|
[153] | 37 | $prefs = new Prefs('my-namespace'); |
---|
[150] | 38 | $prefs->setParam(array( |
---|
[477] | 39 | 'storagetype' => ($auth->isLoggedIn() ? 'database' : 'session'), |
---|
[150] | 40 | 'user_id' => $auth->get('user_id'), |
---|
| 41 | )); |
---|
| 42 | $prefs->setDefaults(array( |
---|
| 43 | 'search_num_results' => 25, |
---|
| 44 | 'datalog_num_entries' => 25, |
---|
| 45 | )); |
---|
| 46 | $prefs->load(); |
---|
[151] | 47 | |
---|
| 48 | // Update preferences. Make sure to validate this input first! |
---|
| 49 | $prefs->set('search_num_results', getFormData('search_num_results')); |
---|
| 50 | $prefs->set('datalog_num_entries', getFormData('datalog_num_entries')); |
---|
| 51 | $prefs->save(); |
---|
[150] | 52 | --------------------------------------------------------------------- |
---|
[1] | 53 | */ |
---|
[502] | 54 | class Prefs |
---|
| 55 | { |
---|
[1] | 56 | |
---|
[136] | 57 | // Namespace of this instance of Prefs. |
---|
[484] | 58 | protected $_ns; |
---|
[1] | 59 | |
---|
[152] | 60 | // Configuration parameters for this object. |
---|
[484] | 61 | protected $_params = array( |
---|
[462] | 62 | |
---|
[481] | 63 | // Store preferences in one of the available storage mechanisms: session, cookie, database |
---|
| 64 | // This default should remain set to 'session' for legacy support. |
---|
| 65 | 'storagetype' => 'session', |
---|
| 66 | |
---|
[615] | 67 | // This parameter is only used for legacy support, superseded by the 'storagetype' setting. |
---|
[152] | 68 | // Enable database storage. If this is false, all prefs will live only as long as the session. |
---|
[477] | 69 | 'persistent' => null, |
---|
[462] | 70 | |
---|
[477] | 71 | // ---------------------------------------------------------- |
---|
| 72 | // Cookie-type settings. |
---|
| 73 | |
---|
| 74 | // Lifespan of the cookie. If set to an integer, interpreted as a timestamp (0 for 'when user closes browser'), otherwise as a strtotime-compatible value ('tomorrow', etc). |
---|
| 75 | 'cookie_expire' => '+10 years', |
---|
| 76 | |
---|
| 77 | // The path on the server in which the cookie will be available on. |
---|
| 78 | 'cookie_path' => null, |
---|
| 79 | |
---|
| 80 | // The domain that the cookie is available to. |
---|
| 81 | 'cookie_domain' => null, |
---|
| 82 | |
---|
| 83 | // ---------------------------------------------------------- |
---|
| 84 | // Database-type settings. |
---|
| 85 | |
---|
| 86 | // The current user_id for which to load/save database-backed preferences. |
---|
[149] | 87 | 'user_id' => null, |
---|
[462] | 88 | |
---|
[669] | 89 | // How long before we force a reload of the persistent prefs data? |
---|
| 90 | 'load_timeout' => 60, |
---|
[462] | 91 | |
---|
[481] | 92 | // Name of database table to store prefs. |
---|
[147] | 93 | 'db_table' => 'pref_tbl', |
---|
[146] | 94 | |
---|
| 95 | // Automatically create table and verify columns. Better set to false after site launch. |
---|
[396] | 96 | // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available. |
---|
[146] | 97 | 'create_table' => true, |
---|
[644] | 98 | |
---|
| 99 | // Original namespace set during __construct(). |
---|
| 100 | // 'namespace' => '', |
---|
[146] | 101 | ); |
---|
| 102 | |
---|
[1] | 103 | /** |
---|
| 104 | * Prefs constructor. |
---|
| 105 | */ |
---|
[478] | 106 | public function __construct($namespace='', array $params=null) |
---|
[1] | 107 | { |
---|
[477] | 108 | $app =& App::getInstance(); |
---|
[146] | 109 | |
---|
[154] | 110 | $this->_ns = $namespace; |
---|
[462] | 111 | |
---|
[644] | 112 | // Save the original namespace for the DB pref_namespace column. $this->_ns, used in the SESSION variable, will change based on the user_id. |
---|
| 113 | $this->setParam(array('namespace' => $namespace)); |
---|
| 114 | |
---|
[146] | 115 | // Get create tables config from global context. |
---|
| 116 | if (!is_null($app->getParam('db_create_tables'))) { |
---|
| 117 | $this->setParam(array('create_table' => $app->getParam('db_create_tables'))); |
---|
| 118 | } |
---|
[478] | 119 | |
---|
| 120 | // Optional initial params. |
---|
| 121 | $this->setParam($params); |
---|
| 122 | |
---|
[719] | 123 | if (isset($params['save_on_shutdown']) && $params['save_on_shutdown']) { |
---|
| 124 | // Run Prefs->save() upon script completion if we're using the database storagetype. |
---|
| 125 | // This only works if: |
---|
| 126 | // - 'storagetype' is provided as a parameter to the constructor rather than via setParam() later. |
---|
| 127 | // - $app->stop() is not called at the end of the script (which would close the PDO connection before the shutdown function runs). |
---|
| 128 | if ('database' == $this->getParam('storagetype')) { |
---|
| 129 | register_shutdown_function(array($this, 'save')); |
---|
| 130 | } |
---|
[478] | 131 | } |
---|
[1] | 132 | } |
---|
| 133 | |
---|
| 134 | /** |
---|
[146] | 135 | * Setup the database table for this class. |
---|
| 136 | * |
---|
| 137 | * @access public |
---|
| 138 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 139 | * @since 04 Jun 2006 16:41:42 |
---|
| 140 | */ |
---|
[468] | 141 | public function initDB($recreate_db=false) |
---|
[146] | 142 | { |
---|
[477] | 143 | $app =& App::getInstance(); |
---|
[719] | 144 | $pdo =& \Strangecode\Codebase\PDO::getInstance(); |
---|
[146] | 145 | |
---|
| 146 | static $_db_tested = false; |
---|
| 147 | |
---|
| 148 | if ($recreate_db || !$_db_tested && $this->getParam('create_table')) { |
---|
| 149 | if ($recreate_db) { |
---|
[719] | 150 | $pdo->query(sprintf("DROP TABLE IF EXISTS `%s`", $pdo->sanitizeIdentifier($this->getParam('db_table')))); |
---|
[201] | 151 | $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__); |
---|
[146] | 152 | } |
---|
[719] | 153 | $stmt = $pdo->query(sprintf(" |
---|
| 154 | CREATE TABLE IF NOT EXISTS `%s` ( |
---|
| 155 | `user_id` VARCHAR(32) NOT NULL DEFAULT '', |
---|
| 156 | `pref_namespace` VARCHAR(32) NOT NULL DEFAULT '', |
---|
| 157 | `pref_key` VARCHAR(64) NOT NULL DEFAULT '', |
---|
| 158 | `pref_value` TEXT, |
---|
| 159 | PRIMARY KEY (`user_id`, `pref_namespace`, `pref_key`) |
---|
| 160 | ) |
---|
| 161 | ", $pdo->sanitizeIdentifier($this->getParam('db_table')))); |
---|
[146] | 162 | |
---|
[719] | 163 | if (!$pdo->columnExists($this->getParam('db_table'), array( |
---|
[146] | 164 | 'user_id', |
---|
| 165 | 'pref_namespace', |
---|
| 166 | 'pref_key', |
---|
| 167 | 'pref_value', |
---|
| 168 | ), false, false)) { |
---|
| 169 | $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__); |
---|
| 170 | trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR); |
---|
| 171 | } |
---|
| 172 | } |
---|
| 173 | $_db_tested = true; |
---|
| 174 | } |
---|
| 175 | |
---|
| 176 | /** |
---|
| 177 | * Set the params of this object. |
---|
| 178 | * |
---|
| 179 | * @param array $params Array of param keys and values to set. |
---|
| 180 | */ |
---|
[478] | 181 | public function setParam(array $params=null) |
---|
[146] | 182 | { |
---|
[548] | 183 | $app =& App::getInstance(); |
---|
| 184 | |
---|
[477] | 185 | // CLI scripts can't use prefs stored in HTTP-based protocols. |
---|
[665] | 186 | if ($app->isCLI() |
---|
[477] | 187 | && isset($params['storagetype']) |
---|
| 188 | && in_array($params['storagetype'], array('cookie', 'session'))) { |
---|
[665] | 189 | $app->logMsg(sprintf('Storage type %s not available for CLI', $params['storagetype']), LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 190 | } |
---|
| 191 | |
---|
| 192 | // Convert the legacy param 'persistent' to 'storagetype=database'. |
---|
[481] | 193 | // Old sites would set 'persistent' to true (use database) or false (use sessions). |
---|
| 194 | // If it is true, we set storagetype=database here. |
---|
| 195 | // If false, we rely on the default, sessions (which is assigned in the params). |
---|
[477] | 196 | if (isset($params['persistent']) && $params['persistent'] && !isset($params['storagetype'])) { |
---|
| 197 | $params['storagetype'] = 'database'; |
---|
| 198 | } |
---|
| 199 | |
---|
[644] | 200 | // Append the user_id to the namespace to keep separate collections for different users. |
---|
| 201 | if (isset($params['user_id']) && $params['user_id']) { |
---|
| 202 | // $this->getParam('namespace') should always be available since it is set in __construct(). |
---|
| 203 | $this->_ns = sprintf('%s-%s', $this->getParam('namespace'), $params['user_id']); |
---|
| 204 | } |
---|
| 205 | |
---|
| 206 | // Check max DB string lengths. |
---|
| 207 | if ((isset($params['storagetype']) && $params['storagetype'] == 'database') || $this->getParam('storagetype') == 'database') { |
---|
| 208 | if (isset($params['user_id']) && mb_strlen($params['user_id']) > 32) { |
---|
| 209 | $app->logMsg(sprintf('Prefs user_id param longer than 32 characters: %s', $params['user_id']), LOG_ERR, __FILE__, __LINE__); |
---|
| 210 | } |
---|
| 211 | if (isset($params['namespace']) && mb_strlen($params['namespace']) > 32) { |
---|
| 212 | $app->logMsg(sprintf('Prefs namespace longer than 32 characters: %s', $this->_ns), LOG_ERR, __FILE__, __LINE__); |
---|
| 213 | } |
---|
| 214 | if (isset($params['pref_key']) && mb_strlen($params['pref_key']) > 64) { |
---|
| 215 | $app->logMsg(sprintf('Prefs pref_key param longer than 64 characters: %s', $params['pref_key']), LOG_ERR, __FILE__, __LINE__); |
---|
| 216 | } |
---|
| 217 | } |
---|
| 218 | |
---|
[146] | 219 | if (isset($params) && is_array($params)) { |
---|
| 220 | // Merge new parameters with old overriding only those passed. |
---|
| 221 | $this->_params = array_merge($this->_params, $params); |
---|
| 222 | } |
---|
| 223 | } |
---|
| 224 | |
---|
| 225 | /** |
---|
| 226 | * Return the value of a parameter, if it exists. |
---|
| 227 | * |
---|
| 228 | * @access public |
---|
| 229 | * @param string $param Which parameter to return. |
---|
| 230 | * @return mixed Configured parameter value. |
---|
| 231 | */ |
---|
[468] | 232 | public function getParam($param) |
---|
[146] | 233 | { |
---|
[477] | 234 | $app =& App::getInstance(); |
---|
[462] | 235 | |
---|
[478] | 236 | if (array_key_exists($param, $this->_params)) { |
---|
[146] | 237 | return $this->_params[$param]; |
---|
| 238 | } else { |
---|
| 239 | $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 240 | return null; |
---|
| 241 | } |
---|
| 242 | } |
---|
| 243 | |
---|
[644] | 244 | /* |
---|
| 245 | * Setup the SESSION storage array. This method is called at the beginning of each method that accesses $_SESSION['_prefs']. |
---|
| 246 | * |
---|
| 247 | * @access public |
---|
| 248 | * @param |
---|
| 249 | * @return |
---|
| 250 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 251 | * @since 02 Oct 2018 15:35:09 |
---|
| 252 | */ |
---|
| 253 | private function _init() |
---|
| 254 | { |
---|
| 255 | if ('cookie' != $this->getParam('storagetype') && !isset($_SESSION['_prefs'][$this->_ns])) { |
---|
| 256 | $this->clear(); |
---|
| 257 | } |
---|
| 258 | } |
---|
| 259 | |
---|
[146] | 260 | /** |
---|
[462] | 261 | * Sets the default values for preferences. If a preference is not explicitly |
---|
[151] | 262 | * set, the value set here will be used. Can be called multiple times to merge additional |
---|
[481] | 263 | * defaults together. This is mostly only useful for the database storagetype, when you have |
---|
[478] | 264 | * values you want to use as default, and those are not stored to the database (so the defaults |
---|
| 265 | * can be changed later and apply to all users who haven't make s specific setting). |
---|
[481] | 266 | * For the cookie storagetype, using setDefaults just sets cookies but only if a cookie with |
---|
[478] | 267 | * the same name is not already set. |
---|
[1] | 268 | * |
---|
[462] | 269 | * @param array $defaults Array of key-value pairs |
---|
[1] | 270 | */ |
---|
[468] | 271 | public function setDefaults($defaults) |
---|
[1] | 272 | { |
---|
[478] | 273 | $app =& App::getInstance(); |
---|
| 274 | |
---|
[644] | 275 | $this->_init(); |
---|
| 276 | |
---|
[146] | 277 | if (isset($defaults) && is_array($defaults)) { |
---|
[478] | 278 | switch ($this->getParam('storagetype')) { |
---|
| 279 | case 'session': |
---|
| 280 | case 'database': |
---|
| 281 | $_SESSION['_prefs'][$this->_ns]['defaults'] = array_merge($_SESSION['_prefs'][$this->_ns]['defaults'], $defaults); |
---|
| 282 | break; |
---|
| 283 | |
---|
| 284 | case 'cookie': |
---|
| 285 | foreach ($defaults as $key => $val) { |
---|
| 286 | if (!$this->exists($key)) { |
---|
| 287 | $this->set($key, $val); |
---|
| 288 | } |
---|
| 289 | } |
---|
| 290 | unset($key, $val); |
---|
| 291 | break; |
---|
| 292 | } |
---|
| 293 | } else { |
---|
| 294 | $app->logMsg(sprintf('Wrong data-type passed to Prefs->setDefaults().', null), LOG_NOTICE, __FILE__, __LINE__); |
---|
[1] | 295 | } |
---|
| 296 | } |
---|
| 297 | |
---|
| 298 | /** |
---|
[478] | 299 | * Store a key-value pair. |
---|
| 300 | * When using the database storagetype, if the value is different than what is set by setDefaults the value will be scheduled to be saved in the database. |
---|
[1] | 301 | * |
---|
[152] | 302 | * @param string $key The name of the preference to modify. |
---|
| 303 | * @param string $val The new value for this preference. |
---|
[1] | 304 | */ |
---|
[468] | 305 | public function set($key, $val) |
---|
[1] | 306 | { |
---|
[151] | 307 | $app =& App::getInstance(); |
---|
[152] | 308 | |
---|
[477] | 309 | if (!is_string($key)) { |
---|
| 310 | $app->logMsg(sprintf('Key is not a string-compatible type (%s)', getDump($key)), LOG_NOTICE, __FILE__, __LINE__); |
---|
[151] | 311 | return false; |
---|
[149] | 312 | } |
---|
[477] | 313 | if ('' == trim($key)) { |
---|
| 314 | $app->logMsg(sprintf('Key is empty (along with value: %s)', $val), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 315 | return false; |
---|
| 316 | } |
---|
| 317 | if (!is_scalar($val) && !is_array($val) && !is_object($val)) { |
---|
[479] | 318 | $app->logMsg(sprintf('Value is not a compatible data type (%s=%s)', $key, getDump($val)), LOG_WARNING, __FILE__, __LINE__); |
---|
[477] | 319 | return false; |
---|
| 320 | } |
---|
[462] | 321 | |
---|
[644] | 322 | $this->_init(); |
---|
| 323 | |
---|
[477] | 324 | switch ($this->getParam('storagetype')) { |
---|
[478] | 325 | // Both session and database prefs are saved in the session (for database, only temporarily until they are saved). |
---|
[477] | 326 | case 'session': |
---|
[478] | 327 | case 'database': |
---|
| 328 | // Set a saved preference if... |
---|
| 329 | // - there isn't a default. |
---|
| 330 | // - or the new value is different than the default |
---|
| 331 | // - or there is a previously existing saved key. |
---|
[480] | 332 | if (!(isset($_SESSION['_prefs'][$this->_ns]['defaults']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['defaults'])) |
---|
[477] | 333 | || $_SESSION['_prefs'][$this->_ns]['defaults'][$key] != $val |
---|
[480] | 334 | || (isset($_SESSION['_prefs'][$this->_ns]['saved']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['saved']))) { |
---|
[477] | 335 | $_SESSION['_prefs'][$this->_ns]['saved'][$key] = $val; |
---|
[719] | 336 | $app->logMsg(sprintf('Setting session/database preference %s => %s', $key, getDump($val, true)), LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 337 | } else { |
---|
[719] | 338 | $app->logMsg(sprintf('Not setting session/database preference %s => %s', $key, getDump($val, true)), LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 339 | } |
---|
| 340 | break; |
---|
| 341 | |
---|
| 342 | case 'cookie': |
---|
| 343 | $name = $this->_getCookieName($key); |
---|
| 344 | $val = json_encode($val); |
---|
| 345 | $app->setCookie($name, $val, $this->getParam('cookie_expire'), $this->getParam('cookie_path'), $this->getParam('cookie_domain')); |
---|
[478] | 346 | $_COOKIE[$name] = $val; |
---|
[477] | 347 | $app->logMsg(sprintf('Setting cookie preference %s => %s', $key, $val), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 348 | break; |
---|
[151] | 349 | } |
---|
[477] | 350 | |
---|
[1] | 351 | } |
---|
[42] | 352 | |
---|
[1] | 353 | /** |
---|
[462] | 354 | * Returns the value of the requested preference. Saved values take precedence, but if none is set |
---|
[151] | 355 | * a default value is returned, or if not that, null. |
---|
[1] | 356 | * |
---|
[136] | 357 | * @param string $key The name of the preference to retrieve. |
---|
[1] | 358 | * |
---|
| 359 | * @return string The value of the preference. |
---|
| 360 | */ |
---|
[468] | 361 | public function get($key) |
---|
[1] | 362 | { |
---|
[151] | 363 | $app =& App::getInstance(); |
---|
[477] | 364 | |
---|
[644] | 365 | $this->_init(); |
---|
| 366 | |
---|
[477] | 367 | switch ($this->getParam('storagetype')) { |
---|
| 368 | case 'session': |
---|
| 369 | case 'database': |
---|
| 370 | if (isset($_SESSION['_prefs'][$this->_ns]['saved']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['saved'])) { |
---|
| 371 | $app->logMsg(sprintf('Found %s in saved', $key), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 372 | return $_SESSION['_prefs'][$this->_ns]['saved'][$key]; |
---|
| 373 | } else if (isset($_SESSION['_prefs'][$this->_ns]['defaults']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['defaults'])) { |
---|
| 374 | $app->logMsg(sprintf('Found %s in defaults', $key), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 375 | return $_SESSION['_prefs'][$this->_ns]['defaults'][$key]; |
---|
| 376 | } else { |
---|
| 377 | $app->logMsg(sprintf('Key not found in prefs cache: %s', $key), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 378 | } |
---|
[579] | 379 | return null; |
---|
[477] | 380 | |
---|
| 381 | case 'cookie': |
---|
| 382 | $name = $this->_getCookieName($key); |
---|
[579] | 383 | if ($this->exists($key) && '' != $_COOKIE[$name]) { |
---|
[526] | 384 | $val = json_decode($_COOKIE[$name], true); |
---|
[477] | 385 | $app->logMsg(sprintf('Found %s in cookie: %s', $key, getDump($val)), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 386 | return $val; |
---|
| 387 | } else { |
---|
[579] | 388 | $app->logMsg(sprintf('Did not find %s in cookie', $key), LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 389 | } |
---|
[579] | 390 | return null; |
---|
[151] | 391 | } |
---|
[1] | 392 | } |
---|
[42] | 393 | |
---|
[1] | 394 | /** |
---|
[152] | 395 | * To see if a preference has been set. |
---|
[1] | 396 | * |
---|
[136] | 397 | * @param string $key The name of the preference to check. |
---|
[151] | 398 | * @return boolean True if the preference isset and not empty false otherwise. |
---|
[1] | 399 | */ |
---|
[468] | 400 | public function exists($key) |
---|
[1] | 401 | { |
---|
[644] | 402 | $this->_init(); |
---|
| 403 | |
---|
[477] | 404 | switch ($this->getParam('storagetype')) { |
---|
| 405 | case 'session': |
---|
| 406 | case 'database': |
---|
[480] | 407 | return (isset($_SESSION['_prefs'][$this->_ns]['saved']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['saved'])); |
---|
[477] | 408 | |
---|
| 409 | case 'cookie': |
---|
| 410 | $name = $this->_getCookieName($key); |
---|
[480] | 411 | return (isset($_COOKIE) && array_key_exists($name, $_COOKIE)); |
---|
[477] | 412 | } |
---|
| 413 | |
---|
[1] | 414 | } |
---|
[42] | 415 | |
---|
[1] | 416 | /** |
---|
[478] | 417 | * Delete an existing preference value. This will also remove the value from the database, once save() is called. |
---|
[1] | 418 | * |
---|
[146] | 419 | * @param string $key The name of the preference to delete. |
---|
[1] | 420 | */ |
---|
[468] | 421 | public function delete($key) |
---|
[1] | 422 | { |
---|
[477] | 423 | $app =& App::getInstance(); |
---|
| 424 | |
---|
[644] | 425 | $this->_init(); |
---|
| 426 | |
---|
[477] | 427 | switch ($this->getParam('storagetype')) { |
---|
| 428 | case 'session': |
---|
| 429 | case 'database': |
---|
| 430 | unset($_SESSION['_prefs'][$this->_ns]['saved'][$key]); |
---|
| 431 | break; |
---|
| 432 | |
---|
| 433 | case 'cookie': |
---|
| 434 | if ($this->exists($key)) { |
---|
| 435 | // Just set the existing value to an empty string, which expires in the past. |
---|
| 436 | $name = $this->_getCookieName($key); |
---|
| 437 | $app->setCookie($name, '', time() - 86400); |
---|
| 438 | // Also unset the received cookie value, so it is unavailable. |
---|
| 439 | unset($_COOKIE[$name]); |
---|
| 440 | } |
---|
| 441 | break; |
---|
| 442 | } |
---|
| 443 | |
---|
[1] | 444 | } |
---|
| 445 | |
---|
| 446 | /** |
---|
[478] | 447 | * Resets all existing values under this namespace. This should be executed with the same consideration as $auth->clear(), such as when logging out. |
---|
[644] | 448 | * Set $save true to persist the clear action to the storage (i.e., erase all stored prefs for this user). |
---|
[1] | 449 | */ |
---|
[644] | 450 | public function clear($scope='all', $save=false) |
---|
[1] | 451 | { |
---|
[611] | 452 | $app =& App::getInstance(); |
---|
| 453 | |
---|
[478] | 454 | switch ($scope) { |
---|
[241] | 455 | case 'all' : |
---|
[477] | 456 | switch ($this->getParam('storagetype')) { |
---|
| 457 | case 'session': |
---|
| 458 | case 'database': |
---|
| 459 | $_SESSION['_prefs'][$this->_ns] = array( |
---|
| 460 | 'loaded' => false, |
---|
| 461 | 'load_datetime' => '1970-01-01', |
---|
| 462 | 'defaults' => array(), |
---|
| 463 | 'saved' => array(), |
---|
| 464 | ); |
---|
| 465 | break; |
---|
| 466 | case 'cookie': |
---|
| 467 | foreach ($_COOKIE as $key => $value) { |
---|
| 468 | // All cookie keys with our internal prefix. Use only the last part as the key. |
---|
[478] | 469 | if (preg_match('/^' . preg_quote(sprintf('_prefs-%s-', $this->_ns)) . '(.+)$/i', $key, $match)) { |
---|
[477] | 470 | $this->delete($match[1]); |
---|
| 471 | } |
---|
| 472 | } |
---|
| 473 | break; |
---|
| 474 | } |
---|
[241] | 475 | break; |
---|
[478] | 476 | |
---|
[241] | 477 | case 'defaults' : |
---|
| 478 | $_SESSION['_prefs'][$this->_ns]['defaults'] = array(); |
---|
| 479 | break; |
---|
[478] | 480 | |
---|
[462] | 481 | case 'saved' : |
---|
| 482 | $_SESSION['_prefs'][$this->_ns]['saved'] = array(); |
---|
[241] | 483 | break; |
---|
| 484 | } |
---|
[611] | 485 | |
---|
[644] | 486 | if ($save) { |
---|
| 487 | $this->save(true); |
---|
| 488 | $app->logMsg(sprintf('Deleted all %s %s prefs for user_id %s', $this->getParam('storagetype'), $this->_ns, $this->getParam('user_id')), LOG_INFO, __FILE__, __LINE__); |
---|
| 489 | } else { |
---|
| 490 | $app->logMsg(sprintf('Cleared %s %s prefs', $scope, $this->_ns), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 491 | } |
---|
[1] | 492 | } |
---|
[462] | 493 | |
---|
[146] | 494 | /* |
---|
[151] | 495 | * Retrieves all prefs from the database and stores them in the $_SESSION. |
---|
[146] | 496 | * |
---|
| 497 | * @access public |
---|
[150] | 498 | * @param bool $force Set to always load from database, regardless if _isLoaded() or not. |
---|
[146] | 499 | * @return bool True if loading succeeded. |
---|
| 500 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 501 | * @version 1.0 |
---|
| 502 | * @since 04 Jun 2006 16:56:53 |
---|
| 503 | */ |
---|
[468] | 504 | public function load($force=false) |
---|
[146] | 505 | { |
---|
| 506 | $app =& App::getInstance(); |
---|
[719] | 507 | $pdo =& \Strangecode\Codebase\PDO::getInstance(); |
---|
[462] | 508 | |
---|
[477] | 509 | // Skip this method if not using the db. |
---|
| 510 | if ('database' != $this->getParam('storagetype')) { |
---|
[665] | 511 | $app->logMsg('Prefs->load() does nothing unless using a database storagetype.', LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 512 | return true; |
---|
| 513 | } |
---|
[146] | 514 | |
---|
[150] | 515 | $this->initDB(); |
---|
| 516 | |
---|
[644] | 517 | $this->_init(); |
---|
| 518 | |
---|
[146] | 519 | // Prefs already loaded for this session. |
---|
[477] | 520 | if (!$force && $this->_isLoaded()) { |
---|
| 521 | return true; |
---|
| 522 | } |
---|
[146] | 523 | |
---|
| 524 | // User_id must not be empty. |
---|
| 525 | if ('' == $this->getParam('user_id')) { |
---|
[653] | 526 | $app->logMsg(sprintf('Cannot load prefs because user_id not set.', null), LOG_WARNING, __FILE__, __LINE__); |
---|
[146] | 527 | return false; |
---|
| 528 | } |
---|
[462] | 529 | |
---|
[150] | 530 | // Clear existing cache. |
---|
[462] | 531 | $this->clear('saved'); |
---|
| 532 | |
---|
[151] | 533 | // Retrieve all prefs for this user and namespace. |
---|
[719] | 534 | $stmt = $pdo->prepare(sprintf("SELECT `pref_key`, `pref_value` FROM `%s` WHERE `user_id` = ? AND `pref_namespace` = ? LIMIT 100000", $pdo->sanitizeIdentifier($this->getParam('db_table')))); |
---|
| 535 | $stmt->execute([$this->getParam('user_id'), $this->getParam('namespace')]); |
---|
| 536 | while (list($key, $val) = $stmt->fetch(\PDO::FETCH_NUM)) { |
---|
[462] | 537 | $_SESSION['_prefs'][$this->_ns]['saved'][$key] = unserialize($val); |
---|
[477] | 538 | } |
---|
[462] | 539 | |
---|
[719] | 540 | $app->logMsg(sprintf('Loaded %s prefs from database.', sizeof($_SESSION['_prefs'][$this->_ns]['saved'])), LOG_DEBUG, __FILE__, __LINE__); |
---|
[462] | 541 | |
---|
[477] | 542 | // Data loaded only once per session. |
---|
| 543 | $_SESSION['_prefs'][$this->_ns]['loaded'] = true; |
---|
[154] | 544 | $_SESSION['_prefs'][$this->_ns]['load_datetime'] = date('Y-m-d H:i:s'); |
---|
[462] | 545 | |
---|
[477] | 546 | return true; |
---|
[146] | 547 | } |
---|
[462] | 548 | |
---|
[146] | 549 | /* |
---|
[149] | 550 | * Returns true if the prefs had been loaded from the database into the $_SESSION recently. |
---|
| 551 | * This function is simply a check so the database isn't access every page load. |
---|
[462] | 552 | * |
---|
[146] | 553 | * @access private |
---|
| 554 | * @return bool True if prefs are loaded. |
---|
| 555 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 556 | * @version 1.0 |
---|
| 557 | * @since 04 Jun 2006 17:12:44 |
---|
| 558 | */ |
---|
[484] | 559 | protected function _isLoaded() |
---|
[146] | 560 | { |
---|
[477] | 561 | if ('database' != $this->getParam('storagetype')) { |
---|
[665] | 562 | $app->logMsg('Prefs->_isLoaded() does nothing unless using a database storagetype.', LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 563 | return true; |
---|
| 564 | } |
---|
| 565 | |
---|
[644] | 566 | $this->_init(); |
---|
| 567 | |
---|
[154] | 568 | if (isset($_SESSION['_prefs'][$this->_ns]['load_datetime']) |
---|
| 569 | && strtotime($_SESSION['_prefs'][$this->_ns]['load_datetime']) > time() - $this->getParam('load_timeout') |
---|
[462] | 570 | && isset($_SESSION['_prefs'][$this->_ns]['loaded']) |
---|
[154] | 571 | && true === $_SESSION['_prefs'][$this->_ns]['loaded']) { |
---|
[149] | 572 | return true; |
---|
| 573 | } else { |
---|
| 574 | return false; |
---|
| 575 | } |
---|
[146] | 576 | } |
---|
[462] | 577 | |
---|
[146] | 578 | /* |
---|
| 579 | * Saves all prefs stored in the $_SESSION into the database. |
---|
| 580 | * |
---|
| 581 | * @access public |
---|
| 582 | * @return bool True if prefs exist and were saved. |
---|
| 583 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 584 | * @version 1.0 |
---|
| 585 | * @since 04 Jun 2006 17:19:56 |
---|
| 586 | */ |
---|
[644] | 587 | public function save($allow_empty=false) |
---|
[146] | 588 | { |
---|
| 589 | $app =& App::getInstance(); |
---|
[719] | 590 | $pdo =& \Strangecode\Codebase\PDO::getInstance(); |
---|
[462] | 591 | |
---|
[477] | 592 | // Skip this method if not using the db. |
---|
| 593 | if ('database' != $this->getParam('storagetype')) { |
---|
[653] | 594 | $app->logMsg('Prefs->save() does nothing unless using a database storagetype.', LOG_DEBUG, __FILE__, __LINE__); |
---|
[477] | 595 | return true; |
---|
| 596 | } |
---|
[462] | 597 | |
---|
[146] | 598 | // User_id must not be empty. |
---|
| 599 | if ('' == $this->getParam('user_id')) { |
---|
[653] | 600 | $app->logMsg(sprintf('Cannot save prefs because user_id not set.', null), LOG_DEBUG, __FILE__, __LINE__); |
---|
[146] | 601 | return false; |
---|
| 602 | } |
---|
| 603 | |
---|
| 604 | $this->initDB(); |
---|
| 605 | |
---|
[644] | 606 | $this->_init(); |
---|
| 607 | |
---|
| 608 | if (isset($_SESSION['_prefs'][$this->_ns]['saved']) && is_array($_SESSION['_prefs'][$this->_ns]['saved']) && ($allow_empty || !empty($_SESSION['_prefs'][$this->_ns]['saved']))) { |
---|
[146] | 609 | // Delete old prefs from database. |
---|
[719] | 610 | $stmt = $pdo->prepare(sprintf("DELETE FROM `%s` WHERE `user_id` = ? AND `pref_namespace` = ?", $pdo->sanitizeIdentifier($this->getParam('db_table')))); |
---|
| 611 | $stmt->execute([$this->getParam('user_id'), $this->getParam('namespace')]); |
---|
[462] | 612 | |
---|
[146] | 613 | // Insert new prefs. |
---|
| 614 | $insert_values = array(); |
---|
[462] | 615 | foreach ($_SESSION['_prefs'][$this->_ns]['saved'] as $key => $val) { |
---|
[719] | 616 | $insert_values[] = sprintf("(%s, %s, %s, %s)", |
---|
| 617 | $pdo->quote($this->getParam('user_id')), |
---|
| 618 | $pdo->quote($this->getParam('namespace')), |
---|
| 619 | $pdo->quote($key), |
---|
| 620 | $pdo->quote(serialize($val)) |
---|
[158] | 621 | ); |
---|
[146] | 622 | } |
---|
[644] | 623 | if (!empty($insert_values)) { |
---|
[719] | 624 | $stmt = $pdo->query(sprintf(" |
---|
| 625 | INSERT INTO `%s` |
---|
| 626 | (`user_id`, `pref_namespace`, `pref_key`, `pref_value`) |
---|
| 627 | VALUES |
---|
| 628 | %s |
---|
| 629 | ", $pdo->sanitizeIdentifier($this->getParam('db_table')), join(', ', $insert_values))); |
---|
[644] | 630 | $app->logMsg(sprintf('Saved %s prefs to database for user_id %s.', sizeof($insert_values), $this->getParam('user_id')), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 631 | } |
---|
[462] | 632 | |
---|
[146] | 633 | return true; |
---|
| 634 | } |
---|
[462] | 635 | |
---|
[146] | 636 | return false; |
---|
| 637 | } |
---|
[477] | 638 | |
---|
| 639 | /* |
---|
| 640 | * |
---|
| 641 | * |
---|
| 642 | * @access public |
---|
| 643 | * @param |
---|
| 644 | * @return |
---|
| 645 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 646 | * @version 1.0 |
---|
| 647 | * @since 02 May 2014 18:17:04 |
---|
| 648 | */ |
---|
[484] | 649 | protected function _getCookieName($key) |
---|
[477] | 650 | { |
---|
| 651 | $app =& App::getInstance(); |
---|
| 652 | |
---|
[478] | 653 | if (mb_strpos($key, sprintf('_prefs-%s', $this->_ns)) === 0) { |
---|
| 654 | $app->logMsg(sprintf('Invalid key name (%s). Leave off "_prefs-%s-" and it should work.', $key, $this->_ns), LOG_NOTICE, __FILE__, __LINE__); |
---|
[477] | 655 | } |
---|
[478] | 656 | // Use standardized class data names: _ + classname + namespace + variablekey |
---|
[644] | 657 | // (namespace = namespace + user_id) |
---|
[478] | 658 | return sprintf('_prefs-%s-%s', $this->_ns, $key); |
---|
[477] | 659 | } |
---|
[1] | 660 | } |
---|
| 661 | |
---|