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