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

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