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

Revision 6945, 53.9 KB checked in by acoutinho, 10 years ago (diff)

Ticket #2966 - Criacao de atividades com suporte a alarmes e anexos

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