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

Revision 7795, 70.2 KB checked in by cristiano, 9 years ago (diff)

Ticket #3325 - Melhoria de funcionalidade na API (serviço Postgres)

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