summaryrefslogtreecommitdiff
path: root/plugins/libkolab/lib/kolab_storage_config.php
blob: d58e3c048f7f51b6e6bc01206f1da4b40eba483e (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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
<?php

/**
 * Kolab storage class providing access to configuration objects on a Kolab server.
 *
 * @version @package_version@
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 * @author Aleksander Machniak <machniak@kolabsys.com>
 *
 * Copyright (C) 2012-2014, 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_storage_config
{
    const FOLDER_TYPE = 'configuration';


    /**
     * Singleton instace of kolab_storage_config
     *
     * @var kolab_storage_config
     */
    static protected $instance;

    private $folders;
    private $default;
    private $enabled;


    /**
     * This implements the 'singleton' design pattern
     *
     * @return kolab_storage_config The one and only instance
     */
    static function get_instance()
    {
        if (!self::$instance) {
            self::$instance = new kolab_storage_config();
        }

        return self::$instance;
    }

    /**
     * Private constructor (finds default configuration folder as a config source)
     */
    private function __construct()
    {
        // get all configuration folders
        $this->folders = kolab_storage::get_folders(self::FOLDER_TYPE, false);

        foreach ($this->folders as $folder) {
            if ($folder->default) {
                $this->default = $folder;
                break;
            }
        }

        // if no folder is set as default, choose the first one
        if (!$this->default) {
            $this->default = reset($this->folders);
        }

        // attempt to create a default folder if it does not exist
        if (!$this->default) {
            $folder_name = 'Configuration';
            $folder_type = self::FOLDER_TYPE . '.default';

            if (kolab_storage::folder_create($folder_name, $folder_type, true)) {
                $this->default = new kolab_storage_folder($folder_name, $folder_type);
            }
        }

        // check if configuration folder exist
        if ($this->default && $this->default->name) {
            $this->enabled = true;
        }
    }

    /**
     * Check wether any configuration storage (folder) exists
     *
     * @return bool
     */
    public function is_enabled()
    {
        return $this->enabled;
    }

    /**
     * Get configuration objects
     *
     * @param array $filter  Search filter
     * @param bool  $default Enable to get objects only from default folder
     * @param int   $limit   Max. number of records (per-folder)
     *
     * @return array List of objects
     */
    public function get_objects($filter = array(), $default = false, $limit = 0)
    {
        $list = array();

        foreach ($this->folders as $folder) {
            // we only want to read from default folder
            if ($default && !$folder->default) {
                continue;
            }

            // for better performance it's good to assume max. number of records
            if ($limit) {
                $folder->set_order_and_limit(null, $limit);
            }

            foreach ($folder->select($filter) as $object) {
                unset($object['_formatobj']);
                $list[] = $object;
            }
        }

        return $list;
    }

    /**
     * Get configuration object
     *
     * @param string $uid     Object UID
     * @param bool   $default Enable to get objects only from default folder
     *
     * @return array Object data
     */
    public function get_object($uid, $default = false)
    {
        foreach ($this->folders as $folder) {
            // we only want to read from default folder
            if ($default && !$folder->default) {
                continue;
            }

            if ($object = $folder->get_object($uid)) {
                return $object;
            }
        }
    }

    /**
     * Create/update configuration object
     *
     * @param array  $object Object data
     * @param string $type   Object type
     *
     * @return bool True on success, False on failure
     */
    public function save(&$object, $type)
    {
        if (!$this->enabled) {
            return false;
        }

        $folder = $this->find_folder($object);

        if ($type) {
            $object['type'] = $type;
        }

        return $folder->save($object, self::FOLDER_TYPE . '.' . $object['type'], $object['uid']);
    }

    /**
     * Remove configuration object
     *
     * @param string $uid Object UID
     *
     * @return bool True on success, False on failure
     */
    public function delete($uid)
    {
        if (!$this->enabled) {
            return false;
        }

        // fetch the object to find folder
        $object = $this->get_object($uid);

        if (!$object) {
            return false;
        }

        $folder = $this->find_folder($object);

        return $folder->delete($uid);
    }

    /**
     * Find folder
     */
    public function find_folder($object = array())
    {
        // find folder object
        if ($object['_mailbox']) {
            foreach ($this->folders as $folder) {
                if ($folder->name == $object['_mailbox']) {
                    break;
                }
            }
        }
        else {
            $folder = $this->default;
        }

        return $folder;
    }

    /**
     * Builds relation member URI
     *
     * @param string|array Object UUID or Message folder, UID, Search headers (Message-Id, Date)
     *
     * @return string $url Member URI
     */
    public static function build_member_url($params)
    {
        // param is object UUID
        if (is_string($params) && !empty($params)) {
            return 'urn:uuid:' . $params;
        }

        if (empty($params) || !strlen($params['folder'])) {
            return null;
        }

        $rcube   = rcube::get_instance();
        $storage = $rcube->get_storage();

        // modify folder spec. according to namespace
        $folder = $params['folder'];
        $ns     = $storage->folder_namespace($folder);

        if ($ns == 'shared') {
            // Note: this assumes there's only one shared namespace root
            if ($ns = $storage->get_namespace('shared')) {
                if ($prefix = $ns[0][0]) {
                    $folder = 'shared' . substr($folder, strlen($prefix));
                }
            }
        }
        else {
            if ($ns == 'other') {
                // Note: this assumes there's only one other users namespace root
                if ($ns = $storage->get_namespace('shared')) {
                    if ($prefix = $ns[0][0]) {
                        $folder = 'user' . substr($folder, strlen($prefix));
                    }
                }
            }
            else {
                $folder = 'user' . '/' . $rcube->get_user_name() . '/' . $folder;
            }
        }

        $folder = implode('/', array_map('rawurlencode', explode('/', $folder)));

        // build URI
        $url = 'imap:///' . $folder;

        // UID is optional here because sometimes we want
        // to build just a member uri prefix
        if ($params['uid']) {
            $url .= '/' . $params['uid'];
        }

        unset($params['folder']);
        unset($params['uid']);

        if (!empty($params)) {
            $url .= '?' . http_build_query($params, '', '&');
        }

        return $url;
    }

    /**
     * Parses relation member string
     *
     * @param string $url Member URI
     *
     * @return array Message folder, UID, Search headers (Message-Id, Date)
     */
    public static function parse_member_url($url)
    {
        // Look for IMAP URI:
        // imap:///(user/username@domain|shared)/<folder>/<UID>?<search_params>
        if (strpos($url, 'imap:///') === 0) {
            $rcube   = rcube::get_instance();
            $storage = $rcube->get_storage();

            // parse_url does not work with imap:/// prefix
            $url   = parse_url(substr($url, 8));
            $path  = explode('/', $url['path']);
            parse_str($url['query'], $params);

            $uid  = array_pop($path);
            $ns   = array_shift($path);
            $path = array_map('rawurldecode', $path);

            // resolve folder name
            if ($ns == 'shared') {
                $folder = implode('/', $path);
                // Note: this assumes there's only one shared namespace root
                if ($ns = $storage->get_namespace('shared')) {
                    if ($prefix = $ns[0][0]) {
                        $folder = $prefix . '/' . $folder;
                    }
                }
            }
            else if ($ns == 'user') {
                $username = array_shift($path);
                $folder   = implode('/', $path);

                if ($username != $rcube->get_user_name()) {
                    // Note: this assumes there's only one other users namespace root
                    if ($ns = $storage->get_namespace('other')) {
                        if ($prefix = $ns[0][0]) {
                            $folder = $prefix . '/' . $username . '/' . $folder;
                        }
                    }
                }
                else if (!strlen($folder)) {
                    $folder = 'INBOX';
                }
            }
            else {
                return;
            }

            return array(
                'folder' => $folder,
                'uid'    => $uid,
                'params' => $params,
            );
        }

        return false;
    }

    /**
     * Build array of member URIs from set of messages
     *
     * @param string $folder   Folder name
     * @param array  $messages Array of rcube_message objects
     *
     * @return array List of members (IMAP URIs)
     */
    public static function build_members($folder, $messages)
    {
        $members = array();

        foreach ((array) $messages as $msg) {
            $params = array(
                'folder' => $folder,
                'uid'    => $msg->uid,
            );

            // add search parameters:
            // we don't want to build "invalid" searches e.g. that
            // will return false positives (more or wrong messages)
            if (($messageid = $msg->get('message-id', false)) && ($date = $msg->get('date', false))) {
                $params['message-id'] = $messageid;
                $params['date']       = $date;

                if ($subject = $msg->get('subject', false)) {
                    $params['subject'] = substr($subject, 0, 256);
                }
            }

            $members[] = self::build_member_url($params);
        }

        return $members;
    }

    /**
     * Resolve/validate/update members (which are IMAP URIs) of relation object.
     *
     * @param array $tag   Tag object
     * @param bool  $force Force members list update
     *
     * @return array Folder/UIDs list
     */
    public static function resolve_members(&$tag, $force = true)
    {
        $result = array();

        foreach ((array) $tag['members'] as $member) {
            // IMAP URI members
            if ($url = self::parse_member_url($member)) {
                $folder = $url['folder'];

                if (!$force) {
                    $result[$folder][] = $url['uid'];
                }
                else {
                    $result[$folder]['uid'][]    = $url['uid'];
                    $result[$folder]['params'][] = $url['params'];
                    $result[$folder]['member'][] = $member;
                }
            }
        }

        if (empty($result) || !$force) {
            return $result;
        }

        $rcube   = rcube::get_instance();
        $storage = $rcube->get_storage();
        $search  = array();
        $missing = array();

        // first we search messages by Folder+UID
        foreach ($result as $folder => $data) {
            // @FIXME: maybe better use index() which is cached?
            // @TODO: consider skip_deleted option
            $index = $storage->search_once($folder, 'UID ' . rcube_imap_generic::compressMessageSet($data['uid']));
            $uids  = $index->get();

            // messages that were not found need to be searched by search parameters
            $not_found = array_diff($data['uid'], $uids);
            if (!empty($not_found)) {
                foreach ($not_found as $uid) {
                    $idx = array_search($uid, $data['uid']);

                    if ($p = $data['params'][$idx]) {
                        $search[] = $p;
                    }

                    $missing[] = $result[$folder]['member'][$idx];

                    unset($result[$folder]['uid'][$idx]);
                    unset($result[$folder]['params'][$idx]);
                    unset($result[$folder]['member'][$idx]);
                }
            }

            $result[$folder] = $uids;
        }

        // search in all subscribed mail folders using search parameters
        if (!empty($search)) {
            // remove not found members from the members list
            $tag['members'] = array_diff($tag['members'], $missing);

            // get subscribed folders
            $folders = $storage->list_folders_subscribed('', '*', 'mail', null, true);

            // @TODO: do this search in chunks (for e.g. 10 messages)?
            $search_str = '';

            foreach ($search as $p) {
                $search_params = array();
                foreach ($p as $key => $val) {
                    $key = strtoupper($key);
                    // don't search by subject, we don't want false-positives
                    if ($key != 'SUBJECT') {
                        $search_params[] = 'HEADER ' . $key . ' ' . rcube_imap_generic::escape($val);
                    }
                }

                $search_str .= ' (' . implode(' ', $search_params) . ')';
            }

            $search_str = trim(str_repeat(' OR', count($search)-1) . $search_str);

            // search
            $search = $storage->search_once($folders, $search_str);

            // handle search result
            $folders = (array) $search->get_parameters('MAILBOX');

            foreach ($folders as $folder) {
                $set  = $search->get_set($folder);
                $uids = $set->get();

                if (!empty($uids)) {
                    $msgs    = $storage->fetch_headers($folder, $uids, false);
                    $members = self::build_members($folder, $msgs);

                    // merge new members into the tag members list
                    $tag['members'] = array_merge($tag['members'], $members);

                    // add UIDs into the result
                    $result[$folder] = array_unique(array_merge((array)$result[$folder], $uids));
                }
            }

            // update tag object with new members list
            $tag['members'] = array_unique($tag['members']);
            kolab_storage_config::get_instance()->save($tag, 'relation', false);
        }

        return $result;
    }

    /**
     * Assign tags to kolab objects
     *
     * @param array $records List of kolab objects
     *
     * @return array List of tags
     */
    public function apply_tags(&$records)
    {
        // first convert categories into tags
        foreach ($records as $i => $rec) {
            if (!empty($rec['categories'])) {
                $folder = new kolab_storage_folder($rec['_mailbox']);
                if ($object = $folder->get_object($rec['uid'])) {
                    $tags = $rec['categories'];

                    unset($object['categories']);
                    unset($records[$i]['categories']);

                    $this->save_tags($rec['uid'], $tags);
                    $folder->save($object, $rec['_type'], $rec['uid']);
                }
            }
        }

        $tags = array();

        // assign tags to objects
        foreach ($this->get_tags() as $tag) {
            foreach ($records as $idx => $rec) {
                $uid = self::build_member_url($rec['uid']);
                if (in_array($uid, (array) $tag['members'])) {
                    $records[$idx]['tags'][] = $tag['name'];
                }
            }

            $tags[] = $tag['name'];
        }

        $tags = array_unique($tags);

        return $tags;
    }

    /**
     * Update object tags
     *
     * @param string $uid  Kolab object UID
     * @param array  $tags List of tag names
     */
    public function save_tags($uid, $tags)
    {
        $url       = self::build_member_url($uid);
        $relations = $this->get_tags();

        foreach ($relations as $idx => $relation) {
            $selected = !empty($tags) && in_array($relation['name'], $tags);
            $found    = !empty($relation['members']) && in_array($url, $relation['members']);
            $update   = false;

            // remove member from the relation
            if ($found && !$selected) {
                $relation['members'] = array_diff($relation['members'], (array) $url);
                $update = true;
            }
            // add member to the relation
            else if (!$found && $selected) {
                $relation['members'][] = $url;
                $update = true;
            }

            if ($update) {
                if ($this->save($relation, 'relation')) {
                    $this->tags[$idx] = $relation; // update in-memory cache
                }
            }

            if ($selected) {
                $tags = array_diff($tags, (array)$relation['name']);
            }
        }

        // create new relations
        if (!empty($tags)) {
            foreach ($tags as $tag) {
                $relation = array(
                    'name'     => $tag,
                    'members'  => (array) $url,
                    'category' => 'tag',
                );

                if ($this->save($relation, 'relation')) {
                    $this->tags[] = $relation; // update in-memory cache
                }
            }
        }
    }

    /**
     * Get tags (all or referring to specified object)
     *
     * @param string $uid Optional object UID
     *
     * @return array List of Relation objects
     */
    public function get_tags($uid = '*')
    {
        if (!isset($this->tags)) {
            $default = true;
            $filter  = array(
                array('type', '=', 'relation'),
                array('category', '=', 'tag')
            );

            // use faster method
            if ($uid && $uid != '*') {
                $filter[] = array('member', '=', $uid);
                $tags = $this->get_objects($filter, $default);
            }
            else {
                $this->tags = $tags = $this->get_objects($filter, $default);
            }
        }
        else {
            $tags = $this->tags;
        }

        if ($uid === '*') {
            return $tags;
        }

        $result = array();
        $search = self::build_member_url($uid);

        foreach ($tags as $tag) {
            if (in_array($search, (array) $tag['members'])) {
                $result[] = $tag;
            }
        }

        return $result;
    }

    /**
     * Find objects linked with the given groupware object through a relation
     *
     * @param string Object UUID
     * @param array List of related URIs
     */
    public function get_object_links($uid)
    {
        $links = array();
        $object_uri = self::build_member_url($uid);

        foreach ($this->get_relations_for_member($uid) as $relation) {
            if (in_array($object_uri, (array) $relation['members'])) {
                // make relation members up-to-date
                kolab_storage_config::resolve_members($relation);

                foreach ($relation['members'] as $member) {
                    if ($member != $object_uri) {
                        $links[] = $member;
                    }
                }
            }
        }

        return array_unique($links);
    }

    /**
     *
     */
    public function save_object_links($uid, $links, $remove = array())
    {
        $object_uri = self::build_member_url($uid);
        $relations = $this->get_relations_for_member($uid);
        $done = false;

        foreach ($relations as $relation) {
            // make relation members up-to-date
            kolab_storage_config::resolve_members($relation);

            // remove and add links
            $members = array_diff($relation['members'], (array)$remove);
            $members = array_unique(array_merge($members, $links));

            // make sure the object_uri is still a member
            if (!in_array($object_uri, $members)) {
                $members[$object_uri];
            }

            // remove relation if no other members remain
            if (count($members) <= 1) {
                $done = $this->delete($relation['uid']);
            }
            // update relation object if members changed
            else if (count(array_diff($members, $relation['members'])) || count(array_diff($relation['members'], $members))) {
                $relation['members'] = $members;
                $done = $this->save($relation, 'relation');
                $links = array();
            }
            // no changes, we're happy
            else {
                $done = true;
                $links = array();
            }
        }

        // create a new relation
        if (!$done && !empty($links)) {
            $relation = array(
                'members'  => array_merge($links, array($object_uri)),
                'category' => 'generic',
            );

            $ret = $this->save($relation, 'relation');
        }

        return $ret;
    }

    /**
     * Find relation objects referring to specified note
     */
    public function get_relations_for_member($uid, $reltype = 'generic')
    {
        $default = true;
        $filter  = array(
            array('type', '=', 'relation'),
            array('category', '=', $reltype),
            array('member', '=', $uid),
        );

        return $this->get_objects($filter, $default, 100);
    }

    /**
     * Find kolab objects assigned to specified e-mail message
     *
     * @param rcube_message $message E-mail message
     * @param string        $folder  Folder name
     * @param string        $type    Result objects type
     *
     * @return array List of kolab objects
     */
    public function get_message_relations($message, $folder, $type)
    {
        static $_cache = array();

        $result  = array();
        $uids    = array();
        $default = true;
        $uri     = self::get_message_uri($message, $folder);
        $filter  = array(
            array('type', '=', 'relation'),
            array('category', '=', 'generic'),
        );

        // query by message-id
        $member_id = $message->get('message-id', false);
        if (empty($member_id)) {
            // derive message identifier from URI
            $member_id = md5($uri);
        }
        $filter[] = array('member', '=', $member_id);

        if (!isset($_cache[$uri])) {
            // get UIDs of related groupware objects
            foreach ($this->get_objects($filter, $default) as $relation) {
                // we don't need to update members if the URI is found
                if (!in_array($uri, $relation['members'])) {
                    // update members...
                    $messages = kolab_storage_config::resolve_members($relation);
                    // ...and check again
                    if (empty($messages[$folder]) || !in_array($message->uid, $messages[$folder])) {
                        continue;
                    }
                }

                // find groupware object UID(s)
                foreach ($relation['members'] as $member) {
                    if (strpos($member, 'urn:uuid:') === 0) {
                        $uids[] = substr($member, 9);
                    }
                }
            }

            // remember this lookup
            $_cache[$uri] = $uids;
        }
        else {
            $uids = $_cache[$uri];
        }

        // get kolab objects of specified type
        if (!empty($uids)) {
            $query  = array(array('uid', '=', array_unique($uids)));
            $result = kolab_storage::select($query, $type);
        }

        return $result;
    }

    /**
     * Build a URI representing the given message reference
     */
    public static function get_message_uri($headers, $folder)
    {
        $params = array(
            'folder' => $headers->folder ?: $folder,
            'uid'    => $headers->uid,
        );

        if (($messageid = $headers->get('message-id', false)) && ($date = $headers->get('date', false))) {
            $params['message-id'] = $messageid;
            $params['date']       = $date;

            if ($subject = $headers->get('subject')) {
                $params['subject'] = $subject;
            }
        }

        return self::build_member_url($params);
    }
}