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

Revision 7861, 72.1 KB checked in by acoutinho, 9 years ago (diff)

Ticket #3340 - Falha ao alterar o grupo de uma tarefa quando inserido em uma atividade

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