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

Revision 6968, 59.0 KB checked in by acoutinho, 10 years ago (diff)

Ticket #2966 - Criado suporte a historico em atividades

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