db = dbconnect(); if (!$this->db) { echo "Erro de conexao com o banco.\n"; exit; } } function Logon($username, $domain, $password) { $this->_uidnumber = $this->authUser($this->parseUser($username), $password); if(! $this->_uidnumber) return false; else return true; } function Setup($user, $devid, $protocolversion) { $this->_user = $user; $this->_devid = $devid; $this->_protocolversion = $protocolversion; return true; } function SendMail($rfc822, $forward = false, $reply = false, $parent = false) { return false; } function GetWasteBasket() { return false; } function GetMessageList($folderid, $cutoffdate) { debugLog('CalendarExpresso::GetMessageList('.$this->_uidnumber.', '.$cutoffdate.')'); 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); if ($folderid != "calendar") return false; $cal_ids = null; $messages = array(); try { $result = pg_query($this->db,"BEGIN;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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;"); 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 . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); while ($row = pg_fetch_row($result)) { 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].')'); $result_recur = pg_query($this->db,"select recur_enddate from phpgw_cal_repeats where cal_id = " . $row[0] . ";"); if ($result_recur == FALSE) throw new Exception(pg_last_error($this->db)); if ($row[3] == 'M') { if ($recur_enddate = pg_fetch_result($result_recur, 0, 0)) { 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); if ($recur_enddate < $row[2]) { 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'); 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. } } } $LatestUpdate = $row[1]; $message = array(); $message["id"] = $row[0]; $message["mod"] = substr($LatestUpdate, 0, strlen($LatestUpdate)-3); $message["flags"] = 1; // always 'read' $messages[] = $message; if ($cal_ids === null) $cal_ids = $row[0]; else $cal_ids = $cal_ids . ',' . $row[0]; } // Eventos com reference invalidos 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.");"); 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 .";"); if ($result_invalid_ref == FALSE) throw new Exception(pg_last_error($this->db)); while ($row_invalid_ref = pg_fetch_row($result_invalid_ref)) { 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].')'); } // Evento fora da faixa filtrada if ($cutoffdate !== 0) { $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 .";"); if ($result_out_cutoffdate == FALSE) throw new Exception(pg_last_error($this->db)); while ($row_out_cutoffdate = pg_fetch_row($result_out_cutoffdate)) { 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].')'); } } $result = pg_query($this->db,"COMMIT;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); } catch (Exception $e) { pg_query($this->db,"ROLLBACK;"); debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine()); } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageList-> Fim normal da função'); return $messages; } function GetFolderList() { debugLog('CalendarExpresso::GetFolderList()'); $folder = $this->StatFolder("calendar"); return $folder; } function GetFolder($id) { debugLog('CalendarExpresso::GetFolder('.$id.')'); if($id == "calendar") { $folder = new SyncFolder(); $folder->serverid = $id; $folder->parentid = "0"; $folder->displayname = "Calendario"; $folder->type = SYNC_FOLDER_TYPE_APPOINTMENT; return $folder; } else return false; } function StatFolder($id) { debugLog('CalendarExpresso::StatFolder('.$id.')'); $folder = $this->GetFolder($id); $stat = array(); $stat["id"] = $id; $stat["parent"] = $folder->parentid; $stat["mod"] = $folder->displayname; return $stat; } function GetAttachmentData($attname) { return false; } function StatMessage($folderid, $id) { debugLog('CalendarExpresso::StatMessage('.$folderid.', '.$id.')'); if($folderid != "calendar") return false; try { $result = pg_query($this->db,"BEGIN;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result_calendar = pg_query($this->db, "select last_update from phpgw_cal where cal_id = " . $id . ";"); if ($result_calendar == FALSE) throw new Exception(pg_last_error($this->db)); while ($row_calendar = pg_fetch_row($result_calendar)) { if(isset($row_calendar[0])) { $message = array(); $message["mod"] = substr($row_calendar[0], 0, strlen($row_calendar[0])-3); $message["id"] = $id; $message["flags"] = 1; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::StatMessage-> mod: '.$message["mod"].', id: '.$message["id"]); return $message; } } $result = pg_query($this->db,"COMMIT;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); } catch (Exception $e) { pg_query($this->db,"ROLLBACK;"); debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine()); } 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.'); return false; } function GetMessageDAO($id) { debugLog('CalendarExpresso::GetMessageDAO('.$id.', ..)'); if(trim($id == "")) return false; $message = new SyncAppointment(); try { $has_parent_event = false; $result = pg_query($this->db,"BEGIN;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); //Evento $result = pg_query($this->db,"select config_value from phpgw_config WHERE config_name = 'hostname' AND config_app = 'phpgwapi';"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $uid = "-@" . pg_fetch_result($result, 0, 0) . "-" . $id; $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 . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($row = pg_fetch_row($result)) { 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].')'); if ($row[7] != 0) $has_parent_event = true; else $has_parent_event = false; if (!$has_parent_event) { $message->fileas = $id; $message->uid = utf8_encode($uid); if(isset($row[3])) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $message->dtstamp = $row[3]; // phpgw_cal.mdatetime date_default_timezone_set($tz); } if(isset($row[4])) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $message->starttime = $row[4]; // phpgw_cal.datetime date_default_timezone_set($tz); } if(isset($row[5])) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $message->endtime = $row[5]; // phpgw_cal.edatetime date_default_timezone_set($tz); } } if ($has_parent_event) { $message->exceptionstarttime = $row[4]; $message->deleted = 0; } if(isset($row[1])) { $message->subject = utf8_encode($row[1]); // phpgw_cal.title } if(isset($row[2])) { $message->location = utf8_encode($row[2]); // phpgw_cal.location } if(isset($row[6]) and $row[6] != "") { $message->body = utf8_encode(str_replace('\\n', chr(13) . chr(10), $this->escape($row[6]))); // phpgw_cal.description $message->bodysize = strlen($message->body); $message->bodytruncated = 0; } if (isset($row[8]) and $row[8] == 1) $message->sensitivity = 0; // 0 - Normal else $message->sensitivity = 2; // 2 - Privado if (isset($row[9]) and $row[9] != "") { $result = pg_query($this->db,"select cat_name from phpgw_categories WHERE cat_id in(" . $row[9] . ");"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); while ($cat_name = pg_fetch_row($result)) { if (!isset($message->categories)) $message->categories = array(); array_push($message->categories, utf8_encode($cat_name[0])); } } $message->alldayevent = 0; // (0 - Não(default), 1- Sim) $message->busystatus = 2; // 2 - Ocupado //TODO: Tratar $message - timezone //$tz = $this->_getGMTTZ(); $tz = array("bias" => 180, "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); $message->timezone = base64_encode($this->_getSyncBlobFromTZ($tz)); //TODO: Se necessario, tratar $message - meetingstatus //TODO: Se necessario, tratar AppointmentReplyTime e ResponseType } //Alarme do Evento - O alarme nao sera sincronizado por enquanto. /* Esse exemplo sincroniza o alarme mais distante do evento com o dispositivo movel * $result = pg_query("select data from phpgw_async where id like 'cal:" . $id . ":%' and data like '%enabled%' order by next desc;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($data = pg_fetch_result($result, 0, 0)) { $array_data = unserialize($data); $offset = $array_data["offset"]; if (isset($array_data["offset"])) { if ($offset >= 60) $message->reminder = intval($offset / 60); else $message->reminder = 0; } }*/ if (!$has_parent_event) { //Recorrencia do evento //TODO: Implementar recorrencia mensal por dia e anual por dia, recur - type 3 e 6 respectivamente. O Expresso ainda nao suporta isso. :( $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);"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($row = pg_fetch_row($result)){ 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].')'); $recur = new SyncRecurrence(); // Converte os tipos do Expresso para os tipos do Protocolo ActiveSync switch ($row[0]) { case 1: //repeticao diaria $recur->type = 0; break; case 2: //repeticao semanal $recur->type = 1; break; case 3: //repeticao mensal por data $recur->type = 2; break; case 5: //repeticao anual por data $recur->type = 5; break; } if (isset($row[2])) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $recur->until = $row[2]; date_default_timezone_set($tz); } if (isset($row[3]) and $row[3] != 0) $recur->interval = $row[3]; else $recur->interval = 1; //TODO: Se o Expresso estiver utilizando o campo phpgw_cal_repeats.recur_use_end, implementar. if ($recur->type == 1 or $recur->type == 3 or $recur->type == 6) { if (isset($row[4])) $recur->dayofweek = $row[4]; } if ($recur->type == 2 or $recur->type == 5) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $array_startdatetime = getdate($message->starttime); $recur->dayofmonth = $array_startdatetime['mday']; date_default_timezone_set($tz); } if ($recur->type == 5 or $recur->type == 6) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $array_startdatetime = getdate($message->starttime); $recur->monthofyear = $array_startdatetime['mon']; date_default_timezone_set($tz); } $message->recurrence = $recur; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::GetMessageDAO-> Fim do Bloco - Lê recorrência do evento.'); } //Eventos Unicos da Recorrencia Editados $result = pg_query($this->db, "select cal_id from phpgw_cal where reference = " . $id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); while ($row_recur_exception = pg_fetch_row($result)) { 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]); $recur_exception = $this->GetMessageDAO($row_recur_exception[0]); if ($recur_exception instanceof SyncAppointment) { if (!isset($message->exceptions)) $message->exceptions = array(); array_push($message->exceptions, $recur_exception); } 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]); } //Eventos Unicos da Recorrencia Deletados if (isset($row[5]) and $row[5] != "") { $array_timestamps_recur_deleted = explode(",",$row[5]); foreach ($array_timestamps_recur_deleted as $timestamp_recur_deleted) { 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); $recur_deleted = new SyncAppointment(); $recur_deleted->deleted = '1'; $recur_deleted->exceptionstarttime = (integer)$timestamp_recur_deleted; if (!isset($message->exceptions)) $message->exceptions = array(); array_push($message->exceptions, $recur_deleted); } } //TODO: Tratar Participantes do Evento } $result = pg_query($this->db,"COMMIT;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); } catch (Exception $e) { pg_query($this->db,"ROLLBACK;"); debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine()); return; } 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); return $message; } function GetMessage($folderid, $id, $truncsize, $mimesupport = 0) { debugLog('CalendarExpresso::GetMessage('.$folderid.', '.$id.', ..)'); if($folderid != "calendar") return; if(trim($id == "")) return; $message = $this->GetMessageDAO($id); return $message; } function DeleteMessage($folderid, $id) { debugLog('CalendarExpresso::DeleteMessage('.$folderid.', '.$id.', ..)'); if (!isset($id)) return false; $result = pg_query($this->db, "select owner from phpgw_cal where cal_id = " . $id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($this->_uidnumber != pg_fetch_result($result, 0, 0)) return false; try { $result = pg_query($this->db,"BEGIN;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_delete($this->db, "phpgw_cal_user", array('cal_id' => $id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_delete($this->db, "phpgw_cal", array('reference' => $id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_delete($this->db, "phpgw_cal_repeats", array('cal_id' => $id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query("delete from phpgw_async where id like 'cal:" . $id . "%';"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_delete($this->db, "phpgw_cal_extra", array('cal_id' => $id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_delete($this->db, "phpgw_cal", array('cal_id' => $id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query($this->db,"COMMIT;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); } catch (Exception $e) { pg_query($this->db,"ROLLBACK;"); debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine()); return false; } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog("CalendarExpresso::DeleteMessage-> Fim normal da Função."); return true; } function SetReadFlag($folderid, $id, $flags) { return false; } function ChangeMessageDAO($id, $message) { debugLog('CalendarExpresso::ChangeMessageDAO('.$id.', ..)'); 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); try { $result = pg_query($this->db,"BEGIN;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $found_cal_id = false; $found_cal_user = false; $found_cal_repeats = false; if ($id != false) { $result = pg_query($this->db, "select cal_id, cal_type, owner, description from phpgw_cal where cal_id = " . $id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); // tenta localizar cal_id para fazer Update while ($row = pg_fetch_row($result)) { if(isset($row[0])) { if ($this->_uidnumber != $row[2]) return false; // Nao atualiza evento de outro proprietario $cal_id = $row[0]; $cal_type_from_DB = $row[1]; $description_from_DB = $row[3]; $found_cal_id = true; 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'); } } // Verifica se ja existe o registro do evento na tabela phpgw_cal_user $result = pg_query($this->db, "select cal_id, cal_login from phpgw_cal_user where cal_id = " . $cal_id . " and cal_login = '" . $this->_uidnumber . "';"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($row = pg_fetch_row($result)) { if(isset($row[0])) { $found_cal_user = true; 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'); } } // Verifica se ja existe o registro de recorrencia do evento na tabela phpgw_cal_repeats $result = pg_query($this->db, "select cal_id from phpgw_cal_repeats where cal_id = " . $cal_id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($row = pg_fetch_row($result)) { if(isset($row[0])) { $found_cal_repeats = true; 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'); } } } //Insere/Atualiza tabela phpgw_cal if(isset($message->uid)) { $arrayCal["uid"] = $this->truncateString(utf8_decode($message->uid),255); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> uid: '.$arrayCal["uid"]); } if(isset($message->subject)) { $arrayCal["title"] = $this->truncateString(utf8_decode($message->subject),299); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> title: '.$arrayCal["title"]); } if(isset($message->location)) { $arrayCal["location"] = $this->truncateString(utf8_decode($message->location),255); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> location: '.$arrayCal["location"]); } if(isset($message->dtstamp)) { $arrayCal["mdatetime"] = $message->dtstamp; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> mdatetime: '.$arrayCal["mdatetime"]); } if(isset($message->starttime)) { $arrayCal["datetime"] = $message->starttime; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> datetime: '.$arrayCal["datetime"]); } if(isset($message->endtime)) { $arrayCal["edatetime"] = $message->endtime; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> edatetime: '.$arrayCal["edatetime"]); } if(isset($message->sensitivity) and $message->sensitivity == 0) { $arrayCal["is_public"] = 1; // 1 - Normal } else $arrayCal["is_public"] = 0; // 0 - Privado if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> is_public: '.$arrayCal["is_public"]); if(isset($message->rtf)) { $rtf_to_ascii = new rtf(); $rtf_to_ascii->output("ascii"); $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf)); if ($result_loadrtf == true) $rtf_to_ascii->parse(); $arrayCal["description"] = $rtf_to_ascii->out; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> description: '.$arrayCal["description"]); // } else { // $arrayCal["description"] = ''; } $arrayCal["category"] = ''; if (isset($message->categories)) { foreach ($message->categories as $category) { $cat_id = $this->addCategory($category); if ($cat_id != false) { if ($arrayCal["category"] == '') { $arrayCal["category"] = $cat_id; } else { $arrayCal["category"] .= ',' . $cat_id; } } } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> category: '.$arrayCal["category"]); } $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone)); //TODO: Atribuir valores para ex_participants $arrayCal["ex_participants"] = ''; //TODO: Converter eventos que sao alldayevent para iniciar as 0:00hs e terminar as 23:59hs. Isso porque o Expresso nao suporta alldayevents // if(isset($message->alldayevent)) { // $arrayCal["alldayevent"] = $this->truncateString(utf8_decode($message->alldayevent),30); // } if (!$found_cal_id){ $result = pg_query("select nextval('seq_phpgw_cal');"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $cal_id = pg_fetch_result($result, 0, 0); $arrayCal["cal_id"] = $cal_id; $arrayCal["owner"] = $this->_uidnumber; if (isset($message->recurrence)) $arrayCal["cal_type"] = 'M'; else $arrayCal["cal_type"] = 'E'; $result = pg_insert($this->db, 'phpgw_cal', $arrayCal); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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"]); } else { if (isset($cal_type_from_DB)) { if (isset($message->recurrence)) $arrayCal["cal_type"] = 'M'; else if ($cal_type_from_DB == 'M') $arrayCal["cal_type"] = 'E'; } $result = pg_update($this->db, 'phpgw_cal', $arrayCal, array('cal_id' => $cal_id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento ATUALIZADO na tabela phpgw_cal'); } // Insere/Atualiza tabela phpgw_cal_user $arrayCalUser["cal_type"] = 'u'; if (!$found_cal_user){ $arrayCalUser["cal_id"] = $cal_id; $arrayCalUser["cal_login"] = $this->_uidnumber; //TODO: Tratar os outros valores de cal_status $arrayCalUser["cal_status"] = 'A'; $result = pg_insert($this->db, 'phpgw_cal_user', $arrayCalUser); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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"]); } else { $result = pg_update($this->db, 'phpgw_cal_user', $arrayCalUser, array('cal_id' => $cal_id, 'cal_login' => $this->_uidnumber)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento ATUALIZADO na tabela phpgw_cal_user'); } if (!$id) { $id = $cal_id; } //TODO: Implementar para os tipos 3 e 6. O Expresso ainda nao suporta esses tipos :-( if (isset($message->recurrence) and ($message->recurrence->type == 0 or $message->recurrence->type == 1 or $message->recurrence->type == 2 or $message->recurrence->type == 5)) { if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> O Evento é Recorrente.'); switch ($message->recurrence->type) { case 0: //repeticao diaria $arrayRecur["recur_type"] = 1; $type_name = "day"; break; case 1: //repeticao semanal $arrayRecur["recur_type"] = 2; $type_name = "week"; break; case 2: //repeticao mensal por data $arrayRecur["recur_type"] = 3; $type_name = "month"; break; case 5: //repeticao anual por data $arrayRecur["recur_type"] = 5; $type_name = "year"; break; } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_type: '.$arrayRecur["recur_type"]); if (isset($message->recurrence->interval)) { $arrayRecur["recur_interval"] = $message->recurrence->interval; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_interval: '.$arrayRecur["recur_interval"]); } if ($message->recurrence->type == 1 or $message->recurrence->type == 3 or $message->recurrence->type == 6) { if (isset($message->recurrence->dayofweek)) { $arrayRecur["recur_data"] = $message->recurrence->dayofweek; if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_data: '.$arrayRecur["recur_data"]); /*$day = $message->recurrence->dayofweek; $day_of_week_counter = 0; if (($day & 1) > 0) $day_of_week_counter++; if (($day & 2) > 0) $day_of_week_counter++; if (($day & 4) > 0) $day_of_week_counter++; if (($day & 8) > 0) $day_of_week_counter++; if (($day & 16) > 0) $day_of_week_counter++; if (($day & 32) > 0) $day_of_week_counter++; if (($day & 64) > 0) $day_of_week_counter++;*/ } } //TODO: Converter ocurrences para until. /*if (!isset($message->recurrence->until) and (isset($message->recurrence->occurrences))) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $message->recurrence->until = strtotime(date("Y-m-d H:i:s", $message->starttime) . " +" . $message->recurrence->occurrences * $message->recurrence->interval . " " . $type_name); unset($message->recurrence->occurrences); date_default_timezone_set($tz); }*/ if (isset($message->recurrence->until)){ $defaultTZ = new DateTimeZone(date_default_timezone_get()); $gmtTZ = new DateTimeZone('GMT'); $gmtDate = new DateTime("now", $gmtTZ); $GMT_EX = $defaultTZ->getOffset($gmtDate); $GMT_CEL = -(($tz_CEL["bias"] + $tz_CEL["dstbias"]) * 60); $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $day_CEL = date("d", $message->starttime + $GMT_CEL); $day_EX = date("d", $message->starttime + $GMT_EX); if ($day_EX > $day_CEL) $arrayRecur["recur_enddate"] = $message->recurrence->until + $GMT_CEL - $GMT_EX + 86400; else if ($day_EX < $day_CEL) $arrayRecur["recur_enddate"] = $message->recurrence->until + $GMT_CEL - $GMT_EX - 86400; else $arrayRecur["recur_enddate"] = $message->recurrence->until; date_default_timezone_set($tz); /*$arrayRecur["recur_enddate"] = $message->recurrence->until - $offsetTZ; $hour = date("G", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60)); $min = date("i", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60)); $sec = date("s", $message->starttime - (($tz["bias"] - $tz["dstbias"]) * 60)); $arrayRecur["recur_enddate"] = $message->recurrence->until + ($hour * 3600) + ($min * 60) + $sec + $offsetTZ + (($tz["bias"] - $tz["dstbias"]) * 60);*/ } else { $arrayRecur["recur_enddate"] = 1893283200; // Se nao tem data de termino seta para 30/12/2029 } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência-> recur_enddate: '.$arrayRecur["recur_enddate"]); // Trata excecoes da recorrencia if (isset($message->exceptions)){ // Tem Excecoes de recorrencia do tipo Edicao // Verifica se ja existe o registro do evento de excecao de recorrencia na tabela phpgw_cal if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Evento tem exceção de recorrência'); $recur_exception_changed_ids = ""; $recur_exception_deleted_starttimes = ""; foreach ($message->exceptions as $recur_exception) { if ($recur_exception->deleted == 0){ //Tem Excecoes do Tipo Edicao $found_recur_exception_changed = true; if (isset($arrayExceptCal)) unset($arrayExceptCal); if (isset($arrayExceptCalUser)) unset($arrayExceptCalUser); if (isset($except_cal_id)) unset($except_cal_id); if (isset($except_cal_type_from_DB)) unset($except_cal_type_from_DB); if (isset($except_description_from_DB)) unset($except_description_from_DB); $found_except_cal_id = false; $found_except_cal_user = false; $result = pg_query($this->db, "select cal_id, cal_type, description from phpgw_cal where reference = " . $id . " and datetime = " . $recur_exception->exceptionstarttime . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); // tenta localizar cal_id para fazer Update while ($row = pg_fetch_row($result)) { if(isset($row[0])) { $except_cal_id = $row[0]; $except_cal_type_from_DB = $row[1]; $except_description_from_DB = $row[2]; $found_except_cal_id = true; 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'); } } // Verifica se ja existe o registro do evento de excecao de recorrencia na tabela phpgw_cal_user if (isset($except_cal_id)) { $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 . "';"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if ($row = pg_fetch_row($result)) { if(isset($row[0])) { $found_except_cal_user = true; 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'); } } } //Insere/Atualiza tabela phpgw_cal $arrayExceptCal["reference"] = $cal_id; if(isset($message->uid)) { $arrayExceptCal["uid"] = $this->truncateString(utf8_decode($message->uid),255); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> uid: '.$arrayExceptCal["uid"]); } if(isset($recur_exception->subject)) { $arrayExceptCal["title"] = $this->truncateString(utf8_decode($recur_exception->subject),299); } elseif(isset($message->subject)) { $arrayExceptCal["title"] = $this->truncateString(utf8_decode($message->subject),299); } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> title: '.$arrayExceptCal["title"]); if(isset($recur_exception->location)) { $arrayExceptCal["location"] = $this->truncateString(utf8_decode($recur_exception->location),255); } else if(isset($message->location)) { $arrayExceptCal["location"] = $this->truncateString(utf8_decode($message->location),255); } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> location: '.$arrayExceptCal["location"]); if(isset($recur_exception->dtstamp)) { $arrayExceptCal["mdatetime"] = $recur_exception->dtstamp; } elseif(isset($message->dtstamp)) { $arrayExceptCal["mdatetime"] = $message->dtstamp; } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> mdatetime: '.$arrayExceptCal["mdatetime"]); if(isset($recur_exception->starttime)) { $arrayExceptCal["datetime"] = $recur_exception->starttime; } else if(isset($message->starttime)) { $arrayExceptCal["datetime"] = $message->starttime; } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> datetime: '.$arrayExceptCal["datetime"]); if(isset($recur_exception->endtime)) { $arrayExceptCal["edatetime"] = $recur_exception->endtime; }elseif(isset($message->endtime)) { $arrayExceptCal["edatetime"] = $message->endtime; } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> edatetime: '.$arrayExceptCal["edatetime"]); if(isset($recur_exception->sensitivity) and $recur_exception->sensitivity == 0) { $arrayExceptCal["is_public"] = 1; // 1 - Normal }elseif (isset($recur_exception->sensitivity) and $recur_exception->sensitivity == 1){ $arrayExceptCal["is_public"] = 0; // 0 - Privado }elseif(isset($message->sensitivity) and $message->sensitivity == 0) { $arrayExceptCal["is_public"] = 1; // 1 - Normal }else $arrayExceptCal["is_public"] = 0; // 0 - Privado 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"]); if (isset($recur_exception->body)) { $arrayExceptCal["description"] = utf8_decode($recur_exception->body); } elseif (!isset($except_description_from_DB)) { if (isset($message->rtf)) { $rtf_to_ascii = new rtf(); $rtf_to_ascii->output("ascii"); $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf)); if ($result_loadrtf == true) $rtf_to_ascii->parse(); $arrayExceptCal["description"] = $rtf_to_ascii->out; } elseif (isset($description_from_DB)) { $arrayExceptCal["description"] = utf8_decode($description_from_DB); } } $arrayExceptCal["category"] = ''; if (isset($recur_exception->categories)) { foreach ($recur_exception->categories as $category) { $cat_id = $this->addCategory($category); if ($cat_id != false) { if ($arrayExceptCal["category"] == '') { $arrayExceptCal["category"] = $cat_id; } else { $arrayExceptCal["category"] .= ',' . $cat_id; } } } }elseif (isset($message->categories)) { foreach ($message->categories as $category) { $cat_id = $this->addCategory($category); if ($cat_id != false) { if ($arrayExceptCal["category"] == '') { $arrayExceptCal["category"] = $cat_id; } else { $arrayExceptCal["category"] .= ',' . $cat_id; } } } } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Exceção De Recorrência-> category: '.$arrayExceptCal["category"]); //TODO: Converter eventos que sao alldayevent para iniciar as 0:00hs e terminar as 23:59hs. Isso porque o Expresso nao suporta alldayevents // if(isset($message->alldayevent)) { // $arrayCal["alldayevent"] = $this->truncateString(utf8_decode($message->alldayevent),30); // } if (!$found_except_cal_id){ $result = pg_query("select nextval('seq_phpgw_cal');"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $except_cal_id = pg_fetch_result($result, 0, 0); $arrayExceptCal["cal_id"] = $except_cal_id; $arrayExceptCal["owner"] = $this->_uidnumber; $arrayExceptCal["cal_type"] = 'E'; $result = pg_insert($this->db, 'phpgw_cal', $arrayExceptCal); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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"]); } else { $result = pg_update($this->db, 'phpgw_cal', $arrayExceptCal, array('cal_id' => $except_cal_id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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'); } // Insere/Atualiza Excecoes de Recorrencia na tabela phpgw_cal_user $arrayExceptCalUser["cal_type"] = 'u'; if (!$found_except_cal_user){ $arrayExceptCalUser["cal_id"] = $except_cal_id; $arrayExceptCalUser["cal_login"] = $this->_uidnumber; //TODO: Tratar os outros valores de cal_status $arrayExceptCalUser["cal_status"] = 'A'; $result = pg_insert($this->db, 'phpgw_cal_user', $arrayExceptCalUser); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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"]); } else { $result = pg_update($this->db, 'phpgw_cal_user', $arrayExceptCalUser, array('cal_id' => $except_cal_id, 'cal_login' => $this->_uidnumber)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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'); } if ($recur_exception_changed_ids == "") { $recur_exception_changed_ids = $except_cal_id; } else { $recur_exception_changed_ids .= "," . $except_cal_id; } } else { if ($recur_exception_deleted_starttimes == "") { $recur_exception_deleted_starttimes = $recur_exception->exceptionstarttime; } else { $recur_exception_deleted_starttimes .= "," . $recur_exception->exceptionstarttime; } } } if ($recur_exception_deleted_starttimes != "") { //Tem Excecoes de recorrencia do tipo Exclusao $arrayRecur["recur_exception"] = $recur_exception_deleted_starttimes; 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); } else { $arrayRecur["recur_exception"] = ""; 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'); } if ($recur_exception_changed_ids == "") { // Se nao tem excecoes de recorrencia do tipo edicao, entao deleta as excecoes da recorrencia $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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.'); } else { //Deleta as excecoes da recorrencia, exceto as inseridas/atualizadas acima $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 . "));"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . " and cal_id not in (" . $recur_exception_changed_ids . ");"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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); } } else { // Se nao tem excecoes da recorrencia entao $arrayRecur["recur_exception"] = ""; $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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..'); } if (!$found_cal_repeats){ $arrayRecur["cal_id"] = $cal_id; $result = pg_insert($this->db, 'phpgw_cal_repeats', $arrayRecur); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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"]); } else { $result = pg_update($this->db, 'phpgw_cal_repeats', $arrayRecur, array('cal_id' => $cal_id)); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Recorrência ATUALIZADA na tabela phpgw_cal_repeats'); } } elseif ($found_cal_id) { // Se nao tem recorrencia entao $result = pg_query($this->db, "delete from phpgw_cal_user where cal_id in (select cal_id from phpgw_cal where reference = " . $cal_id . ");"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query($this->db, "delete from phpgw_cal where reference = " . $cal_id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $result = pg_query($this->db, "delete from phpgw_cal_repeats where cal_id = " . $cal_id . ";"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); 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'); } $result = pg_query($this->db,"COMMIT;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); //TODO: Implementar Participantes } catch (Exception $e) { debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine()); pg_query($this->db,"ROLLBACK;"); return false; } if (TRACE_UID !== false and (TRACE_TYPE == 'CALENDAR' or TRACE_TYPE == 'ALL')) traceLog('CalendarExpresso::ChangeMessageDAO-> Fim normal da Função'); return $id; } function ChangeMessage($folderid, $id, $message) { debugLog('CalendarExpresso::ChangeMessage('.$folderid.', '.$id.', ..)'); $id = $this->ChangeMessageDAO($id, $message); if ($id != false) return $this->StatMessage($folderid, $id); else return false; } function MoveMessage($folderid, $id, $newfolderid) { return false; } function addCategory($category) { $cat_id = false; try { $result = pg_query($this->db,"BEGIN;"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $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)))) . "';"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if (!($cat_id = pg_fetch_result($result, 0, 0))){ $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)))) . "';"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); if (!($cat_id = pg_fetch_result($result, 0, 0))){ $result = pg_query("select nextval('seq_phpgw_categories');"); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); $cat_id = pg_fetch_result($result, 0, 0); $arrayCat["cat_id"] = $cat_id; $arrayCat["cat_owner"] = $this->_uidnumber; $arrayCat["cat_access"] = 'public'; $arrayCat["cat_appname"] = 'calendar'; $arrayCat["cat_name"] = utf8_decode($category); $arrayCat["cat_description"] = ''; $arrayCat["cat_data"] = 'N;'; $arrayCat["last_mod"] = time(); $result = pg_insert($this->db, 'phpgw_categories', $arrayCat); if ($result == FALSE) throw new Exception(pg_last_error($this->db)); } } } catch (Exception $e) { pg_query($this->db,"ROLLBACK;"); debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine()); return false; } return $cat_id; } // ----------------------------------- function escape($data){ if (is_array($data)) { foreach ($data as $key => $val) { $data[$key] = $this->escape($val); } return $data; } $data = str_replace("\r\n", "\n", $data); $data = str_replace("\r", "\n", $data); $data = str_replace(array('\\', ';', ',', "\n"), array('\\\\', '\\;', '\\,', '\\n'), $data); return $data; } function unescape($data){ $data = str_replace(array('\\\\', '\\;', '\\,', '\\n','\\N'),array('\\', ';', ',', "\n", "\n"),$data); return $data; } function removeAccents($data){ $data = strtr($data,"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ","aaaaaaaceeeeiiii noooooxouuutbaaaaaaaceeeeiiii nooooo/ouuuty"); return $data; } function truncateString($string, $size) { if(strlen($string) <= $size) return $string; else return substr($string, 0, $size - 1); } function parseUser($id_user) { $pos = strripos($id_user, '\\'); if ($pos === false) { if (strlen($id_user) < 1) return false; else return $id_user; } else { if (strlen($id_user) <= $pos + 1) { return false; } else { return substr(substr($id_user, $pos + 1), 0, strlen(substr($id_user, $pos + 1))); } } } function _getGMTTZ() { //$tz = array("bias" => 0, "stdbias" => 0, "dstbias" => 0, "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); $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); return $tz; } // Unpack timezone info from Sync function _getTZFromSyncBlob($data) { $tz = unpack( "lbias/a64name/vdstendyear/vdstendmonth/vdstendday/vdstendweek/vdstendhour/vdstendminute/vdstendsecond/vdstendmillis/" . "lstdbias/a64name/vdststartyear/vdststartmonth/vdststartday/vdststartweek/vdststarthour/vdststartminute/vdststartsecond/vdststartmillis/" . "ldstbias", $data); // Make the structure compatible with class.recurrence.php $tz["timezone"] = $tz["bias"]; $tz["timezonedst"] = $tz["dstbias"]; return $tz; } // Pack timezone info for Sync function _getSyncBlobFromTZ($tz) { $packed = pack("la64vvvvvvvv" . "la64vvvvvvvv" . "l", $tz["bias"], "", 0, $tz["dstendmonth"], $tz["dstendday"], $tz["dstendweek"], $tz["dstendhour"], $tz["dstendminute"], $tz["dstendsecond"], $tz["dstendmillis"], $tz["stdbias"], "", 0, $tz["dststartmonth"], $tz["dststartday"], $tz["dststartweek"], $tz["dststarthour"], $tz["dststartminute"], $tz["dststartsecond"], $tz["dststartmillis"], $tz["dstbias"]); return $packed; } // Authenticate user and return UIDNumber attribute on success function authUser($user, $pwd) { $ldap = new AuthLDAP(); $uid_number = ($ldap->bind($user,$pwd)); $ldap->disconnect(); unset($ldap); if (! $uid_number) return false; return $uid_number; } }; ?>