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

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