]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_user.php
Imported Upstream version 0.3
[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 identity record
139    */
140   function get_identity($id = null)
141   {
142     $result = $this->list_identities($id ? sprintf('AND identity_id=%d', $id) : '');
143     return $result[0];
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     $result = array();
164     while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
165       $result[] = $sql_arr;
166     }
167     
168     return $result;
169   }
170   
171   
172   /**
173    * Update a specific identity record
174    *
175    * @param int    Identity ID
176    * @param array  Hash array with col->value pairs to save
177    * @return boolean True if saved successfully, false if nothing changed
178    */
179   function update_identity($iid, $data)
180   {
181     if (!$this->ID)
182       return false;
183     
184     $query_cols = $query_params = array();
185     
186     foreach ((array)$data as $col => $value)
187     {
188       $query_cols[] = $this->db->quoteIdentifier($col) . '=?';
189       $query_params[] = $value;
190     }
191     $query_params[] = $iid;
192     $query_params[] = $this->ID;
193
194     $sql = "UPDATE ".get_table_name('identities')."
195        SET ".join(', ', $query_cols)."
196        WHERE  identity_id=?
197        AND    user_id=?
198        AND    del<>1";
199
200     call_user_func_array(array($this->db, 'query'),
201                         array_merge(array($sql), $query_params));
202     
203     return $this->db->affected_rows();
204   }
205   
206   
207   /**
208    * Create a new identity record linked with this user
209    *
210    * @param array  Hash array with col->value pairs to save
211    * @return int  The inserted identity ID or false on error
212    */
213   function insert_identity($data)
214   {
215     if (!$this->ID)
216       return false;
217
218     $insert_cols = $insert_values = array();
219     foreach ((array)$data as $col => $value)
220     {
221       $insert_cols[] = $this->db->quoteIdentifier($col);
222       $insert_values[] = $value;
223     }
224     $insert_cols[] = 'user_id';
225     $insert_values[] = $this->ID;
226
227     $sql = "INSERT INTO ".get_table_name('identities')."
228         (".join(', ', $insert_cols).")
229        VALUES (".join(', ', array_pad(array(), sizeof($insert_values), '?')).")";
230
231     call_user_func_array(array($this->db, 'query'),
232                         array_merge(array($sql), $insert_values));
233
234     return $this->db->insert_id('identities');
235   }
236   
237   
238   /**
239    * Mark the given identity as deleted
240    *
241    * @param int  Identity ID
242    * @return boolean True if deleted successfully, false if nothing changed
243    */
244   function delete_identity($iid)
245   {
246     if (!$this->ID)
247       return false;
248
249     if (!$this->ID || $this->ID == '')
250       return false;
251
252     $sql_result = $this->db->query("SELECT count(*) AS ident_count FROM " .
253       get_table_name('identities') .
254       " WHERE user_id = ? AND del <> 1",
255       $this->ID);
256
257     $sql_arr = $this->db->fetch_assoc($sql_result);
258     if ($sql_arr['ident_count'] <= 1)
259       return false;
260     
261     $this->db->query(
262       "UPDATE ".get_table_name('identities')."
263        SET    del=1
264        WHERE  user_id=?
265        AND    identity_id=?",
266       $this->ID,
267       $iid);
268
269     return $this->db->affected_rows();
270   }
271   
272   
273   /**
274    * Make this identity the default one for this user
275    *
276    * @param int The identity ID
277    */
278   function set_default($iid)
279   {
280     if ($this->ID && $iid)
281     {
282       $this->db->query(
283         "UPDATE ".get_table_name('identities')."
284          SET ".$this->db->quoteIdentifier('standard')."='0'
285          WHERE  user_id=?
286          AND    identity_id<>?
287          AND    del<>1",
288         $this->ID,
289         $iid);
290     }
291   }
292   
293   
294   /**
295    * Update user's last_login timestamp
296    */
297   function touch()
298   {
299     if ($this->ID)
300     {
301       $this->db->query(
302         "UPDATE ".get_table_name('users')."
303          SET    last_login=".$this->db->now()."
304          WHERE  user_id=?",
305         $this->ID);
306     }
307   }
308   
309   
310   /**
311    * Clear the saved object state
312    */
313   function reset()
314   {
315     $this->ID = null;
316     $this->data = null;
317   }
318   
319   
320   /**
321    * Find a user record matching the given name and host
322    *
323    * @param string IMAP user name
324    * @param string IMAP host name
325    * @return object rcube_user New user instance
326    */
327   static function query($user, $host)
328   {
329     $dbh = rcmail::get_instance()->get_dbh();
330     
331     // query for matching user name
332     $query = "SELECT * FROM ".get_table_name('users')." WHERE mail_host=? AND %s=?";
333     $sql_result = $dbh->query(sprintf($query, 'username'), $host, $user);
334     
335     // query for matching alias
336     if (!($sql_arr = $dbh->fetch_assoc($sql_result))) {
337       $sql_result = $dbh->query(sprintf($query, 'alias'), $host, $user);
338       $sql_arr = $dbh->fetch_assoc($sql_result);
339     }
340     
341     // user already registered -> overwrite username
342     if ($sql_arr)
343       return new rcube_user($sql_arr['user_id'], $sql_arr);
344     else
345       return false;
346   }
347   
348   
349   /**
350    * Create a new user record and return a rcube_user instance
351    *
352    * @param string IMAP user name
353    * @param string IMAP host
354    * @return object rcube_user New user instance
355    */
356   static function create($user, $host)
357   {
358     $user_name  = '';
359     $user_email = '';
360     $rcmail = rcmail::get_instance();
361
362     // try to resolve user in virtuser table and file
363     if (!strpos($user, '@')) {
364       if ($email_list = self::user2email($user, false, true))
365         $user_email = is_array($email_list[0]) ? $email_list[0][0] : $email_list[0];
366     }
367
368     $data = $rcmail->plugins->exec_hook('create_user',
369         array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
370
371     // plugin aborted this operation
372     if ($data['abort'])
373       return false;
374
375     $user_name = $data['user_name'];
376     $user_email = $data['user_email'];
377
378     $dbh = $rcmail->get_dbh();
379
380     $dbh->query(
381       "INSERT INTO ".get_table_name('users')."
382         (created, last_login, username, mail_host, alias, language)
383        VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
384       strip_newlines($user),
385       strip_newlines($host),
386       strip_newlines($data['alias'] ? $data['alias'] : $user_email),
387       $_SESSION['language']);
388
389     if ($user_id = $dbh->insert_id('users'))
390     {
391       // create rcube_user instance to make plugin hooks work
392       $user_instance = new rcube_user($user_id);
393       $rcmail->user = $user_instance;
394
395       $mail_domain = $rcmail->config->mail_domain($host);
396
397       if ($user_email=='')
398         $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
399
400       if ($user_name == '') {
401         $user_name = $user != $user_email ? $user : '';
402       }
403
404       if (empty($email_list))
405         $email_list[] = strip_newlines($user_email);
406       // identities_level check
407       else if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
408         $email_list = array($email_list[0]);
409
410       // create new identities records
411       $standard = 1;
412       foreach ($email_list as $row) {
413         if (is_array($row)) {
414           $email = $row[0];
415           $name = $row[1] ? $row[1] : $user_name;
416         }
417         else {
418           $email = $row;
419           $name = $user_name;
420         }
421
422         $plugin = $rcmail->plugins->exec_hook('create_identity', array(
423           'login' => true,
424           'record' => array(
425             'user_id' => $user_id,
426             'name' => strip_newlines($name),
427             'email' => $email,
428             'standard' => $standard,
429             'signature' => '',
430           ),
431         ));
432           
433         if (!$plugin['abort'] && $plugin['record']['email']) {
434           $dbh->query(
435               "INSERT INTO ".get_table_name('identities')."
436                 (user_id, del, standard, name, email, signature)
437                VALUES (?, 0, ?, ?, ?, ?)",
438               $user_id,
439               $plugin['record']['standard'],
440               $plugin['record']['name'] != NULL ? $plugin['record']['name'] : '',
441               $plugin['record']['email'],
442               $plugin['record']['signature']);
443         }
444         $standard = 0;
445       }
446     }
447     else
448     {
449       raise_error(array(
450         'code' => 500,
451         'type' => 'php',
452         'line' => __LINE__,
453         'file' => __FILE__,
454         'message' => "Failed to create new user"), true, false);
455     }
456     
457     return $user_id ? $user_instance : false;
458   }
459   
460   
461   /**
462    * Resolve username using a virtuser file
463    *
464    * @param string E-mail address to resolve
465    * @return string Resolved IMAP username
466    */
467   static function email2user($email)
468   {
469     $r = self::findinvirtual('/^' . preg_quote($email, '/') . '\s/');
470
471     for ($i=0; $i<count($r); $i++)
472     {
473       $data = trim($r[$i]);
474       $arr = preg_split('/\s+/', $data);
475       if (count($arr) > 0)
476         return trim($arr[count($arr)-1]);
477     }
478
479     return NULL;
480   }
481
482
483   /**
484    * Resolve e-mail address from virtuser file/table
485    *
486    * @param string User name
487    * @param boolean If true returns first found entry
488    * @param boolean If true returns email as array (email and name for identity)
489    * @return mixed Resolved e-mail address string or array of strings
490    */
491   static function user2email($user, $first=true, $extended=false)
492   {
493     $result = array();
494     $rcmail = rcmail::get_instance();
495     $dbh = $rcmail->get_dbh();
496
497     // SQL lookup
498     if ($virtuser_query = $rcmail->config->get('virtuser_query')) {
499       $sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query));
500       while ($sql_arr = $dbh->fetch_array($sql_result))
501         if (strpos($sql_arr[0], '@')) {
502           $result[] = ($extended && count($sql_arr) > 1) ? $sql_arr : $sql_arr[0];
503           if ($first)
504             return $result[0];
505         }
506     }
507     // File lookup
508     $r = self::findinvirtual('/\s' . preg_quote($user, '/') . '\s*$/');
509     for ($i=0; $i<count($r); $i++)
510     {
511       $data = $r[$i];
512       $arr = preg_split('/\s+/', $data);
513       if (count($arr) > 0 && strpos($arr[0], '@'))
514       {
515         $result[] = trim(str_replace('\\@', '@', $arr[0]));
516
517         if ($first)
518           return $result[0];
519       }
520     }
521     
522     return empty($result) ? NULL : $result;
523   }
524   
525   
526   /**
527    * Find matches of the given pattern in virtuser file
528    * 
529    * @param string Regular expression to search for
530    * @return array Matching entries
531    */
532   private static function findinvirtual($pattern)
533   {
534     $result = array();
535     $virtual = null;
536     
537     if ($virtuser_file = rcmail::get_instance()->config->get('virtuser_file'))
538       $virtual = file($virtuser_file);
539     
540     if (empty($virtual))
541       return $result;
542     
543     // check each line for matches
544     foreach ($virtual as $line)
545     {
546       $line = trim($line);
547       if (empty($line) || $line{0}=='#')
548         continue;
549         
550       if (preg_match($pattern, $line))
551         $result[] = $line;
552     }
553     
554     return $result;
555   }
556
557 }
558
559