Ignore:
Timestamp:
11/03/11 13:24:28 (12 years ago)
Author:
wmerlotto
Message:

Ticket #2305 - Enviando alteracoes, desenvolvidas internamente na Prognus, do modulo ExpressoMail?.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/expressoMail1_2/inc/class.imap_functions.inc.php

    r5083 r5134  
    2727        var $foldersLimit; 
    2828        var $imap_sentfolder; 
     29        var $rawMessage; 
    2930 
    3031        function imap_functions (){ 
     32                $this->init(); 
     33        } 
     34         
     35        function init(){ 
    3136                $this->foldersLimit = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] ?  $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] : 20000; //Limit of folders (mailboxes) user can see 
    3237                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid']; 
     
    5358        function open_mbox($folder = False,$force_die=true) 
    5459        { 
    55                 $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"); 
     60                $folder = mb_convert_encoding($folder, "UTF7-IMAP", mb_detect_encoding($folder.'x', 'UTF-8, ISO-8859-1, UTF7-IMAP')); 
    5661                if (is_resource($this->mbox)) 
    5762                { 
     
    8085         } 
    8186 
    82         function parse_error($error){ 
     87        function parse_error($error, $field = ''){ 
    8388                // This error is returned from Imap. 
    8489                if(strstr($error,'Connection refused')) { 
    8590                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later.")); 
    8691                } 
    87                 elseif(strstr($error,'virus')) { 
     92                else if(strstr($error,'virus')) { 
    8893                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected.")); 
     94                } 
     95                else if(strstr($error,'Failed to add recipient:')) { 
     96                        preg_match_all('/:\s([\s\.";@!a-z0-9]+)\s\[SMTP:/', $error, $res); 
     97                        return  str_replace("%1", $res['1']['0'], $this->functions->getLang("SMTP Error: The following recipient addresses failed: %1")); 
     98                } 
     99                else if(strstr($error,'Recipient address rejected')) { 
     100                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Invalid recipients in the message").'.'); 
     101                } 
     102                else if(strstr($error,'Invalid Mail:')) { 
     103                        return  str_replace("%1", $field, $this->functions->getLang("The recipients addresses failed %1")); 
     104                } 
     105                else if(strstr($error,'Message file too big')) { 
     106                        return ($this->functions->getLang("Message file too big.")); 
    89107                } 
    90108                // This condition verifies if SESSION is expired. 
     
    102120                $msg_range_begin = $params['msg_range_begin']; 
    103121                $msg_range_end = $params['msg_range_end']; 
    104                 $sort_box_type = $params['sort_box_type']; 
    105                 $sort_box_reverse = $params['sort_box_reverse']; 
    106                 $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false; 
    107  
    108                 $folder                         = $params['folder']; 
    109                 $msg_range_begin        = $params['msg_range_begin']; 
    110                 $msg_range_end          = $params['msg_range_end']; 
    111                 $sort_box_type          = $params['sort_box_type']; 
    112                 $sort_box_reverse       = $params['sort_box_reverse']; 
    113                 $search_box_type        = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false; 
     122                $sort_box_type          = isset($params['sort_box_type']) ? $params['sort_box_type'] : ''; 
     123                $sort_box_reverse       = isset($params['sort_box_reverse']) ? $params['sort_box_reverse'] : ''; 
     124                $search_box_type        = (isset($params['search_box_type']) && $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" )? $params['search_box_type'] : false; 
    114125 
    115126                if( !$this->mbox || !is_resource( $this->mbox ) ) 
     
    138149                                { 
    139150                                        $temp = $this->get_info_head_msg($msg_number); 
    140                                         //$temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder); 
     151                                        $temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder); 
    141152                                        if(!$temp) 
    142153                                                return false; 
     
    238249                } 
    239250 
     251                if(isset($header->from)) 
    240252                $from = $header->from; 
    241253                $head_array['from'] = array(); 
    242254                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL; 
     255                if(isset($from)) 
    243256                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host; 
    244                 if(!$head_array['from']['name']) 
     257                else 
     258                        $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@"; 
     259                if(!$head_array['from']['name'] || trim($head_array['from']['name']) === '' ) 
    245260                        $head_array['from']['name'] = $head_array['from']['email']; 
     261                if(isset($header->to)) 
    246262                $to = $header->to; 
    247263                $head_array['to'] = array(); 
    248                 if($to[1] && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe. 
     264                if(isset($to[1]) && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe. 
    249265                        $head_array['to']['name'] = $head_array['to']['email'] = NULL; 
    250266                } 
     
    256272                                $head_array['to']['name'] = $head_array['to']['email']; 
    257273                } 
     274                $cc = null; 
     275                $cco = null; 
     276                if(isset($header->cc)){ 
    258277                $cc = $header->cc; 
     278                } 
     279                if(isset($header->bcc)){ 
    259280                $cco = $header->bcc; 
     281                } 
    260282                if ( ($cc) && (!$head_array['to']['name']) ){ 
    261283                        $head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL; 
    262284                        $head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host; 
    263                         if(!$head_array['to']['name']) 
    264                                 $head_array['to']['name'] = $head_array['from']['email']; 
     285                        if(!$head_array['to']['name']){ 
     286                                $head_array['to']['name'] = $head_array['from']['name']; 
     287                                //$head_array['to']['email'] = $head_array['from']['email']; 
     288                        } 
    265289                } 
    266290                else if ( ($cco) && (!$head_array['to']['name']) ){ 
     
    268292                        $head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host; 
    269293                        if(!$head_array['to']['name']) 
    270                                 $head_array['to']['name'] = $head_array['from']['email']; 
     294                                $head_array['to']['name'] = $head_array['from']['name']; 
    271295                } 
    272296                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : ''; 
     297                if($head_array['subject'] == "" || $head_array['subject'] == '' || $head_array['subject'] == null ){ 
     298                        $head_array['subject'] = $this->functions->getLang("(no subject)   "); 
     299                } 
     300         
     301                if($head_array['to']['name'] == 'undisclosed-recipients@' || $head_array['to']['name'] == '@'){ 
     302                        $head_array['to']['name'] = $head_array['from']['name']; 
     303                        $head_array['to']['email'] = $head_array['from']['email']; 
     304                } 
    273305 
    274306                $head_array['Size'] = $header->Size; 
     
    280312        } 
    281313 
    282          
    283314        /** 
    284         * Decodifica a string da mensagem 
    285315        * 
    286316        * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    287         * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    288         * @sponsor    Caixa Econômica Federal 
    289         * @param      $string 
     317        * @param      string $string String a ser decodificada 
     318        * @return     string 
    290319        * @todo       Verificar a possibilidade de se utilizar a função iconv_mime_decode, que é capaz de identificar a codificação por si só, mas que pode ser interpretada de forma diversa dependendo da implementação do sistema 
    291320        * @todo       Executar testes suficientes para validar a funçao iconv_mime_decode em substituição à este método decode_string 
     
    293322        function decode_string($string) 
    294323        { 
     324        $return = ''; 
     325        $decoded = ''; 
    295326                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false)) 
    296327                { 
    297             $retun = ''; 
    298328                        $tmp = imap_mime_header_decode($string); 
    299329                        foreach ($tmp as $tmp1) 
     
    335365          
    336366            } 
    337         else if (eregi('=?', $string)) 
    338             return iconv_mime_decode($string); 
     367        else if( strpos( $string , '=?' ) !== false )  
     368            return $this->htmlspecialchars_encode(iconv_mime_decode( $string )); 
    339369         
    340370 
     
    409439                                                                        $email 
    410440                                                                        ); 
    411                         if(!$status){ 
     441                        if(!$status) { 
     442                                //TODO: remover zip_entry pois ele é tratado apenas ao importar mensagens zipadas 
    412443                                array_push($errors,zip_entry_name($zip_entry)); 
    413444                                zip_entry_close($zip_entry); 
     445                        } 
     446                         
     447                        if ( isset( $tmp_box ) && ! sizeof( $errors ) ) { 
     448                                $mc = imap_check($this->mbox); 
     449 
     450                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 ); 
     451 
     452                                $ids = array( ); 
     453                                foreach ($result as $overview) 
     454                                        $ids[ ] = $overview -> uid; 
     455 
     456                                return implode( ',', $ids ); 
    414457                        } 
    415458                } 
     
    457500                } 
    458501 
    459                 $msg = &new message_components($this->mbox); 
     502                $msg = new message_components($this->mbox); 
    460503                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação. 
    461504                                                             Então uso essa classe para verificar a codificação e o charset, 
     
    492535                                        "\r\n". 
    493536                                        "\r\n". 
    494                                         str_replace("\n","\r\n",$this->decodeBody( 
     537                                        str_replace("\n","\r\n",preg_replace("/<img[^>]+\>/i", " ", $this->decodeBody( 
    495538                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show), 
    496539                                                        $all_body_encoding, $all_body_charset 
    497                                                         ) 
    498                                         ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos. 
     540                                                        )) 
     541                                        ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos. //Remove imagens do corpo, pois estas estão na lista de anexo e serão removidas. 
    499542 
    500543                if(!$status) 
     
    570613                        $attach_params["num_msg"] = $msg_number; 
    571614                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params); 
    572                         $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]); 
    573615                        imap_close($this->mbox); 
    574616                        $this->mbox=false; 
     
    589631 
    590632        /** 
    591         * Retorna a linha do Header da mensagem 
    592         * 
    593633        * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    594634        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    595         * @sponsor    Caixa Econômica Federal 
    596         * @param      $msg_number 
     635        * @param     $msg_number numero da mensagem 
    597636        */ 
    598637        function getRawHeader($msg_number) 
     
    601640        } 
    602641         
    603          
    604642        /** 
    605         * Retorna a linha do Corpo da mensagem 
    606         * 
    607643        * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    608644        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    609         * @sponsor    Caixa Econômica Federal 
    610         * @param      $msg_number 
     645        * @param     $msg_number numero da mensagem 
    611646        */ 
    612647        function getRawBody($msg_number) 
     
    617652         
    618653        /** 
    619         * Constrói o Header da mensagem 
    620         * 
    621654        * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    622655        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    623         * @sponsor    Caixa Econômica Federal 
    624         * @param      $msg 
     656        * @param     $msg mensagem 
    625657        */ 
    626658        function builderMsgHeader($msg) 
     
    654686         
    655687        /** 
    656         * Constrói o corpo da mensagem 
    657         * 
    658         * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    659         * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    660         * @sponsor    Caixa Econômica Federal 
    661         * @param      $structure 
    662         * @param      $content 
    663         * @param      $printHeader 
     688        * Constroe o corpo da msg direto na variavel de conteudo 
     689        * @param Mail_mimeDecode $structure 
     690        * @param <type> $content Ponteiro para Variavel de conteudo da msg 
    664691        */ 
    665692        function builderMsgBody($structure , &$content , $printHeader = false) 
     
    676703                    { 
    677704                       case 'text': 
    678                            $disposition = strtolower($part->disposition); 
     705                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : ''; 
    679706                           if($disposition != 'attachment') 
    680707                           { 
     
    694721                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>'; 
    695722                                } 
    696  
    697  
     723                                if(strtolower($part->ctype_secondary) == 'calendar') 
     724                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset'])); 
    698725 
    699726                           } 
     
    735762                   { 
    736763                       case 'text': 
    737                             
    738                            $disposition = strtolower($part->disposition); 
     764                           $disposition = ''; 
     765                           if(isset($part->disposition)) 
     766                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : ''; 
    739767                           if($disposition != 'attachment') 
    740768                           { 
     
    754782                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>'; 
    755783                                } 
    756  
     784                                if(strtolower($part->ctype_secondary) == 'calendar') 
     785                                    $content .= $this->builderMsgCalendar($part->body); 
    757786                         
    758787                           } 
     
    767796                            break; 
    768797                       case 'message': 
    769  
     798                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != '1') 
     799                        { 
    770800                            if(!is_array($part->parts)) 
    771801                            { 
     
    781811            } 
    782812        } 
    783          
     813        } 
    784814         
    785815         
    786816        /** 
    787         * Retorna o  
    788         * 
    789817        * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    790818        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    791         * @sponsor    Caixa Econômica Federal 
    792         * @param      $msg_number 
     819        * @param     $msg_number numero da mensagem 
    793820        */ 
    794821        function get_msg_sample($msg_number) 
    795822        { 
     823        $content = ''; 
    796824 
    797825                $return = "";  
     
    804832 
    805833                include_once("class.message_components.inc.php"); 
    806                 $msg = &new message_components($this->mbox); 
     834                $msg = new message_components($this->mbox); 
    807835                $msg->fetch_structure($msg_number);   
    808836 
    809                 if(!$msg->structure[$msg_number]->parts) 
     837                if(!isset($msg->structure[$msg_number]->parts)) 
    810838                { 
    811839                        $content = ''; 
     
    827855                        } 
    828856                } 
    829                 $content = $this->replace_special_characters($content); 
     857       
    830858                $tags_replace = array("<br>","<br/>","<br />"); 
    831                 $content = str_replace($tags_replace," ", $content); 
    832                 $content = strip_tags($content); 
    833                 $content = str_replace(array("{","}","&nbsp;"), " ", $content); 
    834                 $content = trim($content); 
    835                 $content = html_entity_decode(substr($content,0,300)); 
     859                $content = str_replace($tags_replace," ", nl2br($content)); 
     860                $content = $this->html2txt($content);    
    836861                $content != "" ? $return['body'] = " - " . $content: $return['body'] = ""; 
     862                $return['body'] = base64_encode(mb_convert_encoding(substr($return['body'], 0, 305),'ISO-8859-1')); 
    837863                return $return; 
    838864        } 
     865    function html2txt($document){ 
     866        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript 
     867                       '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags 
     868                       '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly 
     869                       '@<![\s\S]*?--[ \t\n\r]*>@si'         // Strip multi-line comments including CDATA                     
     870        ); 
     871        $text = preg_replace($search, '', $document); 
     872        return html_entity_decode($text); 
     873    }  
     874 
     875    function ope_msg_part($params) 
     876    { 
     877        $return = array(); 
     878        require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php'; 
    839879         
     880        $atObj = new attachment(); 
     881        $atObj->setStructureFromMail($params['msg_folder'],$params['msg_number']); 
     882        $mbox_stream = $this->open_mbox($params['save_folder']); 
     883        $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], $atObj->getAttachment($params['msg_part']), "\\Seen \\Draft"); 
     884        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], SA_UIDNEXT); 
    840885         
     886        $return['msg_folder']  = $params['save_folder']; 
     887        $return['msg_number'] = $status->uidnext - 1;         
     888 
     889        return $return; 
     890 
     891    } 
    841892         
    842893        function get_info_msg($params) 
     
    846897                $msg_folder = urldecode($params['msg_folder']); 
    847898                 
    848                 if(preg_match('(.+)(_[a-zA-Z0-9]+)',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.  
     899                if(preg_match('/(.+)(_[a-zA-Z0-9]+)/',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.  
    849900                        $msg_number = $matches[1]; 
    850901                        $plus_id = $matches[2]; 
     
    879930            $return['attachments']      = $return_get_body['attachments']; 
    880931            $return['thumbs']           = $return_get_body['thumbs']; 
    881             $return['signature']        = $return_get_body['signature']; 
     932            //$return['signature']      = $return_get_body['signature']; 
    882933                } 
    883934                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm'; 
     
    906957                $return['msg_folder'] = $msg_folder; 
    907958 
    908                 $date_msg = gmdate("d/m/Y",$header->udate); 
    909                 if (date("d/m/Y") == $date_msg) 
    910                         $return['udate'] = gmdate("H:i",$header->udate); 
    911                 else 
    912                         $return['udate'] = $date_msg; 
     959                 
     960                 
     961                $msgTimesTamp = $header->udate + $this->functions->CalculateDateOffset(); //Aplica offset do usuario 
     962                $date_msg = gmdate("d/m/Y",$msgTimesTamp); 
     963 
     964//      Removido codigo pois a o método send_nofication precisa da data completa. 
     965//              if (date("d/m/Y") == $date_msg) 
     966//                      $return['udate'] = gmdate("H:i",$header->udate); 
     967//              else 
     968 
     969//      Passa o a data completa para mensagem.           
     970                $return['udate'] = $header->udate; 
    913971 
    914972                $return['msg_day'] = $date_msg; 
    915                 $return['msg_hour'] = gmdate("H:i",$header->udate); 
     973                $return['msg_hour'] = gmdate("H:i",$msgTimesTamp); 
    916974 
    917975                if (date("d/m/Y") == $date_msg) //no dia 
    918976                { 
    919                         $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate); 
    920                         $return['smalldate'] = gmdate("H:i",$header->udate); 
    921  
    922                         $timestamp_now = strtotime("now") + $offset; 
    923                         $timestamp_msg_time = $header->udate; 
     977                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp); 
     978                        $return['smalldate'] = gmdate("H:i",$msgTimesTamp); 
     979                         
     980 
     981                                $timestamp_now = strtotime("now"); 
     982                        //      removido offset nao esta sendo parametrizado 
     983                        //      $timestamp_now = strtotime("now") + $offset; 
     984                         
     985                         
     986                        $timestamp_msg_time = $msgTimesTamp; 
    924987                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.  
    925988                        // The variable $timestamp_diff is calculated without MailDate TZ. 
     
    9451008                } 
    9461009                else{ 
    947                         $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate); 
    948                         $return['smalldate'] = gmdate("d/m/Y",$header->udate); 
     1010                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp); 
     1011                        $return['smalldate'] = gmdate("d/m/Y",$msgTimesTamp); 
    9491012                } 
    9501013 
    9511014                $from = $header->from; 
    9521015                $return['from'] = array(); 
    953                 $return['from']['name'] = $this->decode_string($from[0]->personal); 
     1016                $return['from']['name'] = isset($sender[0]->personal) ? $this->decode_string($from[0]->personal) : ''; 
    9541017                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host); 
    9551018                if ($return['from']['name']) 
     
    9661029                $sender = $header->sender; 
    9671030                $return['sender'] = array(); 
    968                 $return['sender']['name'] = $this->decode_string($sender[0]->personal); 
     1031                $return['sender']['name'] = isset($sender[0]->personal) ? $this->decode_string($sender[0]->personal): ''; 
    9691032                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host); 
     1033                 
    9701034                if ($return['sender']['name']) 
    9711035                { 
     
    10141078                        $return['toaddress2'] = ""; 
    10151079                }        
    1016  
     1080                if(isset($header->cc)) 
    10171081                $cc = $header->cc; 
    10181082                $return['cc'] = ""; 
     
    10271091                                        $return['cc'] .= " "; 
    10281092                                        $return['cc'] .= "&lt;"; 
     1093                                        if ($tmp_cc->host != 'unspecified-domain') 
    10291094                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host; 
     1095                                        else 
     1096                                                $return['cc'] .= $tmp_cc->mailbox; 
     1097                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host; 
    10301098                                        $return['cc'] .= "&gt;"; 
    10311099                                        $return['cc'] .= ", "; 
     
    10331101                                else 
    10341102                                { 
     1103                                        if ($tmp_cc->host != 'unspecified-domain') 
    10351104                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host; 
     1105                                        else 
     1106                                                $return['cc'] .= $tmp_cc->mailbox; 
     1107                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host; 
    10361108                                        $return['cc'] .= ", "; 
    10371109                                } 
     
    10491121                # @BRIEF Adding the BCC field. 
    10501122                ## 
    1051                  
     1123        if(isset($header->bcc)){         
    10521124                $bcc = $header->bcc; 
     1125                } 
    10531126                $return['bcc'] = ""; 
    10541127                if (!empty($bcc)) 
     
    10621135                                        $return['bcc'] .= " "; 
    10631136                                        $return['bcc'] .= "&lt;"; 
     1137                                        if ($tmp_bcc->host != 'unspecified-domain') 
    10641138                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host; 
     1139                                        else 
     1140                                                $return['bcc'] .= $tmp_bcc->mailbox; 
    10651141                                        $return['bcc'] .= "&gt;"; 
    10661142                                        $return['bcc'] .= ", "; 
     
    10681144                                else 
    10691145                                { 
     1146                                        if ($tmp_bcc->host != 'unspecified-domain') 
    10701147                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host; 
     1148                                        else 
     1149                                                $return['bcc'] .= $tmp_bcc->mailbox; 
     1150                                        //$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host; 
    10711151                                        $return['bcc'] .= ", "; 
    10721152                                } 
     
    11071187                $return['reply_to'] = $this->decode_string($return['reply_to']); 
    11081188                $return['subject'] = $this->decode_string($header->fetchsubject); 
     1189 
     1190                if($return['subject'] == $this->functions->getLang("(no subject)   ")){ 
     1191                        $return['subject'] = str_replace(" ","", $return['subject']); 
     1192                } 
     1193                if($return['subject'] == '' || $return['subject'] == null){ 
     1194                        $return['subject'] = $this->functions->getLang("(no subject)   "); 
     1195                } 
    11091196                $return['Size'] = $header->Size; 
    11101197                $return['reply_toaddress'] = $header->reply_toaddress; 
     
    11151202                $return['reply_toaddress'] = $header->reply_toaddress; 
    11161203                 
     1204                if(($return['from']['email'] ==  '@unspecified-domain' || $return['sender']['email'] == null) && $return['msg_folder'] == 'INBOX/Drafts'){ 
     1205                        $return['from']['email'] = "Rascunho"; 
     1206                } 
     1207                if($return['toaddress2'] == 'undisclosed-recipients@, @'){ 
     1208                        $return['toaddress2'] = $this->functions->getLang('without destination'); 
     1209                } 
    11171210                return $return; 
    11181211        } 
    11191212 
    11201213         
    1121         /** 
     1214        /*  
    11221215        * Converte textos utf8 para o padrão html. 
    1123         * 
    1124         * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    1125         * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    1126         * @sponsor    Caixa Econômica Federal 
     1216         * Modificado por Cristiano Corrêa Schmidt 
     1217         * @link http://php.net/manual/en/function.utf8-decode.php  
    11271218        * @author     luka8088 <luka8088@gmail.com>  
    1128         * @param      $data 
    11291219        */       
    11301220        function utf8_to_html ($data)  
     
    11381228                foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)  
    11391229                        $ret += (ord($v) % 128) * pow(64, $k);  
    1140                     return "&#$ret;";  
     1230                    return html_entity_decode("&#$ret;" , ENT_QUOTES);  
    11411231                }  
    11421232        //------------------------------------------------------------------------------//  
    11431233 
    11441234 
    1145          
    1146          
    11471235                /** 
    1148                 * Decodifica a parte do email 
    1149                 * 
    1150                 * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    1151                 * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    1152                 * @sponsor    Caixa Econômica Federal 
    1153                 * @param      $part 
    1154                 * @param      $encode 
    1155                 * @param      $html 
     1236         * Decodifica uma part da mensagem para iso-8859-1 
     1237         * @param <type> $part parte do email 
     1238         * @param <type> $encode codificação da parte 
     1239         * @return <type> string decodificada 
    11561240                */ 
    11571241        function decodeMailPart($part, $encode, $html = true) 
     
    11641248 
    11651249                case 'utf-8': 
    1166                     if ($html)  
    1167                                                 return  $this->utf8_to_html($part);  
    1168                 else 
    1169                                                 return  utf8_decode ($part); 
     1250                    if ($html) return  $this->utf8_to_html($part); 
     1251                    else       return  utf8_decode ($part); 
    11701252                    break; 
    11711253 
     
    11851267            require_once $_SESSION['rootPath'].'/library/mime/mimeDecode.php'; 
    11861268            require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php'; 
    1187                 include_once("class.message_components.inc.php"); 
     1269            //include_once("class.message_components.inc.php"); 
    11881270            //--------------------------------------------------------------------// 
    11891271 
    11901272            $return = array(); 
    11911273 
    1192                 $msg = &new message_components($this->mbox); 
    1193                 $msg->fetch_structure($msg_number); 
     1274//            $msg = new message_components($this->mbox); 
     1275//            $msg->fetch_structure($msg_number); 
    11941276 
    11951277            $content = ''; 
    11961278 
    1197             $rawMessageData = $this->getRawHeader($msg_number).$this->getRawBody($msg_number); 
     1279            /*  
     1280            * Chamada original  $this->getRawHeader($msg_number)."\r\n".$this->getRawBody($msg_number);  
     1281            * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios  
     1282            */  
     1283            $rawMessageData = str_replace("\r\n\t", '', $this->getRawHeader($msg_number))."\r\n".$this->getRawBody($msg_number);  
    11981284 
    11991285            $decoder = new Mail_mimeDecode($rawMessageData); 
     
    12021288            $params['decode_bodies']  = true; 
    12031289            $params['decode_headers'] = true; 
     1290                        if(array_key_exists('nested_messages_are_shown', $_SESSION['phpgw_info']['user']['preferences']['expressoMail']) && ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] == '1')) 
     1291                                $params['rfc_822bodies']  = true; 
    12041292            $structure = $decoder->decode($params); 
    12051293 
     
    12271315                { 
    12281316                    $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder); 
    1229                         $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder); 
     1317               // $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder); 
    12301318                } 
    12311319 
     
    12411329 
    12421330                        $msg_subtype = strtolower($structure->ctype_secondary); 
     1331                    if(isset($structure->disposition)) 
    12431332                        $disposition = strtolower($structure->disposition); 
     1333                    else 
     1334                        $disposition = ''; 
    12441335 
    12451336                        if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment')) 
    12461337                        { 
    1247  
    1248  
    12491338                                if(strtolower($msg_subtype) == 'plain') 
    12501339                                        {  
     1340                        if(isset($structure->ctype_parameters['charset'])) 
    12511341                                        $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false); 
     1342                        else 
     1343                            $content = $this->decodeMailPart($structure->body, null,false); 
    12521344                                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );  
    12531345                                                $content = htmlentities( $content );  
     
    12601352                                                                $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']); 
    12611353                                } 
     1354                    if(strtolower($structure->ctype_secondary) == 'calendar') 
     1355                           $content .= $this->builderMsgCalendar($structure->body); 
    12621356 
    12631357                    break; 
    12641358 
    12651359               case 'multipart': 
    1266                     $this-> builderMsgBody($structure , $content); 
     1360                    $this->builderMsgBody($structure , $content); 
    12671361 
    12681362                    break; 
    12691363 
    12701364               case 'message': 
     1365                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != 1) 
     1366                    { 
    12711367                    if(!is_array($structure->parts)) 
    12721368                                { 
     
    12771373                                            else 
    12781374                        $this->builderMsgBody($structure , $content,true); 
    1279  
     1375                    } 
    12801376                    break; 
    12811377 
     1378            case 'application': 
     1379                if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime') 
     1380                {    
     1381                  //  $return['body']='isCripted'; 
     1382                  // return $return; 
     1383                                   
     1384                                  //TODO: Descartar código após atualização do módulo de segurança da SERPRO 
     1385                                        $rawMessageData2 = $this->extractSignedContents($rawMessageData);  
     1386                                        if($rawMessageData2 === false){  
     1387                                                $return['body']='isCripted';  
     1388                                                return $return;  
     1389                                        }  
     1390                                        $decoder2 = new Mail_mimeDecode($rawMessageData2);  
     1391                            $structure2 = $decoder2->decode($params);  
     1392                            $this-> builderMsgBody($structure2 , $content);   
     1393                  
     1394                            $attachmentManager->setStructure($structure2);  
     1395                            /*  
     1396                            * Monta informações dos anexos para o cabecarios  
     1397                            */  
     1398                            $attachments = $attachmentManager->getAttachmentsInfo();  
     1399                        $return['attachments'] = $attachments;  
     1400 
     1401                            //----------------------------------------------//  
     1402                  
     1403                            /*  
     1404                        * Monta informações das imagens  
     1405                            */  
     1406                            $images = $attachmentManager->getEmbeddedImagesInfo();  
     1407                            //----------------------------------------------//  
     1408                  
     1409                            if(!$this->has_cid){  
     1410                                $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);  
     1411                                $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);  
     1412                            } 
     1413                } 
     1414                        /////////////////////////////////////////////////////////////////////////////////////////// 
    12821415               default: 
    12831416                    if(count($attachments) > 0) 
    12841417                       $content .= ''; 
    1285                     else  
    1286                                                                 {  
    1287                        $content .= $this->functions->getLang('Message not supported') . '. '; 
    1288                        $content .= $this->functions->getLang('Type') . ': ' . $structure->ctype_primary . '/' . $structure->ctype_secondary; 
    1289                                                                 }  
    12901418                    break; 
    12911419                                                                }  
     
    13011429        } 
    13021430 
     1431         
     1432        //TODO: Descartar código após atualização do módulo de segurança da SERPRO 
     1433        function extractSignedContents( $data )  
     1434    {  
     1435                $pipes_desc = array(  
     1436                        0 => array('pipe', 'r'),  
     1437                        1 => array('pipe', 'w')  
     1438            );  
     1439          
     1440            $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes);  
     1441            if (!is_resource($fp)) {  
     1442                        return false;  
     1443            }  
     1444          
     1445            $output = '';  
     1446          
     1447                /* $pipes[0] => writeable handle connected to child stdin  
     1448                $pipes[1] => readable handle connected to child stdout */  
     1449            fwrite($pipes[0], $data);  
     1450            fclose($pipes[0]);  
     1451          
     1452            while (!feof($pipes[1])) {  
     1453                        $output .= fgets($pipes[1], 1024);  
     1454            }  
     1455            fclose($pipes[1]);  
     1456            proc_close($fp);  
     1457          
     1458            return $output;  
     1459        } 
     1460    /////////////////////////////////////////////////////////////////////////////////////// 
     1461     
     1462        function builderMsgCalendar($calendar) 
     1463        { 
     1464            $icalService = ServiceLocator::getService('ical'); 
     1465 
     1466            $codificao =  mb_detect_encoding($calendar.'x', 'UTF-8, ISO-8859-1'); 
     1467            if($codificao == 'UTF-8') 
     1468                $calendar = utf8_decode($calendar); 
     1469 
     1470            if($icalService->setIcal($calendar)) 
     1471            { 
     1472                $content = ''; 
     1473 
     1474                switch ($icalService->getMethod()) { 
     1475 
     1476                    case 'REPLY': 
     1477                          include_once($_SESSION['rootPath'].'/header.inc.php'); 
     1478                          include_once($_SESSION['rootPath'].'/calendar/inc/class.boicalendar.inc.php'); 
     1479                          $boicalendar = new boicalendar(); 
     1480 
     1481                          $ical = $icalService->getComponent('vevent'); 
     1482                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />'; 
     1483                          $content.= '<span style="font-size: 12" >'; 
     1484                          $notExist = false; 
     1485 
     1486                          foreach ($ical['attendee'] as $attendee) 
     1487                          { 
     1488                                if($attendee['params']['PARTSTAT'] == 'ACCEPTED') 
     1489                                { 
     1490                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'ACCEPTED',$attendee['params']['CN'])) 
     1491                                    { 
     1492                                        $content.= $this->functions->getLang('User').' '; 
     1493                                        if($attendee['params']['CN']) 
     1494                                            $content.= '<b>'.$attendee['params']['CN'].'</b> '; 
     1495                                        else 
     1496                                            $content.= '<b>'.$attendee['value'].'</b> '; 
     1497 
     1498                                        $content.= $this->functions->getLang('accepted your event'); 
     1499                                    } 
     1500                                    else 
     1501                                        $notExist = true; 
     1502                                } 
     1503 
     1504                                if($attendee['params']['PARTSTAT'] == 'TENTATIVE') 
     1505                                { 
     1506                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'TENTATIVE',$attendee['params']['CN'])) 
     1507                                    { 
     1508                                        $content.= $this->functions->getLang('User').' '; 
     1509                                        if($attendee['params']['CN']) 
     1510                                            $content.= '<b>'.$attendee['params']['CN'].'</b> '; 
     1511                                        else 
     1512                                            $content.= '<b>'.$attendee['value'].'</b> '; 
     1513 
     1514                                        if($ical['description']['value']) 
     1515                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value'])); 
     1516                                        else 
     1517                                            $content.= $this->functions->getLang('provisionally accepted you event'); 
     1518                                    } 
     1519                                    else 
     1520                                         $notExist = true; 
     1521                                } 
     1522 
     1523                                if($attendee['params']['PARTSTAT'] == 'DECLINED') 
     1524                                { 
     1525                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'DECLINED',$attendee['params']['CN'])) 
     1526                                    { 
     1527                                        $content.= $this->functions->getLang('User').' '; 
     1528                                        if($attendee['params']['CN']) 
     1529                                            $content.= '<b>'.$attendee['params']['CN'].'</b> '; 
     1530                                        else 
     1531                                            $content.= '<b>'.$attendee['value'].'</b> '; 
     1532 
     1533                                        if($ical['description']['value']) 
     1534                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value'])); 
     1535                                        else 
     1536                                            $content.= $this->functions->getLang('provisionally decline you event'); 
     1537                                    } 
     1538                                    else 
     1539                                        $notExist = true; 
     1540                                } 
     1541                          } 
     1542                          if($notExist) 
     1543                            $content.= '<b><span style="color:red">'.$this->functions->getLang('This event does not exist on its agenda').'.</span></b>'; 
     1544                          $content.= '</span><br /><br />'; 
     1545 
     1546                        break; 
     1547 
     1548                      case 'CANCEL': 
     1549 
     1550                          $ical = $icalService->getComponent('vevent'); 
     1551                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />'; 
     1552                          $content.= '<span style="font-size: 12" >'; 
     1553                          $content.= '<b><span style="color:red">'.$this->functions->getLang('Your event has been canceled').'</span></b>'; 
     1554    
     1555                          if($ical['description']['value']) 
     1556                              $content.= ' <br /> <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value'])); 
     1557 
     1558                          $content.= '<br /><b>* '.$this->functions->getLang('To remove the event from your calendar to import the iCal file attached').'.</b>'; 
     1559                          $content.= '</span><br /><br />'; 
     1560                        break; 
     1561 
     1562                    case 'REQUEST': 
     1563 
     1564                        $ical = $icalService->getComponent('vevent'); 
     1565                        if($ical['dtstart']['value']['tz'] == 'Z') 
     1566                        { 
     1567                            $tz = $_SESSION['phpgw_info']['user']['preferences']['common']['tz_offset']; 
     1568                            $ical['dtstart']['value']['hour'] += $tz; 
     1569                            $ical['dtend']['value']['hour'] += $tz; 
     1570                        } 
     1571                         
     1572                        $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br />'. 
     1573                                   ' <br /> <b>'.$this->functions->getLang('Title').': </b>'.$ical['summary']['value']. 
     1574                                   ' <br /> <b>'.$this->functions->getLang('Location').': </b>'.$ical['location']['value']. 
     1575                                   ' <br /> <b>'.$this->functions->getLang('Details').': </b>'. str_replace('\n','<br />',nl2br($ical['description']['value'])); 
     1576                        $content.= ' <br /> <b>'.$this->functions->getLang('Start') . ':  </b>' . $ical['dtstart']['value']['day'] . "/" . $ical['dtstart']['value']['month']  . "/" . $ical['dtstart']['value']['year']  . " - " . $ical['dtstart']['value']['hour']  . ":" . $ical['dtstart']['value']['min'] ; 
     1577                        $content.= ' <br /> <b>'.$this->functions->getLang('End') . ': </b>' . $ical['dtend']['value']['day'] . "/" . $ical['dtend']['value']['month']  . "/" . $ical['dtend']['value']['year']  . " - " . $ical['dtend']['value']['hour']  . ":" . $ical['dtend']['value']['min'] ; 
     1578 
     1579                        if($ical['organizer']['params']['CN']) 
     1580                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b>'.$ical['organizer']['params']['CN'].' -  <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a></li>' ; 
     1581                        else 
     1582                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b> <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a>' ; 
     1583 
     1584                        if($ical['attendee']) 
     1585                        { 
     1586                            $att = ' <br /> <b>'.$this->functions->getLang('Participants').': </b>'; 
     1587                            $att .= '<ul> '; 
     1588                            foreach ($ical['attendee'] as $attendee) 
     1589                            { 
     1590                                if($attendee['params']['CN']) 
     1591                                    $att .= '<li>'.$attendee['params']['CN'].' -  <a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ; 
     1592                                else 
     1593                                    $att .= '<li><a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ; 
     1594                            } 
     1595                            $att .= '</ul> <br />'  ; 
     1596                        } 
     1597                        $content.= $att; 
     1598 
     1599                        break; 
     1600                    default: 
     1601                        break; 
     1602                } 
     1603       
     1604            } 
     1605            return $content; 
     1606        } 
     1607         
    13031608        function htmlfilter($body) 
    13041609        { 
     
    14541759                $image['cid'] = eregi_replace("<", "", $image['cid']); 
    14551760                $image['cid'] = eregi_replace(">", "", $image['cid']); 
     1761                                //if is Draft Ticket #1256 
     1762                                $image['cid'] = str_replace("@localhost", "@prognus.org", $image['cid']); 
    14561763                                $body = eregi_replace("<br/>", "", $body); 
    1457                 $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body); 
    1458                 $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body); 
    1459                 $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);    
     1764                                 
     1765                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\" ", $body); 
     1766                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body); 
     1767                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);  
    14601768                        } 
    14611769                return $body; 
     
    14741782                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body); 
    14751783 
     1784                //Remove Comentario Expresso  
     1785                                $findExpCom[] = '<!-- TAG <';  
     1786                                $findExpCom[] = '> Removed by ExpressoMail -->';  
     1787                                $body = str_replace($findExpCom, '', $body);  
     1788                ///--------------------------------//  
     1789 
    14761790                // tags to be removed doe to security reasons 
    14771791                $tag_list = Array( 
    1478                         'head','blink','object','frame','iframe', 
     1792                        'blink','object','frame','iframe', 
    14791793                        'layer','ilayer','plaintext','script', 
    14801794                        'applet','embed','frameset','xml','xmp' 
     
    14821796 
    14831797                foreach($tag_list as $index => $tag) { 
    1484                         $body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", "<!-- TAG <$tag> Removed by ExpressoMail -->", $body);  
    1485                         } 
     1798                        $body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body);  
     1799                        } 
     1800                 
     1801                $body = @mb_eregi_replace("<meta[^>]*>", '', $body); 
     1802                $body = @mb_eregi_replace("<base[^>]*>", '', $body);  
    14861803                 
    14871804                //try to wrap CSS code instead of remove STYLE tags 
     
    14921809                $regs_found = array();  
    14931810                $tags_found = @mb_eregi("<style\b[^>]*>(.*?)</style>", $body, $regs_found); 
     1811                $wrapper_class = 'ExpressoCssWrapper'.time(); 
    14941812                 
    14951813                foreach ($regs_found as $block_found) {  
     
    15041822                         
    15051823                        $prefix = ".$wrapper_class ";  
     1824            if( isset($css->css[41]) && count($css->css[41] > 0)) 
    15061825                        foreach ($css->css[41] as $key => $value) { 
    15071826                                                //explode multiple selectors per block  
     
    15411860            //--------------------------------------------------------------------------------------------//     
    15421861 
    1543                 //$body = $this->replace_links($body); 
    1544  
    15451862                //Remoção de tags <span></span> para correção de erro no firefox 
    1546 //               if($_SESSION['phpgw_session']['phpgw_app_sessions']['phpgwapi']['browser_agent']['content'] != 'IE'){ 
    1547 //                   $body = mb_eregi_replace("<span><span>","",$body); 
    1548 //                   $body = mb_eregi_replace("</span></span>","",$body); 
    1549 //               } 
    1550  
    1551                 $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body); 
    1552                 $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body); 
    1553                 $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body); 
    1554 //Correção para compatibilização com Outlook, ao visualizar a mensagem  
     1863                //Comentado pois estes replaces geram erros no html da msg, não se pode garantir que o os </span></span> sejam realmente os fechamentos dos <span><span>. 
     1864                //Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo. 
     1865                //              $body = mb_eregi_replace("<span><span>","",$body); 
     1866                //              $body = mb_eregi_replace("</span></span>","",$body); 
     1867 
     1868                //Correção para compatibilização com Outlook, ao visualizar a mensagem 
    15551869                $body = mb_ereg_replace('<!--\[','<!-- [',$body);  
    15561870                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body); 
    1557                 $body = mb_ereg_replace('<!\[endif\]-->', '<!--[endif]--->', $body); 
    1558                 $body = str_replace("\x00", '', $body); 
    15591871                 
    15601872                return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>'; 
    1561         } 
    1562  
    1563  
    1564  
     1873 
     1874        } 
    15651875         
    1566         /** 
    1567         * Substitui os links do callback 
    1568         * 
    1569         * @license    http://www.gnu.org/copyleft/gpl.html GPL 
    1570         * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) 
    1571         * @sponsor    Caixa Econômica Federal 
    1572         * @param      $matches 
    1573         */ 
    15741876        function replace_links_callback($matches)   
    15751877        { 
     
    15951897                $replacement = '<a href="://$4$5" target="_blank">$4$5</a>';  
    15961898            $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body); 
    1597                 // E-mail address in the text should create a new e-mail on ExpressoMail 
    1598                 $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';  
    1599                 $replacement = '$1<a href="mailto:$2">$2</a>$3'; 
    1600                 $body = preg_replace( $pattern, $replacement, $body ); 
    16011899 
    16021900        } 
     
    17162014        { 
    17172015 
    1718                 $thumbs_array = array(); 
    1719                 $i = 0; 
    1720  
    1721             foreach ($images as $x => $image) 
    1722         { 
    1723                  if($x && $x == 'names') 
    1724                     continue; 
    1725                   
    1726                  $img = "<img id='".$msg_folder.";;".$msg_number.";;".$i.";;".$image['pid'].";;".$image['encoding']."' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid']." />"; 
    1727                  $href = "./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid']; 
    1728                                  $anchor = "<a class=\"expressomail-thumbs-link\" onMouseDown='save_image(event,this,\"".$image['type']."\")' href=\"".$href."\" onclick=\"window.open('".$href."','mywindow','width=700,height=600,scrollbars=yes');return false;\">". $img ."</a>"; 
    1729                  $thumbs_array[] = $anchor;  
    1730                         $i++; 
     2016                if (!count($images)) return ''; 
    17312017                
     2018                foreach ($images as $key => $value) {  
     2019                        $images[$key]['width']  = 160;  
     2020                        $images[$key]['height'] = 120;  
     2021                        $images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$image['pid']."&image=true";  
    17322022                } 
    1733         return $thumbs_array; 
     2023 
     2024                return json_encode($images);  
    17342025        } 
    17352026 
     
    17552046                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1"); 
    17562047                $msgs_number = explode(",",$params['msgs_number']); 
     2048                if(array_key_exists('border_ID' ,$params)) 
    17572049                $border_ID = $params['border_ID']; 
    1758  
     2050                else 
     2051                        $border_ID = ''; 
    17592052                $return = array(); 
    17602053 
    1761                 if ($params['get_previous_msg']){ 
     2054                if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){ 
    17622055                        $return['previous_msg'] = $this->get_info_previous_msg($params); 
    17632056                        // Fix problem in unserialize function JS. 
     
    17862079        { 
    17872080 
     2081                $return = array(); 
     2082                $return['new_msgs'] = 0; 
    17882083                $folder = $params['folder']; 
    17892084                $msg_range_begin = $params['msg_range_begin']; 
     
    17992094                        return array(); 
    18002095 
     2096                $return['new_msgs'] = imap_num_recent($this->mbox); 
    18012097                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox)); 
     2098 
    18022099                $msgs_in_the_client = explode(",", $msgs_existent); 
    18032100 
    18042101                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client); 
     2102 
     2103                if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){ 
     2104                        $aux = 0; 
     2105                        while(array_key_exists($aux, $msg_to_insert)){ 
     2106                                if($msg_to_insert[$aux] > $msgs_in_the_client[0]){ 
     2107                                        $return['new_msgs'] += 1; 
     2108                                } 
     2109                                $aux++; 
     2110                        } 
     2111                }else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){ 
     2112                        $aux = 0; 
     2113                        while(array_key_exists($aux, $msg_to_insert)){ 
     2114                                if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){ 
     2115                                        $return['new_msgs'] += 1; 
     2116                                } 
     2117                                $aux++; 
     2118                        } 
     2119                }else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0){ 
     2120                        $return['tot_msgs'] = $num_msgs; 
     2121                } 
     2122                 
    18052123                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server); 
    1806  
    18072124                $msgs_to_exec = array(); 
    18082125                foreach($msg_to_insert as $msg_number) 
    18092126                        $msgs_to_exec[] = $msg_number; 
    18102127                //sort($msgs_to_exec); 
    1811  
    1812                 $return = array(); 
    1813                 $return['new_msgs'] = imap_num_recent($this->mbox); 
    18142128                $i = 0; 
    18152129                foreach($msgs_to_exec as $msg_number) 
     
    18642178                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host; 
    18652179                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>'; 
    1866                         if(!$return[$i]['from']['name']) 
     2180                        if(!$return[$i]['from']['name'] || trim($return[$i]['from']['name']) === '') 
    18672181                                $return[$i]['from']['name'] = $return[$i]['from']['email']; 
    18682182 
     
    18732187                        $to = $header->to; 
    18742188                        $return[$i]['to'] = array(); 
     2189                        if(isset($to[0]->personal)) 
    18752190                        $tmp = imap_mime_header_decode($to[0]->personal); 
     2191                        if(trim($return[$i]['to']['name']) === '') 
     2192                                $return[$i]['to']['name'] = $to[0]->mailbox . "@" . $to[0]->host; 
     2193                        else 
    18762194                        $return[$i]['to']['name'] = $tmp[0]->text; 
    18772195                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host; 
    18782196                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>'; 
     2197                        if(isset($header->cc)) 
    18792198                        $cc = $header->cc; 
    1880                         if ( ($cc) && (!$return[$i]['to']['name']) ){ 
     2199 
     2200                        if ( isset($cc) && (!$return[$i]['to']['name'] || $return[$i]['to']['name'] == '@') ){ 
    18812201                                $return[$i]['to']['name'] =  $cc[0]->personal; 
    18822202                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host; 
    18832203                        } 
    1884                         $return[$i]['subject'] = $this->decode_string($header->fetchsubject); 
    1885  
     2204                        $return[$i]['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : ''; 
     2205                        if($return[$i]['subject'] == "" || $return[$i]['subject'] == '' || $return[$i]['subject'] == null ){ 
     2206                                $return[$i]['subject'] = $this->functions->getLang("(no subject)   "); 
     2207                        } 
    18862208                        $return[$i]['Size'] = $header->Size; 
    18872209                        $return[$i]['reply_toaddress'] = $header->reply_toaddress; 
    18882210 
     2211                        if($return[$i]['to']['email'] == '@' || $return[$i]['to']['email'] =='undisclosed-recipients@' || $return[$i]['to']['name'] =='undisclosed-recipients@' 
     2212                                || $return[$i]['to']['name'] == null){ 
     2213                                $return[$i]['to']['email'] = $return[$i]['from']['email']; 
     2214                                $return[$i]['to']['name'] = $return[$i]['from']['name']; 
     2215                                $return[$i]['to']['full'] = $return[$i]['reply_toaddress']; 
     2216                        } 
     2217                         
    18892218                        $return[$i]['attachment'] = array(); 
    18902219                        if (!isset($imap_attachment)) 
     
    19492278        { 
    19502279                $mbox_stream = $this->open_mbox(); 
    1951                 if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){ 
     2280                if($params &&  array_key_exists('onload', $params)   &&  $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){ 
    19522281                        $this->delete_mailbox(array("del_past" => "INBOX".$this->imap_delimiter."decifradas")); 
    19532282                } 
    19542283 
    19552284                $inbox = 'INBOX'; 
     2285                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']; 
     2286                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']; 
     2287                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']; 
    19562288                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']; 
    1957                 $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']; 
    1958                 $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']; 
    1959                 $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']; 
     2289                if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'] )) 
    19602290                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];  
     2291                else 
     2292                        $uid2cn = false; 
    19612293                // Free others requests  
    19622294                session_write_close();  
     
    19642296                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";  
    19652297                 
    1966                 if ( $params && $params['noSharedFolders'] ) 
     2298                if ( $params && isset($params['noSharedFolders']) ) 
    19672299                        $folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) ); 
    19682300                else 
     
    19732305                $tmp = array();  
    19742306                $resultMine = array();  
     2307                $resultSharedMine = array();  
    19752308                $resultDefault = array();  
     2309                $resultSharedDefault = array();  
     2310                $aux = ""; 
     2311                $qtd = -1 ; 
    19762312 
    19772313                if (is_array($folders_list)) { 
     
    19942330                            if( $folderUser != "INBOX" && $folderUser != "" ) 
    19952331                            { 
    1996                                $Permission = imap_getacl( $mbox_stream, $folderUser ); 
     2332                               $Permission = @imap_getacl( $mbox_stream, $folderUser ); 
    19972333                            } 
    1998  
    1999                             if( $Permission ) 
    2000                             { 
    20012334                                $tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" ); 
    20022335 
     
    20052338                                        continue; 
    20062339                                } 
     2340                                 
     2341                                if(isset($status->unseen)) 
    20072342                                $result[$i]['folder_unseen'] = $status->unseen; 
     2343                                 
    20082344                                $folder_id = $tmp_folder_id[1]; 
    20092345                                $result[$i]['folder_id'] = $folder_id; 
     
    20272363                                else 
    20282364                                        $result[$i]['folder_hasChildren'] = 0; 
    2029  
     2365                                $user = explode($this->imap_delimiter , $tmp_folder_id[1]); 
    20302366                                switch ($tmp_folder_id[1]) { 
    20312367                                        case $inbox: 
     2368                                        case $drafts: 
    20322369                                        case $sent: 
    2033                                         case $drafts: 
    20342370                                        case $spam: 
    20352371                                        case $trash: 
    20362372                                                $resultDefault[]=$result[$i]; 
    20372373                                                break; 
     2374                                        case "user". $this->imap_delimiter . $user[1]: 
     2375                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']: 
     2376                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']: 
     2377                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']: 
     2378                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']: 
     2379                                                if($aux != $user[1]){ 
     2380                                                        $aux = $user[1]; 
     2381                                                        $qtd += 1; 
     2382                                                } 
     2383                                                if( isset($resultSharedDefault[$qtd]) && !is_array($resultSharedDefault[$qtd])) 
     2384                                                        $resultSharedDefault[$qtd] = array(); 
     2385                                                $resultSharedDefault[$qtd][]=$result[$i]; 
     2386                                                break;   
    20382387                                        default: 
     2388                                                if($user[0] == $inbox) 
    20392389                                                $resultMine[]=$result[$i]; 
     2390                                                else{ 
     2391                                                        if($aux != $user[1]){ 
     2392                                                                $aux = $user[1]; 
     2393                                                                $qtd += 1; 
     2394                                                        } 
     2395                                                        if(!is_array($resultSharedDefault[$qtd])) 
     2396                                                                $resultSharedMine[$qtd] = array(); 
     2397                                                        $resultSharedMine[$qtd][]=$result[$i]; 
    20402398                                } 
    20412399 
     
    20452403                } 
    20462404 
    2047                 if ( $params && !$params['noQuotaInfo'] ) { 
     2405                if ( $params && !array_key_exists('noQuotaInfo',$params) ) { 
    20482406                        //Get quota info of current folder 
    20492407                        $current_folder = "INBOX"; 
    2050                         if($params && $params['folder']) 
     2408                        if($params && isset($params['folder'])) 
    20512409                                $current_folder = $params['folder']; 
    20522410 
     
    20782436                                        $resultDefault2[0] = $resultDefault[$key]; 
    20792437                                        break; 
    2080                                 case $sent:  
     2438                                case $drafts:  
    20812439                                        $resultDefault2[1] = $resultDefault[$key]; 
    20822440                                        break; 
    2083                                 case $drafts:  
     2441                                case $sent:  
    20842442                                        $resultDefault2[2] = $resultDefault[$key]; 
    20852443                                        break; 
     
    20932451                } 
    20942452                 
    2095                 if ( $params && $params['folderType'] && $params['folderType'] == 'default' ) 
     2453                $shareds = array(); 
     2454                if(!empty($resultSharedDefault)) 
     2455                for($i = 0; $i <= $qtd; $i++){                   
     2456                        foreach ($resultSharedDefault[$i] as $key => $folder_id) 
     2457                        { 
     2458                                $user = explode($this->imap_delimiter , $resultSharedDefault[$i][$key]['folder_id']); 
     2459 
     2460                                switch ($resultSharedDefault[$i][$key]['folder_id']) { 
     2461                                        case "user". $this->imap_delimiter . $user[1]:  
     2462                                                $resultSharedDefault2[0] = $resultSharedDefault[$i][$key]; 
     2463                                                break; 
     2464                                        case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:   
     2465                                                $resultSharedDefault2[1] = $resultSharedDefault[$i][$key]; 
     2466                                                break;   
     2467                                        case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:   
     2468                                                $resultSharedDefault2[2] = $resultSharedDefault[$i][$key]; 
     2469                                                break; 
     2470                                        case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:   
     2471                                                $resultSharedDefault2[3] = $resultSharedDefault[$i][$key]; 
     2472                                                break; 
     2473                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']: 
     2474                                                $resultSharedDefault2[4] = $resultSharedDefault[$i][$key]; 
     2475                                                break; 
     2476                                } 
     2477                        } 
     2478                        if($resultDefault2 != null) 
     2479                                $shareds = array_merge($shareds, $resultSharedDefault2); 
     2480                        if(isset($resultSharedMine[$i]) && $resultSharedMine[$i] != null) 
     2481                                $shareds = array_merge($shareds, $resultSharedMine[$i]); 
     2482                        $resultSharedDefault2 = array(); 
     2483                } 
     2484                if ( $params && isset($params['folderType']) && $params['folderType'] == 'default' ) 
    20962485                        return array_merge($resultDefault2, $arr_quota_info); 
    20972486 
    2098                 if ( $params && $params['folderType'] && $params['folderType'] == 'personal' ) 
     2487                if ( $params && array_key_exists('folderType', $params) && $params['folderType'] == 'personal' ) 
    20992488                        return array_merge($result2, $arr_quota_info); 
    21002489 
    21012490                // Merge default folders and personal 
    21022491                $result2 = array_merge($resultDefault2, $result2); 
    2103                  
     2492                if(!empty($shareds)) 
     2493                        $result2 = array_merge($result2, $shareds); 
    21042494                return array_merge($result2, $arr_quota_info); 
    21052495        } 
     
    22142604        function send_mail($params) 
    22152605        { 
    2216                 include_once("class.phpmailer.php"); 
    2217                 $mail = new PHPMailer(); 
     2606                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php'; 
     2607                $mailService = ServiceLocator::getService('mail'); 
     2608 
    22182609                include_once("class.db_functions.inc.php"); 
    22192610                $db = new db_functions(); 
    22202611                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : ""; 
     2612                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;  
     2613                 
    22212614                ## 
    22222615                # @AUTHOR Rodrigo Souza dos Santos 
     
    22382631                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc']))); 
    22392632                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco']))); 
     2633 
     2634                $toaddress  = preg_replace('/<\s+/', '<', $toaddress);                   
     2635                $toaddress  = preg_replace('/\s+>/', '>', $toaddress); 
     2636                         
     2637                $ccaddress  = preg_replace('/<\s+/', '<', $ccaddress); 
     2638                $ccaddress  = preg_replace('/\s+>/', '>', $ccaddress); 
     2639                 
     2640                $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress); 
     2641                $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress); 
     2642                 
    22402643                $replytoaddress = $params['input_replyto']; 
    22412644                $subject = $params['input_subject']; 
     
    22462649                $signed = $params['input_return_digital']; 
    22472650 
    2248                 if($params['smime']) 
     2651                $message_attachments = $params['message_attachments']; 
     2652                  
     2653                if(substr($params['input_to'],-1) == ',') 
     2654                    $params['input_to'] = substr($params['input_to'],0,-1); 
     2655 
     2656                if(substr($params['input_cc'],-1) == ',') 
     2657                    $params['input_cc'] = substr($params['input_cc'],0,-1); 
     2658 
     2659                if(substr($params['input_cco'],-1) == ',') 
     2660                    $params['input_cco'] = substr($params['input_cco'],0,-1); 
     2661                 
     2662 
     2663                // Valida numero Maximo de Destinatarios  
     2664                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0)  
     2665                {  
     2666                    $sendersNumber = count(explode(',',$params['input_to']));  
     2667 
     2668                    if($params['input_cc'])  
     2669                        $sendersNumber +=  count(explode(',',$params['input_cc']));  
     2670                    if($params['input_cco'])  
     2671                        $sendersNumber +=  count(explode(',',$params['input_cco']));  
     2672 
     2673                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username);  
     2674                    if($userMaxmimumSenders)  
     2675                    {  
     2676                        if($sendersNumber > $userMaxmimumSenders)  
     2677                            return $this->functions->getLang('Number of recipients greater than allowed');  
     2678                    }  
     2679                    else  
     2680                    {  
     2681                        $ldap = new ldap_functions();  
     2682                        $groupsToUser = $ldap->get_user_groups($this->username);  
     2683 
     2684                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser);  
     2685 
     2686                        if($groupMaxmimumSenders > 0)  
     2687                        {  
     2688                            if($sendersNumber > $groupMaxmimumSenders)  
     2689                                return $this->functions->getLang('Number of recipients greater than allowed');  
     2690                        }  
     2691                        else  
     2692                        {  
     2693                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'])  
     2694                             return $this->functions->getLang('Number of recipients greater than allowed');  
     2695                        }  
     2696                    }  
     2697 
     2698                }  
     2699                //Fim Valida numero maximo de destinatarios  
     2700                 
     2701                 
     2702                //Valida envio de email para shared accounts 
     2703                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true') 
     2704                { 
     2705                    $ldap = new ldap_functions(); 
     2706                    $arrayF = explode(';', $params['input_from']); 
     2707 
     2708                    /* 
     2709                     * Verifica se o remetente n?o ? uma conta compartilhada 
     2710                     */ 
     2711                    if(!$ldap->isSharedAccountByMail($arrayF[1])) 
     2712                    { 
     2713                        $groupsToUser = $ldap->get_user_groups($this->username); 
     2714                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress); 
     2715 
     2716                        /* 
     2717                         * Pega o UID do remetente 
     2718                         */ 
     2719                        $uidFrom = $ldap->mail2uid($arrayF[1]); 
     2720 
     2721                         /* 
     2722                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada 
     2723                         */ 
     2724                        foreach ($sharedAccounts as $key => $value) 
     2725                        { 
     2726                            if($value) 
     2727                                 $acl = $this->getaclfrombox($value); 
     2728 
     2729                             if (array_key_exists($uidFrom, $acl)) 
     2730                                 unset($sharedAccounts[$key]); 
     2731 
     2732                        } 
     2733 
     2734                        /* 
     2735                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas 
     2736                         */ 
     2737                        if(count($sharedAccounts) > 0) 
     2738                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts); 
     2739 
     2740                        /* 
     2741                         * Retorna as contas compartilhadas bloqueadas 
     2742                         */ 
     2743                        if(count($accountsBlockeds) > 0) 
     2744                        { 
     2745                            $return = ''; 
     2746 
     2747                            foreach ($accountsBlockeds as $accountBlocked) 
     2748                                $return.= $accountBlocked.', '; 
     2749 
     2750                             $return = substr($return,0,-2); 
     2751 
     2752                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return; 
     2753                        } 
     2754                    } 
     2755                } 
     2756                // Fim Valida envio de email para shared accounts 
     2757                 
     2758                 
     2759//          TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo 
     2760            if($params['smime'] AND false) 
    22492761        { 
    22502762            $body = $params['smime']; 
     
    22852797        else 
    22862798        { 
    2287             $body = $params['body']; 
    22882799            //Compatibilização com Outlook, ao encaminhar a mensagem 
    2289             $body = mb_ereg_replace('<!--\[','<!-- [',$body); 
     2800                        $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']); 
    22902801        } 
    2291                 //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>"; 
     2802 
    22922803                $attachments = $_FILES; 
    22932804                $forwarding_attachments = $params['forwarding_attachments']; 
     
    22982809                        //build shared folder path 
    22992810                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder; 
    2300                         if( $this->folder_exists($newfolder) ) $folder = $newfolder; 
    2301                         else $folder =  $params['folder'];                       
     2811                        if($this->folder_exists($newfolder))  
     2812                                $folder = $newfolder; 
     2813                        else  
     2814                                $folder = $params['folder']; 
     2815                         
    23022816                } else  { 
    23032817                        $folder = $params['folder'];                     
    23042818                } 
    23052819                 
    2306                 $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"); 
     2820                $folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1'); 
     2821                $folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder); 
    23072822                $folder_name = $params['folder_name']; 
    2308                 // Fix problem with cyrus delimiter changes. 
    2309                 // Dots in names: enabled/disabled. 
    2310                 $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder); 
    2311                 $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder); 
    2312                 // End Fix. 
    2313                 if ($folder != 'null'){ 
    2314                         $mail->SaveMessageInFolder = $folder; 
    2315                 } 
    2316 //////////////////////////////////////////////////////////////////////////////////////////////////// 
    2317                 $mail->SMTPDebug = false; 
    2318  
    2319                 if($signed && !$params['smime']) 
     2823 
     2824//              TODO - tratar assinatura e remover o AND false 
     2825                if($signed && !$params['smime'] AND false) 
    23202826                { 
    23212827            $mail->Mailer = "smime"; 
    23222828                        $mail->SignedBody = true; 
    23232829                } 
    2324                 else 
    2325             $mail->IsSMTP(); 
    2326  
    2327                 $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer']; 
    2328                 $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort']; 
    2329                 $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email']; 
    2330                 $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname']; 
    2331                 if($fromaddress){ 
    2332                         $mail->Sender = $mail->From; 
    2333                         $mail->SenderName = $mail->FromName; 
    2334                         $mail->FromName = $fromaddress[0]; 
    2335                         $mail->From = $fromaddress[1]; 
    2336                 } 
    2337  
    2338                 $this->add_recipients("to", $toaddress, &$mail); 
    2339                 $this->add_recipients("cc", $ccaddress, &$mail); 
     2830 
     2831 
     2832                if($fromaddress) 
     2833                        $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>'); 
     2834               else 
     2835                        $mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>'); 
     2836                //$mailService->addTo($toaddress); 
     2837                //$mailService->addCc($ccaddress); 
     2838                $bol = $this->add_recipients('to', $toaddress, $mailService); 
     2839                if(!$bol){ 
     2840                        return $this->parse_error("Invalid Mail:", $toaddress); 
     2841                } 
     2842                $bol = $this->add_recipients('cc', $ccaddress, $mailService); 
     2843                if(!$bol){ 
     2844                        return $this->parse_error("Invalid Mail:", $ccaddress); 
     2845                } 
    23402846                $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy'];  
    23412847                  
    2342                                 if( $allow )  
     2848                if($allow)  
    23432849                                {  
    2344                 $this->add_recipients("cco", $ccoaddress, &$mail); 
     2850                        //$mailService->addBcc($ccoaddress); 
     2851                        $bol = $this->add_recipients('cco', $ccoaddress, $mailService); 
     2852 
     2853                        if(!$bol){ 
     2854                                return $this->parse_error("Invalid Mail:", $ccoaddress); 
     2855                        } 
    23452856                                } 
    2346                 $mail->AddReplyTo($replytoaddress); 
    2347                 $mail->Subject = $subject; 
    2348                 $mail->IsHTML( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true ); 
    2349                 $mail->Body = $body; 
    2350  
    2351         if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada... 
     2857 
     2858                $mailService->setSubject($subject); 
     2859                $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ?  
     2860                                                strtolower($params['type']) != 'plain' : true ); 
     2861         
     2862 
     2863//              TODO - tratar mensagem criptografada e remover o AND false abaixo 
     2864        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)      // a msg deve ser enviada cifrada... 
    23522865                { 
    23532866                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress); 
     
    24402953            $mail->Certs_crypt = $aux_mails; 
    24412954        } 
    2442                 // Build CID images  
    2443                 $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);  
     2955                                                 
     2956                if( count($forwarding_attachments) > 0 )// Build CID images  
     2957                        $this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body);  
    24442958 
    24452959                //      Build Uploading Attachments!!! 
     
    24472961                { 
    24482962                        $total_uploaded_size = 0; 
    2449                         $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024; 
    24502963                        foreach ($attachments as $attach) 
    24512964                        { 
     
    24542967                                if($attach['name']=='Unknown') 
    24552968                                        continue; 
    2456                                 $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name 
     2969                                $mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment'); 
    24572970                                $total_uploaded_size = $total_uploaded_size + $attach['size']; 
    24582971                        } 
    2459                         if( $total_uploaded_size > $upload_max_filesize){ 
     2972                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) 
     2973                        { 
     2974          
     2975                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024; 
     2976                            if( $total_uploaded_size > $upload_max_filesize) 
    24602977                                return $this->parse_error("message file too big"); 
    24612978                        } 
     
    24642981 
    24652982                        $total_uploaded_size = 0; 
    2466                         $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; 
     2983                         
    24672984                        foreach($local_attachments as $local_attachment) { 
    24682985                                $file_description = unserialize(rawurldecode($local_attachment)); 
     
    24712988                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor); 
    24722989                                } 
    2473                                 $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name 
     2990                                $mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment'); 
    24742991                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size']; 
    24752992                        } 
    2476                         if( $total_uploaded_size > $upload_max_filesize) 
    2477                                 return 'false'; 
    2478                 } 
    2479 //////////////////////////////////////////////////////////////////////////////////////////////////// 
     2993                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) 
     2994                        { 
     2995                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024; 
     2996                            if( $total_uploaded_size > $upload_max_filesize) 
     2997                                   return $this->parse_error("message file too big"); 
     2998                        } 
     2999                } 
     3000 
    24803001                //      Build Forwarding Attachments!!! 
    24813002                if (count($forwarding_attachments) > 0) 
     
    24903011                        foreach($forwarding_attachments as $forwarding_attachment) 
    24913012                        { 
    2492                                         $file_description = unserialize(rawurldecode($forwarding_attachment)); 
    2493                                         $tmp = array_values($file_description); 
    2494                                         foreach($file_description as $i => $descriptor){ 
    2495                                                 $tmp[$i]  = eregi_replace('\'*\'','',$descriptor); 
     3013                                $file_description = unserialize(rawurldecode($forwarding_attachment)); 
     3014                                $tmp = array_values($file_description); 
     3015                                foreach($file_description as $i => $descriptor){ 
     3016                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor); 
     3017                                } 
     3018                                $file_description = $tmp; 
     3019                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]); 
     3020                                $fileName = $file_description[2]; 
     3021                                if(!array_search(trim($fileName),$name_cid_files)) { 
     3022                                        $filename_dec = html_entity_decode(rawurldecode($fileName)); 
     3023                                        $mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] ); 
     3024 
     3025                                } 
     3026                        } 
     3027                } 
     3028                 
     3029                //Build Message Attachments!!! 
     3030                if(count($message_attachments) > 0 )  
     3031                { 
     3032                        foreach($message_attachments as $folder_name => $messages) 
     3033                        { 
     3034                                foreach ($messages as $message_number => $message_subject)  
     3035                                { 
     3036                                        if (!$message_subject) 
     3037                                                $message_subject  = 'no title.eml'; 
     3038                                        else  
     3039                                                $message_subject .= '.eml'; 
     3040                                         
     3041                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) ) 
     3042                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] ); 
     3043                                        else{ 
     3044                                                $mbox_stream = $this->open_mbox($folder_name); 
     3045                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number); 
    24963046                                        } 
    2497                                         $file_description = $tmp; 
    2498                                         $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]); 
    2499                                         $fileName = $file_description[2]; 
    2500                                         if(!array_search(trim($fileName),$name_cid_files)) { 
    2501                                                 $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2])); 
    2502                                 } 
    2503                         } 
    2504                 } 
    2505  
    2506 //////////////////////////////////////////////////////////////////////////////////////////////////// 
    2507                 // Important message 
     3047                                                         
     3048                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg)); 
     3049                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' ); 
     3050                                } 
     3051                        } 
     3052                } 
     3053                 
     3054                $message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */ 
     3055                $message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */ 
     3056                 
     3057                ////////////////////////////////////////////////////////////////////////////////////////////////////     
     3058                /**  
     3059                * Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão. 
     3060                 */ 
     3061                $default_max_size_rule = $db->get_default_max_size_rule();       
     3062                if(!$default_max_size_rule) 
     3063                { 
     3064                        $default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */ 
     3065                } 
     3066                else 
     3067                { 
     3068                        foreach($default_max_size_rule as $i=>$value) 
     3069                        {                
     3070                                $default_max_size_rule = $value['config_value']; 
     3071                        }                                
     3072                } 
     3073                 
     3074                $default_max_size_rule = $default_max_size_rule * 1024 * 1024;            /* Tamanho da regra padrão, em bytes */ 
     3075                $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];    
     3076                 
     3077                 
     3078                $ldap = new ldap_functions(); 
     3079                $groups_user = $ldap->get_user_groups($id_user); 
     3080 
     3081                $size_rule_by_group = array();   
     3082                foreach($groups_user as $k=>$value_) 
     3083                {        
     3084                        $rule_in_group = $db->get_rule_by_user_in_groups($k); 
     3085                        if ($rule_in_group != "") 
     3086                                array_push($size_rule_by_group, $rule_in_group); 
     3087                }        
     3088                 
     3089                $n_rule_groups = 0; 
     3090                $maior_valor_regra_grupo = 0; 
     3091                foreach($size_rule_by_group as $i=>$value) 
     3092                { 
     3093                        if(is_array($value[0])) 
     3094                        { 
     3095                                $n_rule_groups++; 
     3096                                if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo) 
     3097                                        $maior_valor_regra_grupo = $value[0]['email_max_recipient']; 
     3098                        } 
     3099                } 
     3100                 
     3101                if($default_max_size_rule) 
     3102                { 
     3103                        $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']); 
     3104 
     3105                        if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */ 
     3106                        { 
     3107                                if($message_size_total > $default_max_size_rule) 
     3108                                        return $this->functions->getLang("Message size greateruler than allowed (Default rule)"); 
     3109                        } 
     3110 
     3111                        else  
     3112                        { 
     3113                                if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */ 
     3114                                { 
     3115                                        $regra_mais_permissiva = 0; 
     3116                                        foreach($size_rule as $i=>$value) 
     3117                                        {        
     3118                                                if($regra_mais_permissiva < $value['email_max_recipient']) 
     3119                                                        $regra_mais_permissiva = $value['email_max_recipient']; 
     3120                                        } 
     3121                                        $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;                   
     3122                                        if($message_size_total > $regra_mais_permissiva) 
     3123                                                return $this->functions->getLang("Message size greater than allowed (Rule By User)"); 
     3124                                } 
     3125                                else /* Regra por grupo */ 
     3126                                {                
     3127                                        $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;                       
     3128                                        if($message_size_total > $maior_valor_regra_grupo) 
     3129                                                return $this->functions->getLang("Message size greater than allowed (Rule By Group)");   
     3130                                 
     3131                                 
     3132                                } 
     3133                        } 
     3134                } 
     3135                /**  
     3136         * Fim da validação do tamanho da regra do tamanho de mensagem. 
     3137                 */ 
     3138                 //////////////////////////////////////////////////////////////////////////////////////////////////// 
     3139                 
     3140                 
     3141                 
     3142                 
     3143                 
     3144                if($isHTML) 
     3145                        $mailService->setBodyHtml($body); 
     3146                else 
     3147                        $mailService->setBodyText($body); 
     3148 
    25083149                if($is_important) 
    2509                         $mail->isImportant(); 
    2510  
    2511 //////////////////////////////////////////////////////////////////////////////////////////////////// 
    2512                 // Disposition-Notification-To 
    2513                 if ($return_receipt) 
    2514                         $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email']; 
    2515 //////////////////////////////////////////////////////////////////////////////////////////////////// 
    2516  
    2517                 $sent = $mail->Send(); 
    2518  
    2519                 if(!$sent) 
    2520                 { 
    2521                         return $this->parse_error($mail->ErrorInfo); 
     3150                        $mailService->addHeaderField('Importance','High'); 
     3151 
     3152                if($return_receipt) 
     3153                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']); 
     3154 
     3155 
     3156                if ($folder != 'null'){ 
     3157                        $mbox_stream = $this->open_mbox($folder); 
     3158                        @imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen"); 
     3159                } 
     3160 
     3161                $sent = $mailService->send(); 
     3162 
     3163                if($sent !== true) 
     3164                { 
     3165                        return $this->parse_error($sent); 
    25223166                } 
    25233167                else 
     
    25363180                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log"); 
    25373181                        } 
    2538                         if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] && 
    2539                            $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) { 
     3182                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) { 
    25403183                                $contacts = new dynamic_contacts(); 
    25413184                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress); 
     
    25543197        * @param     $forwarding_attachments anexos 
    25553198        */ 
    2556         function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)  
     3199 
     3200        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body) 
    25573201        {  
    2558                 //      Build CID for embedded Images!!!  
    2559                 $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';  
     3202                //Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail 
     3203                $pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU'; 
    25603204                $cid_imgs = '';  
    2561                 preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);  
    2562                 $cid_array = array();  
    2563  
    2564                 foreach($cid_imgs[6] as $j => $val){  
    2565                         if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )  
    2566                         {  
    2567                                 $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);  
    2568                         }  
    2569                         $cid = $cid_array[$cid_imgs[4][$j].$val];   
    2570  
    2571                         $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);  
    2572  
     3205                preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER ); 
     3206                //-------------------------------------------------------------------// 
     3207 
     3208                $attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments 
     3209 
     3210                foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link 
     3211                        $desc = unserialize(rawurldecode($v)); 
     3212                        $attPostions[$desc[3]] = $i; 
     3213                } 
     3214 
     3215                //Intera as imagens encontradas 
     3216                foreach($cid_imgs[6] as $j => $val) 
     3217        {                
     3218                        $cid = base_convert(microtime().$j, 10, 36); //Gera um cid 
     3219                        $body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'@'.$_SESSION['phpgw_info']['expressomail']['server']['domain_name'].'"', $body ); //tira o src da imagem e coloca o cid, ele e concatenado com o domain do servidor por que a biblioteaca mime faz isso na hora de gerar o mime. 
    25733220                        $count    = strlen($cid_imgs[6][$j]); 
    2574                         $position = substr($cid_imgs[6][$j], 2, $count); 
    2575                         $position--; 
    25763221                                         
    2577                         $attach_img = $forwarding_attachments[$position]; 
     3222                        $attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]; 
    25783223                        $file_description = unserialize(rawurldecode($attach_img)); 
    25793224                         
    25803225                        if (is_array($file_description)) 
    25813226                                foreach($file_description as $i => $descriptor)                          
    2582                                         $file_description[$i]  = eregi_replace('\'*\'','',$descriptor); 
     3227                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor); 
    25833228 
    25843229                        // The image is not in the same mail? 
    25853230                        if ($msg_uid != $cid_imgs[4][$j])  
    25863231                        {  
    2587                                 $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');  
    2588                                 $fileName = ($msg_uid != 'undefined') ? "image_".($j).".jpg" : $file_description[2]; 
    2589                                 $fileCode = "base64";  
    2590                                 $fileType = "image/jpg";  
     3232                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64'); 
     3233                $fileContent = &$fa['binary']; 
     3234                                $fileName = $fa['name']; 
     3235                                $fileCode = $fa['encoding']; 
     3236                                $fileType =  $fa['type']; 
    25913237                                $file_attached[0] = $cid_imgs[2][$j];  
    25923238                                $file_attached[1] = $cid_imgs[4][$j];  
    25933239                                $file_attached[2] = $fileName;  
    2594                                 $file_attached[3] = '0.'.($j+1); 
     3240                                $file_attached[3] = '0.'.(string)($j+1); 
    25953241                                $file_attached[4] = 'base64';  
    25963242                                $file_attached[5] = strlen($fileContent); //Size of file  
     
    25993245 
    26003246                                if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined') 
    2601                                         unset($forwarding_attachments[$position]); 
     3247                                        unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]); 
    26023248                                 
    26033249                        }  
     
    26073253                                $fileName = $file_description[2];  
    26083254                                $fileCode = $file_description[4];  
    2609                                 $file_description[3] = '0.'.($j+1); 
     3255                                $file_description[3] = '0.'.(string)($j+1); 
    26103256                                $file_description[6] = $cid_imgs[6][$j]; 
    26113257                                $fileType = $this->get_file_type($file_description[2]);  
    2612                                 unset($forwarding_attachments[$position]); 
     3258                                unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]); 
    26133259                                if (!empty($file_description))  
    26143260                                {  
     
    26173263                                }  
    26183264                        }  
    2619                         $tempDir = '/tmp'; 
    2620                         $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                         
    2621                         $f = fopen($tempDir.'/'.$file,"w");  
    2622                         fputs($f,$fileContent);  
    2623                         fclose($f);  
    26243265 
    26253266                        if ($fileContent)  
    2626                                 $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);  
     3267                                $mail->addStringImage($fileContent,$fileType,$fileName, $cid);                                   
    26273268                } 
    26283269 
     
    26543295                $full_address = preg_replace("/, ?,/",",",$full_address); 
    26553296                $parse_address = imap_rfc822_parse_adrlist($full_address, ""); 
     3297                $bolean = true; 
    26563298                foreach ($parse_address as $val) 
    26573299                { 
     
    26653307                                { 
    26663308                                        case "to": 
    2667                                                 $mail->AddAddress($val->mailbox."@".$val->host); 
     3309                                                $mail->AddTo($val->mailbox."@".$val->host); 
    26683310                                                break; 
    26693311                                        case "cc": 
    2670                                                 $mail->AddCC($val->mailbox."@".$val->host); 
     3312                                                $mail->AddCc($val->mailbox."@".$val->host); 
    26713313                                                break; 
    26723314                                        case "cco": 
    2673                                                 $mail->AddBCC($val->mailbox."@".$val->host); 
     3315                                                $mail->AddBcc($val->mailbox."@".$val->host); 
    26743316                                                break; 
    26753317                                } 
     
    26803322                                { 
    26813323                                        case "to": 
    2682                                                 $mail->AddAddress($val->mailbox."@".$val->host, $val->personal); 
     3324                                                $mail->AddTo($val->mailbox."@".$val->host, $val->personal); 
    26833325                                                break; 
    26843326                                        case "cc": 
    2685                                                 $mail->AddCC($val->mailbox."@".$val->host, $val->personal); 
     3327                                                $mail->AddCc($val->mailbox."@".$val->host, $val->personal); 
    26863328                                                break; 
    26873329                                        case "cco": 
    2688                                                 $mail->AddBCC($val->mailbox."@".$val->host, $val->personal); 
     3330                                                $mail->AddBcc($val->mailbox."@".$val->host, $val->personal); 
    26893331                                                break; 
    26903332                                } 
    26913333                        } 
    2692                 } 
    2693                 return true; 
     3334                        if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){ 
     3335                                $bolean = false; 
     3336                } 
     3337                         
     3338                } 
     3339                return $bolean; 
    26943340        } 
    26953341 
    26963342        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding) 
     3343        { 
     3344            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php'; 
     3345            $attachment = new attachment(); 
     3346                        $attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo. 
     3347            $attachment->setStructureFromMail($msg_folder, $msg_number); 
     3348            return $attachment->getAttachment($msg_part); 
     3349        } 
     3350 
     3351        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding) 
    26973352        { 
    26983353            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php'; 
    26993354            $attachment = new attachment(); 
    27003355            $attachment->setStructureFromMail($msg_folder, $msg_number); 
    2701             return $attachment->getAttachment($msg_part); 
     3356            $return = $attachment->getAttachmentInfo($msg_part); 
     3357            $return['binary'] = $attachment->getAttachment($msg_part); 
     3358            return $return; 
    27023359        } 
    27033360 
     
    27623419                                        else 
    27633420                                                $from = $header->from; 
    2764  
     3421                                        if(isset($from[0]->personal)) 
    27653422                                        $tmp = imap_mime_header_decode($from[0]->personal); 
    2766  
    2767                                         if ($tmp[0]->text != "") 
     3423                                        else 
     3424                                                $tmp = null; 
     3425                                        if (isset($tmp[0]->text)) 
    27683426                                                $sort[$iuid] = $tmp[0]->text; 
    27693427                                        else 
     
    27863444                                $sort = array_reverse($sort,true); 
    27873445                } 
    2788  
    2789                 if(!is_array($sort)) 
     3446                if(empty($sort) or !is_array($sort)){ 
    27903447                        $sort = array(); 
     3448                } 
     3449                 
     3450                         
    27913451 
    27923452 
     
    28363496                $folder = $params['folder']; 
    28373497                $mbox_stream = $this->open_mbox($folder); 
    2838                 $newmailbox = urldecode($params['new_folder']); 
     3498                $newmailbox = ($params['new_folder']); 
    28393499                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1"); 
    2840                 $new_folder_name = urldecode($params['new_folder_name']); 
     3500                $new_folder_name = $params['new_folder_name']; 
    28413501                $msgs_number = $params['msgs_number']; 
    28423502                $return = array('msgs_number' => $msgs_number, 
     
    28663526        } 
    28673527        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name 
     3528        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){ 
    28683529        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){ 
    28693530            if (substr($new_folder_name,0,4) == 'user'){ 
     
    28773538            } 
    28783539        } 
     3540                } 
    28793541 
    28803542                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior. 
     
    28833545                        $return['previous_msg'] = $this->get_info_previous_msg($params); 
    28843546                        // Fix problem in unserialize function JS. 
     3547                        if(array_key_exists('body', $return['previous_msg'])) 
    28853548                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']); 
    28863549                } 
     
    29413604        } 
    29423605 
     3606 
    29433607        function save_msg($params) 
    29443608        { 
    2945  
    2946                 include_once("class.phpmailer.php"); 
    2947                 $mail = new PHPMailer(); 
    2948                 include_once("class.db_functions.inc.php"); 
    2949                 $toaddress = $params['input_to']; 
    2950                 $ccaddress = $params['input_cc']; 
    2951                 $ccoaddress = $params['input_cco']; 
     3609                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php'; 
     3610                $mailService = ServiceLocator::getService('mail'); 
     3611 
    29523612                $return_receipt = $params['input_return_receipt']; 
    29533613                $is_important = $params['input_important_message']; 
    2954                 $subject = $params['input_subject']; 
     3614                 
    29553615                $msg_uid = $params['msg_id']; 
    29563616                $body = $params['body']; 
    29573617                $body = str_replace("%nbsp;","&nbsp;",$body); 
    29583618                $body = preg_replace("/\n/"," ",$body); 
    2959                 $body = preg_replace("/\r/","",$body); 
     3619                $body = preg_replace("/\r/","" ,$body); 
     3620                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' ); 
    29603621                $forwarding_attachments = $params['forwarding_attachments']; 
     3622                $message_attachments    = $params['message_attachments']; 
    29613623                $attachments = $params['FILES']; 
    29623624                $return_files = $params['FILES']; 
     3625                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;  
    29633626 
    29643627                if(is_array($params['local_attachments'])){ 
    29653628                    foreach ($params['local_attachments'] as $key => $local_attach) { 
    29663629                       $tmp = unserialize(urldecode($local_attach)); 
    2967                        $attachments[$key]['name'] = $tmp[2]; 
    2968                        $return_files[$key]['name'] = $tmp[2]; 
     3630                           $attachments[$key]['name'] = urldecode($tmp[2]); 
     3631                           $return_files[$key]['name'] = urldecode($tmp[2]); 
    29693632                    } 
    29703633                } 
    29713634 
    2972  
    2973                 $folder = $params['folder']; 
    2974                 $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"); 
    2975                 // Fix problem with cyrus delimiter changes. 
    2976                 // Dots in names: enabled/disabled. 
    2977                 $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder); 
    2978                 $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder); 
    2979                 // End Fix. 
    2980  
    2981                 $mail->SaveMessageInFolder = $folder; 
    2982                 $mail->SMTPDebug = false; 
    2983  
    2984                 $mail->IsSMTP(); 
    2985                 $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer']; 
    2986                 $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort']; 
    2987                 $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email']; 
    2988                 $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname']; 
    2989  
    2990                 $mail->Sender = $mail->From; 
    2991                 $mail->SenderName = $mail->FromName; 
    2992                 $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname']; 
    2993                 $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email']; 
    2994  
    2995                 $this->add_recipients("to", $toaddress, &$mail); 
    2996                 $this->add_recipients("cc", $ccaddress, &$mail); 
    2997                 $this->add_recipients("cco", $ccoaddress, &$mail); 
    2998                 $mail->AddReplyTo($replytoaddress); 
    2999                 $mail->Subject = $subject; 
    3000                 $mail->IsHTML(true); 
    3001                 $mail->Body = $body; 
    3002                  
    3003                 $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments); 
     3635                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO_8859-1"); 
     3636                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder); 
     3637 
     3638                $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>'); 
     3639                $mailService->addTo($params['input_to']); 
     3640                $mailService->addCc( $params['input_cc']); 
     3641                $mailService->addBcc($params['input_cco']); 
     3642                $mailService->setSubject($params['input_subject']); 
     3643 
     3644                if($is_important){ 
     3645                        $mailService->addHeaderField('Importance','High'); 
     3646                } 
     3647 
     3648                if($return_receipt) 
     3649                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']); 
     3650 
     3651                $isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true ); 
     3652 
     3653                 
     3654                if( count($forwarding_attachments) > 0 ) 
     3655                        $return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body); 
     3656                         
     3657                //Build Message Attachments!!! 
     3658                if(count($message_attachments) > 0 )  
     3659                { 
     3660                        foreach($message_attachments as $folder_name => $messages) 
     3661                        { 
     3662                                foreach ($messages as $message_number => $message_subject)  
     3663                                { 
     3664                                        if (!$message_subject) 
     3665                                                $message_subject  = 'no title.eml'; 
     3666                                        else  
     3667                                                $message_subject .= '.eml'; 
     3668                                         
     3669                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) ) 
     3670                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] ); 
     3671                                        else{ 
     3672                                                $mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name); 
     3673                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number); 
     3674                                        } 
     3675                                                                                         
     3676                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg)); 
     3677                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' ); 
     3678                                } 
     3679                        } 
     3680                } 
     3681                 
    30043682                $imagesParts = array();  
    30053683 
     3684                if(count($return_forward) > 0 ) 
    30063685                foreach ($return_forward as $value) 
    30073686                        $imagesParts[$value[6]] = $value[3];     
    30083687 
    3009         //      Build Forwarding Attachments!!! 
     3688                //Build Forwarding Attachments!!! 
     3689                if(count($forwarding_attachments) > 0 )  
     3690                { 
    30103691                        foreach($forwarding_attachments as $forwarding_attachment) 
    30113692                        { 
    30123693                                $file_description = unserialize(rawurldecode($forwarding_attachment)); 
     3694                                                 
     3695                                 
    30133696                        $file_description = array_values($file_description);  
    30143697                                         
    3015                                 foreach($file_description as $i => $descriptor){ 
     3698                                foreach($file_description as $i => $descriptor) 
    30163699                                                        $file_description[$i] = eregi_replace('\'*\'','',$descriptor);  
    3017                                 } 
     3700                                 
    30183701                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]); 
    3019                                 $fileName = $file_description[2]; 
     3702                                $file_description[2] = html_entity_decode($file_description[2]); 
    30203703 
    30213704                                $file_description[5] = strlen($fileContent); //Size of file 
    30223705                                $return_forward[] = $file_description; 
    3023  
    3024                                         $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2])); 
     3706                                $mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] ); 
     3707                        } 
    30253708                        } 
    30263709 
    30273710                if ((count($return_forward) > 0) && (count($return_files) > 0)) 
    3028                 { 
    30293711                        $return_files = array_merge_recursive($return_forward,$return_files); 
    3030                 } 
    30313712                else if (count($return_files) < 1) 
    3032                 { 
    30333713                                $return_files = $return_forward; 
    3034                 } 
    3035  
    3036                 //      Build Uploading Attachments!!! 
     3714 
     3715                //Build Uploading Attachments!!! 
    30373716                $sizeof_attachments = count($attachments); 
    30383717                if ($sizeof_attachments) 
    3039                 { 
    30403718                        foreach ($attachments as $numb => $attach) 
    3041                         { 
    3042                                 if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true') 
    3043                                 { // Auto-resize image 
    3044                                         list($width, $height,$image_type) = getimagesize($attach['tmp_name']); 
    3045                                         switch ($image_type) 
    3046                                         { 
    3047                                         // Do not corrupt animated gif 
    3048                                         //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break; 
    3049                                                 case 2:  
    3050                                                         $image_big = imagecreatefromjpeg($attach['tmp_name']);  break; 
    3051                                                 case 3:  
    3052                                                         $image_big = imagecreatefrompng($attach['tmp_name']); break; 
    3053                                         case 6: 
    3054                                                 require_once("gd_functions.php"); 
    3055                                                 $image_big = imagecreatefrombmp($attach['tmp_name']); break; 
    3056                                         default: 
    3057                                                 $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name'])); 
    3058                                                 break; 
    3059                                         } 
    3060                                         header('Content-type: image/jpeg'); 
    3061                                         $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size']; 
    3062                                         $max_resolution = ($max_resolution==""?'65536':$max_resolution); 
    3063                                         if ($width < $max_resolution && $height < $max_resolution) 
    3064                                         { 
    3065                                                 $new_width = $width; 
    3066                                                 $new_height = $height; 
    3067                                         } 
    3068                                         else if ($width > $max_resolution) 
    3069                                         { 
    3070                                                 $new_width = $max_resolution; 
    3071                                                 $new_height = $height*($new_width/$width); 
    3072                                         } 
    3073                                         else  
    3074                                         { 
    3075                                                 $new_height = $max_resolution; 
    3076                                                 $new_width = $width*($new_height/$height); 
    3077                                         } 
    3078                                         $image_new = imagecreatetruecolor($new_width, $new_height); 
    3079                                         imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    3080                                         $tmpDir = '/tmp'; 
    3081  
    3082                                        // $tmpDir = ini_get("session.save_path"); 
    3083                                         $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat"; 
    3084                                         imagejpeg($image_new,$tmpDir.$_file, 85); 
    3085                                         $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file)); 
    3086                                 }else{ 
    3087                                         $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name'])); 
    3088                                 }// optional name 
    3089                         } 
    3090                 } 
    3091  
    3092                 if(!empty($mail->AltBody)) 
    3093             $mail->ContentType = "multipart/alternative"; 
    3094  
    3095                 $mail->error_count = 0; // reset errors 
    3096                 $mail->SetMessageType(); 
    3097                 $header = $mail->CreateHeader(); 
    3098                 $body = $mail->CreateBody(); 
     3719                                $mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment'); 
     3720 
     3721 
     3722                if (!$body) 
     3723                        $body = ' '; 
     3724                 
     3725                if($isHTML) 
     3726                        $mailService->setBodyHtml($body); 
     3727                else 
     3728                        $mailService->setBodyText($body); 
     3729 
    30993730 
    31003731                $mbox_stream = $this->open_mbox($folder); 
    3101                 $new_header = str_replace("\n", "\r\n", $header); 
    3102                 $new_body = str_replace("\n", "\r\n", $body); 
    3103                 $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft"); 
     3732                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"); 
     3733 
    31043734                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT); 
    31053735                $return['msg_no'] = $status->uidnext - 1; 
     
    31103740                        imap_close($mbox_stream); 
    31113741                         
    3112                 if (is_array($return_files)) 
     3742                $returnFiles = array();                   
     3743                $ii = 0; 
     3744                                 
     3745                if(count($return_files) > 0) 
    31133746                { 
    31143747                        foreach ($return_files as $index => $_attachment)  
     
    31163749                                if (array_key_exists("name", $_attachment)) 
    31173750                                { 
    3118                                 unset($return_files[$index]); 
    3119                                 $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size']; 
    3120                         } 
    3121                         else 
     3751                                        $returnFiles[$ii]['name'] = base64_encode($_attachment['name']); 
     3752                                        $returnFiles[$ii]['size'] = $_attachment['size']; 
     3753                                        $ii++; 
     3754                        } 
     3755                                else if($_attachment[2]) 
    31223756                        { 
    3123                                 unset($return_files[$index]); 
    3124                                 $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5]; 
    3125                         } 
    3126                 } 
    3127                 } 
    3128  
    3129                 $return['files'] = serialize($return_files); 
    3130                 $return["subject"] = $subject; 
    3131  
    3132                 if (!$return['append']) 
    3133                         $return['append'] = imap_last_error(); 
    3134  
     3757                                        $returnFiles[$ii]['name'] = base64_encode($_attachment[2]);  
     3758                                        $returnFiles[$ii]['size'] = $_attachment[5];          
     3759                                        $ii++; 
     3760                        } 
     3761                } 
     3762                } 
     3763                $return['files'] = serialize($returnFiles); 
     3764                $return["subject"] = $params['input_subject']; 
     3765                if (!$return['append']) $return['append'] = imap_last_error(); 
    31353766                return $return; 
    31363767        } 
     
    31393770        { 
    31403771                $folder = $params['folder']; 
    3141                 $rowids_to_set = $params['msgs_to_set']; // contains the row ids 
     3772                $msgs_to_set = $params['msgs_to_set']; 
    31423773                $flag = $params['flag']; 
    31433774                $return = array(); 
    3144                 $return["rowids_to_set"] = $rowids_to_set; 
     3775                $return["msgs_to_set"] = $msgs_to_set; 
    31453776                $return["flag"] = $flag; 
    3146  
    3147                 $msgs_to_set = ''; 
    3148                 foreach (explode(',',$rowids_to_set) as $msg) {//extracting message ids 
    3149                         $pos = strpos($msg,'_'); 
    3150                         if ($pos===false) 
    3151                                 $msgs_to_set .= ','.$msg; 
    3152                         else 
    3153                                 $msgs_to_set .= ','.substr($msg,0,$pos); 
    3154                 } 
    3155                 $msgs_to_set = substr($msgs_to_set,1); 
    3156                 $return["msgs_to_set"] = $msgs_to_set; 
    31573777 
    31583778                if(!$this->mbox && !is_resource($this->mbox)) 
     
    32133833                $file_name = strtolower($file_name); 
    32143834                $strFileType = strrev(substr(strrev($file_name),0,4)); 
     3835                if ($strFileType == ".eml") 
     3836                        return "message/rfc822"; 
    32153837                if ($strFileType == ".asf") 
    32163838                        return "video/x-ms-asf"; 
     
    37104332                                                        { 
    37114333                                                            $filter .= '"'.$filter_array[1].'"'; 
    3712                                                         } 
    3713                                                         if(trim($filter_array[0]) == 'BEFORE' ) 
    3714                                                         { 
     4334                                                        }else if(trim($filter_array[0]) == 'BEFORE' ){ 
    37154335                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"'; 
    37164336                                                        }else{ 
     
    37214341                                } 
    37224342                                 
    3723                                 $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" ); 
     4343                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" ); 
    37244344                                $filter = $this->remove_accents($filter); 
    37254345 
     
    37374357                                } 
    37384358                                else 
    3739                                         $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" ); 
     4359                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" ); 
    37404360                                 
    37414361                                if(!is_resource($mbox_stream)) 
     
    37604380                                                        { 
    37614381                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);  
    3762                                                                 $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );  
     4382                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );  
    37634383                                                                $elem['uid'] = $new_search; 
    37644384                                                                /* compare dates in ordering */ 
     
    37704390                                } 
    37714391                                else{ 
     4392                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID); 
    37724393                                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) 
    37734394                                    { 
     
    37854406                                                } 
    37864407                                            } 
    3787  
    3788                                             $new_filter = trim(preg_replace('/UNFLAGGED|FLAGGED/','',$filter)); 
    3789  
    3790                                             $search_without_flagged = imap_search($mbox_stream, $new_filter, SE_UID); 
    3791  
    3792                                             if (strpos($filter,"UNFLAGGED") === false) 
     4408                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false)) 
    37934409                                            { 
    3794                                                 $search_criteria = array_intersect($search_without_flagged, $flagged_msgs); 
    3795                                             } 
    3796                                             else 
     4410                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs; 
     4411                                                    foreach($arry_diff as $msg) 
    37974412                                            { 
    3798                                                 $search_criteria = array_diff($search_without_flagged,$flagged_msgs); 
     4413                                                        $search_criteria[] = $msg; 
    37994414                                            } 
    38004415                                        } 
    3801                                         else 
     4416                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false)) 
    38024417                                        { 
    3803                                             $search_criteria = imap_search($mbox_stream, $filter, SE_UID); 
     4418                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs); 
    38044419                                        } 
    38054420                                    } 
    3806                                     else 
    3807                                     { 
    3808                                         $search_criteria = imap_search($mbox_stream, $filter, SE_UID); 
    38094421                                    } 
    38104422 
     
    38144426                                        { 
    38154427                                            $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
    3816                                             $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
     4428                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );  
    38174429                                            $elem['uid'] = $new_search; 
    38184430                                            /* compare dates in ordering */ 
     
    40364648                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user); 
    40374649                else 
    4038                   $mbox_acl = imap_getacl($mbox_stream, $user); 
     4650                  $mbox_acl = @imap_getacl($mbox_stream, $user); 
     4651                if(isset($mbox_acl[$this->username])) 
    40394652                return $mbox_acl[$this->username]; 
     4653                else  
     4654                    return ''; 
    40404655        } 
    40414656 
     
    41664781         
    41674782         
     4783/** 
     4784* Descrição do método 
     4785* 
     4786* @license    http://www.gnu.org/copyleft/gpl.html GPL 
     4787* @author      
     4788* @sponsor    Caixa Econômica Federal 
     4789* @author      
     4790* @param      <tipo> <$msg_number> <Número da mensagem> 
     4791* @return     <cabeçalho da mensagem> 
     4792* @access     <public> 
     4793*/       
    41684794        function get_header($msg_number) 
    41694795        { 
     
    41724798                        return false; 
    41734799 
    4174                 if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) { 
     4800                if($header->Flagged != "F" ) { 
    41754801                        $flag = preg_match('/importance *: *(.*)\r/i', 
    41764802                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number)) 
     
    41914817        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort']; 
    41924818        $imap_options = '/notls/novalidate-cert'; 
     4819 
     4820         
     4821        $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1"); 
     4822 
    41934823        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password); 
    4194         if(imap_last_error()) 
    4195         { 
     4824         
     4825        if(imap_last_error() === 'Mailbox already exists') 
    41964826            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder)); 
    4197         } 
    41984827        if($timestamp){ 
    41994828                        $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local)  
     
    42054834                fputs($f,base64_encode($source)); 
    42064835            fclose($f); 
    4207                    $command = "python ".$_SESSION['rootPatch']."/expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." ".escapeshellarg($folder)." ".escapeshellarg($file); 
    4208             $return['command']=exec(escapeshellcmd($command)); 
     4836            $command = "python ".$_SESSION['rootPath']."/expressoMail1_2/imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\""; 
     4837            $return['command']= exec($command); 
    42094838        }else{ 
    42104839            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen"); 
     
    42304859                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID); 
    42314860                } 
     4861         
     4862        //Ignorando erro de AUTH=Plain 
     4863        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN') 
     4864            $return['error'] = false; 
     4865                                 
    42324866        if($mbox_stream) 
    42334867            imap_close($mbox_stream); 
     
    42354869    } 
    42364870 
    4237     function show_decript($params){ 
     4871        function show_decript($params,$dec=0){  
    42384872        $source = $params['source']; 
    4239         //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');  
    4240                         $source = str_replace(" ", "+", $source,$i);  
    42414873                  
     4874        //error_log("source: $source\nversao: " . PHP_VERSION);           
     4875        if ($dec == 0)  
     4876        {  
     4877            $source = str_replace(" ", "+", $source,$i);  
    42424878                        if (version_compare(PHP_VERSION, '5.2.0', '>=')){  
    42434879                            if(!$source = base64_decode($source,true))  
    4244                                 return "error ".$source."Espaços ".$i;  
     4880                    return "error ".$source."Espaï¿?os ".$i;  
    42454881                  
    42464882                        }  
    42474883                        else {  
    42484884                            if(!$source = base64_decode($source))  
    4249                                 return "error ".$source."Espaços ".$i; 
    4250  
     4885                    return "error ".$source."Espaï¿?os ".$i;  
     4886            }  
    42514887        } 
    42524888 
     
    43164952        $dest_folder = $params['folder']; 
    43174953        $sources = explode("#@#@#@",$params['source']); 
    4318         $timestamps = explode("#@#@#@",$params['timestamp']); 
     4954        //Add user timeszone 
     4955        $timestamps     = $params['timestamp'] + $this->functions->CalculateDateOffset();  
    43194956        $flags = explode("#@#@#@",$params['flags']); 
    43204957 
    4321         foreach($sources as $index=>$src) 
    4322         { 
    4323             if($src!="") 
    4324             { 
     4958                foreach($sources as $index=>$src) { 
     4959                        if($src!=""){ 
    43254960                $source = $this->treat_base64_from_post($src); 
    4326                 $insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]); 
     4961                        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestamps,$flags[$index]);  
    43274962            } 
    43284963        } 
    4329          
    43304964        return $insert; 
    43314965    } 
     
    43574991                        $msg_user = "Sem mensagem!";  
    43584992                          
    4359                 $toaddresses = $_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'];   
    4360                 $toaddress   = explode(",", $toaddresses);        
    4361                                   
    4362                 for($i=0; $i<count($toaddress); $i++)  
    4363                         $toaddress[$i] = trim($toaddress[$i]);  
    4364                                   
    43654993                $toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];  
    43664994                  
     
    43725000                                "$msg_user</body><br><br><hr>";  
    43735001                              
     5002                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php'; 
    43745003                $mailService = ServiceLocator::getService('mail');       
    4375                 $mailService->addAttachment($mail_content, 'report.eml', 'application/text');  
    4376                 $mailService->send($toaddress, $GLOBALS['phpgw_info']['user']['email'], $title, $body);  
     5004                $mailService->addStringAttachment($mail_content, 'report.eml', 'application/text');  
     5005                $mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body);  
    43775006        }  
    43785007         
     5008        function array_msort($array, $cols) 
     5009        { 
     5010                $colarr = array(); 
     5011                foreach ($cols as $col => $order) { 
     5012                        $colarr[$col] = array(); 
     5013                        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); } 
     5014                } 
     5015                $params = array(); 
     5016                foreach ($cols as $col => $order) { 
     5017                        $params[] =& $colarr[$col]; 
     5018                        $params = array_merge($params, (array)$order); 
     5019                } 
     5020                call_user_func_array('array_multisort', $params); 
     5021                $ret = array(); 
     5022                $keys = array(); 
     5023                $first = true; 
     5024                foreach ($colarr as $col => $arr) { 
     5025                        foreach ($arr as $k => $v) { 
     5026                                if ($first) { $keys[$k] = substr($k,1); } 
     5027                                $k = $keys[$k]; 
     5028                                if (!isset($ret[$k])) $ret[$k] = $array[$k]; 
     5029                                $ret[$k][$col] = $array[$k][$col]; 
     5030                        } 
     5031                        $first = false; 
     5032                } 
     5033                 
     5034                return $ret; 
     5035 
     5036        } 
     5037         
     5038        function parseCriteriaSearchMail($search) 
     5039        { 
     5040            $criteria = ''; 
     5041            $searchArray = explode(' ', $search); 
     5042 
     5043            foreach ($searchArray as $v) 
     5044                if(trim($v) !== '' ) 
     5045                    $criteria .= 'TEXT "'.$v.'" ' ; 
     5046            
     5047            return $criteria; 
     5048        } 
     5049         
     5050        function quickSearchMail( $params ) 
     5051        { 
     5052                $return = array(); 
     5053                $return['folder'] = $params['folder']; 
     5054                if(!is_array($params['folder'])) 
     5055                        $params['folder'] = array( $params['folder'] ); 
     5056                 
     5057                if(!isset($params['sort'])) 
     5058                        $params['sort'] = SORTDATE; 
     5059                                 
     5060                $params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1')); 
     5061                 
     5062                $i = 0;          
     5063                if(!isset($params['page'])) $params['page'] = 0; 
     5064                $end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));        
     5065                $ini = $end - $this->prefs['max_email_per_page'] ; 
     5066                $count = 0; 
     5067                 
     5068                $search = $this->parseCriteriaSearchMail($params['search']); 
     5069                                 
     5070                foreach ($params['folder'] as $folder)  
     5071                { 
     5072                        $imap = $this->open_mbox( $folder ) ; 
     5073                        $msgIds = imap_sort( $imap , SORTDATE , 0 , SE_UID , $search ,'UTF-8'); 
     5074                                                 
     5075                        $count += count($msgIds);   
     5076                         
     5077                        foreach ($msgIds as $ii => $v) 
     5078                        {                                
     5079                                $msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) ); 
     5080                                $return['msgs'][$i]['from'] = ''; 
     5081                                 
     5082                                $from = $msg->from[0]->mailbox; 
     5083                                if($msg->from[0]->personal != "") 
     5084                                        $from = $msg->from[0]->personal; 
     5085                                $return['msgs'][$i]['from']     = mb_convert_encoding($this->decode_string($from), 'UTF-8');  
     5086                                 
     5087                                $return['msgs'][$i]['subject'] = ' '; 
     5088                                 
     5089                                $subject = imap_mime_header_decode($msg->subject); 
     5090                                foreach ($subject as $tmp) 
     5091                                        $return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8'); 
     5092                                 
     5093                                $return['msgs'][$i]['flag'] = ' '; 
     5094                                $return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : ''; 
     5095                                $return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';         
     5096                                $return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';       
     5097                                $return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : '';   
     5098                                $return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';     
     5099                                $return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';       
     5100                                 
     5101                                $return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset());  
     5102                                $return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2); 
     5103                            $return['msgs'][$i]['date'] =   $msg->udate; 
     5104                                $return['msgs'][$i]['size'] =  $msg->Size; 
     5105                                $return['msgs'][$i]['boxname'] = $folder; 
     5106                                $return['msgs'][$i]['uid'] = $v; 
     5107                                $i++; 
     5108                        }        
     5109                } 
     5110                 
     5111                $return['num_msgs'] = $count; 
     5112                 
     5113                if(!isset($return['msgs'])) 
     5114                        $return['msgs'] = array(); 
     5115                 
     5116                define('SORTBOX', 69); 
     5117                define('SORTWHO', 2); 
     5118                define('SORTBOX_REVERSE', 69); 
     5119                define('SORTWHO_REVERSE', 2); 
     5120                define('SORTDATE_REVERSE', 0); 
     5121                define('SORTSUBJECT_REVERSE', 3); 
     5122                define('SORTSIZE_REVERSE', 6); 
     5123                 
     5124                switch (constant( $params['sort'] )){ 
     5125                        case 0 : $sA = 'date'; break; 
     5126                        case 2 : $sA = 'from'; break; 
     5127                        case 69 : $sA = 'boxname'; break; 
     5128                        case 3 : $sA = 'subject'; break; 
     5129                        case 6 : $sA = 'size'; break; 
     5130        }  
    43795131         
     5132                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC)); 
     5133                         
     5134                if(strpos($params['sort'],'REVERSE') !== false) 
     5135                        $return['msgs'] = array_reverse($return['msgs']);        
     5136                                 
     5137                 
     5138                $k = -1; 
     5139                $nMsgs = array(); 
     5140                 
     5141                foreach ($return['msgs'] as $v) 
     5142                {                
     5143                        $k++; 
     5144                        if($k < $ini || $k >= $end ) continue;                   
     5145                        $nMsgs[] = $v; 
     5146                } 
     5147                $return['msgs'] = $nMsgs; 
     5148                $return = json_encode($return);          
     5149                $return = base64_encode($return); 
     5150         
     5151                return $return; 
     5152        } 
    43805153         
    43815154    function get_quota_folders(){  
     
    44165189            return $data;  
    44175190    }   
     5191     
     5192    function getaclfrombox($mail) 
     5193        { 
     5194                $mailArray = explode('@', $mail); 
     5195                $boxacl = $mailArray[0]; 
     5196                $return = array(); 
     5197 
     5198                if(!$this->mbox) 
     5199                     $this->open_mbox(); 
     5200 
     5201                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl); 
     5202 
     5203                foreach ($mbox_acl as $user => $acl) 
     5204                { 
     5205                        if ($user != $boxacl ) 
     5206                            $return[$user] = $acl; 
     5207                } 
     5208                return $return; 
     5209        } 
    44185210} 
    44195211?> 
Note: See TracChangeset for help on using the changeset viewer.