]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_user.php
39a77ada785bd6023e8c1588ffcd952b14abe588
[roundcube.git] / program / include / rcube_user.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_user.inc                                        |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
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
19  $Id: rcube_user.php 4554 2011-02-16 09:42:31Z alec $
20
21 */
22
23
24 /**
25  * Class representing a system user
26  *
27  * @package    Core
28  * @author     Thomas Bruederli <roundcube@gmail.com>
29  */
30 class rcube_user
31 {
32     public $ID = null;
33     public $data = null;
34     public $language = null;
35
36     /**
37      * Holds database connection.
38      *
39      * @var rcube_mdb2
40      */
41     private $db = null;
42
43
44     /**
45      * Object constructor
46      *
47      * @param int   $id      User id
48      * @param array $sql_arr SQL result set
49      */
50     function __construct($id = null, $sql_arr = null)
51     {
52         $this->db = rcmail::get_instance()->get_dbh();
53
54         if ($id && !$sql_arr) {
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      *
71      * @param  string $part Username part (empty or 'local' or 'domain')
72      * @return string Full user name or its part
73      */
74     function get_username($part = null)
75     {
76         if ($this->data['username']) {
77             list($local, $domain) = explode('@', $this->data['username']);
78
79             // at least we should always have the local part
80             if ($part == 'local') {
81                 return $local;
82             }
83             // if no domain was provided...
84             if (empty($domain)) {
85                 $rcmail = rcmail::get_instance();
86                 $domain = $rcmail->config->mail_domain($this->data['mail_host']);
87             }
88
89             if ($part == 'domain') {
90                 return $domain;
91             }
92
93             if (!empty($domain))
94                 return $local . '@' . $domain;
95             else
96                 return $local;
97         }
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);
112
113         if ($this->ID && $this->data['preferences'])
114             $prefs += (array)unserialize($this->data['preferences']);
115
116         return $prefs;
117     }
118
119
120     /**
121      * Write the given user prefs to the user's record
122      *
123      * @param array $a_user_prefs User prefs to save
124      * @return boolean True on success, False on failure
125      */
126     function save_prefs($a_user_prefs)
127     {
128         if (!$this->ID)
129             return false;
130
131         $config = rcmail::get_instance()->config;
132         $old_prefs = (array)$this->get_prefs();
133
134         // merge (partial) prefs array with existing settings
135         $save_prefs = $a_user_prefs + $old_prefs;
136         unset($save_prefs['language']);
137
138         // don't save prefs with default values if they haven't been changed yet
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;
164     }
165
166
167     /**
168      * Get default identity of this user
169      *
170      * @param  int   $id Identity ID. If empty, the default identity is returned
171      * @return array Hash array with all cols of the identity record
172      */
173     function get_identity($id = null)
174     {
175         $result = $this->list_identities($id ? sprintf('AND identity_id = %d', $id) : '');
176         return $result[0];
177     }
178
179
180     /**
181      * Return a list of all identities linked with this user
182      *
183      * @param string $sql_add Optional WHERE clauses
184      * @return array List of identities
185      */
186     function list_identities($sql_add = '')
187     {
188         $result = array();
189
190         $sql_result = $this->db->query(
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);
196
197         while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
198             $result[] = $sql_arr;
199         }
200
201         return $result;
202     }
203
204
205     /**
206      * Update a specific identity record
207      *
208      * @param int    $iid  Identity ID
209      * @param array  $data Hash array with col->value pairs to save
210      * @return boolean True if saved successfully, false if nothing changed
211      */
212     function update_identity($iid, $data)
213     {
214         if (!$this->ID)
215             return false;
216
217         $query_cols = $query_params = array();
218
219         foreach ((array)$data as $col => $value) {
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));
234
235         return $this->db->affected_rows();
236     }
237
238
239     /**
240      * Create a new identity record linked with this user
241      *
242      * @param array $data Hash array with col->value pairs to save
243      * @return int  The inserted identity ID or false on error
244      */
245     function insert_identity($data)
246     {
247         if (!$this->ID)
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');
268     }
269
270
271     /**
272      * Mark the given identity as deleted
273      *
274      * @param  int     $iid Identity ID
275      * @return boolean True if deleted successfully, false if nothing changed
276      */
277     function delete_identity($iid)
278     {
279         if (!$this->ID)
280             return false;
281
282         $sql_result = $this->db->query(
283             "SELECT count(*) AS ident_count FROM ".get_table_name('identities').
284             " WHERE user_id = ? AND del <> 1",
285             $this->ID);
286
287         $sql_arr = $this->db->fetch_assoc($sql_result);
288
289         // we'll not delete last identity
290         if ($sql_arr['ident_count'] <= 1)
291             return false;
292
293         $this->db->query(
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);
300
301         return $this->db->affected_rows();
302     }
303
304
305     /**
306      * Make this identity the default one for this user
307      *
308      * @param int $iid The identity ID
309      */
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     }
323
324
325     /**
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     }
338
339
340     /**
341      * Clear the saved object state
342      */
343     function reset()
344     {
345         $this->ID = null;
346         $this->data = null;
347     }
348
349
350     /**
351      * Find a user record matching the given name and host
352      *
353      * @param string $user IMAP user name
354      * @param string $host IMAP host name
355      * @return rcube_user New user instance
356      */
357     static function query($user, $host)
358     {
359         $dbh = rcmail::get_instance()->get_dbh();
360
361         // use BINARY (case-sensitive) comparison on MySQL, other engines are case-sensitive
362         $mod = preg_match('/^mysql/', $dbh->db_provider) ? 'BINARY' : '';
363
364         // query for matching user name
365         $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host = ? AND %s = $mod ?";
366         $sql_result = $dbh->query(sprintf($query, 'username'), $host, $user);
367
368         // query for matching alias
369         if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
370             $sql_result = $dbh->query(sprintf($query, 'alias'), $host, $user);
371             $sql_arr = $dbh->fetch_assoc($sql_result);
372         }
373
374         // user already registered -> overwrite username
375         if ($sql_arr)
376             return new rcube_user($sql_arr['user_id'], $sql_arr);
377         else
378             return false;
379     }
380
381
382     /**
383      * Create a new user record and return a rcube_user instance
384      *
385      * @param string $user IMAP user name
386      * @param string $host IMAP host
387      * @return rcube_user New user instance
388      */
389     static function create($user, $host)
390     {
391         $user_name  = '';
392         $user_email = '';
393         $rcmail = rcmail::get_instance();
394
395         // try to resolve user in virtuser table and file
396         if ($email_list = self::user2email($user, false, true)) {
397             $user_email = is_array($email_list[0]) ? $email_list[0]['email'] : $email_list[0];
398         }
399
400         $data = $rcmail->plugins->exec_hook('user_create',
401                 array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
402
403         // plugin aborted this operation
404         if ($data['abort'])
405             return false;
406
407         $user_name  = $data['user_name'];
408         $user_email = $data['user_email'];
409
410         $dbh = $rcmail->get_dbh();
411
412         $dbh->query(
413             "INSERT INTO ".get_table_name('users').
414             " (created, last_login, username, mail_host, alias, language)".
415             " VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
416             strip_newlines($user),
417             strip_newlines($host),
418             strip_newlines($data['alias'] ? $data['alias'] : $user_email),
419             strip_newlines($data['language'] ? $data['language'] : $_SESSION['language']));
420
421         if ($user_id = $dbh->insert_id('users')) {
422             // create rcube_user instance to make plugin hooks work
423             $user_instance = new rcube_user($user_id);
424             $rcmail->user  = $user_instance;
425
426             $mail_domain = $rcmail->config->mail_domain($host);
427
428             if ($user_email == '') {
429                 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
430             }
431             if ($user_name == '') {
432                 $user_name = $user != $user_email ? $user : '';
433             }
434
435             if (empty($email_list))
436                 $email_list[] = strip_newlines($user_email);
437             // identities_level check
438             else if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
439                 $email_list = array($email_list[0]);
440
441             // create new identities records
442             $standard = 1;
443             foreach ($email_list as $row) {
444                     $record = array();
445
446                 if (is_array($row)) {
447                         $record = $row;
448                 }
449                 else {
450                     $record['email'] = $row;
451                 }
452
453                     if (empty($record['name']))
454                         $record['name'] = $user_name;
455                 $record['name'] = strip_newlines($record['name']);
456                 $record['user_id'] = $user_id;
457                 $record['standard'] = $standard;
458
459                 $plugin = $rcmail->plugins->exec_hook('identity_create',
460                         array('login' => true, 'record' => $record));
461
462                 if (!$plugin['abort'] && $plugin['record']['email']) {
463                     $rcmail->user->insert_identity($plugin['record']);
464                 }
465                 $standard = 0;
466             }
467         }
468         else {
469             raise_error(array(
470                 'code' => 500,
471                 'type' => 'php',
472                 'line' => __LINE__,
473                 'file' => __FILE__,
474                 'message' => "Failed to create new user"), true, false);
475         }
476
477         return $user_id ? $user_instance : false;
478     }
479
480
481     /**
482      * Resolve username using a virtuser plugins
483      *
484      * @param string $email E-mail address to resolve
485      * @return string Resolved IMAP username
486      */
487     static function email2user($email)
488     {
489         $rcmail = rcmail::get_instance();
490         $plugin = $rcmail->plugins->exec_hook('email2user',
491             array('email' => $email, 'user' => NULL));
492
493         return $plugin['user'];
494     }
495
496
497     /**
498      * Resolve e-mail address from virtuser plugins
499      *
500      * @param string $user User name
501      * @param boolean $first If true returns first found entry
502      * @param boolean $extended If true returns email as array (email and name for identity)
503      * @return mixed Resolved e-mail address string or array of strings
504      */
505     static function user2email($user, $first=true, $extended=false)
506     {
507         $rcmail = rcmail::get_instance();
508         $plugin = $rcmail->plugins->exec_hook('user2email',
509             array('email' => NULL, 'user' => $user,
510                 'first' => $first, 'extended' => $extended));
511
512         return empty($plugin['email']) ? NULL : $plugin['email'];
513     }
514
515 }