source: trunk/lib/Prefs.inc.php @ 526

Last change on this file since 526 was 526, checked in by anonymous, 9 years ago

Enabled App to load version from json file. Lock URL fixed to permit additional query arguments. Return array instead of object for Prefs cookie json.

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