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