thomascube
2008-09-19 42e328a85f5880e3e767eebaaa88b55a2b49d2ff
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                     |
286420 8  | Copyright (C) 2005-2008, 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
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  *
45f56c 27  * @package    Core
fba1f5 28  * @author     Thomas Bruederli <roundcube@gmail.com>
T 29  */
30 class rcube_user
31 {
197601 32   public $ID = null;
T 33   public $data = null;
29111b 34   public $language = null;
197601 35   
T 36   private $db = null;
fba1f5 37   
T 38   
39   /**
40    * Object constructor
41    *
42    * @param object DB Database connection
43    */
44   function __construct($id = null, $sql_arr = null)
45   {
197601 46     $this->db = rcmail::get_instance()->get_dbh();
fba1f5 47     
T 48     if ($id && !$sql_arr)
49     {
197601 50       $sql_result = $this->db->query("SELECT * FROM ".get_table_name('users')." WHERE  user_id=?", $id);
T 51       $sql_arr = $this->db->fetch_assoc($sql_result);
fba1f5 52     }
T 53     
54     if (!empty($sql_arr))
55     {
56       $this->ID = $sql_arr['user_id'];
57       $this->data = $sql_arr;
197601 58       $this->language = $sql_arr['language'];
fba1f5 59     }
T 60   }
61
95987c 62
fba1f5 63   /**
T 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   {
155329 81     $prefs = array('language' => $this->language);
T 82     
fba1f5 83     if ($this->ID && $this->data['preferences'])
155329 84       $prefs += (array)unserialize($this->data['preferences']);
T 85     
86     return $prefs;
fba1f5 87   }
T 88   
89   
90   /**
91    * Write the given user prefs to the user's record
92    *
286420 93    * @param array User prefs to save
fba1f5 94    * @return boolean True on success, False on failure
T 95    */
96   function save_prefs($a_user_prefs)
97   {
98     if (!$this->ID)
99       return false;
286420 100       
T 101     $config = rcmail::get_instance()->config;
102     $old_prefs = (array)$this->get_prefs();
fba1f5 103
T 104     // merge (partial) prefs array with existing settings
286420 105     $save_prefs = $a_user_prefs + $old_prefs;
T 106     unset($save_prefs['language']);
107     
108     // don't save prefs with default values if they haven't been changed yet
109     foreach ($a_user_prefs as $key => $value) {
110       if (!isset($old_prefs[$key]) && ($value == $config->get($key)))
111         unset($save_prefs[$key]);
112     }
113     
197601 114     $this->db->query(
fba1f5 115       "UPDATE ".get_table_name('users')."
T 116        SET    preferences=?,
117               language=?
118        WHERE  user_id=?",
286420 119       serialize($save_prefs),
197601 120       $_SESSION['language'],
fba1f5 121       $this->ID);
T 122
197601 123     $this->language = $_SESSION['language'];
286420 124     if ($this->db->affected_rows()) {
T 125       $config->merge($a_user_prefs);
fba1f5 126       return true;
T 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) : '');
197601 142     return $this->db->fetch_assoc($sql_result);
fba1f5 143   }
T 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
197601 154     $sql_result = $this->db->query(
fba1f5 155       "SELECT * FROM ".get_table_name('identities')."
T 156        WHERE  del<>1
157        AND    user_id=?
158        $sql_add
197601 159        ORDER BY ".$this->db->quoteIdentifier('standard')." DESC, name ASC",
fba1f5 160       $this->ID);
T 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",
197601 183         $this->db->quoteIdentifier($col),
T 184         $this->db->quote($value));
fba1f5 185     }
T 186     
197601 187     $this->db->query(
fba1f5 188       "UPDATE ".get_table_name('identities')."
T 189        SET ".join(', ', $write_sql)."
190        WHERE  identity_id=?
191        AND    user_id=?
192        AND    del<>1",
193       $iid,
194       $this->ID);
195     
197601 196     return $this->db->affected_rows();
fba1f5 197   }
T 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     {
197601 214       $insert_cols[] = $this->db->quoteIdentifier($col);
T 215       $insert_values[] = $this->db->quote($value);
fba1f5 216     }
T 217
197601 218     $this->db->query(
fba1f5 219       "INSERT INTO ".get_table_name('identities')."
T 220         (user_id, ".join(', ', $insert_cols).")
221        VALUES (?, ".join(', ', $insert_values).")",
222       $this->ID);
223
197601 224     return $this->db->insert_id(get_sequence_name('identities'));
fba1f5 225   }
T 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;
e3a0af 238
8779cd 239     if (!$this->ID || $this->ID == '')
T 240       return false;
241
197601 242     $sql_result = $this->db->query("SELECT count(*) AS ident_count FROM " .
e3a0af 243       get_table_name('identities') .
d45176 244       " WHERE user_id = ? AND del <> 1",
e3a0af 245       $this->ID);
T 246
197601 247     $sql_arr = $this->db->fetch_assoc($sql_result);
e3a0af 248     if ($sql_arr['ident_count'] <= 1)
T 249       return false;
fba1f5 250     
197601 251     $this->db->query(
fba1f5 252       "UPDATE ".get_table_name('identities')."
T 253        SET    del=1
254        WHERE  user_id=?
255        AND    identity_id=?",
256       $this->ID,
257       $iid);
258
197601 259     return $this->db->affected_rows();
fba1f5 260   }
T 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     {
197601 272       $this->db->query(
fba1f5 273         "UPDATE ".get_table_name('identities')."
197601 274          SET ".$this->db->quoteIdentifier('standard')."='0'
fba1f5 275          WHERE  user_id=?
T 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     {
197601 291       $this->db->query(
fba1f5 292         "UPDATE ".get_table_name('users')."
197601 293          SET    last_login=".$this->db->now()."
fba1f5 294          WHERE  user_id=?",
T 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    */
197601 317   static function query($user, $host)
fba1f5 318   {
197601 319     $dbh = rcmail::get_instance()->get_dbh();
fba1f5 320     
ba0e78 321     // query for matching user name
T 322     $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host=? AND %s=?";
323     $sql_result = $dbh->query(sprintf($query, 'username'), $host, $user);
324     
325     // query for matching alias
326     if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
327       $sql_result = $dbh->query(sprintf($query, 'alias'), $host, $user);
328       $sql_arr = $dbh->fetch_assoc($sql_result);
329     }
330     
fba1f5 331     // user already registered -> overwrite username
ba0e78 332     if ($sql_arr)
fba1f5 333       return new rcube_user($sql_arr['user_id'], $sql_arr);
T 334     else
335       return false;
336   }
337   
338   
339   /**
340    * Create a new user record and return a rcube_user instance
341    *
342    * @param string IMAP user name
343    * @param string IMAP host
344    * @return object rcube_user New user instance
345    */
197601 346   static function create($user, $host)
fba1f5 347   {
T 348     $user_email = '';
197601 349     $rcmail = rcmail::get_instance();
T 350     $dbh = $rcmail->get_dbh();
fba1f5 351
T 352     // try to resolve user in virtusertable
197601 353     if ($rcmail->config->get('virtuser_file') && !strpos($user, '@'))
846dd7 354       $user_email = rcube_user::user2email($user);
fba1f5 355
197601 356     $dbh->query(
fba1f5 357       "INSERT INTO ".get_table_name('users')."
T 358         (created, last_login, username, mail_host, alias, language)
197601 359        VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
fba1f5 360       strip_newlines($user),
T 361       strip_newlines($host),
362       strip_newlines($user_email),
197601 363       $_SESSION['language']);
fba1f5 364
197601 365     if ($user_id = $dbh->insert_id(get_sequence_name('users')))
fba1f5 366     {
83a763 367       $mail_domain = $rcmail->config->mail_domain($host);
fba1f5 368
T 369       if ($user_email=='')
370         $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
371
372       $user_name = $user != $user_email ? $user : '';
373
374       // try to resolve the e-mail address from the virtuser table
197601 375       if ($virtuser_query = $rcmail->config->get('virtuser_query') &&
T 376           ($sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query))) &&
377           ($dbh->num_rows() > 0))
fba1f5 378       {
197601 379         while ($sql_arr = $dbh->fetch_array($sql_result))
fba1f5 380         {
197601 381           $dbh->query(
fba1f5 382             "INSERT INTO ".get_table_name('identities')."
T 383               (user_id, del, standard, name, email)
384              VALUES (?, 0, 1, ?, ?)",
385             $user_id,
386             strip_newlines($user_name),
387             preg_replace('/^@/', $user . '@', $sql_arr[0]));
388         }
389       }
390       else
391       {
392         // also create new identity records
197601 393         $dbh->query(
fba1f5 394           "INSERT INTO ".get_table_name('identities')."
T 395             (user_id, del, standard, name, email)
396            VALUES (?, 0, 1, ?, ?)",
397           $user_id,
398           strip_newlines($user_name),
399           strip_newlines($user_email));
400       }
401     }
402     else
403     {
404       raise_error(array(
405         'code' => 500,
406         'type' => 'php',
407         'line' => __LINE__,
408         'file' => __FILE__,
409         'message' => "Failed to create new user"), true, false);
410     }
411     
412     return $user_id ? new rcube_user($user_id) : false;
413   }
414   
415   
416   /**
417    * Resolve username using a virtuser table
418    *
419    * @param string E-mail address to resolve
420    * @return string Resolved IMAP username
421    */
197601 422   static function email2user($email)
fba1f5 423   {
T 424     $user = $email;
c86e94 425     $r = self::findinvirtual('^' . quotemeta($email) . '[[:space:]]');
fba1f5 426
T 427     for ($i=0; $i<count($r); $i++)
428     {
e20033 429       $data = trim($r[$i]);
fba1f5 430       $arr = preg_split('/\s+/', $data);
T 431       if (count($arr) > 0)
432       {
433         $user = trim($arr[count($arr)-1]);
434         break;
435       }
436     }
437
438     return $user;
439   }
440
441
442   /**
443    * Resolve e-mail address from virtuser table
444    *
445    * @param string User name
446    * @return string Resolved e-mail address
447    */
197601 448   static function user2email($user)
fba1f5 449   {
c86e94 450     $email = '';
A 451     $r = self::findinvirtual('[[:space:]]' . quotemeta($user) . '[[:space:]]*$');
fba1f5 452
T 453     for ($i=0; $i<count($r); $i++)
454     {
455       $data = $r[$i];
456       $arr = preg_split('/\s+/', $data);
457       if (count($arr) > 0)
458       {
846dd7 459         $email = trim(str_replace('\\@', '@', $arr[0]));
fba1f5 460         break;
T 461       }
462     }
463
464     return $email;
465   }
83a763 466   
T 467   
468   /**
469    * Find matches of the given pattern in virtuser table
470    * 
471    * @param string Regular expression to search for
472    * @return array Matching entries
473    */
474   private static function findinvirtual($pattern)
475   {
476     $result = array();
477     $virtual = null;
478     
479     if ($virtuser_file = rcmail::get_instance()->config->get('virtuser_file'))
480       $virtual = file($virtuser_file);
481     
482     if (empty($virtual))
483       return $result;
484     
485     // check each line for matches
486     foreach ($virtual as $line)
487     {
488       $line = trim($line);
489       if (empty($line) || $line{0}=='#')
490         continue;
491         
492       if (eregi($pattern, $line))
493         $result[] = $line;
494     }
495     
496     return $result;
497   }
498
fba1f5 499
T 500 }
501
502