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 (!strpos($user, '@')) {
364 if ($email_list = self::user2email($user, false, true))
365 $user_email = is_array($email_list[0]) ? $email_list[0][0] : $email_list[0];
368 $data = $rcmail->plugins->exec_hook('create_user',
369 array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
371 // plugin aborted this operation
375 $user_name = $data['user_name'];
376 $user_email = $data['user_email'];
378 $dbh = $rcmail->get_dbh();
381 "INSERT INTO ".get_table_name('users')."
382 (created, last_login, username, mail_host, alias, language)
383 VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
384 strip_newlines($user),
385 strip_newlines($host),
386 strip_newlines($data['alias'] ? $data['alias'] : $user_email),
387 $_SESSION['language']);
389 if ($user_id = $dbh->insert_id('users'))
391 // create rcube_user instance to make plugin hooks work
392 $user_instance = new rcube_user($user_id);
393 $rcmail->user = $user_instance;
395 $mail_domain = $rcmail->config->mail_domain($host);
398 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
400 if ($user_name == '') {
401 $user_name = $user != $user_email ? $user : '';
404 if (empty($email_list))
405 $email_list[] = strip_newlines($user_email);
406 // identities_level check
407 else if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
408 $email_list = array($email_list[0]);
410 // create new identities records
412 foreach ($email_list as $row) {
413 if (is_array($row)) {
415 $name = $row[1] ? $row[1] : $user_name;
422 $plugin = $rcmail->plugins->exec_hook('create_identity', array(
425 'user_id' => $user_id,
426 'name' => strip_newlines($name),
428 'standard' => $standard,
433 if (!$plugin['abort'] && $plugin['record']['email']) {
435 "INSERT INTO ".get_table_name('identities')."
436 (user_id, del, standard, name, email, signature)
437 VALUES (?, 0, ?, ?, ?, ?)",
439 $plugin['record']['standard'],
440 $plugin['record']['name'] != NULL ? $plugin['record']['name'] : '',
441 $plugin['record']['email'],
442 $plugin['record']['signature']);
454 'message' => "Failed to create new user"), true, false);
457 return $user_id ? $user_instance : false;
462 * Resolve username using a virtuser file
464 * @param string E-mail address to resolve
465 * @return string Resolved IMAP username
467 static function email2user($email)
469 $r = self::findinvirtual('/^' . preg_quote($email, '/') . '\s/');
471 for ($i=0; $i<count($r); $i++)
473 $data = trim($r[$i]);
474 $arr = preg_split('/\s+/', $data);
476 return trim($arr[count($arr)-1]);
484 * Resolve e-mail address from virtuser file/table
486 * @param string User name
487 * @param boolean If true returns first found entry
488 * @param boolean If true returns email as array (email and name for identity)
489 * @return mixed Resolved e-mail address string or array of strings
491 static function user2email($user, $first=true, $extended=false)
494 $rcmail = rcmail::get_instance();
495 $dbh = $rcmail->get_dbh();
498 if ($virtuser_query = $rcmail->config->get('virtuser_query')) {
499 $sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query));
500 while ($sql_arr = $dbh->fetch_array($sql_result))
501 if (strpos($sql_arr[0], '@')) {
502 $result[] = ($extended && count($sql_arr) > 1) ? $sql_arr : $sql_arr[0];
508 $r = self::findinvirtual('/\s' . preg_quote($user, '/') . '\s*$/');
509 for ($i=0; $i<count($r); $i++)
512 $arr = preg_split('/\s+/', $data);
513 if (count($arr) > 0 && strpos($arr[0], '@'))
515 $result[] = trim(str_replace('\\@', '@', $arr[0]));
522 return empty($result) ? NULL : $result;
527 * Find matches of the given pattern in virtuser file
529 * @param string Regular expression to search for
530 * @return array Matching entries
532 private static function findinvirtual($pattern)
537 if ($virtuser_file = rcmail::get_instance()->config->get('virtuser_file'))
538 $virtual = file($virtuser_file);
543 // check each line for matches
544 foreach ($virtual as $line)
547 if (empty($line) || $line{0}=='#')
550 if (preg_match($pattern, $line))