source: trunk/expressoMail1_2/inc/class.db_functions.inc.php @ 1035

Revision 1035, 14.7 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #558 - Adicionada funcionalidade de assinatura e criptografia de e-mails.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2define('PHPGW_INCLUDE_ROOT','../');     
3define('PHPGW_API_INC','../phpgwapi/inc');     
4include_once(PHPGW_API_INC.'/class.db.inc.php');
5include_once('class.dynamic_contacts.inc.php');
6       
7class db_functions
8{       
9       
10        var $db;
11        var $user_id;
12        var $related_ids;
13       
14        function db_functions(){
15                $this->db = new db();           
16                $this->db->Halt_On_Error = 'no';
17                $this->db->connect(
18                                $_SESSION['phpgw_info']['expressomail']['server']['db_name'],
19                                $_SESSION['phpgw_info']['expressomail']['server']['db_host'],
20                                $_SESSION['phpgw_info']['expressomail']['server']['db_port'],
21                                $_SESSION['phpgw_info']['expressomail']['server']['db_user'],
22                                $_SESSION['phpgw_info']['expressomail']['server']['db_pass'],
23                                $_SESSION['phpgw_info']['expressomail']['server']['db_type']
24                );             
25                $this -> user_id = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];       
26        }
27
28        // BEGIN of functions.
29        function get_cc_contacts()
30        {                               
31                $result = array();
32                $stringDropDownContacts = '';           
33               
34                $query_related = $this->get_query_related('A.id_owner'); // field name for owner
35                       
36                // Traz os contatos pessoais e compartilhados
37                $query = 'select A.names_ordered, C.connection_value from phpgw_cc_contact A, '.
38                        'phpgw_cc_contact_conns B, phpgw_cc_connections C where '.
39                        'A.id_contact = B.id_contact and B.id_connection = C.id_connection '.
40                        'and B.id_typeof_contact_connection = 1 and ('.$query_related.') group by '.
41                        'A.names_ordered,C.connection_value     order by lower(A.names_ordered)';
42               
43        if (!$this->db->query($query))
44                return null;
45                while($this->db->next_record())
46                        $result[] = $this->db->row();
47
48                if (count($result) != 0)
49                {
50                        // Monta string                         
51                        foreach($result as $contact)
52                                $stringDropDownContacts = $stringDropDownContacts . $contact['names_ordered']. ';' . $contact['connection_value'] . ',';
53                        //Retira ultima virgula.
54                        $stringDropDownContacts = substr($stringDropDownContacts,0,(strlen($stringDropDownContacts) - 1));
55                }
56                else
57                        return null;
58
59                return $stringDropDownContacts;
60        }
61        // Get Related Ids for sharing contacts or groups.
62        function get_query_related($field_name){               
63                $query_related = $field_name .'='.$this -> user_id;
64                // Only at first time, it gets all related ids...
65                if(!$this->related_ids) {
66                        $query = 'select id_related from phpgw_cc_contact_rels where id_contact='.$this -> user_id.' and id_typeof_contact_relation=1';         
67                        if (!$this->db->query($query)){
68                return $query_related;
69                        }
70                       
71                        while($this->db->next_record()){
72                                $row = $this->db->row();
73                                $result[] = $row['id_related'];
74                        }
75                        if($result)
76                                $this->related_ids = implode(",",$result);
77                }
78                if($this->related_ids)
79                        $query_related .= ' or '.$field_name.' in ('.$this->related_ids.')';
80               
81                return $query_related;
82        }
83        function get_cc_groups()
84        {
85                // Pesquisa no CC os Grupos Pessoais.
86                $stringDropDownContacts = '';                   
87                $result = array();
88                $query_related = $this->get_query_related('owner'); // field name for 'owner'           
89                $query = 'select title, short_name, owner from phpgw_cc_groups where '.$query_related.' order by lower(title)';
90
91                // Executa a query
92                if (!$this->db->query($query))
93                return null;
94                // Retorna cada resultado               
95                while($this->db->next_record())
96                        $result[] = $this->db->row();
97
98                // Se houver grupos ....                               
99                if (count($result) != 0)
100                {
101                        // Create Ldap Object, if exists related Ids for sharing groups.
102                        if($this->related_ids){
103                                $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids']= array();
104                                include_once("class.ldap_functions.inc.php");
105                                $ldap = new ldap_functions();
106                        }
107                        $owneruid = '';
108                        foreach($result as $group){
109                                // Searching uid (LDAP), if exists related Ids for sharing groups.
110                                // Save into user session. It will used before send mail (verify permission).
111                                if(!$_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'][$group['owner']] && $ldap){                                       
112                                        $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'][$group['owner']] = $ldap -> uidnumber2uid($group['owner']);
113                                }
114                                if($this->user_id != $group['owner'])
115                                        $owneruid = "::".$_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'][$group['owner']];
116                                else
117                                        $owneruid = '';
118
119                                $stringDropDownContacts .=  $group['title']. ';' . ($group['short_name'].$owneruid) . ',';
120                        }
121                        //Retira ultima virgula.
122                        $stringDropDownContacts = substr($stringDropDownContacts,0,(strlen($stringDropDownContacts) - 1));
123                }
124                else
125                        return null;           
126                return $stringDropDownContacts;
127        }
128       
129        function getContactsByGroupAlias($alias)
130        {
131                list($alias,$uid) = explode("::",$alias);               
132                $cc_related_ids = $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'];           
133                // Explode personal group, If exists related ids (the user has permission to send email).
134                if(is_array($cc_related_ids) && $uid){
135                        $owner =  array_search($uid,$cc_related_ids);                   
136                }
137               
138                $query = "select C.id_connection, A.names_ordered, C.connection_value from phpgw_cc_contact A, ".
139                "phpgw_cc_contact_conns B, phpgw_cc_connections C,phpgw_cc_contact_grps D,phpgw_cc_groups E where ".
140                "A.id_contact = B.id_contact and B.id_connection = C.id_connection ".
141                "and B.id_typeof_contact_connection = 1 and ".
142                "A.id_owner =".($owner ? $owner : $this->user_id)." and ".                     
143                "D.id_group = E.id_group and ".
144                "D.id_connection = C.id_connection and E.short_name = '".$alias."'";
145
146                if (!$this->db->query($query))
147                {
148                        exit ('Query failed! File: '.__FILE__.' on line'.__LINE__);
149                }
150
151                $return = false;
152
153                while($this->db->next_record())
154                {
155                        $return[] = $this->db->row();
156                }
157
158                return $return;
159        }
160
161        function getAddrs($array_addrs) {
162                $array_addrs_final = array();                           
163
164                for($i = 0; $i < count($array_addrs); $i++){
165                        $j = count($array_addrs_final);
166
167                        if(!strchr($array_addrs[$i],'@')
168                                        && strchr($array_addrs[$i],'<')
169                                         && strchr($array_addrs[$i],'>')) {             
170
171                                $alias = substr($array_addrs[$i], strpos($array_addrs[$i],'<'), strpos($array_addrs[$i],'>'));                         
172                                $alias = str_replace('<','', str_replace('>','',$alias));
173                                                                                       
174                                $arrayContacts = $this -> getContactsByGroupAlias($alias);
175
176                                if($arrayContacts) {
177                                        foreach($arrayContacts as $index => $contact){
178                                                if($contact['names_ordered']) {
179                                                        $array_addrs_final[$j] = '"'.$contact['names_ordered'].'" <'.$contact['connection_value'].'>';
180                                                }
181                                                else
182                                                        $array_addrs_final[$j] = $contact['connection_value'];
183
184                                                $j++;
185                                        }
186                                }
187                        }
188                        else
189                                $array_addrs_final[$j++] = $array_addrs[$i];                                                   
190                }
191                return $array_addrs_final;
192        }
193
194        function get_dropdown_contacts(){
195               
196                $contacts = $this -> get_cc_contacts();
197                $groups = $this -> get_cc_groups();
198               
199                if(($contacts) && ($groups))
200                        $stringDropDownContacts = $contacts . ',' . $groups;
201                elseif ((!$contacts) && (!$groups))
202                        $stringDropDownContacts = '';
203                elseif (($contacts) && (!$groups))
204                        $stringDropDownContacts = $contacts;
205                elseif ((!$contacts) && ($groups))
206                        $stringDropDownContacts = $groups;
207                                       
208                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
209                        $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
210                        $dynamic_contact = new dynamic_contacts();
211                        $dynamic = $dynamic_contact->dynamic_contact_toString();
212                        if ($dynamic)
213                                $stringDropDownContacts .= ($stringDropDownContacts ? ',' : '') . $dynamic;
214                }
215                return $stringDropDownContacts;
216        }
217        /*
218        function update_preferences($params){
219               
220                $aux = explode("##",$params['prefe_string']);
221                $new_prefe = array();
222               
223                foreach($aux as $key=>$tmp){
224                        if($key == 0){
225                                $new_prefe['max_email_per_page'] = $tmp;
226                        }
227                        if($key == 1){
228                                $new_prefe['save_deleted_msg'] = $tmp;
229                        }
230                        if($key == 2){
231                                $new_prefe['delete_trash_messages_after_n_days'] = $tmp;
232                        }
233                        if($key == 3){
234                                $new_prefe['delete_and_show_previous_message'] = $tmp;
235                        }
236                        if($key == 4){
237                                $new_prefe['alert_new_msg'] = $tmp;
238                        }
239                        if($key == 5){
240                                $new_prefe['mainscreen_showmail'] = $tmp;
241                        }
242                        if($key == 10){
243                                $new_prefe['signature'] = $tmp;
244                        }
245                        if($key == 7){
246                                $new_prefe['hide_folders'] = $tmp;
247                        }
248                        if($key == 6){
249                                $new_prefe['save_in_folder'] = $tmp;
250                        }
251                        if($key == 8){
252                                $new_prefe['line_height'] = $tmp;
253                        }
254                        if($key == 9){
255                                $new_prefe['font_size'] = $tmp;
256                        }
257                        if($key == 11){
258                                $new_prefe['use_shortcuts'] = $tmp;
259                        }
260                }
261               
262                $string_serial =  serialize($new_prefe);
263                $string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
264                $query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
265                                 " and preference_owner = '".$this->user_id."'";
266               
267                if (!$this->db->query($query))
268                return "Failed!";
269                else
270                        return "OK!";
271        }
272        */
273        function update_preferences($params){
274                $string_serial = urldecode($params['prefe_string']);                           
275                $string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
276                $query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
277                                 " and preference_owner = '".$this->user_id."'";
278               
279                if (!$this->db->query($query))
280                return $this->db->error;
281                else
282                        return array("success" => true);
283        }
284        function getUserByEmail($params){       
285                // Follow the referral
286                $email = $params['email'];
287                $query = 'select A.names_ordered, C.connection_name, C.connection_value, A.photo'.
288                                ' from phpgw_cc_contact A, phpgw_cc_contact_conns B, '.
289                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
290                                ' and B.id_connection = C.id_connection and A.id_contact ='.
291                                '(select A.id_contact from phpgw_cc_contact A, phpgw_cc_contact_conns B,'.
292                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
293                                ' and B.id_connection = C.id_connection and A.id_owner = '.$this -> user_id.
294                                ' and C.connection_value = \''.$email.'\') and '.
295                                'C.connection_is_default = true and B.id_typeof_contact_connection = 2';
296
297        if (!$this->db->query($query))
298                return null;
299
300
301                if($this->db->next_record()) {
302                        $result = $this->db->row();
303
304                        $obj =  array("cn" => $result['names_ordered'],
305                                          "email" => $email,
306                                          "type" => "personal",
307                                          "telefone" =>  $result['connection_value']);
308
309                        if($result['photo'])
310                                $_SESSION['phpgw_info']['expressomail']['contact_photo'] =  array($result['photo']);                           
311
312                        return $obj;
313                }
314                return $result;
315        }
316       
317        function get_dynamic_contacts()
318        {                               
319                // Pesquisa os emails e ultima inserção nos contatos dinamicos.
320                if(!$this->db->select('phpgw_expressomail_contacts','data',
321                                                  'id_owner ='.$this -> user_id,
322                                                  __LINE__,__FILE__))
323                {
324                return $this->db->Error;
325}
326                while($this->db->next_record())
327                {
328                        $result[] = $this->db->row();
329                }
330                if($result) foreach($result as $item)
331                {
332                        $contacts = unserialize($item['data']);
333                }
334                if (count($contacts) == 0)
335                {                       
336                        return null;
337                }       
338                //Sort by email
339                function cmp($a, $b) { return strcmp($a["email"], $b["email"]);}
340                usort($contacts,"cmp");
341                return $contacts;
342        }
343        function update_contacts($contacts=array())
344        {                       
345                // Atualiza um email nos contatos dinamicos.
346                if(!$this->db->update('phpgw_expressomail_contacts ','data=\''.serialize($contacts).'\'',
347                                                          'id_owner ='.$this -> user_id,
348                                                          __LINE__,__FILE__))
349                {
350                        return $this->db->Error;
351                }
352        return $contacts;
353        }       
354       
355        function insert_contact($contact)       
356        {
357                $contacts[] = array( 'timestamp'        => time(),
358                                                                'email'         => $contact );
359
360                // Insere um email nos contatos dinamicos.     
361                $query = 'INSERT INTO phpgw_expressomail_contacts (data, id_owner)  ' .
362                                        'values ( \''.serialize($contacts).'\', '.$this->user_id.')';
363               
364                if(!$this->db->query($query,__LINE__,__FILE__))
365                return $this->db->Error;
366        return $contacts;
367        }
368       
369        function remove_dynamic_contact($user_id,$line,$file)
370        {
371                $where = $user_id.' = id_owner';
372                $this->db->delete('phpgw_expressomail_contacts',$where,$line,$file);   
373        }
374       
375        function import_vcard($params){
376                       
377                include_once('class.imap_functions.inc.php');
378                $objImap = new imap_functions();
379                $msg_number = $params['msg_number'];
380                $idx_file = $params['idx_file'];
381                $msg_part = $params['msg_part'];
382                $msg_folder = $params['msg_folder'];
383                $encoding = strtolower($params['encoding']);
384                $fileContent = "";
385
386                if($msg_number && $msg_part && $msg_folder && (intval($idx_file == '0' ? '1' : $idx_file))) {
387                        $mbox_stream = $objImap->open_mbox($msg_folder);       
388                        $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
389                        include_once('class.imap_attachment.inc.php');
390                        $imap_attachment = new imap_attachment();
391                        $a = $imap_attachment->download_attachment($mbox_stream, $msg_number);
392                        $filename = $a[$idx_file]['name'];
393                }
394                else
395                        $filename = $idx_file;
396                                       
397                if($fileContent) {
398                        if($encoding == 'base64')
399                                $calendar = imap_base64($fileContent);
400                        else if($encoding == 'quoted-printable')
401                                $calendar = quoted_printable_decode($fileContent);
402                        else
403                                $calendar = $fileContent;
404                }
405                       
406                $uiicalendar = CreateObject("calendar.uiicalendar");
407                return $uiicalendar = $uiicalendar->import_from_mail($calendar);
408        }
409
410    function insert_certificate($email,$certificate,$serialnumber,$authoritykeyidentifier=null)
411        {
412                if(!$email || !$certificate || !$serialnumber || !$authoritykeyidentifier)
413                        return false;
414                // Insere uma chave publica na tabela phpgw_certificados.
415                $data = array   ('email' => $email,
416                                                 'chave_publica' => $certificate,
417                                                 'serialnumber' => $serialnumber,
418                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
419
420                if(!$this->db->insert('phpgw_certificados',$data,array(),__LINE__,__FILE__)){
421                return $this->db->Error;
422        }
423        return true;
424        }
425
426        function get_certificate($email=null)
427        {
428                if(!$email) return false;
429                $result = array();
430
431                $where = array ('email' => $email,
432                                                'revogado' => 0,
433                                                'expirado' => 0);
434
435                if(!$this->db->select('phpgw_certificados','chave_publica', $where, __LINE__,__FILE__))
436        {
437            $result['dberr1'] = $this->db->Error;
438            return $result;
439        }
440                $regs = array();
441                while($this->db->next_record())
442        {
443            $regs[] = $this->db->row();
444        }
445                if (count($regs) == 0)
446        {
447            $result['dberr2'] = ' Certificado nao localizado.';
448            return $result;
449        }
450                $result['certs'] = $regs;
451                return $result;
452        }
453
454        function update_certificate($serialnumber=null,$email=null,$authoritykeyidentifier,$expirado,$revogado)
455        {
456                if(!$email || !$serialnumber) return false;
457                if(!$expirado)
458                        $expirado = 0;
459                if(!$revogado)
460                        $revogado = 0;
461
462                $data = array   ('expirado' => $expirado,
463                                                 'revogado' => $revogado);
464
465                $where = array  ('email' => $email,
466                                                 'serialnumber' => $serialnumber,
467                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
468
469                if(!$this->db->update('phpgw_certificados',$data,$where,__LINE__,__FILE__))
470                {
471                        return $this->db->Error;
472                }
473                return true;
474        }
475
476}
477?>
Note: See TracBrowser for help on using the repository browser.