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

Revision 5380, 20.8 KB checked in by thiago, 12 years ago (diff)

Ticket #2447 - Erro ao enviar uma mensagem para um grupo previamente criado

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