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

Revision 7170, 63.5 KB checked in by acoutinho, 10 years ago (diff)

Ticket #3070 - Incluir o uid do dono de uma agenda ao pesquisa-la

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