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