source: contrib/z-push/backend/BackendCalendarExpresso.php @ 4219

Revision 4219, 54.5 KB checked in by emersonfaria, 13 years ago (diff)

Ticket #1829 - Criado trace detalhado filtrado por usuario e backend

  • Property svn:executable set to *
Line 
1<?php
2/***********************************************
3 * File      :   BackendCalendarExpresso.php
4 * Project   :   Z-Push
5 * Descr     :   This Calendar Backend is for Expresso Groupware.
6 *
7 * Created   :   06.12.2010 - emerson-faria.nobre@serpro.gov.br
8 *
9 * ï¿œ Zarafa Deutschland GmbH, www.zarafaserver.de
10 * This file is distributed under GPL v2.
11 * Consult LICENSE file for details
12 ************************************************/
13require_once("diffbackend.php");
14require_once("include/z_RTF.php");
15require_once("include/dbconnect.php");
16require_once("include/authldap.php");
17
18class BackendCalendarExpresso extends BackendDiff {
19        var $db;
20        var $_uidnumber;
21
22        function __construct()
23        {
24                $this->db = dbconnect();
25
26                if (!$this->db) {
27                        echo "Erro de conexao com o banco.\n";
28                        exit;
29                }
30        }
31
32        function Logon($username, $domain, $password) {
33                $this->_uidnumber = $this->authUser($this->parseUser($username), $password);
34                if(! $this->_uidnumber) return false;
35                else return true;
36        }
37
38        function Setup($user, $devid, $protocolversion) {
39                $this->_user = $user;
40                $this->_devid = $devid;
41                $this->_protocolversion = $protocolversion;
42                return true;
43        }
44
45        function SendMail($rfc822, $forward = false, $reply = false, $parent = false) {
46                return false;
47        }
48
49        function GetWasteBasket() {
50                return false;
51        }
52
53        function GetMessageList($folderid, $cutoffdate) {
54                debugLog('CalendarExpresso::GetMessageList('.$this->_uidnumber.', '.$cutoffdate.')');
55                if (TRACE_UID !== false and $cutoffdate !== 0  and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> Filtra eventos com data maior que cutoffdate: '.date("d/m/Y G:i:s",$cutoffdate).', cutoffdate_timestamp: '.$cutoffdate);
56                if ($folderid != "calendar") return false;
57
58                $cal_ids = null;
59                $messages = array();
60                try {
61                        $result = pg_query($this->db,"BEGIN;");
62                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
63                        if ($cutoffdate == 0) $result = pg_query($this->db, "select c.cal_id, c.last_update, c.datetime, c.cal_type, c.title from phpgw_cal c join phpgw_cal_user u on (c.cal_id = u.cal_id) where u.cal_login ='" . $this->_uidnumber . "'and c.reference = 0;");
64                        else $result = pg_query($this->db, "select c.cal_id, c.last_update, c.datetime, c.cal_type, c.title from phpgw_cal c join phpgw_cal_user u on (c.cal_id = u.cal_id) where u.cal_login ='" . $this->_uidnumber . "'and c.reference = 0 and c.edatetime > " . $cutoffdate . ";");
65                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
66                        while ($row = pg_fetch_row($result)) {
67                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> Lê item do BD (cal_id: '.$row[0].', title: '.$row[4].', last_update: '.date("d/m/Y G:i:s",substr($row[1], 0, strlen($row[1])-3)).', last_update_timestamp: '.$row[1].', datetime: '.date("d/m/Y G:i:s",$row[2]).', datetime_timestamp: '.$row[2].', cal_type: '.$row[3].')');
68                                $result_recur = pg_query($this->db,"select recur_enddate from phpgw_cal_repeats where cal_id = " . $row[0] . ";");
69                                if ($result_recur == FALSE) throw new Exception(pg_last_error($this->db));
70                                if ($row[3] == 'M') {
71                                        if ($recur_enddate = pg_fetch_result($result_recur, 0, 0)) {
72                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> Evento '.$row[0].' é recorrente: recur_enddate : '.date("d/m/Y G:i:s",$recur_enddate).', recur_enddate_timestamp: '.$recur_enddate);
73                                                if ($recur_enddate < $row[2]) {
74                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> ERRO: Esse evento não será adicionado na lista porque o campo phpgw_cal_repeats.recur_enddate é menor que o campo phpgw_cal.datetime. Corrija o valor de um dos campos');
75                                                        continue; // Nao sincroniza este evento, porque a data final da recorrencia eh menor que a data inicial do evento. Eh o BD do Expresso que esta inconsistente.
76                                                }
77                                        }
78                                }
79                                $LatestUpdate = $row[1];
80                                $message = array();
81                                $message["id"] = $row[0];
82                                $message["mod"] = substr($LatestUpdate, 0, strlen($LatestUpdate)-3);
83                                $message["flags"] = 1; // always 'read'
84                                $messages[] = $message;
85                                if ($cal_ids === null) $cal_ids = $row[0];
86                                else $cal_ids = $cal_ids . ',' . $row[0];
87                        }
88                        // Eventos com reference invalidos
89                        if ($cutoffdate == 0) $result_invalid_ref = pg_query($this->db, "select c.cal_id, c.last_update, c.datetime, c.cal_type, c.title, c.reference from phpgw_cal c join phpgw_cal_user u on (c.cal_id = u.cal_id) where u.cal_login ='" . $this->_uidnumber . "'and c.reference <> 0 and c.reference not in(".$cal_ids.");");
90                        else $result_invalid_ref = pg_query($this->db, "select c.cal_id, c.last_update, c.datetime, c.cal_type, c.title, c.reference from phpgw_cal c join phpgw_cal_user u on (c.cal_id = u.cal_id) where u.cal_login ='" . $this->_uidnumber . "'and c.reference <> 0 and c.reference not in(".$cal_ids.") and c.datetime > ". $cutoffdate .";");
91                        if ($result_invalid_ref == FALSE) throw new Exception(pg_last_error($this->db));
92                        while ($row_invalid_ref = pg_fetch_row($result_invalid_ref)) {
93                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> ERRO: Evento com campo reference inválido (cal_id: '.$row_invalid_ref[0].', title: '.$row_invalid_ref[4].', reference: '.$row_invalid_ref[5].', last_update: '.date("d/m/Y G:i:s",substr($row_invalid_ref[1], 0, strlen($row[1])-3)).', last_update_timestamp: '.$row_invalid_ref[1].', datetime: '.date("d/m/Y G:i:s",$row_invalid_ref[2]).', datetime_timestamp: '.$row_invalid_ref[2].', cal_type: '.$row_invalid_ref[3].')');
94                        }
95                        // Evento fora da faixa filtrada
96                        if ($cutoffdate !== 0) {
97                                $result_out_cutoffdate = pg_query($this->db, "select c.cal_id, c.datetime, c.cal_type, c.title, c.reference from phpgw_cal c join phpgw_cal_user u on (c.cal_id = u.cal_id) where u.cal_login ='" . $this->_uidnumber . "'and c.datetime <= ". $cutoffdate .";");
98                                if ($result_out_cutoffdate == FALSE) throw new Exception(pg_last_error($this->db));
99                                while ($row_out_cutoffdate = pg_fetch_row($result_out_cutoffdate)) {
100                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> INFORMACAO: Evento com campo datetime fora da faixa filtrada (cal_id: '.$row_out_cutoffdate[0].', title: '.$row_out_cutoffdate[3].', reference: '.$row_out_cutoffdate[4].', datetime: '.date("d/m/Y G:i:s",$row_out_cutoffdate[1]).', datetime_timestamp: '.$row_out_cutoffdate[1].', cal_type: '.$row_out_cutoffdate[2].')');
101                                }
102                        }
103                        $result = pg_query($this->db,"COMMIT;");
104                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
105                } catch (Exception $e) {
106                        pg_query($this->db,"ROLLBACK;");
107                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
108                }
109                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> Fim normal da função');
110                return $messages;
111        }
112
113        function GetFolderList() {
114                debugLog('CalendarExpresso::GetFolderList()');
115                $folder = $this->StatFolder("calendar");
116                return $folder;
117        }
118
119        function GetFolder($id) {
120                debugLog('CalendarExpresso::GetFolder('.$id.')');
121                if($id == "calendar") {
122                        $folder = new SyncFolder();
123                        $folder->serverid = $id;
124                        $folder->parentid = "0";
125                        $folder->displayname = "Calendario";
126                        $folder->type = SYNC_FOLDER_TYPE_APPOINTMENT;
127                        return $folder;
128                } else return false;
129        }
130
131        function StatFolder($id) {
132                debugLog('CalendarExpresso::StatFolder('.$id.')');
133                $folder = $this->GetFolder($id);
134                $stat = array();
135                $stat["id"] = $id;
136                $stat["parent"] = $folder->parentid;
137                $stat["mod"] = $folder->displayname;
138                return $stat;
139        }
140
141        function GetAttachmentData($attname) {
142                return false;
143        }
144
145        function StatMessage($folderid, $id) {
146                debugLog('CalendarExpresso::StatMessage('.$folderid.', '.$id.')');
147                if($folderid != "calendar") return false;
148                try {
149                 $result = pg_query($this->db,"BEGIN;");
150                 if ($result == FALSE) throw new Exception(pg_last_error($this->db));
151                 $result_calendar = pg_query($this->db, "select last_update from phpgw_cal where cal_id = " . $id . ";");
152                 if ($result_calendar == FALSE) throw new Exception(pg_last_error($this->db));
153                 while ($row_calendar = pg_fetch_row($result_calendar)) {
154                        if(isset($row_calendar[0])) {
155                                $message = array();
156                                $message["mod"] = substr($row_calendar[0], 0, strlen($row_calendar[0])-3);
157                                $message["id"] = $id;
158                                $message["flags"] = 1;
159                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::StatMessage-> mod: '.$message["mod"].', id: '.$message["id"]);
160                                return $message;
161                        }
162                 }
163                 $result = pg_query($this->db,"COMMIT;");
164                 if ($result == FALSE) throw new Exception(pg_last_error($this->db));
165                } catch (Exception $e) {
166                        pg_query($this->db,"ROLLBACK;");
167                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
168                }
169                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::StatMessage: ERRO: Não encontrou valor para o campo last_update para esse evento.');
170                return false;
171        }
172
173        function GetMessageDAO($id) {
174                debugLog('CalendarExpresso::GetMessageDAO('.$id.', ..)');
175                if(trim($id == "")) return false;
176                $message = new SyncAppointment();
177                try {
178                        $has_parent_event = false;
179                        $result = pg_query($this->db,"BEGIN;");
180                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
181                        //Evento
182                        $result = pg_query($this->db,"select config_value from phpgw_config WHERE config_name = 'hostname' AND config_app = 'phpgwapi';");
183                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
184                        $uid = "-@" . pg_fetch_result($result, 0, 0) . "-" . $id;
185                        $result = pg_query($this->db, "select cal_id, title, location, mdatetime, datetime, edatetime, description, reference, is_public, category from phpgw_cal where cal_id = " . $id . ";");
186                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
187                        if ($row = pg_fetch_row($result)) {
188                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO-> Lê evento do DB para enviar para o celular (cal_id: '.$row[0].', title:'.$row[1].', location: '.$row[2].', mdatetime: '.$row[3].', datetime: '.$row[4].', edatetime: '.$row[5].', reference: '.$row[7].', isPublic: '.$row[8].')');
189                                if ($row[7] != 0) $has_parent_event = true;
190                                else $has_parent_event = false;
191                                if (!$has_parent_event) {
192                                        $message->fileas = $id;
193                                        $message->uid = utf8_encode($uid);
194                                        if(isset($row[3])) {
195                                                $tz = date_default_timezone_get();
196                                                date_default_timezone_set('UTC');
197                                                $message->dtstamp = $row[3]; // phpgw_cal.mdatetime
198                                                date_default_timezone_set($tz);
199                                        }
200                                        if(isset($row[4])) {
201                                                $tz = date_default_timezone_get();
202                                                date_default_timezone_set('UTC');
203                                                $message->starttime =  $row[4]; // phpgw_cal.datetime
204                                                date_default_timezone_set($tz);
205                                        }
206                                        if(isset($row[5])) {
207                                                $tz = date_default_timezone_get();
208                                                date_default_timezone_set('UTC');
209                                                $message->endtime = $row[5]; // phpgw_cal.edatetime
210                                                date_default_timezone_set($tz);
211                                        }
212                                }
213                                if ($has_parent_event) {
214                                        $message->exceptionstarttime = $row[4];
215                                        $message->deleted = 0;
216                                }
217                                if(isset($row[1])) {
218                                        $message->subject = utf8_encode($row[1]); // phpgw_cal.title
219                                }
220                                if(isset($row[2])) {
221                                        $message->location = utf8_encode($row[2]); // phpgw_cal.location
222                                }
223                                if(isset($row[6]) and $row[6] != "") {
224                                        $message->body = utf8_encode(str_replace('\\n', chr(13) . chr(10), $this->escape($row[6]))); // phpgw_cal.description
225                                        $message->bodysize = strlen($message->body);
226                                        $message->bodytruncated = 0;
227                                }
228                                if (isset($row[8]) and $row[8] == 1) $message->sensitivity = 0; // 0 - Normal
229                                else $message->sensitivity = 2; // 2 - Privado
230                                if (isset($row[9]) and $row[9] != "") {
231                                        $result = pg_query($this->db,"select cat_name from phpgw_categories WHERE cat_id in(" . $row[9] . ");");
232                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
233                                        while ($cat_name = pg_fetch_row($result)) {
234                                                if (!isset($message->categories)) $message->categories = array();
235                                                array_push($message->categories, utf8_encode($cat_name[0]));
236                                        }
237                                }
238                                $message->alldayevent = 0; // (0 - Não(default), 1- Sim)
239                                $message->busystatus = 2; // 2 - Ocupado
240                                //TODO: Tratar $message - timezone
241                                //$tz = $this->_getGMTTZ();
242                                $tz = array("bias" => 180, "stdbias" => 0, "dstbias" => -60, "dstendyear" => 0, "dstendmonth" => 2, "dstendday" => 0, "dstendweek" => 2, "dstendhour" => 2, "dstendminute" => 0, "dstendsecond" => 0, "dstendmillis" => 0,
243                                                      "dststartyear" => 0, "dststartmonth" =>10, "dststartday" =>0, "dststartweek" => 3, "dststarthour" => 2, "dststartminute" => 0, "dststartsecond" => 0, "dststartmillis" => 0);
244                                $message->timezone = base64_encode($this->_getSyncBlobFromTZ($tz));
245                                //TODO: Se necessario, tratar $message - meetingstatus
246                                //TODO: Se necessario, tratar AppointmentReplyTime e ResponseType
247                        }
248
249                        //Alarme do Evento - O alarme nao sera sincronizado por enquanto.
250                        /* Esse exemplo sincroniza o alarme mais distante do evento com o dispositivo movel
251                        * $result = pg_query("select data from phpgw_async where id like 'cal:" . $id . ":%' and data like '%enabled%' order by next desc;");
252                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
253                        if ($data = pg_fetch_result($result, 0, 0)) {
254                        $array_data = unserialize($data);
255                        $offset = $array_data["offset"];
256                        if (isset($array_data["offset"])) {
257                        if ($offset >= 60) $message->reminder = intval($offset / 60);
258                        else $message->reminder = 0;
259                        }
260                        }*/
261                        if (!$has_parent_event) {
262                                //Recorrencia do evento
263                                //TODO: Implementar recorrencia mensal por dia e anual por dia, recur - type 3 e 6 respectivamente. O Expresso ainda nao suporta isso. :(
264                                $result = pg_query($this->db,"select recur_type, recur_use_end, recur_enddate, recur_interval, recur_data, recur_exception from phpgw_cal_repeats where cal_id = " . $id . "and recur_type in (1,2,3,5);");
265                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
266                                if ($row = pg_fetch_row($result)){
267                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO-> Lê recorrência do evento (recur_type: '.$row[0].', recur_use_end: '.$row[1].', recur_enddate: '.$row[2].', recur_interval: '.$row[3].', recur_data: '.$row[4].', recur_exception: '.$row[5].')');
268                                        $recur = new SyncRecurrence();
269                                        // Converte os tipos do Expresso para os tipos do Protocolo ActiveSync
270                                        switch ($row[0]) {
271                                                case 1: //repeticao diaria
272                                                        $recur->type = 0;
273                                                        break;
274                                                case 2: //repeticao semanal
275                                                        $recur->type = 1;
276                                                        break;
277                                                case 3: //repeticao mensal por data
278                                                        $recur->type = 2;
279                                                        break;
280                                                case 5: //repeticao anual por data
281                                                        $recur->type = 5;
282                                                        break;
283                                        }
284                                        if (isset($row[2])) {
285                                                $tz = date_default_timezone_get();
286                                                date_default_timezone_set('UTC');
287                                                $recur->until = $row[2];
288                                                date_default_timezone_set($tz);
289                                        }
290                                        if (isset($row[3]) and $row[3] != 0) $recur->interval = $row[3];
291                                        else $recur->interval = 1;
292                                        //TODO: Se o Expresso estiver utilizando o campo phpgw_cal_repeats.recur_use_end, implementar.
293                                        if ($recur->type == 1 or $recur->type == 3 or $recur->type == 6) {
294                                                if (isset($row[4])) $recur->dayofweek = $row[4];
295                                        }
296                                        if ($recur->type == 2 or $recur->type == 5) {
297                                                $tz = date_default_timezone_get();
298                                                date_default_timezone_set('UTC');
299                                                $array_startdatetime    = getdate($message->starttime);
300                                                $recur->dayofmonth = $array_startdatetime['mday'];
301                                                date_default_timezone_set($tz);
302
303                                        }
304                                        if ($recur->type == 5 or $recur->type == 6) {
305                                                $tz = date_default_timezone_get();
306                                                date_default_timezone_set('UTC');
307                                                $array_startdatetime    = getdate($message->starttime);
308                                                $recur->monthofyear = $array_startdatetime['mon'];
309                                                date_default_timezone_set($tz);
310
311                                        }
312                                        $message->recurrence = $recur;
313                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO-> Fim do Bloco - Lê recorrência do evento.');
314                                }
315
316                                //Eventos Unicos da Recorrencia Editados
317                                $result = pg_query($this->db, "select cal_id from phpgw_cal where reference = " . $id . ";");
318                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
319                                while ($row_recur_exception = pg_fetch_row($result)) {
320                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO: Lê evento único da recorrência com id: '.$row_recur_exception[0]);
321                                        $recur_exception = $this->GetMessageDAO($row_recur_exception[0]);
322                                        if ($recur_exception instanceof SyncAppointment) {
323                                                if (!isset($message->exceptions)) $message->exceptions = array();
324                                                array_push($message->exceptions, $recur_exception);
325                                        }
326                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO-> Fim do Bloco - Lê evento único da recorrência com id: '.$row_recur_exception[0]);
327                                }
328
329                                //Eventos Unicos da Recorrencia Deletados
330                                if (isset($row[5]) and $row[5] != "") {
331                                        $array_timestamps_recur_deleted = explode(",",$row[5]);
332                                        foreach ($array_timestamps_recur_deleted as $timestamp_recur_deleted) {
333                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO: Timestamps dos eventos únicos da recorrência do tipo deletados: '.$timestamp_recur_deleted);
334                                                $recur_deleted = new SyncAppointment();
335                                                $recur_deleted->deleted = '1';
336                                                $recur_deleted->exceptionstarttime = (integer)$timestamp_recur_deleted;
337                                                if (!isset($message->exceptions)) $message->exceptions = array();
338                                                array_push($message->exceptions, $recur_deleted);
339                                        }
340                                }
341                                //TODO: Tratar Participantes do Evento
342
343                        }
344                        $result = pg_query($this->db,"COMMIT;");
345                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
346                } catch (Exception $e) {
347                        pg_query($this->db,"ROLLBACK;");
348                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
349                        return;
350                }
351                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO-> Fim do Bloco - Lê evento do DB para enviar para o celular: '.$id);
352                return $message;
353        }
354
355        function GetMessage($folderid, $id, $truncsize, $mimesupport = 0) {
356                debugLog('CalendarExpresso::GetMessage('.$folderid.', '.$id.', ..)');
357                if($folderid != "calendar")     return;
358                if(trim($id == "")) return;
359                $message = $this->GetMessageDAO($id);
360                return $message;
361        }
362
363        function DeleteMessage($folderid, $id) {
364                debugLog('CalendarExpresso::DeleteMessage('.$folderid.', '.$id.', ..)');
365                if (!isset($id)) return false;
366                $result = pg_query($this->db, "select owner from phpgw_cal where cal_id = " . $id . ";");
367                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
368                if ($this->_uidnumber != pg_fetch_result($result, 0, 0)) return false;
369                try {
370                        $result = pg_query($this->db,"BEGIN;");
371                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
372                        $result = pg_delete($this->db, "phpgw_cal_user", array('cal_id' => $id));
373                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
374                        $result = pg_delete($this->db, "phpgw_cal", array('reference' => $id));
375                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
376                        $result = pg_delete($this->db, "phpgw_cal_repeats", array('cal_id' => $id));
377                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
378                        $result = pg_query("delete from phpgw_async where id like 'cal:" . $id . "%';");
379                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
380                        $result = pg_delete($this->db, "phpgw_cal_extra", array('cal_id' => $id));
381                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
382                        $result = pg_delete($this->db, "phpgw_cal", array('cal_id' => $id));
383                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
384                        $result = pg_query($this->db,"COMMIT;");
385                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
386                } catch (Exception $e) {
387                        pg_query($this->db,"ROLLBACK;");
388                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
389                        return false;
390                }
391                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog("CalendarExpresso::DeleteMessage-> Fim normal da Função.");
392                return true;
393        }
394
395        function SetReadFlag($folderid, $id, $flags) {
396                return false;
397        }
398
399        function ChangeMessageDAO($id, $message) {
400                debugLog('CalendarExpresso::ChangeMessageDAO('.$id.', ..)');
401                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> O evento do celular será inserido/atualizado no BD com o ID: '.$id);
402                try {
403                        $result = pg_query($this->db,"BEGIN;");
404                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
405                        $found_cal_id = false;
406                        $found_cal_user = false;
407                        $found_cal_repeats = false;
408                        if ($id != false) {
409                                $result = pg_query($this->db, "select cal_id, cal_type, owner, description from phpgw_cal where cal_id = " . $id . ";");
410                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
411                                // tenta localizar cal_id para fazer Update
412                                while ($row = pg_fetch_row($result)) {
413                                        if(isset($row[0])) {
414                                                if ($this->_uidnumber != $row[2]) return false; // Nao atualiza evento de outro proprietario
415                                                $cal_id = $row[0];
416                                                $cal_type_from_DB = $row[1];
417                                                $description_from_DB = $row[3];
418                                                $found_cal_id = true;
419                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Achou o evento na tabela phpgw_cal, vai ATUALIZAR essa tabela');
420                                        }
421                                }
422                                // Verifica se ja existe o registro do evento na tabela phpgw_cal_user
423                                $result = pg_query($this->db, "select cal_id, cal_login from phpgw_cal_user where cal_id = " . $cal_id . " and cal_login = '" . $this->_uidnumber . "';");
424                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
425                                if ($row = pg_fetch_row($result)) {
426                                        if(isset($row[0])) {
427                                                $found_cal_user = true;
428                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Achou o evento na tabela phpgw_cal_user, vai ATUALIZAR essa tabela');
429                                        }
430                                }
431                                // Verifica se ja existe o registro de recorrencia do evento na tabela phpgw_cal_repeats
432                                $result = pg_query($this->db, "select cal_id from phpgw_cal_repeats where cal_id = " . $cal_id . ";");
433                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
434                                if ($row = pg_fetch_row($result)) {
435                                        if(isset($row[0])) {
436                                                $found_cal_repeats = true;
437                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Achou o evento na tabela phpgw_cal_repeats, vai ATUALIZAR essa tabela');
438                                        }
439                                }
440                        }
441
442                        //Insere/Atualiza tabela phpgw_cal
443                        if(isset($message->uid)) {
444                                $arrayCal["uid"] = $this->truncateString(utf8_decode($message->uid),255);
445                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> uid: '.$arrayCal["uid"]);
446                        }
447                        if(isset($message->subject)) {
448                                $arrayCal["title"] = $this->truncateString(utf8_decode($message->subject),299);
449                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> title: '.$arrayCal["title"]);
450                        }
451                        if(isset($message->location)) {
452                                $arrayCal["location"] = $this->truncateString(utf8_decode($message->location),255);
453                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> location: '.$arrayCal["location"]);
454                        }
455                        if(isset($message->dtstamp)) {
456                                $arrayCal["mdatetime"] = $message->dtstamp;
457                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> mdatetime: '.$arrayCal["mdatetime"]);
458                        }
459                        if(isset($message->starttime)) {
460                                $arrayCal["datetime"] = $message->starttime;
461                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> datetime: '.$arrayCal["datetime"]);
462                        }
463                        if(isset($message->endtime)) {
464                                $arrayCal["edatetime"] = $message->endtime;
465                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> edatetime: '.$arrayCal["edatetime"]);
466                        }
467                        if(isset($message->sensitivity) and $message->sensitivity == 0) {
468                                $arrayCal["is_public"] = 1; // 1 - Normal
469                        } else $arrayCal["is_public"] = 0; // 0 - Privado
470                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> is_public: '.$arrayCal["is_public"]);
471
472                        if(isset($message->rtf)) {
473                                $rtf_to_ascii = new rtf();
474                                $rtf_to_ascii->output("ascii");
475                                $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf));
476                                if ($result_loadrtf == true) $rtf_to_ascii->parse();
477                                $arrayCal["description"] = $rtf_to_ascii->out;
478                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> description: '.$arrayCal["description"]);
479                                //                      } else {
480                                //                              $arrayCal["description"] = '';
481                        }
482                        $arrayCal["category"] = '';
483                        if (isset($message->categories)) {
484                                foreach ($message->categories as $category) {
485                                        $cat_id = $this->addCategory($category);
486                                        if ($cat_id != false) {
487                                                if ($arrayCal["category"] == '') {
488                                                        $arrayCal["category"] = $cat_id;
489                                                } else {
490                                                        $arrayCal["category"] .= ',' . $cat_id;
491                                                }
492                                        }
493                                }
494                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> category: '.$arrayCal["category"]);
495                        }
496                        $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone));
497                        //TODO: Atribuir valores para ex_participants
498                        $arrayCal["ex_participants"] = '';
499                        //TODO: Converter eventos que sao alldayevent para iniciar as 0:00hs e terminar as 23:59hs. Isso porque o Expresso nao suporta alldayevents
500                        //               if(isset($message->alldayevent)) {
501                        //                      $arrayCal["alldayevent"] = $this->truncateString(utf8_decode($message->alldayevent),30);
502                        //               }
503                        if (!$found_cal_id){
504                                $result = pg_query("select nextval('seq_phpgw_cal');");
505                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
506                                $cal_id = pg_fetch_result($result, 0, 0);
507                                $arrayCal["cal_id"] = $cal_id;
508                                $arrayCal["owner"] = $this->_uidnumber;
509                                if (isset($message->recurrence)) $arrayCal["cal_type"] = 'M';
510                                else $arrayCal["cal_type"] = 'E';
511                                $result = pg_insert($this->db, 'phpgw_cal', $arrayCal);
512                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
513                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento INSERIDO na tabela phpgw_cal com cal_id: '.$arrayCal["cal_id"]);
514                        } else {
515                                if (isset($cal_type_from_DB)) {
516                                        if (isset($message->recurrence)) $arrayCal["cal_type"] = 'M';
517                                        else if ($cal_type_from_DB == 'M') $arrayCal["cal_type"] = 'E';
518                                }
519                                $result = pg_update($this->db, 'phpgw_cal', $arrayCal, array('cal_id' => $cal_id));
520                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
521                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento ATUALIZADO na tabela phpgw_cal');
522                        }
523
524                        // Insere/Atualiza tabela phpgw_cal_user
525                        $arrayCalUser["cal_type"] = 'u';
526                        if (!$found_cal_user){
527                                $arrayCalUser["cal_id"] = $cal_id;
528                                $arrayCalUser["cal_login"] = $this->_uidnumber;
529                                //TODO: Tratar os outros valores de cal_status
530                                $arrayCalUser["cal_status"] = 'A';
531                                $result = pg_insert($this->db, 'phpgw_cal_user', $arrayCalUser);
532                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
533                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento INSERIDO na tabela phpgw_cal_user com cal_id: '.$arrayCalUser["cal_id"]);
534                        } else {
535                                $result = pg_update($this->db, 'phpgw_cal_user', $arrayCalUser, array('cal_id' => $cal_id, 'cal_login' => $this->_uidnumber));
536                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
537                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento ATUALIZADO na tabela phpgw_cal_user');
538                        }
539                        if (!$id) {
540                                $id = $cal_id;
541                        }
542
543                        //TODO: Implementar para os tipos 3 e 6. O Expresso ainda nao suporta esses tipos :-(
544                        if (isset($message->recurrence) and ($message->recurrence->type == 0 or $message->recurrence->type == 1 or $message->recurrence->type == 2 or $message->recurrence->type == 5)) {
545                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> O Evento é Recorrente.');
546                                switch ($message->recurrence->type) {
547                                        case 0: //repeticao diaria
548                                                $arrayRecur["recur_type"] = 1;
549                                                $type_name = "day";
550                                                break;
551                                        case 1: //repeticao semanal
552                                                $arrayRecur["recur_type"] = 2;
553                                                $type_name = "week";
554                                                break;
555                                        case 2: //repeticao mensal por data
556                                                $arrayRecur["recur_type"] = 3;
557                                                $type_name = "month";
558                                                break;
559                                        case 5: //repeticao anual por data
560                                                $arrayRecur["recur_type"] = 5;
561                                                $type_name = "year";
562                                                break;
563                                }
564                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_type: '.$arrayRecur["recur_type"]);
565                                if (isset($message->recurrence->interval)) {
566                                        $arrayRecur["recur_interval"] = $message->recurrence->interval;
567                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_interval: '.$arrayRecur["recur_interval"]);
568                                }
569                                if ($message->recurrence->type == 1 or $message->recurrence->type == 3 or $message->recurrence->type == 6) {
570                                        if (isset($message->recurrence->dayofweek)) {
571                                                $arrayRecur["recur_data"] = $message->recurrence->dayofweek;
572                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_data: '.$arrayRecur["recur_data"]);
573                                                /*$day = $message->recurrence->dayofweek;
574                                                 $day_of_week_counter = 0;
575                                                 if (($day & 1) > 0) $day_of_week_counter++;
576                                                 if (($day & 2) > 0) $day_of_week_counter++;
577                                                 if (($day & 4) > 0) $day_of_week_counter++;
578                                                 if (($day & 8) > 0) $day_of_week_counter++;
579                                                 if (($day & 16) > 0) $day_of_week_counter++;
580                                                 if (($day & 32) > 0) $day_of_week_counter++;
581                                                 if (($day & 64) > 0) $day_of_week_counter++;*/
582                                        }
583                                }
584                                //TODO: Converter ocurrences para until.
585                                /*if (!isset($message->recurrence->until) and (isset($message->recurrence->occurrences))) {
586                                $tz = date_default_timezone_get();
587                                date_default_timezone_set('UTC');
588                                $message->recurrence->until = strtotime(date("Y-m-d H:i:s", $message->starttime) . " +" . $message->recurrence->occurrences * $message->recurrence->interval . " " . $type_name);
589                                unset($message->recurrence->occurrences);
590                                date_default_timezone_set($tz);
591                                }*/
592                                if (isset($message->recurrence->until)){
593                                        $defaultTZ = new DateTimeZone(date_default_timezone_get());
594                                        $gmtTZ = new DateTimeZone('GMT');
595                                        $gmtDate = new DateTime("now", $gmtTZ);
596                                        $GMT_EX = $defaultTZ->getOffset($gmtDate);
597                                        $GMT_CEL = -(($tz_CEL["bias"] + $tz_CEL["dstbias"]) * 60);
598
599                                        $tz = date_default_timezone_get();
600                                        date_default_timezone_set('UTC');
601                                        $day_CEL = date("d", $message->starttime +  $GMT_CEL);
602                                        $day_EX = date("d", $message->starttime +  $GMT_EX);
603
604                                        if ($day_EX > $day_CEL) $arrayRecur["recur_enddate"] = $message->recurrence->until + $GMT_CEL - $GMT_EX + 86400;
605                                        else if ($day_EX < $day_CEL) $arrayRecur["recur_enddate"] = $message->recurrence->until + $GMT_CEL - $GMT_EX - 86400;
606                                        else $arrayRecur["recur_enddate"] = $message->recurrence->until;
607                                        date_default_timezone_set($tz);
608                                        /*$arrayRecur["recur_enddate"] = $message->recurrence->until - $offsetTZ;
609                                         $hour = date("G", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60));
610                                         $min = date("i", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60));
611                                         $sec = date("s", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60));
612                                               
613                                         $arrayRecur["recur_enddate"] = $message->recurrence->until + ($hour * 3600) + ($min * 60) + $sec + $offsetTZ + (($tz["bias"] - $tz["dstbias"]) * 60);*/
614                                } else {
615                                        $arrayRecur["recur_enddate"] = 1893283200; // Se nao tem data de termino seta para 30/12/2029
616                                }
617                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_enddate: '.$arrayRecur["recur_enddate"]);
618
619                                // Trata excecoes da recorrencia
620                                if (isset($message->exceptions)){
621                                        // Tem Excecoes de recorrencia do tipo Edicao
622                                        // Verifica se ja existe o registro do evento de excecao de recorrencia na tabela phpgw_cal
623                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento tem exceção de recorrência');
624                                        $recur_exception_changed_ids = "";
625                                        $recur_exception_deleted_starttimes = "";
626                                        foreach ($message->exceptions as $recur_exception) {
627                                                if ($recur_exception->deleted == 0){ //Tem Excecoes do Tipo Edicao
628                                                        $found_recur_exception_changed = true;
629                                                        if (isset($arrayExceptCal)) unset($arrayExceptCal);
630                                                        if (isset($arrayExceptCalUser)) unset($arrayExceptCalUser);
631                                                        if (isset($except_cal_id)) unset($except_cal_id);
632                                                        if (isset($except_cal_type_from_DB)) unset($except_cal_type_from_DB);
633                                                        if (isset($except_description_from_DB)) unset($except_description_from_DB);
634                                                        $found_except_cal_id = false;
635                                                        $found_except_cal_user = false;
636                                                        $result = pg_query($this->db, "select cal_id, cal_type, description from phpgw_cal where reference = " . $id . " and datetime = " . $recur_exception->exceptionstarttime . ";");
637                                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
638                                                        // tenta localizar cal_id para fazer Update
639                                                        while ($row = pg_fetch_row($result)) {
640                                                                if(isset($row[0])) {
641                                                                        $except_cal_id = $row[0];
642                                                                        $except_cal_type_from_DB = $row[1];
643                                                                        $except_description_from_DB = $row[2];
644                                                                        $found_except_cal_id = true;
645                                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Achou o evento na tabela phpgw_cal, vai ATUALIZAR a exceção da recorrência nessa tabela');
646                                                                }
647                                                        }
648                                                        // Verifica se ja existe o registro do evento de excecao de recorrencia na tabela phpgw_cal_user
649                                                        if (isset($except_cal_id)) {
650                                                                $result = pg_query($this->db, "select cal_id, cal_login from phpgw_cal_user where cal_id = " . $except_cal_id . " and cal_login = '" . $this->_uidnumber . "';");
651                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
652                                                                if ($row = pg_fetch_row($result)) {
653                                                                        if(isset($row[0])) {
654                                                                                $found_except_cal_user = true;
655                                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Achou o evento na tabela phpgw_cal_user, vai ATUALIZAR a exceção da recorrência nessa tabela');
656                                                                        }
657                                                                }
658                                                        }
659                                                        //Insere/Atualiza tabela phpgw_cal
660                                                        $arrayExceptCal["reference"] = $cal_id;
661                                                        if(isset($message->uid)) {
662                                                                $arrayExceptCal["uid"] = $this->truncateString(utf8_decode($message->uid),255);
663                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> uid: '.$arrayExceptCal["uid"]);
664                                                        }
665                                                        if(isset($recur_exception->subject)) {
666                                                                $arrayExceptCal["title"] = $this->truncateString(utf8_decode($recur_exception->subject),299);
667                                                        } elseif(isset($message->subject)) {
668                                                                $arrayExceptCal["title"] = $this->truncateString(utf8_decode($message->subject),299);
669                                                        }
670                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> title: '.$arrayExceptCal["title"]);
671                                                        if(isset($recur_exception->location)) {
672                                                                $arrayExceptCal["location"] = $this->truncateString(utf8_decode($recur_exception->location),255);
673                                                        } else if(isset($message->location)) {
674                                                                $arrayExceptCal["location"] = $this->truncateString(utf8_decode($message->location),255);
675                                                        }
676                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> location: '.$arrayExceptCal["location"]);
677                                                        if(isset($recur_exception->dtstamp)) {
678                                                                $arrayExceptCal["mdatetime"] = $recur_exception->dtstamp;
679                                                        } elseif(isset($message->dtstamp)) {
680                                                                $arrayExceptCal["mdatetime"] = $message->dtstamp;
681                                                        }
682                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> mdatetime: '.$arrayExceptCal["mdatetime"]);
683                                                        if(isset($recur_exception->starttime)) {
684                                                                $arrayExceptCal["datetime"] = $recur_exception->starttime;
685                                                        } else if(isset($message->starttime)) {
686                                                                $arrayExceptCal["datetime"] = $message->starttime;
687                                                        }
688                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> datetime: '.$arrayExceptCal["datetime"]);
689                                                        if(isset($recur_exception->endtime)) {
690                                                                $arrayExceptCal["edatetime"] = $recur_exception->endtime;
691                                                        }elseif(isset($message->endtime)) {
692                                                                $arrayExceptCal["edatetime"] = $message->endtime;
693                                                        }
694                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> edatetime: '.$arrayExceptCal["edatetime"]);
695                                                        if(isset($recur_exception->sensitivity) and $recur_exception->sensitivity == 0) {
696                                                                $arrayExceptCal["is_public"] = 1; // 1 - Normal
697                                                        }elseif (isset($recur_exception->sensitivity) and $recur_exception->sensitivity == 1){
698                                                                $arrayExceptCal["is_public"] = 0; // 0 - Privado
699                                                        }elseif(isset($message->sensitivity) and $message->sensitivity == 0) {
700                                                                $arrayExceptCal["is_public"] = 1; // 1 - Normal
701                                                        }else $arrayExceptCal["is_public"] = 0; // 0 - Privado
702                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> is_public: '.$arrayExceptCal["is_public"]);
703                                                        if (isset($recur_exception->body)) {
704                                                                $arrayExceptCal["description"] = utf8_decode($recur_exception->body);
705                                                        } elseif (!isset($except_description_from_DB)) {
706                                                                if (isset($message->rtf)) {
707                                                                        $rtf_to_ascii = new rtf();
708                                                                        $rtf_to_ascii->output("ascii");
709                                                                        $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf));
710                                                                        if ($result_loadrtf == true) $rtf_to_ascii->parse();
711                                                                        $arrayExceptCal["description"] = $rtf_to_ascii->out;
712                                                                } elseif (isset($description_from_DB)) {
713                                                                        $arrayExceptCal["description"] = utf8_decode($description_from_DB);
714                                                                }
715                                                        }
716                                                        $arrayExceptCal["category"] = '';
717                                                        if (isset($recur_exception->categories)) {
718                                                                foreach ($recur_exception->categories as $category) {
719                                                                        $cat_id = $this->addCategory($category);
720                                                                        if ($cat_id != false) {
721                                                                                if ($arrayExceptCal["category"] == '') {
722                                                                                        $arrayExceptCal["category"] = $cat_id;
723                                                                                } else {
724                                                                                        $arrayExceptCal["category"] .= ',' . $cat_id;
725                                                                                }
726                                                                        }
727                                                                }
728                                                        }elseif (isset($message->categories)) {
729                                                                foreach ($message->categories as $category) {
730                                                                        $cat_id = $this->addCategory($category);
731                                                                        if ($cat_id != false) {
732                                                                                if ($arrayExceptCal["category"] == '') {
733                                                                                        $arrayExceptCal["category"] = $cat_id;
734                                                                                } else {
735                                                                                        $arrayExceptCal["category"] .= ',' . $cat_id;
736                                                                                }
737                                                                        }
738                                                                }
739                                                        }
740                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> category: '.$arrayExceptCal["category"]);
741                                                        //TODO: Converter eventos que sao alldayevent para iniciar as 0:00hs e terminar as 23:59hs. Isso porque o Expresso nao suporta alldayevents
742                                                        //               if(isset($message->alldayevent)) {
743                                                        //                      $arrayCal["alldayevent"] = $this->truncateString(utf8_decode($message->alldayevent),30);
744                                                        //               }
745                                                        if (!$found_except_cal_id){
746                                                                $result = pg_query("select nextval('seq_phpgw_cal');");
747                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
748                                                                $except_cal_id = pg_fetch_result($result, 0, 0);
749                                                                $arrayExceptCal["cal_id"] = $except_cal_id;
750                                                                $arrayExceptCal["owner"] = $this->_uidnumber;
751                                                                $arrayExceptCal["cal_type"] = 'E';
752                                                                $result = pg_insert($this->db, 'phpgw_cal', $arrayExceptCal);
753                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
754                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento de Exceção da Recorrência INSERIDO na tabela phpgw_cal com cal_id: '.$arrayExceptCal["cal_id"]);
755                                                        } else {
756                                                                $result = pg_update($this->db, 'phpgw_cal', $arrayExceptCal, array('cal_id' => $except_cal_id));
757                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
758                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento de Exceção da Recorrência ATUALIZADO na tabela phpgw_cal');
759                                                        }
760
761                                                        // Insere/Atualiza Excecoes de Recorrencia na tabela phpgw_cal_user
762                                                        $arrayExceptCalUser["cal_type"] = 'u';
763                                                        if (!$found_except_cal_user){
764                                                                $arrayExceptCalUser["cal_id"] = $except_cal_id;
765                                                                $arrayExceptCalUser["cal_login"] = $this->_uidnumber;
766                                                                //TODO: Tratar os outros valores de cal_status
767                                                                $arrayExceptCalUser["cal_status"] = 'A';
768                                                                $result = pg_insert($this->db, 'phpgw_cal_user', $arrayExceptCalUser);
769                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
770                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento de Exceção da Recorrência INSERIDO na tabela phpgw_cal_user com cal_id: '.$arrayExceptCalUser["cal_id"]);
771                                                        } else {
772                                                                $result = pg_update($this->db, 'phpgw_cal_user', $arrayExceptCalUser, array('cal_id' => $except_cal_id, 'cal_login' => $this->_uidnumber));
773                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
774                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento de Exceção da Recorrência ATUALIZADO na tabela phpgw_cal_user');
775                                                        }
776                                                        if ($recur_exception_changed_ids == "") {
777                                                                $recur_exception_changed_ids = $except_cal_id;
778                                                        } else {
779                                                                $recur_exception_changed_ids .= "," . $except_cal_id;
780                                                        }
781                                                } else {
782                                                        if ($recur_exception_deleted_starttimes == "") {
783                                                                $recur_exception_deleted_starttimes = $recur_exception->exceptionstarttime;
784                                                        } else {
785                                                                $recur_exception_deleted_starttimes .= "," . $recur_exception->exceptionstarttime;
786                                                        }
787                                                }
788                                        }
789                                        if ($recur_exception_deleted_starttimes != "") {
790                                                //Tem Excecoes de recorrencia do tipo Exclusao
791                                                $arrayRecur["recur_exception"] = $recur_exception_deleted_starttimes;
792                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento tem exceção de recorrência do tipo exclusão com os seguintes starttimes: '.$recur_exception_deleted_starttimes);
793                                        } else {
794                                                $arrayRecur["recur_exception"] = "";
795                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Não tem exceção de recorrência do tipo exclusão para esse evento');
796                                        }
797                                        if ($recur_exception_changed_ids == "") {
798                                                // Se nao tem excecoes de recorrencia do tipo edicao, entao deleta as excecoes da recorrencia
799                                                $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");");
800                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
801                                                $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";");
802                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
803                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Não tem exceção de recorrência, então deleta possíveis eventos de exceção de recorrência criados anteriormente para esse evento.');
804                                        } else {
805                                                //Deleta as excecoes da recorrencia, exceto as inseridas/atualizadas acima
806                                                $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . " and cal_id not in (" . $recur_exception_changed_ids . "));");
807                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
808                                                $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . " and cal_id not in (" . $recur_exception_changed_ids . ");");
809                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
810                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Deleta as exçeções da recorrência, exceto as inseridas/atualizadas pelo celular com os seguintes cal_id:'.$recur_exception_changed_ids);
811                                        }
812                                } else {
813                                        // Se nao tem excecoes da recorrencia entao
814                                        $arrayRecur["recur_exception"] = "";
815                                        $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");");
816                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
817                                        $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";");
818                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
819                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Não tem exceção de recorrência, então deleta possíveis eventos de exceção de recorrência criados anteriormente para esse evento..');
820                                }
821                                if (!$found_cal_repeats){
822                                        $arrayRecur["cal_id"] = $cal_id;
823                                        $result = pg_insert($this->db, 'phpgw_cal_repeats', $arrayRecur);
824                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
825                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência INSERIDA na tabela phpgw_cal_repeats com cal_id: '.$arrayRecur["cal_id"]);
826                                } else {
827                                        $result = pg_update($this->db, 'phpgw_cal_repeats', $arrayRecur, array('cal_id' => $cal_id));
828                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
829                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência ATUALIZADA na tabela phpgw_cal_repeats');
830                                }
831                        } elseif ($found_cal_id) {
832                                // Se nao tem recorrencia entao
833                                $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");");
834                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
835                                $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";");
836                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
837                                $result = pg_query($this->db, "delete from phpgw_cal_repeats where cal_id = " . $cal_id . ";");
838                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
839                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Não tem recorrência, então deleta possíveis eventos de recorrência criados anteriormente para esse evento');
840                        }
841                        $result = pg_query($this->db,"COMMIT;");
842                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
843                        //TODO: Implementar Participantes
844                } catch (Exception $e) {
845                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
846                        pg_query($this->db,"ROLLBACK;");
847                        return false;
848                }
849                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Fim normal da Função');
850                return $id;
851        }
852
853        function ChangeMessage($folderid, $id, $message) {
854                debugLog('CalendarExpresso::ChangeMessage('.$folderid.', '.$id.', ..)');
855                $id = $this->ChangeMessageDAO($id, $message);
856                if ($id != false) return $this->StatMessage($folderid, $id);
857                else return false;
858        }
859
860        function MoveMessage($folderid, $id, $newfolderid) {
861                return false;
862        }
863
864        function addCategory($category) {
865                $cat_id = false;
866                try {
867                        $result = pg_query($this->db,"BEGIN;");
868                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
869                        $result = pg_query("SELECT cat_id from phpgw_categories WHERE cat_owner = -1 AND cat_appname = 'calendar' AND LOWER(to_ASCII(cat_name)) = '" . trim(strtolower($this->removeAccents(utf8_decode($category)))) . "';");
870                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
871                        if (!($cat_id = pg_fetch_result($result, 0, 0))){
872                                $result = pg_query("SELECT cat_id from phpgw_categories WHERE cat_owner = " . $this->_uidnumber . " AND cat_appname = 'calendar' AND LOWER(to_ASCII(cat_name)) = '" . trim(strtolower($this->removeAccents(utf8_decode($category)))) . "';");
873                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
874                                if (!($cat_id = pg_fetch_result($result, 0, 0))){
875                                        $result = pg_query("select nextval('seq_phpgw_categories');");
876                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
877                                        $cat_id = pg_fetch_result($result, 0, 0);
878                                        $arrayCat["cat_id"] = $cat_id;
879                                        $arrayCat["cat_owner"] = $this->_uidnumber;
880                                        $arrayCat["cat_access"] = 'public';
881                                        $arrayCat["cat_appname"] = 'calendar';
882                                        $arrayCat["cat_name"] = utf8_decode($category);
883                                        $arrayCat["cat_description"] = '';
884                                        $arrayCat["cat_data"] = 'N;';
885                                        $arrayCat["last_mod"] = time();
886                                        $result = pg_insert($this->db, 'phpgw_categories', $arrayCat);
887                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
888                                }
889                        }
890                } catch (Exception $e) {
891                        pg_query($this->db,"ROLLBACK;");
892                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
893                        return false;
894                }
895                return $cat_id;
896        }
897
898        // -----------------------------------
899
900        function escape($data){
901                if (is_array($data)) {
902                        foreach ($data as $key => $val) {
903                                $data[$key] = $this->escape($val);
904                        }
905                        return $data;
906                }
907                $data = str_replace("\r\n", "\n", $data);
908                $data = str_replace("\r", "\n", $data);
909                $data = str_replace(array('\\', ';', ',', "\n"), array('\\\\', '\\;', '\\,', '\\n'), $data);
910                return $data;
911        }
912
913        function unescape($data){
914                $data = str_replace(array('\\\\', '\\;', '\\,', '\\n','\\N'),array('\\', ';', ',', "\n", "\n"),$data);
915                return $data;
916        }
917
918        function  removeAccents($data){
919                $data = strtr($data,"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ","aaaaaaaceeeeiiii noooooxouuutbaaaaaaaceeeeiiii nooooo/ouuuty");
920                return $data;
921        }
922
923        function truncateString($string, $size)
924        {
925                if(strlen($string) <= $size) return $string;
926                else return substr($string, 0, $size - 1);
927        }
928
929        function parseUser($id_user)
930        {
931                $pos = strripos($id_user, '\\');
932                if ($pos === false) {
933                        if (strlen($id_user) < 1) return false;
934                        else return $id_user;
935                } else {
936                        if (strlen($id_user) <= $pos + 1) {
937                                return false;
938                        } else {
939                                return substr(substr($id_user, $pos + 1), 0, strlen(substr($id_user, $pos + 1)));
940                        }
941                }
942        }
943
944        function _getGMTTZ() {
945                //$tz = array("bias" => 0, "stdbias" => 0, "dstbias" => 0, "dstendyear" => 0, "dstendmonth" => 2, "dstendday" => 0, "dstendweek" => 2, "dstendhour" => 2, "dstendminute" => 0, "dstendsecond" => 0, "dstendmillis" => 0,
946                //                              "dststartyear" => 0, "dststartmonth" =>10, "dststartday" =>0, "dststartweek" => 3, "dststarthour" => 2, "dststartminute" => 0, "dststartsecond" => 0, "dststartmillis" => 0);
947                $tz = array("bias" => 120, "stdbias" => 0, "dstbias" => -60, "dstendyear" => 0, "dstendmonth" => 2, "dstendday" => 0, "dstendweek" => 2, "dstendhour" => 2, "dstendminute" => 0, "dstendsecond" => 0, "dstendmillis" => 0,
948                                                      "dststartyear" => 0, "dststartmonth" =>10, "dststartday" =>0, "dststartweek" => 3, "dststarthour" => 2, "dststartminute" => 0, "dststartsecond" => 0, "dststartmillis" => 0);
949                return $tz;
950        }
951
952        // Unpack timezone info from Sync
953        function _getTZFromSyncBlob($data) {
954                $tz = unpack(    "lbias/a64name/vdstendyear/vdstendmonth/vdstendday/vdstendweek/vdstendhour/vdstendminute/vdstendsecond/vdstendmillis/" .
955                        "lstdbias/a64name/vdststartyear/vdststartmonth/vdststartday/vdststartweek/vdststarthour/vdststartminute/vdststartsecond/vdststartmillis/" .
956                        "ldstbias", $data);
957
958                // Make the structure compatible with class.recurrence.php
959                $tz["timezone"] = $tz["bias"];
960                $tz["timezonedst"] = $tz["dstbias"];
961
962                return $tz;
963        }
964
965        // Pack timezone info for Sync
966        function _getSyncBlobFromTZ($tz) {
967                $packed = pack("la64vvvvvvvv" . "la64vvvvvvvv" . "l",
968                $tz["bias"], "", 0, $tz["dstendmonth"], $tz["dstendday"], $tz["dstendweek"], $tz["dstendhour"], $tz["dstendminute"], $tz["dstendsecond"], $tz["dstendmillis"],
969                $tz["stdbias"], "", 0, $tz["dststartmonth"], $tz["dststartday"], $tz["dststartweek"], $tz["dststarthour"], $tz["dststartminute"], $tz["dststartsecond"], $tz["dststartmillis"],
970                $tz["dstbias"]);
971
972                return $packed;
973        }
974
975        // Authenticate user and return UIDNumber attribute on success
976        function authUser($user, $pwd) {
977                $ldap = new AuthLDAP();
978                $uid_number = ($ldap->bind($user,$pwd));
979                $ldap->disconnect();
980                unset($ldap);
981                if (! $uid_number) return false;
982                return $uid_number;
983        }
984};
985?>
Note: See TracBrowser for help on using the repository browser.