Thomas Bruederli
2012-08-06 c41a86e5cc26dc8ae37ed4b3fddcaa195b1616a4
commit | author | age
48e9c1 1 <?php
T 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-2012, 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->storage_init();
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         $sid    = get_input_value('_id', RCUBE_INPUT_GPC);
90         $users  = array();
91
92         if ($this->init_ldap()) {
93             $max  = (int) $this->rc->config->get('autocomplete_max', 15);
94             $mode = (int) $this->rc->config->get('addressbook_search_mode');
95
96             $this->ldap->set_pagesize($max);
97             $result = $this->ldap->search('*', $search, $mode);
98
99             foreach ($result->records as $record) {
100                 $user = $record['uid'];
101
102                 if (is_array($user)) {
103                     $user = array_filter($user);
104                     $user = $user[0];
105                 }
106
107                 if ($user) {
108                     if ($record['name'])
109                         $user = $record['name'] . ' (' . $user . ')';
110
111                     $users[] = $user;
112                 }
113             }
114         }
115
116         sort($users, SORT_LOCALE_STRING);
117
118         $this->rc->output->command('ksearch_query_results', $users, $search, $sid);
119         $this->rc->output->send();
120     }
121
122     /**
123      * Handler for 'folder_form' hook
124      *
125      * @param array $args Hook arguments array (form data)
126      *
127      * @return array Hook arguments array
128      */
129     function folder_form($args)
130     {
131         $mbox_imap = $args['options']['name'];
b866a2 132         $myrights  = $args['options']['rights'];
AM 133
134         // Edited folder name (empty in create-folder mode)
48e9c1 135         if (!strlen($mbox_imap)) {
T 136             return $args;
137         }
138 /*
139         // Do nothing on protected folders (?)
140         if ($args['options']['protected']) {
141             return $args;
142         }
143 */
144         // Get MYRIGHTS
b866a2 145         if (empty($myrights)) {
48e9c1 146             return $args;
T 147         }
148
149         // Load localization and include scripts
150         $this->load_config();
151         $this->add_texts('localization/', array('deleteconfirm', 'norights',
152             'nouser', 'deleting', 'saving'));
153         $this->include_script('acl.js');
154         $this->rc->output->include_script('list.js');
155         $this->include_stylesheet($this->local_skin_path().'/acl.css');
156
157         // add Info fieldset if it doesn't exist
158         if (!isset($args['form']['props']['fieldsets']['info']))
159             $args['form']['props']['fieldsets']['info'] = array(
160                 'name'  => rcube_label('info'),
161                 'content' => array());
162
163         // Display folder rights to 'Info' fieldset
164         $args['form']['props']['fieldsets']['info']['content']['myrights'] = array(
165             'label' => Q($this->gettext('myrights')),
166             'value' => $this->acl2text($myrights)
167         );
168
169         // Return if not folder admin
170         if (!in_array('a', $myrights)) {
171             return $args;
172         }
173
174         // The 'Sharing' tab
175         $this->mbox = $mbox_imap;
176         $this->rc->output->set_env('acl_users_source', (bool) $this->rc->config->get('acl_users_source'));
177         $this->rc->output->set_env('mailbox', $mbox_imap);
178         $this->rc->output->add_handlers(array(
179             'acltable'  => array($this, 'templ_table'),
180             'acluser'   => array($this, 'templ_user'),
181             'aclrights' => array($this, 'templ_rights'),
182         ));
183
184         $this->rc->output->set_env('autocomplete_max', (int)$this->rc->config->get('autocomplete_max', 15));
185         $this->rc->output->set_env('autocomplete_min_length', $this->rc->config->get('autocomplete_min_length'));
186         $this->rc->output->add_label('autocompletechars', 'autocompletemore');
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             'other' => preg_replace('/[lrswi'.$deleteright.']/', '', 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->storage->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                 'other' => preg_replace('/[lrswi'.$deleteright.']/', '', 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             $label = $this->gettext('shortacl'.$key);
384             $table->add_header(array('class' => 'acl'.$key, 'title' => $label), $label);
385         }
386
387         $i = 1;
388         $js_table = array();
389         foreach ($acl as $user => $rights) {
390             if ($this->rc->storage->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         $users = $oldid ? array($user) : explode(',', $user);
438
439         foreach ($users as $user) {
440             $user = trim($user);
441
442             if (!empty($this->specials) && in_array($user, $this->specials)) {
443                 $username = $this->gettext($user);
444             }
445             else {
446                 if (!strpos($user, '@') && ($realm = $this->get_realm())) {
447                     $user .= '@' . rcube_idn_to_ascii(preg_replace('/^@/', '', $realm));
448                 }
449                 $username = $user;
450             }
451
452             if (!$acl || !$user || !strlen($mbox)) {
453                 continue;
454             }
455
456             if ($user != $_SESSION['username'] && $username != $_SESSION['username']) {
457                 if ($this->rc->storage->set_acl($mbox, $user, $acl)) {
458                     $ret = array('id' => html_identifier($user),
459                          'username' => $username, 'acl' => implode($acl), 'old' => $oldid);
460                     $this->rc->output->command('acl_update', $ret);
461                     $result++;
462                 }
463             }
464         }
465
466         if ($result) {
467             $this->rc->output->show_message($oldid ? 'acl.updatesuccess' : 'acl.createsuccess', 'confirmation');
468         }
469         else {
470             $this->rc->output->show_message($oldid ? 'acl.updateerror' : 'acl.createerror', 'error');
471         }
472     }
473
474     /**
475      * Handler for ACL delete action
476      */
477     private function action_delete()
478     {
479         $mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true)); //UTF7-IMAP
480         $user = trim(get_input_value('_user', RCUBE_INPUT_GPC));
481
482         $user = explode(',', $user);
483
484         foreach ($user as $u) {
485             $u = trim($u);
486             if ($this->rc->storage->delete_acl($mbox, $u)) {
487                 $this->rc->output->command('acl_remove_row', html_identifier($u));
488             }
489             else {
490                 $error = true;
491             }
492         }
493
494         if (!$error) {
495             $this->rc->output->show_message('acl.deletesuccess', 'confirmation');
496         }
497         else {
498             $this->rc->output->show_message('acl.deleteerror', 'error');
499         }
500     }
501
502     /**
503      * Handler for ACL list update action (with display mode change)
504      */
505     private function action_list()
506     {
507         if (in_array('acl_advanced_mode', (array)$this->rc->config->get('dont_override'))) {
508             return;
509         }
510
511         $this->mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true)); // UTF7-IMAP
512         $advanced   = trim(get_input_value('_mode', RCUBE_INPUT_GPC));
513         $advanced   = $advanced == 'advanced' ? true : false;
514
515         // Save state in user preferences
516         $this->rc->user->save_prefs(array('acl_advanced_mode' => $advanced));
517
518         $out = $this->list_rights();
519
520         $out = preg_replace(array('/^<table[^>]+>/', '/<\/table>$/'), '', $out);
521
522         $this->rc->output->command('acl_list_update', $out);
523     }
524
525     /**
526      * Creates <UL> list with descriptive access rights
527      *
528      * @param array $rights MYRIGHTS result
529      *
530      * @return string HTML content
531      */
532     function acl2text($rights)
533     {
534         if (empty($rights)) {
535             return '';
536         }
537
538         $supported = $this->rights_supported();
539         $list      = array();
540         $attrib    = array(
541             'name' => 'rcmyrights',
542             'style' => 'margin:0; padding:0 15px;',
543         );
544
545         foreach ($supported as $right) {
546             if (in_array($right, $rights)) {
547                 $list[] = html::tag('li', null, Q($this->gettext('acl' . $right)));
548             }
549         }
550
551         if (count($list) == count($supported))
552             return Q($this->gettext('aclfull'));
553
554         return html::tag('ul', $attrib, implode("\n", $list));
555     }
556
557     /**
558      * Compares two ACLs (according to supported rights)
559      *
560      * @param array $acl1 ACL rights array (or string)
561      * @param array $acl2 ACL rights array (or string)
562      *
563      * @param int Comparision result, 2 - full match, 1 - partial match, 0 - no match
564      */
565     function acl_compare($acl1, $acl2)
566     {
567         if (!is_array($acl1)) $acl1 = str_split($acl1);
568         if (!is_array($acl2)) $acl2 = str_split($acl2);
569
570         $rights = $this->rights_supported();
571
572         $acl1 = array_intersect($acl1, $rights);
573         $acl2 = array_intersect($acl2, $rights);
574         $res  = array_intersect($acl1, $acl2);
575
576         $cnt1 = count($res);
577         $cnt2 = count($acl2);
578
579         if ($cnt1 == $cnt2)
580             return 2;
581         else if ($cnt1)
582             return 1;
583         else
584             return 0;
585     }
586
587     /**
588      * Get list of supported access rights (according to RIGHTS capability)
589      *
590      * @return array List of supported access rights abbreviations
591      */
592     function rights_supported()
593     {
594         if ($this->supported !== null) {
595             return $this->supported;
596         }
597
598         $capa = $this->rc->storage->get_capability('RIGHTS');
599
600         if (is_array($capa)) {
601             $rights = strtolower($capa[0]);
602         }
603         else {
604             $rights = 'cd';
605         }
606
607         return $this->supported = str_split('lrswi' . $rights . 'pa');
608     }
609
610     /**
611      * Username realm detection.
612      *
613      * @return string Username realm (domain)
614      */
615     private function get_realm()
616     {
617         // When user enters a username without domain part, realm
618         // alows to add it to the username (and display correct username in the table)
619
620         if (isset($_SESSION['acl_username_realm'])) {
621             return $_SESSION['acl_username_realm'];
622         }
623
624         // find realm in username of logged user (?)
625         list($name, $domain) = explode('@', $_SESSION['username']);
626
627         // Use (always existent) ACL entry on the INBOX for the user to determine
628         // whether or not the user ID in ACL entries need to be qualified and how
629         // they would need to be qualified.
630         if (empty($domain)) {
631             $acl = $this->rc->storage->get_acl('INBOX');
632             if (is_array($acl)) {
633                 $regexp = '/^' . preg_quote($_SESSION['username'], '/') . '@(.*)$/';
634                 foreach (array_keys($acl) as $name) {
635                     if (preg_match($regexp, $name, $matches)) {
636                         $domain = $matches[1];
637                         break;
638                     }
639                 }
640             }
641         }
642
643         return $_SESSION['acl_username_realm'] = $domain;
644     }
645
646     /**
647      * Initializes autocomplete LDAP backend
648      */
649     private function init_ldap()
650     {
651         if ($this->ldap)
652             return $this->ldap->ready;
653
654         // get LDAP config
655         $config = $this->rc->config->get('acl_users_source');
656
657         if (empty($config)) {
658             return false;
659         }
660
661         // not an array, use configured ldap_public source
662         if (!is_array($config)) {
663             $ldap_config = (array) $this->rc->config->get('ldap_public');
664             $config = $ldap_config[$config];
665         }
666
667         $uid_field = $this->rc->config->get('acl_users_field', 'mail');
668         $filter    = $this->rc->config->get('acl_users_filter');
669
670         if (empty($uid_field) || empty($config)) {
671             return false;
672         }
673
674         // get name attribute
675         if (!empty($config['fieldmap'])) {
676             $name_field = $config['fieldmap']['name'];
677         }
678         // ... no fieldmap, use the old method
679         if (empty($name_field)) {
680             $name_field = $config['name_field'];
681         }
682
683         // add UID field to fieldmap, so it will be returned in a record with name
684         $config['fieldmap'] = array(
685             'name' => $name_field,
686             'uid'  => $uid_field,
687         );
688
689         // search in UID and name fields
690         $config['search_fields'] = array_values($config['fieldmap']);
691         $config['required_fields'] = array($uid_field);
692
693         // set search filter
694         if ($filter)
695             $config['filter'] = $filter;
696
697         // disable vlv
698         $config['vlv'] = false;
699
700         // Initialize LDAP connection
701         $this->ldap = new rcube_ldap($config,
702             $this->rc->config->get('ldap_debug'),
703             $this->rc->config->mail_domain($_SESSION['imap_host']));
704
705         return $this->ldap->ready;
706     }
707 }