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

Revision 6977, 60.6 KB checked in by acoutinho, 10 years ago (diff)

Ticket #2966 - Suporte a edicao de tarefas na edicao de tarefas

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