summaryrefslogtreecommitdiff
path: root/plugins/kolab_folders/kolab_folders.php
blob: b3c2e8ef62a78479d3857f88dd4e05c115fa09a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<?php

/**
 * Type-aware folder management/listing for Kolab
 *
 * @version @package_version@
 * @author Aleksander Machniak <machniak@kolabsys.com>
 *
 * Copyright (C) 2011, Kolab Systems AG <contact@kolabsys.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

class kolab_folders extends rcube_plugin
{
    public $task = '?(?!login).*';

    public $types      = array('mail', 'event', 'journal', 'task', 'note', 'contact', 'configuration', 'file', 'freebusy');
    public $subtypes   = array(
        'mail'          => array('inbox', 'drafts', 'sentitems', 'outbox', 'wastebasket', 'junkemail'),
        'event'         => array('default', 'confidential'),
        'task'          => array('default', 'confidential'),
        'journal'       => array('default'),
        'note'          => array('default'),
        'contact'       => array('default'),
        'configuration' => array('default'),
        'file'          => array('default'),
        'freebusy'      => array('default'),
    );
    public $act_types  = array('event', 'task');

    private $rc;
    private static $instance;


    /**
     * Plugin initialization.
     */
    function init()
    {
        self::$instance = $this;
        $this->rc = rcube::get_instance();

        // load required plugin
        $this->require_plugin('libkolab');

        // Folder listing hooks
        $this->add_hook('storage_folders', array($this, 'mailboxes_list'));

        // Folder manager hooks
        $this->add_hook('folder_form', array($this, 'folder_form'));
        $this->add_hook('folder_update', array($this, 'folder_save'));
        $this->add_hook('folder_create', array($this, 'folder_save'));
        $this->add_hook('folder_delete', array($this, 'folder_save'));
        $this->add_hook('folder_rename', array($this, 'folder_save'));
        $this->add_hook('folders_list', array($this, 'folders_list'));

        // Special folders setting
        $this->add_hook('preferences_save', array($this, 'prefs_save'));
    }

    /**
     * Handler for mailboxes_list hook. Enables type-aware lists filtering.
     */
    function mailboxes_list($args)
    {
        // infinite loop prevention
        if ($this->is_processing) {
            return $args;
        }

        if (!$this->metadata_support()) {
            return $args;
        }

        $this->is_processing = true;

        // get folders
        $folders = kolab_storage::list_folders($args['root'], $args['name'], $args['filter'], $args['mode'] == 'LSUB', $folderdata);

        $this->is_processing = false;

        if (!is_array($folders)) {
            return $args;
        }

        // Create default folders
        if ($args['root'] == '' && $args['name'] = '*') {
            $this->create_default_folders($folders, $args['filter'], $folderdata, $args['mode'] == 'LSUB');
        }

        $args['folders'] = $folders;

        return $args;
    }

    /**
     * Handler for folders_list hook. Add css classes to folder rows.
     */
    function folders_list($args)
    {
        if (!$this->metadata_support()) {
            return $args;
        }

        // load translations
        $this->add_texts('localization/', false);

        // Add javascript script to the client
        $this->include_script('kolab_folders.js');

        $this->add_label('folderctype');
        foreach ($this->types as $type) {
            $this->add_label('foldertype' . $type);
        }

        $skip_namespace = $this->rc->config->get('kolab_skip_namespace');
        $skip_roots     = array();

        if (!empty($skip_namespace)) {
            $storage = $this->rc->get_storage();
            foreach ((array)$skip_namespace as $ns) {
                foreach((array)$storage->get_namespace($ns) as $root) {
                    $skip_roots[] = rtrim($root[0], $root[1]);
                }
            }
        }

        $this->rc->output->set_env('skip_roots', $skip_roots);
        $this->rc->output->set_env('foldertypes', $this->types);

        // get folders types
        $folderdata = kolab_storage::folders_typedata();

        if (!is_array($folderdata)) {
            return $args;
        }

        // Add type-based style for table rows
        // See kolab_folders::folder_class_name()
        if ($table = $args['table']) {
            for ($i=1, $cnt=$table->size(); $i<=$cnt; $i++) {
                $attrib = $table->get_row_attribs($i);
                $folder = $attrib['foldername']; // UTF7-IMAP
                $type   = $folderdata[$folder];

                if (!$type) {
                    $type = 'mail';
                }

                $class_name = self::folder_class_name($type);
                $attrib['class'] = trim($attrib['class'] . ' ' . $class_name);
                $table->set_row_attribs($attrib, $i);
            }
        }

        // Add type-based class for list items
        if (is_array($args['list'])) {
            foreach ((array)$args['list'] as $k => $item) {
                $folder = $item['folder_imap']; // UTF7-IMAP
                $type   = $folderdata[$folder];

                if (!$type) {
                    $type = 'mail';
                }

                $class_name = self::folder_class_name($type);
                $args['list'][$k]['class'] = trim($item['class'] . ' ' . $class_name);
            }
        }

        return $args;
    }

    /**
     * Handler for folder info/edit form (folder_form hook).
     * Adds folder type selector.
     */
    function folder_form($args)
    {
        if (!$this->metadata_support()) {
            return $args;
        }
        // load translations
        $this->add_texts('localization/', false);

        // INBOX folder is of type mail.inbox and this cannot be changed
        if ($args['name'] == 'INBOX') {
            $args['form']['props']['fieldsets']['settings']['content']['foldertype'] = array(
                'label' => $this->gettext('folderctype'),
                'value' => sprintf('%s (%s)', $this->gettext('foldertypemail'), $this->gettext('inbox')),
            );

            return $args;
        }

        if ($args['options']['is_root']) {
            return $args;
        }

        $mbox = strlen($args['name']) ? $args['name'] : $args['parent_name'];

        if (isset($_POST['_ctype'])) {
            $new_ctype   = trim(rcube_utils::get_input_value('_ctype', rcube_utils::INPUT_POST));
            $new_subtype = trim(rcube_utils::get_input_value('_subtype', rcube_utils::INPUT_POST));
        }

        // Get type of the folder or the parent
        if (strlen($mbox)) {
            list($ctype, $subtype) = $this->get_folder_type($mbox);
            if (strlen($args['parent_name']) && $subtype == 'default')
                $subtype = ''; // there can be only one
        }

        if (!$ctype) {
            $ctype = 'mail';
        }

        $storage = $this->rc->get_storage();

        // Don't allow changing type of shared folder, according to ACL
        if (strlen($mbox)) {
            $options = $storage->folder_info($mbox);
            if ($options['namespace'] != 'personal' && !in_array('a', (array)$options['rights'])) {
                if (in_array($ctype, $this->types)) {
                    $value = $this->gettext('foldertype'.$ctype);
                }
                else {
                    $value = $ctype;
                }
                if ($subtype) {
                    $value .= ' ('. ($subtype == 'default' ? $this->gettext('default') : $subtype) .')';
                }

                $args['form']['props']['fieldsets']['settings']['content']['foldertype'] = array(
                    'label' => $this->gettext('folderctype'),
                    'value' => $value,
                );

                return $args;
            }
        }

        // Add javascript script to the client
        $this->include_script('kolab_folders.js');

        // build type SELECT fields
        $type_select = new html_select(array('name' => '_ctype', 'id' => '_ctype'));
        $sub_select  = new html_select(array('name' => '_subtype', 'id' => '_subtype'));
        $sub_select->add('', '');

        foreach ($this->types as $type) {
            $type_select->add($this->gettext('foldertype'.$type), $type);
        }
        // add non-supported type
        if (!in_array($ctype, $this->types)) {
            $type_select->add($ctype, $ctype);
        }

        $sub_types = array();
        foreach ($this->subtypes as $ftype => $subtypes) {
            $sub_types[$ftype] = array_combine($subtypes, array_map(array($this, 'gettext'), $subtypes));

            // fill options for the current folder type
            if ($ftype == $ctype || $ftype == $new_ctype) {
                $sub_select->add(array_values($sub_types[$ftype]), $subtypes);
            }
        }

        $args['form']['props']['fieldsets']['settings']['content']['foldertype'] = array(
            'label' => $this->gettext('folderctype'),
            'value' => $type_select->show(isset($new_ctype) ? $new_ctype : $ctype)
                . $sub_select->show(isset($new_subtype) ? $new_subtype : $subtype),
        );

        $this->rc->output->set_env('kolab_folder_subtypes', $sub_types);
        $this->rc->output->set_env('kolab_folder_subtype', isset($new_subtype) ? $new_subtype : $subtype);

        return $args;
    }

    /**
     * Handler for folder update/create action (folder_update/folder_create hook).
     */
    function folder_save($args)
    {
        // Folder actions from folders list
        if (empty($args['record'])) {
            return $args;
        }

        // Folder create/update with form
        $ctype     = trim(rcube_utils::get_input_value('_ctype', rcube_utils::INPUT_POST));
        $subtype   = trim(rcube_utils::get_input_value('_subtype', rcube_utils::INPUT_POST));
        $mbox      = $args['record']['name'];
        $old_mbox  = $args['record']['oldname'];
        $subscribe = $args['record']['subscribe'];

        if (empty($ctype)) {
            return $args;
        }

        // load translations
        $this->add_texts('localization/', false);

        // Skip folder creation/rename in core
        // @TODO: Maybe we should provide folder_create_after and folder_update_after hooks?
        //        Using create_mailbox/rename_mailbox here looks bad
        $args['abort']  = true;

        // There can be only one default folder of specified type
        if ($subtype == 'default') {
            $default = $this->get_default_folder($ctype);

            if ($default !== null && $old_mbox != $default) {
                $args['result'] = false;
                $args['message'] = $this->gettext('defaultfolderexists');
                return $args;
            }
        }
        // Subtype sanity-checks
        else if ($subtype && (!($subtypes = $this->subtypes[$ctype]) || !in_array($subtype, $subtypes))) {
            $subtype = '';
        }

        $ctype .= $subtype ? '.'.$subtype : '';

        $storage = $this->rc->get_storage();

        // Create folder
        if (!strlen($old_mbox)) {
            // By default don't subscribe to non-mail folders
            if ($subscribe)
                $subscribe = (bool) preg_match('/^mail/', $ctype);

            $result = $storage->create_folder($mbox, $subscribe);
            // Set folder type
            if ($result) {
                $this->set_folder_type($mbox, $ctype);
            }
        }
        // Rename folder
        else {
            if ($old_mbox != $mbox) {
                $result = $storage->rename_folder($old_mbox, $mbox);
            }
            else {
                $result = true;
            }

            if ($result) {
                list($oldtype, $oldsubtype) = $this->get_folder_type($mbox);
                $oldtype .= $oldsubtype ? '.'.$oldsubtype : '';

                if ($ctype != $oldtype) {
                    $this->set_folder_type($mbox, $ctype);
                }
            }
        }

        $args['record']['class'] = self::folder_class_name($ctype);
        $args['record']['subscribe'] = $subscribe;
        $args['result'] = $result;

        return $args;
    }

    /**
     * Handler for user preferences save (preferences_save hook)
     *
     * @param array $args Hash array with hook parameters
     *
     * @return array Hash array with modified hook parameters
     */
    public function prefs_save($args)
    {
        if ($args['section'] != 'folders') {
            return $args;
        }

        $dont_override = (array) $this->rc->config->get('dont_override', array());

        // map config option name to kolab folder type annotation
        $opts = array(
            'drafts_mbox' => 'mail.drafts',
            'sent_mbox'   => 'mail.sentitems',
            'junk_mbox'   => 'mail.junkemail',
            'trash_mbox'  => 'mail.wastebasket',
        );

        // check if any of special folders has been changed
        foreach ($opts as $opt_name => $type) {
            $new = $args['prefs'][$opt_name];
            $old = $this->rc->config->get($opt_name);
            if (!strlen($new) || $new === $old || in_array($opt_name, $dont_override)) {
                unset($opts[$opt_name]);
            }
        }

        if (empty($opts)) {
            return $args;
        }

        $folderdata = kolab_storage::folders_typedata();

        if (!is_array($folderdata)) {
             return $args;
        }

        foreach ($opts as $opt_name => $type) {
            $foldername = $args['prefs'][$opt_name];

            // get all folders of specified type
            $folders = array_intersect($folderdata, array($type));

            // folder already annotated with specified type
            if (!empty($folders[$foldername])) {
                continue;
            }

            // set type to the new folder
            $this->set_folder_type($foldername, $type);

            // unset old folder(s) type annotation
            list($maintype, $subtype) = explode('.', $type);
            foreach (array_keys($folders) as $folder) {
                $this->set_folder_type($folder, $maintype);
            }
        }

        return $args;
    }

    /**
     * Checks if IMAP server supports any of METADATA, ANNOTATEMORE, ANNOTATEMORE2
     *
     * @return boolean
     */
    function metadata_support()
    {
        $storage = $this->rc->get_storage();

        return $storage->get_capability('METADATA') ||
            $storage->get_capability('ANNOTATEMORE') ||
            $storage->get_capability('ANNOTATEMORE2');
    }

    /**
     * Checks if IMAP server supports any of METADATA, ANNOTATEMORE, ANNOTATEMORE2
     *
     * @param string $folder Folder name
     *
     * @return array Folder content-type
     */
    function get_folder_type($folder)
    {
        return explode('.', (string)kolab_storage::folder_type($folder));
    }

    /**
     * Sets folder content-type.
     *
     * @param string $folder Folder name
     * @param string $type   Content type
     *
     * @return boolean True on success
     */
    function set_folder_type($folder, $type = 'mail')
    {
        return kolab_storage::set_folder_type($folder, $type);
    }

    /**
     * Returns the name of default folder
     *
     * @param string $type Folder type
     *
     * @return string Folder name
     */
    function get_default_folder($type)
    {
        $folderdata = kolab_storage::folders_typedata();

        if (!is_array($folderdata)) {
            return null;
        }

        // get all folders of specified type
        $folderdata = array_intersect($folderdata, array($type.'.default'));

        return key($folderdata);
    }

    /**
     * Returns CSS class name for specified folder type
     *
     * @param string $type Folder type
     *
     * @return string Class name
     */
    static function folder_class_name($type)
    {
        list($ctype, $subtype) = explode('.', $type);

        $class[] = 'type-' . ($ctype ? $ctype : 'mail');

        if ($subtype)
            $class[] = 'subtype-' . $subtype;

        return implode(' ', $class);
    }

    /**
     * Creates default folders if they doesn't exist
     */
    private function create_default_folders(&$folders, $filter, $folderdata = null, $lsub = false)
    {
        $storage     = $this->rc->get_storage();
        $namespace   = $storage->get_namespace();
        $defaults    = array();
        $prefix      = '';

        // Find personal namespace prefix
        if (is_array($namespace['personal']) && count($namespace['personal']) == 1) {
            $prefix = $namespace['personal'][0][0];
        }

        $this->load_config();

        // get configured defaults
        foreach ($this->types as $type) {
            foreach ((array)$this->subtypes[$type] as $subtype) {
                $opt_name = 'kolab_folders_' . $type . '_' . $subtype;
                if ($folder = $this->rc->config->get($opt_name)) {
                    // convert configuration value to UTF7-IMAP charset
                    $folder = rcube_charset::convert($folder, RCUBE_CHARSET, 'UTF7-IMAP');
                    // and namespace prefix if needed
                    if ($prefix && strpos($folder, $prefix) === false && $folder != 'INBOX') {
                        $folder = $prefix . $folder;
                    }
                    $defaults[$type . '.' . $subtype] = $folder;
                }
            }
        }

        if (empty($defaults)) {
            return;
        }

        if ($folderdata === null) {
            $folderdata = kolab_storage::folders_typedata();
        }

        if (!is_array($folderdata)) {
            return;
        }

        // find default folders
        foreach ($defaults as $type => $foldername) {
            // get all folders of specified type
            $_folders = array_intersect($folderdata, array($type));

            // default folder found
            if (!empty($_folders)) {
                continue;
            }

            list($type1, $type2) = explode('.', $type);

            $activate = in_array($type1, $this->act_types);
            $exists   = false;
            $result   = false;

            // check if folder exists
            if (!empty($folderdata[$foldername]) || $foldername == 'INBOX') {
                $exists = true;
            }
            else if ((!$filter || $filter == $type1) && in_array($foldername, $folders)) {
                // this assumes also that subscribed folder exists
                $exists = true;
            }
            else {
                $exists = $storage->folder_exists($foldername);
            }

            // create folder
            if (!$exists) {
                $exists = $storage->create_folder($foldername);
            }

            // set type + subscribe + activate
            if ($exists) {
                if ($result = kolab_storage::set_folder_type($foldername, $type)) {
                    // check if folder is subscribed
                    if ((!$filter || $filter == $type1) && $lsub && in_array($foldername, $folders)) {
                        // already subscribed
                        $subscribed = true;
                    }
                    else {
                        $subscribed = $storage->subscribe($foldername);
                    }

                    // activate folder
                    if ($activate) {
                        kolab_storage::folder_activate($foldername, true);
                    }
                }
            }

            // add new folder to the result
            if ($result && (!$filter || $filter == $type1) && (!$lsub || $subscribed)) {
                $folders[] = $foldername;
            }
        }
    }

    /**
     * Static getter for default folder of the given type
     *
     * @param string $type Folder type
     * @return string Folder name
     */
    public static function default_folder($type)
    {
        return self::$instance->get_default_folder($type);
    }
}