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

Last change on this file since 159 was 159, checked in by scdev, 18 years ago

${1}

File size: 13.7 KB
Line 
1<?php
2/**
3 * Prefs.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Prefs provides an API for saving arbitrary values in a user's session.
7 * Session prefs can be stored into a database with the optional save() and load() methods.
8 *
9 * @author  Quinn Comendant <quinn@strangecode.com>
10 * @version 2.1
11 *
12 * Example of use:
13---------------------------------------------------------------------
14// Load preferences for the user's session.
15require_once 'codebase/lib/Prefs.inc.php';
16$prefs = new Prefs('my-namespace');
17$prefs->setParam(array(
18    'persistent' => $auth->isLoggedIn(),
19    'user_id' => $auth->get('user_id'),
20));
21$prefs->setDefaults(array(
22    'search_num_results' => 25,
23    'datalog_num_entries' => 25,
24));
25$prefs->load();
26
27// Update preferences. Make sure to validate this input first!
28$prefs->set('search_num_results', getFormData('search_num_results'));
29$prefs->set('datalog_num_entries', getFormData('datalog_num_entries'));
30$prefs->save();
31
32---------------------------------------------------------------------
33 */
34class Prefs {
35
36    // Namespace of this instance of Prefs.
37    var $_ns;
38
39    // Configuration parameters for this object.
40    var $_params = array(
41       
42        // Enable database storage. If this is false, all prefs will live only as long as the session.
43        'persistent' => false,
44       
45        // The current user_id for which to load/save persistent preferences.
46        'user_id' => null,
47       
48        // How long before we force a reload of the persistent prefs data? 3600 = once every hour.
49        'load_timeout' => 3600,
50       
51        // Name of database table to store persistent prefs.
52        'db_table' => 'pref_tbl',
53
54        // Automatically create table and verify columns. Better set to false after site launch.
55        'create_table' => true,
56    );
57
58    /**
59     * Prefs constructor.
60     */
61    function Prefs($namespace='')
62    {
63        $app =& App::getInstance();
64
65        $this->_ns = $namespace;
66       
67        // Initialized the prefs array.
68        if (!isset($_SESSION['_prefs'][$this->_ns])) {
69            $this->clear();
70        }
71
72        // Get create tables config from global context.
73        if (!is_null($app->getParam('db_create_tables'))) {
74            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
75        }
76    }
77
78    /**
79     * Setup the database table for this class.
80     *
81     * @access  public
82     * @author  Quinn Comendant <quinn@strangecode.com>
83     * @since   04 Jun 2006 16:41:42
84     */
85    function initDB($recreate_db=false)
86    {
87        $app =& App::getInstance();
88        $db =& DB::getInstance();
89
90        static $_db_tested = false;
91
92        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
93            if ($recreate_db) {
94                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
95                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
96            }
97            $db->query("CREATE TABLE IF NOT EXISTS " . $db->escapeString($this->getParam('db_table')) . " (
98                user_id VARCHAR(32) NOT NULL DEFAULT '',
99                pref_namespace VARCHAR(32) NOT NULL DEFAULT '',
100                pref_key VARCHAR(64) NOT NULL DEFAULT '',
101                pref_value TEXT,
102                PRIMARY KEY (user_id, pref_namespace, pref_key)
103            )");
104
105            if (!$db->columnExists($this->getParam('db_table'), array(
106                'user_id',
107                'pref_namespace',
108                'pref_key',
109                'pref_value',
110            ), false, false)) {
111                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
112                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
113            }
114        }
115        $_db_tested = true;
116    }
117
118    /**
119     * Set the params of this object.
120     *
121     * @param  array $params   Array of param keys and values to set.
122     */
123    function setParam($params=null)
124    {
125        if (isset($params) && is_array($params)) {
126            // Merge new parameters with old overriding only those passed.
127            $this->_params = array_merge($this->_params, $params);
128        }
129    }
130
131    /**
132     * Return the value of a parameter, if it exists.
133     *
134     * @access public
135     * @param string $param        Which parameter to return.
136     * @return mixed               Configured parameter value.
137     */
138    function getParam($param)
139    {
140        $app =& App::getInstance();
141   
142        if (isset($this->_params[$param])) {
143            return $this->_params[$param];
144        } else {
145            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
146            return null;
147        }
148    }
149
150    /**
151     * Sets the default values for preferences. If a preference is not explicitly
152     * set, the value set here will be used. Can be called multiple times to merge additional
153     * defaults together.
154     *
155     * @param  array $defaults  Array of key-value pairs
156     */
157    function setDefaults($defaults)
158    {
159        if (isset($defaults) && is_array($defaults)) {
160            $_SESSION['_prefs'][$this->_ns]['defaults'] = array_merge($_SESSION['_prefs'][$this->_ns]['defaults'], $defaults);
161        }
162    }
163
164    /**
165     * Store a key-value pair in the session. If the value is different than what is set by setDefaults
166     * the value will be scheduled to be saved in the database.
167     * This function determins what data is saved to the database. Ensure clean values!
168     *
169     * @param  string $key          The name of the preference to modify.
170     * @param  string $val          The new value for this preference.
171     * @param  bool   $persistent   Save this value forever? Set to false and value will exist as long as the session is in use.
172     */
173    function set($key, $val)
174    {
175        $app =& App::getInstance();
176
177        if ('' == $key) {
178            $app->logMsg(sprintf('Key is empty (provided with value: %s)', $val), LOG_NOTICE, __FILE__, __LINE__);
179            return false;
180        }
181       
182        // Set a persistent perference if...
183        // - there isn't a default.
184        // - the new value is different than the default
185        // - there is a previously existing pesistent key.
186        if (!isset($_SESSION['_prefs'][$this->_ns]['defaults'][$key]) || $_SESSION['_prefs'][$this->_ns]['defaults'][$key] != $val || isset($_SESSION['_prefs'][$this->_ns]['persistent'][$key])) {
187            $_SESSION['_prefs'][$this->_ns]['persistent'][$key] = $val;           
188            $app->logMsg(sprintf('Setting preference %s to %s', $key, $val), LOG_DEBUG, __FILE__, __LINE__);
189        } else {
190            $app->logMsg(sprintf('not setting %s to %s', $key, $val), LOG_DEBUG, __FILE__, __LINE__);
191        }
192    }
193
194    /**
195     * Returns the value of the requested preference. Persistent values take precedence, but if none is set
196     * a default value is returned, or if not that, null.
197     *
198     * @param string $key       The name of the preference to retrieve.
199     *
200     * @return string           The value of the preference.
201     */
202    function get($key)
203    {
204        $app =& App::getInstance();
205        if (array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['persistent'])) {
206            return $_SESSION['_prefs'][$this->_ns]['persistent'][$key];
207        } else if (array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['defaults'])) {
208            return $_SESSION['_prefs'][$this->_ns]['defaults'][$key];
209        } else {
210            $app->logMsg(sprintf('Key not found in prefs cache: %s', $key), LOG_DEBUG, __FILE__, __LINE__);
211            return null;
212        }
213    }
214
215    /**
216     * To see if a preference has been set.
217     *
218     * @param string $key       The name of the preference to check.
219     * @return boolean          True if the preference isset and not empty false otherwise.
220     */
221    function exists($key)
222    {
223        return array_key_exists($key, $_SESSION['_prefs'][$this->_ns]['persistent']);
224    }
225
226    /**
227     * Clear a set preference value. This will also remove the value from the database.
228     *
229     * @param string $key       The name of the preference to delete.
230     */
231    function delete($key)
232    {
233        unset($_SESSION['_prefs'][$this->_ns]['persistent'][$key]);
234    }
235
236    /**
237     * Resets the $_SESSION cache. This should be executed with the same consideration
238     * as $auth->clear(), such as when logging out.
239     */
240    function clear()
241    {
242        $_SESSION['_prefs'][$this->_ns] = array(
243            'loaded' => false,
244            'load_datetime' => '1970-01-01',
245            'defaults' => array(),
246            'persistent' => array(),
247        );
248    }
249   
250    /*
251    * Retrieves all prefs from the database and stores them in the $_SESSION.
252    *
253    * @access   public
254    * @param    bool    $force  Set to always load from database, regardless if _isLoaded() or not.
255    * @return   bool    True if loading succeeded.
256    * @author   Quinn Comendant <quinn@strangecode.com>
257    * @version  1.0
258    * @since    04 Jun 2006 16:56:53
259    */
260    function load($force=false)
261    {
262        $app =& App::getInstance();
263        $db =& DB::getInstance();
264       
265        // Skip this method if not using the db.
266        if (true !== $this->getParam('persistent')) {
267            return true;
268        }
269
270        $this->initDB();
271
272        // Prefs already loaded for this session.
273        if (!$force && $this->_isLoaded()) {
274            return true;
275        }
276
277        // User_id must not be empty.
278        if ('' == $this->getParam('user_id')) {
279            $app->logMsg(sprintf('Cannot save prefs because user_id not set.', null), LOG_WARNING, __FILE__, __LINE__);
280            return false;
281        }
282       
283        // Clear existing cache.
284        $this->clear();
285       
286        // Retrieve all prefs for this user and namespace.
287        $qid = $db->query("
288            SELECT pref_key, pref_value
289            FROM " . $db->escapeString($this->getParam('db_table')) . "
290            WHERE user_id = '" . $db->escapeString($this->getParam('user_id')) . "'
291            AND pref_namespace = '" . $db->escapeString($this->_ns) . "'
292            LIMIT 10000
293        ");
294        while (list($key, $val) = mysql_fetch_row($qid)) {
295            $_SESSION['_prefs'][$this->_ns]['persistent'][$key] = unserialize($val);
296        }
297       
298        $app->logMsg(sprintf('Loaded %s prefs from database.', sizeof($_SESSION['_prefs'][$this->_ns]['persistent'])), LOG_DEBUG, __FILE__, __LINE__);
299       
300        // Data loaded only once per session.
301        $_SESSION['_prefs'][$this->_ns]['loaded'] = true;
302        $_SESSION['_prefs'][$this->_ns]['load_datetime'] = date('Y-m-d H:i:s');
303       
304        return true;
305    }
306   
307    /*
308    * Returns true if the prefs had been loaded from the database into the $_SESSION recently.
309    * This function is simply a check so the database isn't access every page load.
310    *
311    * @access   private
312    * @return   bool    True if prefs are loaded.
313    * @author   Quinn Comendant <quinn@strangecode.com>
314    * @version  1.0
315    * @since    04 Jun 2006 17:12:44
316    */
317    function _isLoaded()
318    {
319        if (isset($_SESSION['_prefs'][$this->_ns]['load_datetime'])
320        && strtotime($_SESSION['_prefs'][$this->_ns]['load_datetime']) > time() - $this->getParam('load_timeout')
321        && isset($_SESSION['_prefs'][$this->_ns]['loaded']) 
322        && true === $_SESSION['_prefs'][$this->_ns]['loaded']) {
323            return true;
324        } else {
325            return false;
326        }
327    }
328   
329    /*
330    * Saves all prefs stored in the $_SESSION into the database.
331    *
332    * @access   public
333    * @return   bool    True if prefs exist and were saved.
334    * @author   Quinn Comendant <quinn@strangecode.com>
335    * @version  1.0
336    * @since    04 Jun 2006 17:19:56
337    */
338    function save()
339    {
340        $app =& App::getInstance();
341        $db =& DB::getInstance();
342       
343        // Skip this method if not using the db.
344        if (true !== $this->getParam('persistent')) {
345            return true;
346        }
347       
348        // User_id must not be empty.
349        if ('' == $this->getParam('user_id')) {
350            $app->logMsg(sprintf('Cannot save prefs because user_id not set.', null), LOG_WARNING, __FILE__, __LINE__);
351            return false;
352        }
353
354        $this->initDB();
355
356        if (isset($_SESSION['_prefs'][$this->_ns]['persistent']) && is_array($_SESSION['_prefs'][$this->_ns]['persistent']) && !empty($_SESSION['_prefs'][$this->_ns]['persistent'])) {
357            // Delete old prefs from database.
358            $db->query("
359                DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
360                WHERE user_id = '" . $db->escapeString($this->getParam('user_id')) . "'
361                AND pref_namespace = '" . $db->escapeString($this->_ns) . "'
362            ");
363           
364            // Insert new prefs.
365            $insert_values = array();
366            foreach ($_SESSION['_prefs'][$this->_ns]['persistent'] as $key => $val) {
367                $insert_values[] = sprintf("('%s', '%s', '%s', '%s')", 
368                    $db->escapeString($this->getParam('user_id')), 
369                    $db->escapeString($this->_ns), 
370                    $db->escapeString($key), 
371                    $db->escapeString(serialize($val))
372                );
373            }
374            // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
375            $db->query("
376                INSERT INTO " . $db->escapeString($this->getParam('db_table')) . "
377                (user_id, pref_namespace, pref_key, pref_value)
378                VALUES " . join(', ', $insert_values) . "
379            ");
380           
381            $app->logMsg(sprintf('Saved %s prefs to database.', sizeof($insert_values)), LOG_DEBUG, __FILE__, __LINE__);
382            return true;
383        }
384       
385        return false;
386    }
387}
388
389
390?>
Note: See TracBrowser for help on using the repository browser.