source: trunk/zpush/backend/expresso/providers/contactProvider.php @ 7631

Revision 7631, 77.1 KB checked in by cristiano, 11 years ago (diff)

Ticket #3209 - Retirado configurações estaticas, comandos desnecessarios do conctactProvider

Line 
1<?php
2include_once(__DIR__.'/../../../lib/default/diffbackend/diffbackend.php');
3
4
5class ExpressoContactProvider extends BackendDiff
6{
7    var $db;
8    var $_uidnumber;
9
10    /**
11     * Returns a list (array) of folders, each entry being an associative array
12     * with the same entries as StatFolder(). This method should return stable information; ie
13     * if nothing has changed, the items in the array must be exactly the same. The order of
14     * the items within the array is not important though.
15     *
16     * @access protected
17     * @return array/boolean        false if the list could not be retrieved
18     */
19    public function GetFolderList()
20    {
21        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->GetFolderList()");
22        return array($this->StatFolder("contacts"));
23    }
24
25    /**
26     * Returns an actual SyncFolder object with all the properties set. Folders
27     * are pretty simple, having only a type, a name, a parent and a server ID.
28     *
29     * @param string        $id           id of the folder
30     *
31     * @access public
32     * @return object   SyncFolder with information
33     */
34    public function GetFolder($id)
35    {
36        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->GetFolder()");
37        if($id == "contacts") {
38            $folder = new SyncFolder();
39            $folder->serverid = $id;
40            $folder->parentid = "0";
41            $folder->displayname = "Contatos";
42            $folder->type = SYNC_FOLDER_TYPE_CONTACT;
43
44            return $folder;
45        }
46        else return false;
47    }
48
49    /**
50     * Returns folder stats. An associative array with properties is expected.
51     *
52     * @param string        $id             id of the folder
53     *
54     * @access public
55     * @return array
56     *          Associative array(
57     *              string  "id"            The server ID that will be used to identify the folder. It must be unique, and not too long
58     *                                      How long exactly is not known, but try keeping it under 20 chars or so. It must be a string.
59     *              string  "parent"        The server ID of the parent of the folder. Same restrictions as 'id' apply.
60     *              long    "mod"           This is the modification signature. It is any arbitrary string which is constant as long as
61     *                                      the folder has not changed. In practice this means that 'mod' can be equal to the folder name
62     *                                      as this is the only thing that ever changes in folders. (the type is normally constant)
63     *          )
64     */
65    public function StatFolder($id)
66    {
67        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->StatFolder()");
68
69        $folder = $this->GetFolder($id);
70
71        $stat = array();
72        $stat["id"] = $id;
73        $stat["parent"] = $folder->parentid;
74        $stat["mod"] = $folder->displayname;
75
76        return $stat;
77    }
78
79    /**
80     * Creates or modifies a folder
81     *
82     * @param string        $folderid       id of the parent folder
83     * @param string        $oldid          if empty -> new folder created, else folder is to be renamed
84     * @param string        $displayname    new folder name (to be created, or to be renamed to)
85     * @param int           $type           folder type
86     *
87     * @access public
88     * @return boolean                      status
89     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
90     *
91     */
92    public function ChangeFolder($folderid, $oldid, $displayname, $type)
93    {
94        // TODO: Implement ChangeFolder() method.
95    }
96
97    /**
98     * Deletes a folder
99     *
100     * @param string        $id
101     * @param string        $parent         is normally false
102     *
103     * @access public
104     * @return boolean                      status - false if e.g. does not exist
105     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
106     */
107    public function DeleteFolder($id, $parentid)
108    {
109        // TODO: Implement DeleteFolder() method.
110    }
111
112    /**
113     * Returns a list (array) of messages, each entry being an associative array
114     * with the same entries as StatMessage(). This method should return stable information; ie
115     * if nothing has changed, the items in the array must be exactly the same. The order of
116     * the items within the array is not important though.
117     *
118     * The $cutoffdate is a date in the past, representing the date since which items should be shown.
119     * This cutoffdate is determined by the user's setting of getting 'Last 3 days' of e-mail, etc. If
120     * the cutoffdate is ignored, the user will not be able to select their own cutoffdate, but all
121     * will work OK apart from that.
122     *
123     * @param string        $folderid       id of the parent folder
124     * @param long          $cutoffdate     timestamp in the past from which on messages should be returned
125     *
126     * @access public
127     * @return array/false                  array with messages or false if folder is not available
128     */
129    public function GetMessageList($folderid, $cutoffdate)
130    {
131        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->GetMessageList()");
132
133        $messages = array();
134        $ids = array();
135        try {
136            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
137            $result = pg_query($this->db, "select given_names, family_names, last_update, id_contact from phpgw_cc_contact where id_owner = " . $this->_uidnumber . ";");
138            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
139            while ($row = pg_fetch_row($result)) {
140                $message = array();
141                $message["id"] = $row[3];
142                $message["mod"] = substr($row[2], 0, strlen($row[2])-3);
143                $message["flags"] = 1; // always 'read'
144                $messages[] = $message;
145            }
146            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
147        } catch (Exception $e) {
148       //     debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
149        }
150
151
152        return $messages;
153    }
154
155    /**
156     * Returns the actual SyncXXX object type. The '$folderid' of parent folder can be used.
157     * Mixing item types returned is illegal and will be blocked by the engine; ie returning an Email object in a
158     * Tasks folder will not do anything. The SyncXXX objects should be filled with as much information as possible,
159     * but at least the subject, body, to, from, etc.
160     *
161     * @param string            $folderid           id of the parent folder
162     * @param string            $id                 id of the message
163     * @param ContentParameters $contentparameters  parameters of the requested message (truncation, mimesupport etc)
164     *
165     * @access public
166     * @return object/false                 false if the message could not be retrieved
167     */
168    public function GetMessage($folderid, $id, $contentparameters)
169    {
170        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->GetMessage()");
171
172        // Parse the database into object
173        $message = new SyncContact();
174        try {
175            $result_contact = pg_query($this->db, "select id_contact, id_owner, id_status, photo, alias, id_prefix, given_names, family_names, names_ordered, id_suffix, birthdate, sex, pgp_key, notes, is_global, last_status, last_update, category, web_page, corporate_name, job_title, department from phpgw_cc_contact where id_contact = " . $id . ";");
176            if ($result_contact == FALSE) throw new Exception(pg_last_error($this->db));
177            while ($row_contact = pg_fetch_row($result_contact)) {
178                //if(isset($row_contact[3])) {
179                //      $message->picture = base64_encode($row_contact[3]);
180                //}
181                if(isset($row_contact[4])) {
182                    $message->nickname = utf8_encode($row_contact[4]);
183                }
184                if(isset($row_contact[7])) {
185                    $arrayFamilyName = explode(' ',trim($row_contact[7]));
186                    if (sizeof($arrayFamilyName) > 1) {
187                        $message->lastname = utf8_encode($arrayFamilyName[sizeof($arrayFamilyName) - 1]);
188                        for ($i = 0; $i < (sizeof($arrayFamilyName) - 1); $i++) {
189                            $message->middlename .= " " . utf8_encode($arrayFamilyName[$i]);
190                        }
191                        $message->middlename = trim($message->middlename);
192                    } else {
193                        $message->lastname = utf8_encode(trim($row_contact[7]));
194                    }
195                    $message->fileas = $message->lastname;
196                }
197                if(isset($row_contact[6])) {
198                    $message->firstname = utf8_encode(trim($row_contact[6]));
199                    if(isset($row_contact[7])) $message->fileas .= ', ' . $message->firstname;
200                    else $message->fileas = $message->firstname;
201                }
202                if(isset($row_contact[10])) {
203                    $dataParte = explode('-',$row_contact[10]);
204                    $data = $dataParte[2] . '-' . $dataParte[1] . '-' . $dataParte[0];
205                    $tz = date_default_timezone_get();
206                    date_default_timezone_set('UTC');
207                    $message->birthday = strtotime($data);
208                    $message->birthday += 3600 * 10; // Soma 10 horas para nao alterar a data quando mudar o Timezone
209                    date_default_timezone_set($tz);
210                }
211                // TODO:Incluir campo de Aniversario na sincronizacao. O BD do Expresso ainda nao tem esse campo :-(
212                if(isset($row_contact[13])) {
213                    $message->body = utf8_encode(str_replace('\\n', chr(13) . chr(10), $this->escape($row_contact[13])));
214                    $message->bodysize = strlen($message->body);
215                    $message->bodytruncated = 0;
216                }
217                //TODO:Tratar o conteudo do campo de categorias
218                //if(isset($row_contact[17])) {
219                //      $message->categories = utf8_encode($row_contact[17]);
220                //}
221                if(isset($row_contact[18])) {
222                    $message->webpage = utf8_encode($row_contact[18]);
223                }
224                if(isset($row_contact[19])) {
225                    $message->companyname = utf8_encode($row_contact[19]);
226                    if (!isset($row_contact[6]) and !isset($row_contact[7])) $message->fileas = $message->companyname;
227                }
228                if(isset($row_contact[20])) {
229                    $message->jobtitle = utf8_encode($row_contact[20]);
230                }
231                if(isset($row_contact[21])) {
232                    $message->department = utf8_encode($row_contact[21]);
233                }
234
235                // Endereço Comercial
236                $result_addresses_comercial = pg_query($this->db,"select co.id_address, co.id_city, city_name, co.id_state, state_symbol, co.id_country, address1, address2, complement, address_other, postal_code, po_box, address_is_default from phpgw_cc_addresses co join phpgw_cc_contact_addrs ca on (co.id_address = ca.id_address) join phpgw_cc_typeof_ct_addrs tca on (ca.id_typeof_contact_address = tca.id_typeof_contact_address) left outer join phpgw_cc_city ci on (ci.id_city = co.id_city) left outer join phpgw_cc_state cs on (cs.id_state = co.id_state) where tca.contact_address_type_name = 'Comercial' and ca.id_contact = " . $row_contact[0] . ";");
237                if ($result_addresses_comercial == FALSE) throw new Exception(pg_last_error($this->db));
238                while ($row_addresses_comercial = pg_fetch_row($result_addresses_comercial)) {
239                    if (isset($row_addresses_comercial[2])) {
240                        $message->businesscity = utf8_encode($row_addresses_comercial[2]);
241                    }
242                    if (isset($row_addresses_comercial[5])) {
243                        $message->businesscountry = utf8_encode($row_addresses_comercial[5]);
244                    }
245                    if (isset($row_addresses_comercial[10])) {
246                        $message->businesspostalcode = utf8_encode($row_addresses_comercial[10]);
247                    }
248                    if (isset($row_addresses_comercial[4])) {
249                        $message->businessstate = utf8_encode($row_addresses_comercial[4]);
250                    }
251                    if (isset($row_addresses_comercial[6])) {
252                        $message->businessstreet = utf8_encode($row_addresses_comercial[6]);
253                    }
254                    if (isset($row_addresses_comercial[8])) {
255                        if (isset($message->businessstreet)) {
256                            $message->businessstreet .= ":";
257                        }
258                        $message->businessstreet .= utf8_encode($row_addresses_comercial[8]);
259                    }
260                    if (isset($row_addresses_comercial[7])) {
261                        if (isset($message->businessstreet)) {
262                            $message->businessstreet .= ":";
263                        }
264                        $message->businessstreet .= utf8_encode($row_addresses_comercial[7]);
265                    }
266                    if (isset($row_addresses_comercial[9])) {
267                        if (isset($message->businessstreet)) {
268                            $message->businessstreet .= ":";
269                        }
270                        $message->businessstreet .= utf8_encode($row_addresses_comercial[9]);
271                    }
272                    if (isset($row_addresses_comercial[11])) {
273                        if (isset($message->businessstreet)) {
274                            $message->businessstreet .= ":";
275                        }
276                        $message->businessstreet .= utf8_encode($row_addresses_comercial[11]);
277                    }
278                }
279                // Endereço Residencial
280                $result_addresses_residencial = pg_query($this->db,"select co.id_address, co.id_city, city_name, co.id_state, state_name, co.id_country, address1, address2, complement, address_other, postal_code, po_box, address_is_default from phpgw_cc_addresses co join phpgw_cc_contact_addrs ca on (co.id_address = ca.id_address) join phpgw_cc_typeof_ct_addrs tca on (ca.id_typeof_contact_address = tca.id_typeof_contact_address) left outer join phpgw_cc_city ci on (ci.id_city = co.id_city) left outer join phpgw_cc_state cs on (cs.id_state = co.id_state) where tca.contact_address_type_name = 'Residencial' and ca.id_contact = " . $row_contact[0] . ";");
281                if ($result_addresses_residencial == FALSE) throw new Exception(pg_last_error($this->db));
282                while ($row_addresses_residencial = pg_fetch_row($result_addresses_residencial)) {
283                    if (isset($row_addresses_residencial[2])) {
284                        $message->homecity = utf8_encode($row_addresses_residencial[2]);
285                    }
286                    if (isset($row_addresses_residencial[5])) {
287                        $message->homecountry = utf8_encode($row_addresses_residencial[5]);
288                    }
289                    if (isset($row_addresses_residencial[10])) {
290                        $message->homepostalcode = utf8_encode($row_addresses_residencial[10]);
291                    }
292                    if (isset($row_addresses_residencial[4])) {
293                        $message->homestate = utf8_encode($row_addresses_residencial[4]);
294                    }
295                    if (isset($row_addresses_residencial[6])) {
296                        $message->homestreet = utf8_encode($row_addresses_residencial[6]);
297                    }
298                    if (isset($row_addresses_residencial[8])) {
299                        if (isset($message->homestreet)) {
300                            $message->homestreet .= ":";
301                        }
302                        $message->homestreet .= utf8_encode($row_addresses_residencial[8]);
303                    }
304                    if (isset($row_addresses_residencial[7])) {
305                        if (isset($message->homestreet)) {
306                            $message->homestreet .= ":";
307                        }
308                        $message->homestreet .= utf8_encode($row_addresses_residencial[7]);
309                    }
310                    if (isset($row_addresses_residencial[9])) {
311                        if (isset($message->homestreet)) {
312                            $message->homestreet .= ":";
313                        }
314                        $message->homestreet .= utf8_encode($row_addresses_residencial[9]);
315                    }
316                    if (isset($row_addresses_residencial[11])) {
317                        if (isset($message->homestreet)) {
318                            $message->homestreet .= ":";
319                        }
320                        $message->homestreet .= utf8_encode($row_addresses_residencial[11]);
321                    }
322                }
323                // Emails
324                $result_emails = pg_query($this->db,"select cn.id_connection, connection_name, connection_value, connection_is_default from phpgw_cc_connections cn join phpgw_cc_contact_conns cc on (cn.id_connection = cc.id_connection) join phpgw_cc_typeof_ct_conns ct on (ct.id_typeof_contact_connection = cc.id_typeof_contact_connection) where ct.contact_connection_type_name = 'Email' and cc.id_contact = "  . $row_contact[0] . ";");
325                if ($result_emails == FALSE) throw new Exception(pg_last_error($this->db));
326                while ($row_emails = pg_fetch_row($result_emails)) {
327                    if ($row_emails[1] == "Principal") {
328                        $message->email1address = utf8_encode($row_emails[2]);
329                    }
330                    if ($row_emails[1] == "Alternativo") {
331                        $message->email2address = utf8_encode($row_emails[2]);
332                    }
333                    //TODO : Atribuir o email3address. O Expresso ainda não tem campo para um terceiro email :(
334                }
335                // Telefones
336                $result_tel = pg_query($this->db,"select cn.id_connection, connection_name, connection_value, connection_is_default from phpgw_cc_connections cn join phpgw_cc_contact_conns cc on (cn.id_connection = cc.id_connection) join phpgw_cc_typeof_ct_conns ct on (ct.id_typeof_contact_connection = cc.id_typeof_contact_connection) where ct.contact_connection_type_name = 'Telefone' and cc.id_contact = "  . $row_contact[0] . ";");
337                if ($result_tel == FALSE) throw new Exception(pg_last_error($this->db));
338                while ($row_tel = pg_fetch_row($result_tel)) {
339                    if ($row_tel[1] == "Trabalho") {
340                        $message->businessphonenumber = utf8_encode($row_tel[2]);
341                    }
342                    if ($row_tel[1] == "Casa") {
343                        $message->homephonenumber = utf8_encode($row_tel[2]);
344                    }
345                    if ($row_tel[1] == "Celular") {
346                        $message->mobilephonenumber = utf8_encode($row_tel[2]);
347                    }
348                    if ($row_tel[1] == "Fax") {
349                        $message->businessfaxnumber = utf8_encode($row_tel[2]);
350                    }
351                    if ($row_tel[1] == "Principal") {
352                        $message->business2phonenumber = utf8_encode($row_tel[2]);
353                    }
354                    if ($row_tel[1] == "Alternativo") {
355                        $message->home2phonenumber = utf8_encode($row_tel[2]);
356                    }
357                    //TODO : Permitir mais de um número de telefone para Trabalho, Casa e Celular. O Expresso ainda não suporta isso :(
358                }
359            }
360        } catch (Exception $e) {
361            debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
362            return;
363        }
364        return $message;
365    }
366
367    /**
368     * Returns message stats, analogous to the folder stats from StatFolder().
369     *
370     * @param string        $folderid       id of the folder
371     * @param string        $id             id of the message
372     *
373     * @access public
374     * @return array or boolean if fails
375     *          Associative array(
376     *              string  "id"            Server unique identifier for the message. Again, try to keep this short (under 20 chars)
377     *              int     "flags"         simply '0' for unread, '1' for read
378     *              long    "mod"           This is the modification signature. It is any arbitrary string which is constant as long as
379     *                                      the message has not changed. As soon as this signature changes, the item is assumed to be completely
380     *                                      changed, and will be sent to the PDA as a whole. Normally you can use something like the modification
381     *                                      time for this field, which will change as soon as the contents have changed.
382     *          )
383     */
384    public function StatMessage($folderid, $id)
385    {
386        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->StatMessage()");
387
388        try {
389            $result = pg_query($this->db,"BEGIN;");
390            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
391            $result_contact = pg_query($this->db, "select last_update from phpgw_cc_contact where id_contact = " . $id . ";");
392            if ($result_contact == FALSE) throw new Exception(pg_last_error($this->db));
393            while ($row_contact = pg_fetch_row($result_contact)) {
394                if(isset($row_contact[0])) {
395                    $message = array();
396                    $message["mod"] = substr($row_contact[0], 0, strlen($row_contact[0])-3);
397                    $message["id"] = $id;
398                    $message["flags"] = 1;
399                    return $message;
400                }
401            }
402            $result = pg_query($this->db,"COMMIT;");
403            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
404        } catch (Exception $e) {
405            pg_query($this->db,"ROLLBACK;");
406            debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
407        }
408        return false;
409    }
410
411    /**
412     * Called when a message has been changed on the mobile. The new message must be saved to disk.
413     * The return value must be whatever would be returned from StatMessage() after the message has been saved.
414     * This way, the 'flags' and the 'mod' properties of the StatMessage() item may change via ChangeMessage().
415     * This method will never be called on E-mail items as it's not 'possible' to change e-mail items. It's only
416     * possible to set them as 'read' or 'unread'.
417     *
418     * @param string        $folderid       id of the folder
419     * @param string        $id             id of the message
420     * @param SyncXXX       $message        the SyncObject containing a message
421     *
422     * @access public
423     * @return array                        same return value as StatMessage()
424     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
425     */
426    public function ChangeMessage($folderid, $id, $message)
427    {
428        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->ChangeMessage()");
429
430        try {
431            $result = pg_query($this->db,"BEGIN;");
432            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
433
434            // Obtem o id_contact
435            $found_id_contact = false;
436            if (trim($id) !== "") {
437                $result_contact = pg_query($this->db, "select id_contact from phpgw_cc_contact where id_contact = " . $id . ";");
438                if ($result_contact == FALSE) throw new Exception(pg_last_error($this->db));
439                // tenta localizar id_contact para fazer Update
440                while ($row_contact = pg_fetch_row($result_contact)) {
441                    if(isset($row_contact[0])) {
442                        $id_contact = $row_contact[0];
443                        $found_id_contact = true;
444                    }
445                }
446            }
447            // se não encontrou id_contact para fazer Update, define o próximo id_contact para fazer Insert
448            if (!isset($id_contact)) {
449                $result = pg_query($this->db,"LOCK TABLE phpgw_cc_contact IN ACCESS EXCLUSIVE MODE;");
450                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
451                $result_contact_max_id = pg_query($this->db, "select max(id_contact) from phpgw_cc_contact;");
452                if ($result_contact_max_id == FALSE) throw new Exception(pg_last_error($this->db));
453                $row_contact_max_id = pg_fetch_row($result_contact_max_id);
454                if (isset($row_contact_max_id[0])) {
455                    $id_contact = $row_contact_max_id[0] + 1;
456                } else $id_contact = 1;
457            }
458
459            // Procura o id_address comercial e residencial
460            $result_address = pg_query($this->db, "select co.id_address, tca.contact_address_type_name from phpgw_cc_addresses co join phpgw_cc_contact_addrs ca on (co.id_address = ca.id_address) join phpgw_cc_typeof_ct_addrs tca on (ca.id_typeof_contact_address = tca.id_typeof_contact_address) where ca.id_contact = " . $id_contact . ";");
461            if ($result_address == FALSE) throw new Exception(pg_last_error($this->db));
462            $found_id_address_comercial = false;
463            $found_id_address_residencial = false;
464            while ($row_address = pg_fetch_row($result_address)) {
465                if(isset($row_address[0])) {
466                    if ($row_address[1] == "Comercial") {
467                        $id_address_comercial = $row_address[0];
468                        $found_id_address_comercial = true;
469                    }
470                    if ($row_address[1] == "Residencial") {
471                        $id_address_residencial = $row_address[0];
472                        $found_id_address_residencial = true;
473                    }
474                }
475            }
476            // Verifica se os campos de endereco estao preenchidos na mensagem recebida do dispositivo movel
477            $isset_business_address_fields = false;
478            if(isset($message->businessstate) or isset($message->businesspostalcode) or isset($message->businessstreet)) {
479                $isset_business_address_fields = true;
480            }
481            $isset_home_address_fields = false;
482            if(isset($message->homestate) or isset($message->homepostalcode) or isset($message->homestreet)) {
483                $isset_home_address_fields = true;
484            }
485            // Obtem o ultimo id_address
486            if (!($found_id_address_comercial and $found_id_address_residencial) and ($isset_business_address_fields or $isset_home_address_fields)) {
487                $result = pg_query($this->db,"LOCK TABLE phpgw_cc_addresses IN ACCESS EXCLUSIVE MODE;");
488                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
489                $result_address_max_id = pg_query($this->db, "select max(id_address) from phpgw_cc_addresses;");
490                if ($result_address_max_id == FALSE) throw new Exception(pg_last_error($this->db));
491                $array_row_address_max_id = pg_fetch_row($result_address_max_id);
492                if (isset($array_row_address_max_id)) $row_address_max_id = $array_row_address_max_id[0];
493                if (!isset($row_address_max_id)) $row_address_max_id = 0;
494            }
495            $next_offset_address_to_insert = 0;
496            // se não encontrou id_address_comercial para fazer Update, define o próximo id_address_comercial para fazer Insert
497            if (!$found_id_address_comercial and $isset_business_address_fields) {
498                $next_offset_address_to_insert += 1;
499                $id_address_comercial = $row_address_max_id + $next_offset_address_to_insert;
500            }
501            // se não encontrou id_address_residencial para fazer Update, define o próximo id_address_residencial para fazer Insert
502            if (!$found_id_address_residencial and $isset_home_address_fields) {
503                $next_offset_address_to_insert += 1;
504                $id_address_residencial = $row_address_max_id + $next_offset_address_to_insert;
505            }
506
507            // Procura o id_connection de Emails e Telefones
508            $result_connection = pg_query($this->db, "select cn.id_connection, connection_name, connection_is_default, cc.id_typeof_contact_connection from phpgw_cc_connections cn join phpgw_cc_contact_conns cc on (cn.id_connection = cc.id_connection) join phpgw_cc_typeof_ct_conns ct on (ct.id_typeof_contact_connection = cc.id_typeof_contact_connection) where cc.id_contact = " . $id_contact . ";");
509            if ($result_connection == FALSE) throw new Exception(pg_last_error($this->db));
510            $found_id_connection_email_principal = false;
511            $found_id_connection_email_alternativo = false;
512            $found_id_connection_tel_trabalho = false;
513            $found_id_connection_tel_casa = false;
514            $found_id_connection_tel_celular = false;
515            $found_id_connection_tel_fax = false;
516            $found_id_connection_tel_principal = false;
517            $found_id_connection_tel_alternativo = false;
518            $tel_default = "";
519            $email_default = "";
520            while ($row_connection = pg_fetch_row($result_connection)) {
521                if(isset($row_connection[0])) {
522                    if ($row_connection[1] == "Principal" and $row_connection[3] == 1) {
523                        $id_connection_email_principal = $row_connection[0];
524                        $found_id_connection_email_principal = true;
525                        if ($row_connection[2] == 't') $email_default = "Principal";
526                    }
527                    if ($row_connection[1] == "Alternativo" and $row_connection[3] == 1) {
528                        $id_connection_email_alternativo = $row_connection[0];
529                        $found_id_connection_email_alternativo = true;
530                        if ($row_connection[2] == 't') $email_default = "Alternativo";
531                    }
532                    if ($row_connection[1] == "Trabalho") {
533                        $id_connection_tel_trabalho = $row_connection[0];
534                        $found_id_connection_tel_trabalho = true;
535                        if ($row_connection[2] == 't') $tel_default = "Trabalho";
536                    }
537                    if ($row_connection[1] == "Casa") {
538                        $id_connection_tel_casa = $row_connection[0];
539                        $found_id_connection_tel_casa = true;
540                        if ($row_connection[2] == 't') $tel_default = "Casa";
541                    }
542                    if ($row_connection[1] == "Celular") {
543                        $id_connection_tel_celular = $row_connection[0];
544                        $found_id_connection_tel_celular = true;
545                        if ($row_connection[2] == 't') $tel_default = "Celular";
546                    }
547                    if ($row_connection[1] == "Fax") {
548                        $id_connection_tel_fax = $row_connection[0];
549                        $found_id_connection_tel_fax = true;
550                        if ($row_connection[2] == 't') $tel_default = "Fax";
551                    }
552                    if ($row_connection[1] == "Principal" and $row_connection[3] == 2) {
553                        $id_connection_tel_principal = $row_connection[0];
554                        $found_id_connection_tel_principal = true;
555                        if ($row_connection[2] == 't') $tel_default = "Principal";
556                    }
557                    if ($row_connection[1] == "Alternativo" and $row_connection[3] == 2) {
558                        $id_connection_tel_alternativo = $row_connection[0];
559                        $found_id_connection_tel_alternativo = true;
560                        if ($row_connection[2] == 't') $tel_default = "Alternativo";
561                    }
562                }
563            }
564            // Obtem o ultimo id_connection
565            if (!($found_id_connection_email_principal and $found_id_connection_email_alternativo and $found_id_connection_tel_trabalho and $found_id_connection_tel_celular and $found_id_connection_tel_casa and $found_id_connection_tel_fax and $found_id_connection_tel_principal and $found_id_connection_tel_alternativo) and (isset($message->email1address) or isset($message->email2address) or isset($message->businessphonenumber) or isset($message->homephonenumber) or isset($message->mobilephonenumber) or isset($message->businessfaxnumber) or isset($message->business2phonenumber) or isset($message->home2phonenumber))){
566                $result = pg_query($this->db,"LOCK TABLE phpgw_cc_connections IN ACCESS EXCLUSIVE MODE;");
567                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
568                $result_connection_max_id = pg_query($this->db, "select max(id_connection) from phpgw_cc_connections;");
569                if ($result_connection_max_id == FALSE) throw new Exception(pg_last_error($this->db));
570                $array_row_connection_max_id = pg_fetch_row($result_connection_max_id);
571                if (isset($array_row_connection_max_id)) $row_connection_max_id = $array_row_connection_max_id[0];
572                if (!isset($row_connection_max_id)) $row_connection_max_id = 0;
573            }
574            $next_offset_connection_to_insert = 0;
575            // se não encontrou id_connection_email_principal para fazer Update, define o próximo id_connection_email_principal para fazer Insert
576            if (!$found_id_connection_email_principal and isset($message->email1address)) {
577                $next_offset_connection_to_insert += 1;
578                $id_connection_email_principal = $row_connection_max_id + $next_offset_connection_to_insert;
579            }
580            // se não encontrou id_connection_email_alternativo para fazer Update, define o próximo id_connection_email_alternativo para fazer Insert
581            if (!$found_id_connection_email_alternativo and isset($message->email2address)) {
582                $next_offset_connection_to_insert += 1;
583                $id_connection_email_alternativo = $row_connection_max_id + $next_offset_connection_to_insert;
584            }
585            // se não encontrou $id_connection_tel_trabalho para fazer Update, define o próximo $id_connection_tel_trabalho para fazer Insert
586            if (!$found_id_connection_tel_trabalho and isset($message->businessphonenumber)) {
587                $next_offset_connection_to_insert += 1;
588                $id_connection_tel_trabalho = $row_connection_max_id + $next_offset_connection_to_insert;
589            }
590            // se não encontrou $id_connection_tel_casa para fazer Update, define o próximo $id_connection_tel_casa para fazer Insert
591            if (!$found_id_connection_tel_casa and isset($message->homephonenumber)) {
592                $next_offset_connection_to_insert += 1;
593                $id_connection_tel_casa = $row_connection_max_id + $next_offset_connection_to_insert;
594            }
595            // se não encontrou $id_connection_tel_celular para fazer Update, define o próximo $id_connection_tel_celular para fazer Insert
596            if (!$found_id_connection_tel_celular and isset($message->mobilephonenumber)) {
597                $next_offset_connection_to_insert += 1;
598                $id_connection_tel_celular = $row_connection_max_id + $next_offset_connection_to_insert;
599            }
600            // se não encontrou $id_connection_tel_fax para fazer Update, define o próximo $id_connection_tel_fax para fazer Insert
601            if (!$found_id_connection_tel_fax and isset($message->businessfaxnumber)) {
602                $next_offset_connection_to_insert += 1;
603                $id_connection_tel_fax = $row_connection_max_id + $next_offset_connection_to_insert;
604            }
605            // se não encontrou $id_connection_tel_principal para fazer Update, define o próximo $id_connection_tel_principal para fazer Insert
606            if (!$found_id_connection_tel_principal and isset($message->business2phonenumber)) {
607                $next_offset_connection_to_insert += 1;
608                $id_connection_tel_principal = $row_connection_max_id + $next_offset_connection_to_insert;
609            }
610            // se não encontrou $id_connection_tel_alternativo para fazer Update, define o próximo $id_connection_tel_alternativo para fazer Insert
611            if (!$found_id_connection_tel_alternativo and isset($message->home2phonenumber)) {
612                $next_offset_connection_to_insert += 1;
613                $id_connection_tel_alternativo = $row_connection_max_id + $next_offset_connection_to_insert;
614            }
615
616            // Incluir/Alterar registro na tabela phpgw_cc_contact no Banco de Dados
617            //if(isset($message->picture)) {
618            //  $arrayContact["photo"] = base64_decode($message->picture);
619            //}
620            if(isset($message->nickname)) {
621                $arrayContact["alias"] = utf8_decode($message->nickname);
622            }
623            if(isset($message->firstname)) {
624                $arrayContact["given_names"] = utf8_decode($message->firstname);
625                $arrayContact["names_ordered"] = utf8_decode($message->firstname);
626            }
627            if (isset($message->middlename)) {
628                $arrayContact["family_names"] = utf8_decode($message->middlename);
629                if(isset($message->firstname)) {
630                    $arrayContact["names_ordered"] .= " ";
631                }
632                $arrayContact["names_ordered"] .= utf8_decode($message->middlename);
633            }
634            if(isset($message->lastname)) {
635                if(isset($message->middlename)) {
636                    $arrayContact["family_names"] .= " ";
637                }
638                if (isset($arrayContact["family_names"])) $arrayContact["family_names"] .= utf8_decode($message->lastname);
639                else $arrayContact["family_names"] = utf8_decode($message->lastname);
640                if(isset($message->firstname) or isset($message->middlename)) {
641                    $arrayContact["names_ordered"] .= " ";
642                }
643                $arrayContact["names_ordered"] .= utf8_decode($message->lastname);
644            }
645            if (isset($message->birthday)) {
646                $tz = date_default_timezone_get();
647                date_default_timezone_set('UTC');
648                $arrayContact["birthdate"] = date("Y-m-d",$message->birthday);
649                date_default_timezone_set($tz);
650            }
651            //TODO: Incluir o campo de Aniversario na Sincronizacao. O DB do Expresso nao tem esse campo :-(
652
653            if(isset($message->rtf)) {
654                $rtf_to_ascii = new rtf();
655                $rtf_to_ascii->output("ascii");
656                $result_loadrtf = $rtf_to_ascii->loadrtf(base64_decode($message->rtf));
657                if ($result_loadrtf == true) $rtf_to_ascii->parse();
658                $arrayContact["notes"] = $rtf_to_ascii->out;
659            }
660            //TODO: Tratar o conteudo do campo de categorias
661            //if(isset($message->categories)) {
662            //  $arrayContact["category"] = $this->truncateString(utf8_decode($message->categories),20);
663            //}
664            if(isset($message->webpage)) {
665                $arrayContact["web_page"] = $this->truncateString(utf8_decode($message->webpage),100);
666            }
667            if(isset($message->companyname)) {
668                $arrayContact["corporate_name"] = $this->truncateString(utf8_decode($message->companyname),100);
669            }
670            if(isset($message->jobtitle)) {
671                $arrayContact["job_title"] = $this->truncateString(utf8_decode($message->jobtitle),40);
672            }
673            if(isset($message->department)) {
674                $arrayContact["department"] = $this->truncateString(utf8_decode($message->department),30);
675            }
676            if (!$found_id_contact){
677                $arrayContact["id_contact"] = $id_contact;
678                $arrayContact["id_owner"] = $this->_uidnumber;
679                $result = pg_insert($this->db, 'phpgw_cc_contact', $arrayContact);
680                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
681            } else {
682                $result = pg_update($this->db, 'phpgw_cc_contact', $arrayContact, array('id_contact' => $id_contact));
683                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
684            }
685
686            // Incluir/Alterar Endereco Comercial na tabela phpgw_cc_addresses no Banco de Dados
687            if(isset($message->businessstate)) {
688                $result = pg_query($this->db, "select id_state, id_country from phpgw_cc_state where LOWER(to_ASCII(state_name)) = '" . trim(strtolower($this->removeAccents(utf8_decode($message->businessstate)))) . "' or LOWER(to_ASCII(state_symbol)) = '" . trim(strtolower($this->removeAccents(utf8_decode($message->businessstate)))) . "';");
689                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
690                $row = pg_fetch_row($result);
691                if(isset($row[0])) {
692                    $arrayAddressComercial["id_state"] = $row[0];
693                }
694                if(isset($row[1])) {
695                    $arrayAddressComercial["id_country"] = $row[1];
696                }
697                if(isset($message->businesscity) and isset($arrayAddressComercial["id_state"])) {
698                    $result = pg_query($this->db, "select id_city from phpgw_cc_city where id_state = " . $arrayAddressComercial["id_state"] . " and LOWER(to_ASCII(city_name)) = '" . trim(strtolower($this->removeAccents(utf8_decode($message->businesscity)))) . "';");
699                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
700                    $row = pg_fetch_row($result);
701                    if(isset($row[0])) {
702                        $arrayAddressComercial["id_city"] = $row[0];
703                    }
704                }
705            }
706            if(isset($message->businesspostalcode)) {
707                $arrayAddressComercial["postal_code"] = $this->truncateString(utf8_decode($message->businesspostalcode),15);
708            }
709            if(isset($message->businessstreet)) {
710                $arrayAddressComercial["address1"] = $this->truncateString(utf8_decode($message->businessstreet),60);
711            }
712            if($isset_business_address_fields) {
713                if (!$found_id_address_comercial) {
714                    $arrayAddressComercial["id_address"] = $id_address_comercial;
715                    $result = pg_insert($this->db, 'phpgw_cc_addresses', $arrayAddressComercial);
716                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
717                    $arrayContactAddressComercial["id_contact"] = $id_contact;
718                    $arrayContactAddressComercial["id_address"] = $id_address_comercial;
719                    $arrayContactAddressComercial["id_typeof_contact_address"] = 1; //comercial
720                    $result = pg_insert($this->db, 'phpgw_cc_contact_addrs', $arrayContactAddressComercial);
721                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
722                } else {
723                    $result = pg_update($this->db, 'phpgw_cc_addresses', $arrayAddressComercial, array('id_address' => $id_address_comercial));
724                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
725                }
726            } elseif ($found_id_address_comercial) {
727                $result = pg_delete($this->db, "phpgw_cc_contact_addrs", array('id_contact' => $id_contact, 'id_address' => $id_address_comercial));
728                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
729                $result = pg_delete($this->db, "phpgw_cc_addresses", array('id_address' => $id_address_comercial));
730                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
731            }
732
733            // Incluir/Alterar Endereco Residencial na tabela phpgw_cc_addresses no Banco de Dados
734            if(isset($message->homestate)) {
735                $result = pg_query($this->db, "select id_state, id_country from phpgw_cc_state where LOWER(to_ASCII(state_name)) = '" . trim(strtolower($this->removeAccents(utf8_decode($message->homestate)))) . "' or LOWER(to_ASCII(state_symbol)) = '" . trim(strtolower($this->removeAccents(utf8_decode($message->homestate)))) . "';");
736                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
737                $row = pg_fetch_row($result);
738                if(isset($row[0])) {
739                    $arrayAddressResidencial["id_state"] = $row[0];
740                }
741                if(isset($row[1])) {
742                    $arrayAddressResidencial["id_country"] = $row[1];
743                }
744                if(isset($message->homecity) and isset($arrayAddressResidencial["id_state"])) {
745                    $result = pg_query($this->db, "select id_city from phpgw_cc_city where id_state = " . $arrayAddressResidencial["id_state"] . " and LOWER(to_ASCII(city_name)) = '" . trim(strtolower($this->removeAccents(utf8_decode($message->homecity)))) . "';");
746                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
747                    $row = pg_fetch_row($result);
748                    if(isset($row[0])) {
749                        $arrayAddressResidencial["id_city"] = $row[0];
750                    }
751                }
752            }
753            if(isset($message->homepostalcode)) {
754                $arrayAddressResidencial["postal_code"] = $this->truncateString(utf8_decode($message->homepostalcode),15);
755            }
756            if(isset($message->homestreet)) {
757                $arrayAddressResidencial["address1"] = $this->truncateString(utf8_decode($message->homestreet),60);
758            }
759            if($isset_home_address_fields) {
760                if (!$found_id_address_residencial) {
761                    $arrayAddressResidencial["id_address"] = $id_address_residencial;
762                    $result = pg_insert($this->db, 'phpgw_cc_addresses', $arrayAddressResidencial);
763                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
764                    $arrayContactAddressResidencial["id_contact"] = $id_contact;
765                    $arrayContactAddressResidencial["id_address"] = $id_address_residencial;
766                    $arrayContactAddressResidencial["id_typeof_contact_address"] = 2; //residencial
767                    $result = pg_insert($this->db, 'phpgw_cc_contact_addrs', $arrayContactAddressResidencial);
768                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
769                } else {
770                    $result = pg_update($this->db, 'phpgw_cc_addresses', $arrayAddressResidencial, array('id_address' => $id_address_residencial));
771                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
772                }
773            } elseif ($found_id_address_residencial) {
774                $result = pg_delete($this->db, "phpgw_cc_contact_addrs", array('id_contact' => $id_contact, 'id_address' => $id_address_residencial));
775                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
776                $result = pg_delete($this->db, "phpgw_cc_addresses", array('id_address' => $id_address_residencial));
777                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
778            }
779
780            // Email Principal
781            if(isset($message->email1address)) {
782                $arrayConnectionEmailPrincipal["connection_value"] = $this->truncateString($this->formatMail(utf8_decode($message->email1address)),100);
783                if (!$found_id_connection_email_principal){
784                    $arrayConnectionEmailPrincipal["id_connection"] = $id_connection_email_principal;
785                    $arrayConnectionEmailPrincipal["connection_name"] = "Principal";
786                    if ($email_default != "Alternativo"){
787                        $arrayConnectionEmailPrincipal["connection_is_default"] = 't';
788                        $email_default = "Principal";
789                    } else {
790                        $arrayConnectionEmailPrincipal["connection_is_default"] = 'f';
791                    }
792                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionEmailPrincipal);
793                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
794                    $arrayContactConnection["id_contact"] = $id_contact;
795                    $arrayContactConnection["id_connection"] = $id_connection_email_principal;
796                    $arrayContactConnection["id_typeof_contact_connection"] = 1;
797                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
798                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
799                } else {
800                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionEmailPrincipal, array('id_connection' => $id_connection_email_principal));
801                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
802                }
803
804            } elseif ($found_id_connection_email_principal) {
805                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_email_principal));
806                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
807                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_email_principal));
808                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
809                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_email_principal));
810                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
811            }
812
813            // Email Alternativo
814            if(isset($message->email2address)) {
815                $arrayConnectionEmailAlternativo["connection_value"] = $this->truncateString($this->formatMail(utf8_decode($message->email2address)),100);
816                if (!$found_id_connection_email_alternativo){
817                    $arrayConnectionEmailAlternativo["id_connection"] = $id_connection_email_alternativo;
818                    $arrayConnectionEmailAlternativo["connection_name"] = "Alternativo";
819                    if ($email_default != "Principal"){
820                        $arrayConnectionEmailAlternativo["connection_is_default"] = 't';
821                        $email_default = "Alternativo";
822                    } else {
823                        $arrayConnectionEmailAlternativo["connection_is_default"] = 'f';
824                    }
825                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionEmailAlternativo);
826                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
827                    $arrayContactConnection["id_contact"] = $id_contact;
828                    $arrayContactConnection["id_connection"] = $id_connection_email_alternativo;
829                    $arrayContactConnection["id_typeof_contact_connection"] = 1;
830                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
831                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
832                } else {
833                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionEmailAlternativo, array('id_connection' => $id_connection_email_alternativo));
834                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
835                }
836
837            } elseif ($found_id_connection_email_alternativo) {
838                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_email_alternativo));
839                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
840                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_email_alternativo));
841                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
842                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_email_alternativo));
843                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
844            }
845            //TODO : Atribuir o email3address. O Expresso ainda não tem campo para um terceiro email :(
846
847            // Telefone Trabalho
848            if(isset($message->businessphonenumber)) {
849                $arrayConnectionTelTrabalho["connection_value"] = $this->truncateString(utf8_decode($message->businessphonenumber),100);
850                if (!$found_id_connection_tel_trabalho){
851                    $arrayConnectionTelTrabalho["id_connection"] = $id_connection_tel_trabalho;
852                    $arrayConnectionTelTrabalho["connection_name"] = "Trabalho";
853                    if ($tel_default != "Celular" and $tel_default != "Casa" and $tel_default != "Fax"  and $tel_default != "Principal"  and $tel_default != "Alternativo"){
854                        $arrayConnectionTelTrabalho["connection_is_default"] = 't';
855                        $tel_default = "Trabalho";
856                    } else {
857                        $arrayConnectionTelTrabalho["connection_is_default"] = 'f';
858                    }
859                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionTelTrabalho);
860                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
861                    $arrayContactConnection["id_contact"] = $id_contact;
862                    $arrayContactConnection["id_connection"] = $id_connection_tel_trabalho;
863                    $arrayContactConnection["id_typeof_contact_connection"] = 2;
864                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
865                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
866                } else {
867                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionTelTrabalho, array('id_connection' => $id_connection_tel_trabalho));
868                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
869                }
870
871            } elseif ($found_id_connection_tel_trabalho) {
872                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_tel_trabalho));
873                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
874                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_tel_trabalho));
875                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
876                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_tel_trabalho));
877                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
878            }
879
880            // Telefone Celular
881            if(isset($message->mobilephonenumber)) {
882                $arrayConnectionTelCelular["connection_value"] = $this->truncateString(utf8_decode($message->mobilephonenumber),100);
883                if (!$found_id_connection_tel_celular){
884                    $arrayConnectionTelCelular["id_connection"] = $id_connection_tel_celular;
885                    $arrayConnectionTelCelular["connection_name"] = "Celular";
886                    if ($tel_default != "Trabalho" and $tel_default != "Casa" and $tel_default != "Fax"   and $tel_default != "Principal"  and $tel_default != "Alternativo"){
887                        $arrayConnectionTelCelular["connection_is_default"] = 't';
888                        $tel_default = "Celular";
889                    } else {
890                        $arrayConnectionTelCelular["connection_is_default"] = 'f';
891                    }
892                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionTelCelular);
893                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
894                    $arrayContactConnection["id_contact"] = $id_contact;
895                    $arrayContactConnection["id_connection"] = $id_connection_tel_celular;
896                    $arrayContactConnection["id_typeof_contact_connection"] = 2;
897                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
898                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
899                } else {
900                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionTelCelular, array('id_connection' => $id_connection_tel_celular));
901                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
902                }
903
904            } elseif ($found_id_connection_tel_celular) {
905                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_tel_celular));
906                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
907                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_tel_celular));
908                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
909                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_tel_celular));
910                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
911            }
912
913            // Telefone Casa
914            if(isset($message->homephonenumber)) {
915                $arrayConnectionTelCasa["connection_value"] = $this->truncateString(utf8_decode($message->homephonenumber),100);
916                if (!$found_id_connection_tel_casa){
917                    $arrayConnectionTelCasa["id_connection"] = $id_connection_tel_casa;
918                    $arrayConnectionTelCasa["connection_name"] = "Casa";
919                    if ($tel_default != "Trabalho" and $tel_default != "Celular" and $tel_default != "Fax" and $tel_default != "Principal"  and $tel_default != "Alternativo"){
920                        $arrayConnectionTelCasa["connection_is_default"] = 't';
921                        $tel_default = "Casa";
922                    } else {
923                        $arrayConnectionTelCasa["connection_is_default"] = 'f';
924                    }
925                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionTelCasa);
926                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
927                    $arrayContactConnection["id_contact"] = $id_contact;
928                    $arrayContactConnection["id_connection"] = $id_connection_tel_casa;
929                    $arrayContactConnection["id_typeof_contact_connection"] = 2;
930                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
931                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
932                } else {
933                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionTelCasa, array('id_connection' => $id_connection_tel_casa));
934                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
935                }
936
937            } elseif ($found_id_connection_tel_casa) {
938                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_tel_casa));
939                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
940                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_tel_casa));
941                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
942                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_tel_casa));
943                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
944            }
945
946            // Fax
947            if(isset($message->businessfaxnumber)) {
948                $arrayConnectionFax["connection_value"] = $this->truncateString(utf8_decode($message->businessfaxnumber),100);
949                if (!$found_id_connection_tel_fax){
950                    $arrayConnectionFax["id_connection"] = $id_connection_tel_fax;
951                    $arrayConnectionFax["connection_name"] = "Fax";
952                    if ($tel_default != "Trabalho" and $tel_default != "Celular" and $tel_default != "Casa" and $tel_default != "Principal"  and $tel_default != "Alternativo"){
953                        $arrayConnectionFax["connection_is_default"] = 't';
954                        $tel_default = "Fax";
955                    } else {
956                        $arrayConnectionFax["connection_is_default"] = 'f';
957                    }
958                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionFax);
959                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
960                    $arrayContactConnection["id_contact"] = $id_contact;
961                    $arrayContactConnection["id_connection"] = $id_connection_tel_fax;
962                    $arrayContactConnection["id_typeof_contact_connection"] = 2;
963                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
964                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
965                } else {
966                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionFax, array('id_connection' => $id_connection_tel_fax));
967                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
968                }
969
970            } elseif ($found_id_connection_tel_fax) {
971                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_tel_fax));
972                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
973                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_tel_fax));
974                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
975                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_tel_fax));
976                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
977            }
978
979            // Telefone Principal
980            if(isset($message->business2phonenumber)) {
981                $arrayConnectionTelPrincipal["connection_value"] = $this->truncateString(utf8_decode($message->business2phonenumber),100);
982                if (!$found_id_connection_tel_principal){
983                    $arrayConnectionTelPrincipal["id_connection"] = $id_connection_tel_principal;
984                    $arrayConnectionTelPrincipal["connection_name"] = "Principal";
985                    if ($tel_default != "Celular" and $tel_default != "Casa" and $tel_default != "Fax"  and $tel_default != "Trabalho"  and $tel_default != "Alternativo"){
986                        $arrayConnectionTelPrincipal["connection_is_default"] = 't';
987                        $tel_default = "Principal";
988                    } else {
989                        $arrayConnectionTelPrincipal["connection_is_default"] = 'f';
990                    }
991                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionTelPrincipal);
992                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
993                    $arrayContactConnection["id_contact"] = $id_contact;
994                    $arrayContactConnection["id_connection"] = $id_connection_tel_principal;
995                    $arrayContactConnection["id_typeof_contact_connection"] = 2;
996                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
997                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
998                } else {
999                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionTelPrincipal, array('id_connection' => $id_connection_tel_principal));
1000                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1001                }
1002
1003            } elseif ($found_id_connection_tel_principal) {
1004                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_tel_principal));
1005                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1006                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_tel_principal));
1007                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1008                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_tel_principal));
1009                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1010            }
1011
1012            // Telefone Alternativo
1013            if(isset($message->home2phonenumber)) {
1014                $arrayConnectionTelAlternativo["connection_value"] = $this->truncateString(utf8_decode($message->home2phonenumber),100);
1015                if (!$found_id_connection_tel_alternativo){
1016                    $arrayConnectionTelAlternativo["id_connection"] = $id_connection_tel_alternativo;
1017                    $arrayConnectionTelAlternativo["connection_name"] = "Alternativo";
1018                    if ($tel_default != "Trabalho" and $tel_default != "Celular" and $tel_default != "Fax" and $tel_default != "Principal"  and $tel_default != "Casa"){
1019                        $arrayConnectionTelAlternativo["connection_is_default"] = 't';
1020                        $tel_default = "Alternativo";
1021                    } else {
1022                        $arrayConnectionTelAlternativo["connection_is_default"] = 'f';
1023                    }
1024                    $result = pg_insert($this->db, 'phpgw_cc_connections', $arrayConnectionTelAlternativo);
1025                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1026                    $arrayContactConnection["id_contact"] = $id_contact;
1027                    $arrayContactConnection["id_connection"] = $id_connection_tel_alternativo;
1028                    $arrayContactConnection["id_typeof_contact_connection"] = 2;
1029                    $result = pg_insert($this->db, 'phpgw_cc_contact_conns', $arrayContactConnection);
1030                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1031                } else {
1032                    $result = pg_update($this->db, 'phpgw_cc_connections', $arrayConnectionTelAlternativo, array('id_connection' => $id_connection_tel_alternativo));
1033                    if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1034                }
1035
1036            } elseif ($found_id_connection_tel_alternativo) {
1037                $result = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact, 'id_connection' => $id_connection_tel_alternativo));
1038                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1039                $result = pg_delete($this->db, "phpgw_cc_contact_grps", array('id_connection' => $id_connection_tel_alternativo));
1040                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1041                $result = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection_tel_alternativo));
1042                if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1043            }
1044
1045            //TODO : Permitir mais de um número de telefone para Trabalho, Celular e Casa. O Expresso ainda não suporta isso :(
1046
1047            $result = pg_query($this->db,"COMMIT;");
1048            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1049            if (!$id) {
1050                $id = $id_contact;
1051            }
1052        } catch (Exception $e) {
1053            debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
1054            pg_query($this->db,"ROLLBACK;");
1055            return false;
1056        }
1057        return $this->StatMessage($folderid, $id);
1058    }
1059
1060    /**
1061     * Changes the 'read' flag of a message on disk. The $flags
1062     * parameter can only be '1' (read) or '0' (unread). After a call to
1063     * SetReadFlag(), GetMessageList() should return the message with the
1064     * new 'flags' but should not modify the 'mod' parameter. If you do
1065     * change 'mod', simply setting the message to 'read' on the mobile will trigger
1066     * a full resync of the item from the server.
1067     *
1068     * @param string        $folderid       id of the folder
1069     * @param string        $id             id of the message
1070     * @param int           $flags          read flag of the message
1071     *
1072     * @access public
1073     * @return boolean                      status of the operation
1074     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1075     */
1076    public function SetReadFlag($folderid, $id, $flags)
1077    {
1078
1079        // TODO: Implement SetReadFlag() method.
1080    }
1081
1082    /**
1083     * Called when the user has requested to delete (really delete) a message. Usually
1084     * this means just unlinking the file its in or somesuch. After this call has succeeded, a call to
1085     * GetMessageList() should no longer list the message. If it does, the message will be re-sent to the mobile
1086     * as it will be seen as a 'new' item. This means that if this method is not implemented, it's possible to
1087     * delete messages on the PDA, but as soon as a sync is done, the item will be resynched to the mobile
1088     *
1089     * @param string        $folderid       id of the folder
1090     * @param string        $id             id of the message
1091     *
1092     * @access public
1093     * @return boolean                      status of the operation
1094     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1095     */
1096    public function DeleteMessage($folderid, $id)
1097    {
1098        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->DeleteMessage()");
1099        $result = pg_query($this->db,"BEGIN;");
1100        try {
1101            $result_contact = pg_query($this->db, "select id_contact from phpgw_cc_contact where id_contact = " . $id . ";");
1102            if ($result_contact == FALSE) throw new Exception(pg_last_error($this->db));
1103            while ($row_contact = pg_fetch_row($result_contact)) {
1104                if(isset($row_contact[0])) {
1105                    $id_contact = $row_contact[0];
1106                }
1107            }
1108            if(!isset($id_contact)){
1109                return true;
1110            }
1111
1112            $result_contact_addrs = pg_query($this->db, "select id_address from phpgw_cc_contact_addrs where id_contact = " . $id_contact . ";");
1113            if ($result_contact_addrs == FALSE) throw new Exception(pg_last_error($this->db));
1114            while ($row_contact_addrs = pg_fetch_row($result_contact_addrs)) {
1115                if(isset($row_contact_addrs[0])) {
1116                    $id_address = $row_contact_addrs[0];
1117                    $result_delete_address = pg_delete($this->db, "phpgw_cc_addresses", array('id_address' => $id_address));
1118                    if ($result_delete_address == FALSE) throw new Exception(pg_last_error($this->db));
1119                }
1120            }
1121
1122            $result_delete_contact_addrs = pg_delete($this->db, "phpgw_cc_contact_addrs", array('id_contact' => $id_contact));
1123            if ($result_delete_contact_addrs == FALSE) throw new Exception(pg_last_error($this->db));
1124
1125            $result_contact_conns = pg_query($this->db, "select id_connection from phpgw_cc_contact_conns where id_contact = " . $id_contact . ";");
1126            if ($result_contact_conns == FALSE) throw new Exception(pg_last_error($this->db));
1127            while ($row_contact_conns = pg_fetch_row($result_contact_conns)) {
1128                if(isset($row_contact_conns[0])) {
1129                    $id_connection = $row_contact_conns[0];
1130                    $result_delete_connections = pg_delete($this->db, "phpgw_cc_connections", array('id_connection' => $id_connection));
1131                    if ($result_delete_connections == FALSE) throw new Exception(pg_last_error($this->db));
1132                    $result_delete_contact_grps = pg_delete($this->db,"phpgw_cc_contact_grps", array('id_connection' => $id_connection));
1133                    if ($result_delete_contact_grps == FALSE) throw new Exception(pg_last_error($this->db));
1134                }
1135            }
1136
1137            $result_delete_contact_conns = pg_delete($this->db, "phpgw_cc_contact_conns", array('id_contact' => $id_contact));
1138            if ($result_delete_contact_conns == FALSE) throw new Exception(pg_last_error($this->db));
1139            $result_delete_contact = pg_delete($this->db, "phpgw_cc_contact", array('id_contact' => $id_contact));
1140            if ($result_delete_contact == FALSE) throw new Exception(pg_last_error($this->db));
1141            $result = pg_query($this->db,"COMMIT;");
1142            if ($result == FALSE) throw new Exception(pg_last_error($this->db));
1143        } catch (Exception $e) {
1144            pg_query($this->db,"ROLLBACK;");
1145            debugLog("exception -> " . $e->getMessage() . " - ARQUIVO: " . $e->getFile() . " - LINHA: " . $e->getLine());
1146            return false;
1147        }
1148        return true;
1149    }
1150
1151    /**
1152     * Called when the user moves an item on the PDA from one folder to another. Whatever is needed
1153     * to move the message on disk has to be done here. After this call, StatMessage() and GetMessageList()
1154     * should show the items to have a new parent. This means that it will disappear from GetMessageList()
1155     * of the sourcefolder and the destination folder will show the new message
1156     *
1157     * @param string        $folderid       id of the source folder
1158     * @param string        $id             id of the message
1159     * @param string        $newfolderid    id of the destination folder
1160     *
1161     * @access public
1162     * @return boolean                      status of the operation
1163     * @throws StatusException              could throw specific SYNC_MOVEITEMSSTATUS_* exceptions
1164     */
1165    public function MoveMessage($folderid, $id, $newfolderid)
1166    {
1167        // TODO: Implement MoveMessage() method.
1168    }
1169
1170    /**
1171     * Authenticates the user
1172     *
1173     * @param string        $username
1174     * @param string        $domain
1175     * @param string        $password
1176     *
1177     * @access public
1178     * @return boolean
1179     * @throws FatalException   e.g. some required libraries are unavailable
1180     */
1181    public function Logon($username, $domain, $password)
1182    {
1183        ZLog::Write(LOGLEVEL_DEBUG, "ExpressoContactProvider->Logon()");
1184
1185        $ldapConfig = parse_ini_file(EXPRESSO_PATH . '/prototype/config/OpenLDAP.srv' , true );
1186        $ldapConfig =  $ldapConfig['config'];
1187        $sr = ldap_search( $GLOBALS['connections']['ldap'] , $ldapConfig['context'] , "(uid=$username)" , array('uidNumber'), 0 , 1 );
1188        if(!$sr) return false;
1189
1190        $entries = ldap_get_entries( $GLOBALS['connections']['ldap'] , $sr );
1191        $this->_uidnumber = $entries[0]['uidnumber'][0];
1192        $this->db =  $GLOBALS['connections']['db'] ;
1193
1194        return true;
1195    }
1196
1197    /**
1198     * Logs off
1199     * non critical operations closing the session should be done here
1200     *
1201     * @access public
1202     * @return boolean
1203     */
1204    public function Logoff()
1205    {
1206       return true;
1207    }
1208
1209    /**
1210     * Sends an e-mail
1211     * This messages needs to be saved into the 'sent items' folder
1212     *
1213     * Basically two things can be done
1214     *      1) Send the message to an SMTP server as-is
1215     *      2) Parse the message, and send it some other way
1216     *
1217     * @param SyncSendMail        $sm         SyncSendMail object
1218     *
1219     * @access public
1220     * @return boolean
1221     * @throws StatusException
1222     */
1223    public function SendMail($sm)
1224    {
1225        // TODO: Implement SendMail() method.
1226    }
1227
1228    /**
1229     * Returns the waste basket
1230     *
1231     * The waste basked is used when deleting items; if this function returns a valid folder ID,
1232     * then all deletes are handled as moves and are sent to the backend as a move.
1233     * If it returns FALSE, then deletes are handled as real deletes
1234     *
1235     * @access public
1236     * @return string
1237     */
1238    public function GetWasteBasket()
1239    {
1240        // TODO: Implement GetWasteBasket() method.
1241    }
1242
1243    /**
1244     * Returns the content of the named attachment as stream. The passed attachment identifier is
1245     * the exact string that is returned in the 'AttName' property of an SyncAttachment.
1246     * Any information necessary to locate the attachment must be encoded in that 'attname' property.
1247     * Data is written directly - 'print $data;'
1248     *
1249     * @param string        $attname
1250     *
1251     * @access public
1252     * @return SyncItemOperationsAttachment
1253     * @throws StatusException
1254     */
1255    public function GetAttachmentData($attname)
1256    {
1257        // TODO: Implement GetAttachmentData() method.
1258    }
1259
1260    function escape($data){
1261        if (is_array($data)) {
1262            foreach ($data as $key => $val) {
1263                $data[$key] = $this->escape($val);
1264            }
1265            return $data;
1266        }
1267        $data = str_replace("\r\n", "\n", $data);
1268        $data = str_replace("\r", "\n", $data);
1269        $data = str_replace(array('\\', ';', ',', "\n"), array('\\\\', '\\;', '\\,', '\\n'), $data);
1270        return $data;
1271    }
1272
1273    function truncateString($string, $size)
1274    {
1275        if(strlen($string) <= $size) return $string;
1276        else return substr($string, 0, $size - 1);
1277    }
1278
1279    function formatMail($mail)
1280    {
1281        if (preg_match('/[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}/', $mail , $mat ))
1282            return $mat[0];
1283        else
1284            return '';
1285    }
1286
1287    function  removeAccents($data){
1288        $data = strtr($data,"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ","aaaaaaaceeeeiiii noooooxouuutbaaaaaaaceeeeiiii nooooo/ouuuty");
1289        return $data;
1290    }
1291
1292}
Note: See TracBrowser for help on using the repository browser.