6 * This contains functions for manipulating user preferences
7 * stored in a database, accessed through the Pear DB layer
8 * or PDO, the latter taking precedence if available.
12 * The preferences table should have three columns:
17 * CREATE TABLE userprefs (user CHAR(128) NOT NULL DEFAULT '',
18 * prefkey CHAR(64) NOT NULL DEFAULT '',
19 * prefval BLOB NOT NULL DEFAULT '',
20 * primary key (user,prefkey));
22 * Configuration of databasename, username and password is done
23 * by using conf.pl or the administrator plugin
25 * Three settings that control PDO behavior can be specified in
26 * config/config_local.php if needed:
27 * boolean $disable_pdo SquirrelMail uses PDO by default to access the
28 * user preferences and address book databases, but
29 * setting this to TRUE will cause SquirrelMail to
30 * fall back to using Pear DB instead.
31 * boolean $pdo_show_sql_errors When database errors are encountered,
32 * setting this to TRUE causes the actual
33 * database error to be displayed, otherwise
34 * generic errors are displayed, preventing
35 * internal database information from being
36 * exposed. This should be enabled only for
38 * string $pdo_identifier_quote_char By default, SquirrelMail will quote
39 * table and field names in database
40 * queries with what it thinks is the
41 * appropriate quote character for the
42 * database type being used (backtick
43 * for MySQL (and thus MariaDB), double
44 * quotes for all others), but you can
45 * override the character used by
46 * putting it here, or tell SquirrelMail
47 * NOT to quote identifiers by setting
50 * @copyright 1999-2015 The SquirrelMail Project Team
51 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
53 * @package squirrelmail
59 if (!defined('SM_PATH')) define('SM_PATH','../');
61 /** Unknown database */
62 define('SMDB_UNKNOWN', 0);
64 define('SMDB_MYSQL', 1);
66 define('SMDB_PGSQL', 2);
69 * Needs either PDO or the DB functions
70 * Don't display errors here. (no code execution in functions/*.php).
71 * will handle error in dbPrefs class.
73 global $use_pdo, $disable_pdo;
74 if (empty($disable_pdo) && class_exists('PDO'))
80 @include_once
('DB.php');
82 global $prefs_are_cached, $prefs_cache;
87 function cachePrefValues($username) {
88 global $prefs_are_cached, $prefs_cache;
90 sqgetGlobalVar('prefs_are_cached', $prefs_are_cached, SQ_SESSION
);
91 if ($prefs_are_cached) {
92 sqgetGlobalVar('prefs_cache', $prefs_cache, SQ_SESSION
);
96 sqsession_unregister('prefs_cache');
97 sqsession_unregister('prefs_are_cached');
100 if(isset($db->error
)) {
101 printf( _("Preference database error (%s). Exiting abnormally"),
106 $db->fillPrefsCache($username);
107 if (isset($db->error
)) {
108 printf( _("Preference database error (%s). Exiting abnormally"),
113 $prefs_are_cached = true;
115 sqsession_register($prefs_cache, 'prefs_cache');
116 sqsession_register($prefs_are_cached, 'prefs_are_cached');
120 * Class used to handle connections to prefs database and operations with preferences
122 * @package squirrelmail
129 * Table used to store preferences
132 var $table = 'userprefs';
135 * Field used to store owner of preference
138 var $user_field = 'user';
141 * Field used to store preference name
144 var $key_field = 'prefkey';
147 * Field used to store preference value
150 var $val_field = 'prefval';
153 * Database connection object
165 * Database type (SMDB_* constants)
166 * Is used in setKey().
169 var $db_type = SMDB_UNKNOWN
;
172 * Character used to quote database table
176 var $identifier_quote_char = '';
179 * Default preferences
182 var $default = Array('theme_default' => 0,
183 'include_self_reply_all' => '0',
184 'do_not_reply_to_self' => '1',
185 'show_html_default' => '0');
188 * Preference owner field size
192 var $user_size = 128;
195 * Preference key field size
202 * Preference value field size
206 var $val_size = 65536;
211 * initialize the default preferences array.
215 // Try and read the default preferences file.
216 $default_pref = SM_PATH
. 'config/default_pref';
217 if (@file_exists
($default_pref)) {
218 if ($file = @fopen
($default_pref, 'r')) {
219 while (!feof($file)) {
220 $pref = fgets($file, 1024);
221 $i = strpos($pref, '=');
223 $this->default[trim(substr($pref, 0, $i))] = trim(substr($pref, $i +
1));
232 * initialize DB connection object
234 * @return boolean true, if object is initialized
238 global $prefs_dsn, $prefs_table, $use_pdo, $pdo_identifier_quote_char;
239 global $prefs_user_field, $prefs_key_field, $prefs_val_field;
240 global $prefs_user_size, $prefs_key_size, $prefs_val_size;
242 /* test if PDO or Pear DB classes are available and freak out if necessary */
243 if (!$use_pdo && !class_exists('DB')) {
244 // same error also in abook_database.php
245 $error = _("Could not find or include PHP PDO or PEAR database functions required for the database backend.") . "\n";
246 $error .= sprintf(_("PDO should come preinstalled with PHP version 5.1 or higher. Otherwise, is PEAR installed, and is the include path set correctly to find %s?"), 'DB.php') . "\n";
247 $error .= _("Please contact your system administrator and report this error.");
251 if(isset($this->dbh
)) {
255 if (strpos($prefs_dsn, 'mysql') === 0) {
256 $this->db_type
= SMDB_MYSQL
;
257 } else if (strpos($prefs_dsn, 'pgsql') === 0) {
258 $this->db_type
= SMDB_PGSQL
;
261 // figure out identifier quoting (only used for PDO, though we could change that)
262 if (empty($pdo_identifier_quote_char)) {
263 if ($this->db_type
== SMDB_MYSQL
)
264 $this->identifier_quote_char
= '`';
266 $this->identifier_quote_char
= '"';
267 } else if ($pdo_identifier_quote_char === 'none')
268 $this->identifier_quote_char
= '';
270 $this->identifier_quote_char
= $pdo_identifier_quote_char;
272 if (!empty($prefs_table)) {
273 $this->table
= $prefs_table;
275 if (!empty($prefs_user_field)) {
276 $this->user_field
= $prefs_user_field;
279 // the default user field is "user", which in PostgreSQL
280 // is an identifier and causes errors if not escaped
282 if ($this->db_type
== SMDB_PGSQL
) {
283 $this->user_field
= '"' . $this->user_field
. '"';
286 if (!empty($prefs_key_field)) {
287 $this->key_field
= $prefs_key_field;
289 if (!empty($prefs_val_field)) {
290 $this->val_field
= $prefs_val_field;
292 if (!empty($prefs_user_size)) {
293 $this->user_size
= (int) $prefs_user_size;
295 if (!empty($prefs_key_size)) {
296 $this->key_size
= (int) $prefs_key_size;
298 if (!empty($prefs_val_size)) {
299 $this->val_size
= (int) $prefs_val_size;
302 // connect, create database connection object
305 // parse and convert DSN to PDO style
306 // $matches will contain:
312 //TODO: add support for unix_socket and charset
313 if (!preg_match('|^(.+)://(.+):(.+)@(.+)/(.+)$|i', $prefs_dsn, $matches)) {
314 $this->error
= _("Could not parse prefs DSN");
317 if (preg_match('|^(.+):(\d+)$|', $matches[4], $host_port_matches)) {
318 $matches[4] = $host_port_matches[1];
319 $matches[6] = $host_port_matches[2];
322 $pdo_prefs_dsn = $matches[1] . ':host=' . $matches[4] . (!empty($matches[6]) ?
';port=' . $matches[6] : '') . ';dbname=' . $matches[5];
324 $dbh = new PDO($pdo_prefs_dsn, $matches[2], $matches[3]);
325 } catch (Exception
$e) {
326 $this->error
= $e->getMessage();
330 $dbh = DB
::connect($prefs_dsn, true);
332 if(DB
::isError($dbh)) {
333 $this->error
= DB
::errorMessage($dbh);
343 * Function used to handle database connection errors
345 * @param object PEAR Error object
348 function failQuery($res = NULL) {
351 printf(_("Preference database error (%s). Exiting abnormally"),
354 printf(_("Preference database error (%s). Exiting abnormally"),
355 ($use_pdo ?
implode(' - ', $res->errorInfo()) : DB
::errorMessage($res)));
361 * Get user's prefs setting
363 * @param string $user user name
364 * @param string $key preference name
365 * @param mixed $default (since 1.2.5) default value
367 * @return mixed preference value
370 function getKey($user, $key, $default = '') {
373 $temp = array(&$user, &$key);
374 $result = do_hook('get_pref_override', $temp);
375 if (is_null($result)) {
376 cachePrefValues($user);
378 if (isset($prefs_cache[$key])) {
379 $result = $prefs_cache[$key];
381 //FIXME: is there a justification for having two prefs hooks so close? who uses them?
382 $temp = array(&$user, &$key);
383 $result = do_hook('get_pref', $temp);
384 if (is_null($result)) {
385 if (isset($this->default[$key])) {
386 $result = $this->default[$key];
397 * Delete user's prefs setting
399 * @param string $user user name
400 * @param string $key preference name
405 function deleteKey($user, $key) {
406 global $prefs_cache, $use_pdo, $pdo_show_sql_errors;
408 if (!$this->open()) {
412 if (!($sth = $this->dbh
->prepare('DELETE FROM ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' WHERE ' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ' = ? AND ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ' = ?'))) {
413 if ($pdo_show_sql_errors)
414 $this->error
= implode(' - ', $this->dbh
->errorInfo());
416 $this->error
= _("Could not prepare query");
419 if (!($res = $sth->execute(array($user, $key)))) {
420 if ($pdo_show_sql_errors)
421 $this->error
= implode(' - ', $sth->errorInfo());
423 $this->error
= _("Could not execute query");
427 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
430 $this->dbh
->quoteString($user),
432 $this->dbh
->quoteString($key));
434 $res = $this->dbh
->simpleQuery($query);
435 if(DB
::isError($res)) {
436 $this->failQuery($res);
440 unset($prefs_cache[$key]);
446 * Set user's preference
448 * @param string $user user name
449 * @param string $key preference name
450 * @param mixed $value preference value
455 function setKey($user, $key, $value) {
456 global $use_pdo, $pdo_show_sql_errors;
457 if (!$this->open()) {
462 * Check if username fits into db field
464 if (strlen($user) > $this->user_size
) {
465 $this->error
= "Oversized username value."
466 ." Your preferences can't be saved."
467 ." See the administrator's manual or contact your system administrator.";
470 * Debugging function. Can be used to log all issues that trigger
471 * oversized field errors. Function should be enabled in all three
472 * strlen checks. See http://www.php.net/error-log
474 // error_log($user.'|'.$key.'|'.$value."\n",3,'/tmp/oversized_log');
477 $this->failQuery(null);
480 * Check if preference key fits into db field
482 if (strlen($key) > $this->key_size
) {
483 $err_msg = "Oversized user's preference key."
484 ." Some preferences were not saved."
485 ." See the administrator's manual or contact your system administrator.";
486 // error is not fatal. Only some preference is not saved.
487 trigger_error($err_msg,E_USER_WARNING
);
491 * Check if preference value fits into db field
493 if (strlen($value) > $this->val_size
) {
494 $err_msg = "Oversized user's preference value."
495 ." Some preferences were not saved."
496 ." See the administrator's manual or contact your system administrator.";
497 // error is not fatal. Only some preference is not saved.
498 trigger_error($err_msg,E_USER_WARNING
);
503 if ($this->db_type
== SMDB_MYSQL
) {
505 if (!($sth = $this->dbh
->prepare('REPLACE INTO ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' (' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ', ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ', ' . $this->identifier_quote_char
. $this->val_field
. $this->identifier_quote_char
. ') VALUES (?, ?, ?)'))) {
506 if ($pdo_show_sql_errors)
507 $this->error
= implode(' - ', $this->dbh
->errorInfo());
509 $this->error
= _("Could not prepare query");
512 if (!($res = $sth->execute(array($user, $key, $value)))) {
513 if ($pdo_show_sql_errors)
514 $this->error
= implode(' - ', $sth->errorInfo());
516 $this->error
= _("Could not execute query");
520 $query = sprintf("REPLACE INTO %s (%s, %s, %s) ".
521 "VALUES('%s','%s','%s')",
526 $this->dbh
->quoteString($user),
527 $this->dbh
->quoteString($key),
528 $this->dbh
->quoteString($value));
530 $res = $this->dbh
->simpleQuery($query);
531 if(DB
::isError($res)) {
532 $this->failQuery($res);
535 } elseif ($this->db_type
== SMDB_PGSQL
) {
537 if ($this->dbh
->exec('BEGIN TRANSACTION') === FALSE) {
538 if ($pdo_show_sql_errors)
539 $this->error
= implode(' - ', $this->dbh
->errorInfo());
541 $this->error
= _("Could not execute query");
544 if (!($sth = $this->dbh
->prepare('DELETE FROM ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' WHERE ' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ' = ? AND ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ' = ?'))) {
545 if ($pdo_show_sql_errors)
546 $this->error
= implode(' - ', $this->dbh
->errorInfo());
548 $this->error
= _("Could not prepare query");
551 if (!($res = $sth->execute(array($user, $key)))) {
552 if ($pdo_show_sql_errors)
553 $this->error
= implode(' - ', $sth->errorInfo());
555 $this->error
= _("Could not execute query");
556 $this->dbh
->exec('ROLLBACK TRANSACTION');
559 if (!($sth = $this->dbh
->prepare('INSERT INTO ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' (' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ', ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ', ' . $this->identifier_quote_char
. $this->val_field
. $this->identifier_quote_char
. ') VALUES (?, ?, ?)'))) {
560 if ($pdo_show_sql_errors)
561 $this->error
= implode(' - ', $this->dbh
->errorInfo());
563 $this->error
= _("Could not prepare query");
566 if (!($res = $sth->execute(array($user, $key, $value)))) {
567 if ($pdo_show_sql_errors)
568 $this->error
= implode(' - ', $sth->errorInfo());
570 $this->error
= _("Could not execute query");
571 $this->dbh
->exec('ROLLBACK TRANSACTION');
574 if ($this->dbh
->exec('COMMIT TRANSACTION') === FALSE) {
575 if ($pdo_show_sql_errors)
576 $this->error
= implode(' - ', $this->dbh
->errorInfo());
578 $this->error
= _("Could not execute query");
582 $this->dbh
->simpleQuery("BEGIN TRANSACTION");
583 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
586 $this->dbh
->quoteString($user),
588 $this->dbh
->quoteString($key));
589 $res = $this->dbh
->simpleQuery($query);
590 if (DB
::isError($res)) {
591 $this->dbh
->simpleQuery("ROLLBACK TRANSACTION");
592 $this->failQuery($res);
594 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
599 $this->dbh
->quoteString($user),
600 $this->dbh
->quoteString($key),
601 $this->dbh
->quoteString($value));
602 $res = $this->dbh
->simpleQuery($query);
603 if (DB
::isError($res)) {
604 $this->dbh
->simpleQuery("ROLLBACK TRANSACTION");
605 $this->failQuery($res);
607 $this->dbh
->simpleQuery("COMMIT TRANSACTION");
611 if (!($sth = $this->dbh
->prepare('DELETE FROM ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' WHERE ' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ' = ? AND ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ' = ?'))) {
612 if ($pdo_show_sql_errors)
613 $this->error
= implode(' - ', $this->dbh
->errorInfo());
615 $this->error
= _("Could not prepare query");
618 if (!($res = $sth->execute(array($user, $key)))) {
619 if ($pdo_show_sql_errors)
620 $this->error
= implode(' - ', $sth->errorInfo());
622 $this->error
= _("Could not execute query");
625 if (!($sth = $this->dbh
->prepare('INSERT INTO ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' (' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ', ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ', ' . $this->identifier_quote_char
. $this->val_field
. $this->identifier_quote_char
. ') VALUES (?, ?, ?)'))) {
626 if ($pdo_show_sql_errors)
627 $this->error
= implode(' - ', $this->dbh
->errorInfo());
629 $this->error
= _("Could not prepare query");
632 if (!($res = $sth->execute(array($user, $key, $value)))) {
633 if ($pdo_show_sql_errors)
634 $this->error
= implode(' - ', $sth->errorInfo());
636 $this->error
= _("Could not execute query");
640 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
643 $this->dbh
->quoteString($user),
645 $this->dbh
->quoteString($key));
646 $res = $this->dbh
->simpleQuery($query);
647 if (DB
::isError($res)) {
648 $this->failQuery($res);
650 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
655 $this->dbh
->quoteString($user),
656 $this->dbh
->quoteString($key),
657 $this->dbh
->quoteString($value));
658 $res = $this->dbh
->simpleQuery($query);
659 if (DB
::isError($res)) {
660 $this->failQuery($res);
669 * Fill preference cache array
671 * @param string $user user name
676 function fillPrefsCache($user) {
677 global $prefs_cache, $use_pdo, $pdo_show_sql_errors;
679 if (!$this->open()) {
683 $prefs_cache = array();
685 if (!($sth = $this->dbh
->prepare('SELECT ' . $this->identifier_quote_char
. $this->key_field
. $this->identifier_quote_char
. ' AS prefkey, ' . $this->identifier_quote_char
. $this->val_field
. $this->identifier_quote_char
. ' AS prefval FROM ' . $this->identifier_quote_char
. $this->table
. $this->identifier_quote_char
. ' WHERE ' . $this->identifier_quote_char
. $this->user_field
. $this->identifier_quote_char
. ' = ?'))) {
686 if ($pdo_show_sql_errors)
687 $this->error
= implode(' - ', $this->dbh
->errorInfo());
689 $this->error
= _("Could not prepare query");
692 if (!($res = $sth->execute(array($user)))) {
693 if ($pdo_show_sql_errors)
694 $this->error
= implode(' - ', $sth->errorInfo());
696 $this->error
= _("Could not execute query");
700 while ($row = $sth->fetch(PDO
::FETCH_ASSOC
)) {
701 $prefs_cache[$row['prefkey']] = $row['prefval'];
704 $query = sprintf("SELECT %s as prefkey, %s as prefval FROM %s ".
710 $this->dbh
->quoteString($user));
711 $res = $this->dbh
->query($query);
712 if (DB
::isError($res)) {
713 $this->failQuery($res);
716 while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC
)) {
717 $prefs_cache[$row['prefkey']] = $row['prefval'];
722 } /* end class dbPrefs */
726 * Returns the value for the requested preference
729 function getPref($data_dir, $username, $pref_name, $default = '') {
731 if(isset($db->error
)) {
732 printf( _("Preference database error (%s). Exiting abnormally"),
737 return $db->getKey($username, $pref_name, $default);
741 * Remove the desired preference setting ($pref_name)
744 function removePref($data_dir, $username, $pref_name) {
747 if(isset($db->error
)) {
751 $db->deleteKey($username, $pref_name);
753 if (isset($prefs_cache[$pref_name])) {
754 unset($prefs_cache[$pref_name]);
757 sqsession_register($prefs_cache , 'prefs_cache');
762 * Sets the desired preference setting ($pref_name) to whatever is in $value
765 function setPref($data_dir, $username, $pref_name, $value) {
768 if (isset($prefs_cache[$pref_name]) && ($prefs_cache[$pref_name] == $value)) {
773 removePref($data_dir, $username, $pref_name);
778 if(isset($db->error
)) {
782 $db->setKey($username, $pref_name, $value);
783 $prefs_cache[$pref_name] = $value;
784 assert_options(ASSERT_ACTIVE
, 1);
785 assert_options(ASSERT_BAIL
, 1);
786 assert ('$value == $prefs_cache[$pref_name]');
787 sqsession_register($prefs_cache , 'prefs_cache');
792 * This checks if the prefs are available
795 function checkForPrefs($data_dir, $username) {
797 if(isset($db->error
)) {
803 * Writes the Signature
806 function setSig($data_dir, $username, $number, $value) {
807 if ($number == "g") {
808 $key = '___signature___';
810 $key = sprintf('___sig%s___', $number);
812 setPref($data_dir, $username, $key, $value);
820 function getSig($data_dir, $username, $number) {
821 if ($number == "g") {
822 $key = '___signature___';
824 $key = sprintf('___sig%d___', $number);
826 return getPref($data_dir, $username, $key);