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

Revision 7980, 76.2 KB checked in by cristiano, 7 years ago (diff)

Ticket #3378 - Importação automatica de eventos nos participantes

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