source: trunk/prototype/modules/calendar/interceptors/DBMapping.php @ 6299

Revision 6299, 41.5 KB checked in by acoutinho, 8 years ago (diff)

Ticket #2797 - Agendas sendo assinadas pelo proprio dono

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