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

Revision 5316, 20.6 KB checked in by cristiano, 12 years ago (diff)

Ticket #2423 - Trocar chamada da variável rootPath

  • Property svn:eol-style set to native
  • Property svn:executable set to *
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                $contacts = $this->get_cc_contacts();
213                $groups = $this->get_cc_groups();
214               
215                if(($contacts) && ($groups))
216                        $stringDropDownContacts = $contacts . ',' . $groups;
217                elseif ((!$contacts) && (!$groups))
218                        $stringDropDownContacts = '';
219                elseif (($contacts) && (!$groups))
220                        $stringDropDownContacts = $contacts;
221                elseif ((!$contacts) && ($groups))
222                        $stringDropDownContacts = $groups;
223                                       
224                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
225                        // Free others requests
226                        session_write_close();
227                        $dynamic_contact = new dynamic_contacts();
228                        $dynamic = $dynamic_contact->dynamic_contact_toString();
229                        if ($dynamic)
230                                $stringDropDownContacts .= ($stringDropDownContacts ? ',' : '') . $dynamic;
231                }
232                return $stringDropDownContacts;
233        }
234        function getUserByEmail($params){       
235                // Follow the referral
236                $email = $params['email'];
237                $query = 'select A.names_ordered, C.connection_name, C.connection_value, A.photo'.
238                                ' from phpgw_cc_contact A, phpgw_cc_contact_conns B, '.
239                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
240                                ' and B.id_connection = C.id_connection and A.id_contact ='.
241                                '(select A.id_contact from phpgw_cc_contact A, phpgw_cc_contact_conns B,'.
242                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
243                                ' and B.id_connection = C.id_connection and A.id_owner = '.$this -> user_id.
244                                ' and C.connection_value = \''.$email.'\') and '.
245                                'C.connection_is_default = true and B.id_typeof_contact_connection = 2';
246
247        if (!$this->db->query($query))
248                return null;
249
250
251                if($this->db->next_record()) {
252                        $result = $this->db->row();
253
254                        $obj =  array("cn" => $result['names_ordered'],
255                                          "email" => $email,
256                                          "type" => "personal",
257                                          "telefone" =>  $result['connection_value']);
258
259                        if($result['photo'])
260                                $_SESSION['phpgw_info']['expressomail']['contact_photo'] =  array($result['photo']);                           
261
262                        return $obj;
263                }
264                return $result;
265        }
266       
267        function get_dynamic_contacts()
268        {                               
269                // Pesquisa os emails e ultima inserção nos contatos dinamicos.
270                if(!$this->db->select('phpgw_expressomail_contacts','data','id_owner ='.$this->user_id,__LINE__,__FILE__))
271                {
272                return $this->db->Error;
273}
274                while($this->db->next_record())
275                {
276                        $result[] = $this->db->row();
277                }
278                if($result) foreach($result as $item)
279                {
280                        $contacts = unserialize($item['data']);
281                }
282                if (count($contacts) == 0)
283                {                       
284                        return null;
285                }       
286                //Sort by email
287                function cmp($a, $b) { return strcmp($a["email"], $b["email"]);}
288                usort($contacts,"cmp");
289                return $contacts;
290        }
291        function update_contacts($contacts=array())
292        {                       
293               
294       
295                if(!$this->db->select('phpgw_expressomail_contacts','data','id_owner ='.$this->user_id,__LINE__,__FILE__))
296        {
297            $result['dberr1'] = $this->db->Error;
298        }
299                $regs = array();
300                while($this->db->next_record())
301        {
302            $regs[] = $this->db->row();
303        }
304                $old_contatacts = array();
305                foreach($regs as $old){
306                        $old_contatacts = unserialize($old['data']);
307                }
308                 
309                foreach($old_contatacts as $i => $v)
310                        foreach($contacts as $ii => $vv)
311                                if(trim($v['email']) == trim($vv['email']))
312                                        unset($old_contatacts[$i]);
313               
314                 
315                 $old_contatacts = array_merge( $old_contatacts , $contacts);           
316                // Atualiza um email nos contatos dinamicos.
317                if(!$this->db->update('phpgw_expressomail_contacts ','data=\''.serialize($old_contatacts).'\'','id_owner ='.$this->user_id,__LINE__,__FILE__))
318                {
319                        return $this->db->Error;
320                }
321                return $contacts;
322        }       
323        function update_preferences($params){
324                $string_serial = urldecode($params['prefe_string']);                           
325                $string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
326                $query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
327                        " and preference_owner = '".$this->user_id."'";
328
329                if (!$this->db->query($query))
330                        return $this->db->error;
331                else
332                        return array("success" => true);
333        }
334       
335        function insert_contact($contact)       
336        {
337                $contacts[] = array( 'timestamp'        => time(),
338                                                                'email'         => $contact );
339
340                // Insere um email nos contatos dinamicos.     
341                $query = 'INSERT INTO phpgw_expressomail_contacts (data, id_owner)  ' .
342                                        'values ( \''.serialize($contacts).'\', '.$this->user_id.')';
343               
344                if(!$this->db->query($query,__LINE__,__FILE__))
345                return $this->db->Error;
346        return $contacts;
347        }
348       
349        function remove_dynamic_contact($user_id,$line,$file)
350        {
351                $where = $user_id.' = id_owner';
352                $this->db->delete('phpgw_expressomail_contacts',$where,$line,$file);   
353        }
354       
355        function import_vcard($params){
356                       
357                include_once('class.imap_functions.inc.php');
358                $objImap = new imap_functions();
359                $msg_number = $params['msg_number'];
360                $idx_file = $params['idx_file'];
361                $msg_part = $params['msg_part'];
362                $msg_folder = $params['msg_folder'];
363            $from_ajax = $params['from_ajax'];
364                $encoding = strtolower($params['encoding']);
365                $fileContent = "";
366            $cirus_delimiter = $params['cirus_delimiter'];
367            $expFolder = explode($cirus_delimiter, $msg_folder);
368
369            if($msg_number != null && $msg_part != null && $msg_folder != null && (intval($idx_file == '0' ? '1' : $idx_file)))
370            {
371                require_once dirname(__FILE__).'/class.attachment.inc.php';
372                $attachmentObj = new attachment();
373                $attachmentObj->setStructureFromMail($msg_folder,$msg_number);
374                $fileContent = $attachmentObj->getAttachment($msg_part);
375                $info = $attachmentObj->getAttachmentInfo($msg_part);
376                $filename = $info['name'];
377                }
378                else
379                        $filename = $idx_file;
380                                       
381                // It's necessary to access calendar method.
382            $GLOBALS['phpgw_info']['flags']['noappheader'] = True;
383            $GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
384            $GLOBALS['phpgw_info']['flags']['currentapp'] = 'calendar';
385                include_once(PHPGW_INCLUDE_ROOT.'/header.inc.php');
386                $uiicalendar = CreateObject("calendar.uiicalendar");
387
388            if(strtoupper($expFolder[0]) == 'USER' && $expFolder[1]) // IF se a conta o ical estiver em uma conta compartilhada
389            {
390                include_once('class.ldap_functions.inc.php');
391                $ldap = new ldap_functions();
392                $account['uid'] = $expFolder[1];
393                $account['uidnumber']  = $ldap->uid2uidnumber($expFolder[1]);
394                $account['mail']  = $ldap->getMailByUid($expFolder[1]);
395
396                return $uiicalendar->import_from_mail($fileContent, $from_ajax,$account);
397            }
398            else
399                return $uiicalendar->import_from_mail($fileContent, $from_ajax);
400           
401           
402        }
403
404    function insert_certificate($email,$certificate,$serialnumber,$authoritykeyidentifier=null)
405        {
406                if(!$email || !$certificate || !$serialnumber || !$authoritykeyidentifier)
407                        return false;
408                // Insere uma chave publica na tabela phpgw_certificados.
409                $data = array   ('email' => $email,
410                                                 'chave_publica' => $certificate,
411                                                 'serialnumber' => $serialnumber,
412                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
413
414                if(!$this->db->insert('phpgw_certificados',$data,array(),__LINE__,__FILE__)){
415                return $this->db->Error;
416        }
417        return true;
418        }
419
420        function get_certificate($email=null)
421        {
422                if(!$email) return false;
423                $result = array();
424
425                $where = array ('email' => $email,
426                                                'revogado' => 0,
427                                                'expirado' => 0);
428
429                if(!$this->db->select('phpgw_certificados','chave_publica', $where, __LINE__,__FILE__))
430        {
431            $result['dberr1'] = $this->db->Error;
432            return $result;
433        }
434                $regs = array();
435                while($this->db->next_record())
436        {
437            $regs[] = $this->db->row();
438        }
439                if (count($regs) == 0)
440        {
441            $result['dberr2'] = ' Certificado nao localizado.';
442            return $result;
443        }
444                $result['certs'] = $regs;
445                return $result;
446        }
447
448        function update_certificate($serialnumber=null,$email=null,$authoritykeyidentifier,$expirado,$revogado)
449        {
450                if(!$email || !$serialnumber) return false;
451                if(!$expirado)
452                        $expirado = 0;
453                if(!$revogado)
454                        $revogado = 0;
455
456                $data = array   ('expirado' => $expirado,
457                                                 'revogado' => $revogado);
458
459                $where = array  ('email' => $email,
460                                                 'serialnumber' => $serialnumber,
461                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
462
463                if(!$this->db->update('phpgw_certificados',$data,$where,__LINE__,__FILE__))
464                {
465                        return $this->db->Error;
466                }
467                return true;
468        }
469
470       
471        /**
472     * @abstract Recupera o valor da regra padrão.
473     * @return retorna o valor da regra padrão.
474     */
475        function get_default_max_size_rule()
476        {
477                $query = "SELECT config_value FROM phpgw_config WHERE config_name = 'expressoAdmin_default_max_size'";
478                if(!$this->db->query($query))
479            return false;
480
481        $return = array();
482                       
483                while($this->db->next_record())
484            array_push($return, $this->db->row());
485                       
486                return $return;
487        }
488       
489        /**
490     * @abstract Recupera a regra de um usuário.
491     * @return retorna a regra que o usuário pertence. Caso o usuário não participe de nenhuma regra, retorna false.
492     */
493        function get_rule_by_user($id_user)
494        {
495                $return = array();     
496                $query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user='$id_user' AND configuration_type='MessageMaxSize'";
497               
498                if(!$this->db->query($query))
499            return false;
500               
501                while($this->db->next_record())
502            array_push($return, $this->db->row());
503                       
504                return $return;
505        }
506       
507       
508        function get_rule_by_user_in_groups($id_group)
509        {
510                $return = array();
511                $query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE configuration_type='MessageMaxSize' AND email_user_type='G' AND email_user='".$id_group."'";
512
513                if(!$this->db->query($query))   
514                        return false;   
515                       
516                while($this->db->next_record())
517                        array_push($return, $this->db->row());
518
519                return $return;
520        }
521        function getMaximumRecipientsUser($pUserUID)
522        {
523
524           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$pUserUID.'\' AND configuration_type = \'LimitRecipient\' AND email_user_type = \'U\' ';
525           $this->db->query($query);
526
527           $return = array();
528
529            while($this->db->next_record())
530              $return =  $this->db->row();
531
532            return $return['email_max_recipient'];
533        }
534
535        function getMaximumRecipientsGroup($pGroupsGuidnumbers)
536        {
537           $groupsGuidNumbers = '';
538
539           foreach ($pGroupsGuidnumbers as $guidNumber => $cn)
540             $groupsGuidNumbers .= $guidNumber.', ';
541
542           $groupsGuidNumbers = substr($groupsGuidNumbers,0,-2);
543
544           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user IN ('.$groupsGuidNumbers.') AND configuration_type = \'LimitRecipient\' AND email_user_type = \'G\' ';
545           $this->db->query($query);
546
547           $return = array();
548
549            while($this->db->next_record())
550              $return[] =  $this->db->row();
551
552            $maxSenderReturn = 0;
553
554            foreach ($return as $maxSender)
555            {
556                if($maxSender['email_max_recipient'] > $maxSenderReturn)
557                    $maxSenderReturn = $maxSender['email_max_recipient'];
558            }
559
560            return $maxSenderReturn;
561        }
562
563        function validadeSharedAccounts($user,$grups,$accountsMails)
564        {
565
566             $arrayMailsBlocked = array();
567
568             $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$user.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'U\' ';
569             $this->db->query($query);
570             $this->db->next_record();
571                 if($this->db->row())
572                   return $arrayMailsBlocked;
573
574            foreach ($grups as $guidNumber => $cn)
575            {
576                 $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$guidNumber.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'G\' ';
577                 $this->db->query($query);
578                 $this->db->next_record();
579                 if($this->db->row())
580                     return $arrayMailsBlocked;
581
582            }
583
584            foreach ($accountsMails as $mail)
585            {
586               
587               $blocked = true;
588
589               $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_recipient = \''.$mail.'\' AND configuration_type = \'InstitutionalAccountException\' ';
590               $this->db->query($query);
591           
592                while($this->db->next_record())
593                {
594                    $row =  $this->db->row();
595                   
596                    if(($row['email_user'] == '*' ||  $row['email_user'] == $user) && ($row['email_user_type'] == 'T' || $row['email_user_type'] == 'U'))
597                        $blocked = false;
598                    else if(array_key_exists($row['email_user'], $grups) && $row['email_user_type'] == 'G')
599                         $blocked = false;
600
601                }
602
603                if($blocked == true)
604                    array_push ($arrayMailsBlocked, $mail);
605            }
606
607            return $arrayMailsBlocked;
608        }
609
610}
611?>
Note: See TracBrowser for help on using the repository browser.