summaryrefslogtreecommitdiff
path: root/plugins/kolab_zpush/kolab_zpush.php
blob: e9d1170ebe61617813992de6f1f98270c81e0b41 (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
<?php

/**
 * Z-Push configuration utility for Kolab accounts
 *
 * @version 0.2
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 * Copyright (C) 2012, 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_zpush extends rcube_plugin
{
    public $task = 'settings';
    public $urlbase;

    private $rc;
    private $ui;
    private $cache;
    private $devices;
    private $folders;
    private $folders_meta;
    private $root_meta;

    const ROOT_MAILBOX = 'INBOX';
    const CTYPE_KEY = '/shared/vendor/kolab/folder-type';
    const ACTIVESYNC_KEY = '/private/vendor/kolab/activesync';

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

        $this->require_plugin('jqueryui');
        $this->add_texts('localization/', true);

        $this->include_script('kolab_zpush.js');

        $this->register_action('plugin.zpushconfig', array($this, 'config_view'));
        $this->register_action('plugin.zpushjson', array($this, 'json_command'));

        if ($this->rc->action == 'plugin.zpushconfig') {
            $this->require_plugin('libkolab');
        }
    }


    /**
     * Establish IMAP connection
     */
    public function init_imap()
    {
        $storage = $this->rc->get_storage();

        // @TODO: Metadata is already cached by rcube storage, get rid of cache here

        $this->cache = $this->rc->get_cache('zpush', 'db', 900);
        $this->cache->expunge();

        if ($meta = $storage->get_metadata(self::ROOT_MAILBOX, self::ACTIVESYNC_KEY)) {
            // clear cache if device config changed
            if (($oldmeta = $this->cache->read('devicemeta')) && $oldmeta != $meta)
                $this->cache->remove();

            $this->root_meta = $this->unserialize_metadata($meta[self::ROOT_MAILBOX][self::ACTIVESYNC_KEY]);
            $this->cache->remove('devicemeta');
            $this->cache->write('devicemeta', $meta);
        }
    }


    /**
     * Handle JSON requests
     */
    public function json_command()
    {
        $storage = $this->rc->get_storage();
        $cmd     = rcube_utils::get_input_value('cmd', rcube_utils::INPUT_GPC);
        $imei    = rcube_utils::get_input_value('id', rcube_utils::INPUT_GPC);

        switch ($cmd) {
        case 'load':
            $result = array();
            $devices = $this->list_devices();
            if ($device = $devices[$imei]) {
                $result['id'] = $imei;
                $result['devicealias'] = $device['ALIAS'];
                $result['syncmode'] = intval($device['MODE']);
                $result['laxpic'] = intval($device['LAXPIC']);
                $result['subscribed'] = array();

                foreach ($this->folders_meta() as $folder => $meta) {
                    if ($meta[$imei]['S'])
                        $result['subscribed'][$folder] = intval($meta[$imei]['S']);
                }

                $this->rc->output->command('plugin.zpush_data_ready', $result);
            }
            else {
                $this->rc->output->show_message($this->gettext('devicenotfound'), 'error');
            }
            break;

        case 'save':
            $syncmode     = intval(rcube_utils::get_input_value('syncmode', rcube_utils::INPUT_POST));
            $laxpic       = intval(rcube_utils::get_input_value('laxpic', rcube_utils::INPUT_POST));
            $devicealias  = rcube_utils::get_input_value('devicealias', rcube_utils::INPUT_POST, true);
            $subsciptions = rcube_utils::get_input_value('subscribed', rcube_utils::INPUT_POST);
            $devices = $this->list_devices();
            $err     = false;

            if ($device = $devices[$imei]) {
                // update device config if changed
                if ($devicealias != $this->root_meta['DEVICE'][$imei]['ALIAS']  ||
                       $syncmode != $this->root_meta['DEVICE'][$imei]['MODE']   ||
                       $laxpic   != $this->root_meta['DEVICE'][$imei]['LAXPIC'] ||
                       $subsciptions[self::ROOT_MAILBOX] != $this->root_meta['FOLDER'][$imei]['S']) {
                    $this->root_meta['DEVICE'][$imei]['MODE'] = $syncmode;
                    $this->root_meta['DEVICE'][$imei]['ALIAS'] = $devicealias;
                    $this->root_meta['DEVICE'][$imei]['LAXPIC'] = $laxpic;
                    $this->root_meta['FOLDER'][$imei]['S'] = intval($subsciptions[self::ROOT_MAILBOX]);

                    $err = !$storage->set_metadata(self::ROOT_MAILBOX,
                        array(self::ACTIVESYNC_KEY => $this->serialize_metadata($this->root_meta)));

                    // update cached meta data
                    if (!$err) {
                        $this->cache->remove('devicemeta');
                        $this->cache->write('devicemeta', $storage->get_metadata(self::ROOT_MAILBOX, self::ACTIVESYNC_KEY));
                    }
                }
                // iterate over folders list and update metadata if necessary
                foreach ($this->folders_meta() as $folder => $meta) {
                    // skip root folder (already handled above)
                    if ($folder == self::ROOT_MAILBOX)
                        continue;

                    if ($subsciptions[$folder] != $meta[$imei]['S']) {
                        $meta[$imei]['S'] = intval($subsciptions[$folder]);
                        $this->folders_meta[$folder] = $meta;
                        unset($meta['TYPE']);

                        // read metadata first
                        $folderdata = $storage->get_metadata($folder, array(self::ACTIVESYNC_KEY));
                        if ($asyncdata = $folderdata[$folder][self::ACTIVESYNC_KEY])
                            $metadata = $this->unserialize_metadata($asyncdata);
                        $metadata['FOLDER'] = $meta;

                        $err |= !$storage->set_metadata($folder, array(self::ACTIVESYNC_KEY => $this->serialize_metadata($metadata)));
                    }
                }

                // update cache
                $this->cache->remove('folders');
                $this->cache->write('folders', $this->folders_meta);

                $this->rc->output->command('plugin.zpush_save_complete', array('success' => !$err, 'id' => $imei, 'devicealias' => Q($devicealias)));
            }

            if ($err)
                $this->rc->output->show_message($this->gettext('savingerror'), 'error');
            else
                $this->rc->output->show_message($this->gettext('successfullysaved'), 'confirmation');

            break;

        case 'delete':
            $devices = $this->list_devices();

            if ($device = $devices[$imei]) {
                unset($this->root_meta['DEVICE'][$imei], $this->root_meta['FOLDER'][$imei]);

                // update annotation and cached meta data
                if ($success = $storage->set_metadata(self::ROOT_MAILBOX, array(self::ACTIVESYNC_KEY => $this->serialize_metadata($this->root_meta)))) {
                    $this->cache->remove('devicemeta');
                    $this->cache->write('devicemeta', $storage->get_metadata(self::ROOT_MAILBOX, self::ACTIVESYNC_KEY));

                    // remove device annotation in every folder
                    foreach ($this->folders_meta() as $folder => $meta) {
                        // skip root folder (already handled above)
                        if ($folder == self::ROOT_MAILBOX)
                            continue;

                        if (isset($meta[$imei])) {
                            $type = $meta['TYPE'];  // remember folder type
                            unset($meta[$imei], $meta['TYPE']);

                            // read metadata first and update FOLDER property
                            $folderdata = $storage->get_metadata($folder, array(self::ACTIVESYNC_KEY));
                            if ($asyncdata = $folderdata[$folder][self::ACTIVESYNC_KEY])
                                $metadata = $this->unserialize_metadata($asyncdata);
                            $metadata['FOLDER'] = $meta;

                            if ($storage->set_metadata($folder, array(self::ACTIVESYNC_KEY => $this->serialize_metadata($metadata)))) {
                                $this->folders_meta[$folder] = $metadata;
                                $this->folders_meta[$folder]['TYPE'] = $type;
                            }
                        }
                    }

                    // update cache
                    $this->cache->remove('folders');
                    $this->cache->write('folders', $this->folders_meta);
                }
            }

            if ($success) {
                $this->rc->output->show_message($this->gettext('successfullydeleted'), 'confirmation');
                $this->rc->output->redirect(array('action' => 'plugin.zpushconfig'));  // reload UI
            }
            else
                $this->rc->output->show_message($this->gettext('savingerror'), 'error');

            break;
        }

        $this->rc->output->send();
    }


    /**
     * Render main UI for device configuration
     */
    public function config_view()
    {
        require_once $this->home . '/kolab_zpush_ui.php';

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

        // checks if IMAP server supports any of METADATA, ANNOTATEMORE, ANNOTATEMORE2
        if (!($storage->get_capability('METADATA') || $storage->get_capability('ANNOTATEMORE') || $storage->get_capability('ANNOTATEMORE2'))) {
            $this->rc->output->show_message($this->gettext('notsupported'), 'error');
        }

        $this->ui = new kolab_zpush_ui($this);

        $this->register_handler('plugin.devicelist', array($this->ui, 'device_list'));
        $this->register_handler('plugin.deviceconfigform', array($this->ui, 'device_config_form'));
        $this->register_handler('plugin.foldersubscriptions', array($this->ui, 'folder_subscriptions'));

        $this->rc->output->set_env('devicecount', count($this->list_devices()));
        $this->rc->output->send('kolab_zpush.config');
    }


    /**
     * List known devices
     *
     * @return array Device list as hash array
     */
    public function list_devices()
    {
        if (!isset($this->devices)) {
            $this->init_imap();
            $this->devices = (array)$this->root_meta['DEVICE'];
        }

        return $this->devices;
    }


    /**
     * Get list of all folders available for sync
     *
     * @return array List of mailbox folders
     */
    public function list_folders()
    {
        if (!isset($this->folders)) {
            // read cached folder meta data
            if ($cached_folders = $this->cache->read('folders')) {
                $this->folders_meta = $cached_folders;
                $this->folders = array_keys($this->folders_meta);
            }
            // fetch folder data from server
            else {
                $storage       = $this->rc->get_storage();
                $this->folders = $storage->list_folders();

                foreach ($this->folders as $folder) {
                    $folderdata = $storage->get_metadata($folder, array(self::ACTIVESYNC_KEY, self::CTYPE_KEY));
                    $foldertype = explode('.', $folderdata[$folder][self::CTYPE_KEY]);

                    if ($asyncdata = $folderdata[$folder][self::ACTIVESYNC_KEY]) {
                        $metadata = $this->unserialize_metadata($asyncdata);
                        $this->folders_meta[$folder] = $metadata['FOLDER'];
                    }
                    $this->folders_meta[$folder]['TYPE'] = !empty($foldertype[0]) ? $foldertype[0] : 'mail';
                }

                // cache it!
                $this->cache->write('folders', $this->folders_meta);
            }
        }

        return $this->folders;
    }

    /**
     * Getter for folder metadata
     *
     * @return array Hash array with meta data for each folder
     */
    public function folders_meta()
    {
        if (!isset($this->folders_meta))
            $this->list_folders();

        return $this->folders_meta;
    }

    /**
     * Helper method to decode saved IMAP metadata
     */
    private function unserialize_metadata($str)
    {
        if (!empty($str))
            return @json_decode(base64_decode($str), true);

        return null;
    }

    /**
     * Helper method to encode IMAP metadata for saving
     */
    private function serialize_metadata($data)
    {
        if (is_array($data))
            return base64_encode(json_encode($data));

        return '';
    }

}