source: sandbox/2.3-MailArchiver/expressoMail1_2/inc/class.db_functions.inc.php @ 6779

Revision 6779, 14.5 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2946 - Liberado Expresso(branch 2.3) integrado ao MailArchiver?.

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