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

Revision 7405, 63.9 KB checked in by acoutinho, 8 years ago (diff)

Ticket #3122 - Inconsistencias na criacao de grupos, erros sendo apresentado no javaScript

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