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

Revision 8152, 21.3 KB checked in by angelo, 11 years ago (diff)

Ticket #3486 - Problema na criacao e envio de email para grupos compartilhados

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2                /***************************************************************************
3                * Expresso Livre                                                           *
4                * http://www.expressolivre.org                                             *
5                * --------------------------------------------                             *
6                *  This program is free software; you can redistribute it and/or modify it *
7                *  under the terms of the GNU General Public License as published by the   *
8                *  Free Software Foundation; either version 2 of the License, or (at your  *
9                *  option) any later version.                                              *
10                \**************************************************************************/
11               
12if(!isset($_SESSION['phpgw_info']['expressomail']['server']['db_name'])) {
13        include_once('../header.inc.php');
14        $_SESSION['phpgw_info']['expressomail']['server']['db_name'] = $GLOBALS['phpgw_info']['server']['db_name']; 
15        $_SESSION['phpgw_info']['expressomail']['server']['db_host'] = $GLOBALS['phpgw_info']['server']['db_host'];
16        $_SESSION['phpgw_info']['expressomail']['server']['db_port'] = $GLOBALS['phpgw_info']['server']['db_port'];
17        $_SESSION['phpgw_info']['expressomail']['server']['db_user'] = $GLOBALS['phpgw_info']['server']['db_user'];
18        $_SESSION['phpgw_info']['expressomail']['server']['db_pass'] = $GLOBALS['phpgw_info']['server']['db_pass'];
19        $_SESSION['phpgw_info']['expressomail']['server']['db_type'] = $GLOBALS['phpgw_info']['server']['db_type'];
20}
21else{
22        define('PHPGW_INCLUDE_ROOT','../');     
23        define('PHPGW_API_INC','../phpgwapi/inc');       
24        include_once(PHPGW_API_INC.'/class.db.inc.php');
25}
26       
27class db_functions
28{       
29       
30        var $db;
31        var $user_id;
32        var $related_ids;
33       
34        function db_functions(){
35                $this->db = new db();           
36                $this->db->Halt_On_Error = 'no';
37                $this->db->connect(
38                                $_SESSION['phpgw_info']['expressomail']['server']['db_name'],
39                                $_SESSION['phpgw_info']['expressomail']['server']['db_host'],
40                                $_SESSION['phpgw_info']['expressomail']['server']['db_port'],
41                                $_SESSION['phpgw_info']['expressomail']['server']['db_user'],
42                                $_SESSION['phpgw_info']['expressomail']['server']['db_pass'],
43                                $_SESSION['phpgw_info']['expressomail']['server']['db_type']
44                );             
45                $this -> user_id = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];       
46        }
47
48        // BEGIN of functions.
49        function get_cc_contacts()
50        {                               
51                $result = array();
52                $stringDropDownContacts = '';           
53               
54                $query_related = $this->get_query_related('A.id_owner'); // field name for owner
55                       
56                // Traz os contatos pessoais e compartilhados
57                $query = 'select A.names_ordered, C.connection_value from phpgw_cc_contact A, '.
58                        'phpgw_cc_contact_conns B, phpgw_cc_connections C where '.
59                        'A.id_contact = B.id_contact and B.id_connection = C.id_connection '.
60                        'and B.id_typeof_contact_connection = 1 and ('.$query_related.') group by '.
61                        'A.names_ordered,C.connection_value     order by lower(A.names_ordered)';
62               
63        if (!$this->db->query($query))
64                return null;
65                while($this->db->next_record())
66                        $result[] = $this->db->row();
67
68                if (count($result) != 0)
69                {
70                        // Monta string                         
71                        foreach($result as $contact)
72                                $stringDropDownContacts = $stringDropDownContacts . urldecode(urldecode($contact['names_ordered'])). ';' . $contact['connection_value'] . ',';
73                        //Retira ultima virgula.
74                        $stringDropDownContacts = substr($stringDropDownContacts,0,(strlen($stringDropDownContacts) - 1));
75                }
76                else
77                        return null;
78
79                return $stringDropDownContacts;
80        }
81        // Get Related Ids for sharing contacts or groups.
82        function get_query_related($field_name){               
83                $query_related = $field_name .'='.$this -> user_id;
84                // Only at first time, it gets all related ids...
85                if(!$this->related_ids) {
86                        $query = 'select id_related from phpgw_cc_contact_rels where id_contact='.$this -> user_id.' and id_typeof_contact_relation=1';         
87                        if (!$this->db->query($query)){
88                return $query_related;
89                        }
90                       
91                        $result = array( );
92                        while($this->db->next_record()){
93                                $row = $this->db->row();
94                                $result[] = $row['id_related'];
95                        }
96                        if($result)
97                                $this->related_ids = implode(",",$result);
98                }
99                if($this->related_ids)
100                        $query_related .= ' or '.$field_name.' in ('.$this->related_ids.')';
101               
102                return $query_related;
103        }
104        function get_cc_groups()
105        {
106                // Pesquisa no CC os Grupos Pessoais.
107                $stringDropDownContacts = '';                   
108                $result = array();
109                $query_related = $this->get_query_related('owner'); // field name for 'owner'           
110                $query = 'select title, short_name, owner from phpgw_cc_groups where '.$query_related.' order by lower(title)';
111
112                // Executa a query
113                if (!$this->db->query($query))
114                return null;
115                // Retorna cada resultado               
116                while($this->db->next_record())
117                        $result[] = $this->db->row();
118
119                // Se houver grupos ....                               
120                if (count($result) != 0)
121                {
122                        // Create Ldap Object, if exists related Ids for sharing groups.
123                        if($this->related_ids){
124                                $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids']= array();
125                                include_once("class.ldap_functions.inc.php");
126                                $ldap = new ldap_functions();
127                        }
128                        $owneruid = '';
129                        foreach($result as $group){
130                                // Searching uid (LDAP), if exists related Ids for sharing groups.
131                                // Save into user session. It will used before send mail (verify permission).
132                                if(!isset($_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'][$group['owner']]) && isset($ldap)){                                 
133                                        $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'][$group['owner']] = $ldap -> uidnumber2uid($group['owner']);
134                                }
135                                if($this->user_id != $group['owner'])
136                                        $owneruid = "::".$_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'][$group['owner']];
137                                else
138                                        $owneruid = '';
139
140                                $stringDropDownContacts .=  $group['title']. ';' . ($group['short_name'].$owneruid) . ',';
141                        }
142                        //Retira ultima virgula.
143                        $stringDropDownContacts = substr($stringDropDownContacts,0,(strlen($stringDropDownContacts) - 1));
144                }
145                else
146                        return null;           
147                return $stringDropDownContacts;
148        }
149function getContactsByGroupAlias($alias)
150        {
151                /*
152                list($alias,$uid) = explode("::",$alias);               
153               
154                $cc_related_ids = $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'];           
155                // Explode personal group, If exists related ids (the user has permission to send email).
156               
157                if(is_array($cc_related_ids) && $uid){
158                        $owner =  array_search($uid,$cc_related_ids);                                   
159                }*/
160                $groups = $this->get_cc_groups();
161                if ($groups){
162                        $groups = explode(",", $groups);
163                        for($ii=0; $ii < count($groups); ++$ii) {
164                                $tmp = preg_split("/;|\::/",$groups[$ii]);
165                                $relatedGroups[$ii] = array("name" => $tmp[0],"alias" => $tmp[1],"owner" => $tmp[2]);
166                        }
167                        foreach ($relatedGroups as $key => $value) {
168                                if ($value["alias"] == $alias)
169                                        $owner = $value["owner"];
170                        }
171                        if ($owner){
172                                        include_once("class.ldap_functions.inc.php");
173                                        $ldap = new ldap_functions();                   
174                                        $owner = $ldap->uid2uidnumber($owner);
175                        }
176                }
177
178                $query = "select C.id_connection, A.names_ordered, C.connection_value from phpgw_cc_contact A, ".
179                "phpgw_cc_contact_conns B, phpgw_cc_connections C,phpgw_cc_contact_grps D,phpgw_cc_groups E where ".
180                "A.id_contact = B.id_contact and B.id_connection = C.id_connection ".
181                "and B.id_typeof_contact_connection = 1 and ".
182                "A.id_owner =".($owner ? $owner : $this->user_id)." and ".                     
183                "D.id_group = E.id_group and ".
184                "D.id_connection = C.id_connection and E.short_name = '".$alias."'";
185
186                if (!$this->db->query($query))
187                {
188                        exit ('Query failed! File: '.__FILE__.' on line'.__LINE__);
189                }
190
191                $return = false;
192
193                while($this->db->next_record())
194                {
195                        $return[] = $this->db->row();
196                }
197
198                return $return;
199        }
200
201        function getAddrs($array_addrs) {
202                $array_addrs_final = array();
203
204        $array_addrs_count = count($array_addrs);
205                for($i = 0; $i < $array_addrs_count; ++$i){
206                        $j = count($array_addrs_final);
207
208                        if(preg_replace('/\s+/', '', $array_addrs[$i]) != ""){
209
210                                if(strchr($array_addrs[$i],'@') == "") {               
211                                        if(strpos($array_addrs[$i],'<') && strpos($array_addrs[$i],'>')){
212                                                $alias = substr($array_addrs[$i], strpos($array_addrs[$i],'<'), strpos($array_addrs[$i],'>'));
213                                                $alias = str_replace('<','', str_replace('>','',$alias));
214
215                                        }
216                                        else{
217                                                $alias = $array_addrs[$i];                     
218                                                $alias = preg_replace('/\s/', '', $alias);
219                                        }       
220
221                                        $arrayContacts = $this -> getContactsByGroupAlias($alias);
222
223
224                                        if($arrayContacts) {
225                                                foreach($arrayContacts as $index => $contact){
226                                                        if($contact['names_ordered']) {
227                                                                $array_addrs_final[$j] = '"'.$contact['names_ordered'].'" <'.$contact['connection_value'].'>';
228                                                        }
229                                                        else
230                                                                $array_addrs_final[$j] = $contact['connection_value'];
231
232                                                        ++$j;
233                                                }
234                                        }else{
235                                                return array("False" => "$alias");
236                                        }
237                                }
238//-- validação email --
239                                else{
240                                        $array_addrs[$i] = trim($array_addrs[$i]);
241                                        preg_match('/<([^>]+)>/', $array_addrs[$i], $match);
242                                        if(count($match) == 2){
243                                        $ex_arr = explode('@', $match[1]);
244                                        }else{
245                                         $ex_arr = explode('@', $array_addrs[$i]);
246                                         }
247                                        if(count($ex_arr) == 2){
248                                                if($ex_arr[0] !== '' && $ex_arr[1] !== ''){
249                                                        if(preg_match("/[^0-9a-zA-Z._-]+/", $ex_arr[0]) == 0 && preg_match("/[^0-9a-zA-Z._-]+/", $ex_arr[1]) == 0){
250                                                                $array_addrs_final[$j] = $array_addrs[$i];
251                                                        }else{
252                                                                return array("False" => "$alias");
253                                                         }
254                                                }else{
255                                                        return array("False" => "$alias");
256                                                 }
257                                        }else{
258                                                return array("False" => "$alias");
259                                         }
260                                }
261//-- fim --
262                        }else{
263                                $array_addrs_final[$j] = $array_addrs[$i];
264                        }
265                }
266                return $array_addrs_final;
267        }
268
269        function getUserByEmail($params){       
270                // Follow the referral
271                $email = $params['email'];
272                $query = 'select A.names_ordered, C.connection_name, C.connection_value, A.photo'.
273                                ' from phpgw_cc_contact A, phpgw_cc_contact_conns B, '.
274                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
275                                ' and B.id_connection = C.id_connection and A.id_contact ='.
276                                '(select A.id_contact from phpgw_cc_contact A, phpgw_cc_contact_conns B,'.
277                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
278                                ' and B.id_connection = C.id_connection and A.id_owner = '.$this -> user_id.
279                                ' and C.connection_value = \''.$email.'\') and '.
280                                'C.connection_is_default = true and B.id_typeof_contact_connection = 2';
281
282        if (!$this->db->query($query))
283                return null;
284
285
286                if($this->db->next_record()) {
287                        $result = $this->db->row();
288
289                        $obj =  array("cn" => $result['names_ordered'],
290                                          "email" => $email,
291                                          "type" => "personal",
292                                          "telefone" =>  $result['connection_value']);
293
294                        if($result['photo'])
295                                $_SESSION['phpgw_info']['expressomail']['contact_photo'] =  array($result['photo']);                           
296
297                        return $obj;
298                }
299                return $result;
300        }
301       
302        function update_preferences($params){
303                $string_serial = urldecode($params['prefe_string']);                           
304                $string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
305                $query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
306                        " and preference_owner = '".$this->user_id."'";
307
308                if (!$this->db->query($query))
309                        return $this->db->error;
310                else
311                        return array("success" => true);
312        }
313       
314        function import_vcard($params){
315            include_once('class.imap_functions.inc.php');
316            $objImap = new imap_functions();
317            $msg_number = $params['msg_number'];
318            $idx_file = $params['idx_file'];
319            $msg_part = $params['msg_part'];
320            $msg_folder = $params['msg_folder'];
321            $from_ajax = $params['from_ajax'];
322            $encoding = strtolower($params['encoding']);
323            $fileContent = "";
324            $cirus_delimiter = $params['cirus_delimiter'];
325            $expFolder = explode($cirus_delimiter, $msg_folder);
326
327            if($msg_number != null && $msg_part != null && $msg_folder != null && (intval($idx_file == '0' ? '1' : $idx_file)))
328            {
329                require_once PHPGW_INCLUDE_ROOT.'/expressoMail1_2/inc/class.attachment.inc.php';
330                $attachmentObj = new attachment();
331                $attachmentObj->setStructureFromMail($msg_folder,$msg_number);
332                $fileContent = $attachmentObj->getAttachment($msg_part);
333                $info = $attachmentObj->getAttachmentInfo($msg_part);
334                $filename = $info['name'];
335            }
336            else
337                    $filename = $idx_file;
338                   
339            // It's necessary to access calendar method.
340            $GLOBALS['phpgw_info']['flags']['noappheader'] = True;
341            $GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
342            $GLOBALS['phpgw_info']['flags']['currentapp'] = 'calendar';
343
344                        if(isset($params['selected']) || isset($params['readable'])){
345                               
346                                $_REQUEST['data'] = $fileContent;
347                                $_REQUEST['type'] = 'iCal';
348                                $_REQUEST['params']['calendar'] = isset($params['selected']) ? $params['selected'] : false;
349                                $_REQUEST['readable'] = (isset($params['readable']) && $params['readable']) ? true : false;
350                                $_REQUEST['analize'] = isset($params['analize']) ? true : false;
351                                $_REQUEST['params']['status'] = isset($params['status']) ? $params['status'] : false;
352                                $_REQUEST['params']['owner'] = $params['uidAccount'];
353                                if(isset($params['acceptedSuggestion'])){
354                                        $_REQUEST['params']['acceptedSuggestion'] = $params['acceptedSuggestion'];
355                                        $_REQUEST['params']['from'] = $params['from'];
356                                }
357                               
358                                ob_start();
359                                include_once(PHPGW_INCLUDE_ROOT.'/prototype/converter.php');
360                                $output = ob_get_clean();                       
361                                $valid = json_decode($output, true);
362
363                                if($_REQUEST['readable']){     
364                                        if(!is_array($valid))
365                                        {
366                                                $output = unserialize($output);
367                                                foreach($output as $key => $value)
368                                                        return $value;
369                                        }
370                                        return false;
371                                }                               
372                                if(empty($output))
373                                        return "error";
374                                return "ok";
375                        }
376                       
377            include_once(PHPGW_INCLUDE_ROOT.'/header.inc.php');
378            $uiicalendar = CreateObject("calendar.uiicalendar");       
379            if(strtoupper($expFolder[0]) == 'USER' && $expFolder[1]) // IF se a conta o ical estiver em uma conta compartilhada
380            {
381                include_once('class.ldap_functions.inc.php');
382                $ldap = new ldap_functions();
383                $account['uid'] = $expFolder[1];
384                $account['uidnumber']  = $ldap->uid2uidnumber($expFolder[1]);
385                $account['mail']  = $ldap->getMailByUid($expFolder[1]);
386
387                return $uiicalendar->import_from_mail($fileContent, $from_ajax,$account);
388            }
389            else
390                return $uiicalendar->import_from_mail($fileContent, $from_ajax);
391
392        }
393
394    function insert_certificate($email,$certificate,$serialnumber,$authoritykeyidentifier=null)
395        {
396                if(!$email || !$certificate || !$serialnumber || !$authoritykeyidentifier)
397                        return false;
398                // Insere uma chave publica na tabela phpgw_certificados.
399                $data = array   ('email' => $email,
400                                                 'chave_publica' => $certificate,
401                                                 'serialnumber' => $serialnumber,
402                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
403
404                if(!$this->db->insert('phpgw_certificados',$data,array(),__LINE__,__FILE__)){
405                return $this->db->Error;
406        }
407        return true;
408        }
409
410        function get_certificate($email=null)
411        {
412                if(!$email) return false;
413                $result = array();
414
415                $where = array ('email' => $email,
416                                                'revogado' => 0,
417                                                'expirado' => 0);
418
419                if(!$this->db->select('phpgw_certificados','chave_publica', $where, __LINE__,__FILE__))
420        {
421            $result['dberr1'] = $this->db->Error;
422            return $result;
423        }
424                $regs = array();
425                while($this->db->next_record())
426        {
427            $regs[] = $this->db->row();
428        }
429                if (count($regs) == 0)
430        {
431            $result['dberr2'] = ' Certificado nao localizado.';
432            return $result;
433        }
434                $result['certs'] = $regs;
435                return $result;
436        }
437
438        function update_certificate($serialnumber=null,$email=null,$authoritykeyidentifier,$expirado,$revogado)
439        {
440                if(!$email || !$serialnumber) return false;
441                if(!$expirado)
442                        $expirado = 0;
443                if(!$revogado)
444                        $revogado = 0;
445
446                $data = array   ('expirado' => $expirado,
447                                                 'revogado' => $revogado);
448
449                $where = array  ('email' => $email,
450                                                 'serialnumber' => $serialnumber,
451                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
452
453                if(!$this->db->update('phpgw_certificados',$data,$where,__LINE__,__FILE__))
454                {
455                        return $this->db->Error;
456                }
457                return true;
458        }
459
460       
461        /**
462     * @abstract Recupera o valor da regra padrão.
463     * @return retorna o valor da regra padrão.
464     */
465        function get_default_max_size_rule()
466        {
467                $query = "SELECT config_value FROM phpgw_config WHERE config_name = 'expressoAdmin_default_max_size'";
468                if(!$this->db->query($query))
469            return false;
470
471        $return = array();
472                       
473                while($this->db->next_record())
474            array_push($return, $this->db->row());
475                       
476                return $return;
477        }
478       
479        /**
480     * @abstract Recupera a regra de um usuário.
481     * @return retorna a regra que o usuário pertence. Caso o usuário não participe de nenhuma regra, retorna false.
482     */
483        function get_rule_by_user($id_user)
484        {
485                $return = array();     
486                $query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user='$id_user' AND configuration_type='MessageMaxSize'";
487               
488                if(!$this->db->query($query))
489            return false;
490               
491                while($this->db->next_record())
492            array_push($return, $this->db->row());
493                       
494                return $return;
495        }
496       
497       
498        function get_rule_by_user_in_groups($id_group)
499        {
500                $return = array();
501                $query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE configuration_type='MessageMaxSize' AND email_user_type='G' AND email_user='".$id_group."'";
502
503                if(!$this->db->query($query))   
504                        return false;   
505                       
506                while($this->db->next_record())
507                        array_push($return, $this->db->row());
508
509                return $return;
510        }
511        function getMaximumRecipientsUser($pUserUID)
512        {
513
514           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$pUserUID.'\' AND configuration_type = \'LimitRecipient\' AND email_user_type = \'U\' ';
515           $this->db->query($query);
516
517           $return = array();
518
519            while($this->db->next_record())
520              $return =  $this->db->row();
521
522            return $return['email_max_recipient'];
523        }
524
525        function getMaximumRecipientsGroup($pGroupsGuidnumbers)
526        {
527           $groupsGuidNumbers = '';
528
529           foreach ($pGroupsGuidnumbers as $guidNumber => $cn)
530             $groupsGuidNumbers .= $guidNumber.', ';
531
532           $groupsGuidNumbers = substr($groupsGuidNumbers,0,-2);
533
534           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user IN ('.$groupsGuidNumbers.') AND configuration_type = \'LimitRecipient\' AND email_user_type = \'G\' ';
535           $this->db->query($query);
536
537           $return = array();
538
539            while($this->db->next_record())
540              $return[] =  $this->db->row();
541
542            $maxSenderReturn = 0;
543
544            foreach ($return as $maxSender)
545            {
546                if($maxSender['email_max_recipient'] > $maxSenderReturn)
547                    $maxSenderReturn = $maxSender['email_max_recipient'];
548            }
549
550            return $maxSenderReturn;
551        }
552
553        function validadeSharedAccounts($user,$grups,$accountsMails)
554        {
555
556             $arrayMailsBlocked = array();
557
558             $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$user.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'U\' ';
559             $this->db->query($query);
560             $this->db->next_record();
561                 if($this->db->row())
562                   return $arrayMailsBlocked;
563
564            foreach ($grups as $guidNumber => $cn)
565            {
566                 $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$guidNumber.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'G\' ';
567                 $this->db->query($query);
568                 $this->db->next_record();
569                 if($this->db->row())
570                     return $arrayMailsBlocked;
571
572            }
573
574            foreach ($accountsMails as $mail)
575            {
576               
577               $blocked = true;
578
579               $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_recipient = \''.$mail.'\' AND configuration_type = \'InstitutionalAccountException\' ';
580               $this->db->query($query);
581           
582                while($this->db->next_record())
583                {
584                    $row =  $this->db->row();
585                   
586                    if(($row['email_user'] == '*' ||  $row['email_user'] == $user) && ($row['email_user_type'] == 'T' || $row['email_user_type'] == 'U'))
587                        $blocked = false;
588                    else if(array_key_exists($row['email_user'], $grups) && $row['email_user_type'] == 'G')
589                         $blocked = false;
590
591                }
592
593                if($blocked == true)
594                    array_push ($arrayMailsBlocked, $mail);
595            }
596
597            return $arrayMailsBlocked;
598        }
599
600                function write_log($action, $about)
601                {
602                        $sql = "INSERT INTO phpgw_expressoadmin_log (date, manager, action, userinfo) "
603                                . "VALUES('now','" . $_SESSION['phpgw_info']['expressomail']['user']['account_lid'] . "','" . strtolower($action) . "','" . strtolower($about) . "')";
604                        if (!$this->db->query($sql)) {
605                        return false;
606                }
607        return true;
608       }
609}
610?>
Note: See TracBrowser for help on using the repository browser.