1 | <?php |
---|
2 | /** |
---|
3 | * The Strangecode Codebase - a general application development framework for PHP |
---|
4 | * For details visit the project site: <http://trac.strangecode.com/codebase/> |
---|
5 | * Copyright 2001-2012 Strangecode, LLC |
---|
6 | * |
---|
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. |
---|
13 | * |
---|
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. |
---|
18 | * |
---|
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 | /** |
---|
24 | * Prefs.inc.php |
---|
25 | * |
---|
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. |
---|
28 | * |
---|
29 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
30 | * @version 3.0 |
---|
31 | * @todo This class could really benefit from being refactored using the factory pattern, with backend storage mechanisms. |
---|
32 | * |
---|
33 | * Example of use (database storagetype): |
---|
34 | --------------------------------------------------------------------- |
---|
35 | // Load preferences for the user's session. |
---|
36 | require_once 'codebase/lib/Prefs.inc.php'; |
---|
37 | $prefs = new Prefs('my-namespace'); |
---|
38 | $prefs->setParam(array( |
---|
39 | 'storagetype' => ($auth->isLoggedIn() ? 'database' : 'session'), |
---|
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(); |
---|
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(); |
---|
52 | --------------------------------------------------------------------- |
---|
53 | */ |
---|
54 | class Prefs |
---|
55 | { |
---|
56 | |
---|
57 | // Namespace of this instance of Prefs. |
---|
58 | protected $_ns; |
---|
59 | |
---|
60 | // Configuration parameters for this object. |
---|
61 | protected $_params = array( |
---|
62 | |
---|
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 | |
---|
67 | // This parameter is only used for legacy support, superseded by the 'storagetype' setting. |
---|
68 | // Enable database storage. If this is false, all prefs will live only as long as the session. |
---|
69 | 'persistent' => null, |
---|
70 | |
---|
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. |
---|
87 | 'user_id' => null, |
---|
88 | |
---|
89 | // How long before we force a reload of the persistent prefs data? 300 = every five minutes. |
---|
90 | 'load_timeout' => 300, |
---|
91 | |
---|
92 | // Name of database table to store prefs. |
---|
93 | 'db_table' => 'pref_tbl', |
---|
94 | |
---|
95 | // Automatically create table and verify columns. Better set to false after site launch. |
---|
96 | // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available. |
---|
97 | 'create_table' => true, |
---|
98 | |
---|
99 | // Original namespace set during __construct(). |
---|
100 | // 'namespace' => '', |
---|
101 | ); |
---|
102 | |
---|
103 | /** |
---|
104 | * Prefs constructor. |
---|
105 | */ |
---|
106 | public function __construct($namespace='', array $params=null) |
---|
107 | { |
---|
108 | $app =& App::getInstance(); |
---|
109 | |
---|
110 | $this->_ns = $namespace; |
---|
111 | |
---|
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 | |
---|
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 | } |
---|
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 | } |
---|
128 | } |
---|
129 | |
---|
130 | /** |
---|
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 | */ |
---|
137 | public function initDB($recreate_db=false) |
---|
138 | { |
---|
139 | $app =& App::getInstance(); |
---|
140 | $db =& DB::getInstance(); |
---|
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')); |
---|
147 | $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__); |
---|
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 | */ |
---|
175 | public function setParam(array $params=null) |
---|
176 | { |
---|
177 | $app =& App::getInstance(); |
---|
178 | |
---|
179 | // CLI scripts can't use prefs stored in HTTP-based protocols. |
---|
180 | if ($app->cli |
---|
181 | && isset($params['storagetype']) |
---|
182 | && in_array($params['storagetype'], array('cookie', 'session'))) { |
---|
183 | $app->logMsg(sprintf('Storage type %s not available for CLI', $params['storagetype']), LOG_NOTICE, __FILE__, __LINE__); |
---|
184 | } |
---|
185 | |
---|
186 | // Convert the legacy param 'persistent' to 'storagetype=database'. |
---|
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). |
---|
190 | if (isset($params['persistent']) && $params['persistent'] && !isset($params['storagetype'])) { |
---|
191 | $params['storagetype'] = 'database'; |
---|
192 | } |
---|
193 | |
---|
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 | |
---|
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 | */ |
---|
226 | public function getParam($param) |
---|
227 | { |
---|
228 | $app =& App::getInstance(); |
---|
229 | |
---|
230 | if (array_key_exists($param, $this->_params)) { |
---|
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 | |
---|
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 | |
---|
254 | /** |
---|
255 | * Sets the default values for preferences. If a preference is not explicitly |
---|
256 | * set, the value set here will be used. Can be called multiple times to merge additional |
---|
257 | * defaults together. This is mostly only useful for the database storagetype, when you have |
---|
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). |
---|
260 | * For the cookie storagetype, using setDefaults just sets cookies but only if a cookie with |
---|
261 | * the same name is not already set. |
---|
262 | * |
---|
263 | * @param array $defaults Array of key-value pairs |
---|
264 | */ |
---|
265 | public function setDefaults($defaults) |
---|
266 | { |
---|
267 | $app =& App::getInstance(); |
---|
268 | |
---|
269 | $this->_init(); |
---|
270 | |
---|
271 | if (isset($defaults) && is_array($defaults)) { |
---|
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__); |
---|
289 | } |
---|
290 | } |
---|
291 | |
---|
292 | /** |
---|
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. |
---|
295 | * |
---|
296 | * @param string $key The name of the preference to modify. |
---|
297 | * @param string $val The new value for this preference. |
---|
298 | */ |
---|
299 | public function set($key, $val) |
---|
300 | { |
---|
301 | $app =& App::getInstance(); |
---|
302 | |
---|
303 | if (!is_string($key)) { |
---|
304 | $app->logMsg(sprintf('Key is not a string-compatible type (%s)', getDump($key)), LOG_NOTICE, __FILE__, __LINE__); |
---|
305 | return false; |
---|
306 | } |
---|
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)) { |
---|
312 | $app->logMsg(sprintf('Value is not a compatible data type (%s=%s)', $key, getDump($val)), LOG_WARNING, __FILE__, __LINE__); |
---|
313 | return false; |
---|
314 | } |
---|
315 | |
---|
316 | $this->_init(); |
---|
317 | |
---|
318 | switch ($this->getParam('storagetype')) { |
---|
319 | // Both session and database prefs are saved in the session (for database, only temporarily until they are saved). |
---|
320 | case 'session': |
---|
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. |
---|
326 | if (!(isset($_SESSION['_prefs'][$this->_ns]['defaults']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['defaults'])) |
---|
327 | || $_SESSION['_prefs'][$this->_ns]['defaults'][$key] != $val |
---|
328 | || (isset($_SESSION['_prefs'][$this->_ns]['saved']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['saved']))) { |
---|
329 | $_SESSION['_prefs'][$this->_ns]['saved'][$key] = $val; |
---|
330 | $app->logMsg(sprintf('Setting session preference %s => %s', $key, getDump($val, true)), LOG_DEBUG, __FILE__, __LINE__); |
---|
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')); |
---|
340 | $_COOKIE[$name] = $val; |
---|
341 | $app->logMsg(sprintf('Setting cookie preference %s => %s', $key, $val), LOG_DEBUG, __FILE__, __LINE__); |
---|
342 | break; |
---|
343 | } |
---|
344 | |
---|
345 | } |
---|
346 | |
---|
347 | /** |
---|
348 | * Returns the value of the requested preference. Saved values take precedence, but if none is set |
---|
349 | * a default value is returned, or if not that, null. |
---|
350 | * |
---|
351 | * @param string $key The name of the preference to retrieve. |
---|
352 | * |
---|
353 | * @return string The value of the preference. |
---|
354 | */ |
---|
355 | public function get($key) |
---|
356 | { |
---|
357 | $app =& App::getInstance(); |
---|
358 | |
---|
359 | $this->_init(); |
---|
360 | |
---|
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 | } |
---|
373 | return null; |
---|
374 | |
---|
375 | case 'cookie': |
---|
376 | $name = $this->_getCookieName($key); |
---|
377 | if ($this->exists($key) && '' != $_COOKIE[$name]) { |
---|
378 | $val = json_decode($_COOKIE[$name], true); |
---|
379 | $app->logMsg(sprintf('Found %s in cookie: %s', $key, getDump($val)), LOG_DEBUG, __FILE__, __LINE__); |
---|
380 | return $val; |
---|
381 | } else { |
---|
382 | $app->logMsg(sprintf('Did not find %s in cookie', $key), LOG_DEBUG, __FILE__, __LINE__); |
---|
383 | } |
---|
384 | return null; |
---|
385 | } |
---|
386 | } |
---|
387 | |
---|
388 | /** |
---|
389 | * To see if a preference has been set. |
---|
390 | * |
---|
391 | * @param string $key The name of the preference to check. |
---|
392 | * @return boolean True if the preference isset and not empty false otherwise. |
---|
393 | */ |
---|
394 | public function exists($key) |
---|
395 | { |
---|
396 | $this->_init(); |
---|
397 | |
---|
398 | switch ($this->getParam('storagetype')) { |
---|
399 | case 'session': |
---|
400 | case 'database': |
---|
401 | return (isset($_SESSION['_prefs'][$this->_ns]['saved']) && array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['saved'])); |
---|
402 | |
---|
403 | case 'cookie': |
---|
404 | $name = $this->_getCookieName($key); |
---|
405 | return (isset($_COOKIE) && array_key_exists($name, $_COOKIE)); |
---|
406 | } |
---|
407 | |
---|
408 | } |
---|
409 | |
---|
410 | /** |
---|
411 | * Delete an existing preference value. This will also remove the value from the database, once save() is called. |
---|
412 | * |
---|
413 | * @param string $key The name of the preference to delete. |
---|
414 | */ |
---|
415 | public function delete($key) |
---|
416 | { |
---|
417 | $app =& App::getInstance(); |
---|
418 | |
---|
419 | $this->_init(); |
---|
420 | |
---|
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 | |
---|
438 | } |
---|
439 | |
---|
440 | /** |
---|
441 | * Resets all existing values under this namespace. This should be executed with the same consideration as $auth->clear(), such as when logging out. |
---|
442 | * Set $save true to persist the clear action to the storage (i.e., erase all stored prefs for this user). |
---|
443 | */ |
---|
444 | public function clear($scope='all', $save=false) |
---|
445 | { |
---|
446 | $app =& App::getInstance(); |
---|
447 | |
---|
448 | switch ($scope) { |
---|
449 | case 'all' : |
---|
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. |
---|
463 | if (preg_match('/^' . preg_quote(sprintf('_prefs-%s-', $this->_ns)) . '(.+)$/i', $key, $match)) { |
---|
464 | $this->delete($match[1]); |
---|
465 | } |
---|
466 | } |
---|
467 | break; |
---|
468 | } |
---|
469 | break; |
---|
470 | |
---|
471 | case 'defaults' : |
---|
472 | $_SESSION['_prefs'][$this->_ns]['defaults'] = array(); |
---|
473 | break; |
---|
474 | |
---|
475 | case 'saved' : |
---|
476 | $_SESSION['_prefs'][$this->_ns]['saved'] = array(); |
---|
477 | break; |
---|
478 | } |
---|
479 | |
---|
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 | } |
---|
486 | } |
---|
487 | |
---|
488 | /* |
---|
489 | * Retrieves all prefs from the database and stores them in the $_SESSION. |
---|
490 | * |
---|
491 | * @access public |
---|
492 | * @param bool $force Set to always load from database, regardless if _isLoaded() or not. |
---|
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 | */ |
---|
498 | public function load($force=false) |
---|
499 | { |
---|
500 | $app =& App::getInstance(); |
---|
501 | $db =& DB::getInstance(); |
---|
502 | |
---|
503 | // Skip this method if not using the db. |
---|
504 | if ('database' != $this->getParam('storagetype')) { |
---|
505 | $app->logMsg('Prefs->load() does nothing unless using a database storagetype.', LOG_NOTICE, __FILE__, __LINE__); |
---|
506 | return true; |
---|
507 | } |
---|
508 | |
---|
509 | $this->initDB(); |
---|
510 | |
---|
511 | $this->_init(); |
---|
512 | |
---|
513 | // Prefs already loaded for this session. |
---|
514 | if (!$force && $this->_isLoaded()) { |
---|
515 | return true; |
---|
516 | } |
---|
517 | |
---|
518 | // User_id must not be empty. |
---|
519 | if ('' == $this->getParam('user_id')) { |
---|
520 | $app->logMsg(sprintf('Cannot save prefs because user_id not set.', null), LOG_WARNING, __FILE__, __LINE__); |
---|
521 | return false; |
---|
522 | } |
---|
523 | |
---|
524 | // Clear existing cache. |
---|
525 | $this->clear('saved'); |
---|
526 | |
---|
527 | // Retrieve all prefs for this user and namespace. |
---|
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')) . "' |
---|
532 | AND pref_namespace = '" . $db->escapeString($this->getParam('namespace')) . "' |
---|
533 | LIMIT 10000 |
---|
534 | "); |
---|
535 | while (list($key, $val) = mysql_fetch_row($qid)) { |
---|
536 | $_SESSION['_prefs'][$this->_ns]['saved'][$key] = unserialize($val); |
---|
537 | } |
---|
538 | |
---|
539 | $app->logMsg(sprintf('Loaded %s prefs from database.', mysql_num_rows($qid)), LOG_DEBUG, __FILE__, __LINE__); |
---|
540 | |
---|
541 | // Data loaded only once per session. |
---|
542 | $_SESSION['_prefs'][$this->_ns]['loaded'] = true; |
---|
543 | $_SESSION['_prefs'][$this->_ns]['load_datetime'] = date('Y-m-d H:i:s'); |
---|
544 | |
---|
545 | return true; |
---|
546 | } |
---|
547 | |
---|
548 | /* |
---|
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. |
---|
551 | * |
---|
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 | */ |
---|
558 | protected function _isLoaded() |
---|
559 | { |
---|
560 | if ('database' != $this->getParam('storagetype')) { |
---|
561 | $app->logMsg('Prefs->_isLoaded() does nothing unless using a database storagetype.', LOG_NOTICE, __FILE__, __LINE__); |
---|
562 | return true; |
---|
563 | } |
---|
564 | |
---|
565 | $this->_init(); |
---|
566 | |
---|
567 | if (isset($_SESSION['_prefs'][$this->_ns]['load_datetime']) |
---|
568 | && strtotime($_SESSION['_prefs'][$this->_ns]['load_datetime']) > time() - $this->getParam('load_timeout') |
---|
569 | && isset($_SESSION['_prefs'][$this->_ns]['loaded']) |
---|
570 | && true === $_SESSION['_prefs'][$this->_ns]['loaded']) { |
---|
571 | return true; |
---|
572 | } else { |
---|
573 | return false; |
---|
574 | } |
---|
575 | } |
---|
576 | |
---|
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 | */ |
---|
586 | public function save($allow_empty=false) |
---|
587 | { |
---|
588 | $app =& App::getInstance(); |
---|
589 | $db =& DB::getInstance(); |
---|
590 | |
---|
591 | // Skip this method if not using the db. |
---|
592 | if ('database' != $this->getParam('storagetype')) { |
---|
593 | $app->logMsg('Prefs->save() does nothing unless using a database storagetype.', LOG_NOTICE, __FILE__, __LINE__); |
---|
594 | return true; |
---|
595 | } |
---|
596 | |
---|
597 | // User_id must not be empty. |
---|
598 | if ('' == $this->getParam('user_id')) { |
---|
599 | $app->logMsg(sprintf('Cannot save prefs because user_id not set.', null), LOG_WARNING, __FILE__, __LINE__); |
---|
600 | return false; |
---|
601 | } |
---|
602 | |
---|
603 | $this->initDB(); |
---|
604 | |
---|
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']))) { |
---|
608 | // Delete old prefs from database. |
---|
609 | $db->query(" |
---|
610 | DELETE FROM " . $db->escapeString($this->getParam('db_table')) . " |
---|
611 | WHERE user_id = '" . $db->escapeString($this->getParam('user_id')) . "' |
---|
612 | AND pref_namespace = '" . $db->escapeString($this->getParam('namespace')) . "' |
---|
613 | "); |
---|
614 | |
---|
615 | // Insert new prefs. |
---|
616 | $insert_values = array(); |
---|
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')), |
---|
620 | $db->escapeString($this->getParam('namespace')), |
---|
621 | $db->escapeString($key), |
---|
622 | $db->escapeString(serialize($val)) |
---|
623 | ); |
---|
624 | } |
---|
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 | } |
---|
634 | |
---|
635 | return true; |
---|
636 | } |
---|
637 | |
---|
638 | return false; |
---|
639 | } |
---|
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 | */ |
---|
651 | protected function _getCookieName($key) |
---|
652 | { |
---|
653 | $app =& App::getInstance(); |
---|
654 | |
---|
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__); |
---|
657 | } |
---|
658 | // Use standardized class data names: _ + classname + namespace + variablekey |
---|
659 | // (namespace = namespace + user_id) |
---|
660 | return sprintf('_prefs-%s-%s', $this->_ns, $key); |
---|
661 | } |
---|
662 | } |
---|
663 | |
---|