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

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

Ticket #3209 - Atualizações de lib e correções de config

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