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

Revision 7696, 67.2 KB checked in by cristiano, 7 years ago (diff)

Ticket #3260 - Requisição de alarmes de eventos custosa quando existem muitos eventos

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