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

Revision 7932, 72.2 KB checked in by cristiano, 7 years ago (diff)

Ticket #3364 - Falha ao importar um evento via expresso Mail

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