4 +-----------------------------------------------------------------------+
5 | program/include/rcube_user.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | This class represents a system user linked and provides access |
13 | to the related database records. |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
19 $Id: rcube_user.inc 933 2007-11-29 14:17:32Z thomasb $
25 * Class representing a system user
28 * @author Thomas Bruederli <roundcube@gmail.com>
34 public $language = null;
42 * @param object DB Database connection
44 function __construct($id = null, $sql_arr = null)
46 $this->db = rcmail::get_instance()->get_dbh();
50 $sql_result = $this->db->query("SELECT * FROM ".get_table_name('users')." WHERE user_id=?", $id);
51 $sql_arr = $this->db->fetch_assoc($sql_result);
56 $this->ID = $sql_arr['user_id'];
57 $this->data = $sql_arr;
58 $this->language = $sql_arr['language'];
64 * Build a user name string (as e-mail address)
66 * @return string Full user name
68 function get_username()
70 return $this->data['username'] ? $this->data['username'] . (!strpos($this->data['username'], '@') ? '@'.$this->data['mail_host'] : '') : false;
75 * Get the preferences saved for this user
77 * @return array Hash array with prefs
81 if (!empty($this->language))
82 $prefs = array('language' => $this->language);
84 if ($this->ID && $this->data['preferences'])
85 $prefs += (array)unserialize($this->data['preferences']);
92 * Write the given user prefs to the user's record
94 * @param array User prefs to save
95 * @return boolean True on success, False on failure
97 function save_prefs($a_user_prefs)
102 $config = rcmail::get_instance()->config;
103 $old_prefs = (array)$this->get_prefs();
105 // merge (partial) prefs array with existing settings
106 $save_prefs = $a_user_prefs + $old_prefs;
107 unset($save_prefs['language']);
109 // don't save prefs with default values if they haven't been changed yet
110 foreach ($a_user_prefs as $key => $value) {
111 if (!isset($old_prefs[$key]) && ($value == $config->get($key)))
112 unset($save_prefs[$key]);
116 "UPDATE ".get_table_name('users')."
120 serialize($save_prefs),
121 $_SESSION['language'],
124 $this->language = $_SESSION['language'];
125 if ($this->db->affected_rows()) {
126 $config->merge($a_user_prefs);
135 * Get default identity of this user
137 * @param int Identity ID. If empty, the default identity is returned
138 * @return array Hash array with all cols of the
140 function get_identity($id = null)
142 $sql_result = $this->list_identities($id ? sprintf('AND identity_id=%d', $id) : '');
143 return $this->db->fetch_assoc($sql_result);
148 * Return a list of all identities linked with this user
150 * @return array List of identities
152 function list_identities($sql_add = '')
154 // get contacts from DB
155 $sql_result = $this->db->query(
156 "SELECT * FROM ".get_table_name('identities')."
160 ORDER BY ".$this->db->quoteIdentifier('standard')." DESC, name ASC, identity_id ASC",
168 * Update a specific identity record
170 * @param int Identity ID
171 * @param array Hash array with col->value pairs to save
172 * @return boolean True if saved successfully, false if nothing changed
174 function update_identity($iid, $data)
179 $write_sql = array();
181 foreach ((array)$data as $col => $value)
183 $write_sql[] = sprintf("%s=%s",
184 $this->db->quoteIdentifier($col),
185 $this->db->quote($value));
189 "UPDATE ".get_table_name('identities')."
190 SET ".join(', ', $write_sql)."
197 return $this->db->affected_rows();
202 * Create a new identity record linked with this user
204 * @param array Hash array with col->value pairs to save
205 * @return int The inserted identity ID or false on error
207 function insert_identity($data)
212 $insert_cols = $insert_values = array();
213 foreach ((array)$data as $col => $value)
215 $insert_cols[] = $this->db->quoteIdentifier($col);
216 $insert_values[] = $this->db->quote($value);
220 "INSERT INTO ".get_table_name('identities')."
221 (user_id, ".join(', ', $insert_cols).")
222 VALUES (?, ".join(', ', $insert_values).")",
225 return $this->db->insert_id(get_sequence_name('identities'));
230 * Mark the given identity as deleted
232 * @param int Identity ID
233 * @return boolean True if deleted successfully, false if nothing changed
235 function delete_identity($iid)
240 if (!$this->ID || $this->ID == '')
243 $sql_result = $this->db->query("SELECT count(*) AS ident_count FROM " .
244 get_table_name('identities') .
245 " WHERE user_id = ? AND del <> 1",
248 $sql_arr = $this->db->fetch_assoc($sql_result);
249 if ($sql_arr['ident_count'] <= 1)
253 "UPDATE ".get_table_name('identities')."
260 return $this->db->affected_rows();
265 * Make this identity the default one for this user
267 * @param int The identity ID
269 function set_default($iid)
271 if ($this->ID && $iid)
274 "UPDATE ".get_table_name('identities')."
275 SET ".$this->db->quoteIdentifier('standard')."='0'
286 * Update user's last_login timestamp
293 "UPDATE ".get_table_name('users')."
294 SET last_login=".$this->db->now()."
302 * Clear the saved object state
312 * Find a user record matching the given name and host
314 * @param string IMAP user name
315 * @param string IMAP host name
316 * @return object rcube_user New user instance
318 static function query($user, $host)
320 $dbh = rcmail::get_instance()->get_dbh();
322 // query for matching user name
323 $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host=? AND %s=?";
324 $sql_result = $dbh->query(sprintf($query, 'username'), $host, $user);
326 // query for matching alias
327 if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
328 $sql_result = $dbh->query(sprintf($query, 'alias'), $host, $user);
329 $sql_arr = $dbh->fetch_assoc($sql_result);
332 // user already registered -> overwrite username
334 return new rcube_user($sql_arr['user_id'], $sql_arr);
341 * Create a new user record and return a rcube_user instance
343 * @param string IMAP user name
344 * @param string IMAP host
345 * @return object rcube_user New user instance
347 static function create($user, $host)
350 $rcmail = rcmail::get_instance();
351 $dbh = $rcmail->get_dbh();
353 // try to resolve user in virtusertable
354 if ($rcmail->config->get('virtuser_file') && !strpos($user, '@'))
355 $user_email = rcube_user::user2email($user);
358 "INSERT INTO ".get_table_name('users')."
359 (created, last_login, username, mail_host, alias, language)
360 VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
361 strip_newlines($user),
362 strip_newlines($host),
363 strip_newlines($user_email),
364 $_SESSION['language']);
366 if ($user_id = $dbh->insert_id(get_sequence_name('users')))
368 $mail_domain = $rcmail->config->mail_domain($host);
371 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
373 $user_name = $user != $user_email ? $user : '';
375 // try to resolve the e-mail address from the virtuser table
376 if (($virtuser_query = $rcmail->config->get('virtuser_query'))
377 && ($sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query)))
378 && ($dbh->num_rows() > 0))
381 while ($sql_arr = $dbh->fetch_array($sql_result))
384 "INSERT INTO ".get_table_name('identities')."
385 (user_id, del, standard, name, email)
386 VALUES (?, 0, ?, ?, ?)",
389 strip_newlines($user_name),
390 preg_replace('/^@/', $user . '@', $sql_arr[0]));
396 // also create new identity records
398 "INSERT INTO ".get_table_name('identities')."
399 (user_id, del, standard, name, email)
400 VALUES (?, 0, 1, ?, ?)",
402 strip_newlines($user_name),
403 strip_newlines($user_email));
413 'message' => "Failed to create new user"), true, false);
416 return $user_id ? new rcube_user($user_id) : false;
421 * Resolve username using a virtuser table
423 * @param string E-mail address to resolve
424 * @return string Resolved IMAP username
426 static function email2user($email)
429 $r = self::findinvirtual('^' . quotemeta($email) . '[[:space:]]');
431 for ($i=0; $i<count($r); $i++)
433 $data = trim($r[$i]);
434 $arr = preg_split('/\s+/', $data);
437 $user = trim($arr[count($arr)-1]);
447 * Resolve e-mail address from virtuser table
449 * @param string User name
450 * @return string Resolved e-mail address
452 static function user2email($user)
455 $r = self::findinvirtual('[[:space:]]' . quotemeta($user) . '[[:space:]]*$');
457 for ($i=0; $i<count($r); $i++)
460 $arr = preg_split('/\s+/', $data);
463 $email = trim(str_replace('\\@', '@', $arr[0]));
473 * Find matches of the given pattern in virtuser table
475 * @param string Regular expression to search for
476 * @return array Matching entries
478 private static function findinvirtual($pattern)
483 if ($virtuser_file = rcmail::get_instance()->config->get('virtuser_file'))
484 $virtual = file($virtuser_file);
489 // check each line for matches
490 foreach ($virtual as $line)
493 if (empty($line) || $line{0}=='#')
496 if (eregi($pattern, $line))