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

Revision 4898, 54.6 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #2180 - Adicionado código fonte completo do zpush

  • 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                        $result = pg_query($this->db,"COMMIT;");
344                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
345                } catch (Exception $e) {
346                        pg_query($this->db,"ROLLBACK;");
347                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
348                        return;
349                }
350                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);
351                return $message;
352        }
353
354        function GetMessage($folderid, $id, $truncsize, $mimesupport = 0) {
355                debugLog('CalendarExpresso::GetMessage('.$folderid.', '.$id.', ..)');
356                if($folderid != "calendar")     return;
357                if(trim($id == "")) return;
358                $message = $this->GetMessageDAO($id);
359                return $message;
360        }
361
362        function DeleteMessage($folderid, $id) {
363                debugLog('CalendarExpresso::DeleteMessage('.$folderid.', '.$id.', ..)');
364                if (!isset($id)) return false;
365                $result = pg_query($this->db, "select owner from phpgw_cal where cal_id = " . $id . ";");
366                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
367                if ($this->_uidnumber != pg_fetch_result($result, 0, 0)) return false;
368                try {
369                        $result = pg_query($this->db,"BEGIN;");
370                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
371                        $result = pg_delete($this->db, "phpgw_cal_user", array('cal_id' => $id));
372                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
373                        $result = pg_delete($this->db, "phpgw_cal", array('reference' => $id));
374                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
375                        $result = pg_delete($this->db, "phpgw_cal_repeats", array('cal_id' => $id));
376                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
377                        $result = pg_query("delete from phpgw_async where id like 'cal:" . $id . "%';");
378                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
379                        $result = pg_delete($this->db, "phpgw_cal_extra", array('cal_id' => $id));
380                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
381                        $result = pg_delete($this->db, "phpgw_cal", array('cal_id' => $id));
382                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
383                        $result = pg_query($this->db,"COMMIT;");
384                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
385                } catch (Exception $e) {
386                        pg_query($this->db,"ROLLBACK;");
387                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
388                        return false;
389                }
390                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog("CalendarExpresso::DeleteMessage-> Fim normal da Função.");
391                return true;
392        }
393
394        function SetReadFlag($folderid, $id, $flags) {
395                return false;
396        }
397
398        function ChangeMessageDAO($id, $message) {
399                debugLog('CalendarExpresso::ChangeMessageDAO('.$id.', ..)');
400                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);
401                try {
402                        $result = pg_query($this->db,"BEGIN;");
403                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
404                        $found_cal_id = false;
405                        $found_cal_user = false;
406                        $found_cal_repeats = false;
407                        if ($id != false) {
408                                $result = pg_query($this->db, "select cal_id, cal_type, owner, description from phpgw_cal where cal_id = " . $id . ";");
409                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
410                                // tenta localizar cal_id para fazer Update
411                                while ($row = pg_fetch_row($result)) {
412                                        if(isset($row[0])) {
413                                                if ($this->_uidnumber != $row[2]) return false; // Nao atualiza evento de outro proprietario
414                                                $cal_id = $row[0];
415                                                $cal_type_from_DB = $row[1];
416                                                $description_from_DB = $row[3];
417                                                $found_cal_id = true;
418                                                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');
419                                        }
420                                }
421                                // Verifica se ja existe o registro do evento na tabela phpgw_cal_user
422                                $result = pg_query($this->db, "select cal_id, cal_login from phpgw_cal_user where cal_id = " . $cal_id . " and cal_login = '" . $this->_uidnumber . "';");
423                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
424                                if ($row = pg_fetch_row($result)) {
425                                        if(isset($row[0])) {
426                                                $found_cal_user = true;
427                                                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');
428                                        }
429                                }
430                                // Verifica se ja existe o registro de recorrencia do evento na tabela phpgw_cal_repeats
431                                $result = pg_query($this->db, "select cal_id from phpgw_cal_repeats where cal_id = " . $cal_id . ";");
432                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
433                                if ($row = pg_fetch_row($result)) {
434                                        if(isset($row[0])) {
435                                                $found_cal_repeats = true;
436                                                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');
437                                        }
438                                }
439                        }
440
441                        //Insere/Atualiza tabela phpgw_cal
442                        if(isset($message->uid)) {
443                                $arrayCal["uid"] = $this->truncateString(utf8_decode($message->uid),255);
444                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> uid: '.$arrayCal["uid"]);
445                        }
446                        if(isset($message->subject)) {
447                                $arrayCal["title"] = $this->truncateString(utf8_decode($message->subject),299);
448                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> title: '.$arrayCal["title"]);
449                        }
450                        if(isset($message->location)) {
451                                $arrayCal["location"] = $this->truncateString(utf8_decode($message->location),255);
452                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> location: '.$arrayCal["location"]);
453                        }
454                        if(isset($message->dtstamp)) {
455                                $arrayCal["mdatetime"] = $message->dtstamp;
456                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> mdatetime: '.$arrayCal["mdatetime"]);
457                        }
458                        if(isset($message->starttime)) {
459                                $arrayCal["datetime"] = $message->starttime;
460                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> datetime: '.$arrayCal["datetime"]);
461                        }
462                        if(isset($message->endtime)) {
463                                $arrayCal["edatetime"] = $message->endtime;
464                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> edatetime: '.$arrayCal["edatetime"]);
465                        }
466                        if(isset($message->sensitivity) and $message->sensitivity == 0) {
467                                $arrayCal["is_public"] = 1; // 1 - Normal
468                        } else $arrayCal["is_public"] = 0; // 0 - Privado
469                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> is_public: '.$arrayCal["is_public"]);
470
471                        if(isset($message->rtf)) {
472                                $rtf_to_ascii = new rtf();
473                                $rtf_to_ascii->output("ascii");
474                                $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf));
475                                if ($result_loadrtf == true) $rtf_to_ascii->parse();
476                                $arrayCal["description"] = $rtf_to_ascii->out;
477                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> description: '.$arrayCal["description"]);
478                                //                      } else {
479                                //                              $arrayCal["description"] = '';
480                        }
481                        $arrayCal["category"] = '';
482                        if (isset($message->categories)) {
483                                foreach ($message->categories as $category) {
484                                        $cat_id = $this->addCategory($category);
485                                        if ($cat_id != false) {
486                                                if ($arrayCal["category"] == '') {
487                                                        $arrayCal["category"] = $cat_id;
488                                                } else {
489                                                        $arrayCal["category"] .= ',' . $cat_id;
490                                                }
491                                        }
492                                }
493                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> category: '.$arrayCal["category"]);
494                        }
495                        $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone));
496                        //TODO: Atribuir valores para ex_participants
497                        $arrayCal["ex_participants"] = '';
498                        //TODO: Converter eventos que sao alldayevent para iniciar as 0:00hs e terminar as 23:59hs. Isso porque o Expresso nao suporta alldayevents
499                        //               if(isset($message->alldayevent)) {
500                        //                      $arrayCal["alldayevent"] = $this->truncateString(utf8_decode($message->alldayevent),30);
501                        //               }
502                        if (!$found_cal_id){
503                                $result = pg_query("select nextval('seq_phpgw_cal');");
504                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
505                                $cal_id = pg_fetch_result($result, 0, 0);
506                                $arrayCal["cal_id"] = $cal_id;
507                                $arrayCal["owner"] = $this->_uidnumber;
508                                if (isset($message->recurrence)) $arrayCal["cal_type"] = 'M';
509                                else $arrayCal["cal_type"] = 'E';
510                                $result = pg_insert($this->db, 'phpgw_cal', $arrayCal);
511                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
512                                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"]);
513                        } else {
514                                if (isset($cal_type_from_DB)) {
515                                        if (isset($message->recurrence)) $arrayCal["cal_type"] = 'M';
516                                        else if ($cal_type_from_DB == 'M') $arrayCal["cal_type"] = 'E';
517                                }
518                                $result = pg_update($this->db, 'phpgw_cal', $arrayCal, array('cal_id' => $cal_id));
519                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
520                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento ATUALIZADO na tabela phpgw_cal');
521                        }
522
523                        // Insere/Atualiza tabela phpgw_cal_user
524                        $arrayCalUser["cal_type"] = 'u';
525                        if (!$found_cal_user){
526                                $arrayCalUser["cal_id"] = $cal_id;
527                                $arrayCalUser["cal_login"] = $this->_uidnumber;
528                                //TODO: Tratar os outros valores de cal_status
529                                $arrayCalUser["cal_status"] = 'A';
530                                $result = pg_insert($this->db, 'phpgw_cal_user', $arrayCalUser);
531                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
532                                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"]);
533                        } else {
534                                $result = pg_update($this->db, 'phpgw_cal_user', $arrayCalUser, array('cal_id' => $cal_id, 'cal_login' => $this->_uidnumber));
535                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
536                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento ATUALIZADO na tabela phpgw_cal_user');
537                        }
538                        if (!$id) {
539                                $id = $cal_id;
540                        }
541
542                        //TODO: Implementar para os tipos 3 e 6. O Expresso ainda nao suporta esses tipos :-(
543                        if (isset($message->recurrence) and ($message->recurrence->type == 0 or $message->recurrence->type == 1 or $message->recurrence->type == 2 or $message->recurrence->type == 5)) {
544                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> O Evento é Recorrente.');
545                                switch ($message->recurrence->type) {
546                                        case 0: //repeticao diaria
547                                                $arrayRecur["recur_type"] = 1;
548                                                $type_name = "day";
549                                                break;
550                                        case 1: //repeticao semanal
551                                                $arrayRecur["recur_type"] = 2;
552                                                $type_name = "week";
553                                                break;
554                                        case 2: //repeticao mensal por data
555                                                $arrayRecur["recur_type"] = 3;
556                                                $type_name = "month";
557                                                break;
558                                        case 5: //repeticao anual por data
559                                                $arrayRecur["recur_type"] = 5;
560                                                $type_name = "year";
561                                                break;
562                                }
563                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_type: '.$arrayRecur["recur_type"]);
564                                if (isset($message->recurrence->interval)) {
565                                        $arrayRecur["recur_interval"] = $message->recurrence->interval;
566                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_interval: '.$arrayRecur["recur_interval"]);
567                                }
568                                if ($message->recurrence->type == 1 or $message->recurrence->type == 3 or $message->recurrence->type == 6) {
569                                        if (isset($message->recurrence->dayofweek)) {
570                                                $arrayRecur["recur_data"] = $message->recurrence->dayofweek;
571                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_data: '.$arrayRecur["recur_data"]);
572                                                /*$day = $message->recurrence->dayofweek;
573                                                 $day_of_week_counter = 0;
574                                                 if (($day & 1) > 0) $day_of_week_counter++;
575                                                 if (($day & 2) > 0) $day_of_week_counter++;
576                                                 if (($day & 4) > 0) $day_of_week_counter++;
577                                                 if (($day & 8) > 0) $day_of_week_counter++;
578                                                 if (($day & 16) > 0) $day_of_week_counter++;
579                                                 if (($day & 32) > 0) $day_of_week_counter++;
580                                                 if (($day & 64) > 0) $day_of_week_counter++;*/
581                                        }
582                                }
583                                //TODO: Converter ocurrences para until.
584                                /*if (!isset($message->recurrence->until) and (isset($message->recurrence->occurrences))) {
585                                $tz = date_default_timezone_get();
586                                date_default_timezone_set('UTC');
587                                $message->recurrence->until = strtotime(date("Y-m-d H:i:s", $message->starttime) . " +" . $message->recurrence->occurrences * $message->recurrence->interval . " " . $type_name);
588                                unset($message->recurrence->occurrences);
589                                date_default_timezone_set($tz);
590                                }*/
591                                if (isset($message->recurrence->until)){
592                                        $defaultTZ = new DateTimeZone(date_default_timezone_get());
593                                        $gmtTZ = new DateTimeZone('GMT');
594                                        $gmtDate = new DateTime("now", $gmtTZ);
595                                        $GMT_EX = $defaultTZ->getOffset($gmtDate);
596                                        $GMT_CEL = -(($tz_CEL["bias"] + $tz_CEL["dstbias"]) * 60);
597
598                                        $tz = date_default_timezone_get();
599                                        date_default_timezone_set('UTC');
600                                        $day_CEL = date("d", $message->starttime +  $GMT_CEL);
601                                        $day_EX = date("d", $message->starttime +  $GMT_EX);
602
603                                        if ($day_EX > $day_CEL) $arrayRecur["recur_enddate"] = $message->recurrence->until + $GMT_CEL - $GMT_EX + 86400;
604                                        else if ($day_EX < $day_CEL) $arrayRecur["recur_enddate"] = $message->recurrence->until + $GMT_CEL - $GMT_EX - 86400;
605                                        else $arrayRecur["recur_enddate"] = $message->recurrence->until;
606                                        date_default_timezone_set($tz);
607                                        /*$arrayRecur["recur_enddate"] = $message->recurrence->until - $offsetTZ;
608                                         $hour = date("G", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60));
609                                         $min = date("i", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60));
610                                         $sec = date("s", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60));
611                                               
612                                         $arrayRecur["recur_enddate"] = $message->recurrence->until + ($hour * 3600) + ($min * 60) + $sec + $offsetTZ + (($tz["bias"] - $tz["dstbias"]) * 60);*/
613                                } else {
614                                        $arrayRecur["recur_enddate"] = 1893283200; // Se nao tem data de termino seta para 30/12/2029
615                                }
616                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_enddate: '.$arrayRecur["recur_enddate"]);
617
618                                // Trata excecoes da recorrencia
619                                if (isset($message->exceptions)){
620                                        // Tem Excecoes de recorrencia do tipo Edicao
621                                        // Verifica se ja existe o registro do evento de excecao de recorrencia na tabela phpgw_cal
622                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento tem exceção de recorrência');
623                                        $recur_exception_changed_ids = "";
624                                        $recur_exception_deleted_starttimes = "";
625                                        foreach ($message->exceptions as $recur_exception) {
626                                                if ($recur_exception->deleted == 0){ //Tem Excecoes do Tipo Edicao
627                                                        $found_recur_exception_changed = true;
628                                                        if (isset($arrayExceptCal)) unset($arrayExceptCal);
629                                                        if (isset($arrayExceptCalUser)) unset($arrayExceptCalUser);
630                                                        if (isset($except_cal_id)) unset($except_cal_id);
631                                                        if (isset($except_cal_type_from_DB)) unset($except_cal_type_from_DB);
632                                                        if (isset($except_description_from_DB)) unset($except_description_from_DB);
633                                                        $found_except_cal_id = false;
634                                                        $found_except_cal_user = false;
635                                                        $result = pg_query($this->db, "select cal_id, cal_type, description from phpgw_cal where reference = " . $id . " and datetime = " . $recur_exception->exceptionstarttime . ";");
636                                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
637                                                        // tenta localizar cal_id para fazer Update
638                                                        while ($row = pg_fetch_row($result)) {
639                                                                if(isset($row[0])) {
640                                                                        $except_cal_id = $row[0];
641                                                                        $except_cal_type_from_DB = $row[1];
642                                                                        $except_description_from_DB = $row[2];
643                                                                        $found_except_cal_id = true;
644                                                                        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');
645                                                                }
646                                                        }
647                                                        // Verifica se ja existe o registro do evento de excecao de recorrencia na tabela phpgw_cal_user
648                                                        if (isset($except_cal_id)) {
649                                                                $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 . "';");
650                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
651                                                                if ($row = pg_fetch_row($result)) {
652                                                                        if(isset($row[0])) {
653                                                                                $found_except_cal_user = true;
654                                                                                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');
655                                                                        }
656                                                                }
657                                                        }
658                                                        //Insere/Atualiza tabela phpgw_cal
659                                                        $arrayExceptCal["reference"] = $cal_id;
660                                                        if(isset($message->uid)) {
661                                                                $arrayExceptCal["uid"] = $this->truncateString(utf8_decode($message->uid),255);
662                                                                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> uid: '.$arrayExceptCal["uid"]);
663                                                        }
664                                                        if(isset($recur_exception->subject)) {
665                                                                $arrayExceptCal["title"] = $this->truncateString(utf8_decode($recur_exception->subject),299);
666                                                        } elseif(isset($message->subject)) {
667                                                                $arrayExceptCal["title"] = $this->truncateString(utf8_decode($message->subject),299);
668                                                        }
669                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> title: '.$arrayExceptCal["title"]);
670                                                        if(isset($recur_exception->location)) {
671                                                                $arrayExceptCal["location"] = $this->truncateString(utf8_decode($recur_exception->location),255);
672                                                        } else if(isset($message->location)) {
673                                                                $arrayExceptCal["location"] = $this->truncateString(utf8_decode($message->location),255);
674                                                        }
675                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> location: '.$arrayExceptCal["location"]);
676                                                        if(isset($recur_exception->dtstamp)) {
677                                                                $arrayExceptCal["mdatetime"] = $recur_exception->dtstamp;
678                                                        } elseif(isset($message->dtstamp)) {
679                                                                $arrayExceptCal["mdatetime"] = $message->dtstamp;
680                                                        }
681                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> mdatetime: '.$arrayExceptCal["mdatetime"]);
682                                                        if(isset($recur_exception->starttime)) {
683                                                                $arrayExceptCal["datetime"] = $recur_exception->starttime;
684                                                        } else if(isset($message->starttime)) {
685                                                                $arrayExceptCal["datetime"] = $message->starttime;
686                                                        }
687                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> datetime: '.$arrayExceptCal["datetime"]);
688                                                        if(isset($recur_exception->endtime)) {
689                                                                $arrayExceptCal["edatetime"] = $recur_exception->endtime;
690                                                        }elseif(isset($message->endtime)) {
691                                                                $arrayExceptCal["edatetime"] = $message->endtime;
692                                                        }
693                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> edatetime: '.$arrayExceptCal["edatetime"]);
694                                                        if(isset($recur_exception->sensitivity) and $recur_exception->sensitivity == 0) {
695                                                                $arrayExceptCal["is_public"] = 1; // 1 - Normal
696                                                        }elseif (isset($recur_exception->sensitivity) and $recur_exception->sensitivity == 1){
697                                                                $arrayExceptCal["is_public"] = 0; // 0 - Privado
698                                                        }elseif(isset($message->sensitivity) and $message->sensitivity == 0) {
699                                                                $arrayExceptCal["is_public"] = 1; // 1 - Normal
700                                                        }else $arrayExceptCal["is_public"] = 0; // 0 - Privado
701                                                        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"]);
702                                                        if (isset($recur_exception->body)) {
703                                                                $arrayExceptCal["description"] = utf8_decode($recur_exception->body);
704                                                        } elseif (!isset($except_description_from_DB)) {
705                                                                if (isset($message->rtf)) {
706                                                                        $rtf_to_ascii = new rtf();
707                                                                        $rtf_to_ascii->output("ascii");
708                                                                        $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf));
709                                                                        if ($result_loadrtf == true) $rtf_to_ascii->parse();
710                                                                        $arrayExceptCal["description"] = $rtf_to_ascii->out;
711                                                                } elseif (isset($description_from_DB)) {
712                                                                        $arrayExceptCal["description"] = utf8_decode($description_from_DB);
713                                                                }
714                                                        }
715                                                        $arrayExceptCal["category"] = '';
716                                                        if (isset($recur_exception->categories)) {
717                                                                foreach ($recur_exception->categories as $category) {
718                                                                        $cat_id = $this->addCategory($category);
719                                                                        if ($cat_id != false) {
720                                                                                if ($arrayExceptCal["category"] == '') {
721                                                                                        $arrayExceptCal["category"] = $cat_id;
722                                                                                } else {
723                                                                                        $arrayExceptCal["category"] .= ',' . $cat_id;
724                                                                                }
725                                                                        }
726                                                                }
727                                                        }elseif (isset($message->categories)) {
728                                                                foreach ($message->categories as $category) {
729                                                                        $cat_id = $this->addCategory($category);
730                                                                        if ($cat_id != false) {
731                                                                                if ($arrayExceptCal["category"] == '') {
732                                                                                        $arrayExceptCal["category"] = $cat_id;
733                                                                                } else {
734                                                                                        $arrayExceptCal["category"] .= ',' . $cat_id;
735                                                                                }
736                                                                        }
737                                                                }
738                                                        }
739                                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> category: '.$arrayExceptCal["category"]);
740                                                        //TODO: Converter eventos que sao alldayevent para iniciar as 0:00hs e terminar as 23:59hs. Isso porque o Expresso nao suporta alldayevents
741                                                        //               if(isset($message->alldayevent)) {
742                                                        //                      $arrayCal["alldayevent"] = $this->truncateString(utf8_decode($message->alldayevent),30);
743                                                        //               }
744                                                        if (!$found_except_cal_id){
745                                                                $result = pg_query("select nextval('seq_phpgw_cal');");
746                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
747                                                                $except_cal_id = pg_fetch_result($result, 0, 0);
748                                                                $arrayExceptCal["cal_id"] = $except_cal_id;
749                                                                $arrayExceptCal["owner"] = $this->_uidnumber;
750                                                                $arrayExceptCal["cal_type"] = 'E';
751                                                                $result = pg_insert($this->db, 'phpgw_cal', $arrayExceptCal);
752                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
753                                                                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"]);
754                                                        } else {
755                                                                $result = pg_update($this->db, 'phpgw_cal', $arrayExceptCal, array('cal_id' => $except_cal_id));
756                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
757                                                                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');
758                                                        }
759
760                                                        // Insere/Atualiza Excecoes de Recorrencia na tabela phpgw_cal_user
761                                                        $arrayExceptCalUser["cal_type"] = 'u';
762                                                        if (!$found_except_cal_user){
763                                                                $arrayExceptCalUser["cal_id"] = $except_cal_id;
764                                                                $arrayExceptCalUser["cal_login"] = $this->_uidnumber;
765                                                                //TODO: Tratar os outros valores de cal_status
766                                                                $arrayExceptCalUser["cal_status"] = 'A';
767                                                                $result = pg_insert($this->db, 'phpgw_cal_user', $arrayExceptCalUser);
768                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
769                                                                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"]);
770                                                        } else {
771                                                                $result = pg_update($this->db, 'phpgw_cal_user', $arrayExceptCalUser, array('cal_id' => $except_cal_id, 'cal_login' => $this->_uidnumber));
772                                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
773                                                                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');
774                                                        }
775                                                        if ($recur_exception_changed_ids == "") {
776                                                                $recur_exception_changed_ids = $except_cal_id;
777                                                        } else {
778                                                                $recur_exception_changed_ids .= "," . $except_cal_id;
779                                                        }
780                                                } else {
781                                                        if ($recur_exception_deleted_starttimes == "") {
782                                                                $recur_exception_deleted_starttimes = $recur_exception->exceptionstarttime;
783                                                        } else {
784                                                                $recur_exception_deleted_starttimes .= "," . $recur_exception->exceptionstarttime;
785                                                        }
786                                                }
787                                        }
788                                        if ($recur_exception_deleted_starttimes != "") {
789                                                //Tem Excecoes de recorrencia do tipo Exclusao
790                                                $arrayRecur["recur_exception"] = $recur_exception_deleted_starttimes;
791                                                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);
792                                        } else {
793                                                $arrayRecur["recur_exception"] = "";
794                                                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');
795                                        }
796                                        if ($recur_exception_changed_ids == "") {
797                                                // Se nao tem excecoes de recorrencia do tipo edicao, entao deleta as excecoes da recorrencia
798                                                $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");");
799                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
800                                                $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";");
801                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
802                                                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.');
803                                        } else {
804                                                //Deleta as excecoes da recorrencia, exceto as inseridas/atualizadas acima
805                                                $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 . "));");
806                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
807                                                $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . " and cal_id not in (" . $recur_exception_changed_ids . ");");
808                                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
809                                                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);
810                                        }
811                                } else {
812                                        // Se nao tem excecoes da recorrencia entao
813                                        $arrayRecur["recur_exception"] = "";
814                                        $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");");
815                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
816                                        $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";");
817                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
818                                        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..');
819                                }
820                                if (!$found_cal_repeats){
821                                        $arrayRecur["cal_id"] = $cal_id;
822                                        $result = pg_insert($this->db, 'phpgw_cal_repeats', $arrayRecur);
823                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
824                                        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"]);
825                                } else {
826                                        $result = pg_update($this->db, 'phpgw_cal_repeats', $arrayRecur, array('cal_id' => $cal_id));
827                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
828                                        if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência ATUALIZADA na tabela phpgw_cal_repeats');
829                                }
830                        } elseif ($found_cal_id) {
831                                // Se nao tem recorrencia entao
832                                $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");");
833                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
834                                $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";");
835                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
836                                $result = pg_query($this->db, "delete from phpgw_cal_repeats where cal_id = " . $cal_id . ";");
837                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
838                                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');
839                        }
840                        $result = pg_query($this->db,"COMMIT;");
841                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
842                        //TODO: Implementar Participantes
843                } catch (Exception $e) {
844                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
845                        pg_query($this->db,"ROLLBACK;");
846                        return false;
847                }
848                if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Fim normal da Função');
849                return $id;
850        }
851
852        function ChangeMessage($folderid, $id, $message) {
853                debugLog('CalendarExpresso::ChangeMessage('.$folderid.', '.$id.', ..)');
854                $id = $this->ChangeMessageDAO($id, $message);
855                if ($id != false) return $this->StatMessage($folderid, $id);
856                else return false;
857        }
858
859        function MoveMessage($folderid, $id, $newfolderid) {
860                return false;
861        }
862
863        function addCategory($category) {
864                $cat_id = false;
865                try {
866                        $result = pg_query($this->db,"BEGIN;");
867                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
868                        $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)))) . "';");
869                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
870                        if (!($cat_id = pg_fetch_result($result, 0, 0))){
871                                $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)))) . "';");
872                                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
873                                if (!($cat_id = pg_fetch_result($result, 0, 0))){
874                                        $result = pg_query("select nextval('seq_phpgw_categories');");
875                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
876                                        $cat_id = pg_fetch_result($result, 0, 0);
877                                        $arrayCat["cat_id"] = $cat_id;
878                                        $arrayCat["cat_owner"] = $this->_uidnumber;
879                                        $arrayCat["cat_access"] = 'public';
880                                        $arrayCat["cat_appname"] = 'calendar';
881                                        $arrayCat["cat_name"] = utf8_decode($category);
882                                        $arrayCat["cat_description"] = '';
883                                        $arrayCat["cat_data"] = 'N;';
884                                        $arrayCat["last_mod"] = time();
885                                        $result = pg_insert($this->db, 'phpgw_categories', $arrayCat);
886                                        if ($result == FALSE) throw new Exception(pg_last_error($this->db));
887                                }
888                        }
889                } catch (Exception $e) {
890                        pg_query($this->db,"ROLLBACK;");
891                        debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
892                        return false;
893                }
894                return $cat_id;
895        }
896
897        // -----------------------------------
898
899        function escape($data){
900                if (is_array($data)) {
901                        foreach ($data as $key => $val) {
902                                $data[$key] = $this->escape($val);
903                        }
904                        return $data;
905                }
906                $data = str_replace("\r\n", "\n", $data);
907                $data = str_replace("\r", "\n", $data);
908                $data = str_replace(array('\\', ';', ',', "\n"), array('\\\\', '\\;', '\\,', '\\n'), $data);
909                return $data;
910        }
911
912        function unescape($data){
913                $data = str_replace(array('\\\\', '\\;', '\\,', '\\n','\\N'),array('\\', ';', ',', "\n", "\n"),$data);
914                return $data;
915        }
916
917        function  removeAccents($data){
918                $data = strtr($data,"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞßàáâãÀåÊçÚéêëìíîïðñòóÎõö÷ÞùÌúßÿ","aaaaaaaceeeeiiii noooooxouuutbaaaaaaaceeeeiiii nooooo/ouuuty");
919                return $data;
920        }
921
922        function truncateString($string, $size)
923        {
924                if(strlen($string) <= $size) return $string;
925                else return substr($string, 0, $size - 1);
926        }
927
928        function parseUser($id_user)
929        {
930                $pos = strripos($id_user, '\\');
931                if ($pos === false) {
932                        if (strlen($id_user) < 1) return false;
933                        else return $id_user;
934                } else {
935                        if (strlen($id_user) <= $pos + 1) {
936                                return false;
937                        } else {
938                                return substr(substr($id_user, $pos + 1), 0, strlen(substr($id_user, $pos + 1)));
939                        }
940                }
941        }
942
943        function _getGMTTZ() {
944                //$tz = array("bias" => 0, "stdbias" => 0, "dstbias" => 0, "dstendyear" => 0, "dstendmonth" => 2, "dstendday" => 0, "dstendweek" => 2, "dstendhour" => 2, "dstendminute" => 0, "dstendsecond" => 0, "dstendmillis" => 0,
945                //"dststartyear" => 0, "dststartmonth" =>10, "dststartday" =>0, "dststartweek" => 3, "dststarthour" => 2, "dststartminute" => 0, "dststartsecond" => 0, "dststartmillis" => 0);
946                $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);
947               
948                return $tz;
949        }
950
951        // Unpack timezone info from Sync
952        function _getTZFromSyncBlob($data) {
953                $tz = unpack(    "lbias/a64name/vdstendyear/vdstendmonth/vdstendday/vdstendweek/vdstendhour/vdstendminute/vdstendsecond/vdstendmillis/" .
954                        "lstdbias/a64name/vdststartyear/vdststartmonth/vdststartday/vdststartweek/vdststarthour/vdststartminute/vdststartsecond/vdststartmillis/" .
955                        "ldstbias", $data);
956
957                // Make the structure compatible with class.recurrence.php
958                $tz["timezone"] = $tz["bias"];
959                $tz["timezonedst"] = $tz["dstbias"];
960
961                return $tz;
962        }
963
964        // Pack timezone info for Sync
965        function _getSyncBlobFromTZ($tz) {
966                $packed = pack("la64vvvvvvvv" . "la64vvvvvvvv" . "l",
967                $tz["bias"], "", 0, $tz["dstendmonth"], $tz["dstendday"], $tz["dstendweek"], $tz["dstendhour"], $tz["dstendminute"], $tz["dstendsecond"], $tz["dstendmillis"],
968                $tz["stdbias"], "", 0, $tz["dststartmonth"], $tz["dststartday"], $tz["dststartweek"], $tz["dststarthour"], $tz["dststartminute"], $tz["dststartsecond"], $tz["dststartmillis"],
969                $tz["dstbias"]);
970
971                return $packed;
972        }
973
974        // Authenticate user and return UIDNumber attribute on success
975        function authUser($user, $pwd) {
976                $ldap = new AuthLDAP();
977                $uid_number = ($ldap->bind($user,$pwd));
978                $ldap->disconnect();
979                unset($ldap);
980                if (! $uid_number) return false;
981                return $uid_number;
982        }
983};
984?>
Note: See TracBrowser for help on using the repository browser.