summaryrefslogtreecommitdiff
path: root/plugins/libkolab/lib/kolab_format_event.php
blob: 075c517861a1c36905ea85ab600e6194f0110f6f (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
<?php

/**
 * Kolab Event model class
 *
 * @version @package_version@
 * @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_format_event extends kolab_format_xcal
{
    public $CTYPEv2 = 'application/x-vnd.kolab.event';

    public static $scheduling_properties = array('start', 'end', 'allday', 'location', 'status', 'cancelled');

    protected $objclass = 'Event';
    protected $read_func = 'readEvent';
    protected $write_func = 'writeEvent';

    /**
     * Default constructor
     */
    function __construct($data = null, $version = 3.0)
    {
        parent::__construct(is_string($data) ? $data : null, $version);

        // got an Event object as argument
        if (is_object($data) && is_a($data, $this->objclass)) {
            $this->obj = $data;
            $this->loaded = true;
        }
    }

    /**
     * Clones into an instance of libcalendaring's extended EventCal class
     *
     * @return mixed EventCal object or false on failure
     */
    public function to_libcal()
    {
        static $error_logged = false;

        if (class_exists('kolabcalendaring')) {
            return new EventCal($this->obj);
        }
        else if (!$error_logged) {
            $error_logged = true;
            rcube::raise_error(array(
                'code' => 900, 'type' => 'php',
                'message' => "required kolabcalendaring module not found"
            ), true);
        }

        return false;
    }

    /**
     * Set event properties to the kolabformat object
     *
     * @param array  Event data as hash array
     */
    public function set(&$object)
    {
        // set common xcal properties
        parent::set($object);

        // do the hard work of setting object values
        $this->obj->setStart(self::get_datetime($object['start'], null, $object['allday']));
        $this->obj->setEnd(self::get_datetime($object['end'], null, $object['allday']));
        $this->obj->setTransparency($object['free_busy'] == 'free');

        $status = kolabformat::StatusUndefined;
        if ($object['free_busy'] == 'tentative')
            $status = kolabformat::StatusTentative;
        if ($object['cancelled'])
            $status = kolabformat::StatusCancelled;
        else if ($object['status'] && array_key_exists($object['status'], $this->status_map))
            $status = $this->status_map[$object['status']];
        $this->obj->setStatus($status);

        // save recurrence exceptions
        if (is_array($object['recurrence']) && is_array($object['recurrence']['EXCEPTIONS'])) {
            $recurrence_id_format = $object['allday'] ? 'Ymd' : 'Ymd\THis';
            $vexceptions = new vectorevent;
            foreach((array)$object['recurrence']['EXCEPTIONS'] as $i => $exception) {
                $exevent = new kolab_format_event;
                $exevent->set(($compacted = $this->compact_exception($exception, $object)));  // only save differing values

                // get value for recurrence-id
                if (!empty($exception['recurrence_date']) && is_a($exception['recurrence_date'], 'DateTime')) {
                    $recurrence_id = $exception['recurrence_date'];
                    $compacted['_instance'] = $recurrence_id->format($recurrence_id_format);
                }
                else if (!empty($exception['_instance']) && strlen($exception['_instance']) > 4) {
                    $recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $object['start']->getTimezone());
                    $compacted['recurrence_date'] = $recurrence_id;
                }
                $exevent->obj->setRecurrenceID(self::get_datetime($recurrence_id ?: $exception['start'], null,  $object['allday']), (bool)$exception['thisandfuture']);

                $vexceptions->push($exevent->obj);

                // write cleaned-up exception data back to memory/cache
                $object['recurrence']['EXCEPTIONS'][$i] = $this->expand_exception($compacted, $object);
            }
            $this->obj->setExceptions($vexceptions);
        }

        // cache this data
        $this->data = $object;
        unset($this->data['_formatobj']);
    }

    /**
     *
     */
    public function is_valid()
    {
        return !$this->formaterror && (($this->data && !empty($this->data['start']) && !empty($this->data['end'])) ||
            (is_object($this->obj) && $this->obj->isValid() && $this->obj->uid()));
    }

    /**
     * Convert the Event object into a hash array data structure
     *
     * @param array Additional data for merge
     *
     * @return array  Event data as hash array
     */
    public function to_array($data = array())
    {
        // return cached result
        if (!empty($this->data))
            return $this->data;

        // read common xcal props
        $object = parent::to_array($data);

        // read object properties
        $object += array(
            'end'         => self::php_datetime($this->obj->end()),
            'allday'      => $this->obj->start()->isDateOnly(),
            'free_busy'   => $this->obj->transparency() ? 'free' : 'busy',  // TODO: transparency is only boolean
            'attendees'   => array(),
        );

        // derive event end from duration (#1916)
        if (!$object['end'] && $object['start'] && ($duration = $this->obj->duration()) && $duration->isValid()) {
            $interval = new DateInterval('PT0S');
            $interval->d = $duration->weeks() * 7 + $duration->days();
            $interval->h = $duration->hours();
            $interval->i = $duration->minutes();
            $interval->s = $duration->seconds();
            $object['end'] = clone $object['start'];
            $object['end']->add($interval);
        }

        // organizer is part of the attendees list in Roundcube
        if ($object['organizer']) {
            $object['organizer']['role'] = 'ORGANIZER';
            array_unshift($object['attendees'], $object['organizer']);
        }

        // status defines different event properties...
        $status = $this->obj->status();
        if ($status == kolabformat::StatusTentative)
          $object['free_busy'] = 'tentative';
        else if ($status == kolabformat::StatusCancelled)
          $object['cancelled'] = true;

        // this is an exception object
        if ($this->obj->recurrenceID()->isValid()) {
            $object['thisandfuture'] = $this->obj->thisAndFuture();
            $object['recurrence_date'] = self::php_datetime($this->obj->recurrenceID());
        }
        // read exception event objects
        else if (($exceptions = $this->obj->exceptions()) && is_object($exceptions) && $exceptions->size()) {
            $recurrence_exceptions = array();
            $recurrence_id_format = $object['allday'] ? 'Ymd' : 'Ymd\THis';
            for ($i=0; $i < $exceptions->size(); $i++) {
                if (($exobj = $exceptions->get($i))) {
                    $exception = new kolab_format_event($exobj);
                    if ($exception->is_valid()) {
                        $exdata = $exception->to_array();

                        // fix date-only recurrence ID saved by old versions
                        if ($exdata['recurrence_date'] && $exdata['recurrence_date']->_dateonly && !$object['allday']) {
                            $exdata['recurrence_date']->setTimezone($object['start']->getTimezone());
                            $exdata['recurrence_date']->setTime($object['start']->format('G'), intval($object['start']->format('i')), intval($object['start']->format('s')));
                        }

                        $recurrence_id = $exdata['recurrence_date'] ?: $exdata['start'];
                        $exdata['_instance'] = $recurrence_id->format($recurrence_id_format);
                        $recurrence_exceptions[] = $this->expand_exception($exdata, $object);
                    }
                }
            }
            $object['recurrence']['EXCEPTIONS'] = $recurrence_exceptions;
        }

        return $this->data = $object;
    }

    /**
     * Callback for kolab_storage_cache to get object specific tags to cache
     *
     * @return array List of tags to save in cache
     */
    public function get_tags()
    {
        $tags = parent::get_tags();

        foreach ((array)$this->data['categories'] as $cat) {
            $tags[] = rcube_utils::normalize_string($cat);
        }

        return $tags;
    }

    /**
     * Remove some attributes from the exception container
     */
    private function compact_exception($exception, $master)
    {
        $forbidden = array('recurrence','organizer','_attachments');

        foreach ($forbidden as $prop) {
            if (array_key_exists($prop, $exception)) {
                unset($exception[$prop]);
            }
        }

        foreach ($master as $prop => $value) {
            if (isset($exception[$prop]) && gettype($exception[$prop]) == gettype($value) && $exception[$prop] == $value) {
                unset($exception[$prop]);
            }
        }

        // preserve this property for date serialization
        $exception['allday'] = $master['allday'];

        return $exception;
    }

    /**
     * Copy attributes not specified by the exception from the master event
     */
    private function expand_exception($exception, $master)
    {
        foreach ($master as $prop => $value) {
            if (empty($exception[$prop]) && !empty($value)) {
                $exception[$prop] = $value;
                if ($prop == 'recurrence') {
                    unset($exception[$prop]['EXCEPTIONS']);
                }
            }
        }

        return $exception;
    }

}