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

Revision 7953, 73.1 KB checked in by acoutinho, 7 years ago (diff)

Ticket #3370 - Corrigido duplicacao de repeticao em compartilhamento de eventos

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