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

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