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

Revision 6876, 49.1 KB checked in by acoutinho, 10 years ago (diff)

Ticket #2966 - Criacao e edicao de tarefas / suporte a anexos, alarmes, participantes e mapa de disponibilidade

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