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

Revision 7702, 69.0 KB checked in by acoutinho, 8 years ago (diff)

Ticket #3259 - Otimizar carregamento de eventos no modulo ExpressoCalendar?

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