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

Last change on this file since 5147 was 5147, checked in by thomasb, 21 months ago

Register ACL plugin for calendar task; send ajax requests to settings task

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