source: branches/2.5/prototype/modules/calendar/interceptors/DBMapping.php @ 7967

Revision 7967, 71.4 KB checked in by douglas, 7 years ago (diff)

Ticket #3372 - Problema com eventos que passem pela data da troca de horário de verão

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                $taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'task', $uri['id']), array('=', 'owner', Config::me('uidNumber'))), 'deepness' => 2));
628                if(!empty($taskToActivity)){
629                    $activity = Controller::read(array('concept' => 'schedulable', 'id' => $taskToActivity[0]['activity']), array('startTime', 'endTime', 'rangeStart', 'rangeEnd', 'allDay'));
630                    $isAllDay = 1;
631
632                    if(!empty($activity)){
633                        $start = $params['startTime'];
634                        $end = $params['endTime'];
635                        foreach($taskToActivity as $t){
636                         if($t['task']['id'] != $params['id']){
637                            $start = $t['task']['startTime'] < $start ? $t['task']['startTime'] : $start;
638                            $end = $t['task']['endTime'] > $end ? $t['task']['endTime'] : $end;
639                            $isAllDay = (($isAllDay == 1) && ($t['task']['allDay'] == '1')) ? 1 : 0;
640                         }
641                        }
642
643                        if($event['allDay'] == '0' || (isset($params['allDay']) && $params['allDay'] == '0'))
644                            $isAllDay = 0;
645
646                        $toUpdate = array();
647
648                        if($start != $activity['startTime'])
649                            $toUpdate['startTime'] = $start;
650
651                        if($end != $activity['endTime']){
652                            $toUpdate['endTime'] = $end;
653                            $toUpdate['due'] = $end;
654                        }
655
656                        if($isAllDay != $activity['allDay'])
657                            $toUpdate['allDay'] = $isAllDay;
658
659                        if(!empty($toUpdate))
660                            Controller::update(array('concept' => 'schedulable', 'id' => $taskToActivity[0]['activity']), $toUpdate);
661                    }
662                }
663            }
664
665            unset($criteria['historic']['endTime']);
666            unset($criteria['historic']['rangeEnd']);
667            unset($criteria['historic']['rangeStart']);
668            unset($criteria['historic']['class']);
669            unset($criteria['historic']['type']);
670            unset($criteria['historic']['allDay']);
671            unset($criteria['historic']['id']);
672        }
673    }
674
675    static function putEvent(&$uri, &$result, &$criteria, $original) {
676        if (Config::module('useCaldav', 'expressoCalendar')) { //Ignorar Put dos eventos ja vindos do caldav
677            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
678
679            $eventID = (isset($result['id'])) ? $result['id'] : $uri['id'];
680            $event = Controller::read(array('concept' => 'schedulable', 'id' => $eventID));
681
682            $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $eventID)));
683
684            if (is_array($participants) && count($participants) > 0)
685                foreach ($participants as $ii => $vv) {
686                    if ($vv['isExternal'] == 1)
687                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
688                    else
689                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
690                }
691
692            $event['URI']['concept'] = 'schedulable';
693            $event['participants'] = $participants;
694
695            $ical = Controller::format(array('service' => 'iCal'), array($event));
696            $calendars = self::schedulable2calendarToObject($original['properties']['id']); //Busca os calendarios do usuario logado que contenham o evento
697            if (is_array($calendars))
698                foreach ($calendars as $calendar)
699                    DAViCalAdapter::putIcal($ical, array('uid' => $event['uid'], 'location' => $calendar['calendar_location']));
700        }
701    }
702
703
704    static function prepareParticipantHistoric(&$uri, &$params, &$criteria, $original){
705       $participant = Controller::read(array('concept' => 'participant', 'id' => $uri['id']));
706       $schedulable = Controller::read(array('concept' => 'schedulable', 'id' => $participant['schedulable']));
707
708
709       if($schedulable['type'] == '2')
710            $criteria['historic']['participant']  = $participant;
711    }
712
713    static function removeParticipantHistoric(&$uri, &$params, &$criteria, $original){
714        if(isset($criteria['historic'])){
715
716            $participant = $criteria['historic']['participant'];
717
718             Controller::create(array('concept' => 'calendarHistoric'),
719                array('schedulable' => $participant['schedulable'],
720                    'user' => Config::me('uidNumber'),
721                    'time' => time() . '000',
722                    'attribute' => 'participant',
723                    'beforeValue' => $participant['user'],
724                    'afterValue' => ''
725                    )
726                );
727
728        }
729
730    }
731
732    static function createParticipantHistoric(&$uri, &$params, &$criteria, $original){
733
734        if(isset($original['properties']) && isset($original['properties']['isOrganizer']) && $original['properties']['isOrganizer'] != '1'){
735            if(!isset($criteria['event'])){
736                $event = Controller::read(array('concept' => 'schedulable', 'id' => $original['properties']['schedulable']));
737                $criteria['event'] = $event;
738            }else
739                $event = $criteria['event'];
740
741            if($event['type'] == '2'){
742                Controller::create(array('concept' => 'calendarHistoric'),
743                    array('schedulable' => $original['properties']['schedulable'],
744                        'user' => Config::me('uidNumber'),
745                        'time' => time() . '000',
746                        'attribute' => 'participant',
747                        'beforeValue' => '',
748                        'afterValue' => $original['properties']['user']
749                        )
750                    );
751            }
752        }
753    }
754
755    static function createHistoric(&$uri, &$result, &$criteria, $original) {
756
757        if(isset($criteria['historic']) && count($criteria['historic'])){
758            $time =  time() . '000';
759
760            foreach($criteria['historic'] as $k => $v){
761                Controller::create(array('concept' => 'calendarHistoric'),
762                    array('schedulable' => $uri['id'],
763                        'user' => Config::me('uidNumber'),
764                        'time' => $time,
765                        'attribute' => $k,
766                        'beforeValue' => $criteria['beforeValue'][$k],
767                        'afterValue' => $v
768                        )
769                    );
770            }
771        }   
772    }
773
774///////////////////////////////////////////////////////////////////////////////////////////////////////////////
775
776    public function verifyCalendarLocation(&$uri, &$params, &$criteria, $original) {
777        if (!isset($params['location']))
778            $params['location'] = Config::me('uid') . '/' . $params['name'];
779    }
780
781    //TODO: Remover apos suporte a ManytoMany na api
782    public function createCalendarToSchedulable(&$uri, &$result, &$criteria, $original) {
783
784        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id']));
785    }
786
787    //TODO: Remover apos suporte a ManytoMany na api
788    public function createTasksToActivity(&$uri, &$result, &$criteria, $original) {
789
790        if(isset($original['properties']['taskToActivity']) && $original['properties']['taskToActivity']){
791
792            foreach($original['properties']['taskToActivity'] as $relational)
793
794                Controller::create(array('concept' => 'taskToActivity'), array('task' => $relational['task'], 'owner' => $relational['owner'], 'activity' => $result['id']));
795
796        }
797    }
798
799    public function removeAttachmentHistoric(&$uri, &$params, &$criteria, $original) {
800
801        if(isset($criteria['historic'])){
802            $attachment = $criteria['historic']['attachment'];
803
804            $attachment['attachment'] = Controller::read(array('concept' => 'attachment', 'id' => $attachment['attachment']), array('name'));
805            Controller::create(array('concept' => 'calendarHistoric'),
806                    array('schedulable' => $attachment['schedulable'],
807                        'user' => Config::me('uidNumber'),
808                        'time' => time() . '000',
809                        'attribute' => 'attachment',
810                        'beforeValue' => $attachment['attachment']['name'],
811                        'afterValue' => ''
812                        )
813                    );
814
815        }
816   
817    }
818
819    public function createAttachmentHistoric(&$uri, &$params, &$criteria, $original) {
820        $event = Controller::read(array('concept' => 'schedulable', 'id' => $original['properties']['schedulable']));
821
822        if($event['type'] == '2'){
823            $attachment = Controller::read(array('concept' => 'attachment', 'id' => $original['properties']['attachment']), array('name'));
824
825            Controller::create(array('concept' => 'calendarHistoric'),
826                array('schedulable' => $original['properties']['schedulable'],
827                    'user' => Config::me('uidNumber'),
828                    'time' => time() . '000',
829                    'attribute' => 'attachment',
830                    'beforeValue' => '',
831                    'afterValue' => $attachment['name']
832                    )
833                );
834
835        }
836    }
837
838    public function deepnessFindCalendarShared(&$uri, &$result, &$criteria, $original) {
839        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != '0' && count($result) > 0) {
840
841            $calendarIds = array();
842            foreach ($result as $value)
843                    $calendarIds[] = $value['calendar'];
844
845            $calendar = Controller::find(array('concept' => 'calendar'), false, array('filter' => array('AND', array('IN', 'id', $calendarIds))));
846
847            if ($calendar && count($calendar) > 0){
848                $newResult = array();
849                        foreach ($calendar as  $value) {
850                            foreach ($result as  $r) {
851
852                                if ($r['calendar'] == $value['id']) {
853                                    $r['calendar'] = $value;
854                                    $newResult[] = $r;
855                                }
856                            }
857                        }
858
859                        foreach ($newResult as &$value) {
860                            if ($value['user'] != 0) {
861                                $value['user'] = Controller::read(array('concept' => 'user', 'id' => $value['user']));
862
863                                if (!$value['user'])
864                                    $value['user'] = Controller::read(array('concept' => 'group', 'id' => $value['user']));
865                            }
866                    $value['owner'] = Controller::read(array('concept' => 'user', 'id' => $value['owner']));
867                        }
868                        $result = $newResult;
869            }else
870                  $result = '';
871        }
872    }
873
874    //TODO: Remover apos suporte a deepness na api
875    public function deepnessFindTask(&$uri, &$result, &$criteria, $original) {
876        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
877           foreach($result as &$value)
878                $value['task'] = Controller::read(array('concept' => 'schedulable', 'id' => $value['task']));
879           
880       
881        return $result;
882    }
883
884    //TODO: Remover apos suporte a deepness na api
885    public function deepnessFindHistoric(&$uri, &$result, &$criteria, $original) {
886        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
887            foreach($result as &$v){
888                $v['user'] = Controller::read(array('concept' => 'user', 'id' => $v['user']));
889
890                if($v['attribute'] == 'participant'){
891                    if($v['beforeValue'] != '')
892                        $v['beforeValue'] = Controller::read(array('concept' => 'user', 'id' => $v['beforeValue']));
893
894                    if($v['afterValue'] != '')
895                        $v['afterValue'] = Controller::read(array('concept' => 'user', 'id' => $v['afterValue']));
896                }
897            }
898        }
899    }
900
901    //TODO: Remover apos suporte a deepness na api
902    public function findDeepnessOne(&$uri, &$params, &$criteria, $original){
903
904        if (isset($criteria['findOne']) && $criteria['findOne'] == '1') {
905
906            $sql = ' SELECT DISTINCT calendar_object.id as id ,calendar_object.cal_uid as "uid", calendar_object.type_id as "type", '
907                .'calendar_object.dtstart as "startTime", calendar_object.summary as "summary", '
908                .'calendar_object.description as "description", calendar_object.dtend as "endTime" , '
909                .'calendar_object.priority as "priority", calendar_object.due as "due", '
910                .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
911                .'calendar_object.location as "location", calendar_object.allday as "allDay", '
912                .'calendar_object.transp as "transparent", calendar_object.class_id as "class", '
913                .'calendar_object.repeat as "repeat", calendar_object.range_start as "rangeStart", '
914                .'calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", '
915                .'calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence", '
916                .'calendar_object.tzid as "timezone" '
917                .'FROM calendar_object '
918                .'WHERE ( calendar_object.id = '. $criteria['schedulable'] .')';
919
920            $params = Controller::service('PostgreSQL')->execResultSql($sql);
921
922            $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
923            return false;
924        }
925
926
927
928    }
929
930    //TODO: Remover apos suporte a deepness na api
931    public function deepnessFindEvent(&$uri, &$result, &$criteria, $original) {
932        if ((isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) ) {
933
934            $date = new DateTime('now', new DateTimeZone('UTC'));
935            $DayLigth = array();
936
937            foreach ($result as $i => $v) {
938
939                $currentTimezone = (isset($v['calendar']) && isset($original['criteria']['timezones'][$v['calendar']])) ? $original['criteria']['timezones'][$v['calendar']] : $v['timezone'];
940
941                $date->setTimestamp((int) ($v['startTime'] / 1000));
942                $date->setTimezone( new DateTimeZone( $v['timezone'] ));
943                $DayLigth['event']['startTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
944
945                $date->setTimezone( new DateTimeZone($currentTimezone));
946                $DayLigth['calendar']['startTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
947
948                $date->setTimestamp((int) ($v['endTime'] / 1000));
949                $date->setTimezone( new DateTimeZone($currentTimezone));
950                $DayLigth['event']['endTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
951
952                if(isset($v['due']) && $v['due'] != '0'){
953                    $date->setTimestamp((int) ($v['due'] / 1000));
954                    $DayLigth['event']['due'] = ($date->getTimestamp() + $date->getOffset()).'000';
955                }else{
956                    $DayLigth['event']['due'] = $v['due'];
957                }
958
959
960                $date->setTimezone( new DateTimeZone($currentTimezone));
961                $DayLigth['calendar']['endTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
962
963
964                $result[$i]['DayLigth'] = $DayLigth;
965
966                if(((int)$v['type']) == 2){
967
968                    $taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'activity', $v['id']), array('=','owner', Config::me('uidNumber'))) , 'deepness' => 2));
969
970                    if($taskToActivity)
971                        $result[$i]['taskToActivity'] = $taskToActivity;
972
973                    $result[$i]['historic'] = Controller::find(array('concept' => 'calendarHistoric'), false, array('filter' => array('=', 'schedulable', $v['id']) , 'deepness' => 2));
974
975                }
976
977                if(isset( $v['occurrences'] ) && count( $v['occurrences'] ) > 0){
978
979                    $date->setTimestamp((int) ($v['startTime'] / 1000));
980                    $date->setTimezone( new DateTimeZone( $v['timezone'] ));
981 
982                    foreach( $result[$i]['occurrences'] as &$o){
983
984                        $o = ($o + $date->getOffset()).'000';
985
986                    }
987                }
988
989                if (isset($v['id'])) {
990                    $data = self::decodeParticipantsEvent($uri, $v, $criteria, $original);
991
992                    $result[$i]['statusAttendees'] = isset($data['statusAttendees']) ? $data['statusAttendees'] : false;
993                    $result[$i]['sizeAttendees'] = isset($data['sizeAttendees']) ? $data['sizeAttendees'] : false;
994                    $result[$i]['participants'] = $data['attendees'];
995
996                    $attachmentRelation = Controller::find(array('concept' => 'schedulableToAttachment'), false, array('filter' => array('=', 'schedulable', $v['id'])));
997                    if (is_array($attachmentRelation)) {
998                    $attachments = array();
999                    foreach ($attachmentRelation as $key => $value)
1000                        if (isset($value['attachment']) || !!$value['attachment'])
1001                        $attachments[$key] = $value['attachment'];
1002                    //Pega os anexos sem source
1003                    $result[$i]['attachments'] = Controller::find(array('concept' => 'attachment'), array('id', 'name', 'type', 'size'), array('filter' => array('IN', 'id', $attachments)));
1004                    }
1005
1006                    $repeat = Controller::find(array('concept' => 'repeat'), false, array('filter' => array('=', 'schedulable', $v['id'])));
1007
1008                    unset($result[$i]['repeat']);
1009
1010                    if (is_array($repeat))
1011                    $result[$i]['repeat'] = $repeat[0];
1012                }
1013            }
1014        }
1015
1016        return $result;
1017    }
1018
1019//TODO: Remover apos suporte a deepness na api
1020    public static function deepnessReadParticipant( &$uri , &$result , &$criteria , $original ){
1021       
1022       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
1023       {
1024            if(isset($result['id']) && isset($result['user']))
1025            {
1026                $result['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result['user'] , 'service' => ( $result['isExternal'] == 1 ? 'PostgreSQL' : 'OpenLDAP' ) ) );
1027
1028                if($result['user']['id'] == Config::me('uidNumber'))
1029                  $result['alarms'] = Controller::find( array( 'concept' => 'alarm' ) , null , array('filter' => array('=', 'participant' ,$result['id'] ) ) );
1030            }
1031       }
1032       
1033     
1034       
1035   }
1036
1037    //TODO: Remover apos suporte a deepness na api
1038    public function deepnessReadEvent( &$uri , &$result , &$criteria , $original ){             
1039   
1040       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
1041       {
1042            if(isset($result['id']))
1043            {
1044                $result['participants'] = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=' ,  'schedulable' ,  $result['id']), 'deepness' => $original['criteria']['deepness'] - 1) );
1045
1046                $repeat =  Controller::find( array( 'concept' => 'repeat' ), false, array( 'filter' => array( '=', 'schedulable', $result['id'] ) ) );
1047
1048                if(is_array($repeat))
1049                    $result['repeat'] = $repeat[0];
1050            }
1051           
1052       }
1053       
1054       if(isset($result['id']) && $result['type'] == '2'){
1055           $result['historic'] =  Controller::find( array( 'concept' => 'calendarHistoric' ), false, array( 'filter' => array( '=', 'schedulable', $result['id'] ) ) );
1056       }
1057   }
1058   
1059    //TODO: Remover apos suporte a deepness na api
1060    public static function deepnessFindParticipant( &$uri , &$result , &$criteria , $original ){
1061       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
1062       {
1063           foreach ($result as $i => &$v)
1064           {
1065                self::deepnessReadParticipant( $uri, $v, $criteria, $original );
1066           }
1067       } 
1068       
1069   }
1070
1071    //TODO: Remover apos suporte a deepness na api
1072    public function deepnessReadCalendarSignature(&$uri, &$result, &$criteria, $original) {
1073
1074        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
1075            if (isset($result['calendar'])) {
1076                $result['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $result['calendar']));
1077                $result['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $result['id'])));
1078            }
1079    }
1080
1081    //TODO: Remover apos suporte a deepness na api
1082    public function deepnessFindCalendarSignature(&$uri, &$result, &$criteria, $original) {
1083
1084        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
1085            foreach ($result as $i => $v) {
1086                if (isset($v['calendar'])) {
1087                    $result[$i]['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $v['calendar']), false, false);
1088                    $result[$i]['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $v['id'])));
1089                    //Caso não seja o dono da agenda retorna o objeto permission com as acls
1090                    if ($result[$i]['isOwner'] == 0) {
1091                        $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'user', Config::me('uidNumber')), 'deepness' => 2)));
1092
1093                        if (!is_array($permission) || !$permission) {
1094
1095                            $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'type', '1')), 'deepness' => 2 ));
1096                        }
1097                        $result[$i]['permission'] = $permission[0];
1098                    }
1099                }
1100                //TODO - Padronizar retorno do deepness
1101
1102        if (isset($v['user']))
1103
1104                    $user = $v['user'];
1105            $result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $v['user']), false, false);
1106            }
1107
1108        if(empty( $result[$i]['user'] ) || count( $result[$i]['user'] ) == 0 ){
1109            $result[$i]['user'] = Controller::read(array( 'concept' => 'group', 'id' => $user) );
1110
1111        }
1112
1113
1114        }
1115    }
1116
1117//Decode Find       
1118//    public function decodeFindConcept(&$uri, &$result, &$criteria, $original) {
1119//      if ($result && is_array($result)) {
1120//          $m = array_flip(self::${$uri['concept'] . 'Map'});
1121//          $new = array();
1122//          foreach ($result as $i => $v)
1123//              $new[$i] = self::parseConcept($result[$i], $m);
1124//
1125//
1126//          $result = $new;
1127//      }
1128//    }
1129
1130    public function addOwner(&$uri, &$params, &$criteria, $original) {
1131        $owner = Controller::read( array( 'concept' => 'calendarSignature' ) , array('user') ,array( 'filter' => array('AND', array('=', 'isOwner'  ,  '1'), array('=', 'calendar', $params['calendar']))));
1132        $params['owner'] = $owner[0]['user'];
1133    }
1134
1135//    public function decodeFindSchedulable(&$uri, &$result, &$criteria, $original) {
1136//      if ($result && is_array($result)) {
1137//          $m = array_flip(self::${$uri['concept'] . 'Map'});
1138//          $m['calendar_id'] = 'calendar';
1139//          $new = array();
1140//          foreach ($result as $i => $v)
1141//              $new[$i] = self::parseConcept($result[$i], $m);
1142//
1143//
1144//          $result = $new;
1145//      }
1146//    }
1147
1148    public function decodeFindAttachment(&$uri, &$result, &$criteria, $original) {
1149        if (isset($result))
1150            foreach ($result as $key => &$value)
1151                $value['source'] = base64_decode($value['source']);
1152    }
1153
1154    public function decodeSignatureAlarmType(&$uri, &$result, &$criteria, $original) {
1155        if (is_array($result))
1156            foreach ($result as &$param)
1157                if (isset($param['type']))
1158                    $param['type'] = self::decodeAlarmType($param['type']);
1159    }
1160
1161/////////////////////////////////////////////////////////////////////////
1162
1163    static function decodeParticipantsEvent( &$uri, $result, &$criteria, $original) {
1164        $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $result['id']) ));
1165
1166        if($participants && ($size = count($participants)) < 100){
1167            if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0){
1168                self::deepnessFindParticipant($uri, $participants, $criteria, $original);
1169                 $participants['attendees'] = $participants;
1170            }
1171           
1172        }else if($participants && ($size = count($participants)) > 100){
1173            $owner = Controller::read( array( 'concept' => 'calendarSignature' ) , false ,array( 'filter' => array('AND', array('=', 'calendar'  ,  $result['calendar']), array('=', 'isOwner', '1'))));
1174            $owner = Controller::read( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('AND', array('=', 'schedulable'  ,  $result['id']), array('=', 'user', $owner[0]['user'])), 'deepness' => 2));
1175
1176            if(is_array($owner))
1177                $owner = $owner[0];
1178
1179            $reference = array_slice($participants, 0, 100);
1180            $organizer = false;
1181            $asOwner = false;
1182
1183            foreach($reference as $r => &$v){
1184                if($v['id'] == $owner['id']){
1185                    $v = $owner;
1186                    $asOwner = true;
1187                    continue;
1188                }
1189
1190                self::deepnessReadParticipant($uri, $v, $criteria, $original);
1191
1192                if($v['isOrganizer'] == "1" )
1193                    $organizer = $v;
1194            }
1195
1196            if(!$organizer){
1197                $organizer = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('AND', array('=', 'schedulable'  ,  $result['id']), array('=', 'isOrganizer', '1')), 'deepness' => 2));
1198
1199                array_push($reference, $organizer[0]);
1200
1201            }else if($organizer && ($organizer['id'] != $owner['id']))
1202                array_merge($reference, $organizer);
1203
1204            if(!$asOwner)
1205                array_push($reference, $owner);
1206
1207            $statusAttendees = array( 'default' => 0, 'accepted' => 0, 'tentative' => 0, 'cancelled' => 0, 'unanswered' => 0, 'delegated' => 0 );
1208            $statusLabels = array( 'default', 'accepted', 'tentative', 'cancelled', 'unanswered', 'delegated' );
1209
1210            foreach($participants as $k => &$p){
1211                if(!$organizer && $p['isOrganizer'] == "1"){
1212                    self::deepnessReadParticipant($uri, $p, $criteria, $original);
1213                    $reference = array_merge($reference, array($p));
1214                }
1215
1216                $statusAttendees[$statusLabels[$p['status']]]++;
1217            }
1218
1219            $participants['statusAttendees'] = $statusAttendees;
1220            $participants['sizeAttendees'] = $size;
1221            $participants['attendees'] = $reference;
1222        }
1223       
1224        return $participants;
1225    }
1226   
1227    static function dayAlarm( &$uri , &$params , &$criteria , $original ) {
1228        if(isset($criteria['filter'][1]) && $criteria['filter'][1] == 'date')
1229        {
1230            $start = $criteria['filter'][2];
1231            $end =  $start + 86400000;
1232            $params = array();
1233
1234            $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 ";
1235
1236            $al = Controller::service('PostgreSQL')->execSql($select);
1237
1238
1239            if(is_array($al))
1240              foreach( $al as $v )
1241                  $params[] = array('schedulable' =>  $v);
1242            else
1243              $params = false;
1244
1245                return false;
1246        }
1247    }
1248   
1249    static private function countMyCalendarsEvent($id, $owner) {
1250                $sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'isOwner', '1'), array('=', 'user', $owner))));
1251                $calendars = array();
1252                foreach ($sig as $val)
1253                        $calendars[] = $val['calendar'];
1254
1255                $return = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('AND', array('IN', 'calendar', $calendars), array('=', 'schedulable', $id))));
1256
1257                return (isset($return[0])) ? count($return) : 0;
1258    }
1259   
1260    public function deleteSchedulable(&$uri, &$params, &$criteria, $original) {
1261
1262        if (Config::module('useCaldav', 'expressoCalendar'))
1263            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1264       
1265        if(isset($criteria['filter']) && $criteria['filter'] && isset($criteria['filter'][1][2])){
1266            $idSchedulable = $criteria['filter'][1][2];
1267                $idCalendar = $criteria['filter'][2][2];
1268            $owner = $criteria['filter'][3][2];
1269
1270            $qtdMyCalendars = self::countMyCalendarsEvent($idSchedulable, $owner);
1271
1272            $link = Controller::read(array('concept' => 'calendarToSchedulable'), false, array('filter' => array('AND', array('=','calendar',$idCalendar), array('=','schedulable',$idSchedulable))));
1273            $link = (is_array($link) && isset($link[0])) ? $link[0] : $link;
1274           
1275            $calendar = Controller::read(array('concept' => 'calendar'), false, array('filter' => array('=','id',$idCalendar)));
1276            $calendar = (is_array($calendar) && isset($calendar[0])) ? $calendar[0] : $calendar;
1277
1278            if($isAttende = !self::ownerSchedulable($idSchedulable, $owner)){
1279                Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link['id']));
1280               
1281                if($qtdMyCalendars <= 1){
1282
1283                    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
1284                        array('AND',
1285                            array('=', 'user', $owner),
1286                            array('=', 'schedulable', $idSchedulable)
1287                        )));
1288
1289                    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
1290                }
1291
1292            }else{
1293                if($qtdMyCalendars > 1 )
1294                    Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link['id']));
1295            }
1296
1297            if (Config::module('useCaldav', 'expressoCalendar'))
1298                    DAViCalAdapter::deleteEvent($idSchedulable, array('location' => $calendar['location']));
1299
1300            if($isAttende || ($qtdMyCalendars > 1))
1301                return false;
1302
1303            $uri['id'] = $idSchedulable;
1304
1305            if(isset($criteria['type']) && $criteria['type'] == '2'){
1306
1307                $tasks = Controller::find(array('concept' => 'taskToActivity'), array('task'), array('filter' => array('=', 'activity', $idSchedulable)));
1308
1309                if(is_array( $tasks ) and count( $tasks ) > 0){
1310                    Controller::delete(array('concept' => 'taskToActivity'), null, array('filter' => array('=', 'activity', $idSchedulable)));
1311                }
1312
1313                if(isset($criteria['removeTaskToActivity']) && $criteria['removeTaskToActivity']){
1314                    if(is_array( $tasks ) and count( $tasks ) > 0){
1315
1316                        $ids = array();
1317                        foreach($tasks as $v){
1318                            $ids[] = $v['task'];
1319                        }
1320
1321                        Controller::delete(array('concept' => 'schedulable'), false, array('filter' => array('IN','id', $ids )));
1322                    }
1323                }
1324            }
1325        }
1326       
1327    }
1328
1329    public function deleteCalendarToPermissionDependences(&$uri, &$params, &$criteria, $original) {
1330        $permission = Controller::read($uri, array('user', 'calendar'));
1331
1332        $calendarSignature = Controller::find(array('concept' => 'calendarSignature'), array('id'), array('filter' => array('AND', array('=', 'calendar', $permission['calendar']), array('=', 'user', $permission['user']), array('=', 'isOwner', '0'))));
1333
1334        if ($calendarSignature)
1335            Controller::delete(array('concept' => 'calendarSignature', 'id' => $calendarSignature[0]['id']));
1336    }
1337
1338    public function deleteCalendarSignatureDependences(&$uri, &$params, &$criteria, $original) {
1339        $signature = Controller::read($uri, array('isOwner', 'calendar'));
1340
1341        if ($signature['isOwner'] == '1') {
1342            $calendarToSchedulables = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('=', 'calendar', $signature['calendar'])));
1343
1344            $schedulables = array();
1345            if (is_array($calendarToSchedulables))
1346                foreach ($calendarToSchedulables as $key => $calendarToSchedulable)
1347                    $schedulables[] = $calendarToSchedulable['schedulable'];
1348
1349            if (!empty($schedulables))
1350                        Controller::deleteALL(array('concept' => 'schedulable'), null, array('filter' => array('IN', 'id', $schedulables)));
1351
1352            Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar']));
1353               
1354                $permissions = Controller::find(array('concept' => 'calendarToPermission'), array('id'), array('filter' => array('=', 'calendar', $signature['calendar'])));
1355
1356               
1357               
1358                if($permissions && count($permissions) > 0){
1359                        $ids = array();
1360                        foreach($permissions as $key => $value)
1361                                array_push($ids, $value['id']);
1362               
1363                        Controller::deleteALL(array('concept' => 'calendarToPermission'), null, array('filter' => array('IN', 'id', $ids)));
1364                       
1365                }
1366               
1367               
1368        }
1369    }
1370
1371    public function decodeSchedulablettachment(&$uri, &$params, &$criteria, $original) {
1372        if (isset($original['URI']['id'])){
1373            $schedulableAttachment = Controller::read(array('concept' => 'schedulableToAttachment'), false, array('filter' => array( '=', 'attachment' , $original['URI']['id'] )));
1374            $uri['id'] = $schedulableAttachment[0]['id'];
1375
1376            $params = $schedulableAttachment[0];
1377
1378            $event = Controller::read(array('concept' => 'schedulable', 'id' => $params['schedulable']));
1379            if($event['type'] == '2')
1380                $criteria['historic']['attachment'] = $schedulableAttachment[0];
1381
1382        }
1383    }
1384
1385    public function deleteAttachmentDependences(&$uri, &$params, &$criteria, $original) {
1386        Controller::delete(array('concept' => 'attachment', 'id' => (isset($params['attachment']) ? $params['attachment'] : $original['URI']['id'])));
1387    }
1388   
1389    public function decodeDeleteCalendarSignatureAlarm(&$uri, &$params, &$criteria, $original) {
1390                if ($original['URI']['id'] == '' && isset($original['criteria']['filter'])){
1391                        Controller::deleteAll(array('concept' => 'calendarSignatureAlarm'), null,$original['criteria']);
1392                        return false;
1393                }
1394    }
1395
1396
1397     public function createDefaultGroup(&$uri, &$result, &$criteria, $original) {
1398        if( $original['criteria']['filter'][1][0] == '=' &&
1399        $original['criteria']['filter'][1][1] == 'user' &&
1400        $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id']){
1401
1402            $existDefaultGroup = false;
1403
1404            foreach($result as $v){
1405                if($v['type'] == 1 && $v['calendar']['type'] == 1)
1406                    $existDefaultGroup = true;
1407            }
1408
1409            if(!$existDefaultGroup){
1410
1411                $cal = array('name' => 'Sem grupo',
1412                    'description' => 'Sem grupo',
1413                    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
1414                    'dtstamp' => time() . '000',
1415                    'type' => '1'
1416                );
1417
1418                $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
1419
1420                $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
1421                    'calendar' => $calCreated['id'],
1422                    'isOwner' => '1',
1423                    'dtstamp' => time() . '000',
1424                    'fontColor' => 'FFFFFF',
1425                    'backgroundColor' => '3366CC',
1426                    'borderColor' => '3366CC',
1427                    'type' => '1'
1428                );
1429
1430                $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
1431                $sigCreated = Controller::read(array('concept' => 'calendarSignature', 'id' => $sigCreated['id']), false, array('deepness' => 2 ));
1432
1433                array_push($result, $sigCreated);
1434            }
1435
1436        }
1437
1438     }
1439
1440    public function createDefaultSignature(&$uri, &$result, &$criteria, $original) {
1441
1442    if(count($result) == 0 && isset($criteria['filter'][3]) && isset($criteria['filter'][3]['isRecursion'])){
1443        throw new Exception('It was not possible to find to calendar!');
1444        return false;
1445    }
1446
1447        //Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
1448        $isValidSignature = false;
1449
1450        //Veirifica pois o usuário pode ter varias assinaturas mas não ser dona de nenhuma
1451        if (count($result) > 0) {
1452            foreach ($result as $value) {
1453                if (isset($value['isOwner']) && $value['isOwner'] != 0 && isset($value['type']) && $value['type'] == 0)
1454                    $isValidSignature = true;
1455            }
1456        }
1457
1458        if (!$isValidSignature &&
1459                ( $original['criteria']['filter'][1][0] == '=' &&
1460                $original['criteria']['filter'][1][1] == 'user' &&
1461                $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id']
1462                )) {
1463
1464            if (Config::module('useCaldav', 'expressoCalendar')) {
1465                require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1466                $calendario = DAViCalAdapter::findCalendars();
1467            }
1468
1469            if (Config::module('useCaldav', 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) {
1470                foreach ($calendario as $i => $v) {
1471
1472                    $urlA = explode('/', $v->url);
1473                    $name = isset($v->displayname) ? $v->displayname : $urlA[(count($urlA) - 2)];
1474                    $cal = array('name' => $name,
1475                        'description' => isset($v->description) ? $v->description : $name,
1476                        'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
1477                        'dtstamp' => time() . '000',
1478                        'location' => $urlA[(count($urlA) - 3)] . '/' . $urlA[(count($urlA) - 2)]
1479                    );
1480
1481                    $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
1482
1483                if(!$calCreated){
1484                    throw new Exception('Error to create calendar');
1485                    return false;
1486                }
1487
1488                    $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
1489                        'calendar' => $calCreated['id'],
1490                        'isOwner' => '1',
1491                        'dtstamp' => time() . '000',
1492                        'fontColor' => 'FFFFFF',
1493                        'backgroundColor' => '3366CC',
1494                        'borderColor' => '3366CC',
1495                    );
1496
1497                    $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
1498
1499                if(!$sigCreated){
1500                    throw new Exception('Error to create signature');
1501                    return false;
1502                }
1503
1504                    DAViCalAdapter::importCollection($v->url, $calCreated['id']);
1505                }
1506            } else {
1507                //Criaremos uma agenda padrão
1508                $cal = array('name' => 'Calendario',
1509                    'description' => 'Calendario Padrão',
1510                    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
1511                    'dtstamp' => time() . '000'
1512                );
1513
1514                $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
1515
1516                $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
1517                    'calendar' => $calCreated['id'],
1518                    'isOwner' => '1',
1519                    'dtstamp' => time() . '000',
1520                    'fontColor' => 'FFFFFF',
1521                    'backgroundColor' => '3366CC',
1522                    'borderColor' => '3366CC',
1523                );
1524
1525                $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
1526        }
1527   
1528        $original['criteria']['filter'][] = array('isRecursion' => true);
1529        $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']);
1530            return false;
1531        }
1532    }
1533
1534    //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal
1535    public function findExternalPaticipants(&$uri, &$result, &$criteria, $original) {
1536        if (Config::me('uidNumber') && !isset($criteria['notExternal'])) {
1537            $newuri['concept'] = 'user';
1538            $newuri['service'] = 'PostgreSQL';
1539
1540            $newCriteria = $original['criteria'];
1541            $valid = true;
1542
1543            $newCriteria['filter'] = array('AND', $newCriteria['filter'], array('=', 'owner', Config::me('uidNumber')));
1544            $externalUsers = Controller::find($newuri, $original['properties'] ? $original['properties'] : null, $newCriteria);
1545
1546            if (is_array($externalUsers)) {
1547                foreach ($externalUsers as $i => $v)
1548                    $externalUsers[$i]['isExternal'] = '1';
1549            }
1550            else
1551                $externalUsers = array();
1552
1553            if (!is_array($result))
1554                $result = array();
1555
1556            return array_merge($result, $externalUsers);
1557        }
1558    }
1559
1560    public function davcalCreateCollection(&$uri, &$params, &$criteria, $original) {
1561        if (Config::module('useCaldav', 'expressoCalendar')) {
1562            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1563            DAViCalAdapter::mkcalendar($params['location'], $params['name'], isset($params['description']) ? $params['description'] : '' );
1564           }
1565    }
1566
1567    public function davcalDeleteCollection(&$uri, &$params, &$criteria, $original) {
1568        if (Config::module('useCaldav', 'expressoCalendar') && Config::module('onRemoveCascadeCalDav')) {
1569            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1570            $calendar = Controller::read($uri);
1571            DAViCalAdapter::rmCalendar($calendar['location']);
1572        }
1573    }
1574
1575    public function davcalUpdateCollection(&$uri, &$params, &$criteria, $original) {
1576        if (Config::module('useCaldav', 'expressoCalendar')) {
1577            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1578            if (isset($params['location'])) {
1579                $calendar = Controller::read($uri);
1580                if ($calendar['location'] !== $params['location'])
1581                    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']);
1582            }
1583        }
1584    }
1585
1586    private static function _makeUid() {
1587
1588        $date = date('Ymd\THisT');
1589        $unique = substr(microtime(), 2, 4);
1590        $base = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890';
1591        $start = 0;
1592        $end = strlen($base) - 1;
1593        $length = 6;
1594        $str = null;
1595        for ($p = 0; $p < $length; ++$p)
1596            $unique .= $base{mt_rand($start, $end)};
1597
1598        return $date . $unique . '@expresso-calendar';
1599    }
1600
1601    private function getStatus($id) {
1602        $a = array(
1603            STATUS_CONFIRMED => 'CONFIRMED',
1604            STATUS_CANCELLED => 'CANCELLED',
1605            STATUS_TENATIVE => 'TENATIVE',
1606            STATUS_UNANSWERED => 'NEEDS-ACTION',
1607            STATUS_DELEGATED => 'DELEGATED'
1608        );
1609        return $a[$id];
1610    }
1611
1612    private static function decodeAlarmType($id) {
1613        $a = array(ALARM_ALERT => 'alert',
1614            ALARM_MAIL => 'mail',
1615            ALARM_SMS => 'sms');
1616
1617        return $a[$id];
1618    }
1619
1620    private static function codeAlarmType($type) {
1621        $a = array('alert' => ALARM_ALERT,
1622            'mail' => ALARM_MAIL,
1623            'sms' => ALARM_SMS);
1624
1625        return $a[$type];
1626    }
1627
1628    private static function codeAlarmUnit($u) {
1629        if ($u === 'd')
1630            return 'days';
1631        if ($u === 'm')
1632            return 'minutes';
1633        if ($u === 'H')
1634            return 'hours';
1635    }
1636
1637    private static function ownerSchedulable($id, $me) {
1638
1639        $isOwner = Controller::find(array('concept' => 'participant'), array('id'), array('filter' =>
1640                    array('AND',
1641                        array('=', 'isOrganizer', '1'),
1642                        array('=', 'user', $me),
1643                        array('=', 'schedulable', $id)
1644                        )));
1645
1646        return ( isset($isOwner[0]['id']) ) ? true : false;
1647    }
1648   
1649   
1650    private static function referenceCalendarToObject($schedulable, $calendar) {
1651        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object FROM calendar_to_calendar_object'
1652            . ' WHERE calendar_to_calendar_object.calendar_id = '. $calendar
1653            . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($schedulable));
1654    }
1655   
1656    private static function schedulable2calendarToObject($Schedulable) {
1657        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'
1658                        . ' WHERE calendar_signature.user_uidnumber = ' . $_SESSION['wallet']['user']['uidNumber']
1659                        //      .' AND calendar_signature.is_owner = 1'
1660                        . ' AND calendar_signature.calendar_id = calendar.id'
1661                        . ' AND calendar_to_calendar_object.calendar_id = calendar.id'
1662                        . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($Schedulable));
1663    }
1664
1665    protected static function isAllowDeleteInCalendar($calendar) {
1666        $f = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'user', Config::me('uidNumber')), array('=', 'calendar', $calendar))));
1667        return (strpos($f[0]['acl'], CALENDAR_ACL_REMOVE) === false) ? false : true;
1668    }
1669
1670    private static function isValidTimeStamp($timestamp)
1671    {
1672        return ((string) (int) $timestamp === $timestamp)
1673            && ($timestamp <= PHP_INT_MAX)
1674            && ($timestamp >= ~PHP_INT_MAX);
1675    }
1676}
1677
1678?>
Note: See TracBrowser for help on using the repository browser.