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