source: subversion/trunk/roundcubemail/program/include/rcube_user.php @ 2691

Last change on this file since 2691 was 2691, checked in by thomasb, 4 years ago

Move 'login' field to the right level + codestyle

File size: 14.4 KB
Line 
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 */
30class 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(get_sequence_name('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    $data = $rcmail->plugins->exec_hook('create_user', array('user'=>$user, 'user_name'=>$user_name, 'user_email'=>$user_email));
363    $user_name = $data['user_name'];
364    $user_email = $data['user_email'];
365   
366    // plugin aborted this operation
367    if ($data['abort'])
368      return false;
369
370    $dbh = $rcmail->get_dbh();
371
372    // try to resolve user in virtuser table and file
373    if ($user_email != '' && !strpos($user, '@')) {
374      if ($email_list = self::user2email($user, false, true))
375        $user_email = is_array($email_list[0]) ? $email_list[0][0] : $email_list[0];
376    }
377
378    $dbh->query(
379      "INSERT INTO ".get_table_name('users')."
380        (created, last_login, username, mail_host, alias, language)
381       VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
382      strip_newlines($user),
383      strip_newlines($host),
384      strip_newlines($data['alias'] ? $data['alias'] : $user_email),
385      $_SESSION['language']);
386
387    if ($user_id = $dbh->insert_id(get_sequence_name('users')))
388    {
389      $mail_domain = $rcmail->config->mail_domain($host);
390
391      if ($user_email=='')
392        $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
393
394      if ($user_name == '') {
395        $user_name = $user != $user_email ? $user : '';
396      }
397
398      if (empty($email_list))
399        $email_list[] = strip_newlines($user_email); 
400
401      // identities_level check
402      if (count($email_list) > 1 && $rcmail->config->get('identities_level', 0) > 1)
403        $email_list = array($email_list[0]);
404
405      // create new identities records
406      $standard = 1;
407      foreach ($email_list as $row) {
408        if (is_array($row)) {
409          $email = $row[0];
410          $name = $row[1] ? $row[1] : $user_name;
411        }
412        else {
413          $email = $row;
414          $name = $user_name;
415        }
416
417        $plugin = $rcmail->plugins->exec_hook('create_identity', array(
418          'login' => true,
419          'record' => array(
420            'user_id' => $user_id,
421            'name' => strip_newlines($name),
422            'email' => $email,
423            'standard' => $standard,
424          ),
425        ));
426         
427        if (!$plugin['abort'] && $plugin['record']['email']) {
428          $dbh->query(
429              "INSERT INTO ".get_table_name('identities')."
430                (user_id, del, standard, name, email)
431               VALUES (?, 0, ?, ?, ?)",
432              $user_id,
433              $plugin['record']['standard'],
434              $plugin['record']['name'] != NULL ? $plugin['record']['name'] : '',
435              $plugin['record']['email']);
436        }
437        $standard = 0;
438      }
439    }
440    else
441    {
442      raise_error(array(
443        'code' => 500,
444        'type' => 'php',
445        'line' => __LINE__,
446        'file' => __FILE__,
447        'message' => "Failed to create new user"), true, false);
448    }
449   
450    return $user_id ? new rcube_user($user_id) : false;
451  }
452 
453 
454  /**
455   * Resolve username using a virtuser file
456   *
457   * @param string E-mail address to resolve
458   * @return string Resolved IMAP username
459   */
460  static function email2user($email)
461  {
462    $r = self::findinvirtual('/^' . preg_quote($email, '/') . '\s/');
463
464    for ($i=0; $i<count($r); $i++)
465    {
466      $data = trim($r[$i]);
467      $arr = preg_split('/\s+/', $data);
468      if (count($arr) > 0)
469        return trim($arr[count($arr)-1]);
470    }
471
472    return NULL;
473  }
474
475
476  /**
477   * Resolve e-mail address from virtuser file/table
478   *
479   * @param string User name
480   * @param boolean If true returns first found entry
481   * @param boolean If true returns email as array (email and name for identity)
482   * @return mixed Resolved e-mail address string or array of strings
483   */
484  static function user2email($user, $first=true, $extended=false)
485  {
486    $result = array();
487    $rcmail = rcmail::get_instance();
488    $dbh = $rcmail->get_dbh();
489
490    // SQL lookup
491    if ($virtuser_query = $rcmail->config->get('virtuser_query')) {
492      $sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query));
493      while ($sql_arr = $dbh->fetch_array($sql_result))
494        if (strpos($sql_arr[0], '@')) {
495          $result[] = ($extended && count($sql_arr) > 1) ? $sql_arr : $sql_arr[0];
496          if ($first)
497            return $result[0];
498        }
499    }
500    // File lookup
501    $r = self::findinvirtual('/\s' . preg_quote($user, '/') . '\s*$/');
502    for ($i=0; $i<count($r); $i++)
503    {
504      $data = $r[$i];
505      $arr = preg_split('/\s+/', $data);
506      if (count($arr) > 0 && strpos($arr[0], '@'))
507      {
508        $result[] = trim(str_replace('\\@', '@', $arr[0]));
509
510        if ($first)
511          return $result[0];
512      }
513    }
514   
515    return empty($result) ? NULL : $result;
516  }
517 
518 
519  /**
520   * Find matches of the given pattern in virtuser file
521   *
522   * @param string Regular expression to search for
523   * @return array Matching entries
524   */
525  private static function findinvirtual($pattern)
526  {
527    $result = array();
528    $virtual = null;
529   
530    if ($virtuser_file = rcmail::get_instance()->config->get('virtuser_file'))
531      $virtual = file($virtuser_file);
532   
533    if (empty($virtual))
534      return $result;
535   
536    // check each line for matches
537    foreach ($virtual as $line)
538    {
539      $line = trim($line);
540      if (empty($line) || $line{0}=='#')
541        continue;
542       
543      if (preg_match($pattern, $line))
544        $result[] = $line;
545    }
546   
547    return $result;
548  }
549
550}
551
552
Note: See TracBrowser for help on using the repository browser.