source: subversion/trunk/plugins/acl/acl.php @ 4970

Last change on this file since 4970 was 4970, checked in by alec, 22 months ago
  • Fix "Identifier" issue when saving acl for username without @ sign
File size: 20.2 KB
Line 
1<?php
2
3/**
4 * Folders Access Control Lists Management (RFC4314, RFC2086)
5 *
6 * @version 0.4
7 * @author Aleksander Machniak <alec@alec.pl>
8 *
9 *
10 * Copyright (C) 2011, Kolab Systems AG
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License version 2
14 * as published by the Free Software Foundation.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 */
25
26class acl extends rcube_plugin
27{
28    public $task = 'settings|addressbook';
29
30    private $rc;
31    private $supported = null;
32    private $mbox;
33    private $ldap;
34    private $specials = array('anyone', 'anonymous');
35
36    /**
37     * Plugin initialization
38     */
39    function init()
40    {
41        $this->rc = rcmail::get_instance();
42
43        // Register hooks
44        $this->add_hook('folder_form', array($this, 'folder_form'));
45        // kolab_addressbook plugin
46        $this->add_hook('addressbook_form', array($this, 'folder_form'));
47        // Plugin actions
48        $this->register_action('plugin.acl', array($this, 'acl_actions'));
49        $this->register_action('plugin.acl-autocomplete', array($this, 'acl_autocomplete'));
50    }
51
52    /**
53     * Handler for plugin actions (AJAX)
54     */
55    function acl_actions()
56    {
57        $action = trim(get_input_value('_act', RCUBE_INPUT_GPC));
58
59        // Connect to IMAP
60        $this->rc->imap_init();
61        $this->rc->imap_connect();
62
63        // Load localization and configuration
64        $this->add_texts('localization/');
65        $this->load_config();
66
67        if ($action == 'save') {
68            $this->action_save();
69        }
70        else if ($action == 'delete') {
71            $this->action_delete();
72        }
73        else if ($action == 'list') {
74            $this->action_list();
75        }
76
77        // Only AJAX actions
78        $this->rc->output->send();
79    }
80
81    /**
82     * Handler for user login autocomplete request
83     */
84    function acl_autocomplete()
85    {
86        $this->load_config();
87
88        $search = get_input_value('_search', RCUBE_INPUT_GPC, true);
89        $users  = array();
90
91        if ($this->init_ldap()) {
92            $this->ldap->set_pagesize(15);
93            $result = $this->ldap->search('*', $search);
94
95            foreach ($result->records as $record) {
96                $user = $record['uid'];
97
98                if (is_array($user)) {
99                    $user = array_filter($user);
100                    $user = $user[0];
101                }
102
103                if ($user) {
104                    if ($record['name'])
105                        $user = $record['name'] . ' (' . $user . ')';
106
107                    $users[] = $user;
108                }
109            }
110        }
111
112        sort($users, SORT_LOCALE_STRING);
113
114        $this->rc->output->command('ksearch_query_results', $users, $search);
115        $this->rc->output->send();
116    }
117
118    /**
119     * Handler for 'folder_form' hook
120     *
121     * @param array $args Hook arguments array (form data)
122     *
123     * @return array Hook arguments array
124     */
125    function folder_form($args)
126    {
127        // Edited folder name (empty in create-folder mode)
128        $mbox_imap = $args['options']['name'];
129        if (!strlen($mbox_imap)) {
130            return $args;
131        }
132/*
133        // Do nothing on protected folders (?)
134        if ($args['options']['protected']) {
135            return $args;
136        }
137*/
138        // Namespace root
139        if ($args['options']['is_root']) {
140            return $args;
141        }
142
143        // Get MYRIGHTS
144        if (!($myrights = $args['options']['rights'])) {
145            return $args;
146        }
147
148        // Do nothing if no ACL support
149        if (!$this->rc->imap->get_capability('ACL')) {
150            return $args;
151        }
152
153        // Load localization and include scripts
154        $this->load_config();
155        $this->add_texts('localization/', array('deleteconfirm', 'norights',
156            'nouser', 'deleting', 'saving'));
157        $this->include_script('acl.js');
158        $this->rc->output->include_script('list.js');
159        $this->include_stylesheet($this->local_skin_path().'/acl.css');
160
161        // add Info fieldset if it doesn't exist
162        if (!isset($args['form']['props']['fieldsets']['info']))
163            $args['form']['props']['fieldsets']['info'] = array(
164                'name'  => rcube_label('info'),
165                'content' => array());
166
167        // Display folder rights to 'Info' fieldset
168        $args['form']['props']['fieldsets']['info']['content']['myrights'] = array(
169            'label' => Q($this->gettext('myrights')),
170            'value' => $this->acl2text($myrights)
171        );
172
173        // Return if not folder admin
174        if (!in_array('a', $myrights)) {
175            return $args;
176        }
177
178        // The 'Sharing' tab
179        $this->mbox = $mbox_imap;
180        $this->rc->output->set_env('acl_users_source', (bool) $this->rc->config->get('acl_users_source'));
181        $this->rc->output->set_env('mailbox', $mbox_imap);
182        $this->rc->output->add_handlers(array(
183            'acltable'  => array($this, 'templ_table'),
184            'acluser'   => array($this, 'templ_user'),
185            'aclrights' => array($this, 'templ_rights'),
186        ));
187
188        $args['form']['sharing'] = array(
189            'name'    => Q($this->gettext('sharing')),
190            'content' => $this->rc->output->parse('acl.table', false, false),
191        );
192
193        return $args;
194    }
195
196    /**
197     * Creates ACL rights table
198     *
199     * @param array $attrib Template object attributes
200     *
201     * @return string HTML Content
202     */
203    function templ_table($attrib)
204    {
205        if (empty($attrib['id']))
206            $attrib['id'] = 'acl-table';
207
208        $out = $this->list_rights($attrib);
209
210        $this->rc->output->add_gui_object('acltable', $attrib['id']);
211
212        return $out;
213    }
214
215    /**
216     * Creates ACL rights form (rights list part)
217     *
218     * @param array $attrib Template object attributes
219     *
220     * @return string HTML Content
221     */
222    function templ_rights($attrib)
223    {
224        // Get supported rights
225        $supported = $this->rights_supported();
226
227        // depending on server capability either use 'te' or 'd' for deleting msgs
228        $deleteright = implode(array_intersect(str_split('ted'), $supported));
229
230        $out = '';
231        $ul  = '';
232        $input = new html_checkbox();
233
234        // Advanced rights
235        $attrib['id'] = 'advancedrights';
236        foreach ($supported as $val) {
237            $id = "acl$val";
238            $ul .= html::tag('li', null,
239                $input->show('', array(
240                    'name' => "acl[$val]", 'value' => $val, 'id' => $id))
241                . html::label(array('for' => $id, 'title' => $this->gettext('longacl'.$val)),
242                    $this->gettext('acl'.$val)));
243        }
244
245        $out = html::tag('ul', $attrib, $ul, html::$common_attrib);
246
247        // Simple rights
248        $ul = '';
249        $attrib['id'] = 'simplerights';
250        $items = array(
251            'read' => 'lrs',
252            'write' => 'wi',
253            'delete' => $deleteright,
254            'full' => implode($supported),
255        );
256
257        foreach ($items as $key => $val) {
258            $id = "acl$key";
259            $ul .= html::tag('li', null,
260                $input->show('', array(
261                    'name' => "acl[$val]", 'value' => $val, 'id' => $id))
262                . html::label(array('for' => $id, 'title' => $this->gettext('longacl'.$key)),
263                    $this->gettext('acl'.$key)));
264        }
265
266        $out .= "\n" . html::tag('ul', $attrib, $ul, html::$common_attrib);
267
268        $this->rc->output->set_env('acl_items', $items);
269
270        return $out;
271    }
272
273    /**
274     * Creates ACL rights form (user part)
275     *
276     * @param array $attrib Template object attributes
277     *
278     * @return string HTML Content
279     */
280    function templ_user($attrib)
281    {
282        // Create username input
283        $attrib['name'] = 'acluser';
284
285        $textfield = new html_inputfield($attrib);
286
287        $fields['user'] = html::label(array('for' => 'iduser'), $this->gettext('username'))
288            . ' ' . $textfield->show();
289
290        // Add special entries
291        if (!empty($this->specials)) {
292            foreach ($this->specials as $key) {
293                $fields[$key] = html::label(array('for' => 'id'.$key), $this->gettext($key));
294            }
295        }
296
297        $this->rc->output->set_env('acl_specials', $this->specials);
298
299        // Create list with radio buttons
300        if (count($fields) > 1) {
301            $ul = '';
302            $radio = new html_radiobutton(array('name' => 'usertype'));
303            foreach ($fields as $key => $val) {
304                $ul .= html::tag('li', null, $radio->show($key == 'user' ? 'user' : '',
305                        array('value' => $key, 'id' => 'id'.$key))
306                    . $val);
307            }
308
309            $out = html::tag('ul', array('id' => 'usertype'), $ul, html::$common_attrib);
310        }
311        // Display text input alone
312        else {
313            $out = $fields['user'];
314        }
315
316        return $out;
317    }
318
319    /**
320     * Creates ACL rights table
321     *
322     * @param array $attrib Template object attributes
323     *
324     * @return string HTML Content
325     */
326    private function list_rights($attrib=array())
327    {
328        // Get ACL for the folder
329        $acl = $this->rc->imap->get_acl($this->mbox);
330
331        if (!is_array($acl)) {
332            $acl = array();
333        }
334
335        // Keep special entries (anyone/anonymous) on top of the list
336        if (!empty($this->specials) && !empty($acl)) {
337            foreach ($this->specials as $key) {
338                if (isset($acl[$key])) {
339                    $acl_special[$key] = $acl[$key];
340                    unset($acl[$key]);
341                }
342            }
343        }
344
345        // Sort the list by username
346        uksort($acl, 'strnatcasecmp');
347
348        if (!empty($acl_special)) {
349            $acl = array_merge($acl_special, $acl);
350        }
351
352        // Get supported rights and build column names
353        $supported = $this->rights_supported();
354
355        // depending on server capability either use 'te' or 'd' for deleting msgs
356        $deleteright = implode(array_intersect(str_split('ted'), $supported));
357
358        // Use advanced or simple (grouped) rights
359        $advanced = $this->rc->config->get('acl_advanced_mode');
360
361        if ($advanced) {
362            $items = array();
363            foreach ($supported as $sup) {
364                $items[$sup] = $sup;
365            }
366        }
367        else {
368            $items = array(
369                'read' => 'lrs',
370                'write' => 'wi',
371                'delete' => $deleteright,
372                'full' => implode($supported),
373            );
374        }
375
376        // Create the table
377        $attrib['noheader'] = true;
378        $table = new html_table($attrib);
379
380        // Create table header
381        $table->add_header('user', $this->gettext('identifier'));
382        foreach (array_keys($items) as $key) {
383            $table->add_header('acl'.$key, $this->gettext('shortacl'.$key));
384        }
385
386        $i = 1;
387        $js_table = array();
388        foreach ($acl as $user => $rights) {
389            if ($this->rc->imap->conn->user == $user) {
390                continue;
391            }
392
393            // filter out virtual rights (c or d) the server may return
394            $userrights = array_intersect($rights, $supported);
395            $userid = html_identifier($user);
396
397            if (!empty($this->specials) && in_array($user, $this->specials)) {
398                $user = $this->gettext($user);
399            }
400
401            $table->add_row(array('id' => 'rcmrow'.$userid));
402            $table->add('user', Q($user));
403
404            foreach ($items as $key => $right) {
405                $in = $this->acl_compare($userrights, $right);
406                $table->add('acl'.$key . ' ' . ($in ? 'enabled' : 'disabled'), '');
407            }
408
409            $js_table[$userid] = implode($userrights);
410        }
411
412        $this->rc->output->set_env('acl', $js_table);
413        $this->rc->output->set_env('acl_advanced', $advanced);
414
415        $out = $table->show();
416
417        return $out;
418    }
419
420    /**
421     * Handler for ACL update/create action
422     */
423    private function action_save()
424    {
425        $mbox  = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true, 'UTF7-IMAP'));
426        $user  = trim(get_input_value('_user', RCUBE_INPUT_GPC));
427        $acl   = trim(get_input_value('_acl', RCUBE_INPUT_GPC));
428        $oldid = trim(get_input_value('_old', RCUBE_INPUT_GPC));
429
430        $acl = array_intersect(str_split($acl), $this->rights_supported());
431
432        if (!empty($this->specials) && in_array($user, $this->specials)) {
433            $username = $this->gettext($user);
434        }
435        else {
436            if (!strpos($user, '@') && ($realm = $this->get_realm())) {
437                $user .= '@' . rcube_idn_to_ascii(preg_replace('/^@/', '', $realm));
438            }
439            $username = $user;
440        }
441
442        if ($acl && $user && strlen($mbox)
443            && $this->rc->imap->set_acl($mbox, $user, $acl)
444        ) {
445            $ret = array('id' => html_identifier($user),
446                 'username' => $username, 'acl' => implode($acl), 'old' => $oldid);
447            $this->rc->output->command('acl_update', $ret);
448            $this->rc->output->show_message($oldid ? 'acl.updatesuccess' : 'acl.createsuccess', 'confirmation');
449        }
450        else {
451            $this->rc->output->show_message($oldid ? 'acl.updateerror' : 'acl.createerror', 'error');
452        }
453    }
454
455    /**
456     * Handler for ACL delete action
457     */
458    private function action_delete()
459    {
460        $mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true, 'UTF7-IMAP'));
461        $user = trim(get_input_value('_user', RCUBE_INPUT_GPC));
462
463        $user = explode(',', $user);
464
465        foreach ($user as $u) {
466            if ($this->rc->imap->delete_acl($mbox, $u)) {
467                $this->rc->output->command('acl_remove_row', html_identifier($u));
468            }
469            else {
470                $error = true;
471            }
472        }
473
474        if (!$error) {
475            $this->rc->output->show_message('acl.deletesuccess', 'confirmation');
476        }
477        else {
478            $this->rc->output->show_message('acl.deleteerror', 'error');
479        }
480    }
481
482    /**
483     * Handler for ACL list update action (with display mode change)
484     */
485    private function action_list()
486    {
487        if (in_array('acl_advanced_mode', (array)$this->rc->config->get('dont_override'))) {
488            return;
489        }
490
491        $this->mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true, 'UTF7-IMAP'));
492        $advanced   = trim(get_input_value('_mode', RCUBE_INPUT_GPC));
493        $advanced   = $advanced == 'advanced' ? true : false;
494
495        // Save state in user preferences
496        $this->rc->user->save_prefs(array('acl_advanced_mode' => $advanced));
497
498        $out = $this->list_rights();
499
500        $out = preg_replace(array('/^<table[^>]+>/', '/<\/table>$/'), '', $out);
501
502        $this->rc->output->command('acl_list_update', $out);
503    }
504
505    /**
506     * Creates <UL> list with descriptive access rights
507     *
508     * @param array $rights MYRIGHTS result
509     *
510     * @return string HTML content
511     */
512    function acl2text($rights)
513    {
514        if (empty($rights)) {
515            return '';
516        }
517
518        $supported = $this->rights_supported();
519        $list      = array();
520        $attrib    = array(
521            'name' => 'rcmyrights',
522            'style' => 'padding: 0 15px;',
523        );
524
525        foreach ($supported as $right) {
526            if (in_array($right, $rights)) {
527                $list[] = html::tag('li', null, Q($this->gettext('acl' . $right)));
528            }
529        }
530
531        if (count($list) == count($supported))
532            return Q($this->gettext('aclfull'));
533
534        return html::tag('ul', $attrib, implode("\n", $list));
535    }
536
537    /**
538     * Compares two ACLs (according to supported rights)
539     *
540     * @param array $acl1 ACL rights array (or string)
541     * @param array $acl2 ACL rights array (or string)
542     *
543     * @param boolean Comparision result
544     */
545    function acl_compare($acl1, $acl2)
546    {
547        if (!is_array($acl1)) $acl1 = str_split($acl1);
548        if (!is_array($acl2)) $acl2 = str_split($acl2);
549
550        $rights = $this->rights_supported();
551
552        $acl1 = array_intersect($acl1, $rights);
553        $acl2 = array_intersect($acl2, $rights);
554        $res  = array_intersect($acl1, $acl2);
555
556        return count($res) == count($acl2);
557    }
558
559    /**
560     * Get list of supported access rights (according to RIGHTS capability)
561     *
562     * @return array List of supported access rights abbreviations
563     */
564    function rights_supported()
565    {
566        if ($this->supported !== null) {
567            return $this->supported;
568        }
569
570        $capa = $this->rc->imap->get_capability('RIGHTS');
571
572        if (is_array($capa)) {
573            $rights = strtolower($capa[0]);
574        }
575        else {
576            $rights = 'cd';
577        }
578
579        return $this->supported = str_split('lrswi' . $rights . 'pa');
580    }
581
582    /**
583     * Username realm detection.
584     *
585     * @return string Username realm (domain)
586     */
587    private function get_realm()
588    {
589        // When user enters a username without domain part, realm
590        // alows to add it to the username (and display correct username in the table)
591
592        if (isset($_SESSION['acl_username_realm'])) {
593            return $_SESSION['acl_username_realm'];
594        }
595
596        // find realm in username of logged user (?)
597        list($name, $domain) = explode('@', $_SESSION['username']);
598
599        // Use (always existent) ACL entry on the INBOX for the user to determine
600        // whether or not the user ID in ACL entries need to be qualified and how
601        // they would need to be qualified.
602        if (empty($domain)) {
603            $acl = $this->rc->imap->get_acl('INBOX');
604            if (is_array($acl)) {
605                $regexp = '/^' . preg_quote($_SESSION['username'], '/') . '@(.*)$/';
606                $regexp = '/^' . preg_quote('aleksander.machniak', '/') . '@(.*)$/';
607                foreach (array_keys($acl) as $name) {
608                    if (preg_match($regexp, $name, $matches)) {
609                        $domain = $matches[1];
610                        break;
611                    }
612                }
613            }
614        }
615
616        return $_SESSION['acl_username_realm'] = $domain;
617    }
618
619    /**
620     * Initializes autocomplete LDAP backend
621     */
622    private function init_ldap()
623    {
624        if ($this->ldap)
625            return $this->ldap->ready;
626
627        // get LDAP config
628        $config = $this->rc->config->get('acl_users_source');
629
630        if (empty($config)) {
631            return false;
632        }
633
634        // not an array, use configured ldap_public source
635        if (!is_array($config)) {
636            $ldap_config = (array) $this->rc->config->get('ldap_public');
637            $config = $ldap_config[$config];
638        }
639
640        $uid_field = $this->rc->config->get('acl_users_field', 'mail');
641        $filter    = $this->rc->config->get('acl_users_filter');
642
643        if (empty($uid_field) || empty($config)) {
644            return false;
645        }
646
647        // get name attribute
648        if (!empty($config['fieldmap'])) {
649            $name_field = $config['fieldmap']['name'];
650        }
651        // ... no fieldmap, use the old method
652        if (empty($name_field)) {
653            $name_field = $config['name_field'];
654        }
655
656        // add UID field to fieldmap, so it will be returned in a record with name
657        $config['fieldmap'] = array(
658            'name' => $name_field,
659            'uid'  => $uid_field,
660        );
661
662        // search in UID and name fields
663        $config['search_fields'] = array_values($config['fieldmap']);
664        $config['required_fields'] = array($uid_field);
665
666        // set search filter
667        if ($filter)
668            $config['filter'] = $filter;
669
670        // disable vlv
671        $config['vlv'] = false;
672
673        // Initialize LDAP connection
674        $this->ldap = new rcube_ldap($config,
675            $this->rc->config->get('ldap_debug'),
676            $this->rc->config->mail_domain($_SESSION['imap_host']));
677
678        return $this->ldap->ready;
679    }
680}
Note: See TracBrowser for help on using the repository browser.