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