summaryrefslogtreecommitdiff
path: root/lib/Kolab/Utils/DAVBackend.php
blob: 8a4139b58c0f678e4f43444d4eb7817ba348b3e6 (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
<?php

/**
 * Utility class prividing a simple API to PHP's APC cache
 *
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 * Copyright (C) 2013, 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/>.
 */

namespace Kolab\Utils;

use \rcube;
use \kolab_storage;
use \rcube_utils;
use \rcube_charset;

/**
 *
 */
class DAVBackend
{
    const IMAP_UID_KEY = '/shared/vendor/kolab/uniqueid';
    const IMAP_UID_KEY_PRIVATE = '/private/vendor/kolab/uniqueid';
    const IMAP_UID_KEY_CYRUS = '/shared/vendor/cmu/cyrus-imapd/uniqueid';

    /**
     * Getter for a kolab_storage_folder with the given UID
     *
     * @param string  Folder UID (saved in annotation)
     * @param string  Kolab folder type (for selecting candidates)
     * @return object \kolab_storage_folder instance
     */
    public static function get_storage_folder($uid, $type)
    {
        foreach (kolab_storage::get_folders($type) as $folder) {
            if (self::get_uid($folder) == $uid)
                return $folder;
        }

        return null;
    }

    /**
     * Helper method to extract folder UID metadata
     *
     * @param object \kolab_storage_folder Folder to get UID for
     * @return string Folder's UID
     */
    public static function get_uid($folder)
    {
        // UID is defined in folder METADATA
        $metakeys = array(self::IMAP_UID_KEY, self::IMAP_UID_KEY_PRIVATE, self::IMAP_UID_KEY_CYRUS);
        $metadata = $folder->get_metadata($metakeys);
        foreach ($metakeys as $key) {
            if (($uid = $metadata[$key])) {
                return $uid;
            }
        }

        // generate a folder UID and set it to IMAP
        $uid = rtrim(chunk_split(md5($folder->name . $folder->get_owner()), 12, '-'), '-');
        self::set_uid($folder, $uid);

        return $uid;
    }

    /**
     * Helper method to set an UID value to the given IMAP folder instance
     *
     * @param object \kolab_storage_folder Folder to set UID
     * @param string Folder's UID
     * @return boolean True on succes, False on failure
     */
    public static function set_uid($folder, $uid)
    {
        if (!($success = $folder->set_metadata(array(self::IMAP_UID_KEY => $uid)))) {
            $success = $folder->set_metadata(array(self::IMAP_UID_KEY_PRIVATE => $uid));
        }
        return $success;
    }

    /**
     * Sort the given list of kolab folders by namespace/name
     *
     * @param array List of kolab_storage_folder objects
     * @return array Sorted list of folders
     */
    public static function sort_folders($folders)
    {
        $nsnames = array('personal' => array(), 'shared' => array(), 'other' => array());
        foreach ($folders as $folder) {
            $folders[$folder->name] = $folder;
            $ns = $folder->get_namespace();
            $nsnames[$ns][$folder->name] = html_entity_decode($folder->get_name(), ENT_COMPAT, RCUBE_CHARSET);  // decode &raquo;
        }

        $names = array();
        foreach ($nsnames as $ns => $dummy) {
            asort($nsnames[$ns], SORT_LOCALE_STRING);
            $names += $nsnames[$ns];
        }

        $out = array();
        foreach ($names as $utf7name => $name) {
            $out[] = $folders[$utf7name];
        }

        return $out;
    }

    /**
     * Build an absolute URL with the given parameters
     */
    public static function abs_url($parts = array())
    {
        $schema = 'http';
        $default_port = 80;
        if (rcube_utils::https_check()) {
            $schema = 'https';
            $default_port = 443;
        }
        $url = $schema . '://' . $_SERVER['HTTP_HOST'];

        if ($_SERVER['SERVER_PORT'] != $default_port)
            $url .= ':' . $_SERVER['SERVER_PORT'];

        if (dirname($_SERVER['SCRIPT_NAME']) != '/')
            $url .= dirname($_SERVER['SCRIPT_NAME']);

        $url .= '/' . join('/', array_map('urlencode', $parts));

        return $url;
    }

    /**
     * Updates properties for a recourse (kolab folder)
     *
     * The mutations array uses the propertyName in clark-notation as key,
     * and the array value for the property value. In the case a property
     * should be deleted, the property value will be null.
     *
     * This method must be atomic. If one property cannot be changed, the
     * entire operation must fail.
     *
     * If the operation was successful, true is returned.
     * If the operation failed, detailed information about any
     * failures is returned.
     *
     * @param object $folder kolab_storage_folder instance to operate on
     * @param array $mutations Hash array with propeties to change
     * @return bool|array
     */
    public static function folder_update($folder, array $mutations)
    {
        $errors = array();
        $updates = array();

        foreach ($mutations as $prop => $val) {
            switch ($prop) {
                case '{DAV:}displayname':
                    // restrict renaming to personal folders only
                    if ($folder->get_namespace() == 'personal') {
                        $parts = preg_split('!(\s*/\s*|\s+[:]\s+)!', $val);
                        $updates['oldname'] = $folder->name;
                        $updates['name'] = array_pop($parts);
                        $updates['parent'] = join('/', $parts);
                    }
                    else {
                        $updates['displayname'] = $val;
                    }
                    break;

                case '{http://apple.com/ns/ical/}calendar-color':
                    $updates['color'] = substr(trim($val, '#'), 0, 6);
                    break;

                case '{urn:ietf:params:xml:ns:caldav}calendar-description':
                default:
                    // unsupported property
                    $errors[403][$prop] = null;
            }
        }

        // execute folder update
        if (!empty($updates)) {
            // 'name' and 'parent' properties are always required
            if (empty($updates['name'])) {
                $parts = explode('/', $folder->name);
                $updates['name'] = rcube_charset::convert(array_pop($parts), 'UTF7-IMAP');
                $updates['parent'] = join('/', $parts);
                $updates['oldname'] = $folder->name;
            }

            if (!kolab_storage::folder_update($updates)) {
                rcube::raise_error(array(
                    'code' => 600, 'type' => 'php',
                    'file' => __FILE__, 'line' => __LINE__,
                    'message' => "Error updating properties for folder $folder->name:" . kolab_storage::$last_error),
                    true, false);
                return false;
            }
        }

        return empty($errors) ? true : $errors;
    }

    /**
     * Creates a new resource (i.e. IMAP folder) of a given type
     *
     * If the creation was a success, an id must be returned that can be used to reference
     * this resource in other methods.
     *
     * @param array $properties
     * @param string $type
     * @param string $uid
     * @return false|string
     */
    public function folder_create(string $type, array $properties, string $uid)
    {
        $props = array(
            'type' => $type,
            'name' => 'Untitled',
            'subscribed' => true,
        );

        foreach ($properties as $prop => $val) {
            switch ($prop) {
                case '{DAV:}displayname':
                    $parts = explode('/', $val);
                    $props['name'] = array_pop($parts);
                    $props['parent'] = join('/', $parts);
                    break;

                case '{http://apple.com/ns/ical/}calendar-color':
                    $props['color'] = substr(trim($val, '#'), 0, 6);
                    break;

                case '{urn:ietf:params:xml:ns:caldav}calendar-description':
                default:
                    // unsupported property
            }
        }

        if (!empty($props['name']) && ($fname = kolab_storage::folder_update($props))) {
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Error creating a new calendar folder '$props[name]':" . kolab_storage::$last_error),
                true, false);
            return false;
        }

        // save UID in folder annotations
        if ($folder = kolab_storage::get_folder($fname)) {
            self::set_uid($folder, $uid);
        }

        return $uid;
    }
}