4 +-----------------------------------------------------------------------+
5 | program/include/rcube_user.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2009, 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 identity record
140 function get_identity($id = null)
142 $result = $this->list_identities($id ? sprintf('AND identity_id=%d', $id) : '');
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",
164 while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
165 $result[] = $sql_arr;
173 * Update a specific identity record
175 * @param int Identity ID
176 * @param array Hash array with col->value pairs to save
177 * @return boolean True if saved successfully, false if nothing changed
179 function update_identity($iid, $data)
184 $query_cols = $query_params = array();
186 foreach ((array)$data as $col => $value)
188 $query_cols[] = $this->db->quoteIdentifier($col) . '=?';
189 $query_params[] = $value;
191 $query_params[] = $iid;
192 $query_params[] = $this->ID;
194 $sql = "UPDATE ".get_table_name('identities')."
195 SET ".join(', ', $query_cols)."
200 call_user_func_array(array($this->db, 'query'),
201 array_merge(array($sql), $query_params));
203 return $this->db->affected_rows();
208 * Create a new identity record linked with this user
210 * @param array Hash array with col->value pairs to save
211 * @return int The inserted identity ID or false on error
213 function insert_identity($data)
218 $insert_cols = $insert_values = array();
219 foreach ((array)$data as $col => $value)
221 $insert_cols[] = $this->db->quoteIdentifier($col);
222 $insert_values[] = $value;
224 $insert_cols[] = 'user_id';
225 $insert_values[] = $this->ID;
227 $sql = "INSERT INTO ".get_table_name('identities')."
228 (".join(', ', $insert_cols).")
229 VALUES (".join(', ', array_pad(array(), sizeof($insert_values), '?')).")";
231 call_user_func_array(array($this->db, 'query'),
232 array_merge(array($sql), $insert_values));
234 return $this->db->insert_id('identities');
239 * Mark the given identity as deleted
241 * @param int Identity ID
242 * @return boolean True if deleted successfully, false if nothing changed
244 function delete_identity($iid)
249 if (!$this->ID || $this->ID == '')
252 $sql_result = $this->db->query("SELECT count(*) AS ident_count FROM " .
253 get_table_name('identities') .
254 " WHERE user_id = ? AND del <> 1",
257 $sql_arr = $this->db->fetch_assoc($sql_result);
258 if ($sql_arr['ident_count'] <= 1)
262 "UPDATE ".get_table_name('identities')."
269 return $this->db->affected_rows();
274 * Make this identity the default one for this user
276 * @param int The identity ID
278 function set_default($iid)
280 if ($this->ID && $iid)
283 "UPDATE ".get_table_name('identities')."
284 SET ".$this->db->quoteIdentifier('standard')."='0'
295 * Update user's last_login timestamp
302 "UPDATE ".get_table_name('users')."
303 SET last_login=".$this->db->now()."
311 * Clear the saved object state
321 * Find a user record matching the given name and host
323 * @param string IMAP user name
324 * @param string IMAP host name
325 * @return object rcube_user New user instance
327 static function query($user, $host)
329 $dbh = rcmail::get_instance()->get_dbh();
331 // query for matching user name
332 $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host=? AND %s=?";
333 $sql_result = $dbh->query(sprintf($query, 'username'), $host, $user);
335 // query for matching alias
336 if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
337 $sql_result = $dbh->query(sprintf($query, 'alias'), $host, $user);
338 $sql_arr = $dbh->fetch_assoc($sql_result);
341 // user already registered -> overwrite username
343 return new rcube_user($sql_arr['user_id'], $sql_arr);
350 * Create a new user record and return a rcube_user instance
352 * @param string IMAP user name
353 * @param string IMAP host
354 * @return object rcube_user New user instance
356 static function create($user, $host)
360 $rcmail = rcmail::get_instance();
362 // try to resolve user in virtuser table and file
363 if ($email_list = self::user2email($user, false, true)) {
364 $user_email = is_array($email_list[0]) ? $email_list[0][0] : $email_list[0];
367 $data = $rcmail->plugins->exec_hook('create_user',
368 array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
370 // plugin aborted this operation
374 $user_name = $data['user_name'];
375 $user_email = $data['user_email'];
377 $dbh = $rcmail->get_dbh();
380 "INSERT INTO ".get_table_name('users')."
381 (created, last_login, username, mail_host, alias, language)
382 VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
383 strip_newlines($user),
384 strip_newlines($host),
385 strip_newlines($data['alias'] ? $data['alias'] : $user_email),
386 $_SESSION['language']);
388 if ($user_id = $dbh->insert_id('users'))
390 // create rcube_user instance to make plugin hooks work
391 $user_instance = new rcube_user($user_id);
392 $rcmail->user = $user_instance;
394 $mail_domain = $rcmail->config->mail_domain($host);
397 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
399 if ($user_name == '') {
400 $user_name = $user != $user_email ? $user : '';
403 if (empty($email_list))
404 $email_list[] = strip_newlines($user_email);
405 // identities_level check
406 else if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
407 $email_list = array($email_list[0]);
409 // create new identities records
411 foreach ($email_list as $row) {
412 if (is_array($row)) {
414 $name = $row[1] ? $row[1] : $user_name;
421 $plugin = $rcmail->plugins->exec_hook('create_identity', array(
424 'user_id' => $user_id,
425 'name' => strip_newlines($name),
427 'standard' => $standard,
432 if (!$plugin['abort'] && $plugin['record']['email']) {
434 "INSERT INTO ".get_table_name('identities')."
435 (user_id, del, standard, name, email, signature)
436 VALUES (?, 0, ?, ?, ?, ?)",
438 $plugin['record']['standard'],
439 $plugin['record']['name'] != NULL ? $plugin['record']['name'] : '',
440 $plugin['record']['email'],
441 $plugin['record']['signature']);
453 'message' => "Failed to create new user"), true, false);
456 return $user_id ? $user_instance : false;
461 * Resolve username using a virtuser file
463 * @param string E-mail address to resolve
464 * @return string Resolved IMAP username
466 static function email2user($email)
468 $r = self::findinvirtual('/^' . preg_quote($email, '/') . '\s/');
470 for ($i=0; $i<count($r); $i++)
472 $data = trim($r[$i]);
473 $arr = preg_split('/\s+/', $data);
475 return trim($arr[count($arr)-1]);
483 * Resolve e-mail address from virtuser file/table
485 * @param string User name
486 * @param boolean If true returns first found entry
487 * @param boolean If true returns email as array (email and name for identity)
488 * @return mixed Resolved e-mail address string or array of strings
490 static function user2email($user, $first=true, $extended=false)
493 $rcmail = rcmail::get_instance();
494 $dbh = $rcmail->get_dbh();
497 if ($virtuser_query = $rcmail->config->get('virtuser_query')) {
498 $sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query));
499 while ($sql_arr = $dbh->fetch_array($sql_result))
500 if (strpos($sql_arr[0], '@')) {
501 $result[] = ($extended && count($sql_arr) > 1) ? $sql_arr : $sql_arr[0];
507 $r = self::findinvirtual('/\s' . preg_quote($user, '/') . '\s*$/');
508 for ($i=0; $i<count($r); $i++)
511 $arr = preg_split('/\s+/', $data);
512 if (count($arr) > 0 && strpos($arr[0], '@'))
514 $result[] = trim(str_replace('\\@', '@', $arr[0]));
521 return empty($result) ? NULL : $result;
526 * Find matches of the given pattern in virtuser file
528 * @param string Regular expression to search for
529 * @return array Matching entries
531 private static function findinvirtual($pattern)
536 if ($virtuser_file = rcmail::get_instance()->config->get('virtuser_file'))
537 $virtual = file($virtuser_file);
542 // check each line for matches
543 foreach ($virtual as $line)
546 if (empty($line) || $line{0}=='#')
549 if (preg_match($pattern, $line))