]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_user.php
Imported Upstream version 0.2~alpha
[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-2007, 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.inc 933 2007-11-29 14:17:32Z thomasb $
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 = 'en_US';
35   
36   private $db = null;
37   
38   
39   /**
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();
47     
48     if ($id && !$sql_arr)
49     {
50       $sql_result = $this->db->query("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     {
56       $this->ID = $sql_arr['user_id'];
57       $this->data = $sql_arr;
58       $this->language = $sql_arr['language'];
59     }
60   }
61
62   /**
63    * PHP 4 object constructor
64    *
65    * @see  rcube_user::__construct
66    */
67   function rcube_user($id = null, $sql_arr = null)
68   {
69     $this->__construct($id, $sql_arr);
70   }
71   
72   
73   /**
74    * Build a user name string (as e-mail address)
75    *
76    * @return string Full user name
77    */
78   function get_username()
79   {
80     return $this->data['username'] ? $this->data['username'] . (!strpos($this->data['username'], '@') ? '@'.$this->data['mail_host'] : '') : false;
81   }
82   
83   
84   /**
85    * Get the preferences saved for this user
86    *
87    * @return array Hash array with prefs
88    */
89   function get_prefs()
90   {
91     if ($this->ID && $this->data['preferences'])
92       return array('language' => $this->language) + unserialize($this->data['preferences']);
93     else
94       return array();
95   }
96   
97   
98   /**
99    * Write the given user prefs to the user's record
100    *
101    * @param mixed User prefs to save
102    * @return boolean True on success, False on failure
103    */
104   function save_prefs($a_user_prefs)
105   {
106     if (!$this->ID)
107       return false;
108
109     // merge (partial) prefs array with existing settings
110     $a_user_prefs += (array)$this->get_prefs();
111     unset($a_user_prefs['language']);
112
113     $this->db->query(
114       "UPDATE ".get_table_name('users')."
115        SET    preferences=?,
116               language=?
117        WHERE  user_id=?",
118       serialize($a_user_prefs),
119       $_SESSION['language'],
120       $this->ID);
121
122     $this->language = $_SESSION['language'];
123     if ($this->db->affected_rows())
124     {
125       rcmail::get_instance()->config->merge($a_user_prefs);
126       return true;
127     }
128
129     return false;
130   }
131   
132   
133   /**
134    * Get default identity of this user
135    *
136    * @param int  Identity ID. If empty, the default identity is returned
137    * @return array Hash array with all cols of the 
138    */
139   function get_identity($id = null)
140   {
141     $sql_result = $this->list_identities($id ? sprintf('AND identity_id=%d', $id) : '');
142     return $this->db->fetch_assoc($sql_result);
143   }
144   
145   
146   /**
147    * Return a list of all identities linked with this user
148    *
149    * @return array List of identities
150    */
151   function list_identities($sql_add = '')
152   {
153     // get contacts from DB
154     $sql_result = $this->db->query(
155       "SELECT * FROM ".get_table_name('identities')."
156        WHERE  del<>1
157        AND    user_id=?
158        $sql_add
159        ORDER BY ".$this->db->quoteIdentifier('standard')." DESC, name ASC",
160       $this->ID);
161     
162     return $sql_result;
163   }
164   
165   
166   /**
167    * Update a specific identity record
168    *
169    * @param int    Identity ID
170    * @param array  Hash array with col->value pairs to save
171    * @return boolean True if saved successfully, false if nothing changed
172    */
173   function update_identity($iid, $data)
174   {
175     if (!$this->ID)
176       return false;
177     
178     $write_sql = array();
179     
180     foreach ((array)$data as $col => $value)
181     {
182       $write_sql[] = sprintf("%s=%s",
183         $this->db->quoteIdentifier($col),
184         $this->db->quote($value));
185     }
186     
187     $this->db->query(
188       "UPDATE ".get_table_name('identities')."
189        SET ".join(', ', $write_sql)."
190        WHERE  identity_id=?
191        AND    user_id=?
192        AND    del<>1",
193       $iid,
194       $this->ID);
195     
196     return $this->db->affected_rows();
197   }
198   
199   
200   /**
201    * Create a new identity record linked with this user
202    *
203    * @param array  Hash array with col->value pairs to save
204    * @return int  The inserted identity ID or false on error
205    */
206   function insert_identity($data)
207   {
208     if (!$this->ID)
209       return false;
210
211     $insert_cols = $insert_values = array();
212     foreach ((array)$data as $col => $value)
213     {
214       $insert_cols[] = $this->db->quoteIdentifier($col);
215       $insert_values[] = $this->db->quote($value);
216     }
217
218     $this->db->query(
219       "INSERT INTO ".get_table_name('identities')."
220         (user_id, ".join(', ', $insert_cols).")
221        VALUES (?, ".join(', ', $insert_values).")",
222       $this->ID);
223
224     return $this->db->insert_id(get_sequence_name('identities'));
225   }
226   
227   
228   /**
229    * Mark the given identity as deleted
230    *
231    * @param int  Identity ID
232    * @return boolean True if deleted successfully, false if nothing changed
233    */
234   function delete_identity($iid)
235   {
236     if (!$this->ID)
237       return false;
238
239     if (!$this->ID || $this->ID == '')
240       return false;
241
242     $sql_result = $this->db->query("SELECT count(*) AS ident_count FROM " .
243       get_table_name('identities') .
244       " WHERE user_id = ? AND del <> 1",
245       $this->ID);
246
247     $sql_arr = $this->db->fetch_assoc($sql_result);
248     if ($sql_arr['ident_count'] <= 1)
249       return false;
250     
251     $this->db->query(
252       "UPDATE ".get_table_name('identities')."
253        SET    del=1
254        WHERE  user_id=?
255        AND    identity_id=?",
256       $this->ID,
257       $iid);
258
259     return $this->db->affected_rows();
260   }
261   
262   
263   /**
264    * Make this identity the default one for this user
265    *
266    * @param int The identity ID
267    */
268   function set_default($iid)
269   {
270     if ($this->ID && $iid)
271     {
272       $this->db->query(
273         "UPDATE ".get_table_name('identities')."
274          SET ".$this->db->quoteIdentifier('standard')."='0'
275          WHERE  user_id=?
276          AND    identity_id<>?
277          AND    del<>1",
278         $this->ID,
279         $iid);
280     }
281   }
282   
283   
284   /**
285    * Update user's last_login timestamp
286    */
287   function touch()
288   {
289     if ($this->ID)
290     {
291       $this->db->query(
292         "UPDATE ".get_table_name('users')."
293          SET    last_login=".$this->db->now()."
294          WHERE  user_id=?",
295         $this->ID);
296     }
297   }
298   
299   
300   /**
301    * Clear the saved object state
302    */
303   function reset()
304   {
305     $this->ID = null;
306     $this->data = null;
307   }
308   
309   
310   /**
311    * Find a user record matching the given name and host
312    *
313    * @param string IMAP user name
314    * @param string IMAP host name
315    * @return object rcube_user New user instance
316    */
317   static function query($user, $host)
318   {
319     $dbh = rcmail::get_instance()->get_dbh();
320     
321     // query if user already registered
322     $sql_result = $dbh->query(
323       "SELECT * FROM ".get_table_name('users')."
324        WHERE  mail_host=? AND (username=? OR alias=?)",
325       $host,
326       $user,
327       $user);
328       
329     // user already registered -> overwrite username
330     if ($sql_arr = $dbh->fetch_assoc($sql_result))
331       return new rcube_user($sql_arr['user_id'], $sql_arr);
332     else
333       return false;
334   }
335   
336   
337   /**
338    * Create a new user record and return a rcube_user instance
339    *
340    * @param string IMAP user name
341    * @param string IMAP host
342    * @return object rcube_user New user instance
343    */
344   static function create($user, $host)
345   {
346     $user_email = '';
347     $rcmail = rcmail::get_instance();
348     $dbh = $rcmail->get_dbh();
349
350     // try to resolve user in virtusertable
351     if ($rcmail->config->get('virtuser_file') && !strpos($user, '@'))
352       $user_email = rcube_user::user2email($user);
353
354     $dbh->query(
355       "INSERT INTO ".get_table_name('users')."
356         (created, last_login, username, mail_host, alias, language)
357        VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
358       strip_newlines($user),
359       strip_newlines($host),
360       strip_newlines($user_email),
361       $_SESSION['language']);
362
363     if ($user_id = $dbh->insert_id(get_sequence_name('users')))
364     {
365       $mail_domain = rcmail_mail_domain($host);
366
367       if ($user_email=='')
368         $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
369
370       $user_name = $user != $user_email ? $user : '';
371
372       // try to resolve the e-mail address from the virtuser table
373       if ($virtuser_query = $rcmail->config->get('virtuser_query') &&
374           ($sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query))) &&
375           ($dbh->num_rows() > 0))
376       {
377         while ($sql_arr = $dbh->fetch_array($sql_result))
378         {
379           $dbh->query(
380             "INSERT INTO ".get_table_name('identities')."
381               (user_id, del, standard, name, email)
382              VALUES (?, 0, 1, ?, ?)",
383             $user_id,
384             strip_newlines($user_name),
385             preg_replace('/^@/', $user . '@', $sql_arr[0]));
386         }
387       }
388       else
389       {
390         // also create new identity records
391         $dbh->query(
392           "INSERT INTO ".get_table_name('identities')."
393             (user_id, del, standard, name, email)
394            VALUES (?, 0, 1, ?, ?)",
395           $user_id,
396           strip_newlines($user_name),
397           strip_newlines($user_email));
398       }
399     }
400     else
401     {
402       raise_error(array(
403         'code' => 500,
404         'type' => 'php',
405         'line' => __LINE__,
406         'file' => __FILE__,
407         'message' => "Failed to create new user"), true, false);
408     }
409     
410     return $user_id ? new rcube_user($user_id) : false;
411   }
412   
413   
414   /**
415    * Resolve username using a virtuser table
416    *
417    * @param string E-mail address to resolve
418    * @return string Resolved IMAP username
419    */
420   static function email2user($email)
421   {
422     $user = $email;
423     $r = rcmail_findinvirtual("^$email");
424
425     for ($i=0; $i<count($r); $i++)
426     {
427       $data = $r[$i];
428       $arr = preg_split('/\s+/', $data);
429       if (count($arr) > 0)
430       {
431         $user = trim($arr[count($arr)-1]);
432         break;
433       }
434     }
435
436     return $user;
437   }
438
439
440   /**
441    * Resolve e-mail address from virtuser table
442    *
443    * @param string User name
444    * @return string Resolved e-mail address
445    */
446   static function user2email($user)
447   {
448     $email = "";
449     $r = rcmail_findinvirtual("$user$");
450
451     for ($i=0; $i<count($r); $i++)
452     {
453       $data = $r[$i];
454       $arr = preg_split('/\s+/', $data);
455       if (count($arr) > 0)
456       {
457         $email = trim(str_replace('\\@', '@', $arr[0]));
458         break;
459       }
460     }
461
462     return $email;
463   }
464
465 }
466
467