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

/**
 * Z-Push configuration utility for Kolab accounts
 *
 * @version 0.1
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 *
 * Copyright (C) 2011, Kolab Systems AG
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

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 = rcmail::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'));
    }


    /**
     * Establish IMAP connection
     */
    public function init_imap()
    {
        $this->rc->imap_connect();
        $this->cache = $this->rc->get_cache('zpush', 'db', 900);
        $this->cache->expunge();

        if ($meta = $this->rc->imap->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()
    {
        $cmd = get_input_value('cmd', RCUBE_INPUT_GPC);
        $imei = get_input_value('id', RCUBE_INPUT_GPC);

        switch ($cmd) {
        case 'load':
            $result = array();
            $this->init_imap();
            $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':
            $this->init_imap();
            $devices = $this->list_devices();
            $syncmode = intval(get_input_value('syncmode', RCUBE_INPUT_POST));
            $devicealias = get_input_value('devicealias', RCUBE_INPUT_POST);
            $laxpic = intval(get_input_value('laxpic', RCUBE_INPUT_POST));
            $subsciptions = get_input_value('subscribed', RCUBE_INPUT_POST);
            $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 = !$this->rc->imap->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', $this->rc->imap->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 = $this->rc->imap->get_metadata($folder, array(self::ACTIVESYNC_KEY));
                        if ($asyncdata = $folderdata[$folder][self::ACTIVESYNC_KEY])
                            $metadata = $this->unserialize_metadata($asyncdata);
                        $metadata['FOLDER'] = $meta;

                        $err |= !$this->rc->imap->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;
        }

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


    /**
     * Render main UI for device configuration
     */
    public function config_view()
    {
        require_once($this->home . '/kolab_zpush_ui.php');
        
        $this->init_imap();
        
        // checks if IMAP server supports any of METADATA, ANNOTATEMORE, ANNOTATEMORE2
        if (!($this->rc->imap->get_capability('METADATA') || $this->rc->imap->get_capability('ANNOTATEMORE') || $this->rc->imap->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->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 {
                $this->folders = $this->rc->imap->list_unsubscribed();
                foreach ($this->folders as $folder) {
                    $folderdata = $this->rc->imap->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 '';
    }

}