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

Revision 7670, 43.5 KB checked in by cristiano, 11 years ago (diff)

Ticket #3209 - Arrumado codificação dos eventos do calendario

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