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 // Pear's full DSN syntax is one of the following:
307 // phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value
308 // phptype(syntax)://user:pass@protocol(proto_opts)/database
310 // $matches will contain:
314 // 4: hostname (and possible port number) OR protocol (and possible protocol options)
315 // 5: database name (and possible options)
316 // 6: port number (moved from match number 4)
317 // 7: options (moved from match number 5)
318 // 8: protocol (instead of hostname)
319 // 9: protocol options (moved from match number 4/8)
320 //TODO: do we care about supporting cases where no password is given? (this is a legal DSN, but causes an error below)
321 if (!preg_match('|^(.+)://(.+):(.+)@(.+)/(.+)$|i', $prefs_dsn, $matches)) {
322 $this->error
= _("Could not parse prefs DSN");
329 if (preg_match('|^(.+):(\d+)$|', $matches[4], $host_port_matches)) {
330 $matches[4] = $host_port_matches[1];
331 $matches[6] = $host_port_matches[2];
333 if (preg_match('|^(.+?)\((.+)\)$|', $matches[4], $protocol_matches)) {
334 $matches[8] = $protocol_matches[1];
335 $matches[9] = $protocol_matches[2];
339 //TODO: currently we just ignore options specified on the end of the DSN
340 if (preg_match('|^(.+?)\?(.+)$|', $matches[5], $database_name_options_matches)) {
341 $matches[5] = $database_name_options_matches[1];
342 $matches[7] = $database_name_options_matches[2];
344 if ($matches[8] === 'unix' && !empty($matches[9]))
345 $pdo_prefs_dsn = $matches[1] . ':unix_socket=' . $matches[9] . ';dbname=' . $matches[5];
347 $pdo_prefs_dsn = $matches[1] . ':host=' . $matches[4] . (!empty($matches[6]) ?
';port=' . $matches[6] : '') . ';dbname=' . $matches[5];
349 $dbh = new PDO($pdo_prefs_dsn, $matches[2], $matches[3]);
350 } catch (Exception
$e) {
351 $this->error
= $e->getMessage();
355 $dbh = DB
::connect($prefs_dsn, true);
357 if(DB
::isError($dbh)) {
358 $this->error
= DB
::errorMessage($dbh);
368 * Function used to handle database connection errors
370 * @param object PEAR Error object
373 function failQuery($res = NULL) {
376 printf(_("Preference database error (%s). Exiting abnormally"),
379 printf(_("Preference database error (%s). Exiting abnormally"),
380 ($use_pdo ?
implode(' - ', $res->errorInfo()) : DB
::errorMessage($res)));
386 * Get user's prefs setting
388 * @param string $user user name
389 * @param string $key preference name
390 * @param mixed $default (since 1.2.5) default value
392 * @return mixed preference value
395 function getKey($user, $key, $default = '') {
398 $temp = array(&$user, &$key);
399 $result = do_hook('get_pref_override', $temp);
400 if (is_null($result)) {
401 cachePrefValues($user);
403 if (isset($prefs_cache[$key])) {
404 $result = $prefs_cache[$key];
406 //FIXME: is there a justification for having two prefs hooks so close? who uses them?
407 $temp = array(&$user, &$key);
408 $result = do_hook('get_pref', $temp);
409 if (is_null($result)) {
410 if (isset($this->default[$key])) {
411 $result = $this->default[$key];
422 * Delete user's prefs setting
424 * @param string $user user name
425 * @param string $key preference name
430 function deleteKey($user, $key) {
431 global $prefs_cache, $use_pdo, $pdo_show_sql_errors;
433 if (!$this->open()) {
437 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
. ' = ?'))) {
438 if ($pdo_show_sql_errors)
439 $this->error
= implode(' - ', $this->dbh
->errorInfo());
441 $this->error
= _("Could not prepare query");
444 if (!($res = $sth->execute(array($user, $key)))) {
445 if ($pdo_show_sql_errors)
446 $this->error
= implode(' - ', $sth->errorInfo());
448 $this->error
= _("Could not execute query");
452 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
455 $this->dbh
->quoteString($user),
457 $this->dbh
->quoteString($key));
459 $res = $this->dbh
->simpleQuery($query);
460 if(DB
::isError($res)) {
461 $this->failQuery($res);
465 unset($prefs_cache[$key]);
471 * Set user's preference
473 * @param string $user user name
474 * @param string $key preference name
475 * @param mixed $value preference value
480 function setKey($user, $key, $value) {
481 global $use_pdo, $pdo_show_sql_errors;
482 if (!$this->open()) {
487 * Check if username fits into db field
489 if (strlen($user) > $this->user_size
) {
490 $this->error
= "Oversized username value."
491 ." Your preferences can't be saved."
492 ." See the administrator's manual or contact your system administrator.";
495 * Debugging function. Can be used to log all issues that trigger
496 * oversized field errors. Function should be enabled in all three
497 * strlen checks. See http://www.php.net/error-log
499 // error_log($user.'|'.$key.'|'.$value."\n",3,'/tmp/oversized_log');
502 $this->failQuery(null);
505 * Check if preference key fits into db field
507 if (strlen($key) > $this->key_size
) {
508 $err_msg = "Oversized user's preference key."
509 ." Some preferences were not saved."
510 ." See the administrator's manual or contact your system administrator.";
511 // error is not fatal. Only some preference is not saved.
512 trigger_error($err_msg,E_USER_WARNING
);
516 * Check if preference value fits into db field
518 if (strlen($value) > $this->val_size
) {
519 $err_msg = "Oversized user's preference value."
520 ." Some preferences were not saved."
521 ." See the administrator's manual or contact your system administrator.";
522 // error is not fatal. Only some preference is not saved.
523 trigger_error($err_msg,E_USER_WARNING
);
528 if ($this->db_type
== SMDB_MYSQL
) {
530 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 (?, ?, ?)'))) {
531 if ($pdo_show_sql_errors)
532 $this->error
= implode(' - ', $this->dbh
->errorInfo());
534 $this->error
= _("Could not prepare query");
537 if (!($res = $sth->execute(array($user, $key, $value)))) {
538 if ($pdo_show_sql_errors)
539 $this->error
= implode(' - ', $sth->errorInfo());
541 $this->error
= _("Could not execute query");
545 $query = sprintf("REPLACE INTO %s (%s, %s, %s) ".
546 "VALUES('%s','%s','%s')",
551 $this->dbh
->quoteString($user),
552 $this->dbh
->quoteString($key),
553 $this->dbh
->quoteString($value));
555 $res = $this->dbh
->simpleQuery($query);
556 if(DB
::isError($res)) {
557 $this->failQuery($res);
560 } elseif ($this->db_type
== SMDB_PGSQL
) {
562 if ($this->dbh
->exec('BEGIN TRANSACTION') === FALSE) {
563 if ($pdo_show_sql_errors)
564 $this->error
= implode(' - ', $this->dbh
->errorInfo());
566 $this->error
= _("Could not execute query");
569 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
. ' = ?'))) {
570 if ($pdo_show_sql_errors)
571 $this->error
= implode(' - ', $this->dbh
->errorInfo());
573 $this->error
= _("Could not prepare query");
576 if (!($res = $sth->execute(array($user, $key)))) {
577 if ($pdo_show_sql_errors)
578 $this->error
= implode(' - ', $sth->errorInfo());
580 $this->error
= _("Could not execute query");
581 $this->dbh
->exec('ROLLBACK TRANSACTION');
584 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 (?, ?, ?)'))) {
585 if ($pdo_show_sql_errors)
586 $this->error
= implode(' - ', $this->dbh
->errorInfo());
588 $this->error
= _("Could not prepare query");
591 if (!($res = $sth->execute(array($user, $key, $value)))) {
592 if ($pdo_show_sql_errors)
593 $this->error
= implode(' - ', $sth->errorInfo());
595 $this->error
= _("Could not execute query");
596 $this->dbh
->exec('ROLLBACK TRANSACTION');
599 if ($this->dbh
->exec('COMMIT TRANSACTION') === FALSE) {
600 if ($pdo_show_sql_errors)
601 $this->error
= implode(' - ', $this->dbh
->errorInfo());
603 $this->error
= _("Could not execute query");
607 $this->dbh
->simpleQuery("BEGIN TRANSACTION");
608 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
611 $this->dbh
->quoteString($user),
613 $this->dbh
->quoteString($key));
614 $res = $this->dbh
->simpleQuery($query);
615 if (DB
::isError($res)) {
616 $this->dbh
->simpleQuery("ROLLBACK TRANSACTION");
617 $this->failQuery($res);
619 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
624 $this->dbh
->quoteString($user),
625 $this->dbh
->quoteString($key),
626 $this->dbh
->quoteString($value));
627 $res = $this->dbh
->simpleQuery($query);
628 if (DB
::isError($res)) {
629 $this->dbh
->simpleQuery("ROLLBACK TRANSACTION");
630 $this->failQuery($res);
632 $this->dbh
->simpleQuery("COMMIT TRANSACTION");
636 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
. ' = ?'))) {
637 if ($pdo_show_sql_errors)
638 $this->error
= implode(' - ', $this->dbh
->errorInfo());
640 $this->error
= _("Could not prepare query");
643 if (!($res = $sth->execute(array($user, $key)))) {
644 if ($pdo_show_sql_errors)
645 $this->error
= implode(' - ', $sth->errorInfo());
647 $this->error
= _("Could not execute query");
650 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 (?, ?, ?)'))) {
651 if ($pdo_show_sql_errors)
652 $this->error
= implode(' - ', $this->dbh
->errorInfo());
654 $this->error
= _("Could not prepare query");
657 if (!($res = $sth->execute(array($user, $key, $value)))) {
658 if ($pdo_show_sql_errors)
659 $this->error
= implode(' - ', $sth->errorInfo());
661 $this->error
= _("Could not execute query");
665 $query = sprintf("DELETE FROM %s WHERE %s='%s' AND %s='%s'",
668 $this->dbh
->quoteString($user),
670 $this->dbh
->quoteString($key));
671 $res = $this->dbh
->simpleQuery($query);
672 if (DB
::isError($res)) {
673 $this->failQuery($res);
675 $query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')",
680 $this->dbh
->quoteString($user),
681 $this->dbh
->quoteString($key),
682 $this->dbh
->quoteString($value));
683 $res = $this->dbh
->simpleQuery($query);
684 if (DB
::isError($res)) {
685 $this->failQuery($res);
694 * Fill preference cache array
696 * @param string $user user name
701 function fillPrefsCache($user) {
702 global $prefs_cache, $use_pdo, $pdo_show_sql_errors;
704 if (!$this->open()) {
708 $prefs_cache = array();
710 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
. ' = ?'))) {
711 if ($pdo_show_sql_errors)
712 $this->error
= implode(' - ', $this->dbh
->errorInfo());
714 $this->error
= _("Could not prepare query");
717 if (!($res = $sth->execute(array($user)))) {
718 if ($pdo_show_sql_errors)
719 $this->error
= implode(' - ', $sth->errorInfo());
721 $this->error
= _("Could not execute query");
725 while ($row = $sth->fetch(PDO
::FETCH_ASSOC
)) {
726 $prefs_cache[$row['prefkey']] = $row['prefval'];
729 $query = sprintf("SELECT %s as prefkey, %s as prefval FROM %s ".
735 $this->dbh
->quoteString($user));
736 $res = $this->dbh
->query($query);
737 if (DB
::isError($res)) {
738 $this->failQuery($res);
741 while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC
)) {
742 $prefs_cache[$row['prefkey']] = $row['prefval'];
747 } /* end class dbPrefs */
751 * Returns the value for the requested preference
754 function getPref($data_dir, $username, $pref_name, $default = '') {
756 if(isset($db->error
)) {
757 printf( _("Preference database error (%s). Exiting abnormally"),
762 return $db->getKey($username, $pref_name, $default);
766 * Remove the desired preference setting ($pref_name)
769 function removePref($data_dir, $username, $pref_name) {
772 if(isset($db->error
)) {
776 $db->deleteKey($username, $pref_name);
778 if (isset($prefs_cache[$pref_name])) {
779 unset($prefs_cache[$pref_name]);
782 sqsession_register($prefs_cache , 'prefs_cache');
787 * Sets the desired preference setting ($pref_name) to whatever is in $value
790 function setPref($data_dir, $username, $pref_name, $value) {
793 if (isset($prefs_cache[$pref_name]) && ($prefs_cache[$pref_name] == $value)) {
798 removePref($data_dir, $username, $pref_name);
803 if(isset($db->error
)) {
807 $db->setKey($username, $pref_name, $value);
808 $prefs_cache[$pref_name] = $value;
809 assert_options(ASSERT_ACTIVE
, 1);
810 assert_options(ASSERT_BAIL
, 1);
811 assert ('$value == $prefs_cache[$pref_name]');
812 sqsession_register($prefs_cache , 'prefs_cache');
817 * This checks if the prefs are available
820 function checkForPrefs($data_dir, $username) {
822 if(isset($db->error
)) {
828 * Writes the Signature
831 function setSig($data_dir, $username, $number, $value) {
832 if ($number == "g") {
833 $key = '___signature___';
835 $key = sprintf('___sig%s___', $number);
837 setPref($data_dir, $username, $key, $value);
845 function getSig($data_dir, $username, $number) {
846 if ($number == "g") {
847 $key = '___signature___';
849 $key = sprintf('___sig%d___', $number);
851 return getPref($data_dir, $username, $key);