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

Revision 7673, 20.8 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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