thomascube
2010-12-17 db1a87cd6c506f2afbd1a37c64cb56ae11120b49
commit | author | age
fba1f5 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_user.inc                                        |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
A 8  | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland                 |
fba1f5 9  | Licensed under the GNU GPL                                            |
T 10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   This class represents a system user linked and provides access      |
13  |   to the related database records.                                    |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
638fb8 19  $Id$
fba1f5 20
T 21 */
22
23
24 /**
25  * Class representing a system user
26  *
45f56c 27  * @package    Core
fba1f5 28  * @author     Thomas Bruederli <roundcube@gmail.com>
T 29  */
30 class rcube_user
31 {
a78901 32     public $ID = null;
A 33     public $data = null;
34     public $language = null;
35
5c461b 36     /**
A 37      * Holds database connection.
38      *
39      * @var rcube_mdb2
40      */
a78901 41     private $db = null;
fba1f5 42
95987c 43
a78901 44     /**
A 45      * Object constructor
46      *
5c461b 47      * @param int   $id      User id
A 48      * @param array $sql_arr SQL result set
a78901 49      */
A 50     function __construct($id = null, $sql_arr = null)
51     {
52         $this->db = rcmail::get_instance()->get_dbh();
e99991 53
a78901 54         if ($id && !$sql_arr) {
A 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);
58         }
59
60         if (!empty($sql_arr)) {
61             $this->ID       = $sql_arr['user_id'];
62             $this->data     = $sql_arr;
63             $this->language = $sql_arr['language'];
64         }
65     }
66
67
68     /**
69      * Build a user name string (as e-mail address)
70      *
5c461b 71      * @param  string $part Username part (empty or 'local' or 'domain')
8dfe51 72      * @return string Full user name or its part
a78901 73      */
8dfe51 74     function get_username($part = null)
a78901 75     {
A 76         if ($this->data['username']) {
8dfe51 77             list($local, $domain) = explode('@', $this->data['username']);
A 78
79             // at least we should always have the local part
80             if ($part == 'local') {
81                 return $local;
82             }
b0eeaa 83             // if no domain was provided...
A 84             if (empty($domain)) {
85                 $rcmail = rcmail::get_instance();
86                 $domain = $rcmail->config->mail_domain($this->data['mail_host']);
87             }
8dfe51 88
A 89             if ($part == 'domain') {
90                 return $domain;
91             }
92
93             if (!empty($domain))
94                 return $local . '@' . $domain;
a78901 95             else
8dfe51 96                 return $local;
a78901 97         }
A 98
99         return false;
100     }
101
102
103     /**
104      * Get the preferences saved for this user
105      *
106      * @return array Hash array with prefs
107      */
108     function get_prefs()
109     {
110         if (!empty($this->language))
111             $prefs = array('language' => $this->language);
8dfe51 112
a78901 113         if ($this->ID && $this->data['preferences'])
A 114             $prefs += (array)unserialize($this->data['preferences']);
8dfe51 115
a78901 116         return $prefs;
A 117     }
8dfe51 118
A 119
a78901 120     /**
A 121      * Write the given user prefs to the user's record
122      *
5c461b 123      * @param array $a_user_prefs User prefs to save
a78901 124      * @return boolean True on success, False on failure
A 125      */
126     function save_prefs($a_user_prefs)
127     {
128         if (!$this->ID)
129             return false;
e99991 130
a78901 131         $config = rcmail::get_instance()->config;
A 132         $old_prefs = (array)$this->get_prefs();
fba1f5 133
a78901 134         // merge (partial) prefs array with existing settings
A 135         $save_prefs = $a_user_prefs + $old_prefs;
136         unset($save_prefs['language']);
e99991 137
a78901 138         // don't save prefs with default values if they haven't been changed yet
A 139         foreach ($a_user_prefs as $key => $value) {
140             if (!isset($old_prefs[$key]) && ($value == $config->get($key)))
141                 unset($save_prefs[$key]);
142         }
143
144         $save_prefs = serialize($save_prefs);
145
146         $this->db->query(
147             "UPDATE ".get_table_name('users').
148             " SET preferences = ?".
149                 ", language = ?".
150             " WHERE user_id = ?",
151             $save_prefs,
152             $_SESSION['language'],
153             $this->ID);
154
155         $this->language = $_SESSION['language'];
156
157         if ($this->db->affected_rows()) {
158             $config->set_user_prefs($a_user_prefs);
159             $this->data['preferences'] = $save_prefs;
160             return true;
161         }
162
163         return false;
286420 164     }
f52c93 165
T 166
a78901 167     /**
A 168      * Get default identity of this user
169      *
5c461b 170      * @param  int   $id Identity ID. If empty, the default identity is returned
a78901 171      * @return array Hash array with all cols of the identity record
A 172      */
173     function get_identity($id = null)
fba1f5 174     {
a78901 175         $result = $this->list_identities($id ? sprintf('AND identity_id = %d', $id) : '');
A 176         return $result[0];
fba1f5 177     }
55f54e 178
A 179
a78901 180     /**
A 181      * Return a list of all identities linked with this user
182      *
5c461b 183      * @param string $sql_add Optional WHERE clauses
a78901 184      * @return array List of identities
A 185      */
186     function list_identities($sql_add = '')
fba1f5 187     {
a78901 188         $result = array();
fba1f5 189
a78901 190         $sql_result = $this->db->query(
A 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",
195             $this->ID);
e99991 196
a78901 197         while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
A 198             $result[] = $sql_arr;
199         }
e99991 200
a78901 201         return $result;
A 202     }
fba1f5 203
a78901 204
A 205     /**
206      * Update a specific identity record
207      *
5c461b 208      * @param int    $iid  Identity ID
A 209      * @param array  $data Hash array with col->value pairs to save
a78901 210      * @return boolean True if saved successfully, false if nothing changed
A 211      */
212     function update_identity($iid, $data)
fba1f5 213     {
a78901 214         if (!$this->ID)
A 215             return false;
216
217         $query_cols = $query_params = array();
e99991 218
a78901 219         foreach ((array)$data as $col => $value) {
A 220             $query_cols[]   = $this->db->quoteIdentifier($col) . ' = ?';
221             $query_params[] = $value;
222         }
223         $query_params[] = $iid;
224         $query_params[] = $this->ID;
225
226         $sql = "UPDATE ".get_table_name('identities').
227             " SET changed = ".$this->db->now().", ".join(', ', $query_cols).
228             " WHERE identity_id = ?".
229                 " AND user_id = ?".
230                 " AND del <> 1";
231
232         call_user_func_array(array($this->db, 'query'),
233             array_merge(array($sql), $query_params));
e99991 234
a78901 235         return $this->db->affected_rows();
fba1f5 236     }
e99991 237
A 238
a78901 239     /**
A 240      * Create a new identity record linked with this user
241      *
5c461b 242      * @param array $data Hash array with col->value pairs to save
a78901 243      * @return int  The inserted identity ID or false on error
A 244      */
245     function insert_identity($data)
fba1f5 246     {
a78901 247         if (!$this->ID)
A 248             return false;
249
250         unset($data['user_id']);
251
252         $insert_cols = $insert_values = array();
253         foreach ((array)$data as $col => $value) {
254             $insert_cols[]   = $this->db->quoteIdentifier($col);
255             $insert_values[] = $value;
256         }
257         $insert_cols[]   = 'user_id';
258         $insert_values[] = $this->ID;
259
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), '?')).")";
263
264         call_user_func_array(array($this->db, 'query'),
265             array_merge(array($sql), $insert_values));
266
267         return $this->db->insert_id('identities');
fba1f5 268     }
e99991 269
A 270
a78901 271     /**
A 272      * Mark the given identity as deleted
273      *
5c461b 274      * @param  int     $iid Identity ID
a78901 275      * @return boolean True if deleted successfully, false if nothing changed
A 276      */
277     function delete_identity($iid)
fba1f5 278     {
a78901 279         if (!$this->ID)
A 280             return false;
07722a 281
a78901 282         $sql_result = $this->db->query(
A 283             "SELECT count(*) AS ident_count FROM ".get_table_name('identities').
284             " WHERE user_id = ? AND del <> 1",
285             $this->ID);
fba1f5 286
a78901 287         $sql_arr = $this->db->fetch_assoc($sql_result);
fba1f5 288
a78901 289         // we'll not delete last identity
A 290         if ($sql_arr['ident_count'] <= 1)
291             return false;
e99991 292
a78901 293         $this->db->query(
A 294             "UPDATE ".get_table_name('identities').
295             " SET del = 1, changed = ".$this->db->now().
296             " WHERE user_id = ?".
297                 " AND identity_id = ?",
298             $this->ID,
299             $iid);
fba1f5 300
a78901 301         return $this->db->affected_rows();
A 302     }
e99991 303
A 304
a78901 305     /**
A 306      * Make this identity the default one for this user
307      *
5c461b 308      * @param int $iid The identity ID
a78901 309      */
A 310     function set_default($iid)
311     {
312         if ($this->ID && $iid) {
313             $this->db->query(
314                 "UPDATE ".get_table_name('identities').
315                 " SET ".$this->db->quoteIdentifier('standard')." = '0'".
316                 " WHERE user_id = ?".
317                     " AND identity_id <> ?".
318                     " AND del <> 1",
319                 $this->ID,
320                 $iid);
321         }
322     }
e99991 323
A 324
a78901 325     /**
A 326      * Update user's last_login timestamp
327      */
328     function touch()
329     {
330         if ($this->ID) {
331             $this->db->query(
332                 "UPDATE ".get_table_name('users').
333                 " SET last_login = ".$this->db->now().
334                 " WHERE user_id = ?",
335                 $this->ID);
336         }
337     }
e99991 338
A 339
a78901 340     /**
A 341      * Clear the saved object state
342      */
343     function reset()
344     {
345         $this->ID = null;
346         $this->data = null;
347     }
e99991 348
A 349
a78901 350     /**
A 351      * Find a user record matching the given name and host
352      *
5c461b 353      * @param string $user IMAP user name
A 354      * @param string $host IMAP host name
355      * @return rcube_user New user instance
a78901 356      */
A 357     static function query($user, $host)
358     {
359         $dbh = rcmail::get_instance()->get_dbh();
e99991 360
db1a87 361         // use BINARY (case-sensitive) comparison on MySQL, other engines are case-sensitive
T 362         $prefix = preg_match('/^mysql/', $dbh->db_provider) ? 'BINARY ' : '';
363
a78901 364         // query for matching user name
A 365         $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host = ? AND %s = ?";
db1a87 366
T 367         $sql_result = $dbh->query(sprintf($query, $prefix.'username'), $host, $user);
e99991 368
a78901 369         // query for matching alias
A 370         if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
db1a87 371             $sql_result = $dbh->query(sprintf($query, $prefix.'alias'), $host, $user);
a78901 372             $sql_arr = $dbh->fetch_assoc($sql_result);
A 373         }
e99991 374
a78901 375         // user already registered -> overwrite username
A 376         if ($sql_arr)
377             return new rcube_user($sql_arr['user_id'], $sql_arr);
378         else
379             return false;
380     }
e99991 381
A 382
a78901 383     /**
A 384      * Create a new user record and return a rcube_user instance
385      *
5c461b 386      * @param string $user IMAP user name
A 387      * @param string $host IMAP host
388      * @return rcube_user New user instance
a78901 389      */
A 390     static function create($user, $host)
391     {
392         $user_name  = '';
393         $user_email = '';
394         $rcmail = rcmail::get_instance();
ac9927 395
a78901 396         // try to resolve user in virtuser table and file
A 397         if ($email_list = self::user2email($user, false, true)) {
398             $user_email = is_array($email_list[0]) ? $email_list[0]['email'] : $email_list[0];
399         }
f20971 400
e6ce00 401         $data = $rcmail->plugins->exec_hook('user_create',
a78901 402             array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
A 403
404         // plugin aborted this operation
405         if ($data['abort'])
406             return false;
407
408         $user_name  = $data['user_name'];
409         $user_email = $data['user_email'];
410
411         $dbh = $rcmail->get_dbh();
412
413         $dbh->query(
414             "INSERT INTO ".get_table_name('users').
415             " (created, last_login, username, mail_host, alias, language)".
416             " VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
417             strip_newlines($user),
418             strip_newlines($host),
419             strip_newlines($data['alias'] ? $data['alias'] : $user_email),
532c25 420             strip_newlines($data['language'] ? $data['language'] : $_SESSION['language']));
a78901 421
A 422         if ($user_id = $dbh->insert_id('users')) {
423             // create rcube_user instance to make plugin hooks work
424             $user_instance = new rcube_user($user_id);
425             $rcmail->user  = $user_instance;
426
427             $mail_domain = $rcmail->config->mail_domain($host);
428
429             if ($user_email == '') {
430                 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
431             }
432             if ($user_name == '') {
433                 $user_name = $user != $user_email ? $user : '';
434             }
435
436             if (empty($email_list))
437                 $email_list[] = strip_newlines($user_email);
438             // identities_level check
439             else if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
440                 $email_list = array($email_list[0]);
441
442             // create new identities records
443             $standard = 1;
444             foreach ($email_list as $row) {
445                 $record = array();
446
447                 if (is_array($row)) {
448                     $record = $row;
449                 }
450                 else {
451                     $record['email'] = $row;
452                 }
453
454                 if (empty($record['name']))
455                     $record['name'] = $user_name;
456                 $record['name'] = strip_newlines($record['name']);
457                 $record['user_id'] = $user_id;
458                 $record['standard'] = $standard;
459
e6ce00 460                 $plugin = $rcmail->plugins->exec_hook('identity_create',
a78901 461                     array('login' => true, 'record' => $record));
e99991 462
a78901 463                 if (!$plugin['abort'] && $plugin['record']['email']) {
A 464                     $rcmail->user->insert_identity($plugin['record']);
465                 }
466                 $standard = 0;
467             }
08c8c3 468         }
T 469         else {
a78901 470             raise_error(array(
A 471                 'code' => 500,
472                 'type' => 'php',
473                 'line' => __LINE__,
474                 'file' => __FILE__,
475                 'message' => "Failed to create new user"), true, false);
08c8c3 476         }
e99991 477
a78901 478         return $user_id ? $user_instance : false;
A 479     }
e99991 480
A 481
a78901 482     /**
A 483      * Resolve username using a virtuser plugins
484      *
5c461b 485      * @param string $email E-mail address to resolve
a78901 486      * @return string Resolved IMAP username
A 487      */
488     static function email2user($email)
489     {
490         $rcmail = rcmail::get_instance();
491         $plugin = $rcmail->plugins->exec_hook('email2user',
492             array('email' => $email, 'user' => NULL));
fba1f5 493
a78901 494         return $plugin['user'];
A 495     }
fba1f5 496
T 497
a78901 498     /**
A 499      * Resolve e-mail address from virtuser plugins
500      *
5c461b 501      * @param string $user User name
A 502      * @param boolean $first If true returns first found entry
503      * @param boolean $extended If true returns email as array (email and name for identity)
a78901 504      * @return mixed Resolved e-mail address string or array of strings
A 505      */
506     static function user2email($user, $first=true, $extended=false)
507     {
508         $rcmail = rcmail::get_instance();
509         $plugin = $rcmail->plugins->exec_hook('user2email',
510             array('email' => NULL, 'user' => $user,
511                 'first' => $first, 'extended' => $extended));
fba1f5 512
a78901 513         return empty($plugin['email']) ? NULL : $plugin['email'];
A 514     }
8dfe51 515
fba1f5 516 }