source: subversion/trunk/roundcubemail/program/include/rcube_user.inc @ 1123

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