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