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

Revision 6160, 39.4 KB checked in by acoutinho, 9 years ago (diff)

Ticket #2714 - Inconsistencia na query de busca de repeticoes

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