source: sandbox/2.5.0-expresso1/expressoMail1_2/inc/class.db_functions.inc.php @ 6532

Revision 6532, 20.7 KB checked in by gustavo, 12 years ago (diff)

Ticket #2766 - Remocao das antigas chamadas e funcoes que faziam o CRUD de contatos dinamicos

  • 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        }
149       
150        function getContactsByGroupAlias($alias)
151        {
152                list($alias,$uid) = explode("::",$alias);               
153                $cc_related_ids = $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'];           
154                // Explode personal group, If exists related ids (the user has permission to send email).
155                if(is_array($cc_related_ids) && $uid){
156                        $owner =  array_search($uid,$cc_related_ids);                   
157                }
158               
159                $query = "select C.id_connection, A.names_ordered, C.connection_value from phpgw_cc_contact A, ".
160                "phpgw_cc_contact_conns B, phpgw_cc_connections C,phpgw_cc_contact_grps D,phpgw_cc_groups E where ".
161                "A.id_contact = B.id_contact and B.id_connection = C.id_connection ".
162                "and B.id_typeof_contact_connection = 1 and ".
163                "A.id_owner =".($owner ? $owner : $this->user_id)." and ".                     
164                "D.id_group = E.id_group and ".
165                "D.id_connection = C.id_connection and E.short_name = '".$alias."'";
166
167                if (!$this->db->query($query))
168                {
169                        exit ('Query failed! File: '.__FILE__.' on line'.__LINE__);
170                }
171
172                $return = false;
173
174                while($this->db->next_record())
175                {
176                        $return[] = $this->db->row();
177                }
178
179                return $return;
180        }
181
182        function getAddrs($array_addrs) {
183                $array_addrs_final = array();                           
184
185                for($i = 0; $i < count($array_addrs); $i++){
186                        $j = count($array_addrs_final);
187
188                        if(preg_replace('/\s+/', '', $array_addrs[$i]) != ""){
189
190                                if(strchr($array_addrs[$i],'@') == "") {               
191                                        if(strpos($array_addrs[$i],'<') && strpos($array_addrs[$i],'>')){
192                                                $alias = substr($array_addrs[$i], strpos($array_addrs[$i],'<'), strpos($array_addrs[$i],'>'));
193                                                $alias = str_replace('<','', str_replace('>','',$alias));
194
195                                        }
196                                        else{
197                                                $alias = $array_addrs[$i];                     
198                                                $alias = preg_replace('/\s/', '', $alias);
199                                        }       
200
201                                        $arrayContacts = $this -> getContactsByGroupAlias($alias);
202
203
204                                        if($arrayContacts) {
205                                                foreach($arrayContacts as $index => $contact){
206                                                        if($contact['names_ordered']) {
207                                                                $array_addrs_final[$j] = '"'.$contact['names_ordered'].'" <'.$contact['connection_value'].'>';
208                                                        }
209                                                        else
210                                                                $array_addrs_final[$j] = $contact['connection_value'];
211
212                                                        $j++;
213                                                }
214                                        }else{
215                                                return array("False" => "$alias");
216                                        }
217                                }
218//-- validação email --
219                                else{
220                                        $array_addrs[$i] = trim($array_addrs[$i]);
221                                        preg_match('/<([^>]+)>/', $array_addrs[$i], $match);
222                                        if(count($match) == 2){
223                                        $ex_arr = explode('@', $match[1]);
224                                        }else{
225                                         $ex_arr = explode('@', $array_addrs[$i]);
226                                         }
227                                        if(count($ex_arr) == 2){
228                                                if($ex_arr[0] !== '' && $ex_arr[1] !== ''){
229                                                        if(preg_match("/[^0-9a-zA-Z._-]+/", $ex_arr[0]) == 0 && preg_match("/[^0-9a-zA-Z._-]+/", $ex_arr[1]) == 0){
230                                                                $array_addrs_final[$j] = $array_addrs[$i];
231                                                        }else{
232                                                                return array("False" => "$alias");
233                                                         }
234                                                }else{
235                                                        return array("False" => "$alias");
236                                                 }
237                                        }else{
238                                                return array("False" => "$alias");
239                                         }
240                                }
241//-- fim --
242                        }else{
243                                $array_addrs_final[$j] = $array_addrs[$i];
244                        }
245                }
246                return $array_addrs_final;
247        }
248
249        function getUserByEmail($params){       
250                // Follow the referral
251                $email = $params['email'];
252                $query = 'select A.names_ordered, C.connection_name, C.connection_value, A.photo'.
253                                ' from phpgw_cc_contact A, phpgw_cc_contact_conns B, '.
254                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
255                                ' and B.id_connection = C.id_connection and A.id_contact ='.
256                                '(select A.id_contact from phpgw_cc_contact A, phpgw_cc_contact_conns B,'.
257                                'phpgw_cc_connections C where A.id_contact = B.id_contact'.
258                                ' and B.id_connection = C.id_connection and A.id_owner = '.$this -> user_id.
259                                ' and C.connection_value = \''.$email.'\') and '.
260                                'C.connection_is_default = true and B.id_typeof_contact_connection = 2';
261
262        if (!$this->db->query($query))
263                return null;
264
265
266                if($this->db->next_record()) {
267                        $result = $this->db->row();
268
269                        $obj =  array("cn" => $result['names_ordered'],
270                                          "email" => $email,
271                                          "type" => "personal",
272                                          "telefone" =>  $result['connection_value']);
273
274                        if($result['photo'])
275                                $_SESSION['phpgw_info']['expressomail']['contact_photo'] =  array($result['photo']);                           
276
277                        return $obj;
278                }
279                return $result;
280        }
281       
282        function update_preferences($params){
283                $string_serial = urldecode($params['prefe_string']);                           
284                $string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
285                $query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
286                        " and preference_owner = '".$this->user_id."'";
287
288                if (!$this->db->query($query))
289                        return $this->db->error;
290                else
291                        return array("success" => true);
292        }
293       
294        function import_vcard($params){
295            include_once('class.imap_functions.inc.php');
296            $objImap = new imap_functions();
297            $msg_number = $params['msg_number'];
298            $idx_file = $params['idx_file'];
299            $msg_part = $params['msg_part'];
300            $msg_folder = $params['msg_folder'];
301            $from_ajax = $params['from_ajax'];
302            $encoding = strtolower($params['encoding']);
303            $fileContent = "";
304            $cirus_delimiter = $params['cirus_delimiter'];
305            $expFolder = explode($cirus_delimiter, $msg_folder);
306
307            if($msg_number != null && $msg_part != null && $msg_folder != null && (intval($idx_file == '0' ? '1' : $idx_file)))
308            {
309                require_once PHPGW_INCLUDE_ROOT.'/expressoMail1_2/inc/class.attachment.inc.php';
310                $attachmentObj = new attachment();
311                $attachmentObj->setStructureFromMail($msg_folder,$msg_number);
312                $fileContent = $attachmentObj->getAttachment($msg_part);
313                $info = $attachmentObj->getAttachmentInfo($msg_part);
314                $filename = $info['name'];
315            }
316            else
317                    $filename = $idx_file;
318                   
319            // It's necessary to access calendar method.
320            $GLOBALS['phpgw_info']['flags']['noappheader'] = True;
321            $GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
322            $GLOBALS['phpgw_info']['flags']['currentapp'] = 'calendar';
323
324                        if(isset($params['selected']) || isset($params['readable'])){
325                               
326                                $_REQUEST['data'] = $fileContent;
327                                $_REQUEST['type'] = 'iCal';
328                                $_REQUEST['params']['calendar'] = isset($params['selected']) ? $params['selected'] : false;
329                                $_REQUEST['readable'] = (isset($params['readable']) && $params['readable']) ? true : false;
330                                $_REQUEST['analize'] = isset($params['analize']) ? true : false;
331                                $_REQUEST['params']['status'] = isset($params['status']) ? $params['status'] : false;
332                                $_REQUEST['params']['owner'] = $params['uidAccount'];
333                                if(isset($params['acceptedSuggestion'])){
334                                        $_REQUEST['params']['acceptedSuggestion'] = $params['acceptedSuggestion'];
335                                        $_REQUEST['params']['from'] = $params['from'];
336                                }
337                               
338                                ob_start();
339                                include_once(PHPGW_INCLUDE_ROOT.'/prototype/converter.php');
340                                $output = ob_get_clean();                       
341                                $valid = json_decode($output, true);
342
343                                if($_REQUEST['readable']){     
344                                        if(!is_array($valid))
345                                        {
346                                                $output = unserialize($output);
347                                                foreach($output as $key => $value)
348                                                        return $value;
349                                        }
350                                        return false;
351                                }                               
352                                if(empty($output))
353                                        return "error";
354                                return "ok";
355                        }
356                       
357            include_once(PHPGW_INCLUDE_ROOT.'/header.inc.php');
358            $uiicalendar = CreateObject("calendar.uiicalendar");       
359            if(strtoupper($expFolder[0]) == 'USER' && $expFolder[1]) // IF se a conta o ical estiver em uma conta compartilhada
360            {
361                include_once('class.ldap_functions.inc.php');
362                $ldap = new ldap_functions();
363                $account['uid'] = $expFolder[1];
364                $account['uidnumber']  = $ldap->uid2uidnumber($expFolder[1]);
365                $account['mail']  = $ldap->getMailByUid($expFolder[1]);
366
367                return $uiicalendar->import_from_mail($fileContent, $from_ajax,$account);
368            }
369            else
370                return $uiicalendar->import_from_mail($fileContent, $from_ajax);
371
372        }
373
374    function insert_certificate($email,$certificate,$serialnumber,$authoritykeyidentifier=null)
375        {
376                if(!$email || !$certificate || !$serialnumber || !$authoritykeyidentifier)
377                        return false;
378                // Insere uma chave publica na tabela phpgw_certificados.
379                $data = array   ('email' => $email,
380                                                 'chave_publica' => $certificate,
381                                                 'serialnumber' => $serialnumber,
382                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
383
384                if(!$this->db->insert('phpgw_certificados',$data,array(),__LINE__,__FILE__)){
385                return $this->db->Error;
386        }
387        return true;
388        }
389
390        function get_certificate($email=null)
391        {
392                if(!$email) return false;
393                $result = array();
394
395                $where = array ('email' => $email,
396                                                'revogado' => 0,
397                                                'expirado' => 0);
398
399                if(!$this->db->select('phpgw_certificados','chave_publica', $where, __LINE__,__FILE__))
400        {
401            $result['dberr1'] = $this->db->Error;
402            return $result;
403        }
404                $regs = array();
405                while($this->db->next_record())
406        {
407            $regs[] = $this->db->row();
408        }
409                if (count($regs) == 0)
410        {
411            $result['dberr2'] = ' Certificado nao localizado.';
412            return $result;
413        }
414                $result['certs'] = $regs;
415                return $result;
416        }
417
418        function update_certificate($serialnumber=null,$email=null,$authoritykeyidentifier,$expirado,$revogado)
419        {
420                if(!$email || !$serialnumber) return false;
421                if(!$expirado)
422                        $expirado = 0;
423                if(!$revogado)
424                        $revogado = 0;
425
426                $data = array   ('expirado' => $expirado,
427                                                 'revogado' => $revogado);
428
429                $where = array  ('email' => $email,
430                                                 'serialnumber' => $serialnumber,
431                                                 'authoritykeyidentifier' => $authoritykeyidentifier);
432
433                if(!$this->db->update('phpgw_certificados',$data,$where,__LINE__,__FILE__))
434                {
435                        return $this->db->Error;
436                }
437                return true;
438        }
439
440       
441        /**
442     * @abstract Recupera o valor da regra padrão.
443     * @return retorna o valor da regra padrão.
444     */
445        function get_default_max_size_rule()
446        {
447                $query = "SELECT config_value FROM phpgw_config WHERE config_name = 'expressoAdmin_default_max_size'";
448                if(!$this->db->query($query))
449            return false;
450
451        $return = array();
452                       
453                while($this->db->next_record())
454            array_push($return, $this->db->row());
455                       
456                return $return;
457        }
458       
459        /**
460     * @abstract Recupera a regra de um usuário.
461     * @return retorna a regra que o usuário pertence. Caso o usuário não participe de nenhuma regra, retorna false.
462     */
463        function get_rule_by_user($id_user)
464        {
465                $return = array();     
466                $query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user='$id_user' AND configuration_type='MessageMaxSize'";
467               
468                if(!$this->db->query($query))
469            return false;
470               
471                while($this->db->next_record())
472            array_push($return, $this->db->row());
473                       
474                return $return;
475        }
476       
477       
478        function get_rule_by_user_in_groups($id_group)
479        {
480                $return = array();
481                $query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE configuration_type='MessageMaxSize' AND email_user_type='G' AND email_user='".$id_group."'";
482
483                if(!$this->db->query($query))   
484                        return false;   
485                       
486                while($this->db->next_record())
487                        array_push($return, $this->db->row());
488
489                return $return;
490        }
491        function getMaximumRecipientsUser($pUserUID)
492        {
493
494           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$pUserUID.'\' AND configuration_type = \'LimitRecipient\' AND email_user_type = \'U\' ';
495           $this->db->query($query);
496
497           $return = array();
498
499            while($this->db->next_record())
500              $return =  $this->db->row();
501
502            return $return['email_max_recipient'];
503        }
504
505        function getMaximumRecipientsGroup($pGroupsGuidnumbers)
506        {
507           $groupsGuidNumbers = '';
508
509           foreach ($pGroupsGuidnumbers as $guidNumber => $cn)
510             $groupsGuidNumbers .= $guidNumber.', ';
511
512           $groupsGuidNumbers = substr($groupsGuidNumbers,0,-2);
513
514           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user IN ('.$groupsGuidNumbers.') AND configuration_type = \'LimitRecipient\' AND email_user_type = \'G\' ';
515           $this->db->query($query);
516
517           $return = array();
518
519            while($this->db->next_record())
520              $return[] =  $this->db->row();
521
522            $maxSenderReturn = 0;
523
524            foreach ($return as $maxSender)
525            {
526                if($maxSender['email_max_recipient'] > $maxSenderReturn)
527                    $maxSenderReturn = $maxSender['email_max_recipient'];
528            }
529
530            return $maxSenderReturn;
531        }
532
533        function validadeSharedAccounts($user,$grups,$accountsMails)
534        {
535
536             $arrayMailsBlocked = array();
537
538             $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$user.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'U\' ';
539             $this->db->query($query);
540             $this->db->next_record();
541                 if($this->db->row())
542                   return $arrayMailsBlocked;
543
544            foreach ($grups as $guidNumber => $cn)
545            {
546                 $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$guidNumber.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'G\' ';
547                 $this->db->query($query);
548                 $this->db->next_record();
549                 if($this->db->row())
550                     return $arrayMailsBlocked;
551
552            }
553
554            foreach ($accountsMails as $mail)
555            {
556               
557               $blocked = true;
558
559               $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_recipient = \''.$mail.'\' AND configuration_type = \'InstitutionalAccountException\' ';
560               $this->db->query($query);
561           
562                while($this->db->next_record())
563                {
564                    $row =  $this->db->row();
565                   
566                    if(($row['email_user'] == '*' ||  $row['email_user'] == $user) && ($row['email_user_type'] == 'T' || $row['email_user_type'] == 'U'))
567                        $blocked = false;
568                    else if(array_key_exists($row['email_user'], $grups) && $row['email_user_type'] == 'G')
569                         $blocked = false;
570
571                }
572
573                if($blocked == true)
574                    array_push ($arrayMailsBlocked, $mail);
575            }
576
577            return $arrayMailsBlocked;
578        }
579
580                function write_log($action, $about)
581                {
582                        $sql = "INSERT INTO phpgw_expressoadmin_log (date, manager, action, userinfo) "
583                                . "VALUES('now','" . $_SESSION['phpgw_info']['expressomail']['user']['account_lid'] . "','" . strtolower($action) . "','" . strtolower($about) . "')";
584                        if (!$this->db->query($sql)) {
585                        return false;
586                }
587        return true;
588       }
589}
590?>
Note: See TracBrowser for help on using the repository browser.