4 +-----------------------------------------------------------------------+
5 | program/include/rcube_user.inc |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2010, 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.php 4554 2011-02-16 09:42:31Z alec $
25 * Class representing a system user
28 * @author Thomas Bruederli <roundcube@gmail.com>
34 public $language = null;
37 * Holds database connection.
47 * @param int $id User id
48 * @param array $sql_arr SQL result set
50 function __construct($id = null, $sql_arr = null)
52 $this->db = rcmail::get_instance()->get_dbh();
54 if ($id && !$sql_arr) {
55 $sql_result = $this->db->query(
56 "SELECT * FROM ".get_table_name('users')." WHERE user_id = ?", $id);
57 $sql_arr = $this->db->fetch_assoc($sql_result);
60 if (!empty($sql_arr)) {
61 $this->ID = $sql_arr['user_id'];
62 $this->data = $sql_arr;
63 $this->language = $sql_arr['language'];
69 * Build a user name string (as e-mail address)
71 * @param string $part Username part (empty or 'local' or 'domain')
72 * @return string Full user name or its part
74 function get_username($part = null)
76 if ($this->data['username']) {
77 list($local, $domain) = explode('@', $this->data['username']);
79 // at least we should always have the local part
80 if ($part == 'local') {
83 // if no domain was provided...
85 $rcmail = rcmail::get_instance();
86 $domain = $rcmail->config->mail_domain($this->data['mail_host']);
89 if ($part == 'domain') {
94 return $local . '@' . $domain;
104 * Get the preferences saved for this user
106 * @return array Hash array with prefs
110 if (!empty($this->language))
111 $prefs = array('language' => $this->language);
113 if ($this->ID && $this->data['preferences'])
114 $prefs += (array)unserialize($this->data['preferences']);
121 * Write the given user prefs to the user's record
123 * @param array $a_user_prefs User prefs to save
124 * @return boolean True on success, False on failure
126 function save_prefs($a_user_prefs)
131 $config = rcmail::get_instance()->config;
132 $old_prefs = (array)$this->get_prefs();
134 // merge (partial) prefs array with existing settings
135 $save_prefs = $a_user_prefs + $old_prefs;
136 unset($save_prefs['language']);
138 // don't save prefs with default values if they haven't been changed yet
139 foreach ($a_user_prefs as $key => $value) {
140 if (!isset($old_prefs[$key]) && ($value == $config->get($key)))
141 unset($save_prefs[$key]);
144 $save_prefs = serialize($save_prefs);
147 "UPDATE ".get_table_name('users').
148 " SET preferences = ?".
150 " WHERE user_id = ?",
152 $_SESSION['language'],
155 $this->language = $_SESSION['language'];
157 if ($this->db->affected_rows()) {
158 $config->set_user_prefs($a_user_prefs);
159 $this->data['preferences'] = $save_prefs;
168 * Get default identity of this user
170 * @param int $id Identity ID. If empty, the default identity is returned
171 * @return array Hash array with all cols of the identity record
173 function get_identity($id = null)
175 $result = $this->list_identities($id ? sprintf('AND identity_id = %d', $id) : '');
181 * Return a list of all identities linked with this user
183 * @param string $sql_add Optional WHERE clauses
184 * @return array List of identities
186 function list_identities($sql_add = '')
190 $sql_result = $this->db->query(
191 "SELECT * FROM ".get_table_name('identities').
192 " WHERE del <> 1 AND user_id = ?".
193 ($sql_add ? " ".$sql_add : "").
194 " ORDER BY ".$this->db->quoteIdentifier('standard')." DESC, name ASC, identity_id ASC",
197 while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
198 $result[] = $sql_arr;
206 * Update a specific identity record
208 * @param int $iid Identity ID
209 * @param array $data Hash array with col->value pairs to save
210 * @return boolean True if saved successfully, false if nothing changed
212 function update_identity($iid, $data)
217 $query_cols = $query_params = array();
219 foreach ((array)$data as $col => $value) {
220 $query_cols[] = $this->db->quoteIdentifier($col) . ' = ?';
221 $query_params[] = $value;
223 $query_params[] = $iid;
224 $query_params[] = $this->ID;
226 $sql = "UPDATE ".get_table_name('identities').
227 " SET changed = ".$this->db->now().", ".join(', ', $query_cols).
228 " WHERE identity_id = ?".
232 call_user_func_array(array($this->db, 'query'),
233 array_merge(array($sql), $query_params));
235 return $this->db->affected_rows();
240 * Create a new identity record linked with this user
242 * @param array $data Hash array with col->value pairs to save
243 * @return int The inserted identity ID or false on error
245 function insert_identity($data)
250 unset($data['user_id']);
252 $insert_cols = $insert_values = array();
253 foreach ((array)$data as $col => $value) {
254 $insert_cols[] = $this->db->quoteIdentifier($col);
255 $insert_values[] = $value;
257 $insert_cols[] = 'user_id';
258 $insert_values[] = $this->ID;
260 $sql = "INSERT INTO ".get_table_name('identities').
261 " (changed, ".join(', ', $insert_cols).")".
262 " VALUES (".$this->db->now().", ".join(', ', array_pad(array(), sizeof($insert_values), '?')).")";
264 call_user_func_array(array($this->db, 'query'),
265 array_merge(array($sql), $insert_values));
267 return $this->db->insert_id('identities');
272 * Mark the given identity as deleted
274 * @param int $iid Identity ID
275 * @return boolean True if deleted successfully, false if nothing changed
277 function delete_identity($iid)
282 $sql_result = $this->db->query(
283 "SELECT count(*) AS ident_count FROM ".get_table_name('identities').
284 " WHERE user_id = ? AND del <> 1",
287 $sql_arr = $this->db->fetch_assoc($sql_result);
289 // we'll not delete last identity
290 if ($sql_arr['ident_count'] <= 1)
294 "UPDATE ".get_table_name('identities').
295 " SET del = 1, changed = ".$this->db->now().
296 " WHERE user_id = ?".
297 " AND identity_id = ?",
301 return $this->db->affected_rows();
306 * Make this identity the default one for this user
308 * @param int $iid The identity ID
310 function set_default($iid)
312 if ($this->ID && $iid) {
314 "UPDATE ".get_table_name('identities').
315 " SET ".$this->db->quoteIdentifier('standard')." = '0'".
316 " WHERE user_id = ?".
317 " AND identity_id <> ?".
326 * Update user's last_login timestamp
332 "UPDATE ".get_table_name('users').
333 " SET last_login = ".$this->db->now().
334 " WHERE user_id = ?",
341 * Clear the saved object state
351 * Find a user record matching the given name and host
353 * @param string $user IMAP user name
354 * @param string $host IMAP host name
355 * @return rcube_user New user instance
357 static function query($user, $host)
359 $dbh = rcmail::get_instance()->get_dbh();
361 // use BINARY (case-sensitive) comparison on MySQL, other engines are case-sensitive
362 $mod = preg_match('/^mysql/', $dbh->db_provider) ? 'BINARY' : '';
364 // query for matching user name
365 $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host = ? AND %s = $mod ?";
366 $sql_result = $dbh->query(sprintf($query, 'username'), $host, $user);
368 // query for matching alias
369 if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
370 $sql_result = $dbh->query(sprintf($query, 'alias'), $host, $user);
371 $sql_arr = $dbh->fetch_assoc($sql_result);
374 // user already registered -> overwrite username
376 return new rcube_user($sql_arr['user_id'], $sql_arr);
383 * Create a new user record and return a rcube_user instance
385 * @param string $user IMAP user name
386 * @param string $host IMAP host
387 * @return rcube_user New user instance
389 static function create($user, $host)
393 $rcmail = rcmail::get_instance();
395 // try to resolve user in virtuser table and file
396 if ($email_list = self::user2email($user, false, true)) {
397 $user_email = is_array($email_list[0]) ? $email_list[0]['email'] : $email_list[0];
400 $data = $rcmail->plugins->exec_hook('user_create',
401 array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
403 // plugin aborted this operation
407 $user_name = $data['user_name'];
408 $user_email = $data['user_email'];
410 $dbh = $rcmail->get_dbh();
413 "INSERT INTO ".get_table_name('users').
414 " (created, last_login, username, mail_host, alias, language)".
415 " VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
416 strip_newlines($user),
417 strip_newlines($host),
418 strip_newlines($data['alias'] ? $data['alias'] : $user_email),
419 strip_newlines($data['language'] ? $data['language'] : $_SESSION['language']));
421 if ($user_id = $dbh->insert_id('users')) {
422 // create rcube_user instance to make plugin hooks work
423 $user_instance = new rcube_user($user_id);
424 $rcmail->user = $user_instance;
426 $mail_domain = $rcmail->config->mail_domain($host);
428 if ($user_email == '') {
429 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
431 if ($user_name == '') {
432 $user_name = $user != $user_email ? $user : '';
435 if (empty($email_list))
436 $email_list[] = strip_newlines($user_email);
437 // identities_level check
438 else if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
439 $email_list = array($email_list[0]);
441 // create new identities records
443 foreach ($email_list as $row) {
446 if (is_array($row)) {
450 $record['email'] = $row;
453 if (empty($record['name']))
454 $record['name'] = $user_name;
455 $record['name'] = strip_newlines($record['name']);
456 $record['user_id'] = $user_id;
457 $record['standard'] = $standard;
459 $plugin = $rcmail->plugins->exec_hook('identity_create',
460 array('login' => true, 'record' => $record));
462 if (!$plugin['abort'] && $plugin['record']['email']) {
463 $rcmail->user->insert_identity($plugin['record']);
474 'message' => "Failed to create new user"), true, false);
477 return $user_id ? $user_instance : false;
482 * Resolve username using a virtuser plugins
484 * @param string $email E-mail address to resolve
485 * @return string Resolved IMAP username
487 static function email2user($email)
489 $rcmail = rcmail::get_instance();
490 $plugin = $rcmail->plugins->exec_hook('email2user',
491 array('email' => $email, 'user' => NULL));
493 return $plugin['user'];
498 * Resolve e-mail address from virtuser plugins
500 * @param string $user User name
501 * @param boolean $first If true returns first found entry
502 * @param boolean $extended If true returns email as array (email and name for identity)
503 * @return mixed Resolved e-mail address string or array of strings
505 static function user2email($user, $first=true, $extended=false)
507 $rcmail = rcmail::get_instance();
508 $plugin = $rcmail->plugins->exec_hook('user2email',
509 array('email' => NULL, 'user' => $user,
510 'first' => $first, 'extended' => $extended));
512 return empty($plugin['email']) ? NULL : $plugin['email'];