source: trunk/zpush/backend/expresso/providers/calendarProvider.php @ 8023

Revision 8023, 52.0 KB checked in by cristiano, 11 years ago (diff)

Ticket #3393 - Desconsiderar sincronização de agendas compartilhadas no Z-Push

Line 
1<?php
2
3require_once __DIR__ . '/../../../lib/default/diffbackend/diffbackend.php';
4require_once EXPRESSO_PATH . '/prototype/api/controller.php';
5require_once EXPRESSO_PATH . '/prototype/api/config.php';
6require_once EXPRESSO_PATH . '/prototype/modules/calendar/constants.php';
7
8use prototype\api\Config as Config;
9
10class ExpressoCalendarProvider extends BackendDiff
11{
12
13    var $_uidnumber;
14
15    function __construct()
16    {
17
18    }
19
20    /**
21     * Returns a list (array) of folders, each entry being an associative array
22     * with the same entries as StatFolder(). This method should return stable information; ie
23     * if nothing has changed, the items in the array must be exactly the same. The order of
24     * the items within the array is not important though.
25     *
26     * @access protected
27     * @return array/boolean        false if the list could not be retrieved
28     */
29    public function GetFolderList()
30    {
31        $return = array();
32        $criteria = CALENDAR_SYNC_SIGNED_CALENDARS ? array( 'filter' => array( 'AND' , array( '=' , 'type' , '0' ) , array( '=' , 'user' , $this->_uidnumber ))) : array( 'filter' => array ( 'AND'  ,array( '=' , 'isOwner' , '1' ),array( '=' , 'type' , '0' ) , array( '=' , 'user' , $this->_uidnumber )));
33        $sigs = Controller::find(array('concept' => 'calendarSignature'), array( 'id','calendar' ), $criteria);
34
35        if(Request::GetDeviceType()  == 'iPhone')
36        {
37            foreach($sigs as $sig)
38            {
39                $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] ));
40                $tmpSig = array();
41                $tmpSig["id"] = 'calendar'.$sig['id'];
42                $tmpSig["parent"] = 0;
43                $tmpSig["mod"] = $calendar['name'];
44                $return[] = $tmpSig;
45            }
46        }
47        else
48        {
49            $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value','id') , array('filter' => array( 'and' , array('=' , 'name' , 'defaultCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $this->_uidnumber )  )) );
50
51            if(isset($defaultCalendar[0])) //Prioriza agenda default de importação pois o android so sincroniza a primeira agenda.
52            {
53                foreach($sigs as $i => $sig)
54                {
55                    if($sig['calendar'] == $defaultCalendar[0]['value'])
56                    {
57                        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] ));
58                        $tmpSig = array();
59                        $tmpSig["id"] = 'calendar'.$sig['id'];
60                        $tmpSig["parent"] = 0;
61                        $tmpSig["mod"] = $calendar['name'];
62                        $return[] = $tmpSig;
63                    }
64                }
65            }
66            else
67            {
68                $sig = $sigs[0];
69                $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] ));
70                $tmpSig = array();
71                $tmpSig["id"] = 'calendar'.$sig['id'];
72                $tmpSig["parent"] = 0;
73                $tmpSig["mod"] = $calendar['name'];
74                $return[] = $tmpSig;
75
76            }
77        }
78
79        return $return;
80    }
81
82    /**
83     * Returns an actual SyncFolder object with all the properties set. Folders
84     * are pretty simple, having only a type, a name, a parent and a server ID.
85     *
86     * @param string        $id           id of the folder
87     *
88     * @access public
89     * @return object   SyncFolder with information
90     */
91    public function GetFolder($id)
92    {
93        $idNumber = (int)str_replace('calendar' , '' , $id);
94
95        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
96        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
97
98        if(is_array($calendarSignature) && count($calendarSignature) > 0 )
99        {
100            $folder = new SyncFolder();
101            $folder->serverid = $id;
102            $folder->parentid = "0";
103            $folder->displayname = $calendar['name'];
104            $folder->type = SYNC_FOLDER_TYPE_APPOINTMENT;
105            return $folder;
106        }
107
108        return false;
109    }
110
111    /**
112     * Returns folder stats. An associative array with properties is expected.
113     *
114     * @param string        $id             id of the folder
115     *
116     * @access public
117     * @return array
118     *          Associative array(
119     *              string  "id"            The server ID that will be used to identify the folder. It must be unique, and not too long
120     *                                      How long exactly is not known, but try keeping it under 20 chars or so. It must be a string.
121     *              string  "parent"        The server ID of the parent of the folder. Same restrictions as 'id' apply.
122     *              long    "mod"           This is the modification signature. It is any arbitrary string which is constant as long as
123     *                                      the folder has not changed. In practice this means that 'mod' can be equal to the folder name
124     *                                      as this is the only thing that ever changes in folders. (the type is normally constant)
125     *          )
126     */
127    public function StatFolder($id)
128    {
129        $return = array();
130        $idNumber = (int)str_replace('calendar' , '' , $id);
131        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
132        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
133
134        $return["id"] = $id;
135        $return["parent"] = 0;
136        $return["mod"] = $calendar['name'];
137
138        return $return;
139    }
140
141    /**
142     * Creates or modifies a folder
143     *
144     * @param string        $folderid       id of the parent folder
145     * @param string        $oldid          if empty -> new folder created, else folder is to be renamed
146     * @param string        $displayname    new folder name (to be created, or to be renamed to)
147     * @param int           $type           folder type
148     *
149     * @access public
150     * @return boolean                      status
151     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
152     *
153     */
154    public function ChangeFolder($folderid, $oldid, $displayname, $type)
155    {
156        return false;
157
158    }
159
160    /**
161     * Deletes a folder
162     *
163     * @param string        $id
164     * @param string        $parent         is normally false
165     *
166     * @access public
167     * @return boolean                      status - false if e.g. does not exist
168     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
169     */
170    public function DeleteFolder($id, $parentid)
171    {
172        return false;
173    }
174
175    /**
176     * Returns a list (array) of messages, each entry being an associative array
177     * with the same entries as StatMessage(). This method should return stable information; ie
178     * if nothing has changed, the items in the array must be exactly the same. The order of
179     * the items within the array is not important though.
180     *
181     * The $cutoffdate is a date in the past, representing the date since which items should be shown.
182     * This cutoffdate is determined by the user's setting of getting 'Last 3 days' of e-mail, etc. If
183     * the cutoffdate is ignored, the user will not be able to select their own cutoffdate, but all
184     * will work OK apart from that.
185     *
186     * @param string        $folderid       id of the parent folder
187     * @param long          $cutoffdate     timestamp in the past from which on messages should be returned
188     *
189     * @access public
190     * @return array/false                  array with messages or false if folder is not available
191     */
192    public function GetMessageList($folderid, $cutoffdate)
193    {
194        $idNumber = (int)str_replace('calendar' , '' , $folderid);
195        $cal_ids = null;
196        $messages = array();
197
198        $sql = 'SELECT calendar_object.last_update , calendar_object.cal_uid FROM calendar_signature , calendar , calendar_to_calendar_object, calendar_object WHERE calendar_signature.id = '.$idNumber.' AND calendar_signature.calendar_id = calendar.id AND calendar_to_calendar_object.calendar_id = calendar.id AND calendar_to_calendar_object.calendar_object_id = calendar_object.id  AND calendar_object.last_update > '. $cutoffdate . '000';
199
200        $rs = Controller::service('PostgreSQL')->execSql($sql);
201
202        if(is_array($rs))
203        {
204            foreach($rs as $v)
205            {
206                $message = array();
207                $message["id"] = $v['cal_uid'];
208                $message["mod"] = substr($v['last_update'], 0, -3);
209                $message["flags"] = 1; // always 'read'
210                $messages[] = $message;
211            }
212        }
213
214        return $messages;
215    }
216
217    /**
218     * Returns the actual SyncXXX object type. The '$folderid' of parent folder can be used.
219     * Mixing item types returned is illegal and will be blocked by the engine; ie returning an Email object in a
220     * Tasks folder will not do anything. The SyncXXX objects should be filled with as much information as possible,
221     * but at least the subject, body, to, from, etc.
222     *
223     * @param string            $folderid           id of the parent folder
224     * @param string            $id                 id of the message
225     * @param ContentParameters $contentparameters  parameters of the requested message (truncation, mimesupport etc)
226     *
227     * @access public
228     * @return object/false                 false if the message could not be retrieved
229     */
230    public function GetMessage($folderid, $id, $contentparameters)
231    {
232        $idNumber = (int)str_replace('calendar' , '' , $folderid);
233        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
234
235        $schedulable = Controller::find(array('concept' => 'schedulable'), null , array('filter' => array( '=' , 'uid' , $id)));
236        if( is_array($schedulable) && count($schedulable) > 0 )
237
238            $schedulable = $schedulable[0];
239        else
240            return false;
241
242        $message = new SyncAppointment();
243        $message->uid = $id;
244        $message->dtstamp = (int) substr($schedulable['dtstamp'], 0, -3);
245        $message->starttime =  (int) substr($schedulable['startTime'], 0, -3);
246        $message->endtime = (int) substr($schedulable['endTime'], 0, -3);
247        $message->deleted = 0;
248
249        $message->subject = mb_convert_encoding($schedulable['summary'] , 'UTF-8' , 'UTF-8,ISO-8859-1');
250        $message->location =  mb_convert_encoding($schedulable['location'], 'UTF-8' , 'UTF-8,ISO-8859-1');
251
252        if(isset($schedulable['description']) && $schedulable['description'] != "") {
253            $message->body = mb_convert_encoding($schedulable['description'], 'UTF-8' , 'UTF-8,ISO-8859-1');  // phpgw_cal.description
254            $message->bodysize = strlen($message->body);
255            $message->bodytruncated = 0;
256        }
257
258        $message->sensitivity = 0; // 0 - Normal,
259        $message->alldayevent = (int)$schedulable['allDay']; // (0 - Não(default), 1- Sim)
260        $message->timezone = base64_encode($this->_getSyncBlobFromTZ($this->_getGMTTZ()));
261
262
263        /*
264         * Sincronização de participantes e organizador
265         */
266        $participants = Controller::find(array('concept' => 'participant'), null , array('deepness' => 1 , 'filter' => array( '=' , 'schedulable' , $schedulable['id'] )));
267        if(is_array($participants) && count($participants) > 0)
268        {
269            $message->attendees = array();
270            foreach($participants as $participant)
271            {
272                if($participant['isOrganizer'] == 1) //organizador
273                {
274                    $message->organizername = mb_convert_encoding($participant['user']['name'], 'UTF-8' , 'UTF-8,ISO-8859-1');
275                    $message->organizeremail = mb_convert_encoding($participant['user']['mail'], 'UTF-8' , 'UTF-8,ISO-8859-1');
276                }
277                else
278                {
279                    $attendee = new SyncAttendee();
280                    $attendee->name =  mb_convert_encoding($participant['user']['name'], 'UTF-8' , 'UTF-8,ISO-8859-1');
281                    $attendee->email = mb_convert_encoding($participant['user']['mail'], 'UTF-8' , 'UTF-8,ISO-8859-1');
282                    $message->attendees[] = $attendee;
283                }
284
285                if($participant['user']['id'] == $this->_uidnumber  )
286                {
287                    if($participant['isOrganizer'] == 1 || strpos($participant['acl'] ,'w') !== false) // Caso ele seja organizador ou tenha permisão de editar o evento
288                    {
289                        $message->meetingstatus = 0;
290                    }
291                    else
292                    {
293                        $message->meetingstatus = 3;
294                    }
295
296                    if(isset($participant['alarms'][0]) )
297                    {
298                        switch($participant['alarms'][0]['unit'])
299                        {
300                            case 'h':
301                                $mult = 60;
302                                break;
303                            case 'd':
304                                $mult = 3600;
305                                break;
306                            default:
307                                $mult = 1;
308                                break;
309                        }
310
311                        $message->reminder = $participant['alarms'][0]['time'] * $mult;
312                    }
313
314                    switch($participant['status'])
315                    {
316                        case STATUS_ACCEPTED:
317                            $message->busystatus = 2;
318                            break;
319                        case STATUS_TENTATIVE:
320                            $message->busystatus = 1;
321                            break;
322                        case STATUS_DECLINED:
323                            $message->busystatus = 3;
324                            break;
325                        case STATUS_UNANSWERED:
326                            $message->busystatus = 0;
327                            break;
328                    }
329
330                }
331            }
332        }
333        //------------------------------------------------------------------------------------------------------------//
334
335        /*
336        * Sincronização de Recorrência
337        */
338        $repeats = Controller::find(array('concept' => 'repeat'), null , array( 'filter' => array( 'and' , array( '=' , 'schedulable' , $schedulable['id'] ),array( '!=' , 'frequency' , 'none' )  ) ));
339        if(is_array($repeats) && count($repeats) > 0)
340        {
341            $repeat = $repeats[0];
342            $recur = new SyncRecurrence();
343
344            switch($repeat['frequency'])
345            {
346                case 'daily':
347                    $recur->type = 0;
348                    break;
349                case 'weekly':
350                    $recur->type = 1;
351                    break;
352                case 'monthly':
353                    $recur->type = 2;
354                    break;
355                case 'yearly':
356                    $recur->type = 5;
357                    break;
358            }
359
360            if($repeat['endTime'])
361                $recur->until =  (int) substr($repeat['endTime'], 0, -3);
362
363            $recur->interval = $repeat['interval'] ? $repeat['interval'] : 1;
364
365            if($repeat["count"])
366                $recur->occurrences = (int)$repeat["count"];
367
368            if($repeat["byweekno"])
369                $recur->weekofmonth = (int)$repeat["byweekno"];
370
371            if($repeat["bymonthday"])
372                $recur->dayofmonth = (int)$repeat["bymonthday"];
373
374
375            if($repeat["byday"])
376                $recur->dayofweek = $this->formatDoWeek($repeat["byday"]);
377
378            //$recurrence->monthofyear ; //Não implementado no expresso
379
380            $expetions = Controller::find(array('concept' => 'repeatOccurrence'), null , array( 'filter' => array( 'and' , array( '=' , 'exception' , '1' ),array( '=' , 'repeat' , $repeat['id'] ) )));
381            if(is_array($expetions) && count($expetions) > 0)
382            {
383                $message->exceptions = array();
384                foreach($expetions as $expetion)
385                {
386                    $exception = new SyncAppointmentException();
387                    $exception->exceptionstarttime =  (int) substr($expetion['occurrence'], 0, -3);
388                    $exception->deleted = '1';
389                    $message->exceptions[] = $exception;
390                }
391            }
392
393            $message->recurrence = $recur;
394        }
395
396
397        return $message;
398    }
399
400    /**
401     * Returns message stats, analogous to the folder stats from StatFolder().
402     *
403     * @param string        $folderid       id of the folder
404     * @param string        $id             id of the message
405     *
406     * @access public
407     * @return array or boolean if fails
408     *          Associative array(
409     *              string  "id"            Server unique identifier for the message. Again, try to keep this short (under 20 chars)
410     *              int     "flags"         simply '0' for unread, '1' for read
411     *              long    "mod"           This is the modification signature. It is any arbitrary string which is constant as long as
412     *                                      the message has not changed. As soon as this signature changes, the item is assumed to be completely
413     *                                      changed, and will be sent to the PDA as a whole. Normally you can use something like the modification
414     *                                      time for this field, which will change as soon as the contents have changed.
415     *          )
416     */
417    public function StatMessage($folderid, $id)
418    {
419        $sql = 'SELECT last_update , cal_uid FROM calendar_object WHERE cal_uid = \''.pg_escape_string($id) .'\'';
420        $message = array();
421
422        $rs = Controller::service('PostgreSQL')->execSql($sql);
423        if(is_array($rs))
424        {
425            $message["mod"] = substr($rs[0]['last_update'], 0, -3);
426            $message["id"] = $id;
427            $message["flags"] = 1;
428        }
429        return $message;
430    }
431
432    /**
433     * Called when a message has been changed on the mobile. The new message must be saved to disk.
434     * The return value must be whatever would be returned from StatMessage() after the message has been saved.
435     * This way, the 'flags' and the 'mod' properties of the StatMessage() item may change via ChangeMessage().
436     * This method will never be called on E-mail items as it's not 'possible' to change e-mail items. It's only
437     * possible to set them as 'read' or 'unread'.
438     *
439     * @param string        $folderid       id of the folder
440     * @param string        $id             id of the message
441     * @param SyncXXX       $message        the SyncObject containing a message
442     *
443     * @access public
444     * @return array                        same return value as StatMessage()
445     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
446     */
447    public function ChangeMessage($folderid, $idMessage, $message)
448    {
449
450        $idNumber = (int)str_replace('calendar' , '' , $folderid);
451        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
452        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
453
454        if($idMessage)
455        {
456            $schedulable = Controller::find(array('concept' => 'schedulable'), null , array('deepness'=> 2 , 'filter' => array( '=' , 'uid' , $idMessage)));
457            $schedulable = $schedulable[0];
458
459
460            foreach($schedulable['participants'] as $i => $v)
461            {
462                if($v['user']['id'] == $this->_uidnumber )
463                {
464                    if(strpos($v['acl'] ,'w') !== false) //Caso o usuario tenha permissão de editar o evento
465                    {
466                        return  $this->updateEvent($folderid, $idMessage, $message , $calendar ,$schedulable);
467                    }
468                    else
469                    {
470                        $interation = array();
471
472                        if(isset($message->reminder) && $message->reminder > 0)
473                        {
474                            $alarm = array();
475                            $alarmID = mt_rand() . '6(Formatter)';
476                            $alarm['type'] = 'alert';
477                            $alarm['time'] = $message->reminder;
478                            $alarm['unit'] = 'm';
479                            $alarm['participant'] = $v['id'];
480                            $alarm['schedulable'] = $schedulable['id'];
481                            $interation['alarm://' . $alarmID ] = $alarm;
482
483                        }
484
485                        $status  = $this->formatBusy($message->busystatus);
486
487                        if($status == STATUS_DECLINED ) //Caso ele não seja dono do evento e recusou o convite deletar o evento da sua agenda.
488                        {
489                            Controller::deleteAll(array('concept' => 'calendarToSchedulable' ) , false , array('filter' => array('AND', array('=','calendar',$calendarSignature['calendar']), array('=','schedulable',$schedulable['id']))));
490                        }
491
492                        $v['status'] = $status;
493
494                        $interation['participant://' . $v['id'] ] = $v;
495
496                        ob_start();
497                        $args = $interation;
498                        include EXPRESSO_PATH.'/prototype/Sync.php';
499                        ob_end_clean();
500
501                    }
502                }
503            }
504            return $this->StatMessage($folderid, $message->uid);
505        }
506        else
507        {
508            if (!$schedulable = $this->_getSchedulable($message->uid))
509                return  $this->createEvent($folderid, $idMessage, $message ,$calendar);
510            else{
511                $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
512                array('AND',
513                    array('=', 'calendar', $calendar['id']),
514                    array('=', 'schedulable', $schedulable['id'])
515                )));
516
517                if(!$links &&  !isset($links[0]))
518                    Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $calendar['id'], 'schedulable' => $schedulable['id']));
519
520                foreach($schedulable['participants'] as $i => $v)
521                {
522                    if($v['user']['id'] == $this->_uidnumber)
523                    {
524                        Controller::update(array('concept' => 'participant','id' => $v['id']), array('status' => $this->formatBusy($message->busystatus ) ));
525                    }
526                }
527
528                return $this->StatMessage($folderid, $message->uid);
529            }
530        }
531
532    }
533
534    private function _getSchedulable($uid) {
535        $schedulable = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'uid', $uid), 'deepness' => 2));
536        return (isset($schedulable[0])) ? $schedulable[0] : false;
537    }
538
539    private function updateEvent($folderid, $idMessage, $message , $calendar ,$schedulable )
540    {
541
542
543        $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone));
544        $GMT_CEL = -(($tz_CEL["bias"] + $tz_CEL["dstbias"]) * 60);
545
546        $interation = array();
547        $eventID = $schedulable['id'];
548        $schedulable['uid'] = $message->uid;
549        $schedulable['summary'] = $message->subject;
550        $schedulable['location'] = $message->location;
551        $schedulable['class'] = 1;
552
553        /// Eliminana o timezone, enviado pelo ceulular e coloca no timezone do calendario.
554        // o celular não manda o nome do timezone apenas o offset dele dae não tem como saber qual foi o timezone selecionado.
555        $calendarSignatureTimezone = new DateTimeZone($calendar['timezone']) ;
556        $schedulable['startTime'] = (($message->starttime + $GMT_CEL) + ($calendarSignatureTimezone->getOffset(new DateTime('@'.($message->starttime + $GMT_CEL), new DateTimeZone('UTC'))) * -1) ) *1000; //$message->starttime  * 1000;
557        $schedulable['endTime'] = (($message->endtime + $GMT_CEL) + ($calendarSignatureTimezone->getOffset(new DateTime('@'.($message->endtime + $GMT_CEL), new DateTimeZone('UTC')))* -1)) *1000;//$message->endtime  * 1000;
558        $schedulable['timezone'] = $calendar['timezone'];
559
560
561        $sv  = new DateTime('@'.($message->starttime + $GMT_CEL), $calendarSignatureTimezone);
562
563        if($sv->format('I') == 0)
564            $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
565
566        $ev  = new DateTime('@'.($message->endtime + $GMT_CEL), $calendarSignatureTimezone);
567
568        if($ev->format('I') == 0)
569            $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
570
571        $schedulable['allDay'] = $message->alldayevent;
572        $schedulable['description'] = $message->body;
573        $schedulable['dtstamp'] = $message->dtstamp;
574        $schedulable['lastUpdate'] = time() * 1000;
575        $schedulable['type'] = '1';
576
577
578        if(isset($message->recurrence))
579        {
580            $repeatID = isset($schedulable['repeat']) ? $schedulable['repeat']['id'] : mt_rand() . '3(Formatter)';
581
582            $repeat = array();
583            $repeat['schedulable'] = $eventID;
584
585            switch( $message->recurrence->type )
586            {
587                case 0:
588                    $repeat['frequency'] = 'daily';
589                    break;
590                case 1:
591                    $repeat['frequency'] = 'weekly';
592                    break;
593                case 2:
594                    $repeat['frequency'] = 'monthly';
595                    break;
596                case 5:
597                    $repeat['frequency'] = 'yearly';
598                    break;
599            }
600
601            if(isset($message->recurrence->until))
602                $repeat['endTime'] =  $message->recurrence->until  * 1000 ;
603            else
604                $repeat['endTime'] = null;
605
606            $repeat['startTime'] =  $message->starttime * 1000 ;
607
608            $repeat['interval'] =  isset($message->recurrence->interval) ? $message->recurrence->interval : 1;
609
610            if(isset($message->recurrence->occurrences) && $message->recurrence->occurrences > 0)
611                $repeat["count"] = $message->recurrence->occurrences;
612            else
613                $repeat["count"] = 0;
614
615            if(isset($message->recurrence->weekofmonth) && $message->recurrence->weekofmonth > 0)
616                $repeat["byweekno"] =  $message->recurrence->weekofmonth;
617            else
618                $repeat["byweekno"] = 0;
619
620            if(isset($message->recurrence->dayofmonth) && $message->recurrence->dayofmonth > 0)
621                $repeat["bymonthday"] = $message->recurrence->dayofmonth;
622            else
623                $repeat["bymonthday"] = 0;
624
625            $day = $message->recurrence->dayofweek;
626            $day_of_week_array = array();
627            if (($day & 1) > 0) $day_of_week_array[] = 'SU';
628            if (($day & 2) > 0) $day_of_week_array[] = 'MO';
629            if (($day & 4) > 0) $day_of_week_array[] = 'TU';
630            if (($day & 8) > 0) $day_of_week_array[] = 'WE';
631            if (($day & 16) > 0) $day_of_week_array[] = 'TH';
632            if (($day & 32) > 0) $day_of_week_array[] = 'FR';
633            if (($day & 64) > 0) $day_of_week_array[] = 'SA';
634
635            $repeat["byday"] = implode(',' ,$day_of_week_array);
636            $interation['repeat://' . $repeatID] = $repeat;
637
638        }
639        else if (isset($schedulable['repeat']) )
640        {
641            $interation['repeat://'.$schedulable['repeat']['id']] = null;
642        }
643
644        $partForDelete = $schedulable['participants'];
645
646        foreach($partForDelete as $partForDeleteIndice => $partForDeleteValue)
647        {
648            if($partForDeleteValue['isOrganizer'] == '1')
649            {
650                if(isset($message->reminder) && $message->reminder > 0)
651                {
652                    $alarm = array();
653                    $alarmID =  isset($partForDeleteValue['alarms'][0]['id']) ? $partForDeleteValue['alarms'][0]['id'] :  mt_rand() . '6(Formatter)';
654                    $alarm['type'] = 'alert';
655                    $alarm['time'] = $message->reminder;
656                    $alarm['unit'] = 'm';
657
658                    foreach ($interation as $iint => &$vint)
659                    {
660                        if(isset($vint['user']) && $vint['user'] == $this->_uidnumber)
661                        {
662                            $alarm['participant'] = str_replace('participant://', '', $iint);
663                            $vint['alarms'][] = $alarmID;
664                        }
665                    }
666
667                    $alarm['schedulable'] = $eventID;
668                    $interation['alarm://' . $alarmID ] = $alarm;
669
670
671                }
672                else if(isset($partForDeleteValue['alarms'][0]['id']))
673                    $interation['alarm://' . $partForDeleteValue['alarms'][0]['id'] ] = false;
674
675                unset($partForDelete[$partForDeleteIndice]);
676                unset($schedulable['participants'][$partForDeleteIndice]['alarms']);
677            }
678        }
679
680        if(isset($message->attendees)  && count($message->attendees) > 0)
681        {
682
683            foreach($message->attendees as $attendee)
684            {
685
686                if($this->_getParticipantByMail($attendee->email, $schedulable['participants']) === false)
687                {
688                    $participantID = mt_rand() . '2(Formatter)';
689                    $participant = array();
690                    $participant['schedulable'] = $eventID;
691                    $participant['isOrganizer'] = '0';
692                    $participant['acl'] = 'r';
693
694                    /* Verifica se este usuario é um usuario interno do ldap */
695                    $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $attendee->email), array('=', 'mailAlternateAddress', $attendee->email))));
696
697                    $user = null;
698                    if ($intUser && count($intUser) > 0) {
699                        $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
700                        $participant['user'] = $intUser[0]['id'];
701                    } else {
702                        $participant['isExternal'] = 1;
703                        /* Gera um randon id para o contexto formater */
704                        $userID = mt_rand() . '4(Formatter)';
705
706                        $user['mail'] = $attendee->email;
707                        $user['name'] = ( isset($attendee->name) ) ? $attendee->name : '';
708                        $user['participants'] = array($participantID);
709                        $user['isExternal'] = '1';
710                        $participant['user'] = $userID;
711                        $interation['user://' . $userID] = $user;
712                    }
713
714                    $interation['participant://' . $participantID] = $participant;
715                    $schedulable['participants'][] = $participantID;
716                }
717                else
718                    unset($partForDelete[$this->_getParticipantByMail($attendee->email, $schedulable['participants'])]);
719
720            }
721
722        }
723
724        foreach( $partForDelete as $toDelete)
725        {
726            $interation['participant://' . $toDelete['id']] = false;
727            foreach ($schedulable['participants'] as $ipart => $part)
728            {
729                if($part['id'] == $toDelete['id'])
730                {
731                    unset($schedulable['participants'][$ipart]);
732                }
733            }
734
735            $schedulable['participants'] = array_merge($schedulable['participants'] , array());
736
737        }
738
739        foreach($schedulable['participants'] as $i => $v)
740        {
741            if($v['user']['id'] == $this->_uidnumber )
742            {
743                $schedulable['participants'][$i]['status'] = $this->formatBusy($message->busystatus);
744            }
745        }
746
747        unset($schedulable['repeat']);
748
749        $interation['schedulable://' . $eventID] = $schedulable;
750
751        ob_start();
752        $args = $interation;
753        include EXPRESSO_PATH.'/prototype/Sync.php';
754        ob_end_clean();
755
756        return $this->StatMessage($folderid, $message->uid);
757    }
758
759    private function createEvent($folderid, $idMessage, $message , $calendar)
760    {
761        $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone));
762        $GMT_CEL = -(($tz_CEL["bias"] + $tz_CEL["dstbias"]) * 60);
763
764
765        $interation = array();
766        $schedulable = array();
767        $eventID = mt_rand() . '(Formatter)';
768
769        $schedulable['calendar'] = $calendar['id'];
770        $schedulable['uid'] = $message->uid;
771        $schedulable['summary'] = $message->subject;
772        $schedulable['location'] = $message->location;
773        $schedulable['class'] = 1;
774
775
776        /// Eliminana o timezone, enviado pelo ceulular e coloca no timezone do calendario.
777        // o celular não manda o nome do timezone apenas o offset dele dae não tem como saber qual foi o timezone selecionado.
778        $calendarSignatureTimezone = new DateTimeZone($calendar['timezone']) ;
779        $schedulable['startTime'] = (($message->starttime + $GMT_CEL) + ($calendarSignatureTimezone->getOffset(new DateTime('@'.($message->starttime + $GMT_CEL), new DateTimeZone('UTC'))) * -1) ) *1000; //$message->starttime  * 1000;
780        $schedulable['endTime'] = (($message->endtime + $GMT_CEL) + ($calendarSignatureTimezone->getOffset(new DateTime('@'.($message->endtime + $GMT_CEL), new DateTimeZone('UTC')))* -1)) *1000;//$message->endtime  * 1000;
781
782        $sv  = new DateTime('@'.($message->starttime + $GMT_CEL), $calendarSignatureTimezone);
783
784        if($sv->format('I') == 0)
785            $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
786
787        $ev  = new DateTime('@'.($message->endtime + $GMT_CEL), $calendarSignatureTimezone);
788
789        if($ev->format('I') == 0)
790            $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
791
792        $schedulable['timezone'] = $calendar['timezone'];
793
794
795        $schedulable['allDay'] = $message->alldayevent;
796        $schedulable['description'] = $message->body;
797        $schedulable['dtstamp'] = $message->dtstamp;
798        // $schedulable['lastUpdate'] = 0;
799        $schedulable['type'] = '1';
800        $participant = array();
801        $participantID = mt_rand() . '2(Formatter)';
802        $participant['schedulable'] = $eventID;
803        $participant['isOrganizer'] = '1';
804        $participant['acl'] = 'rowi';
805        $participant['status'] = '1';
806
807        if($message->organizeremail)
808        {
809            /* Verifica se este usuario é um usuario interno do ldap */
810            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $message->organizeremail), array('=', 'mailAlternateAddress', $message->organizeremail))));
811
812            $user = null;
813            if ($intUser && count($intUser) > 0) {
814                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
815                $participant['user'] = $intUser[0]['id'];
816            } else {
817                $participant['isExternal'] = 1;
818                /* Gera um randon id para o contexto formater */
819                $userID = mt_rand() . '4(Formatter)';
820
821                $user['mail'] = $message->organizeremail;
822                $user['name'] = ( isset($message->organizername) ) ? $message->organizername : '';
823                $user['participants'] = array($participantID);
824                $user['isExternal'] = '1';
825                $participant['user'] = $userID;
826                $interation['user://' . $userID] = $user;
827            }
828        }
829        else
830        {
831            $participant['isExternal'] = 0;
832            $participant['user'] = $this->_uidnumber;
833            $participant['status'] = $this->formatBusy($message->busystatus);
834        }
835
836        //Caso exista recorrencias
837        if(isset($message->recurrence))
838        {
839            /* Gera um randon id para o contexto formater */
840            $repeatID = mt_rand() . '3(Formatter)';
841
842            $repeat = array();
843            $repeat['schedulable'] = $eventID;
844
845            switch( $message->recurrence->type )
846            {
847                case 0:
848                    $repeat['frequency'] = 'daily';
849                    break;
850                case 1:
851                    $repeat['frequency'] = 'weekly';
852                    break;
853                case 2:
854                    $repeat['frequency'] = 'monthly';
855                    break;
856                case 5:
857                    $repeat['frequency'] = 'yearly';
858                    break;
859            }
860
861            if(isset($message->recurrence->until))
862                $repeat['endTime'] =  $message->recurrence->until  * 1000 ;
863
864            $repeat['startTime'] =  $message->starttime * 1000 ;
865
866            $repeat['interval'] =  isset($message->recurrence->interval) ? $message->recurrence->interval : 1;
867
868            if(isset($message->recurrence->occurrences) && $message->recurrence->occurrences > 0)
869                $repeat["count"] = $message->recurrence->occurrences;
870
871            if(isset($message->recurrence->weekofmonth) && $message->recurrence->weekofmonth > 0)
872                $repeat["byweekno"] =  $message->recurrence->weekofmonth;
873
874            if(isset($message->recurrence->dayofmonth) && $message->recurrence->dayofmonth > 0)
875                $repeat["bymonthday"] = $message->recurrence->dayofmonth;
876
877            $day = $message->recurrence->dayofweek;
878            $day_of_week_array = array();
879            if (($day & 1) > 0) $day_of_week_array[] = 'SU';
880            if (($day & 2) > 0) $day_of_week_array[] = 'MO';
881            if (($day & 4) > 0) $day_of_week_array[] = 'TU';
882            if (($day & 8) > 0) $day_of_week_array[] = 'WE';
883            if (($day & 16) > 0) $day_of_week_array[] = 'TH';
884            if (($day & 32) > 0) $day_of_week_array[] = 'FR';
885            if (($day & 64) > 0) $day_of_week_array[] = 'SA';
886
887            $repeat["byday"] = implode(',' ,$day_of_week_array);
888            $interation['repeat://' . $repeatID] = $repeat;
889
890        }
891
892        $interation['participant://' . $participantID] = $participant;
893        $schedulable['participants'][] = $participantID;
894
895
896        if(isset($message->attendees)  && count($message->attendees) > 0)
897        {
898            foreach($message->attendees as $attendee)
899            {
900                $participantID = mt_rand() . '2(Formatter)';
901                $participant = array();
902                $participant['schedulable'] = $eventID;
903                $participant['isOrganizer'] = '0';
904                $participant['acl'] = 'r';
905
906                /* Verifica se este usuario é um usuario interno do ldap */
907                $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $attendee->email), array('=', 'mailAlternateAddress', $attendee->email))));
908
909                $user = null;
910                if ($intUser && count($intUser) > 0) {
911                    $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
912                    $participant['user'] = $intUser[0]['id'];
913                } else {
914                    $participant['isExternal'] = 1;
915                    /* Gera um randon id para o contexto formater */
916                    $userID = mt_rand() . '4(Formatter)';
917
918                    $user['mail'] = $attendee->email;
919                    $user['name'] = ( isset($attendee->name) ) ? $attendee->name : '';
920                    $user['participants'] = array($participantID);
921                    $user['isExternal'] = '1';
922                    $participant['user'] = $userID;
923                    $interation['user://' . $userID] = $user;
924
925                    if($userID == $this->_uidnumber)
926                    {
927                        $participant['status'] = $this->formatBusy($message->busystatus);
928                    }
929
930                }
931
932                $interation['participant://' . $participantID] = $participant;
933                $schedulable['participants'][] = $participantID;
934
935            }
936
937        }
938
939        if(isset($message->reminder) && $message->reminder > 0)
940        {
941            $alarm = array();
942            $alarmID = mt_rand() . '6(Formatter)';
943            $alarm['type'] = 'alert';
944            $alarm['time'] = $message->reminder;
945            $alarm['unit'] = 'm';
946
947            foreach ($interation as $iint => &$vint)
948            {
949                if(isset($vint['user']) && $vint['user'] == $this->_uidnumber)
950                {
951                    $alarm['participant'] = str_replace('participant://', '', $iint);
952                    $vint['alarms'][] = $alarmID;
953                }
954            }
955
956            $alarm['schedulable'] = $eventID;
957            $interation['alarm://' . $alarmID ] = $alarm;
958
959
960        }
961
962        $interation['schedulable://' . $eventID] = $schedulable;
963
964        ob_start();
965        $args = $interation;
966        include EXPRESSO_PATH.'/prototype/Sync.php';
967        ob_end_clean();
968
969        return $this->StatMessage($folderid, $message->uid);
970    }
971
972
973    /**
974     * Changes the 'read' flag of a message on disk. The $flags
975     * parameter can only be '1' (read) or '0' (unread). After a call to
976     * SetReadFlag(), GetMessageList() should return the message with the
977     * new 'flags' but should not modify the 'mod' parameter. If you do
978     * change 'mod', simply setting the message to 'read' on the mobile will trigger
979     * a full resync of the item from the server.
980     *
981     * @param string        $folderid       id of the folder
982     * @param string        $id             id of the message
983     * @param int           $flags          read flag of the message
984     *
985     * @access public
986     * @return boolean                      status of the operation
987     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
988     */
989    public function SetReadFlag($folderid, $id, $flags)
990    {
991        return true;
992    }
993
994    /**
995     * Called when the user has requested to delete (really delete) a message. Usually
996     * this means just unlinking the file its in or somesuch. After this call has succeeded, a call to
997     * GetMessageList() should no longer list the message. If it does, the message will be re-sent to the mobile
998     * as it will be seen as a 'new' item. This means that if this method is not implemented, it's possible to
999     * delete messages on the PDA, but as soon as a sync is done, the item will be resynched to the mobile
1000     *
1001     * @param string        $folderid       id of the folder
1002     * @param string        $id             id of the message
1003     *
1004     * @access public
1005     * @return boolean                      status of the operation
1006     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1007     */
1008    public function DeleteMessage($folderid, $id)
1009    {
1010
1011        $idNumber = (int)str_replace('calendar' , '' , $folderid);
1012        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
1013        $even = $this->_getSchedulable($id );
1014        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
1015
1016        $link = Controller::read(array('concept' => 'calendarToSchedulable'), false, array('filter' => array('AND', array('=','calendar',$calendarSignature['calendar']), array('=','schedulable',$even['id']))));
1017
1018        $delete = false;
1019        foreach($even['participants'] as $i => $v)
1020        {
1021            if($v['user']['id'] == $this->_uidnumber && $v['user']['isOrganizer']  == '1')
1022            {
1023                $delete = true;
1024            }
1025        }
1026
1027        if( $delete === true)
1028        {
1029            Controller::delete(array('concept' => 'schedulable' , 'id' => $even['id']));
1030        }
1031        else
1032        {
1033            Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link[0]['id']));
1034
1035            foreach($even['participants'] as $i => $v)
1036            {
1037                if($v['user']['id'] == $this->_uidnumber)
1038                {
1039                    Controller::update(array('concept' => 'participant','id' => $v['id']), array('status' => STATUS_CANCELLED ));
1040                }
1041            }
1042
1043        }
1044        return true;
1045    }
1046
1047    /**
1048     * Called when the user moves an item on the PDA from one folder to another. Whatever is needed
1049     * to move the message on disk has to be done here. After this call, StatMessage() and GetMessageList()
1050     * should show the items to have a new parent. This means that it will disappear from GetMessageList()
1051     * of the sourcefolder and the destination folder will show the new message
1052     *
1053     * @param string        $folderid       id of the source folder
1054     * @param string        $id             id of the message
1055     * @param string        $newfolderid    id of the destination folder
1056     *
1057     * @access public
1058     * @return boolean                      status of the operation
1059     * @throws StatusException              could throw specific SYNC_MOVEITEMSSTATUS_* exceptions
1060     */
1061    public function MoveMessage($folderid, $id, $newfolderid)
1062    {
1063        return false;
1064    }
1065
1066    /**
1067     * Authenticates the user
1068     *
1069     * @param string        $username
1070     * @param string        $domain
1071     * @param string        $password
1072     *
1073     * @access public
1074     * @return boolean
1075     * @throws FatalException   e.g. some required libraries are unavailable
1076     */
1077    public function Logon($username, $domain, $password)
1078    {
1079        $ldapConfig = parse_ini_file(EXPRESSO_PATH . '/prototype/config/OpenLDAP.srv' , true );
1080        $ldapConfig =  $ldapConfig['config'];
1081
1082        $sr = ldap_search( $GLOBALS['connections']['ldap'] , $ldapConfig['context'] , "(uid=$username)" , array('uidNumber','uid','mail'), 0 , 1 );
1083        if(!$sr) return false;
1084
1085        $entries = ldap_get_entries( $GLOBALS['connections']['ldap'] , $sr );
1086        $this->_uidnumber = $entries[0]['uidnumber'][0];
1087
1088
1089        //Inicia Variaveis de para API expresso
1090        if(!isset($_SESSION))
1091            session_start();
1092
1093        $userWallet = array();
1094        $userWallet['uidNumber'] = $entries[0]['uidnumber'][0];
1095        $userWallet['uid'] = $entries[0]['uid'][0];
1096        $userWallet['mail'] = $entries[0]['mail'][0];
1097
1098        $_SESSION['wallet'] = array();
1099        $_SESSION['wallet']['user'] = $userWallet;
1100        $_SESSION['flags']['currentapp'] = 'expressoCalendar';
1101
1102        //----------------------------------------------------------------------------------------//
1103
1104        return true;
1105    }
1106
1107    /**
1108     * Logs off
1109     * non critical operations closing the session should be done here
1110     *
1111     * @access public
1112     * @return boolean
1113     */
1114    public function Logoff()
1115    {
1116
1117    }
1118
1119    /**
1120     * Sends an e-mail
1121     * This messages needs to be saved into the 'sent items' folder
1122     *
1123     * Basically two things can be done
1124     *      1) Send the message to an SMTP server as-is
1125     *      2) Parse the message, and send it some other way
1126     *
1127     * @param SyncSendMail        $sm         SyncSendMail object
1128     *
1129     * @access public
1130     * @return boolean
1131     * @throws StatusException
1132     */
1133    public function SendMail($sm)
1134    {
1135        return false;
1136    }
1137
1138    /**
1139     * Returns the waste basket
1140     *
1141     * The waste basked is used when deleting items; if this function returns a valid folder ID,
1142     * then all deletes are handled as moves and are sent to the backend as a move.
1143     * If it returns FALSE, then deletes are handled as real deletes
1144     *
1145     * @access public
1146     * @return string
1147     */
1148    public function GetWasteBasket()
1149    {
1150        return false;
1151    }
1152
1153    /**
1154     * Returns the content of the named attachment as stream. The passed attachment identifier is
1155     * the exact string that is returned in the 'AttName' property of an SyncAttachment.
1156     * Any information necessary to locate the attachment must be encoded in that 'attname' property.
1157     * Data is written directly - 'print $data;'
1158     *
1159     * @param string        $attname
1160     *
1161     * @access public
1162     * @return SyncItemOperationsAttachment
1163     * @throws StatusException
1164     */
1165    public function GetAttachmentData($attname)
1166    {
1167        return false;
1168    }
1169
1170    function _getGMTTZ() {
1171        //$tz = array("bias" => 0, "stdbias" => 0, "dstbias" => 0, "dstendyear" => 0, "dstendmonth" => 2, "dstendday" => 0, "dstendweek" => 2, "dstendhour" => 2, "dstendminute" => 0, "dstendsecond" => 0, "dstendmillis" => 0,
1172        //"dststartyear" => 0, "dststartmonth" =>10, "dststartday" =>0, "dststartweek" => 3, "dststarthour" => 2, "dststartminute" => 0, "dststartsecond" => 0, "dststartmillis" => 0);
1173        $tz = array("bias" => 120, "stdbias" => 0, "dstbias" => -60, "dstendyear" => 0, "dstendmonth" => 2, "dstendday" => 0, "dstendweek" => 2, "dstendhour" => 2, "dstendminute" => 0, "dstendsecond" => 0, "dstendmillis" => 0, "dststartyear" => 0, "dststartmonth" =>10, "dststartday" =>0, "dststartweek" => 3, "dststarthour" => 2, "dststartminute" => 0, "dststartsecond" => 0, "dststartmillis" => 0);
1174
1175        return $tz;
1176    }
1177    function _getSyncBlobFromTZ($tz) {
1178        $packed = pack("la64vvvvvvvv" . "la64vvvvvvvv" . "l",
1179            $tz["bias"], "", 0, $tz["dstendmonth"], $tz["dstendday"], $tz["dstendweek"], $tz["dstendhour"], $tz["dstendminute"], $tz["dstendsecond"], $tz["dstendmillis"],
1180            $tz["stdbias"], "", 0, $tz["dststartmonth"], $tz["dststartday"], $tz["dststartweek"], $tz["dststarthour"], $tz["dststartminute"], $tz["dststartsecond"], $tz["dststartmillis"],
1181            $tz["dstbias"]);
1182
1183        return $packed;
1184    }
1185
1186    function _getTZFromSyncBlob($data) {
1187        $tz = unpack(    "lbias/a64name/vdstendyear/vdstendmonth/vdstendday/vdstendweek/vdstendhour/vdstendminute/vdstendsecond/vdstendmillis/" .
1188            "lstdbias/a64name/vdststartyear/vdststartmonth/vdststartday/vdststartweek/vdststarthour/vdststartminute/vdststartsecond/vdststartmillis/" .
1189            "ldstbias", $data);
1190
1191        // Make the structure compatible with class.recurrence.php
1192        $tz["timezone"] = $tz["bias"];
1193        $tz["timezonedst"] = $tz["dstbias"];
1194
1195        return $tz;
1196    }
1197
1198    private function formatDoWeek($week)
1199    {
1200        $recday = explode(',' , $week);
1201        $nday = 0;
1202        foreach ($recday as $day)
1203        {
1204            switch($day)
1205            {
1206                case 'SU':
1207                    $nday=$nday +1;
1208                    break;
1209                case 'MO':
1210                    $nday=$nday +2;
1211                    break;
1212                case 'TU':
1213                    $nday=$nday +4;
1214                    break;
1215                case 'WE':
1216                    $nday=$nday +8;
1217                    break;
1218                case 'TH':
1219                    $nday=$nday +16;
1220                    break;
1221                case 'FR':
1222                    $nday=$nday +32;
1223                    break;
1224                case 'SA':
1225                    $nday=$nday +64;
1226                    break;
1227
1228            }
1229        }
1230        return $nday;
1231    }
1232
1233    private function _getParticipantByMail($mail, &$participants, $isFull = false) {
1234        if ($participants && $participants != '')
1235            foreach ($participants as $i => $v)
1236                if ((is_array($v) && isset($v['user'])) && ($v['user']['mail'] == $mail || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress']))))
1237                    return $i;
1238        return false;
1239    }
1240
1241    private function _getParticipantIDByMail($mail, &$participants, $isFull = false) {
1242        if ($participants && $participants != '')
1243            foreach ($participants as $i => $v)
1244                if ((is_array($v) && isset($v['user'])) && ($v['user']['mail'] == $mail || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress']))))
1245                    return !!$isFull ? $v : $v['id'];
1246        return false;
1247    }
1248
1249
1250    private function formatBusy($status)
1251    {
1252        switch($status)
1253        {
1254            case 2:
1255                return STATUS_ACCEPTED;
1256                break;
1257            case 1:
1258                return STATUS_TENTATIVE;
1259                break;
1260            case 3:
1261                return STATUS_DECLINED;
1262                break;
1263            case 0:
1264                return STATUS_UNANSWERED;
1265                break;
1266        }
1267    }
1268
1269
1270
1271}
Note: See TracBrowser for help on using the repository browser.