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

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