Squash bugs
[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 1999-2016 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 *
88 * @package squirrelmail
89 * @subpackage prefs
90 * @since 1.1.3
91 *
92 */
93 class dbPrefs {
94 /**
95 * Table used to store preferences
96 * @var string
97 */
98 var $table = 'userprefs';
99
100 /**
101 * Field used to store owner of preference
102 * @var string
103 */
104 var $user_field = 'user';
105
106 /**
107 * Field used to store preference name
108 * @var string
109 */
110 var $key_field = 'prefkey';
111
112 /**
113 * Field used to store preference value
114 * @var string
115 */
116 var $val_field = 'prefval';
117
118 /**
119 * Database connection object
120 * @var object
121 */
122 var $dbh = NULL;
123
124 /**
125 * Error messages
126 * @var string
127 */
128 var $error = NULL;
129
130 /**
131 * Database type (SMDB_* constants)
132 * Is used in setKey().
133 * @var integer
134 */
135 var $db_type = SMDB_UNKNOWN;
136
137 /**
138 * Default preferences
139 * @var array
140 */
141 var $default = Array('theme_default' => 0,
142 'include_self_reply_all' => '0',
143 'do_not_reply_to_self' => '1',
144 'show_html_default' => '0');
145
146 /**
147 * Preference owner field size
148 * @var integer
149 * @since 1.5.1
150 */
151 var $user_size = 128;
152
153 /**
154 * Preference key field size
155 * @var integer
156 * @since 1.5.1
157 */
158 var $key_size = 64;
159
160 /**
161 * Preference value field size
162 * @var integer
163 * @since 1.5.1
164 */
165 var $val_size = 65536;
166
167
168
169 /**
170 * initialize the default preferences array.
171 *
172 */
173 function dbPrefs() {
174 // Try and read the default preferences file.
175 $default_pref = SM_PATH . 'config/default_pref';
176 if (@file_exists($default_pref)) {
177 if ($file = @fopen($default_pref, 'r')) {
178 while (!feof($file)) {
179 $pref = fgets($file, 1024);
180 $i = strpos($pref, '=');
181 if ($i > 0) {
182 $this->default[trim(substr($pref, 0, $i))] = trim(substr($pref, $i + 1));
183 }
184 }
185 fclose($file);
186 }
187 }
188 }
189
190 /**
191 * initialize DB connection object
192 *
193 * @return boolean true, if object is initialized
194 *
195 */
196 function open() {
197 global $prefs_dsn, $prefs_table;
198 global $prefs_user_field, $prefs_key_field, $prefs_val_field;
199 global $prefs_user_size, $prefs_key_size, $prefs_val_size;
200
201 /* test if Pear DB class is available and freak out if it is not */
202 if (! class_exists('DB')) {
203 // same error also in abook_database.php
204 $this->error = _("Could not include PEAR database functions required for the database backend.") . "\n";
205 $this->error .= sprintf(_("Is PEAR installed, and is the include path set correctly to find %s?"),
206 'DB.php') . "\n";
207 $this->error .= _("Please contact your system administrator and report this error.");
208 return false;
209 }
210
211 if(isset($this->dbh)) {
212 return true;
213 }
214
215 if (preg_match('/^mysql/', $prefs_dsn)) {
216 $this->db_type = SMDB_MYSQL;
217 } elseif (preg_match('/^pgsql/', $prefs_dsn)) {
218 $this->db_type = SMDB_PGSQL;
219 }
220
221 if (!empty($prefs_table)) {
222 $this->table = $prefs_table;
223 }
224 if (!empty($prefs_user_field)) {
225 $this->user_field = $prefs_user_field;
226 }
227
228 // the default user field is "user", which in PostgreSQL
229 // is an identifier and causes errors if not escaped
230 //
231 if ($this->db_type == SMDB_PGSQL) {
232 $this->user_field = '"' . $this->user_field . '"';
233 }
234
235 if (!empty($prefs_key_field)) {
236 $this->key_field = $prefs_key_field;
237 }
238 if (!empty($prefs_val_field)) {
239 $this->val_field = $prefs_val_field;
240 }
241 if (!empty($prefs_user_size)) {
242 $this->user_size = (int) $prefs_user_size;
243 }
244 if (!empty($prefs_key_size)) {
245 $this->key_size = (int) $prefs_key_size;
246 }
247 if (!empty($prefs_val_size)) {
248 $this->val_size = (int) $prefs_val_size;
249 }
250 $dbh = DB::connect($prefs_dsn, true);
251
252 if(DB::isError($dbh)) {
253 $this->error = DB::errorMessage($dbh);
254 return false;
255 }
256
257 $this->dbh = $dbh;
258 return true;
259 }
260
261 /**
262 * Function used to handle database connection errors
263 *
264 * @param object PEAR Error object
265 *
266 */
267 function failQuery($res = NULL) {
268 if($res == NULL) {
269 printf(_("Preference database error (%s). Exiting abnormally"),
270 $this->error);
271 } else {
272 printf(_("Preference database error (%s). Exiting abnormally"),
273 DB::errorMessage($res));
274 }
275 exit;
276 }
277
278 /**
279 * Get user's prefs setting
280 *
281 * @param string $user user name
282 * @param string $key preference name
283 * @param mixed $default (since 1.2.5) default value
284 *
285 * @return mixed preference value
286 *
287 */
288 function getKey($user, $key, $default = '') {
289 global $prefs_cache;
290
291 $temp = array(&$user, &$key);
292 $result = do_hook('get_pref_override', $temp);
293 if (is_null($result)) {
294 cachePrefValues($user);
295
296 if (isset($prefs_cache[$key])) {
297 $result = $prefs_cache[$key];
298 } else {
299 //FIXME: is there a justification for having two prefs hooks so close? who uses them?
300 $temp = array(&$user, &$key);
301 $result = do_hook('get_pref', $temp);
302 if (is_null($result)) {
303 if (isset($this->default[$key])) {
304 $result = $this->default[$key];
305 } else {
306 $result = $default;
307 }
308 }
309 }
310 }
311 return $result;
312 }
313
314 /**
315 * Delete user's prefs setting
316 *
317 * @param string $user user name
318 * @param string $key preference name
319 *
320 * @return boolean
321 *
322 */
323 function deleteKey($user, $key) {
324 global $prefs_cache;
325
326 if (!$this->open()) {
327 return false;
328 }
329 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
330 $this->table,
331 $this->user_field,
332 $this->dbh->quoteString($user),
333 $this->key_field,
334 $this->dbh->quoteString($key));
335
336 $res = $this->dbh->simpleQuery($query);
337 if(DB::isError($res)) {
338 $this->failQuery($res);
339 }
340
341 unset($prefs_cache[$key]);
342
343 return true;
344 }
345
346 /**
347 * Set user's preference
348 *
349 * @param string $user user name
350 * @param string $key preference name
351 * @param mixed $value preference value
352 *
353 * @return boolean
354 *
355 */
356 function setKey($user, $key, $value) {
357 if (!$this->open()) {
358 return false;
359 }
360
361 /**
362 * Check if username fits into db field
363 */
364 if (strlen($user) > $this->user_size) {
365 $this->error = "Oversized username value."
366 ." Your preferences can't be saved."
367 ." See the administrator's manual or contact your system administrator.";
368
369 /**
370 * Debugging function. Can be used to log all issues that trigger
371 * oversized field errors. Function should be enabled in all three
372 * strlen checks. See http://www.php.net/error-log
373 */
374 // error_log($user.'|'.$key.'|'.$value."\n",3,'/tmp/oversized_log');
375
376 // error is fatal
377 $this->failQuery(null);
378 }
379 /**
380 * Check if preference key fits into db field
381 */
382 if (strlen($key) > $this->key_size) {
383 $err_msg = "Oversized user's preference key."
384 ." Some preferences were not saved."
385 ." See the administrator's manual or contact your system administrator.";
386 // error is not fatal. Only some preference is not saved.
387 trigger_error($err_msg,E_USER_WARNING);
388 return false;
389 }
390 /**
391 * Check if preference value fits into db field
392 */
393 if (strlen($value) > $this->val_size) {
394 $err_msg = "Oversized user's preference value."
395 ." Some preferences were not saved."
396 ." See the administrator's manual or contact your system administrator.";
397 // error is not fatal. Only some preference is not saved.
398 trigger_error($err_msg,E_USER_WARNING);
399 return false;
400 }
401
402
403 if ($this->db_type == SMDB_MYSQL) {
404 $query = sprintf("REPLACE INTO %s (%s, %s, %s) ".
405 "VALUES('%s','%s','%s')",
406 $this->table,
407 $this->user_field,
408 $this->key_field,
409 $this->val_field,
410 $this->dbh->quoteString($user),
411 $this->dbh->quoteString($key),
412 $this->dbh->quoteString($value));
413
414 $res = $this->dbh->simpleQuery($query);
415 if(DB::isError($res)) {
416 $this->failQuery($res);
417 }
418 } elseif ($this->db_type == SMDB_PGSQL) {
419 $this->dbh->simpleQuery("BEGIN TRANSACTION");
420 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
421 $this->table,
422 $this->user_field,
423 $this->dbh->quoteString($user),
424 $this->key_field,
425 $this->dbh->quoteString($key));
426 $res = $this->dbh->simpleQuery($query);
427 if (DB::isError($res)) {
428 $this->dbh->simpleQuery("ROLLBACK TRANSACTION");
429 $this->failQuery($res);
430 }
431 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
432 $this->table,
433 $this->user_field,
434 $this->key_field,
435 $this->val_field,
436 $this->dbh->quoteString($user),
437 $this->dbh->quoteString($key),
438 $this->dbh->quoteString($value));
439 $res = $this->dbh->simpleQuery($query);
440 if (DB::isError($res)) {
441 $this->dbh->simpleQuery("ROLLBACK TRANSACTION");
442 $this->failQuery($res);
443 }
444 $this->dbh->simpleQuery("COMMIT TRANSACTION");
445 } else {
446 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
447 $this->table,
448 $this->user_field,
449 $this->dbh->quoteString($user),
450 $this->key_field,
451 $this->dbh->quoteString($key));
452 $res = $this->dbh->simpleQuery($query);
453 if (DB::isError($res)) {
454 $this->failQuery($res);
455 }
456 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
457 $this->table,
458 $this->user_field,
459 $this->key_field,
460 $this->val_field,
461 $this->dbh->quoteString($user),
462 $this->dbh->quoteString($key),
463 $this->dbh->quoteString($value));
464 $res = $this->dbh->simpleQuery($query);
465 if (DB::isError($res)) {
466 $this->failQuery($res);
467 }
468 }
469
470 return true;
471 }
472
473 /**
474 * Fill preference cache array
475 *
476 * @param string $user user name
477 *
478 * @since 1.2.3
479 *
480 */
481 function fillPrefsCache($user) {
482 global $prefs_cache;
483
484 if (!$this->open()) {
485 return;
486 }
487
488 $prefs_cache = array();
489 $query = sprintf("SELECT %s as prefkey, %s as prefval FROM %s ".
490 "WHERE %s = '%s'",
491 $this->key_field,
492 $this->val_field,
493 $this->table,
494 $this->user_field,
495 $this->dbh->quoteString($user));
496 $res = $this->dbh->query($query);
497 if (DB::isError($res)) {
498 $this->failQuery($res);
499 }
500
501 while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
502 $prefs_cache[$row['prefkey']] = $row['prefval'];
503 }
504 }
505
506 } /* end class dbPrefs */
507
508
509 /**
510 * Returns the value for the requested preference
511 * @ignore
512 */
513 function getPref($data_dir, $username, $pref_name, $default = '') {
514 $db = new dbPrefs;
515 if(isset($db->error)) {
516 printf( _("Preference database error (%s). Exiting abnormally"),
517 $db->error);
518 exit;
519 }
520
521 return $db->getKey($username, $pref_name, $default);
522 }
523
524 /**
525 * Remove the desired preference setting ($pref_name)
526 * @ignore
527 */
528 function removePref($data_dir, $username, $pref_name) {
529 global $prefs_cache;
530 $db = new dbPrefs;
531 if(isset($db->error)) {
532 $db->failQuery();
533 }
534
535 $db->deleteKey($username, $pref_name);
536
537 if (isset($prefs_cache[$pref_name])) {
538 unset($prefs_cache[$pref_name]);
539 }
540
541 sqsession_register($prefs_cache , 'prefs_cache');
542 return;
543 }
544
545 /**
546 * Sets the desired preference setting ($pref_name) to whatever is in $value
547 * @ignore
548 */
549 function setPref($data_dir, $username, $pref_name, $value) {
550 global $prefs_cache;
551
552 if (isset($prefs_cache[$pref_name]) && ($prefs_cache[$pref_name] == $value)) {
553 return;
554 }
555
556 if ($value === '') {
557 removePref($data_dir, $username, $pref_name);
558 return;
559 }
560
561 $db = new dbPrefs;
562 if(isset($db->error)) {
563 $db->failQuery();
564 }
565
566 $db->setKey($username, $pref_name, $value);
567 $prefs_cache[$pref_name] = $value;
568 assert_options(ASSERT_ACTIVE, 1);
569 assert_options(ASSERT_BAIL, 1);
570 assert ('$value == $prefs_cache[$pref_name]');
571 sqsession_register($prefs_cache , 'prefs_cache');
572 return;
573 }
574
575 /**
576 * This checks if the prefs are available
577 * @ignore
578 */
579 function checkForPrefs($data_dir, $username) {
580 $db = new dbPrefs;
581 if(isset($db->error)) {
582 $db->failQuery();
583 }
584 }
585
586 /**
587 * Writes the Signature
588 * @ignore
589 */
590 function setSig($data_dir, $username, $number, $value) {
591 if ($number == "g") {
592 $key = '___signature___';
593 } else {
594 $key = sprintf('___sig%s___', $number);
595 }
596 setPref($data_dir, $username, $key, $value);
597 return;
598 }
599
600 /**
601 * Gets the signature
602 * @ignore
603 */
604 function getSig($data_dir, $username, $number) {
605 if ($number == "g") {
606 $key = '___signature___';
607 } else {
608 $key = sprintf('___sig%d___', $number);
609 }
610 return getPref($data_dir, $username, $key);
611 }