7b59c7215b0630c4b36ee92fbe82239af66bc51e
[squirrelmail.git] / functions / db_prefs.php
1 <?php
2
3 /**
4 * db_prefs.php
5 *
6 * This contains functions for manipulating user preferences
7 * stored in a database, accessed though the Pear DB layer.
8 *
9 * Database:
10 *
11 * The preferences table should have three columns:
12 * user char \ primary
13 * prefkey char / key
14 * prefval blob
15 *
16 * CREATE TABLE userprefs (user CHAR(128) NOT NULL DEFAULT '',
17 * prefkey CHAR(64) NOT NULL DEFAULT '',
18 * prefval BLOB NOT NULL DEFAULT '',
19 * primary key (user,prefkey));
20 *
21 * Configuration of databasename, username and password is done
22 * by using conf.pl or the administrator plugin
23 *
24 * @copyright &copy; 1999-2007 The SquirrelMail Project Team
25 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
26 * @version $Id$
27 * @package squirrelmail
28 * @subpackage prefs
29 * @since 1.1.3
30 */
31
32 /** @ignore */
33 if (!defined('SM_PATH')) define('SM_PATH','../');
34
35 /** Unknown database */
36 define('SMDB_UNKNOWN', 0);
37 /** MySQL */
38 define('SMDB_MYSQL', 1);
39 /** PostgreSQL */
40 define('SMDB_PGSQL', 2);
41
42 /**
43 * don't display errors (no code execution in functions/*.php).
44 * will handle error in dbPrefs class.
45 */
46 @include_once('DB.php');
47
48 global $prefs_are_cached, $prefs_cache;
49
50 /**
51 * @ignore
52 */
53 function cachePrefValues($username) {
54 global $prefs_are_cached, $prefs_cache;
55
56 sqgetGlobalVar('prefs_are_cached', $prefs_are_cached, SQ_SESSION );
57 if ($prefs_are_cached) {
58 sqgetGlobalVar('prefs_cache', $prefs_cache, SQ_SESSION );
59 return;
60 }
61
62 sqsession_unregister('prefs_cache');
63 sqsession_unregister('prefs_are_cached');
64
65 $db = new dbPrefs;
66 if(isset($db->error)) {
67 printf( _("Preference database error (%s). Exiting abnormally"),
68 $db->error);
69 exit;
70 }
71
72 $db->fillPrefsCache($username);
73 if (isset($db->error)) {
74 printf( _("Preference database error (%s). Exiting abnormally"),
75 $db->error);
76 exit;
77 }
78
79 $prefs_are_cached = true;
80
81 sqsession_register($prefs_cache, 'prefs_cache');
82 sqsession_register($prefs_are_cached, 'prefs_are_cached');
83 }
84
85 /**
86 * Class used to handle connections to prefs database and operations with preferences
87 * @package squirrelmail
88 * @subpackage prefs
89 * @since 1.1.3
90 */
91 class dbPrefs {
92 /**
93 * Table used to store preferences
94 * @var string
95 */
96 var $table = 'userprefs';
97 /**
98 * Field used to store owner of preference
99 * @var string
100 */
101 var $user_field = 'user';
102 /**
103 * Field used to store preference name
104 * @var string
105 */
106 var $key_field = 'prefkey';
107 /**
108 * Field used to store preference value
109 * @var string
110 */
111 var $val_field = 'prefval';
112
113 /**
114 * Database connection object
115 * @var object
116 */
117 var $dbh = NULL;
118 /**
119 * Error messages
120 * @var string
121 */
122 var $error = NULL;
123 /**
124 * Database type (SMDB_* constants)
125 * Is used in setKey().
126 * @var integer
127 */
128 var $db_type = SMDB_UNKNOWN;
129
130 /**
131 * Default preferences
132 * @var array
133 */
134 var $default = Array('theme_default' => 0,
135 'show_html_default' => '0');
136
137 /**
138 * Preference owner field size
139 * @var integer
140 * @since 1.5.1
141 */
142 var $user_size = 128;
143 /**
144 * Preference key field size
145 * @var integer
146 * @since 1.5.1
147 */
148 var $key_size = 64;
149 /**
150 * Preference value field size
151 * @var integer
152 * @since 1.5.1
153 */
154 var $val_size = 65536;
155
156 /**
157 * initialize DB connection object
158 * @return boolean true, if object is initialized
159 */
160 function open() {
161 global $prefs_dsn, $prefs_table;
162 global $prefs_user_field, $prefs_key_field, $prefs_val_field;
163 global $prefs_user_size, $prefs_key_size, $prefs_val_size;
164
165 /* test if Pear DB class is available and freak out if it is not */
166 if (! class_exists('DB')) {
167 // same error also in abook_database.php
168 $this->error = _("Could not include PEAR database functions required for the database backend.") . "<br />\n";
169 $this->error .= sprintf(_("Is PEAR installed, and is the include path set correctly to find %s?"),
170 '<tt>DB.php</tt>') . "<br />\n";
171 $this->error .= _("Please contact your system administrator and report this error.");
172 return false;
173 }
174
175 if(isset($this->dbh)) {
176 return true;
177 }
178
179 if (preg_match('/^mysql/', $prefs_dsn)) {
180 $this->db_type = SMDB_MYSQL;
181 } elseif (preg_match('/^pgsql/', $prefs_dsn)) {
182 $this->db_type = SMDB_PGSQL;
183 }
184
185 if (!empty($prefs_table)) {
186 $this->table = $prefs_table;
187 }
188 if (!empty($prefs_user_field)) {
189 $this->user_field = $prefs_user_field;
190 }
191 if (!empty($prefs_key_field)) {
192 $this->key_field = $prefs_key_field;
193 }
194 if (!empty($prefs_val_field)) {
195 $this->val_field = $prefs_val_field;
196 }
197 if (!empty($prefs_user_size)) {
198 $this->user_size = (int) $prefs_user_size;
199 }
200 if (!empty($prefs_key_size)) {
201 $this->key_size = (int) $prefs_key_size;
202 }
203 if (!empty($prefs_val_size)) {
204 $this->val_size = (int) $prefs_val_size;
205 }
206 $dbh = DB::connect($prefs_dsn, true);
207
208 if(DB::isError($dbh)) {
209 $this->error = DB::errorMessage($dbh);
210 return false;
211 }
212
213 $this->dbh = $dbh;
214 return true;
215 }
216
217 /**
218 * Function used to handle database connection errors
219 * @param object PEAR Error object
220 */
221 function failQuery($res = NULL) {
222 if($res == NULL) {
223 printf(_("Preference database error (%s). Exiting abnormally"),
224 $this->error);
225 } else {
226 printf(_("Preference database error (%s). Exiting abnormally"),
227 DB::errorMessage($res));
228 }
229 exit;
230 }
231
232 /**
233 * Get user's prefs setting
234 * @param string $user user name
235 * @param string $key preference name
236 * @param mixed $default (since 1.2.5) default value
237 * @return mixed preference value
238 */
239 function getKey($user, $key, $default = '') {
240 global $prefs_cache;
241
242 cachePrefValues($user);
243
244 if (isset($prefs_cache[$key])) {
245 return $prefs_cache[$key];
246 } else {
247 if (isset($this->default[$key])) {
248 return $this->default[$key];
249 } else {
250 return $default;
251 }
252 }
253 }
254
255 /**
256 * Delete user's prefs setting
257 * @param string $user user name
258 * @param string $key preference name
259 * @return boolean
260 */
261 function deleteKey($user, $key) {
262 global $prefs_cache;
263
264 if (!$this->open()) {
265 return false;
266 }
267 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
268 $this->table,
269 $this->user_field,
270 $this->dbh->quoteString($user),
271 $this->key_field,
272 $this->dbh->quoteString($key));
273
274 $res = $this->dbh->simpleQuery($query);
275 if(DB::isError($res)) {
276 $this->failQuery($res);
277 }
278
279 unset($prefs_cache[$key]);
280
281 return true;
282 }
283
284 /**
285 * Set user's preference
286 * @param string $user user name
287 * @param string $key preference name
288 * @param mixed $value preference value
289 * @return boolean
290 */
291 function setKey($user, $key, $value) {
292 if (!$this->open()) {
293 return false;
294 }
295
296 /**
297 * Check if username fits into db field
298 */
299 if (strlen($user) > $this->user_size) {
300 $this->error = "Oversized username value."
301 ." Your preferences can't be saved."
302 ." See doc/db-backend.txt or contact your system administrator.";
303
304 /**
305 * Debugging function. Can be used to log all issues that trigger
306 * oversized field errors. Function should be enabled in all three
307 * strlen checks. See http://www.php.net/error-log
308 */
309 // error_log($user.'|'.$key.'|'.$value."\n",3,'/tmp/oversized_log');
310
311 // error is fatal
312 $this->failQuery(null);
313 }
314 /**
315 * Check if preference key fits into db field
316 */
317 if (strlen($key) > $this->key_size) {
318 $err_msg = "Oversized user's preference key."
319 ." Some preferences were not saved."
320 ." See doc/db-backend.txt or contact your system administrator.";
321 // error is not fatal. Only some preference is not saved.
322 trigger_error($err_msg,E_USER_WARNING);
323 return false;
324 }
325 /**
326 * Check if preference value fits into db field
327 */
328 if (strlen($value) > $this->val_size) {
329 $err_msg = "Oversized user's preference value."
330 ." Some preferences were not saved."
331 ." See doc/db-backend.txt or contact your system administrator.";
332 // error is not fatal. Only some preference is not saved.
333 trigger_error($err_msg,E_USER_WARNING);
334 return false;
335 }
336
337
338 if ($this->db_type == SMDB_MYSQL) {
339 $query = sprintf("REPLACE INTO %s (%s, %s, %s) ".
340 "VALUES('%s','%s','%s')",
341 $this->table,
342 $this->user_field,
343 $this->key_field,
344 $this->val_field,
345 $this->dbh->quoteString($user),
346 $this->dbh->quoteString($key),
347 $this->dbh->quoteString($value));
348
349 $res = $this->dbh->simpleQuery($query);
350 if(DB::isError($res)) {
351 $this->failQuery($res);
352 }
353 } elseif ($this->db_type == SMDB_PGSQL) {
354 $this->dbh->simpleQuery("BEGIN TRANSACTION");
355 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
356 $this->table,
357 $this->user_field,
358 $this->dbh->quoteString($user),
359 $this->key_field,
360 $this->dbh->quoteString($key));
361 $res = $this->dbh->simpleQuery($query);
362 if (DB::isError($res)) {
363 $this->dbh->simpleQuery("ROLLBACK TRANSACTION");
364 $this->failQuery($res);
365 }
366 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
367 $this->table,
368 $this->user_field,
369 $this->key_field,
370 $this->val_field,
371 $this->dbh->quoteString($user),
372 $this->dbh->quoteString($key),
373 $this->dbh->quoteString($value));
374 $res = $this->dbh->simpleQuery($query);
375 if (DB::isError($res)) {
376 $this->dbh->simpleQuery("ROLLBACK TRANSACTION");
377 $this->failQuery($res);
378 }
379 $this->dbh->simpleQuery("COMMIT TRANSACTION");
380 } else {
381 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
382 $this->table,
383 $this->user_field,
384 $this->dbh->quoteString($user),
385 $this->key_field,
386 $this->dbh->quoteString($key));
387 $res = $this->dbh->simpleQuery($query);
388 if (DB::isError($res)) {
389 $this->failQuery($res);
390 }
391 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
392 $this->table,
393 $this->user_field,
394 $this->key_field,
395 $this->val_field,
396 $this->dbh->quoteString($user),
397 $this->dbh->quoteString($key),
398 $this->dbh->quoteString($value));
399 $res = $this->dbh->simpleQuery($query);
400 if (DB::isError($res)) {
401 $this->failQuery($res);
402 }
403 }
404
405 return true;
406 }
407
408 /**
409 * Fill preference cache array
410 * @param string $user user name
411 * @since 1.2.3
412 */
413 function fillPrefsCache($user) {
414 global $prefs_cache;
415
416 if (!$this->open()) {
417 return;
418 }
419
420 $prefs_cache = array();
421 $query = sprintf("SELECT %s as prefkey, %s as prefval FROM %s ".
422 "WHERE %s = '%s'",
423 $this->key_field,
424 $this->val_field,
425 $this->table,
426 $this->user_field,
427 $this->dbh->quoteString($user));
428 $res = $this->dbh->query($query);
429 if (DB::isError($res)) {
430 $this->failQuery($res);
431 }
432
433 while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
434 $prefs_cache[$row['prefkey']] = $row['prefval'];
435 }
436 }
437
438 } /* end class dbPrefs */
439
440
441 /**
442 * returns the value for the pref $string
443 * @ignore
444 */
445 function getPref($data_dir, $username, $string, $default = '') {
446 $db = new dbPrefs;
447 if(isset($db->error)) {
448 printf( _("Preference database error (%s). Exiting abnormally"),
449 $db->error);
450 exit;
451 }
452
453 return $db->getKey($username, $string, $default);
454 }
455
456 /**
457 * Remove the pref $string
458 * @ignore
459 */
460 function removePref($data_dir, $username, $string) {
461 global $prefs_cache;
462 $db = new dbPrefs;
463 if(isset($db->error)) {
464 $db->failQuery();
465 }
466
467 $db->deleteKey($username, $string);
468
469 if (isset($prefs_cache[$string])) {
470 unset($prefs_cache[$string]);
471 }
472
473 sqsession_register($prefs_cache , 'prefs_cache');
474 return;
475 }
476
477 /**
478 * sets the pref, $string, to $set_to
479 * @ignore
480 */
481 function setPref($data_dir, $username, $string, $set_to) {
482 global $prefs_cache;
483
484 if (isset($prefs_cache[$string]) && ($prefs_cache[$string] == $set_to)) {
485 return;
486 }
487
488 if ($set_to === '') {
489 removePref($data_dir, $username, $string);
490 return;
491 }
492
493 $db = new dbPrefs;
494 if(isset($db->error)) {
495 $db->failQuery();
496 }
497
498 $db->setKey($username, $string, $set_to);
499 $prefs_cache[$string] = $set_to;
500 assert_options(ASSERT_ACTIVE, 1);
501 assert_options(ASSERT_BAIL, 1);
502 assert ('$set_to == $prefs_cache[$string]');
503 sqsession_register($prefs_cache , 'prefs_cache');
504 return;
505 }
506
507 /**
508 * This checks if the prefs are available
509 * @ignore
510 */
511 function checkForPrefs($data_dir, $username) {
512 $db = new dbPrefs;
513 if(isset($db->error)) {
514 $db->failQuery();
515 }
516 }
517
518 /**
519 * Writes the Signature
520 * @ignore
521 */
522 function setSig($data_dir, $username, $number, $string) {
523 if ($number == "g") {
524 $key = '___signature___';
525 } else {
526 $key = sprintf('___sig%s___', $number);
527 }
528 setPref($data_dir, $username, $key, $string);
529 return;
530 }
531
532 /**
533 * Gets the signature
534 * @ignore
535 */
536 function getSig($data_dir, $username, $number) {
537 if ($number == "g") {
538 $key = '___signature___';
539 } else {
540 $key = sprintf('___sig%d___', $number);
541 }
542 return getPref($data_dir, $username, $key);
543 }
544
545 // vim: et ts=4