source: sandbox/2.4.2-expresso1/prototype/modules/calendar/interceptors/DBMapping.php @ 6797

Revision 6797, 46.4 KB checked in by acoutinho, 11 years ago (diff)

Ticket #2966 - primeiras implementacoes de tarefas aninhamento de equipo

Line 
1<?php
2
3//Definindo Constantes
4require_once ROOTPATH . '/modules/calendar/constants.php';
5
6require_once ROOTPATH . '/modules/calendar/interceptors/Helpers.php';
7
8use prototype\api\Config as Config;
9
10class DBMapping extends Helpers {
11
12    static function encodeCreateSchedulable(&$uri, &$params, &$criteria, $original)
13    {
14
15        if(isset($params['summary']) && $params['summary'] == '')
16            $params['summary'] = 'Evento sem título';
17
18        if (!is_numeric($params['startTime']))
19            $params['startTime'] = self::parseTimeDate($params['startTime'], $params['timezone']);
20
21        if (!is_numeric($params['endTime'])) {
22            $params['endTime'] = self::parseTimeDate($params['endTime'], $params['timezone']);
23
24            if ($params['allDay'])
25                $params['endTime'] = $params['endTime'] + 86400000;
26        }
27
28        $params['rangeEnd'] = $params['endTime'];
29        $params['rangeStart'] = $params['startTime'];
30
31        ///////////////////////////////////////////////////////////////////
32
33        $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000';
34        $params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] : time() . '000';
35        $params['uid'] = isset($params['uid']) ? $params['uid'] : self::_makeUid();
36    }
37
38    static function parseTimeDate($time, $timezone) {
39        return strtotime($time . ' ' . $timezone) . '000';
40    }
41
42     public function encodeCreateAlarm( &$uri , &$params , &$criteria , $original ){
43       
44        if(!isset($params['schedulable']) || !isset($params['rangeStart']) || !isset($params['rangeEnd']) )
45        {
46            $participant = Controller::read( array( 'concept' => 'participant' , 'id' => $params['participant'] ) , array('schedulable')  );
47
48            $params['schedulable'] = $participant['schedulable'];
49
50            $params['type'] = self::codeAlarmType($params['type']);
51
52            $params['offset'] = $params['time'] * 1000;
53
54            switch( strtolower($params['unit']) )
55            {
56                case 'd': $params['offset'] *= 24;
57                case 'h': $params['offset'] *= 60;
58                case 'm': $params['offset'] *= 60;
59            }
60        }
61    }
62
63    public function encodeCreateSuggestion(&$uri, &$params, &$criteria, $original) {
64        $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000';
65    }
66
67    public function encodeUpdateAlarm(&$uri, &$params, &$criteria, $original) {
68        if (isset($params['type']))
69            $params['type'] = self::codeAlarmType($params['type']);
70        else{
71            $alarm = Controller::read( array('concept' => 'alarm' , 'id' => $params['id'] ));
72
73            $params['unit'] = $alarm['unit'];
74        }
75        $params['offset'] = $params['time'] * 1000;
76
77
78        switch( strtolower($params['unit']) )
79        {
80            case 'd': $params['offset'] *= 24;
81            case 'h': $params['offset'] *= 60;
82            case 'm': $params['offset'] *= 60;
83        }
84       
85    }
86
87    public function encodeCreateAttachment(&$uri, &$params, &$criteria, $original) {
88
89        if (!isset($params['source']))
90            return false;
91
92        if (isset($_FILES[$params['source']]))
93            if (isset($params['id']))
94                $params = array_merge($_FILES[$params['source']], array('id' => $params['id']));
95            else
96                $params = $_FILES[$params['source']];
97
98        if (isset($params['owner']))
99            $params['owner'] = Config::me('uidNumber');
100    }
101
102///////////////////////////////////////////////////////////////////////////////////////////////////////////////
103
104    public function encodeSignatureAlarmType(&$uri, &$params, &$criteria, $original) {
105        $params['type'] = self::codeAlarmType($params['type']);
106    }
107
108    public function insertOwnerLink(&$uri, &$params, &$criteria, $original) {
109        $params['owner'] = Config::me('uidNumber');
110    }
111
112    public function encodeServiceUser(&$uri, &$params, &$criteria, $original) {
113        if (isset($params['isExternal']) && $params['isExternal'] == '1')
114            $uri['service'] = 'PostgreSQL';
115    }
116
117    public function prepareRepeat(&$uri, &$params, &$criteria, $original) {
118        if (isset($params['startTime']) || isset($params['endTime'])) {
119           
120            if(!isset($params['schedulable']))
121                $params = array_merge($params , Controller::read(array('concept' => 'repeat', 'id' => $params['id']), array('schedulable')));
122 
123            $timezone = Controller::read(array('concept' => 'schedulable', 'id' => $params['schedulable']), array('timezone'));
124
125            if (isset($params['startTime']))
126                $params['startTime'] = self::parseTimeDate($params['startTime'], $timezone['timezone']);
127            if (isset($params['endTime']))
128                $params['endTime'] = self::parseTimeDate($params['endTime'], $timezone['timezone']);
129        }
130    }
131
132    public function findSchedulable(&$uri, &$params, &$criteria, $original) {
133        if (isset($criteria['filter'][2][1]) && $criteria['filter'][2][1] == 'calendar') {
134
135            $sql = ' SELECT calendar_object.id as id ,calendar_object.cal_uid as "uid", calendar_object.type_id as "type", '
136                .'calendar_object.dtstart as "startTime", calendar_object.summary as "summary", '
137                .'calendar_object.description as "description", calendar_object.dtend as "endTime" , '
138                .'calendar_object.location as "location", calendar_object.allday as "allDay", '
139                .'calendar_object.transp as "transparent", calendar_object.class_id as "class", '
140                .'calendar_object.repeat as "repeat", calendar_object.range_start as "rangeStart", '
141                .'calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", '
142                .'calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence", '
143                .'calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as '
144                .'calendar FROM calendar_to_calendar_object , calendar_object '
145                .'WHERE ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['filter'][2][2]) . '\')) '
146                .'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id ';   
147           
148            if(isset($criteria['searchEvent']) && $criteria['searchEvent']){
149                $where = 'AND (((upper("summary") like upper(\'%'.$criteria['filter'][1][1][2].'%\') OR upper("description") like upper(\'%'.$criteria['filter'][1][2][2].'%\')))) ORDER BY dtstart LIMIT '.$criteria['limit'].'  OFFSET '.$criteria['offset'].' ';
150                $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
151
152            }else{
153                $start = array( $criteria['filter'][1][1][1][2] , $criteria['filter'][1][2][1][2], $criteria['filter'][1][3][1][2] );
154                $end = array( $criteria['filter'][1][1][2][2] , $criteria['filter'][1][2][2][2], $criteria['filter'][1][3][2][2] );
155
156                $ids = array();
157                $occ = array();
158
159                if ($occurrences = self::checkOccurrences($start[0], $end[0], $criteria['filter'][2][2]))
160                    foreach ($occurrences as $id => $occurrence) {
161                        $ids[] = $id;
162                        $occ[] = $occurrence;
163                    }   
164
165                $where = 'AND ((range_end >= \'' . $start[0] . '\' AND range_end <= \'' . $end[0] . '\') OR '
166                        .'(range_start >= \'' . $start[1] . '\' AND range_start <= \'' . $end[1] . '\') OR '
167                        .'(range_start <= \'' . $start[2] . '\' AND range_end >= \'' . $end[2] . '\')) '
168                .(!empty($ids) ? ' ' .'AND calendar_object.id NOT IN (\'' . implode('\',\'', $ids) . '\') ' : ' ')
169                .'AND calendar_object.dtstart NOT IN (SELECT calendar_repeat_occurrence.occurrence from calendar_repeat_occurrence, '
170                .'calendar_repeat where (calendar_repeat_occurrence.repeat_id = calendar_repeat.id) '
171                .'AND (calendar_repeat.object_id = calendar_object.id))';
172
173                $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
174                $params = array_merge($params, $occ);           
175            }
176            $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
177            return false;
178        }
179    }
180
181    public function deepnessFindRepeatOccurrence(&$uri, &$result, &$criteria, $original) {
182
183        if (!isset($criteria['deepness']) || $criteria['deepness'] == 0)
184            return;
185
186        foreach ($result as $i => &$res)
187            if (isset($res['repeat']))
188                $res['repeat'] = Controller::read(array('concept' => 'repeat', 'id' => $res['repeat']), false, array('deepness' => intval($criteria['deepness']) - 1));
189    }
190
191    public function deepnessRepeat(&$uri, &$result, &$criteria, $original) {
192
193        if (!isset($criteria['deepness']) || $criteria['deepness'] == 0)
194            return;
195
196        $result['schedulable'] = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'id', $result['schedulable']), 'deepness' => intval($criteria['deepness']) - 1));
197        $result['schedulable'] = $result['schedulable'][0];
198    }
199
200    public function saveOccurrences(&$uri, &$result, &$criteria, $original) {
201        $ranges = Controller::find(array('concept' => 'repeatRange'), array('rangeStart', 'rangeEnd'), array('filter' => array('=', 'user', Config::me("uidNumber"))));
202
203        if (!is_array($ranges) || !isset($ranges[0]['rangeStart']) || !isset($ranges[0]['rangeEnd']))
204            return;
205
206        if (isset($result['id']))
207            $id = $result['id'];
208        else
209            $id = $uri['id'];
210
211        $repeat = Controller::read(array('concept' => 'repeat', 'id' => $id));
212
213        unset($repeat['schedulable']);
214        unset($repeat['id']);
215
216        $exceptions = array();
217
218        if (isset($original['properties']['exceptions'])) {
219            $exceptions = explode(',', $original['properties']['exceptions']);
220            unset($repeat['exceptions']);
221        }
222
223        $lastExceptions = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('AND', array('=', 'repeat', $id), array('=', 'exception', 1))));
224
225        //Recurepa as execeções anteriores caso exista
226        if (isset($lastExceptions) && count($lastExceptions) && $lastExceptions)
227            foreach ($lastExceptions as $value)
228                array_push($exceptions, $value['occurrence']);
229
230        $params = array_diff(self::decodeRepeat($repeat, $ranges[0]['rangeStart'], $ranges[0]['rangeEnd']), $exceptions);
231
232        Controller::delete(array('concept' => 'repeatOccurrence'), false, array('filter' => array('=', 'repeat', $id)));
233
234        if (!empty($params))
235            Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES('" . $id . "','0','" . implode("'),('" . $id . "','0','", $params) . "')" . ( empty($exceptions) ? "" : ",('" . $id . "','1','" . implode("'),('" . $id . "','1','", $exceptions) . "')" ));
236        else if(!empty($exceptions))
237            Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES ('" . $id . "','1','" . implode("'),('" . $id . "','1','", $exceptions) . "')" );
238    }       
239
240    public function checkOccurrences($start, $end, $calendarIds) {
241
242        $ranges = Controller::find(array('concept' => 'repeatRange'), array('rangeStart', 'rangeEnd'), array('filter' => array('=', 'user', Config::me("uidNumber"))));
243        $ranges = $ranges[0];
244
245        $origStart = $start;
246        $origEnd = $end;
247
248        if ($initialized = (isset($ranges['rangeStart']) && isset($ranges['rangeEnd']))) {
249            if ($ranges['rangeStart'] <= $start)
250                $start = false;
251            if ($ranges['rangeEnd'] >= $end)
252                $end = false;
253        }
254
255        $repeats = self::findRepeats($calendarIds);
256        if (!is_array($repeats) || empty($repeats))
257            return( false );
258
259        $result = array();
260        $ids = array();
261
262        foreach ($repeats as $repeat) {
263            $ids[] = $id = $repeat['id'];
264            unset($repeat['id']);
265
266            if (!isset($result[$id]))
267                $result[$id] = !$initialized ? array($repeat['startTime']) : array();
268
269            if (!$initialized)
270                $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $start, $end));
271            else {
272                if ($start)
273                    $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $start, $ranges['rangeStart']));
274
275                if ($end)
276                    $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $ranges['rangeEnd'], $end));
277            }
278
279            if (empty($result[$id]))
280                unset($result[$id]);
281        }
282
283        if ($start || $end) {
284            Controller::begin(array('service' => 'PostgreSQL'));
285
286            foreach ($result as $id => $res){
287               
288                $ocurrences = array_unique($res);
289                Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,occurrence)VALUES('" . $id . "','" . implode("'),('" . $id . "', '", $ocurrences) . "')");
290            }
291            $data = array();
292
293            if ($start)
294                $data['rangeStart'] = $start;
295
296            if ($end)
297                $data['rangeEnd'] = $end;
298
299            if (!$initialized)
300                $data['user'] = Config::me('uidNumber');
301
302            Controller::call(( $initialized ? 'replace' : 'create'), array('concept' => 'repeatRange'), $data, array('filter' => array('=', 'user', Config::me('uidNumber'))));
303
304            Controller::commit(array('service' => 'PostgreSQL'));
305        }
306
307//      $return = Controller::find( array( 'concept' => 'repeatOccurrence' ), false, array( 'filter' => array( 'AND', array( '>=', 'occurrence', $origStart ), array( '<=', 'occurrence', $origEnd ), array( 'IN', 'repeat', $ids ) ), 'deepness' => $deep ) );
308
309        $return = Controller::service('PostgreSQL')->execResultSql('SELECT calendar_repeat_occurrence.occurrence as "occurrence", calendar_repeat.object_id as "schedulable" FROM calendar_repeat, calendar_repeat_occurrence WHERE calendar_repeat_occurrence.occurrence >= \'' . $origStart . '\' AND calendar_repeat_occurrence.occurrence <= \'' . $origEnd . '\' AND calendar_repeat_occurrence.repeat_id IN (\'' . implode('\',\'', $ids) . '\') AND calendar_repeat.id = calendar_repeat_occurrence.repeat_id AND calendar_repeat_occurrence.exception != 1');
310
311        if (!is_array($return))
312            return( false );
313
314        $result = array();
315        $params = array();
316
317        foreach ($return as $ret) {
318            $currentId = $ret['schedulable'];
319
320            if (!isset($result[$currentId])) {
321                $result[$currentId] = Controller::read(array('concept' => 'schedulable', 'id' => $currentId));
322                $result[$currentId]['occurrences'] = array();
323
324                $calendarToCalendarObj = self::schedulable2calendarToObject($currentId);
325                $result[$currentId]['calendar'] = $calendarToCalendarObj[0]['calendar_id'];
326            }
327
328            $result[$currentId]['occurrences'][] = $ret['occurrence'];
329        }
330
331        return( $result );
332    }
333
334    public static function findRepeats($ids) {
335        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_repeat.wkst as "wkst", calendar_repeat.byweekno as "byweekno", calendar_repeat.byminute as "byminute", calendar_repeat.bysecond as "bysecond", calendar_repeat.byyearday as "byyearday", calendar_repeat.bymonthday as "bymonthday", calendar_repeat.bysetpos as "bysetpos", calendar_repeat.byday as "byday", calendar_repeat.byhour as "byhour", calendar_repeat.interval as "interval", calendar_repeat.frequency as "frequency", calendar_repeat.until as "endTime", calendar_repeat.id as "id", calendar_repeat.count as "count", calendar_repeat.dtstart as "startTime" FROM calendar_repeat, calendar_to_calendar_object WHERE calendar_repeat.object_id = calendar_to_calendar_object.calendar_object_id AND calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $ids) . '\')');
336    }
337
338//HELPERS
339    public static function decodeRepeat($repeat, $start, $end) {
340
341        date_default_timezone_set('UTC');
342
343        require_once ROOTPATH . '/plugins/when/When.php';
344
345        $r = new When();
346
347        if ($repeat['frequency'] === 'none')
348            return( array() );
349
350        //Nao deve ser usando o horário da repeticao pois nela contem apenas o dias,
351        //deve se recuperar o horário do evento para um correto calculo.
352        if (max($start, $repeat['startTime']) != $repeat['startTime']) {
353            $time = new DateTime('@' . (int) ( $repeat['startTime'] / 1000 ), new DateTimeZone('UTC'));
354
355            $hoursOcurrence = new DateTime('@' . (int) ( $start / 1000 ), new DateTimeZone('UTC'));
356            $hoursOcurrence = $hoursOcurrence->format('H');
357
358            $diffTime = ((($time->format('H') - $hoursOcurrence) * (3600000)) + ($time->format('i') * (60000)));
359            $start = new DateTime('@' . (int) ( ( $start + $diffTime ) / 1000 ), new DateTimeZone('UTC'));
360        }else
361            $start = new DateTime('@' . (int) ( max($start, $repeat['startTime']) / 1000 ), new DateTimeZone('UTC'));
362
363        foreach ($repeat as $rule => $value) {
364            if (!isset($value) || !$value || $value === "0")
365                continue;
366
367            switch (strtolower($rule)) {
368                case "starttime": break;
369                case "frequency":
370                    $r->recur($start, $value);
371                    break;
372                case "endtime":
373                    $r->until(new DateTime('@' . (int) ( $value / 1000 )));
374                    break;
375                case "count": case "interval": case "wkst":
376                    $r->$rule($value);
377                    break;
378                default :
379                    $r->$rule(!is_array($value) ? explode(',', $value) : $value );
380                    break;
381            }
382        }
383
384        $return = array();
385
386        while ($result = $r->next()) {
387            $u = $result->format('U') * 1000;
388
389            if ($u > $end) //data da repetição atual maior que a data final da busca do usuario ?
390                break;
391
392            $return[] = $u;
393        }
394
395        return( $return );
396    }
397
398///////////////////////////////////////////////////////////////////////////////////////////////////////////////
399
400    public function updateCalendar(&$uri, &$params, &$criteria, $original) {       
401        if (isset($params['calendar'])) {
402            if(isset($params['lastCalendar'])){
403                $calendarObjects = self::referenceCalendarToObject($uri['id'], $params['lastCalendar']);
404                $params2['calendar'] = $params['calendar'];
405            }else{
406                $calendarObjects = self::schedulable2calendarToObject($uri['id']);
407                $params2['calendar'] = $params['calendar'];
408            }
409           
410            foreach ($calendarObjects as $calendarObject)
411                Controller::update(array('concept' => 'calendarToSchedulable', 'id' => $calendarObject['calendar_to_calendar_object']), $params2);
412
413            unset($params['calendar']);
414
415            if (count($params) < 1)
416                return false;
417        }
418    }
419
420//Encode Update
421
422    public function encodeUpdateSchedulable(&$uri, &$params, &$criteria, $original) {
423
424        $event = Controller::read(array('concept' => 'schedulable', 'id' => $params['id']));
425       
426        if (isset($params['startTime'])) {
427
428            if (!is_numeric($params['startTime']))
429                $params['startTime'] = self::parseTimeDate($params['startTime'], $event['timezone']);
430
431            $params['rangeStart'] = $params['startTime'];
432        }if (isset($params['endTime'])) {
433
434            if (!is_numeric($params['endTime'])) {
435                $params['endTime'] = self::parseTimeDate($params['endTime'], $event['timezone']);
436
437            if ((isset($params['allDay']) && $params['allDay']) || ( !isset($params['allDay']) && $event['allDay']))
438                $params['endTime'] = $params['endTime'] + 86400000;
439            }
440            $params['rangeEnd'] = $params['endTime'];
441        }
442    }
443
444    static function putEvent(&$uri, &$result, &$criteria, $original) {
445        if (Config::module('useCaldav', 'expressoCalendar')) { //Ignorar Put dos eventos ja vindos do caldav
446            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
447
448            $eventID = (isset($result['id'])) ? $result['id'] : $uri['id'];
449            $event = Controller::read(array('concept' => 'schedulable', 'id' => $eventID));
450
451            $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $eventID)));
452
453            if (is_array($participants) && count($participants) > 0)
454                foreach ($participants as $ii => $vv) {
455                    if ($vv['isExternal'] == 1)
456                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
457                    else
458                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
459                }
460
461            $event['URI']['concept'] = 'schedulable';
462            $event['participants'] = $participants;
463
464            $ical = Controller::format(array('service' => 'iCal'), array($event));
465            $calendars = self::schedulable2calendarToObject($original['properties']['id']); //Busca os calendarios do usuario logado que contenham o evento
466            if (is_array($calendars))
467                foreach ($calendars as $calendar)
468                    DAViCalAdapter::putIcal($ical, array('uid' => $event['uid'], 'location' => $calendar['calendar_location']));
469        }
470    }
471
472///////////////////////////////////////////////////////////////////////////////////////////////////////////////
473
474    public function verifyCalendarLocation(&$uri, &$params, &$criteria, $original) {
475        if (!isset($params['location']))
476            $params['location'] = Config::me('uid') . '/' . $params['name'];
477    }
478
479    //TODO: Remover apos suporte a ManytoMany na api
480    public function createCalendarToSchedulable(&$uri, &$result, &$criteria, $original) {
481
482        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id']));
483    }
484
485    public function createCreateSchedulableToAttachment(&$uri, &$params, &$criteria, $original) {
486        if (array_key_exists('attachments', $original['properties']))
487            foreach ($original['properties']['attachments'] as $key => $value) {
488                if (isset($params['id']))
489                    Controller::create(array('concept' => 'schedulableToAttachment'), array('attachment' => $value['attachment'], 'schedulable' => $params['id']));
490            }
491    }
492
493    public function deepnessFindCalendarShared(&$uri, &$result, &$criteria, $original) {
494        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != '0' && count($result) > 0) {
495
496            $calendarIds = array();
497            foreach ($result as $key => $value)
498                array_push($calendarIds, $value['calendar']);
499
500            $calendar = Controller::find(array('concept' => 'calendar'), false, array('filter' => array('AND', array('IN', 'id', $calendarIds), $original['criteria']['filter'])));
501
502            if ($calendar && count($calendar) > 0){
503                $newResult = array();
504                foreach ($calendar as $key => $value) {
505                    foreach ($result as $k => $r) {
506
507                        if ($r['calendar'] == $value['id']) {
508                            $r['calendar'] = $value;
509                            array_push($newResult, $r);
510                        }
511                    }
512                }
513
514                foreach ($newResult as $key => &$value) {
515                    if ($value['user'] != 0) {
516                        $user = $value['user'];
517                        $value['user'] = Controller::read(array('concept' => 'user', 'id' => $user));
518
519                        if (!$value['user'])
520                            $value['user'] = Controller::read(array('concept' => 'group', 'id' => $user));
521                    }
522                }
523
524                $result = $newResult;
525            }else
526                $result = '';
527        }
528    }
529
530    //TODO: Remover apos suporte a deepness na api
531    public function deepnessFindEvent(&$uri, &$result, &$criteria, $original) {
532        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
533            $Time = new DateTime('now', new DateTimeZone('UTC'));
534            $DayLigth = array();
535            foreach ($result as $i => $v) {
536
537                if (!isset($currentTimezone) || $currentTimezone != $original['criteria']['timezones'][$v['calendar']]) {
538                    $currentTimezone = isset($original['criteria']['timezones'][$v['calendar']]) ? $original['criteria']['timezones'][$v['calendar']] : $v['timezone'];
539                    $Time->setTimezone(new DateTimeZone($currentTimezone));
540                }
541
542                $Time->setTimestamp((int) ($v['startTime'] / 1000));
543                $DayLigth['calendar']['startTime'] = $Time->format('I') ? 1 : 0;
544
545                $Time->setTimestamp((int) ($v['endTime'] / 1000));
546                $DayLigth['calendar']['endTime'] = $Time->format('I') ? 1 : 0;
547
548                if ($currentTimezone != $v['timezone']) {
549                    $currentTimezone = $v['timezone'];
550                    $Time->setTimezone(new DateTimeZone($v['timezone']));
551
552                    $Time->setTimestamp((int) ($v['startTime'] / 1000));
553                    $DayLigth['event']['startTime'] = $Time->format('I') ? 1 : 0;
554
555                    $Time->setTimestamp((int) ($v['endTime'] / 1000));
556                    $DayLigth['event']['endTime'] = $Time->format('I') ? 1 : 0;
557                }else
558                    $DayLigth['event'] = $DayLigth['calendar'];
559
560
561                $result[$i]['DayLigth'] = $DayLigth;
562
563                if (isset($v['id'])) {
564                    $data = self::decodeParticipantsEvent($uri, $v, $criteria, $original);
565
566                    $result[$i]['statusAttendees'] = isset($data['statusAttendees']) ? $data['statusAttendees'] : false;
567                    $result[$i]['sizeAttendees'] = isset($data['sizeAttendees']) ? $data['sizeAttendees'] : false;
568                    $result[$i]['participants'] = $data['attendees'];
569
570                    $attachmentRelation = Controller::find(array('concept' => 'schedulableToAttachment'), false, array('filter' => array('=', 'schedulable', $v['id'])));
571                    if (is_array($attachmentRelation)) {
572                        $attachments = array();
573                        foreach ($attachmentRelation as $key => $value)
574                            if (isset($value['attachment']) || !!$value['attachment'])
575                                $attachments[$key] = $value['attachment'];
576                        //Pega os anexos sem source
577                        $result[$i]['attachments'] = Controller::find(array('concept' => 'attachment'), array('id', 'name', 'type', 'size'), array('filter' => array('IN', 'id', $attachments)));
578                    }
579
580                    $repeat = Controller::find(array('concept' => 'repeat'), false, array('filter' => array('=', 'schedulable', $v['id'])));
581
582                    unset($result[$i]['repeat']);
583
584                    if (is_array($repeat))
585                        $result[$i]['repeat'] = $repeat[0];
586                }
587            }
588        }
589
590        return $result;
591    }
592   
593
594//TODO: Remover apos suporte a deepness na api
595    public function deepnessReadParticipant( &$uri , &$result , &$criteria , $original ){
596       
597       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
598       {
599            if(isset($result['id']) && isset($result['user']))
600            {
601                $result['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result['user'] , 'service' => ( $result['isExternal'] == 1 ? 'PostgreSQL' : 'OpenLDAP' ) ) );
602
603                if($result['user']['id'] == Config::me('uidNumber'))
604                  $result['alarms'] = Controller::find( array( 'concept' => 'alarm' ) , null , array('filter' => array('=', 'participant' ,$result['id'] ) ) );
605            }
606       }
607       
608     
609       
610   }
611
612    //TODO: Remover apos suporte a deepness na api
613    public function deepnessReadEvent( &$uri , &$result , &$criteria , $original ){             
614   
615       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
616       {
617            if(isset($result['id']))
618            {
619                $result['participants'] = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=' ,  'schedulable' ,  $result['id']), 'deepness' => $original['criteria']['deepness'] - 1) );
620
621                $repeat =  Controller::find( array( 'concept' => 'repeat' ), false, array( 'filter' => array( '=', 'schedulable', $result['id'] ) ) );
622
623                if(is_array($repeat))
624                    $result['repeat'] = $repeat[0];
625            }
626           
627       }
628   }
629   
630    //TODO: Remover apos suporte a deepness na api
631    public function deepnessFindParticipant( &$uri , &$result , &$criteria , $original ){
632       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
633       {
634           foreach ($result as $i => &$v)
635           {
636                self::deepnessReadParticipant( $uri, $v, $criteria, $original );
637           }
638       } 
639       
640   }
641
642    //TODO: Remover apos suporte a deepness na api
643    public function deepnessReadCalendarSignature(&$uri, &$result, &$criteria, $original) {
644
645        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
646            if (isset($result['calendar'])) {
647                $result['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $result['calendar']));
648                $result['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $result['id'])));
649            }
650    }
651
652    //TODO: Remover apos suporte a deepness na api
653    public function deepnessFindCalendarSignature(&$uri, &$result, &$criteria, $original) {
654
655        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
656            foreach ($result as $i => $v) {
657                if (isset($v['calendar'])) {
658                    $result[$i]['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $v['calendar']), false, false);
659                    $result[$i]['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $v['id'])));
660                    //Caso não seja o dono da agenda retorna o objeto permission com as acls
661                    if ($result[$i]['isOwner'] == 0) {
662                        $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'user', Config::me('uidNumber')))));
663
664                        if (!is_array($permission) || !$permission) {
665
666                            $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'type', '1'))));
667                        }
668                        $result[$i]['permission'] = $permission[0];
669                    }
670                }
671                //TODO - Padronizar retorno do deepness
672                if (isset($v['user']))
673                    $result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $v['user']), false, false);
674            }
675        }
676    }
677
678//Decode Find       
679    public function decodeFindConcept(&$uri, &$result, &$criteria, $original) {
680        if ($result && is_array($result)) {
681            $m = array_flip(self::${$uri['concept'] . 'Map'});
682            $new = array();
683            foreach ($result as $i => $v)
684                $new[$i] = self::parseConcept($result[$i], $m);
685
686
687            $result = $new;
688        }
689    }
690
691    public function decodeFindSchedulable(&$uri, &$result, &$criteria, $original) {
692        if ($result && is_array($result)) {
693            $m = array_flip(self::${$uri['concept'] . 'Map'});
694            $m['calendar_id'] = 'calendar';
695            $new = array();
696            foreach ($result as $i => $v)
697                $new[$i] = self::parseConcept($result[$i], $m);
698
699
700            $result = $new;
701        }
702    }
703
704    public function decodeFindAttachment(&$uri, &$result, &$criteria, $original) {
705        if (isset($result))
706            foreach ($result as $key => &$value)
707                $value['source'] = base64_decode($value['source']);
708    }
709
710    public function decodeSignatureAlarmType(&$uri, &$result, &$criteria, $original) {
711        if (is_array($result))
712            foreach ($result as &$param)
713                if (isset($param['type']))
714                    $param['type'] = self::decodeAlarmType($param['type']);
715    }
716
717/////////////////////////////////////////////////////////////////////////
718
719    static function decodeParticipantsEvent( &$uri, $result, &$criteria, $original) {
720        $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $result['id']) ));
721
722        if($participants && ($size = count($participants)) < 100){
723            if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0){
724                self::deepnessFindParticipant($uri, $participants, $criteria, $original);
725                 $participants['attendees'] = $participants;
726            }
727           
728        }else if($participants && ($size = count($participants)) > 100){
729            $owner = Controller::read( array( 'concept' => 'calendarSignature' ) , false ,array( 'filter' => array('AND', array('=', 'calendar'  ,  $result['calendar']), array('=', 'isOwner', '1'))));
730            $owner = Controller::read( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('AND', array('=', 'schedulable'  ,  $result['id']), array('=', 'user', $owner[0]['user'])), 'deepness' => 2));
731
732            if(is_array($owner))
733                $owner = $owner[0];
734
735            $reference = array_slice($participants, 0, 100);
736            $organizer = false;
737            $asOwner = false;
738
739            foreach($reference as $r => &$v){
740                if($v['id'] == $owner['id']){
741                    $v = $owner;
742                    $asOwner = true;
743                    continue;
744                }
745
746                self::deepnessReadParticipant($uri, $v, $criteria, $original);
747
748                if($v['isOrganizer'] == "1" )
749                    $organizer = $v;
750            }
751
752            if(!$organizer){
753                $organizer = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('AND', array('=', 'schedulable'  ,  $result['id']), array('=', 'isOrganizer', '1')), 'deepness' => 2));
754
755                array_push($reference, $organizer[0]);
756
757            }else if($organizer && ($organizer['id'] != $owner['id']))
758                array_merge($reference, $organizer);
759
760            if(!$asOwner)
761                array_push($reference, $owner);
762
763            $statusAttendees = array( 'default' => 0, 'accepted' => 0, 'tentative' => 0, 'cancelled' => 0, 'unanswered' => 0, 'delegated' => 0 );
764            $statusLabels = array( 'default', 'accepted', 'tentative', 'cancelled', 'unanswered', 'delegated' );
765
766            foreach($participants as $k => &$p){
767                if(!$organizer && $p['isOrganizer'] == "1"){
768                    self::deepnessReadParticipant($uri, $p, $criteria, $original);
769                    $reference = array_merge($reference, array($p));
770                }
771
772                $statusAttendees[$statusLabels[$p['status']]]++;
773            }
774
775            $participants['statusAttendees'] = $statusAttendees;
776            $participants['sizeAttendees'] = $size;
777            $participants['attendees'] = $reference;
778        }
779       
780        return $participants;
781    }
782   
783    static function dayAlarm( &$uri , &$params , &$criteria , $original ) {
784        if(isset($criteria['filter'][1]) && $criteria['filter'][1] == 'date')
785        {
786            $target = $criteria['filter'][2];
787
788            $params = array();
789
790            $al = Controller::service('PostgreSQL')->execSql("SELECT distinct co.id as \"id\", co.cal_uid as \"uid\", co.type_id as \"type\", co.dtstart as \"startTime\", co.summary as \"summary\", co.description as \"description\", co.dtend as \"endTime\", co.location as \"location\", co.allday as \"allDay\", co.transp as transparent, co.class_id as class, ".
791                "co.range_start as \"rangeStart\", co.range_end as \"rangeEnd\", co.last_update as \"lastUpdate\", co.dtstamp as \"dtstamp\", co.sequence as \"sequence\", co.tzid as \"timezone\", CASE WHEN rep.object_id = co.id THEN occ.occurrence - al.alarm_offset ELSE co.dtstart - al.alarm_offset END as \"sendTime\", ".
792                "al.unit as \"unit\", al.time as \"time\" FROM calendar_alarm as al, calendar_object as co, calendar_repeat as rep, calendar_repeat_occurrence as occ, calendar_participant as part WHERE ".
793                "al.action_id = '".ALARM_ALERT."' AND al.sent = '0' AND ( (al.participant_id = part.id) AND (part.user_info_id = '". Config::me('uidNumber') ."') ) AND part.object_id = co.id AND ".
794                "CASE WHEN rep.object_id = co.id ".
795                "THEN rep.id = occ.repeat_id AND occ.occurrence - al.alarm_offset >= '$target' AND occ.occurrence - al.alarm_offset <= '".( $target + 86400000)."' ".
796                "ELSE (co.range_start - al.alarm_offset) >= '$target' AND (co.range_start - al.alarm_offset) <= '".( $target + 86400000)."' END");
797           
798            if(is_array($al))
799              foreach( $al as $v )
800                $params[] = array('schedulable' =>  $v);
801             
802            else
803              $params = false;
804 
805            return false;
806        }
807    }
808   
809    static private function countMyCalendarsEvent($id, $owner) {
810                $sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'user', $owner), array('=', 'isOwner', '1'))));
811                $calendars = array();
812                foreach ($sig as $val)
813                        $calendars[] = $val['calendar'];
814
815                $return = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('AND', array('IN', 'calendar', $calendars), array('=', 'schedulable', $id))));
816
817                return (isset($return[0])) ? count($return) : 0;
818    }
819   
820    public function deleteSchedulable(&$uri, &$params, &$criteria, $original) {
821        if (Config::module('useCaldav', 'expressoCalendar'))
822            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
823       
824        if(isset($criteria['filter']) && $criteria['filter'] && isset($criteria['filter'][1][2])){
825            $idSchedulable = $criteria['filter'][1][2];
826                        $idCalendar = $criteria['filter'][2][2];
827            $owner = $criteria['filter'][3][2];
828
829            $qtdMyCalendars = self::countMyCalendarsEvent($idSchedulable, $owner);
830
831            $link = Controller::read(array('concept' => 'calendarToSchedulable'), false, array('filter' => array('AND', array('=','calendar',$idCalendar), array('=','schedulable',$idSchedulable))));
832            $link = (is_array($link) && isset($link[0])) ? $link[0] : $link;
833           
834            $calendar = Controller::read(array('concept' => 'calendar'), false, array('filter' => array('=','id',$idCalendar)));
835            $calendar = (is_array($calendar) && isset($calendar[0])) ? $calendar[0] : $calendar;
836
837            if($isAttende = !self::ownerSchedulable($idSchedulable, $owner)){
838                Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link['id']));
839               
840                if($qtdMyCalendars <= 1){
841
842                    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
843                        array('AND',
844                            array('=', 'user', $owner),
845                            array('=', 'schedulable', $idSchedulable)
846                        )));
847
848                    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
849                }
850
851            }else{
852                if($qtdMyCalendars > 1 )
853                    Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link['id']));
854            }
855
856            if (Config::module('useCaldav', 'expressoCalendar'))
857                    DAViCalAdapter::deleteEvent($idSchedulable, array('location' => $calendar['location']));
858
859            if($isAttende || ($qtdMyCalendars > 1))
860                return false;
861
862            $uri['id'] = $idSchedulable;
863        }
864       
865    }
866
867    public function deleteCalendarToPermissionDependences(&$uri, &$params, &$criteria, $original) {
868        $permission = Controller::read($uri, array('user', 'calendar'));
869
870        $calendarSignature = Controller::find(array('concept' => 'calendarSignature'), array('id'), array('filter' => array('AND', array('=', 'calendar', $permission['calendar']), array('=', 'user', $permission['user']), array('=', 'isOwner', '0'))));
871
872        if ($calendarSignature)
873            Controller::delete(array('concept' => 'calendarSignature', 'id' => $calendarSignature[0]['id']));
874    }
875
876    public function deleteCalendarSignatureDependences(&$uri, &$params, &$criteria, $original) {
877        $signature = Controller::read($uri, array('isOwner', 'calendar'));
878
879        if ($signature['isOwner'] == '1') {
880            $calendarToSchedulables = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('=', 'calendar', $signature['calendar'])));
881
882            $schedulables = array();
883            if (is_array($calendarToSchedulables))
884                foreach ($calendarToSchedulables as $key => $calendarToSchedulable)
885                    $schedulables[] = $calendarToSchedulable['schedulable'];
886
887            if (!empty($schedulables))
888                        Controller::deleteALL(array('concept' => 'schedulable'), null, array('filter' => array('IN', 'id', $schedulables)));
889
890            Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar']));
891               
892                $permissions = Controller::find(array('concept' => 'calendarToPermission'), array('id'), array('filter' => array('=', 'calendar', $signature['calendar'])));
893
894               
895               
896                if($permissions && count($permissions) > 0){
897                        $ids = array();
898                        foreach($permissions as $key => $value)
899                                array_push($ids, $value['id']);
900               
901                        Controller::deleteALL(array('concept' => 'calendarToPermission'), null, array('filter' => array('IN', 'id', $ids)));
902                       
903                }
904               
905               
906        }
907    }
908
909    public function decodeSchedulablettachment(&$uri, &$params, &$criteria, $original) {
910        if (isset($original['URI']['id'])){
911            $schedulableAttachment = Controller::read(array('concept' => 'schedulableToAttachment'), false, array('filter' => array( '=', 'attachment' , $original['URI']['id'] )));
912            $uri['id'] = $schedulableAttachment[0]['id'];
913        }
914    }
915
916    public function deleteAttachmentDependences(&$uri, &$params, &$criteria, $original) {
917        Controller::delete(array('concept' => 'attachment', 'id' => $original['URI']['id']));
918    }
919   
920    public function decodeDeleteCalendarSignatureAlarm(&$uri, &$params, &$criteria, $original) {
921                if ($original['URI']['id'] == '' && isset($original['criteria']['filter'])){
922                        Controller::deleteAll(array('concept' => 'calendarSignatureAlarm'), null,$original['criteria']);
923                        return false;
924                }
925    }
926
927    public function createDefaultSignature(&$uri, &$result, &$criteria, $original) {
928
929        //Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
930        $isValidSignature = false;
931
932        //Veirifica pois o usuário pode ter varias assinaturas mas não ser dona de nenhuma
933        if (count($result) > 0) {
934            foreach ($result as $value) {
935                if (isset($value['isOwner']) && $value['isOwner'] != 0)
936                    $isValidSignature = true;
937            }
938        }
939
940        if (!$isValidSignature &&
941                ( $original['criteria']['filter'][1][0] == '=' &&
942                $original['criteria']['filter'][1][1] == 'user' &&
943                $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id']
944                )) {
945
946            if (Config::module('useCaldav', 'expressoCalendar')) {
947                require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
948
949                $calendario = DAViCalAdapter::findCalendars();
950            }
951
952            if (Config::module('useCaldav', 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) {
953                foreach ($calendario as $i => $v) {
954
955                    $urlA = explode('/', $v->url);
956                    $name = isset($v->displayname) ? $v->displayname : $urlA[(count($urlA) - 2)];
957                    $cal = array('name' => $name,
958                        'description' => isset($v->description) ? $v->description : $name,
959                        'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
960                        'dtstamp' => time() . '000',
961                        'location' => $urlA[(count($urlA) - 3)] . '/' . $urlA[(count($urlA) - 2)]
962                    );
963
964                    $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
965
966
967
968                    $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
969                        'calendar' => $calCreated['id'],
970                        'isOwner' => '1',
971                        'dtstamp' => time() . '000',
972                        'fontColor' => 'FFFFFF',
973                        'backgroundColor' => '3366CC',
974                        'borderColor' => '3366CC',
975                    );
976
977                    $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
978
979
980                    DAViCalAdapter::importCollection($v->url, $calCreated['id']);
981                }
982            } else {
983                //Criaremos uma agenda padrão
984                $cal = array('name' => 'Calendario',
985                    'description' => 'Calendario Padrão',
986                    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
987                    'dtstamp' => time() . '000'
988                );
989
990                $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
991
992                $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
993                    'calendar' => $calCreated['id'],
994                    'isOwner' => '1',
995                    'dtstamp' => time() . '000',
996                    'fontColor' => 'FFFFFF',
997                    'backgroundColor' => '3366CC',
998                    'borderColor' => '3366CC',
999                );
1000
1001                $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
1002            }
1003
1004            $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']);
1005            return false;
1006        }
1007    }
1008
1009    //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal
1010    public function findExternalPaticipants(&$uri, &$result, &$criteria, $original) {
1011        if (Config::me('uidNumber') && !isset($criteria['notExternal'])) {
1012            $newuri['concept'] = 'user';
1013            $newuri['service'] = 'PostgreSQL';
1014
1015            $newCriteria = $original['criteria'];
1016            $valid = true;
1017
1018            $newCriteria['filter'] = array('AND', $newCriteria['filter'], array('=', 'owner', Config::me('uidNumber')));
1019            $externalUsers = Controller::find($newuri, $original['properties'] ? $original['properties'] : null, $newCriteria);
1020
1021            if (is_array($externalUsers)) {
1022                foreach ($externalUsers as $i => $v)
1023                    $externalUsers[$i]['isExternal'] = '1';
1024            }
1025            else
1026                $externalUsers = array();
1027
1028            if (!is_array($result))
1029                $result = array();
1030
1031            return array_merge($result, $externalUsers);
1032        }
1033    }
1034
1035    public function davcalCreateCollection(&$uri, &$params, &$criteria, $original) {
1036        if (Config::module('useCaldav', 'expressoCalendar')) {
1037            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1038            DAViCalAdapter::mkcalendar($params['location'], $params['name'], isset($params['description']) ? $params['description'] : '' );
1039        }
1040    }
1041
1042    public function davcalDeleteCollection(&$uri, &$params, &$criteria, $original) {
1043        if (Config::module('useCaldav', 'expressoCalendar') && Config::module('onRemoveCascadeCalDav')) {
1044            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1045            $calendar = Controller::read($uri);
1046            DAViCalAdapter::rmCalendar($calendar['location']);
1047        }
1048    }
1049
1050    public function davcalUpdateCollection(&$uri, &$params, &$criteria, $original) {
1051        if (Config::module('useCaldav', 'expressoCalendar')) {
1052            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1053            if (isset($params['location'])) {
1054                $calendar = Controller::read($uri);
1055                if ($calendar['location'] !== $params['location'])
1056                    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']);
1057            }
1058        }
1059    }
1060
1061    private static function _makeUid() {
1062
1063        $date = date('Ymd\THisT');
1064        $unique = substr(microtime(), 2, 4);
1065        $base = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890';
1066        $start = 0;
1067        $end = strlen($base) - 1;
1068        $length = 6;
1069        $str = null;
1070        for ($p = 0; $p < $length; $p++)
1071            $unique .= $base{mt_rand($start, $end)};
1072
1073        return $date . $unique . '@expresso-calendar';
1074    }
1075
1076    private function getStatus($id) {
1077        $a = array(
1078            STATUS_CONFIRMED => 'CONFIRMED',
1079            STATUS_CANCELLED => 'CANCELLED',
1080            STATUS_TENATIVE => 'TENATIVE',
1081            STATUS_UNANSWERED => 'NEEDS-ACTION',
1082            STATUS_DELEGATED => 'DELEGATED'
1083        );
1084        return $a[$id];
1085    }
1086
1087    private static function decodeAlarmType($id) {
1088        $a = array(ALARM_ALERT => 'alert',
1089            ALARM_MAIL => 'mail',
1090            ALARM_SMS => 'sms');
1091
1092        return $a[$id];
1093    }
1094
1095    private static function codeAlarmType($type) {
1096        $a = array('alert' => ALARM_ALERT,
1097            'mail' => ALARM_MAIL,
1098            'sms' => ALARM_SMS);
1099
1100        return $a[$type];
1101    }
1102
1103    private static function codeAlarmUnit($u) {
1104        if ($u === 'd')
1105            return 'days';
1106        if ($u === 'm')
1107            return 'minutes';
1108        if ($u === 'H')
1109            return 'hours';
1110    }
1111
1112    private static function ownerSchedulable($id, $me) {
1113
1114        $isOwner = Controller::find(array('concept' => 'participant'), array('id'), array('filter' =>
1115                    array('AND',
1116                        array('=', 'isOrganizer', '1'),
1117                        array('=', 'user', $me),
1118                        array('=', 'schedulable', $id)
1119                        )));
1120
1121        return ( isset($isOwner[0]['id']) ) ? true : false;
1122    }
1123   
1124   
1125    private static function referenceCalendarToObject($schedulable, $calendar) {
1126        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object FROM calendar_to_calendar_object'
1127            . ' WHERE calendar_to_calendar_object.calendar_id = '. $calendar
1128            . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($schedulable));
1129    }
1130   
1131    private static function schedulable2calendarToObject($Schedulable) {
1132        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature'
1133                        . ' WHERE calendar_signature.user_uidnumber = ' . $_SESSION['wallet']['user']['uidNumber']
1134                        //      .' AND calendar_signature.is_owner = 1'
1135                        . ' AND calendar_signature.calendar_id = calendar.id'
1136                        . ' AND calendar_to_calendar_object.calendar_id = calendar.id'
1137                        . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($Schedulable));
1138    }
1139
1140    protected static function isAllowDeleteInCalendar($calendar) {
1141        $f = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'user', Config::me('uidNumber')), array('=', 'calendar', $calendar))));
1142        return (strpos($f[0]['acl'], CALENDAR_ACL_REMOVE) === false) ? false : true;
1143    }
1144
1145}
1146
1147?>
Note: See TracBrowser for help on using the repository browser.