source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 5189

Revision 5189, 200.8 KB checked in by gustavo, 12 years ago (diff)

Ticket #2332 - Pesquisa rápida - Alguns problemas de codifição

  • Property svn:eol-style set to native
  • Property svn:executable set to *
RevLine 
[2]1<?php
[1040]2
[2]3include_once("class.functions.inc.php");
4include_once("class.ldap_functions.inc.php");
[91]5include_once("class.exporteml.inc.php");
6
[2]7class imap_functions
8{
9        var $public_functions = array
[1472]10        (
[2]11                'get_range_msgs'                                => True,
12                'get_info_msg'                                  => True,
[689]13                'get_info_msgs'                                 => True,
[615]14                'get_folders_list'                              => True,
[1518]15                'import_msgs'                                   => True,
[4830]16                'report_mail_error'             => True,
[1518]17                'msgs_to_archive'                               => True
[2]18        );
19
20        var $ldap;
21        var $mbox;
22        var $imap_port;
23        var $has_cid;
24        var $imap_options = '';
25        var $functions;
[3071]26        var $prefs;
[650]27        var $foldersLimit;
[1912]28        var $imap_sentfolder;
[5134]29        var $rawMessage;
[2]30
31        function imap_functions (){
[5134]32                $this->init();
33        }
34       
35        function init(){
[3226]36                $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
[2]37                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
38                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
39                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
40                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
41                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
[1472]42                $this->functions          = new functions();
[1912]43                $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   : str_replace("*","", $this->functions->getLang("Sent"));
[2]44                $this->has_cid = false;
[3071]45                $this->prefs = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
[1472]46
[3071]47
[2]48                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
49                {
50                        $this->imap_options = '/tls/novalidate-cert';
51                }
52                else
53                {
54                        $this->imap_options = '/notls/novalidate-cert';
55                }
56        }
57        // BEGIN of functions.
[3391]58        function open_mbox($folder = False,$force_die=true)
[2]59        {
[5134]60                $folder = mb_convert_encoding($folder, "UTF7-IMAP", mb_detect_encoding($folder.'x', 'UTF-8, ISO-8859-1, UTF7-IMAP'));
[828]61                if (is_resource($this->mbox))
[3394]62                {
63                     if ($force_die)
64                     {
65                        @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
66                     }
67                     else
68                        {
69                            @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder);
70                        }
71                }
72                else
73                    {
74                        if($force_die)
75                        {
76                            $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
77                        }
78                        else
79                            {
80                                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password);
81                            }
82                       
83                    }
84                    return $this->mbox;
[2]85         }
86
[5134]87        function parse_error($error, $field = ''){
[504]88                // This error is returned from Imap.
89                if(strstr($error,'Connection refused')) {
90                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
91                }
[5134]92                else if(strstr($error,'virus')) {
[628]93                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
94                }
[5134]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."));
107                }
[504]108                // This condition verifies if SESSION is expired.
[4795]109                elseif(!count($_SESSION))
[504]110                        return "nosession";
111
112                return $error;
113        }
[1472]114
[2]115        function get_range_msgs2($params)
[4025]116        {
[4044]117                // Free others requests
118                session_write_close();
[4162]119                $folder = $params['folder'];
120                $msg_range_begin = $params['msg_range_begin'];
121                $msg_range_end = $params['msg_range_end'];
[5134]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;
[1472]125
[4044]126                if( !$this->mbox || !is_resource( $this->mbox ) )
[3392]127                        $this->mbox = $this->open_mbox($folder);
128
[4044]129        $return = array();
[4050]130
[4169]131        $return['folder'] = $folder;
132
[4044]133        //Para enviar o offset entre o timezone definido pelo usuário e GMT
134        $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
[3392]135
[4162]136        if(!$search_box_type || $search_box_type=="UNSEEN" || $search_box_type=="SEEN") {
137                        $msgs_info = imap_status($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".mb_convert_encoding( $folder, "UTF7-IMAP", "ISO_8859-1" ) ,SA_ALL);
[3392]138
139
[4162]140                        $return['tot_unseen'] = $search_box_type == "SEEN" ? 0 : $msgs_info->unseen;
[828]141
[4162]142                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
[3392]143
[4162]144                        $num_msgs = ($search_box_type=="UNSEEN") ? $msgs_info->unseen : (($search_box_type=="SEEN") ? ($msgs_info->messages - $msgs_info->unseen) : $msgs_info->messages);
145
[4025]146                        $i = 0;
[4162]147                        if(is_array($sort_array_msg)){
148                                foreach($sort_array_msg as $msg_number => $value)
149                                {
150                                        $temp = $this->get_info_head_msg($msg_number);
[5134]151                                        $temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
[4162]152                                        if(!$temp)
153                                                return false;
[4025]154
[4162]155                                        $return[$i] = $temp;
156                                        $i++;
157                                }
158                        }
159                        $return['num_msgs'] =  $num_msgs;
160                }
161                else {
162                        $num_msgs = imap_num_msg($this->mbox);
163                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
[828]164
[4044]165
[4162]166                        $return['tot_unseen'] = 0;
167                        $i = 0;
[4044]168
[4162]169                        if(is_array($sort_array_msg)){
170
171                            foreach($sort_array_msg as $msg_number => $value)
172                            {
173                                $temp = $this->get_info_head_msg($msg_number);
174                                if(!$temp)
175                                    return false;
176
177                                if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
178                                                $return['tot_unseen']++;
179                                        }
180
181                                if($i <= ($msg_range_end-$msg_range_begin))
182                                    $return[$i] = $temp;
183                                $i++;
184                            }
185                        }
186                        $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
187                }
188                return $return;
[4044]189    }
190
191        function get_info_head_msg($msg_number)
192        {
[689]193                $head_array = array();
194                include_once("class.imap_attachment.inc.php");
[828]195
[3271]196                $imap_attachment = new imap_attachment();
197                //if ($this->prefs['use_important_flag'] )
198                //{
[3071]199                        /*Como eu preciso do atributo Importance para saber se o email é
200                         * importante ou não, uso abaixo a função imap_fetchheader e busco
201                         * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
202                         * duas vezes e de duas formas diferentes, mas em contrapartida, eu
203                         * não preciso reimplementar o método utilizando o fetchheader.
204                         * Como as mensagens são renderizadas em um número pequeno por vez,
205                         * não parece ter perda considerável de performance.
206                         */
[830]207
[3071]208                        $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
209                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[3271]210                //}
211                // Reimplementado código para identificação dos e-mails assinados e cifrados
212                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
213                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
214                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
[1174]215
[689]216                $header = $this->get_header($msg_number);
[828]217                if (!is_object($header))
218                        return false;
[689]219                $head_array['Recent'] = $header->Recent;
220                $head_array['Unseen'] = $header->Unseen;
221                if($header->Answered =='A' && $header->Draft == 'X'){
222                        $head_array['Forwarded'] = 'F';
[2]223                }
[689]224                else {
225                        $head_array['Answered'] = $header->Answered;
[828]226                        $head_array['Draft']    = $header->Draft;
[46]227                }
[689]228                $head_array['Deleted'] = $header->Deleted;
229                $head_array['Flagged'] = $header->Flagged;
230                $head_array['msg_number'] = $msg_number;
[3057]231                $head_array['udate'] = $header->udate;
[3923]232                $head_array['offsetToGMT'] = $this->functions->CalculateDateOffset();
[828]233
[3923]234                $msgTimestamp = $header->udate + $head_array['offsetToGMT'];
235                $head_array['timestamp'] = $msgTimestamp;
236               
[3499]237                $date_msg = gmdate("d/m/Y",$msgTimestamp);
238//              if (date("d/m/Y") == $date_msg)
239//                      $return['udate'] = $header->udate;
240//              else
241
242                if (date("d/m/Y") == $date_msg) //no dia
243                {
244                        $head_array['smalldate'] = gmdate("H:i",$msgTimestamp);
245                }
246                else
247                {
248                        $head_array['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
249                }
250
[5134]251                if(isset($header->from))
[689]252                $from = $header->from;
253                $head_array['from'] = array();
[1740]254                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
[5134]255                if(isset($from))
[689]256                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
[5134]257                else
258                        $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@";
259                if(!$head_array['from']['name'] || trim($head_array['from']['name']) === '' )
[689]260                        $head_array['from']['name'] = $head_array['from']['email'];
[5134]261                if(isset($header->to))
[689]262                $to = $header->to;
263                $head_array['to'] = array();
[5134]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.
[3831]265                        $head_array['to']['name'] = $head_array['to']['email'] = NULL;
266                }
267                else {
268                        $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
269                        $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
270                        $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
271                        if(!$head_array['to']['name'])
272                                $head_array['to']['name'] = $head_array['to']['email'];
273                }
[5134]274                $cc = null;
275                $cco = null;
276                if(isset($header->cc)){
[3777]277                $cc = $header->cc;
[5134]278                }
279                if(isset($header->bcc)){
[3831]280                $cco = $header->bcc;
[5134]281                }
[3777]282                if ( ($cc) && (!$head_array['to']['name']) ){
283                        $head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL;
284                        $head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host;
[5134]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                        }
[3777]289                }
[3831]290                else if ( ($cco) && (!$head_array['to']['name']) ){
291                        $head_array['to']['name'] = ( isset( $cco[0]->personal ) ) ? $this->decode_string($cco[0]->personal) : NULL;
292                        $head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host;
293                        if(!$head_array['to']['name'])
[5134]294                                $head_array['to']['name'] = $head_array['from']['name'];
[3831]295                }
[1751]296                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
[5134]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                }
[828]305
[689]306                $head_array['Size'] = $header->Size;
[828]307
[689]308                $head_array['attachment'] = array();
309                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[828]310
[689]311                return $head_array;
[2]312        }
[828]313
[4416]314        /**
[5079]315        *
[4416]316        * @license    http://www.gnu.org/copyleft/gpl.html GPL
[5134]317        * @param      string $string String a ser decodificada
318        * @return     string
[4416]319        * @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
320        * @todo       Executar testes suficientes para validar a funçao iconv_mime_decode em substituição à este método decode_string
321        */
[2]322        function decode_string($string)
[4795]323        {
[5134]324        $return = '';
325        $decoded = '';
[4795]326                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
327                {
328                        $tmp = imap_mime_header_decode($string);
329                        foreach ($tmp as $tmp1)
[4416]330            {
[4795]331                                $return .= $this->htmlspecialchars_encode($tmp1->text);
[4416]332            }
[4795]333
[4416]334            return str_replace("\t", "", $return);
[4795]335                }
336                else if (strpos(strtolower($string), '=?utf-8') !== false)
337                {
338                        $elements = imap_mime_header_decode($string);
[1472]339
[4795]340                        for($i = 0;$i < count($elements);$i++)
341                        {
342                                $charset = strtolower($elements[$i]->charset);
343                                $text = $elements[$i]->text;
344                                if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
345                                $decoded .= $this->functions->utf8_to_ncr($text);
346                                else
347                                {
348                                        if( strcasecmp($charset,"default") )
349                                                $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
350                                        else
351                                                $decoded .= $this->htmlspecialchars_encode($text);
352                                }
353                        }
[1401]354
[4416]355              return str_replace("\t", "", $decoded);
[4795]356                }
[4773]357                else if(strpos(strtolower($string), '=?us-ascii') !== false)
358           {
359                        $retun = '';
360                        $tmp = imap_mime_header_decode($string);
361                        foreach ($tmp as $tmp1)
362                                $return .= $this->htmlspecialchars_encode(quoted_printable_decode($tmp1->text));
363               
364                        return str_replace("\t", "", $return);
365         
366            }
[5134]367        else if( strpos( $string , '=?' ) !== false )
368            return $this->htmlspecialchars_encode(iconv_mime_decode( $string ));
[4773]369       
[1401]370
[4795]371                        return $this->htmlspecialchars_encode($string);
372        }
[5079]373       
374       
[615]375        /**
376        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
377        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
378        */
[660]379        function import_msgs($params) {
[1000]380                if(!$this->mbox)
[660]381                        $this->mbox = $this->open_mbox();
[1472]382
[1365]383                if( preg_match('/local_/',$params["folder"]) )
[1000]384                {
[1366]385                        // PLEASE, BE CAREFULL!!! YOU SHOULD USE EMAIL CONFIGURATION VALUES (EMAILADMIN MODULE)
[1367]386                        $tmp_box = mb_convert_encoding('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'].$this->imap_delimiter.'tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
[1000]387                        if ( ! imap_createmailbox( $this -> mbox,"{".$this -> imap_server."}$tmp_box" ) )
388                                return $this->functions->getLang( 'Import to Local : fail...' );
389                        imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
390                        $params["folder"] = $tmp_box;
391                }
[615]392                $errors = array();
393                $invalid_format = false;
[1472]394                $filename = $params['FILES'][0]['name'];
[1365]395                $params["folder"] = mb_convert_encoding($params["folder"], "UTF7-IMAP","ISO_8859-1");
[660]396                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
397                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
398                        return array( 'error' => $this->functions->getLang("fail in import:").
[1000]399                                                        " ".$this->functions->getLang("Over quota"));
[660]400                }
[615]401                if(substr($filename,strlen($filename)-4)==".zip") {
[660]402                        $zip = zip_open($params['FILES'][0]['tmp_name']);
[615]403
404                        if ($zip) {
405                                while ($zip_entry = zip_read($zip)) {
[1000]406
[615]407                                        if (zip_entry_open($zip, $zip_entry, "r")) {
408                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
409                                                $status = @imap_append($this->mbox,
[660]410                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
[615]411                                                                        $email
412                                                                        );
413                                                if(!$status)
414                                                        array_push($errors,zip_entry_name($zip_entry));
415                                                zip_entry_close($zip_entry);
416                                        }
417                                }
[660]418                                zip_close($zip);
[615]419                        }
[1000]420
421                        if ( isset( $tmp_box ) && ! sizeof( $errors ) )
422                        {
423
424                                $mc = imap_check($this->mbox);
425
426                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
427
428                                $ids = array( );
429                                foreach ($result as $overview)
430                                        $ids[ ] = $overview -> uid;
431
432                                return implode( ',', $ids );
[830]433                        }
[1000]434                        }
[615]435                else if(substr($filename,strlen($filename)-4)==".eml") {
[660]436                        $email = implode("",file($params['FILES'][0]['tmp_name']));
[615]437                        $status = @imap_append($this->mbox,
[660]438                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
[615]439                                                                        $email
440                                                                        );
[5134]441                        if(!$status) {
442                                //TODO: remover zip_entry pois ele é tratado apenas ao importar mensagens zipadas
[615]443                                array_push($errors,zip_entry_name($zip_entry));
[660]444                                zip_entry_close($zip_entry);
445                        }
[5134]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 );
457                        }
[615]458                }
[1000]459                else
[615]460                {
[1000]461                        if ( isset( $tmp_box ) )
462                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
463
[660]464                        return array("error" => $this->functions->getLang("wrong file format"));
[615]465                        $invalid_format = true;
466                }
[1000]467
[615]468                if(!$invalid_format) {
469                        if(count($errors)>0) {
[660]470                                $message = $this->functions->getLang("fail in import:")."\n";
[615]471                                foreach($errors as $arquivo) {
472                                        $message.=$arquivo."\n";
473                                }
[660]474                                return array("error" => $message);
[615]475                        }
476                        else
[3843]477                                return $this->functions->getLang("The import was executed successfully.");
[615]478                }
[1000]479        }
480        /*
[613]481                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
482                a primeira parte do e-mail, que é o texto, sem anexos.
483                O método considera que o email é multpart.
484        */
485        function remove_attachments($params) {
486                include_once("class.message_components.inc.php");
487                if(!$this->mbox || !is_resource($this->mbox))
488                        $this->mbox = $this->open_mbox($params["folder"]);
489                $return["status"] = true;
490                $header = "";
[1472]491
[613]492                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
493                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
494                        $head1 = explode(":",$head);
[1472]495                        if ( (strtoupper($head1[0]) == "TO") ||
[3566]496                                        (strtoupper($head1[0]) == "FROM") ||
497                                        (strtoupper($head1[0]) == "SUBJECT") ||
498                                        (strtoupper($head1[0]) == "DATE") )
499                                $header .= $head."\r\n";
[613]500                }
[1472]501
[5134]502                $msg = new message_components($this->mbox);
[1472]503                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
504                                                             Então uso essa classe para verificar a codificação e o charset,
[613]505                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
[1472]506
[3566]507                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][0]);
508                $all_body_encoding = $msg->encoding[$params["msg_num"]][0];
509                $all_body_charset = $msg->charset[$params["msg_num"]][0];
510               
511                if($all_body_type=='multipart/alternative') {
512                        if(strtolower($msg->file_type[$params["msg_num"]][2]=='text/html') &&
513                                        $msg->pid[$params["msg_num"]][2] == '1.2') {
514                                $body_part_to_show = '1.2';
515                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][2]);
516                                $all_body_encoding = $msg->encoding[$params["msg_num"]][2];
517                                $all_body_charset = $msg->charset[$params["msg_num"]][2];
518                        }
519                        else {
520                                $body_part_to_show = '1.1';
521                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][1]);
522                                $all_body_encoding = $msg->encoding[$params["msg_num"]][1];
523                                $all_body_charset = $msg->charset[$params["msg_num"]][1];
524                        }
525                }
526                else
527                        $body_part_to_show = '1';
528
[1319]529                $status = imap_append($this->mbox,
[613]530                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
531                                        $header.
[3566]532                                        "Content-Type: ".$all_body_type."; charset = \"".$all_body_charset."\"".
[613]533                                        "\r\n".
[3566]534                                        "Content-Transfer-Encoding: ".$all_body_encoding.
535                                        "\r\n".
536                                        "\r\n".
[5134]537                                        str_replace("\n","\r\n",preg_replace("/<img[^>]+\>/i", " ", $this->decodeBody(
[3566]538                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
539                                                        $all_body_encoding, $all_body_charset
[5134]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.
[1472]542
[1319]543                if(!$status)
544                {
[613]545                        $return["status"] = false;
546                        $return["msg"] = lang("error appending mail on delete attachments");
547                }
[1319]548                else
549                {
550                        $status = imap_status($this->mbox, "{".$this->imap_server.":".$this->imap_port."}".$params['folder'], SA_UIDNEXT);
[1472]551                        $return['msg_no'] = $status->uidnext - 1;
[1319]552                        imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"]));
553                        imap_expunge($this->mbox);
554                }
[1472]555
[613]556                return $return;
[1472]557
[613]558        }
[1518]559       
560        function msgs_to_archive($params) {
561               
562                $folder = $params['folder'];
[1931]563                $all_ids = $this-> get_msgs($folder, 'SORTARRIVAL', false, 0,-1,-1);
[613]564
[1518]565                $messages_not_to_copy = explode(",",$params['mails']);
566                $ids = array();
567               
[1931]568                $cont = 0;
569               
[1518]570                foreach($all_ids as $each_id=>$value) {
[1931]571                        if(!in_array($each_id,$messages_not_to_copy)) {
[1518]572                                array_push($ids,$each_id);
[1931]573                                $cont++;
574                        }
575                        if($cont>=100)
576                                break;
[1518]577                }
578
579                if (empty($ids))
580                        return array();
581
582                $params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
583               
584               
585                return $this->get_info_msgs($params);
586               
587               
588        }
589
[689]590/**
[1472]591         *
592         * @return
[689]593         * @param $params Object
594         */
595        function get_info_msgs($params) {
596                include_once("class.exporteml.inc.php");
[5172]597               
598                if(array_key_exists('messages', $params)){
599                        $sel_msgs = explode(",", $params['messages']);
600                        @reset($sel_msgs);
601                        $sorted_msgs = array();
602                        foreach($sel_msgs as $idx => $sel_msg) {
603                                $sel_msg = explode(";", $sel_msg);
604                                if(array_key_exists($sel_msg[0], $sorted_msgs)){
605                                        $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
606                                }
607                                else {
608                                        $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
609                                }
610                        }
611                        unset($sorted_msgs['']);       
612               
613                        $return = array();
614                        $array_names_keys = array_keys($sorted_msgs);
615                       
616                        for($i = 0; $i < count($sorted_msgs); $i++){
617                       
618                                $new_params = array();
619                                $attach_params = array();
620                       
621                                $new_params["msg_folder"]= $array_names_keys[$i];
622                                $attach_params["folder"] = $params["folder"];
623                                $msgs = explode(",",$sorted_msgs[$array_names_keys[$i]]);
624                                $exporteml = new ExportEml();
625                                $unseen_msgs = array();
626                                foreach($msgs as $msg_number) {
627                                        $new_params["msg_number"] = $msg_number;
628                                        //ini_set("display_errors","1");
629                                        $msg_info = $this->get_info_msg($new_params);
630
631                                        $this->mbox = $this->open_mbox($array_names_keys[$i]); //Não sei porque, mas se não abrir de novo a caixa dá erro.
632                                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
633
634                                        $attach_params["num_msg"] = $msg_number;
635                                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
636                                        imap_close($this->mbox);
637                                        $this->mbox=false;
638                                        array_push($return,serialize($msg_info));
639                               
640                                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
641                                                        array_push($unseen_msgs,$msg_number);
642                                        }
643                                }
644                        }
645                        if($unseen_msgs){
646                                $msgs_list = implode(",",$unseen_msgs);
647                                $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
648                                $this->set_messages_flag($array_msgs);
649                        }
650                        return $return;
651                }else{
[689]652                $return = array();
653                $new_params = array();
654                $attach_params = array();
655                $new_params["msg_folder"]=$params["folder"];
656                $attach_params["folder"] = $params["folder"];
657                $msgs = explode(",",$params["msgs_number"]);
658                $exporteml = new ExportEml();
[1382]659                $unseen_msgs = array();
[689]660                foreach($msgs as $msg_number) {
661                        $new_params["msg_number"] = $msg_number;
662                        //ini_set("display_errors","1");
663                        $msg_info = $this->get_info_msg($new_params);
664
665                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
666                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
667
668                        $attach_params["num_msg"] = $msg_number;
669                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
670                        imap_close($this->mbox);
671                        $this->mbox=false;
672                        array_push($return,serialize($msg_info));
[1472]673
[1388]674                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
[1472]675                                        array_push($unseen_msgs,$msg_number);
676                        }
677                }
[1382]678                if($unseen_msgs){
679                        $msgs_list = implode(",",$unseen_msgs);
680                        $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
[1472]681                        $this->set_messages_flag($array_msgs);
[689]682                }
683                return $return;
684        }
[5172]685        }
[4795]686
[4436]687        /**
[5079]688        * @license    http://www.gnu.org/copyleft/gpl.html GPL
689        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]690        * @param     $msg_number numero da mensagem
[4436]691        */
[4416]692        function getRawHeader($msg_number)
693    {
694                return imap_fetchheader($this->mbox, $msg_number, FT_UID);
695        }
696       
[4436]697        /**
[5079]698        * @license    http://www.gnu.org/copyleft/gpl.html GPL
699        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]700        * @param     $msg_number numero da mensagem
[4436]701        */
[4416]702        function getRawBody($msg_number)
703    {
704                return  imap_body($this->mbox, $msg_number, FT_UID);   
705        }
[689]706
[4436]707       
708        /**
[5079]709        * @license    http://www.gnu.org/copyleft/gpl.html GPL
710        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]711        * @param     $msg mensagem
[4436]712        */
[4416]713        function builderMsgHeader($msg)
714    {
715
716 
717            $fromMail =  str_replace('<','', str_replace('>','',$msg->headers['from']));
718            $tosMails =  str_replace('<','', str_replace('>','',$msg->headers['to']));
719
720            $tos = explode(',',$tosMails);
721            $to = '';
722            foreach ($tos as $value)
723            {
724                $to .= '<a href="mailto:'.str_replace(' ','',$value).'">'.$value.'</a>, ';
725            }
726
727            $header = '
728                <table style="margin: 2px; border: 1px solid black; background: none repeat scroll 0% 0% rgb(234, 234, 234);">
729                <tbody>
730                <tr><td><b>'.$this->functions->getLang('Subject').':</b></td><td>'.$msg->headers['subject'].'</td></tr>
731                <tr><td><b>'.$this->functions->getLang('From').':</b></td><td><a href="mailto:'.$fromMail.'">'.$fromMail.'</a></td></tr>
732                <tr><td><b>'.$this->functions->getLang('Date').':</b></td><td>'.$msg->headers['date'].'</td></tr>
733                <tr><td><b>'.$this->functions->getLang('To').':</b></td><td>'.$to.'</td></tr>
734                </tbody>
735                </table>
736                <br />'
737            ;
738
739          return $header;
740    }
741       
[5079]742        /**
[5134]743        * Constroe o corpo da msg direto na variavel de conteudo
744        * @param Mail_mimeDecode $structure
745        * @param <type> $content Ponteiro para Variavel de conteudo da msg
[5079]746        */
[4416]747        function builderMsgBody($structure , &$content , $printHeader = false)
748        {
749            if(strtolower($structure->ctype_primary) == 'multipart' && strtolower($structure->ctype_secondary) == 'alternative')
750            {
751                $numParts = count($structure->parts) - 1;
752
753                for($i = $numParts; $i >= 0; $i--)
754                {
755                    $part = $structure->parts[$i];
756
757                    switch (strtolower($part->ctype_primary))
758                    {
759                       case 'text':
[5134]760                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
[4416]761                           if($disposition != 'attachment')
762                           {
763                                if(strtolower($part->ctype_secondary) == 'html')
764                                {
765                                   if($printHeader)
766                                        $content .= $this->builderMsgHeader($part);
767
768                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
769                                }
770
771                                if(strtolower($part->ctype_secondary) == 'plain' )
772                                {
773                                  if($printHeader)
774                                      $content .= $this->builderMsgHeader($part);
775
[4781]776                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
[4416]777                                }
[5134]778                                if(strtolower($part->ctype_secondary) == 'calendar')
779                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
[4416]780
781                           }
782
783                            $i = -1;
784                            break;
785
786                       case 'multipart':
787
788                            if($printHeader)
789                               $content .= $this->builderMsgHeader($part);
790
791                            $this->builderMsgBody($part,$content);
792
793                            $i = -1;
794                            break;
795
796                       case 'message':
797
798                            if(!is_array($part->parts))
799                            {
800                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4781]801                                $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body, $structure->ctype_parameters['charset'],false)).'</pre>';
[4416]802                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
803                            }
804                            else
805                                $this->builderMsgBody($part,$content,true);
806
807                            $i = -1;
808                            break;
809                    }
810                }
811            }
812            else
813            {
814                foreach ($structure->parts  as $index => $part)
815                {
816                   switch (strtolower($part->ctype_primary))
817                   {
818                       case 'text':
[5134]819                           $disposition = '';
820                           if(isset($part->disposition))
821                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
[4416]822                           if($disposition != 'attachment')
823                           {
824                                if(strtolower($part->ctype_secondary) == 'html')
825                                {
826                                   if($printHeader)
827                                        $content .= $this->builderMsgHeader($part);
828
829                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
830                                }
831
832                                if(strtolower($part->ctype_secondary) == 'plain')
833                                {
834                                  if($printHeader)
835                                      $content .= $this->builderMsgHeader($part);
836
[4781]837                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
[4416]838                                }
[5134]839                                if(strtolower($part->ctype_secondary) == 'calendar')
840                                    $content .= $this->builderMsgCalendar($part->body);
[4416]841                       
842                           }
843                            break;
844                       case 'multipart':
845
846                            if($printHeader)
847                               $content .= $this->builderMsgHeader($part);
848
849                            $this->builderMsgBody($part,$content);
850
851                            break;
852                       case 'message':
[5134]853                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != '1')
854                        {
[4416]855                            if(!is_array($part->parts))
856                            {
857                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4781]858                                $content .= '<pre>'.  htmlentities($this->decodeMailPart($part->body, $structure->ctype_parameters['charset'],false)).'</pre>';
[4416]859                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
860                            }
861                            else
862                                $this->builderMsgBody($part,$content,true);
863                        break;
864                 }
865               }
866            }
867        }
[5134]868        }
[4416]869       
870       
[4436]871        /**
[5079]872        * @license    http://www.gnu.org/copyleft/gpl.html GPL
873        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]874        * @param     $msg_number numero da mensagem
[4436]875        */
876        function get_msg_sample($msg_number)
[4416]877        {
[5134]878        $content = '';
[4416]879
880                $return = "";
881                if( (!isset($this->prefs['preview_msg_subject']) || ($this->prefs['preview_msg_subject'] != "1")) &&
882                        (!isset($this->prefs['preview_msg_tip']    ) || ($this->prefs['preview_msg_tip']     != "1")) )
883                {
884                        $return['body'] = "";
885                        return $return;
886                }
887
888                include_once("class.message_components.inc.php");
[5134]889                $msg = new message_components($this->mbox);
[4416]890                $msg->fetch_structure($msg_number); 
891
[5134]892                if(!isset($msg->structure[$msg_number]->parts))
[4416]893                {
894                        $content = '';
895                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
896                        {
897                                $content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
898                        }
899                }
900                else
901                {
902                        foreach($msg->pid[$msg_number] as $values => $msg_part)
903                        {
904
905                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
906                                if($file_type == "text/plain" || $file_type == "text/html") {
907                                        $content = $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID|FT_PEEK), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
908                                        break;
909                                }
910                        }
911                }
[5134]912     
[4416]913                $tags_replace = array("<br>","<br/>","<br />");
[5134]914                $content = str_replace($tags_replace," ", nl2br($content));
915                $content = $this->html2txt($content);   
[4416]916                $content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
[5134]917                $return['body'] = base64_encode(mb_convert_encoding(substr($return['body'], 0, 305),'ISO-8859-1'));
[4416]918                return $return;
919        }
[5134]920    function html2txt($document){
921        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
922                       '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
923                       '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
924                       '@<![\s\S]*?--[ \t\n\r]*>@si'         // Strip multi-line comments including CDATA                   
925        );
926        $text = preg_replace($search, '', $document);
927        return html_entity_decode($text);
928    }
929
930    function ope_msg_part($params)
931    {
932        $return = array();
933        require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
[4416]934       
[5134]935        $atObj = new attachment();
936        $atObj->setStructureFromMail($params['msg_folder'],$params['msg_number']);
937        $mbox_stream = $this->open_mbox($params['save_folder']);
938        $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], $atObj->getAttachment($params['msg_part']), "\\Seen \\Draft");
939        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], SA_UIDNEXT);
[4416]940       
[5134]941        $return['msg_folder']  = $params['save_folder'];
942        $return['msg_number'] = $status->uidnext - 1;       
943
944        return $return;
945
946    }
[5079]947       
[2]948        function get_info_msg($params)
949        {
[51]950                $return = array();
[2]951                $msg_number = $params['msg_number'];
[1724]952                $msg_folder = urldecode($params['msg_folder']);
[4416]953               
[5134]954                if(preg_match('/(.+)(_[a-zA-Z0-9]+)/',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.
[4795]955                        $msg_number = $matches[1];
956                        $plus_id = $matches[2];
957                }
958                else {
959                        $plus_id = '';
960                }
961
[411]962                if(!$this->mbox || !is_resource($this->mbox))
[4795]963                        $this->mbox = $this->open_mbox($msg_folder);
[4416]964               
[535]965                $header = $this->get_header($msg_number);
[205]966                if (!$header) {
[4795]967                        $return['status_get_msg_info'] = "false";
[205]968                        return $return;
969                }
[4795]970
971                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
[51]972                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
[4416]973                $body = $return_get_body['body'];
[1035]974                if($return_get_body['body']=='isCripted'){
975                        $exporteml = new ExportEml();
976                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
977                        $return['body']                 = "";
978                        $return['attachments']  =  "";
979                        $return['thumbs']               =  "";
980                        $return['signature']    =  "";
981                        //return $return;
982                }else{
[4795]983            $return['body']             = $body;
984            $return['attachments']      = $return_get_body['attachments'];
985            $return['thumbs']           = $return_get_body['thumbs'];
[5134]986            //$return['signature']      = $return_get_body['signature'];
[4795]987                }
[3018]988                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
[828]989                if (preg_match($pattern, $header_, $fields))
990                {
[4795]991                        if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
992                                $return['DispositionNotificationTo'] = "<".$matches[0].">";
993                        }
[2]994                }
[828]995
[2]996                $return['Recent']       = $header->Recent;
997                $return['Unseen']       = $header->Unseen;
[4795]998                $return['Deleted']      = $header->Deleted;
[2]999                $return['Flagged']      = $header->Flagged;
1000
1001                if($header->Answered =='A' && $header->Draft == 'X'){
1002                        $return['Forwarded'] = 'F';
1003                }
[4795]1004
[2]1005                else {
1006                        $return['Answered']     = $header->Answered;
[4795]1007                        $return['Draft']        = $header->Draft;
[2]1008                }
1009
[4795]1010                $return['msg_number'] = $msg_number.$plus_id;
[2]1011                $return['msg_folder'] = $msg_folder;
[4795]1012
[5134]1013               
1014               
1015                $msgTimesTamp = $header->udate + $this->functions->CalculateDateOffset(); //Aplica offset do usuario
1016                $date_msg = gmdate("d/m/Y",$msgTimesTamp);
[4795]1017
[5134]1018//      Removido codigo pois a o método send_nofication precisa da data completa.
1019//              if (date("d/m/Y") == $date_msg)
1020//                      $return['udate'] = gmdate("H:i",$header->udate);
1021//              else
1022
1023//      Passa o a data completa para mensagem.         
1024                $return['udate'] = $header->udate;
1025
[4795]1026                $return['msg_day'] = $date_msg;
[5134]1027                $return['msg_hour'] = gmdate("H:i",$msgTimesTamp);
[4795]1028
[2]1029                if (date("d/m/Y") == $date_msg) //no dia
1030                {
[5134]1031                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
1032                        $return['smalldate'] = gmdate("H:i",$msgTimesTamp);
1033                       
[605]1034
[5134]1035                                $timestamp_now = strtotime("now");
1036                        //      removido offset nao esta sendo parametrizado
1037                        //      $timestamp_now = strtotime("now") + $offset;
1038                       
1039                       
1040                        $timestamp_msg_time = $msgTimesTamp;
[4416]1041                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
[535]1042                        // The variable $timestamp_diff is calculated without MailDate TZ.
[4416]1043                        $pdate = date_parse($header->MailDate);
1044                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
[4795]1045
[2]1046                        if (gmdate("H",$timestamp_diff) > 0)
1047                        {
[197]1048                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
[2]1049                        }
1050                        else
1051                        {
1052                                if (gmdate("i",$timestamp_diff) == 0){
[197]1053                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
[2]1054                                }
1055                                elseif (gmdate("i",$timestamp_diff) == 1){
[197]1056                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
[2]1057                                }
1058                                else{
[197]1059                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
[2]1060                                }
1061                        }
1062                }
1063                else{
[5134]1064                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
1065                        $return['smalldate'] = gmdate("d/m/Y",$msgTimesTamp);
[2]1066                }
[4795]1067
[2]1068                $from = $header->from;
1069                $return['from'] = array();
[5134]1070                $return['from']['name'] = isset($sender[0]->personal) ? $this->decode_string($from[0]->personal) : '';
[2]1071                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
1072                if ($return['from']['name'])
1073                {
1074                        if (substr($return['from']['name'], 0, 1) == '"')
1075                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
1076                        else
1077                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
1078                }
1079                else
1080                        $return['from']['full'] = $return['from']['email'];
[4795]1081
[2]1082                // Sender attribute
1083                $sender = $header->sender;
[4795]1084                $return['sender'] = array();
[5134]1085                $return['sender']['name'] = isset($sender[0]->personal) ? $this->decode_string($sender[0]->personal): '';
[2]1086                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
[5134]1087               
[2]1088                if ($return['sender']['name'])
1089                {
1090                        if (substr($return['sender']['name'], 0, 1) == '"')
1091                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
1092                        else
1093                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
1094                }
1095                else
1096                        $return['sender']['full'] = $return['sender']['email'];
1097
1098                if($return['from']['full'] == $return['sender']['full'])
1099                        $return['sender'] = null;
1100                $to = $header->to;
1101                $return['toaddress2'] = "";
1102                if (!empty($to))
1103                {
1104                        foreach ($to as $tmp)
1105                        {
1106                                if (!empty($tmp->personal))
1107                                {
1108                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
1109                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
1110                                        $return['toaddress2'] .= " ";
1111                                        $return['toaddress2'] .= "&lt;";
[320]1112                                        if ($tmp->host != 'unspecified-domain')
1113                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
1114                                        else
1115                                                $return['toaddress2'] .= $tmp->mailbox;
[2]1116                                        $return['toaddress2'] .= "&gt;";
1117                                        $return['toaddress2'] .= ", ";
1118                                }
1119                                else
1120                                {
[320]1121                                        if ($tmp->host != 'unspecified-domain')
1122                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
1123                                        else
1124                                                $return['toaddress2'] .= $tmp->mailbox;
[2]1125                                        $return['toaddress2'] .= ", ";
1126                                }
1127                        }
1128                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
1129                }
[4416]1130                else
1131                {
[4730]1132                        $return['toaddress2'] = "";
[4416]1133                }       
[5134]1134                if(isset($header->cc))
[2]1135                $cc = $header->cc;
1136                $return['cc'] = "";
1137                if (!empty($cc))
1138                {
1139                        foreach ($cc as $tmp_cc)
1140                        {
1141                                if (!empty($tmp_cc->personal))
1142                                {
1143                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
1144                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
1145                                        $return['cc'] .= " ";
1146                                        $return['cc'] .= "&lt;";
[5134]1147                                        if ($tmp_cc->host != 'unspecified-domain')
[2]1148                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[5134]1149                                        else
1150                                                $return['cc'] .= $tmp_cc->mailbox;
1151                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[2]1152                                        $return['cc'] .= "&gt;";
1153                                        $return['cc'] .= ", ";
1154                                }
1155                                else
1156                                {
[5134]1157                                        if ($tmp_cc->host != 'unspecified-domain')
[2]1158                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[5134]1159                                        else
1160                                                $return['cc'] .= $tmp_cc->mailbox;
1161                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[2]1162                                        $return['cc'] .= ", ";
1163                                }
1164                        }
1165                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
1166                }
1167                else
1168                {
1169                        $return['cc'] = "";
[4795]1170                }
[449]1171
1172                ##
1173                # @AUTHOR Rodrigo Souza dos Santos
1174                # @DATE 2008/09/12
1175                # @BRIEF Adding the BCC field.
1176                ##
[5134]1177        if(isset($header->bcc)){       
[4795]1178                $bcc = $header->bcc;
[5134]1179                }
[449]1180                $return['bcc'] = "";
1181                if (!empty($bcc))
1182                {
1183                        foreach ($bcc as $tmp_bcc)
1184                        {
1185                                if (!empty($tmp_bcc->personal))
1186                                {
1187                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
1188                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
1189                                        $return['bcc'] .= " ";
1190                                        $return['bcc'] .= "&lt;";
[5134]1191                                        if ($tmp_bcc->host != 'unspecified-domain')
[449]1192                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
[5134]1193                                        else
1194                                                $return['bcc'] .= $tmp_bcc->mailbox;
[449]1195                                        $return['bcc'] .= "&gt;";
1196                                        $return['bcc'] .= ", ";
1197                                }
1198                                else
1199                                {
[5134]1200                                        if ($tmp_bcc->host != 'unspecified-domain')
[449]1201                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
[5134]1202                                        else
1203                                                $return['bcc'] .= $tmp_bcc->mailbox;
1204                                        //$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
[449]1205                                        $return['bcc'] .= ", ";
1206                                }
1207                        }
1208                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
[426]1209                }
[449]1210                else
1211                {
1212                        $return['bcc'] = "";
[4795]1213                }
[426]1214
[2]1215                $reply_to = $header->reply_to;
1216                $return['reply_to'] = "";
1217                if (is_object($reply_to[0]))
1218                {
1219                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
1220                        {
1221                                if (!empty($reply_to[0]->personal))
1222                                {
1223                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
[41]1224                                        if(!empty($personal_reply_to[0]->text)) {
1225                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
1226                                                $return['reply_to'] .= " ";
1227                                                $return['reply_to'] .= "&lt;";
1228                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1229                                                $return['reply_to'] .= "&gt;";
1230                                        }
1231                                        else {
1232                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1233                                        }
[2]1234                                }
1235                                else
1236                                {
1237                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1238                                }
1239                        }
1240                }
1241                $return['reply_to'] = $this->decode_string($return['reply_to']);
1242                $return['subject'] = $this->decode_string($header->fetchsubject);
[5134]1243
1244                if($return['subject'] == $this->functions->getLang("(no subject)   ")){
1245                        $return['subject'] = str_replace(" ","", $return['subject']);
1246                }
1247                if($return['subject'] == '' || $return['subject'] == null){
1248                        $return['subject'] = $this->functions->getLang("(no subject)   ");
1249                }
[4795]1250                $return['Size'] = $header->Size;
[828]1251                $return['reply_toaddress'] = $header->reply_toaddress;
[4795]1252
[689]1253                //All this is to help in local messages
[4795]1254                $return['timestamp'] = $header->udate;
[689]1255                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
1256                $return['reply_toaddress'] = $header->reply_toaddress;
[4795]1257               
[5134]1258                if(($return['from']['email'] ==  '@unspecified-domain' || $return['sender']['email'] == null) && $return['msg_folder'] == 'INBOX/Drafts'){
1259                        $return['from']['email'] = "Rascunho";
1260                }
1261                if($return['toaddress2'] == 'undisclosed-recipients@, @'){
1262                        $return['toaddress2'] = $this->functions->getLang('without destination');
1263                }
[2]1264                return $return;
1265        }
[1472]1266
[5079]1267       
[5134]1268        /*
[5079]1269        * Converte textos utf8 para o padrão html.
[5134]1270         * Modificado por Cristiano Corrêa Schmidt
1271         * @link http://php.net/manual/en/function.utf8-decode.php
[5079]1272        * @author     luka8088 <luka8088@gmail.com>
1273        */     
[4781]1274        function utf8_to_html ($data)
[4795]1275        {
[4781]1276            return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '$this->_utf8_to_html("\\1")', $data);
1277        }
[4795]1278
[4781]1279        function _utf8_to_html ($data)
[4795]1280                {
[4781]1281            $ret = 0;
1282                foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
1283                        $ret += (ord($v) % 128) * pow(64, $k);
[5134]1284                    return html_entity_decode("&#$ret;" , ENT_QUOTES);
[4795]1285                }
[4781]1286        //------------------------------------------------------------------------------//
[4795]1287
1288
[4416]1289                /**
[5134]1290         * Decodifica uma part da mensagem para iso-8859-1
1291         * @param <type> $part parte do email
1292         * @param <type> $encode codificação da parte
1293         * @return <type> string decodificada
[5079]1294                */
[4781]1295        function decodeMailPart($part, $encode, $html = true)
[4795]1296                {
[4416]1297            switch (strtolower($encode))
[4795]1298                        {
[4416]1299                case 'iso-8859-1':
1300                    return $part;
1301                    break;
[1752]1302
[4416]1303                case 'utf-8':
[5134]1304                    if ($html) return  $this->utf8_to_html($part);
1305                    else       return  utf8_decode ($part);
[4416]1306                    break;
[1752]1307
[4416]1308                default:
1309                    return mb_convert_encoding($part, 'iso-8859-1');
[4795]1310                                        break;
1311                                }
1312                        }
1313
[4416]1314       
[2]1315        function get_body_msg($msg_number, $msg_folder)
1316        {
[4429]1317            /*
[4416]1318             * Requires of librarys
1319             */
1320            require_once $_SESSION['rootPath'].'/library/mime/mimePart.php';
1321            require_once $_SESSION['rootPath'].'/library/mime/mimeDecode.php';
1322            require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
[5134]1323            //include_once("class.message_components.inc.php");
[4416]1324            //--------------------------------------------------------------------//
[1472]1325
[4416]1326            $return = array();
[1035]1327
[5134]1328//            $msg = new message_components($this->mbox);
1329//            $msg->fetch_structure($msg_number);
[1035]1330
[4416]1331            $content = '';
[1035]1332
[5134]1333            /*
1334            * Chamada original  $this->getRawHeader($msg_number)."\r\n".$this->getRawBody($msg_number);
1335            * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios
1336            */
1337            $rawMessageData = str_replace("\r\n\t", '', $this->getRawHeader($msg_number))."\r\n".$this->getRawBody($msg_number);
[3018]1338
[4416]1339            $decoder = new Mail_mimeDecode($rawMessageData);
[3018]1340
[4416]1341            $params['include_bodies'] = true;
1342            $params['decode_bodies']  = true;
1343            $params['decode_headers'] = true;
[5134]1344                        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'))
1345                                $params['rfc_822bodies']  = true;
[4416]1346            $structure = $decoder->decode($params);
[3018]1347
[4416]1348            /*
1349             * Inicia Gerenciador de Anexos
1350             */
1351            $attachmentManager = new attachment();
1352            $attachmentManager->setStructure($structure);
1353            //----------------------------------------------//
[1472]1354
[4416]1355            /*
[4429]1356             * Monta informações dos anexos para o cabecalhos
[4416]1357             */
1358            $attachments = $attachmentManager->getAttachmentsInfo();
1359            $return['attachments'] = $attachments;
1360            //----------------------------------------------//
[2]1361
[4416]1362            /*
[4429]1363             * Monta informações das imagens
1364             */
[4416]1365            $images = $attachmentManager->getEmbeddedImagesInfo();
1366            //----------------------------------------------//
[1472]1367
[4795]1368                if(!$this->has_cid)
1369                {
[4416]1370                    $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
[5134]1371               // $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
[4795]1372                }
[1472]1373
[4416]1374            switch (strtolower($structure->ctype_primary))
[4795]1375                {
[4908]1376                        case 'text':
1377                                        if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
1378                                        {
[4795]1379                                $return['body']='isCripted';
1380                                return $return;
1381                        }
[4416]1382                        $attachment = array();
[3414]1383
[4416]1384                        $msg_subtype = strtolower($structure->ctype_secondary);
[5134]1385                    if(isset($structure->disposition))
[4416]1386                        $disposition = strtolower($structure->disposition);
[5134]1387                    else
1388                        $disposition = '';
[1472]1389
[4908]1390                        if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
[4795]1391                        {
[4416]1392                                if(strtolower($msg_subtype) == 'plain')
[4795]1393                                        {
[5134]1394                        if(isset($structure->ctype_parameters['charset']))
[4781]1395                                        $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false);
[5134]1396                        else
1397                            $content = $this->decodeMailPart($structure->body, null,false);
[4795]1398                                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );
1399                                                $content = htmlentities( $content );
[4784]1400                                        $this->replace_links($content);
[4795]1401                                                $content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content );
1402                                                $content = '<pre>' . $content . '</pre>';
1403                                                $return[ 'body' ] = $content;
1404                                                return $return;
1405                                        }
[4781]1406                                                                $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']);
[4795]1407                                }
[5134]1408                    if(strtolower($structure->ctype_secondary) == 'calendar')
1409                           $content .= $this->builderMsgCalendar($structure->body);
[1897]1410
[4416]1411                    break;
[1897]1412
[4429]1413               case 'multipart':
[5134]1414                    $this->builderMsgBody($structure , $content);
[1897]1415
[4416]1416                    break;
[1897]1417
[4416]1418               case 'message':
[5134]1419                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != 1)
1420                    {
[4416]1421                    if(!is_array($structure->parts))
[4795]1422                                {
[4416]1423                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4781]1424                        $content .= '<pre>'.htmlentities($this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false)).'</pre>';
[4416]1425                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4795]1426                                                }
1427                                            else
[4416]1428                        $this->builderMsgBody($structure , $content,true);
[5134]1429                    }
[4429]1430                    break;
[3018]1431
[5134]1432            case 'application':
1433                if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
1434                {   
1435                  //  $return['body']='isCripted';
1436                  // return $return;
1437                                 
1438                                  //TODO: Descartar código após atualização do módulo de segurança da SERPRO
1439                                        $rawMessageData2 = $this->extractSignedContents($rawMessageData);
1440                                        if($rawMessageData2 === false){
1441                                                $return['body']='isCripted';
1442                                                return $return;
1443                                        }
1444                                        $decoder2 = new Mail_mimeDecode($rawMessageData2);
1445                            $structure2 = $decoder2->decode($params);
1446                            $this-> builderMsgBody($structure2 , $content); 
1447                 
1448                            $attachmentManager->setStructure($structure2);
1449                            /*
1450                            * Monta informações dos anexos para o cabecarios
1451                            */
1452                            $attachments = $attachmentManager->getAttachmentsInfo();
1453                        $return['attachments'] = $attachments;
1454
1455                            //----------------------------------------------//
1456                 
1457                            /*
1458                        * Monta informações das imagens
1459                            */
1460                            $images = $attachmentManager->getEmbeddedImagesInfo();
1461                            //----------------------------------------------//
1462                 
1463                            if(!$this->has_cid){
1464                                $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
1465                                $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
1466                            }
1467                }
1468                        ///////////////////////////////////////////////////////////////////////////////////////////
[4429]1469               default:
1470                    if(count($attachments) > 0)
1471                       $content .= '';
1472                    break;
[4795]1473                                                                }
[3018]1474
[1472]1475                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
[2]1476                $this->set_messages_flag($params);
[4416]1477                $content = $this->process_embedded_images($images,$msg_number,$content, $msg_folder);
[4795]1478                $content = $this->replace_special_characters($content);
[4416]1479                $this->replace_links($content);
1480                $return['body'] = &$content;
1481               
[4795]1482                return $return;
[2]1483        }
[1472]1484
[5134]1485       
1486        //TODO: Descartar código após atualização do módulo de segurança da SERPRO
1487        function extractSignedContents( $data )
1488    {
1489                $pipes_desc = array(
1490                        0 => array('pipe', 'r'),
1491                        1 => array('pipe', 'w')
1492            );
1493         
1494            $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes);
1495            if (!is_resource($fp)) {
1496                        return false;
1497            }
1498         
1499            $output = '';
1500         
1501                /* $pipes[0] => writeable handle connected to child stdin
1502                $pipes[1] => readable handle connected to child stdout */
1503            fwrite($pipes[0], $data);
1504            fclose($pipes[0]);
1505         
1506            while (!feof($pipes[1])) {
1507                        $output .= fgets($pipes[1], 1024);
1508            }
1509            fclose($pipes[1]);
1510            proc_close($fp);
1511         
1512            return $output;
1513        }
1514    ///////////////////////////////////////////////////////////////////////////////////////
1515   
1516        function builderMsgCalendar($calendar)
1517        {
1518            $icalService = ServiceLocator::getService('ical');
1519
1520            $codificao =  mb_detect_encoding($calendar.'x', 'UTF-8, ISO-8859-1');
1521            if($codificao == 'UTF-8')
1522                $calendar = utf8_decode($calendar);
1523
1524            if($icalService->setIcal($calendar))
1525            {
1526                $content = '';
1527
1528                switch ($icalService->getMethod()) {
1529
1530                    case 'REPLY':
1531                          include_once($_SESSION['rootPath'].'/header.inc.php');
1532                          include_once($_SESSION['rootPath'].'/calendar/inc/class.boicalendar.inc.php');
1533                          $boicalendar = new boicalendar();
1534
1535                          $ical = $icalService->getComponent('vevent');
1536                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
1537                          $content.= '<span style="font-size: 12" >';
1538                          $notExist = false;
1539
1540                          foreach ($ical['attendee'] as $attendee)
1541                          {
1542                                if($attendee['params']['PARTSTAT'] == 'ACCEPTED')
1543                                {
1544                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'ACCEPTED',$attendee['params']['CN']))
1545                                    {
1546                                        $content.= $this->functions->getLang('User').' ';
1547                                        if($attendee['params']['CN'])
1548                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1549                                        else
1550                                            $content.= '<b>'.$attendee['value'].'</b> ';
1551
1552                                        $content.= $this->functions->getLang('accepted your event');
1553                                    }
1554                                    else
1555                                        $notExist = true;
1556                                }
1557
1558                                if($attendee['params']['PARTSTAT'] == 'TENTATIVE')
1559                                {
1560                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'TENTATIVE',$attendee['params']['CN']))
1561                                    {
1562                                        $content.= $this->functions->getLang('User').' ';
1563                                        if($attendee['params']['CN'])
1564                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1565                                        else
1566                                            $content.= '<b>'.$attendee['value'].'</b> ';
1567
1568                                        if($ical['description']['value'])
1569                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1570                                        else
1571                                            $content.= $this->functions->getLang('provisionally accepted you event');
1572                                    }
1573                                    else
1574                                         $notExist = true;
1575                                }
1576
1577                                if($attendee['params']['PARTSTAT'] == 'DECLINED')
1578                                {
1579                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'DECLINED',$attendee['params']['CN']))
1580                                    {
1581                                        $content.= $this->functions->getLang('User').' ';
1582                                        if($attendee['params']['CN'])
1583                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1584                                        else
1585                                            $content.= '<b>'.$attendee['value'].'</b> ';
1586
1587                                        if($ical['description']['value'])
1588                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1589                                        else
1590                                            $content.= $this->functions->getLang('provisionally decline you event');
1591                                    }
1592                                    else
1593                                        $notExist = true;
1594                                }
1595                          }
1596                          if($notExist)
1597                            $content.= '<b><span style="color:red">'.$this->functions->getLang('This event does not exist on its agenda').'.</span></b>';
1598                          $content.= '</span><br /><br />';
1599
1600                        break;
1601
1602                      case 'CANCEL':
1603
1604                          $ical = $icalService->getComponent('vevent');
1605                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
1606                          $content.= '<span style="font-size: 12" >';
1607                          $content.= '<b><span style="color:red">'.$this->functions->getLang('Your event has been canceled').'</span></b>';
1608   
1609                          if($ical['description']['value'])
1610                              $content.= ' <br /> <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1611
1612                          $content.= '<br /><b>* '.$this->functions->getLang('To remove the event from your calendar to import the iCal file attached').'.</b>';
1613                          $content.= '</span><br /><br />';
1614                        break;
1615
1616                    case 'REQUEST':
1617
1618                        $ical = $icalService->getComponent('vevent');
1619                        if($ical['dtstart']['value']['tz'] == 'Z')
1620                        {
1621                            $tz = $_SESSION['phpgw_info']['user']['preferences']['common']['tz_offset'];
1622                            $ical['dtstart']['value']['hour'] += $tz;
1623                            $ical['dtend']['value']['hour'] += $tz;
1624                        }
1625                       
1626                        $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br />'.
1627                                   ' <br /> <b>'.$this->functions->getLang('Title').': </b>'.$ical['summary']['value'].
1628                                   ' <br /> <b>'.$this->functions->getLang('Location').': </b>'.$ical['location']['value'].
1629                                   ' <br /> <b>'.$this->functions->getLang('Details').': </b>'. str_replace('\n','<br />',nl2br($ical['description']['value']));
1630                        $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'] ;
1631                        $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'] ;
1632
1633                        if($ical['organizer']['params']['CN'])
1634                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b>'.$ical['organizer']['params']['CN'].' -  <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a></li>' ;
1635                        else
1636                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b> <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a>' ;
1637
1638                        if($ical['attendee'])
1639                        {
1640                            $att = ' <br /> <b>'.$this->functions->getLang('Participants').': </b>';
1641                            $att .= '<ul> ';
1642                            foreach ($ical['attendee'] as $attendee)
1643                            {
1644                                if($attendee['params']['CN'])
1645                                    $att .= '<li>'.$attendee['params']['CN'].' -  <a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
1646                                else
1647                                    $att .= '<li><a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
1648                            }
1649                            $att .= '</ul> <br />'  ;
1650                        }
1651                        $content.= $att;
1652
1653                        break;
1654                    default:
1655                        break;
1656                }
1657     
1658            }
1659            return $content;
1660        }
1661       
[2]1662        function htmlfilter($body)
1663        {
1664                require_once('htmlfilter.inc');
[1472]1665
[2]1666                $tag_list = Array(
1667                                false,
1668                                'blink',
1669                                'object',
1670                                'meta',
1671                                'html',
1672                                'link',
1673                                'frame',
1674                                'iframe',
1675                                'layer',
1676                                'ilayer',
1677                                'plaintext'
1678                );
1679
1680                /**
1681                * A very exclusive set:
1682                */
1683                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
1684                $rm_tags_with_content = Array(
1685                                'script',
1686                                'style',
1687                                'applet',
1688                                'embed',
1689                                'head',
1690                                'frameset',
1691                                'xml',
1692                                'xmp'
1693                );
1694
1695                $self_closing_tags =  Array(
1696                                'img',
1697                                'br',
1698                                'hr',
1699                                'input'
1700                );
1701
1702                $force_tag_closing = true;
1703
1704                $rm_attnames = Array(
1705                        '/.*/' =>
1706                                Array(
1707                                        '/target/i',
1708                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
1709                                        '/^dynsrc/i',
1710                                        '/^datasrc/i',
1711                                        '/^data.*/i',
1712                                        '/^lowsrc/i'
1713                                )
1714                );
1715
1716                /**
1717                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
1718                 * some idea of what's going on here. :)
1719                 */
1720
1721                $bad_attvals = Array(
1722                '/.*/' =>
1723                Array(
1724                      '/.*/' =>
1725                              Array(
1726                                Array(
1727                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1728                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1729                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1730                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1731                                      ),
1732                            Array(
1733                                              '\\1oddjob:\\2\\1',
1734                                          //'\\1uucp:\\2\\1', -> doclinks notes
1735                                      '\\1amaretto:\\2\\1',
1736                                          '\\1round:\\2\\1'
1737                                        )
[1472]1738                                    ),
1739
[2]1740                          '/^style/i' =>
1741                              Array(
1742                                        Array(
1743                                          '/expression/i',
1744                                              '/behaviou*r/i',
1745                                          '/binding/i',
1746                                              '/include-source/i',
1747                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1748                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1749                                         ),
1750                                        Array(
1751                                          'idiocy',
1752                                              'idiocy',
1753                                          'idiocy',
1754                                              'idiocy',
1755                                          'url(\\1http://securityfocus.com/\\1)',
1756                                          'url(\\1http://securityfocus.com/\\1)'
1757                                         )
1758                                )
1759                          )
1760                    );
1761
1762                $add_attr_to_tag = Array(
1763                                '/^a$/i' => Array('target' => '"_new"')
1764                );
[1472]1765
1766
[2]1767                $trusted_body = sanitize($body,
1768                                $tag_list,
1769                                $rm_tags_with_content,
1770                                $self_closing_tags,
1771                                $force_tag_closing,
1772                                $rm_attnames,
1773                                $bad_attvals,
1774                                $add_attr_to_tag
1775                );
[1472]1776
[2]1777            return $trusted_body;
1778        }
[1472]1779
[2]1780        function decodeBody($body, $encoding, $charset=null)
1781        {
[4416]1782
[2]1783                if ($encoding == 'quoted-printable')
[828]1784                {
[2]1785                        $body = quoted_printable_decode($body);
[1792]1786
[4795]1787                        }
1788        else if ($encoding == 'base64')
1789        {
1790                $body = base64_decode($body);
1791        }
1792                // All other encodings are returned raw.
1793                if (strtolower($charset) == "utf-8")
1794                        return utf8_decode($body);
1795        else
1796                        return $body;
1797        }
1798
[4436]1799                               
1800        /**
1801        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1802        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1803        * @param     $images
1804        * @param     $msgno
1805        * @param     $body
1806        * @param     $msg_folder
1807        */                     
[4416]1808        function process_embedded_images($images, $msgno, $body, $msg_folder)
[2]1809        {
[1472]1810
[4416]1811            foreach ($images as $image)
[4795]1812                {
[4416]1813                $image['cid'] = eregi_replace("<", "", $image['cid']);
1814                $image['cid'] = eregi_replace(">", "", $image['cid']);
[5134]1815                               
1816                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\" ", $body);
1817                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
1818                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
[4795]1819                        }
1820                return $body;
[2]1821        }
[1472]1822
[2]1823        function replace_special_characters($body)
1824        {
1825                // Suspected TAGS!
[4416]1826                // $tag_list = Array('blink','object','meta','html','link','frame','iframe','layer','ilayer','plaintext','script','style','img','applet','embed','head','frameset','xml','xmp');
[4795]1827
[4416]1828                // remove MS Office's proprietary tag
1829                //$body = mb_ereg_replace('<!\-\-\[if [^!]* mso .*\]>.*<!\[endif\]\-\->', '', $body);
1830               
[4795]1831                // Layout problem: Change html elements
1832                // with absolute position to relate position, CASE INSENSITIVE.
1833                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
[2]1834
[5134]1835                //Remove Comentario Expresso
1836                                $findExpCom[] = '<!-- TAG <';
1837                                $findExpCom[] = '> Removed by ExpressoMail -->';
1838                                $body = str_replace($findExpCom, '', $body);
1839                ///--------------------------------//
1840
[4416]1841                // tags to be removed doe to security reasons
1842                $tag_list = Array(
[5134]1843                        'blink','object','frame','iframe',
[4416]1844                        'layer','ilayer','plaintext','script',
1845                        'applet','embed','frameset','xml','xmp'
1846                );
[4795]1847
[4416]1848                foreach($tag_list as $index => $tag) {
[5134]1849                        $body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body);
[4795]1850                        }
[4416]1851               
[5134]1852                $body = @mb_eregi_replace("<meta[^>]*>", '', $body);
1853                $body = @mb_eregi_replace("<base[^>]*>", '', $body);
1854               
[4416]1855                //try to wrap CSS code instead of remove STYLE tags
1856                require_once('../library/csstidy/class.csstidy.php');
1857                $css = new csstidy();
1858                $css->set_cfg('preserve_css', false);
[6]1859
[4416]1860                $regs_found = array();
1861                $tags_found = @mb_eregi("<style\b[^>]*>(.*?)</style>", $body, $regs_found);
[5134]1862                $wrapper_class = 'ExpressoCssWrapper'.time();
[4416]1863               
1864                foreach ($regs_found as $block_found) {
1865                        $n_start      = strpos($block_found, '>')+1;
1866                        $n_length     = strrpos($block_found, '<')-$n_start;
1867                        $bf_innerHTML = substr($block_found, $n_start, $n_length);
1868                       
1869                        $bf_innerHTML = mb_ereg_replace('<!--', '', $bf_innerHTML);
1870                        $bf_innerHTML = mb_ereg_replace('-->', '', $bf_innerHTML);
[2]1871
[4416]1872                        $css->parse($bf_innerHTML);
1873                       
1874                        $prefix = ".$wrapper_class ";
[5134]1875            if( isset($css->css[41]) && count($css->css[41] > 0))
[4416]1876                        foreach ($css->css[41] as $key => $value) {
[4457]1877                                                //explode multiple selectors per block
1878                                                $selectors = explode(',', $key);
1879                                                         
1880                                    foreach ($selectors as $selector) {
1881                                        if (ereg('\*', $key)) {
1882                                                                //skip selecto '*'
1883                                            continue;
[4795]1884                }
[4457]1885                                                                 
1886                                                        $selector = eregi_replace('[^#\.]*body.*', '', $selector);
1887                                                        $css->css[41][$prefix.trim($selector)] = $value;
1888                                    }
[4416]1889                        unset($css->css[41][$key]);
[2]1890                        }
[4416]1891                       
1892                        $body = str_replace($block_found, '<style>'.$css->print->plain().'</style>', $body);
[2]1893                }
[4416]1894
1895
[650]1896                // Malicious Code Remove
[1923]1897                $dirtyCodePattern = "/(<([\w]+[\w0-9]*)(.*)on(mouse(move|over|down|up)|load|blur|change|error|click|dblclick|focus|key(down|up|press)|select)([\n\ ]*)=([\n\ ]*)[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/misU";
[650]1898                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
[4416]1899                foreach($rest[0] as $i => $val) {
[1270]1900                        if (!(preg_match("/javascript:window\.open\(\"([^'\"]*)\/index\.php\?menuaction=calendar\.uicalendar\.set_action\&cal_id=([^;'\"]+);?['\"]/i",$rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
[3250]1901                                $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
[4416]1902                }
[4795]1903
[4777]1904                /*
1905                * Remove deslocamento a esquerda colocado pelo Outlook.
1906                * Este delocamento faz com que algumas palavras fiquem escondidas atras da barra lateral do expresso.
1907                */
1908                $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
1909            $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
1910            $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
1911            //--------------------------------------------------------------------------------------------//   
[4795]1912
[4989]1913                //Remoção de tags <span></span> para correção de erro no firefox
[5134]1914                //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>.
1915                //Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo.
1916                //              $body = mb_eregi_replace("<span><span>","",$body);
1917                //              $body = mb_eregi_replace("</span></span>","",$body);
[4996]1918
[5134]1919                //Correção para compatibilização com Outlook, ao visualizar a mensagem
[4795]1920                $body = mb_ereg_replace('<!--\[','<!-- [',$body);
[3294]1921                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
[4795]1922               
[4416]1923                return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>';
[5134]1924
[4795]1925        }
[5079]1926       
[4784]1927        function replace_links_callback($matches) 
[4800]1928        {
[4784]1929                if($matches[3])
1930                        $pref = $matches[3];
1931            else
1932                        $pref = $matches[3] = 'http';
[4795]1933
[4784]1934            return '<a href="'.$pref.'://'.$matches[4].$matches[5].'" target="_blank">'.$matches[4].$matches[5].'</a>';
1935        }
[4795]1936
1937
[4436]1938        /**
1939        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1940        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1941        * @param     $body corpo da mensagem
1942        */
1943        function replace_links(&$body)
[4795]1944                {
[4784]1945                // Trata urls do tipo aaaa.bbb.empresa 
1946                // Usadas na intranet. 
1947                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])(((http|https|ftp|ftps)?:\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';     
1948                $replacement = '<a href="://$4$5" target="_blank">$4$5</a>';
1949            $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body);
[1897]1950
[4795]1951        }
1952
[91]1953        function get_signature($msg, $msg_number, $msg_folder)
[1035]1954        {
[3352]1955            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1956            include_once("class.db_functions.inc.php");
1957            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1958            {
1959                $sign = array();
1960                $temp = $this->get_info_head_msg($msg_number);
1961                if($temp['ContentType'] =='normal') return $sign;
1962                $file_type = strtolower($file_type);
1963                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]1964                {
[3394]1965                    if ($temp['ContentType'] == 'signature')
[3352]1966                    {
[3394]1967                        if(!$this->mbox || !is_resource($this->mbox))
1968                        $this->mbox = $this->open_mbox($msg_folder);
[1035]1969
[3352]1970                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[1035]1971
[3352]1972                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1973                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
[1035]1974
[3352]1975                        $certificado = new certificadoB();
1976                        $validade = $certificado->verificar($imap_msg);
[3394]1977                                        $sign[] = $certificado->msg_sem_assinatura;
[3352]1978                        if ($certificado->apresentado)
1979                        {
1980                            $from = $header->from;
1981                            foreach ($from as $id => $object)
1982                            {
1983                                $fromname = $object->personal;
1984                                $fromaddress = $object->mailbox . "@" . $object->host;
1985                            }
1986                            foreach ($certificado->erros_ssl as $item)
1987                            {
1988                                $sign[] = $item . "#@#";
1989                            }
[1035]1990
[3352]1991                            if (count($certificado->erros_ssl) < 1)
1992                            {
1993                                $check_msg = 'Message untouched';
1994                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1995                                {
1996                                    $check_msg .= ' and authentic###';
1997                                }
1998                                else
1999                                {
2000                                    $check_msg .= ' with signer different from sender#@#';
2001                                }
2002                                $sign[] = $check_msg;
2003                            }
2004                                               
2005                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
2006                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
2007                            $sign[] = 'Mail from: ###' . $fromaddress;
2008                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
2009                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
2010                            $sign[] = 'Message date: ###' . $header->Date;
[1035]2011
[3352]2012                            $cert = openssl_x509_parse($certificado->cert_assinante);
[1035]2013
[3352]2014                            $sign_alert = array();
2015                            $sign_alert[] = 'Certificate Owner###:\n';
2016                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
2017                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
2018                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
2019                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
2020                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
2021                            $sign_alert[] = 'Personal Data###:' . '\n';
2022                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
2023                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
2024                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
2025                            $sign_alert[]= 'Certificate Issuer###:\n';
2026                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
2027                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
2028                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
2029                            $sign_alert[]= 'Validity###:\n';
2030                            $H = data_hora($cert[validFrom]);
2031                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2032                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
2033                            $H = data_hora($cert[validTo]);
2034                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2035                            $sign_alert[]= 'Valid Until### ' . $X;
2036                            $sign[] = $sign_alert;
2037
2038                            $this->db = new db_functions();
2039                           
2040                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
2041                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
2042                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
[91]2043                        }
[3352]2044                        else
2045                        {
2046                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
2047                            foreach($certificado->erros_ssl as $item)
2048                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
2049                        }
2050                    }
[91]2051                }
[3352]2052            }
2053            return $sign;
[91]2054        }
2055
[4436]2056       
2057        /**
2058        * @license   http://www.gnu.org/copyleft/gpl.html GPL
2059        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2060        * @param     $images
2061        * @param     $msg_number
2062        * @param     $msg_folder
2063        */
[4416]2064        function get_thumbs($images, $msg_number, $msg_folder)
[2]2065        {
[4416]2066
[5134]2067                if (!count($images)) return '';
[4416]2068               
[5134]2069                foreach ($images as $key => $value) {
2070                        $images[$key]['width']  = 160;
2071                        $images[$key]['height'] = 120;
2072                        $images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$image['pid']."&image=true";
[4795]2073                }
[5134]2074
2075                return json_encode($images);
[2]2076        }
[1472]2077
[2]2078        /*function delete_msg($params)
2079        {
2080                $folder = $params['folder'];
2081                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[1472]2082
[2]2083                $mbox_stream = $this->open_mbox($folder);
[1472]2084
[2]2085                foreach ($msgs_to_delete as $msg_number){
2086                        imap_delete($mbox_stream, $msg_number, FT_UID);
2087                }
2088                imap_close($mbox_stream, CL_EXPUNGE);
2089                return $params['msgs_to_delete'];
2090        }*/
2091
2092        // Novo
2093        function delete_msgs($params)
2094        {
[4795]2095
[2]2096                $folder = $params['folder'];
[51]2097                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]2098                $msgs_number = explode(",",$params['msgs_number']);
[5134]2099                if(array_key_exists('border_ID' ,$params))
[2]2100                $border_ID = $params['border_ID'];
[5134]2101                else
2102                        $border_ID = '';
[2]2103                $return = array();
[4795]2104
[5134]2105                if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){
[2]2106                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]2107                        // Fix problem in unserialize function JS.
2108                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2109                }
[2]2110
[4795]2111                //$mbox_stream = $this->open_mbox($folder);
[504]2112                $mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
[4795]2113
[2]2114                foreach ($msgs_number as $msg_number)
2115                {
2116                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
2117                                $return['msgs_number'][] = $msg_number;
2118                }
[4795]2119
[2]2120                $return['folder'] = $folder;
2121                $return['border_ID'] = $border_ID;
[4795]2122
[51]2123                if($mbox_stream)
2124                        imap_close($mbox_stream, CL_EXPUNGE);
[5172]2125                       
2126                $return['status'] = true;
[2]2127                return $return;
2128        }
2129
[1472]2130
[2]2131        function refresh($params)
2132        {
[3265]2133
[5134]2134                $return = array();
2135                $return['new_msgs'] = 0;
[2]2136                $folder = $params['folder'];
2137                $msg_range_begin = $params['msg_range_begin'];
2138                $msg_range_end = $params['msg_range_end'];
2139                $msgs_existent = $params['msgs_existent'];
[1472]2140                $sort_box_type = $params['sort_box_type'];
[2]2141                $sort_box_reverse = $params['sort_box_reverse'];
2142                $msgs_in_the_server = array();
[53]2143                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]2144                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2145                $msgs_in_the_server = array_keys($msgs_in_the_server);
[1472]2146
[828]2147                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
[5134]2148
[5158]2149                $dif = ($params['msg_range_end'] - $params['msg_range_begin']) +1;
2150                if(!count($msgs_in_the_server)){
2151                        $msg_range_begin -= $dif;
2152                        $msg_range_end -= $dif;
2153                        $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2154                        $msgs_in_the_server = array_keys($msgs_in_the_server); 
2155                        $num_msgs = NULL;
2156                        $return['msg_range_begin'] = $msg_range_begin;
2157                        $return['msg_range_end'] = $msg_range_end;
2158                }               
2159                $return['new_msgs'] = imap_num_recent($this->mbox);
2160               
[1472]2161                $msgs_in_the_client = explode(",", $msgs_existent);
[51]2162
[2]2163                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[5134]2164
2165                if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){
2166                        $aux = 0;
2167                        while(array_key_exists($aux, $msg_to_insert)){
2168                                if($msg_to_insert[$aux] > $msgs_in_the_client[0]){
2169                                        $return['new_msgs'] += 1;
2170                                }
2171                                $aux++;
2172                        }
2173                }else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){
2174                        $aux = 0;
2175                        while(array_key_exists($aux, $msg_to_insert)){
2176                                if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){
2177                                        $return['new_msgs'] += 1;
2178                                }
2179                                $aux++;
2180                        }
[5158]2181                }else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0 && $msg_range_end == $dif){
[5134]2182                        $return['tot_msgs'] = $num_msgs;
2183                }
2184               
[5158]2185                if(!count($msgs_in_the_server)){
2186                        return Array();
2187                }       
2188
[271]2189                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[2]2190                $msgs_to_exec = array();
[3265]2191                foreach($msg_to_insert as $msg_number)
2192                        $msgs_to_exec[] = $msg_number;
[4764]2193                //sort($msgs_to_exec);
[2]2194                $i = 0;
[3265]2195                foreach($msgs_to_exec as $msg_number)
[2]2196                {
[614]2197                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
[1472]2198                        * atributos do cabeçalho. Como eu preciso do atributo Importance
[614]2199                        * para saber se o email é importante ou não, uso abaixo a função
2200                        * imap_fetchheader e busco o atributo importance nela para passar
2201                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
2202                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
2203                        * não preciso reimplementar o método utilizando o fetchheader.
2204                        */
[3955]2205   
2206                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
[1035]2207                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[689]2208                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
[1472]2209
[1752]2210                        $msg_sample = $this->get_msg_sample($msg_number);
2211                        $return[$i]['msg_sample'] = $msg_sample;
2212
[535]2213                        $header = $this->get_header($msg_number);
[2]2214                        if (!is_object($header))
[828]2215                                continue;
2216
[2]2217                        $return[$i]['msg_number']       = $msg_number;
[3955]2218                       
2219                        //get the next msg number to append this msg in the view in a correct place
2220                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
2221                       
[4764]2222                        $return[$i]['msg_key_position'] = $msg_key_position;
2223                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1,$msgs_in_the_server) !== false)
[3955]2224                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
[4764]2225                        else
2226                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position];
[1472]2227
[2]2228                        $return[$i]['msg_folder']       = $folder;
[3955]2229                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
[3265]2230                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
[2]2231                        $return[$i]['Recent']           = $header->Recent;
2232                        $return[$i]['Unseen']           = $header->Unseen;
2233                        $return[$i]['Answered']         = $header->Answered;
2234                        $return[$i]['Deleted']          = $header->Deleted;
2235                        $return[$i]['Draft']            = $header->Draft;
2236                        $return[$i]['Flagged']          = $header->Flagged;
2237
[3106]2238                        $return[$i]['udate'] = $header->udate;
2239               
[2]2240                        $from = $header->from;
2241                        $return[$i]['from'] = array();
2242                        $tmp = imap_mime_header_decode($from[0]->personal);
2243                        $return[$i]['from']['name'] = $tmp[0]->text;
2244                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]2245                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[5134]2246                        if(!$return[$i]['from']['name'] || trim($return[$i]['from']['name']) === '')
[2]2247                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[1472]2248
[2]2249                        /*$toaddress = imap_mime_header_decode($header->toaddress);
2250                        $return[$i]['toaddress'] = '';
2251                        foreach ($toaddress as $tmp)
2252                                $return[$i]['toaddress'] .= $tmp->text;*/
2253                        $to = $header->to;
2254                        $return[$i]['to'] = array();
[5134]2255                        if(isset($to[0]->personal))
[2]2256                        $tmp = imap_mime_header_decode($to[0]->personal);
[5134]2257                        if(trim($return[$i]['to']['name']) === '')
2258                                $return[$i]['to']['name'] = $to[0]->mailbox . "@" . $to[0]->host;
2259                        else
[2]2260                        $return[$i]['to']['name'] = $tmp[0]->text;
2261                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2262                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[5134]2263                        if(isset($header->cc))
[3777]2264                        $cc = $header->cc;
[5134]2265
2266                        if ( isset($cc) && (!$return[$i]['to']['name'] || $return[$i]['to']['name'] == '@') ){
[3777]2267                                $return[$i]['to']['name'] =  $cc[0]->personal;
2268                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
2269                        }
[5134]2270                        $return[$i]['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
2271                        if($return[$i]['subject'] == "" || $return[$i]['subject'] == '' || $return[$i]['subject'] == null ){
2272                                $return[$i]['subject'] = $this->functions->getLang("(no subject)   ");
2273                        }
[2]2274                        $return[$i]['Size'] = $header->Size;
2275                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]2276
[5134]2277                        if($return[$i]['to']['email'] == '@' || $return[$i]['to']['email'] =='undisclosed-recipients@' || $return[$i]['to']['name'] =='undisclosed-recipients@'
2278                                || $return[$i]['to']['name'] == null){
2279                                $return[$i]['to']['email'] = $return[$i]['from']['email'];
2280                                $return[$i]['to']['name'] = $return[$i]['from']['name'];
2281                                $return[$i]['to']['full'] = $return[$i]['reply_toaddress'];
2282                        }
2283                       
[2]2284                        $return[$i]['attachment'] = array();
[3265]2285                        if (!isset($imap_attachment))
2286                        {
2287                                include_once("class.imap_attachment.inc.php");
2288                                $imap_attachment = new imap_attachment();
2289                        }
[51]2290                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]2291                        $i++;
2292                }
[3265]2293                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
2294                $return['sort_box_type'] = $params['sort_box_type'];
[3427]2295                if(!$this->mbox || !is_resource($this->mbox))
2296                {
2297                    $this->open_mbox($folder);
2298                }
[4819]2299
[271]2300                $return['msgs_to_delete'] = $msg_to_delete;
[3493]2301                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
[411]2302                if($this->mbox && is_resource($this->mbox))
[51]2303                        imap_close($this->mbox);
[828]2304
[2]2305                return $return;
2306        }
2307
[1035]2308     /**
2309     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
2310     * assinado ou cifrado.
2311     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
2312     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
2313     * @param $msg_number O número da mesagem
2314     * @return Retorna o tipo da mensagem (normal, signature, cipher).
2315     */
2316    function getMessageType($msg_number, $headers = false){
[3394]2317            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2318            $contentType = "normal";
2319            if (!$headers){
2320                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
2321            }
[3394]2322           
2323            if (preg_match("/pkcs7-signature/i", $headers) == 1){
[1035]2324                $contentType = "signature";
[3394]2325            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
2326                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
[1035]2327            }
2328
2329            return $contentType;
2330    }
2331
[1375]2332         /**
2333     * Metodo que retorna todas as pastas do usuario logado.
2334     * @param $params array opcional para repassar os argumentos ao metodo.
2335     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
2336     * excluindo as compartilhadas para ele.
[3553]2337     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
2338     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
2339     * Se usar $params['folderType'] = null irá retornar todas as pastas
[1472]2340     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
[1375]2341     * folder_id, folder_name, folder_parent e folder_hasChildren.
[1472]2342     */
[449]2343        function get_folders_list($params = null)
[2]2344        {
[1472]2345                $mbox_stream = $this->open_mbox();
[5134]2346                if($params &&  array_key_exists('onload', $params)   &&  $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
[4726]2347                        $this->delete_mailbox(array("del_past" => "INBOX".$this->imap_delimiter."decifradas"));
[1953]2348                }
[650]2349
[1824]2350                $inbox = 'INBOX';
[3018]2351                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
[5134]2352                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
[3018]2353                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
[5134]2354                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[5175]2355
[5134]2356                if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'] ))
[3018]2357                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
[5134]2358                else
2359                        $uid2cn = false;
[3018]2360                // Free others requests
2361                session_write_close();
[1816]2362
[3018]2363                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[3790]2364               
[5134]2365                if ( $params && isset($params['noSharedFolders']) )
[3790]2366                        $folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
2367                else
2368                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, '*' );
[3761]2369
[3018]2370                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
2371
2372                $tmp = array();
2373                $resultMine = array();
[5134]2374                $resultSharedMine = array();
[3018]2375                $resultDefault = array();
[5134]2376                $resultSharedDefault = array();
2377                $aux = "";
2378                $qtd = -1 ;
[3018]2379
[2]2380                if (is_array($folders_list)) {
[3761]2381                        reset($folders_list);
2382                        $this->ldap = new ldap_functions();
[1472]2383
[2]2384                        $i = 0;
[3761]2385                        while (list($key, $val) = each($folders_list)) {
2386                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
[1035]2387
[3761]2388                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
[4824]2389                                $tmp_folder_id = explode("}", $val->name );
[3761]2390
[4824]2391                                $folderUser = trim( strpos( $tmp_folder_id[1], $this->imap_delimiter , 5 ) );
2392
[5175]2393                                $folderUser = trim( substr( $tmp_folder_id[1], 0, $folderUser ) );
[4824]2394
[5175]2395                                $Permission = true;
[4824]2396
[5175]2397                                if( $folderUser != "INBOX" && $folderUser != "" )
2398                                {
2399                                        $Permission = @imap_getacl( $mbox_stream, $folderUser );
2400                                }
2401                                $tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" );
[4824]2402
[5175]2403                                if( $tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas')
2404                                {
[3761]2405                                        continue;
2406                                }
[5134]2407                               
2408                                if(isset($status->unseen))
[5175]2409                                        $result[$i]['folder_unseen'] = $status->unseen;
[5134]2410                               
[3761]2411                                $folder_id = $tmp_folder_id[1];
[2]2412                                $result[$i]['folder_id'] = $folder_id;
[1472]2413
[2]2414                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
2415                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
[96]2416                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
[3761]2417                       
[3018]2418                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
[1340]2419                                        //$this->ldap = new ldap_functions();
[1816]2420                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
[325]2421                                                $result[$i]['folder_name'] = $cn;
2422                                        }
2423                                }
[1472]2424
[2]2425                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
2426                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[1472]2427
[96]2428                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
[2]2429                                        $result[$i]['folder_hasChildren'] = 1;
2430                                else
2431                                        $result[$i]['folder_hasChildren'] = 0;
[5134]2432                                $user = explode($this->imap_delimiter , $tmp_folder_id[1]);
[1816]2433                                switch ($tmp_folder_id[1]) {
[1824]2434                                        case $inbox:
[5134]2435                                        case $drafts:
[1824]2436                                        case $sent:
2437                                        case $spam:
2438                                        case $trash:
[3761]2439                                                $resultDefault[]=$result[$i];
2440                                                break;
[5134]2441                                        case "user". $this->imap_delimiter . $user[1]:
2442                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:
2443                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:
2444                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:
2445                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
2446                                                if($aux != $user[1]){
2447                                                        $aux = $user[1];
2448                                                        $qtd += 1;
2449                                                }
2450                                                if( isset($resultSharedDefault[$qtd]) && !is_array($resultSharedDefault[$qtd]))
2451                                                        $resultSharedDefault[$qtd] = array();
2452                                                $resultSharedDefault[$qtd][]=$result[$i];
2453                                                break; 
[1816]2454                                        default:
[5134]2455                                                if($user[0] == $inbox)
[5175]2456                                                        $resultMine[]=$result[$i];
[5134]2457                                                else{
2458                                                        if($aux != $user[1]){
2459                                                                $aux = $user[1];
2460                                                                $qtd += 1;
2461                                                        }
2462                                                        if(!is_array($resultSharedDefault[$qtd]))
2463                                                                $resultSharedMine[$qtd] = array();
2464                                                        $resultSharedMine[$qtd][]=$result[$i];
[5175]2465                                                }
2466
[1816]2467                                }
[4824]2468                            $i++;
[5175]2469                        }
[2]2470                }
[1472]2471
[5134]2472                if ( $params && !array_key_exists('noQuotaInfo',$params) ) {
[3564]2473                        //Get quota info of current folder
2474                        $current_folder = "INBOX";
[5134]2475                        if($params && isset($params['folder']))
[3564]2476                                $current_folder = $params['folder'];
[3790]2477
[3564]2478                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
2479                } else {
2480                        $arr_quota_info = array();
2481                }
[3790]2482
[1816]2483                // Sorting resultMine
2484                foreach ($resultMine as $folder_info)
[2]2485                {
2486                        $array_tmp[] = $folder_info['folder_id'];
2487                }
[1472]2488
[2]2489                natcasesort($array_tmp);
[3575]2490               
[3790]2491                $result2 = array();
[1472]2492
[2]2493                foreach ($array_tmp as $key => $folder_id)
2494                {
[1816]2495                        $result2[] = $resultMine[$key];
[2]2496                }
[1816]2497               
2498                // Sorting resultDefault
[5175]2499                $resultDefault2 = array();
2500               
[1816]2501                foreach ($resultDefault as $key => $folder_id)
2502                {
[5175]2503
[1816]2504                        switch ($resultDefault[$key]['folder_id']) {
[1824]2505                                case $inbox:
[1816]2506                                        $resultDefault2[0] = $resultDefault[$key];
2507                                        break;
[5134]2508                                case $drafts:
[1816]2509                                        $resultDefault2[1] = $resultDefault[$key];
2510                                        break;
[5134]2511                                case $sent:
[1816]2512                                        $resultDefault2[2] = $resultDefault[$key];
2513                                        break;
[1824]2514                                case $spam:
[1816]2515                                        $resultDefault2[3] = $resultDefault[$key];
2516                                        break;
[1824]2517                                case $trash:
[1816]2518                                        $resultDefault2[4] = $resultDefault[$key];
2519                                        break;
2520                        }
2521                }
[5175]2522                //RE-ORDENA INDICES
2523                ksort($resultDefault2);
[5134]2524                $shareds = array();
2525                if(!empty($resultSharedDefault))
2526                for($i = 0; $i <= $qtd; $i++){                 
2527                        foreach ($resultSharedDefault[$i] as $key => $folder_id)
2528                        {
2529                                $user = explode($this->imap_delimiter , $resultSharedDefault[$i][$key]['folder_id']);
2530
2531                                switch ($resultSharedDefault[$i][$key]['folder_id']) {
2532                                        case "user". $this->imap_delimiter . $user[1]:
2533                                                $resultSharedDefault2[0] = $resultSharedDefault[$i][$key];
2534                                                break;
2535                                        case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']: 
2536                                                $resultSharedDefault2[1] = $resultSharedDefault[$i][$key];
2537                                                break; 
2538                                        case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']: 
2539                                                $resultSharedDefault2[2] = $resultSharedDefault[$i][$key];
2540                                                break;
2541                                        case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']: 
2542                                                $resultSharedDefault2[3] = $resultSharedDefault[$i][$key];
2543                                                break;
2544                                        case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
2545                                                $resultSharedDefault2[4] = $resultSharedDefault[$i][$key];
2546                                                break;
2547                                }
2548                        }
2549                        if($resultDefault2 != null)
2550                                $shareds = array_merge($shareds, $resultSharedDefault2);
2551                        if(isset($resultSharedMine[$i]) && $resultSharedMine[$i] != null)
2552                                $shareds = array_merge($shareds, $resultSharedMine[$i]);
2553                        $resultSharedDefault2 = array();
2554                }
2555                if ( $params && isset($params['folderType']) && $params['folderType'] == 'default' )
[3790]2556                        return array_merge($resultDefault2, $arr_quota_info);
[1816]2557
[5134]2558                if ( $params && array_key_exists('folderType', $params) && $params['folderType'] == 'personal' )
[3790]2559                        return array_merge($result2, $arr_quota_info);
2560
[3553]2561                // Merge default folders and personal
[3790]2562                $result2 = array_merge($resultDefault2, $result2);
[5134]2563                if(!empty($shareds))
2564                        $result2 = array_merge($result2, $shareds);
[3553]2565                return array_merge($result2, $arr_quota_info);
[2]2566        }
[1472]2567
[2]2568        function create_mailbox($arr)
2569        {
2570                $namebox        = $arr['newp'];
2571                $mbox_stream = $this->open_mbox();
2572                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]2573                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[1472]2574
[2]2575                $result = "Ok";
[51]2576                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]2577                {
2578                        $result = implode("<br />\n", imap_errors());
[1472]2579                }
2580
[51]2581                if($mbox_stream)
2582                        imap_close($mbox_stream);
[1472]2583
[2]2584                return $result;
[1472]2585
[2]2586        }
[1472]2587
[2]2588        function create_extra_mailbox($arr)
2589        {
2590                $nameboxs = explode(";",$arr['nw_folders']);
2591                $result = "";
2592                $mbox_stream = $this->open_mbox();
2593                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1472]2594                foreach($nameboxs as $key=>$tmp){
[2]2595                        if($tmp != ""){
2596                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
2597                                        $result = implode("<br />\n", imap_errors());
[51]2598                                        if($mbox_stream)
[1472]2599                                                imap_close($mbox_stream);
[2]2600                                        return $result;
2601                                }
2602                        }
2603                }
[51]2604                if($mbox_stream)
2605                        imap_close($mbox_stream);
[2]2606                return true;
2607        }
[1472]2608
[2]2609        function delete_mailbox($arr)
2610        {
2611                $namebox = $arr['del_past'];
2612                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1953]2613                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
[2]2614                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[1472]2615
[2]2616                $result = "Ok";
2617                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2618                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2619                {
2620                        $result = implode("<br />\n", imap_errors());
2621                }
[1953]2622                /*
[51]2623                if($mbox_stream)
2624                        imap_close($mbox_stream);
[1953]2625                */
[2]2626                return $result;
2627        }
[1472]2628
[2]2629        function ren_mailbox($arr)
2630        {
2631                $namebox = $arr['current'];
2632                $new_box = $arr['rename'];
2633                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2634                $mbox_stream = $this->open_mbox();
2635                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[1472]2636
[2]2637                $result = "Ok";
2638                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]2639                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[1472]2640
[2]2641                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2642                {
[1472]2643                        $result = imap_errors();
[2]2644                }
[51]2645                if($mbox_stream)
2646                        imap_close($mbox_stream);
[2]2647                return $result;
[1472]2648
[2]2649        }
[1472]2650
[2]2651        function get_num_msgs($params)
2652        {
2653                $folder = $params['folder'];
[411]2654                if(!$this->mbox || !is_resource($this->mbox)) {
[2]2655                        $this->mbox = $this->open_mbox($folder);
[411]2656                        if(!$this->mbox || !is_resource($this->mbox))
[2]2657                        return imap_last_error();
[1472]2658                }
[2]2659                $num_msgs = imap_num_msg($this->mbox);
[432]2660                if($this->mbox && is_resource($this->mbox))
[51]2661                        imap_close($this->mbox);
[1472]2662
[2]2663                return $num_msgs;
2664        }
[1472]2665
[1912]2666        function folder_exists($folder){
2667                $mbox =  $this->open_mbox();
2668                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2669                $list = imap_getmailboxes($mbox,$serverString, $folder);
2670                $return = is_array($list);             
2671                imap_close($mbox);
2672                return $return;
2673        }
2674       
[2]2675        function send_mail($params)
2676        {
[5134]2677                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
2678                $mailService = ServiceLocator::getService('mail');
2679
[2]2680                include_once("class.db_functions.inc.php");
2681                $db = new db_functions();
2682                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[5134]2683                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
2684               
[449]2685                ##
2686                # @AUTHOR Rodrigo Souza dos Santos
[3369]2687                # @DATE 2008/09/17$fileName
[449]2688                # @BRIEF Checks if the user has permission to send an email with the email address used.
2689                ##
2690                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2691                {
2692                        $deny = true;
2693                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2694                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2695                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2696
2697                        if ( $deny )
2698                                return "The server denied your request to send a mail, you cannot use this mail address.";
2699                }
[828]2700
[2]2701                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
2702                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
2703                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
[5134]2704
2705                $toaddress  = preg_replace('/<\s+/', '<', $toaddress);                 
2706                $toaddress  = preg_replace('/\s+>/', '>', $toaddress);
2707                       
2708                $ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
2709                $ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
2710               
2711                $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
2712                $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
2713               
[3527]2714                $replytoaddress = $params['input_replyto'];
[2]2715                $subject = $params['input_subject'];
[271]2716                $msg_uid = $params['msg_id'];
[2]2717                $return_receipt = $params['input_return_receipt'];
[614]2718                $is_important = $params['input_important_message'];
[1035]2719        $encrypt = $params['input_return_cripto'];
2720                $signed = $params['input_return_digital'];
2721
[5134]2722                $message_attachments = $params['message_attachments'];
2723                 
2724                if(substr($params['input_to'],-1) == ',')
2725                    $params['input_to'] = substr($params['input_to'],0,-1);
2726
2727                if(substr($params['input_cc'],-1) == ',')
2728                    $params['input_cc'] = substr($params['input_cc'],0,-1);
2729
2730                if(substr($params['input_cco'],-1) == ',')
2731                    $params['input_cco'] = substr($params['input_cco'],0,-1);
2732               
2733
2734                // Valida numero Maximo de Destinatarios
2735                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0)
2736                {
2737                    $sendersNumber = count(explode(',',$params['input_to']));
2738
2739                    if($params['input_cc'])
2740                        $sendersNumber +=  count(explode(',',$params['input_cc']));
2741                    if($params['input_cco'])
2742                        $sendersNumber +=  count(explode(',',$params['input_cco']));
2743
2744                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username);
2745                    if($userMaxmimumSenders)
2746                    {
2747                        if($sendersNumber > $userMaxmimumSenders)
2748                            return $this->functions->getLang('Number of recipients greater than allowed');
2749                    }
2750                    else
2751                    {
2752                        $ldap = new ldap_functions();
2753                        $groupsToUser = $ldap->get_user_groups($this->username);
2754
2755                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser);
2756
2757                        if($groupMaxmimumSenders > 0)
2758                        {
2759                            if($sendersNumber > $groupMaxmimumSenders)
2760                                return $this->functions->getLang('Number of recipients greater than allowed');
2761                        }
2762                        else
2763                        {
2764                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'])
2765                             return $this->functions->getLang('Number of recipients greater than allowed');
2766                        }
2767                    }
2768
2769                }
2770                //Fim Valida numero maximo de destinatarios
2771               
2772               
2773                //Valida envio de email para shared accounts
2774                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
2775                {
2776                    $ldap = new ldap_functions();
2777                    $arrayF = explode(';', $params['input_from']);
2778
2779                    /*
2780                     * Verifica se o remetente n?o ? uma conta compartilhada
2781                     */
2782                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
2783                    {
2784                        $groupsToUser = $ldap->get_user_groups($this->username);
2785                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
2786
2787                        /*
2788                         * Pega o UID do remetente
2789                         */
2790                        $uidFrom = $ldap->mail2uid($arrayF[1]);
2791
2792                         /*
2793                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
2794                         */
2795                        foreach ($sharedAccounts as $key => $value)
2796                        {
2797                            if($value)
2798                                 $acl = $this->getaclfrombox($value);
2799
2800                             if (array_key_exists($uidFrom, $acl))
2801                                 unset($sharedAccounts[$key]);
2802
2803                        }
2804
2805                        /*
2806                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
2807                         */
2808                        if(count($sharedAccounts) > 0)
2809                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
2810
2811                        /*
2812                         * Retorna as contas compartilhadas bloqueadas
2813                         */
2814                        if(count($accountsBlockeds) > 0)
2815                        {
2816                            $return = '';
2817
2818                            foreach ($accountsBlockeds as $accountBlocked)
2819                                $return.= $accountBlocked.', ';
2820
2821                             $return = substr($return,0,-2);
2822
2823                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
2824                        }
2825                    }
2826                }
2827                // Fim Valida envio de email para shared accounts
2828               
2829               
2830//          TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
2831            if($params['smime'] AND false)
[1035]2832        {
2833            $body = $params['smime'];
2834            $mail->SMIME = true;
2835            // A MSG assinada deve ser testada neste ponto.
2836            // Testar o certificado e a integridade da msg....
[3271]2837            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2838            $erros_acumulados = '';
2839            $certificado = new certificadoB();
2840            $validade = $certificado->verificar($body);
2841            if(!$validade)
2842            {
2843                foreach($certificado->erros_ssl as $linha_erro)
2844                {
2845                    $erros_acumulados .= $linha_erro;
2846                }
2847            }
2848            else
2849            {
2850                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2851                if ($certificado->apresentado)
2852                {
2853                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
[4291]2854                    $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'])&&$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']!=''?$_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']]:$this->username;
2855                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
[1035]2856                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2857                }
2858                else
2859                {
2860                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2861                }
2862            }
2863            if(!$erros_acumulados =='')
2864            {
2865                return $erros_acumulados;
2866            }
2867        }
2868        else
2869        {
[3250]2870            //Compatibilização com Outlook, ao encaminhar a mensagem
[5134]2871                        $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
[1035]2872        }
[5134]2873
[3900]2874                $attachments = $_FILES;
[2]2875                $forwarding_attachments = $params['forwarding_attachments'];
[689]2876                $local_attachments = $params['local_attachments'];
[3369]2877
[1912]2878                //Test if must be saved in shared folder and change if necessary
2879                if( $fromaddress[2] == 'y' ){
2880                        //build shared folder path
2881                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
[5134]2882                        if($this->folder_exists($newfolder))
2883                                $folder = $newfolder;
2884                        else
2885                                $folder = $params['folder'];
2886                       
[1912]2887                } else  {
2888                        $folder = $params['folder'];                   
2889                }
2890               
[5134]2891                $folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
2892                $folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
[1472]2893                $folder_name = $params['folder_name'];
[1035]2894
[5134]2895//              TODO - tratar assinatura e remover o AND false
2896                if($signed && !$params['smime'] AND false)
[1035]2897                {
2898            $mail->Mailer = "smime";
2899                        $mail->SignedBody = true;
2900                }
[1472]2901
[5134]2902
2903                if($fromaddress)
2904                        $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
2905               else
2906                        $mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
2907                //$mailService->addTo($toaddress);
2908                //$mailService->addCc($ccaddress);
2909                $bol = $this->add_recipients('to', $toaddress, $mailService);
2910                if(!$bol){
2911                        return $this->parse_error("Invalid Mail:", $toaddress);
[2]2912                }
[5134]2913                $bol = $this->add_recipients('cc', $ccaddress, $mailService);
2914                if(!$bol){
2915                        return $this->parse_error("Invalid Mail:", $ccaddress);
2916                }
[4832]2917                $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy'];
2918                 
[5134]2919                if($allow)
[4832]2920                                {
[5134]2921                        //$mailService->addBcc($ccoaddress);
2922                        $bol = $this->add_recipients('cco', $ccoaddress, $mailService);
2923
2924                        if(!$bol){
2925                                return $this->parse_error("Invalid Mail:", $ccoaddress);
2926                        }
[4832]2927                                }
[271]2928
[5134]2929                $mailService->setSubject($subject);
2930                $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ?
2931                                                strtolower($params['type']) != 'plain' : true );
2932       
2933
2934//              TODO - tratar mensagem criptografada e remover o AND false abaixo
2935        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)      // a msg deve ser enviada cifrada...
[1035]2936                {
2937                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2938            $email = explode(",",$email);
2939            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2940            // Deve ser verificado um numero limite de destinatarios.
2941            // Deve ser verificado se os certificados sao validos.
2942            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2943            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2944            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2945            $erros_acumulados = "";
2946            $aux_mails = array();
2947            $mail_list = array();
2948            if(count($email) > $numero_maximo)
2949            {
2950                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2951                return $erros_acumulados;
2952            }
2953            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2954            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2955            foreach($email as $item)
2956            {
2957                $certificate = $db->get_certificate(strtolower($item));
2958                if(!$certificate)
2959                {
2960                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2961                    return $erros_acumulados;
2962                }
2963
2964                if (array_key_exists("dberr1", $certificate))
2965                {
2966
2967                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2968                    return $erros_acumulados;
2969                                }
2970                if (array_key_exists("dberr2", $certificate))
2971                {
2972                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2973                    //continue;
2974                }
2975                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2976                if (!array_key_exists("certs", $certificate))
2977                {
2978                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2979                    continue;
2980                }
2981            */
[3271]2982                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2983
2984                foreach ($certificate['certs'] as $registro)
2985                {
2986                    $c1 = new certificadoB();
2987                    $c1->certificado($registro['chave_publica']);
2988                    if ($c1->apresentado)
2989                    {
2990                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2991                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2992                        {
2993                            $aux_mails[] = $registro['chave_publica'];
2994                            $mail_list[] = strtolower($item);
2995                        }
2996                        else
2997                        {
2998                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2999                            {
3000                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
3001                                    $c1->dados['EXPIRADO'],$c2->revogado);
3002                            }
3003
3004                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
3005                            foreach($c2->erros_ssl as $linha)
3006                            {
3007                                $erros_acumulados .=  $linha . chr(0x0A);
3008                            }
3009                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
3010                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
3011                        }
3012                    }
3013                    else
3014                    {
3015                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
3016                    }
3017                }
3018                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
3019                                {
3020                                        return $erros_acumulados;
3021                        }
3022            }
3023
3024            $mail->Certs_crypt = $aux_mails;
3025        }
[5134]3026                                               
3027                if( count($forwarding_attachments) > 0 )// Build CID images
3028                        $this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body);
[1035]3029
[2]3030                //      Build Uploading Attachments!!!
[3387]3031                if (count($attachments)>0) //Caso seja forward normal...
[2]3032                {
3033                        $total_uploaded_size = 0;
3034                        foreach ($attachments as $attach)
3035                        {
[3900]3036                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
3037                                    return $this->parse_error("message file too big");
[3387]3038                                if($attach['name']=='Unknown')
3039                                        continue;
[5134]3040                                $mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
[2]3041                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
3042                        }
[5134]3043                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
3044                        {
3045         
3046                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
3047                            if( $total_uploaded_size > $upload_max_filesize)
[1472]3048                                return $this->parse_error("message file too big");
[3387]3049                        }
[828]3050                }
[3387]3051                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
[828]3052
[689]3053                        $total_uploaded_size = 0;
[5134]3054                       
[689]3055                        foreach($local_attachments as $local_attachment) {
3056                                $file_description = unserialize(rawurldecode($local_attachment));
3057                                $tmp = array_values($file_description);
[1472]3058                                foreach($file_description as $i => $descriptor){
[689]3059                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
3060                                }
[5134]3061                                $mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
[689]3062                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
3063                        }
[5134]3064                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
3065                        {
3066                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
3067                            if( $total_uploaded_size > $upload_max_filesize)
3068                                   return $this->parse_error("message file too big");
3069                        }
[689]3070                }
[5134]3071
[271]3072                //      Build Forwarding Attachments!!!
[2]3073                if (count($forwarding_attachments) > 0)
3074                {
3075                        // Bug fixed for array_search function
[3018]3076                        $name_cid_files = array();
[2]3077                        if(count($name_cid_files) > 0) {
3078                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
3079                                $name_cid_files[0] = null;
[1472]3080                        }
3081
[2]3082                        foreach($forwarding_attachments as $forwarding_attachment)
3083                        {
[5134]3084                                $file_description = unserialize(rawurldecode($forwarding_attachment));
[5177]3085                               
3086                                foreach($file_description as $i => $item)
3087                                        $file_description[$i] = urldecode($item);
3088                               
[5134]3089                                $tmp = array_values($file_description);
3090                                foreach($file_description as $i => $descriptor){
3091                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
3092                                }
3093                                $file_description = $tmp;
3094                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
3095                                $fileName = $file_description[2];
3096                                if(!array_search(trim($fileName),$name_cid_files)) {
3097                                        $filename_dec = html_entity_decode(rawurldecode($fileName));
3098                                        $mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
3099
3100                                }
3101                        }
3102                }
3103               
3104                //Build Message Attachments!!!
3105                if(count($message_attachments) > 0 )
3106                {
3107                        foreach($message_attachments as $folder_name => $messages)
3108                        {
3109                                foreach ($messages as $message_number => $message_subject)
3110                                {
3111                                        if (!$message_subject)
3112                                                $message_subject  = 'no title.eml';
3113                                        else
3114                                                $message_subject .= '.eml';
3115                                       
3116                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3117                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3118                                        else{
3119                                                $mbox_stream = $this->open_mbox($folder_name);
3120                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
[271]3121                                        }
[5134]3122                                                       
3123                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3124                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
[63]3125                                }
[2]3126                        }
3127                }
[5134]3128               
3129                $message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
3130                $message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
3131               
3132                ////////////////////////////////////////////////////////////////////////////////////////////////////   
3133                /**
3134                * 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.
3135                 */
3136                $default_max_size_rule = $db->get_default_max_size_rule();     
3137                if(!$default_max_size_rule)
3138                {
3139                        $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 */
3140                }
3141                else
3142                {
3143                        foreach($default_max_size_rule as $i=>$value)
3144                        {               
3145                                $default_max_size_rule = $value['config_value'];
3146                        }                               
3147                }
3148               
3149                $default_max_size_rule = $default_max_size_rule * 1024 * 1024;            /* Tamanho da regra padrão, em bytes */
3150                $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];   
3151               
3152               
3153                $ldap = new ldap_functions();
3154                $groups_user = $ldap->get_user_groups($id_user);
[37]3155
[5134]3156                $size_rule_by_group = array(); 
3157                foreach($groups_user as $k=>$value_)
3158                {       
3159                        $rule_in_group = $db->get_rule_by_user_in_groups($k);
3160                        if ($rule_in_group != "")
3161                                array_push($size_rule_by_group, $rule_in_group);
3162                }       
3163               
3164                $n_rule_groups = 0;
3165                $maior_valor_regra_grupo = 0;
3166                foreach($size_rule_by_group as $i=>$value)
3167                {
3168                        if(is_array($value[0]))
3169                        {
3170                                $n_rule_groups++;
3171                                if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
3172                                        $maior_valor_regra_grupo = $value[0]['email_max_recipient'];
3173                        }
3174                }
3175               
3176                if($default_max_size_rule)
3177                {
3178                        $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
3179
3180                        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. */
3181                        {
3182                                if($message_size_total > $default_max_size_rule)
3183                                        return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
3184                        }
3185
3186                        else
3187                        {
3188                                if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
3189                                {
3190                                        $regra_mais_permissiva = 0;
3191                                        foreach($size_rule as $i=>$value)
3192                                        {       
3193                                                if($regra_mais_permissiva < $value['email_max_recipient'])
3194                                                        $regra_mais_permissiva = $value['email_max_recipient'];
3195                                        }
3196                                        $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;                 
3197                                        if($message_size_total > $regra_mais_permissiva)
3198                                                return $this->functions->getLang("Message size greater than allowed (Rule By User)");
3199                                }
3200                                else /* Regra por grupo */
3201                                {               
3202                                        $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;                     
3203                                        if($message_size_total > $maior_valor_regra_grupo)
3204                                                return $this->functions->getLang("Message size greater than allowed (Rule By Group)"); 
3205                               
3206                               
3207                                }
3208                        }
3209                }
3210                /**
3211         * Fim da validação do tamanho da regra do tamanho de mensagem.
3212                 */
3213                 ////////////////////////////////////////////////////////////////////////////////////////////////////
3214               
3215               
3216               
3217               
3218               
3219                if($isHTML)
3220                        $mailService->setBodyHtml($body);
3221                else
3222                        $mailService->setBodyText($body);
3223
[614]3224                if($is_important)
[5134]3225                        $mailService->addHeaderField('Importance','High');
[614]3226
[5134]3227                if($return_receipt)
3228                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
[504]3229
[1472]3230
[5134]3231                if ($folder != 'null'){
3232                        $mbox_stream = $this->open_mbox($folder);
3233                        @imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
3234                }
3235
3236                $sent = $mailService->send();
3237
3238                if($sent !== true)
[2]3239                {
[5134]3240                        return $this->parse_error($sent);
[2]3241                }
3242                else
3243                {
[1035]3244            if ($signed && !$params['smime'])
3245                        {
3246                                return $sent;
3247                        }
[1472]3248                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]3249                        {
3250                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3251                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
3252                                $now = date("d/m/y H:i:s");
3253                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[1472]3254                                $sent = trim($sent);
[117]3255                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
3256                        }
[5134]3257                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]3258                                $contacts = new dynamic_contacts();
[485]3259                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
3260                                return array("success" => true, "new_contacts" => $new_contacts);
[413]3261                        }
[485]3262                        return array("success" => true);
[2]3263                }
3264        }
[4416]3265       
[4436]3266       
3267        /**
3268        * @license   http://www.gnu.org/copyleft/gpl.html GPL
3269        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
3270        * @param     $mail email
3271        * @param     $msg_uid uid da mensagem
3272        * @param     $forwarding_attachments anexos
3273        */
[5134]3274
3275        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
[4795]3276        {
[5134]3277                //Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
3278                $pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';
[4795]3279                $cid_imgs = '';
[5134]3280                preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
3281                //-------------------------------------------------------------------//
[2]3282
[5134]3283                $attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
[3018]3284
[5134]3285                foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
3286                        $desc = unserialize(rawurldecode($v));
3287                        $attPostions[$desc[3]] = $i;
3288                }
[3018]3289
[5134]3290                //Intera as imagens encontradas
3291                foreach($cid_imgs[6] as $j => $val)
3292        {               
3293                        $cid = base_convert(microtime().$j, 10, 36); //Gera um cid
[5158]3294                        $body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'"', $body ); //tira o src da imagem e coloca o cid.
[4416]3295                        $count    = strlen($cid_imgs[6][$j]);
3296                                       
[5134]3297                        $attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
[4416]3298                        $file_description = unserialize(rawurldecode($attach_img));
3299                       
3300                        if (is_array($file_description))
3301                                foreach($file_description as $i => $descriptor)                         
[5134]3302                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);
[4416]3303
3304                        // The image is not in the same mail?
3305                        if ($msg_uid != $cid_imgs[4][$j])
[4795]3306                        {
[5134]3307                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
3308                $fileContent = &$fa['binary'];
3309                                $fileName = $fa['name'];
3310                                $fileCode = $fa['encoding'];
3311                                $fileType =  $fa['type'];
[4795]3312                                $file_attached[0] = $cid_imgs[2][$j];
3313                                $file_attached[1] = $cid_imgs[4][$j];
3314                                $file_attached[2] = $fileName;
[5134]3315                                $file_attached[3] = '0.'.(string)($j+1);
[4795]3316                                $file_attached[4] = 'base64';
3317                                $file_attached[5] = strlen($fileContent); //Size of file
[4416]3318                                $file_attached[6] = $cid_imgs[6][$j];
[4795]3319                                $return_forward[] = $file_attached;
[4416]3320
3321                                if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
[5134]3322                                        unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
[4416]3323                               
[4795]3324                        }
3325                        else
3326                        {
3327                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
3328                                $fileName = $file_description[2];
3329                                $fileCode = $file_description[4];
[5134]3330                                $file_description[3] = '0.'.(string)($j+1);
[4416]3331                                $file_description[6] = $cid_imgs[6][$j];
[4795]3332                                $fileType = $this->get_file_type($file_description[2]);
[5134]3333                                unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
[4795]3334                                if (!empty($file_description))
3335                                {
3336                                        $file_description[5] = strlen($fileContent); //Size of file
3337                                        $return_forward[] = $file_description;
3338                                }
3339                        }
[4416]3340
[4795]3341                        if ($fileContent)
[5134]3342                                $mail->addStringImage($fileContent,$fileType,$fileName, $cid);                                 
[4416]3343                }
[4795]3344
3345                return $return_forward;
3346        }
[3018]3347        function add_recipients_cert($full_address)
[1035]3348        {
3349                $result = "";
3350                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
3351                foreach ($parse_address as $val)
3352                {
3353                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3354                        if ($val->mailbox == "INVALID_ADDRESS")
3355                                continue;
3356                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
3357                                continue;
3358                        if (empty($val->personal))
3359                                $result .= $val->mailbox."@".$val->host . ",";
3360                        else
3361                                $result .= $val->mailbox."@".$val->host . ",";
3362                }
3363
3364                return substr($result,0,-1);
3365        }
3366
[2]3367        function add_recipients($recipient_type, $full_address, $mail)
3368        {
[3932]3369                //remove a comma if is given two unexpected commas
3370                $full_address = preg_replace("/, ?,/",",",$full_address);
[1472]3371                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
[5134]3372                $bolean = true;
[1472]3373                foreach ($parse_address as $val)
[2]3374                {
3375                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3376                        if ($val->mailbox == "INVALID_ADDRESS")
3377                                continue;
[1472]3378
[2]3379                        if (empty($val->personal))
3380                        {
3381                                switch($recipient_type)
3382                                {
3383                                        case "to":
[5134]3384                                                $mail->AddTo($val->mailbox."@".$val->host);
[2]3385                                                break;
3386                                        case "cc":
[5134]3387                                                $mail->AddCc($val->mailbox."@".$val->host);
[2]3388                                                break;
3389                                        case "cco":
[5134]3390                                                $mail->AddBcc($val->mailbox."@".$val->host);
[2]3391                                                break;
3392                                }
3393                        }
3394                        else
3395                        {
3396                                switch($recipient_type)
3397                                {
3398                                        case "to":
[5134]3399                                                $mail->AddTo($val->mailbox."@".$val->host, $val->personal);
[2]3400                                                break;
3401                                        case "cc":
[5134]3402                                                $mail->AddCc($val->mailbox."@".$val->host, $val->personal);
[2]3403                                                break;
3404                                        case "cco":
[5134]3405                                                $mail->AddBcc($val->mailbox."@".$val->host, $val->personal);
[2]3406                                                break;
3407                                }
3408                        }
[5134]3409                        if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){
3410                                $bolean = false;
[2]3411                }
[5134]3412                       
3413                }
3414                return $bolean;
[2]3415        }
[1472]3416
[2]3417        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
3418        {
[4416]3419            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
3420            $attachment = new attachment();
[5134]3421                        $attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo.
[4416]3422            $attachment->setStructureFromMail($msg_folder, $msg_number);
3423            return $attachment->getAttachment($msg_part);
[2]3424        }
[1472]3425
[5134]3426        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding)
3427        {
3428            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
3429            $attachment = new attachment();
3430            $attachment->setStructureFromMail($msg_folder, $msg_number);
3431            $return = $attachment->getAttachmentInfo($msg_part);
3432            $return['binary'] = $attachment->getAttachment($msg_part);
3433            return $return;
3434        }
3435
[2]3436        function del_last_caracter($string)
3437        {
3438                $string = substr($string,0,(strlen($string) - 1));
[1472]3439                return $string;
[2]3440        }
[1472]3441
[2]3442        function del_last_two_caracters($string)
3443        {
3444                $string = substr($string,0,(strlen($string) - 2));
[1472]3445                return $string;
[2]3446        }
[1472]3447
[828]3448        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
[659]3449        {
[1625]3450                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
[970]3451                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
3452                        foreach($imapsort as $iuid)
3453                                $sort[$iuid] = "";
[1518]3454                       
3455                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
3456                                $slice_array = false;
3457                        else
3458                                $slice_array = true;
[970]3459                }
3460                else
[659]3461                {
[970]3462                        $sort = array();
3463                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
3464                        $num_msgs = imap_num_msg($this->mbox);
3465                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
[975]3466                        $slice_array = true;
3467
[983]3468                        for ($i=$num_msgs; $i>0; $i--)
[828]3469                        {
[983]3470                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
3471                                        break;
[970]3472                                $iuid = @imap_uid($this->mbox,$i);
3473                                $header = $this->get_header($iuid);
3474                                // List UNSEEN messages.
3475                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
3476                                        continue;
3477                                }
3478                                // List SEEN messages.
3479                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
3480                                        continue;
3481                                }
3482                                // List ANSWERED messages.
3483                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
3484                                        continue;
3485                                }
3486                                // List FLAGGED messages.
3487                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
3488                                        continue;
3489                                }
3490
3491                                if($sort_box_type=='SORTFROM') {
3492                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
3493                                                $from = $header->to;
3494                                        else
3495                                                $from = $header->from;
[5134]3496                                        if(isset($from[0]->personal))
[970]3497                                        $tmp = imap_mime_header_decode($from[0]->personal);
[5134]3498                                        else
3499                                                $tmp = null;
3500                                        if (isset($tmp[0]->text))
[970]3501                                                $sort[$iuid] = $tmp[0]->text;
3502                                        else
3503                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
3504                                }
3505                                else if($sort_box_type=='SORTSUBJECT') {
3506                                        $sort[$iuid] = $header->subject;
3507                                }
3508                                else if($sort_box_type=='SORTSIZE') {
3509                                        $sort[$iuid] = $header->Size;
3510                                }
3511                                else {
3512                                        $sort[$iuid] = $header->udate;
3513                                }
3514
[659]3515                        }
[970]3516                        natcasesort($sort);
[828]3517
[970]3518                        if ($sort_box_reverse)
3519                                $sort = array_reverse($sort,true);
[659]3520                }
[5134]3521                if(empty($sort) or !is_array($sort)){
[972]3522                        $sort = array();
[5134]3523                }
3524               
3525                       
[1472]3526
[1808]3527
[972]3528                if ($slice_array)
[828]3529                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
[970]3530
[1472]3531
[828]3532                return $sort;
3533
[659]3534        }
[970]3535
[5172]3536        function move_delete_search_messages($params){
3537                $move = false;
3538                $msg_no_move = "";
3539       
3540                $params['selected_messages'] = urldecode($params['selected_messages_move']);
3541                $params['new_folder'] = urldecode($params['new_folder_move']);
3542                $params['new_folder_name'] = urldecode($params['new_folder_name_move']);
3543                $sel_msgs = explode(",", $params['selected_messages']);
3544                @reset($sel_msgs);
3545                $sorted_msgs = array();
3546                foreach($sel_msgs as $idx => $sel_msg) {
3547                        $sel_msg = explode(";", $sel_msg);
3548                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3549                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3550                         }
3551                         else {
3552                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3553                         }
3554                }               
3555                @ksort($sorted_msgs);
3556                $last_return = false;
3557                foreach($sorted_msgs as $folder => $msgs_number) {
3558                        $params['msgs_number'] = $msgs_number;
3559                        $params['folder'] = $folder;
3560                               
3561                        $last_return = $this->move_messages($params);
3562                       
3563                        if($last_return['status']){
3564                                $move = true;
3565                        }else{
3566                                $msg_no_move =  $params['msgs_number'];
3567                        }
3568                }
3569                $sel_msgs = null;               
3570                $params['selected_messages'] = urldecode($params['selected_messages_delete']);
3571                $params['new_folder'] = urldecode($params['new_folder_delete']);
3572                $params['new_folder_name'] = urldecode($params['new_folder_name_delete']);
3573                $sel_msgs = explode(",", $params['selected_messages']);
3574                @reset($sel_msgs);
3575                $sorted_msgs = array();
3576                foreach($sel_msgs as $idx => $sel_msg) {
3577                        $sel_msg = explode(";", $sel_msg);
3578                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3579                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3580                         }
3581                         else {
3582                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3583                         }
3584                }
3585                @ksort($sorted_msgs);
3586                $last_return = false;
3587                foreach($sorted_msgs as $folder => $msgs_number) {
3588                        $params['msgs_number'] = $msgs_number;
3589                        $params['folder'] = $folder;
3590               
3591                        $params['folder'] = $params['new_folder_delete'];
3592                        $last_return = $this->delete_msgs($params);
3593                        $last_return['deleted'] = true;
3594                        if($last_return['status']){
3595                                $move = true;
3596                        }else{
3597                                $msg_no_move =  $params['msgs_number'];
3598                        }
3599               
3600                }
3601       
3602                if($move)
3603                        $last_return['move'] = true;
3604                       
3605                if($msg_no_move != "")
3606                        $last_return['no_move'] = $msg_no_move;
3607               
3608                return $last_return;
3609        }
[970]3610
[1472]3611        function move_search_messages($params){
3612                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]3613                $params['new_folder'] = urldecode($params['new_folder']);
3614                $params['new_folder_name'] = urldecode($params['new_folder_name']);
3615                $sel_msgs = explode(",", $params['selected_messages']);
[5172]3616                $move = false;
3617                $msg_no_move = "";
3618               
[1472]3619                @reset($sel_msgs);
[163]3620                $sorted_msgs = array();
3621                foreach($sel_msgs as $idx => $sel_msg) {
3622                        $sel_msg = explode(";", $sel_msg);
3623                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3624                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[1472]3625                         }
[163]3626                         else {
3627                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3628                         }
3629                }
3630                @ksort($sorted_msgs);
[1472]3631                $last_return = false;
3632                foreach($sorted_msgs as $folder => $msgs_number) {
[163]3633                        $params['msgs_number'] = $msgs_number;
[1472]3634                        $params['folder'] = $folder;
[5172]3635                       
3636                if($params['delete'] === 'true'){
3637                        $params['folder'] = $params['new_folder'];
3638                        $last_return = $this->delete_msgs($params);
[163]3639                                $last_return['deleted'] = true;
[5172]3640                       
3641                        if($last_return['status']){
3642                                $move = true;
3643                        }else{
3644                                $msg_no_move =  $params['msgs_number'];
[163]3645                        }
[5172]3646                       
3647                }else{
3648                                $last_return = $this->move_messages($params);
3649                               
3650                                if($last_return['status']){
3651                                        $move = true;
3652                                }else{
3653                                        $msg_no_move =  $params['msgs_number'];
3654                        }
[163]3655                }
[5172]3656                }
3657               
3658                if($move)
3659                        $last_return['move'] = true;
3660                       
3661                if($msg_no_move != "")
3662                        $last_return['no_move'] = $msg_no_move;
3663                       
[163]3664                return $last_return;
3665        }
[1472]3666
[2]3667        function move_messages($params)
3668        {
[1472]3669                $folder = $params['folder'];
3670                $mbox_stream = $this->open_mbox($folder);
[5134]3671                $newmailbox = ($params['new_folder']);
[4997]3672                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
[5134]3673                $new_folder_name = $params['new_folder_name'];
[4997]3674                $msgs_number = $params['msgs_number'];
[2]3675                $return = array('msgs_number' => $msgs_number,
3676                                                'folder' => $folder,
3677                                                'new_folder_name' => $new_folder_name,
[325]3678                                                'border_ID' => $params['border_ID'],
3679                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[1472]3680
[325]3681                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
3682        if (substr($folder,0,4) == 'user'){
3683                $acl = $this->getacltouser($folder);
3684                /*
3685                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
3686                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
3687                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
3688                 *   w - write (STORE flags other than SEEN and DELETED)
3689                 *   i - insert (perform APPEND, COPY into mailbox)
3690                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
3691                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
3692                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
3693                 *   a - administer (perform SETACL)
3694                        */
3695                        if (strpos($acl, "d") === false){
3696                                $return['status'] = false;
3697                                return $return;
3698                        }
3699        }
[432]3700        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[5134]3701        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){
[1747]3702        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
3703            if (substr($new_folder_name,0,4) == 'user'){
3704                $this->ldap = new ldap_functions();
3705                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
3706                $return['new_folder_name'] = array_pop($tmp_folder_name);
3707                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
3708                {
3709                    $return['new_folder_name'] = $cn;
3710                }
3711            }
[432]3712        }
[5134]3713                }
[1472]3714
3715                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
[51]3716                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]3717                {
[2]3718                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]3719                        // Fix problem in unserialize function JS.
[5134]3720                        if(array_key_exists('body', $return['previous_msg']))
[449]3721                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
3722                }
[1472]3723
3724                $mbox_stream = $this->open_mbox($folder);
[2]3725                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3726                        imap_expunge($mbox_stream);
[51]3727                        if($mbox_stream)
3728                                imap_close($mbox_stream);
[2]3729                        return $return;
3730                }else {
[1472]3731                        if(strstr(imap_last_error(),'Over quota')) {
[2]3732                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[1472]3733                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
3734                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
[2]3735                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]3736                                $mbox           = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
[2]3737                                if(!$mbox)
3738                                        return imap_last_error();
[1472]3739                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
[2]3740                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]3741                                        if($mbox_stream)
3742                                                imap_close($mbox_stream);
[1472]3743                                        if($mbox)
[51]3744                                                imap_close($mbox);
[1472]3745                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
[2]3746                                }
3747                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3748                                        imap_expunge($mbox_stream);
[51]3749                                        if($mbox_stream)
3750                                                imap_close($mbox_stream);
[2]3751                                        // return to original quota limit.
3752                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]3753                                                if($mbox)
3754                                                        imap_close($mbox);
[1472]3755                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]3756                                        }
[1472]3757                                        return $return;
[2]3758                                }
3759                                else {
[51]3760                                        if($mbox_stream)
3761                                                imap_close($mbox_stream);
[2]3762                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]3763                                                if($mbox)
3764                                                        imap_close($mbox);
[1472]3765                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]3766                                        }
[1472]3767                                        return imap_last_error();
[2]3768                                }
[1472]3769
[2]3770                        }
3771                        else {
[51]3772                                if($mbox_stream)
3773                                        imap_close($mbox_stream);
3774                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]3775                        }
[1472]3776                }
[2]3777        }
[1472]3778
[5134]3779
[2]3780        function save_msg($params)
3781        {
[5134]3782                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
3783                $mailService = ServiceLocator::getService('mail');
[1472]3784
[4795]3785                $return_receipt = $params['input_return_receipt'];
3786                $is_important = $params['input_important_message'];
[5134]3787               
[4795]3788                $msg_uid = $params['msg_id'];
3789                $body = $params['body'];
[4416]3790                $body = str_replace("%nbsp;","&nbsp;",$body);
[155]3791                $body = preg_replace("/\n/"," ",$body);
[5134]3792                $body = preg_replace("/\r/","" ,$body);
[5177]3793                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
[271]3794                $forwarding_attachments = $params['forwarding_attachments'];
[5134]3795                $message_attachments    = $params['message_attachments'];
[4795]3796                $attachments = $params['FILES'];
[271]3797                $return_files = $params['FILES'];
[5134]3798                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
[1472]3799
[4800]3800                if(is_array($params['local_attachments'])){
3801                    foreach ($params['local_attachments'] as $key => $local_attach) {
3802                       $tmp = unserialize(urldecode($local_attach));
[5134]3803                           $attachments[$key]['name'] = urldecode($tmp[2]);
3804                           $return_files[$key]['name'] = urldecode($tmp[2]);
[4800]3805                    }
3806                }
3807
[5134]3808                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO_8859-1");
3809                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
[4800]3810
[5134]3811                $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
3812                $mailService->addTo($params['input_to']);
3813                $mailService->addCc( $params['input_cc']);
3814                $mailService->addBcc($params['input_cco']);
3815                $mailService->setSubject($params['input_subject']);
[4795]3816
[5134]3817                if($is_important){
3818                        $mailService->addHeaderField('Importance','High');
3819                }
[4795]3820
[5134]3821                if($return_receipt)
3822                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
[4795]3823
[5134]3824                $isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
[4795]3825
3826               
[5134]3827                if( count($forwarding_attachments) > 0 )
3828                        $return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
3829                       
3830                //Build Message Attachments!!!
3831                if(count($message_attachments) > 0 )
3832                {
3833                        foreach($message_attachments as $folder_name => $messages)
3834                        {
3835                                foreach ($messages as $message_number => $message_subject)
3836                                {
3837                                        if (!$message_subject)
3838                                                $message_subject  = 'no title.eml';
3839                                        else
3840                                                $message_subject .= '.eml';
3841                                       
3842                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3843                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3844                                        else{
3845                                                $mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
3846                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
3847                                        }
3848                                                                                       
3849                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3850                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
3851                                }
3852                        }
3853                }
3854               
[4416]3855                $imagesParts = array();
[4795]3856
[5134]3857                if(count($return_forward) > 0 )
[4416]3858                foreach ($return_forward as $value)
3859                        $imagesParts[$value[6]] = $value[3];   
[1472]3860
[5134]3861                //Build Forwarding Attachments!!!
3862                if(count($forwarding_attachments) > 0 )
3863                {
[4795]3864                        foreach($forwarding_attachments as $forwarding_attachment)
3865                        {
[5177]3866
[4795]3867                                $file_description = unserialize(rawurldecode($forwarding_attachment));
[5177]3868                                foreach($file_description as $i => $item)
3869                                        $file_description[$i] = urldecode($item);                               
3870                       
3871                                $file_description = array_values($file_description);
[4457]3872                                       
[5134]3873                                foreach($file_description as $i => $descriptor)
[4457]3874                                                        $file_description[$i] = eregi_replace('\'*\'','',$descriptor);
[5134]3875                               
[4795]3876                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
[5134]3877                                $file_description[2] = html_entity_decode($file_description[2]);
[4795]3878
3879                                $file_description[5] = strlen($fileContent); //Size of file
3880                                $return_forward[] = $file_description;
[5134]3881                                $mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
[4795]3882                        }
[5134]3883                        }
[4795]3884
[271]3885                if ((count($return_forward) > 0) && (count($return_files) > 0))
3886                        $return_files = array_merge_recursive($return_forward,$return_files);
[4416]3887                else if (count($return_files) < 1)
[4795]3888                                $return_files = $return_forward;
[1472]3889
[5134]3890                //Build Uploading Attachments!!!
[1005]3891                $sizeof_attachments = count($attachments);
3892                if ($sizeof_attachments)
[4416]3893                        foreach ($attachments as $numb => $attach)
[5134]3894                                $mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
[4416]3895
[4795]3896
[5134]3897                if (!$body)
3898                        $body = ' ';
3899               
3900                if($isHTML)
3901                        $mailService->setBodyHtml($body);
3902                else
3903                        $mailService->setBodyText($body);
[271]3904
[828]3905
[4795]3906                $mbox_stream = $this->open_mbox($folder);
[5134]3907                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
3908
[4795]3909                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
[271]3910                $return['msg_no'] = $status->uidnext - 1;
3911                $return['folder_id'] = $folder;
[4416]3912                $return['imagesParts'] = $imagesParts;
[828]3913
[51]3914                if($mbox_stream)
3915                        imap_close($mbox_stream);
[4416]3916                       
[5134]3917                $returnFiles = array();                 
3918                $ii = 0;
3919                               
3920                if(count($return_files) > 0)
[4416]3921                {
3922                        foreach ($return_files as $index => $_attachment)
[271]3923                        {
[4416]3924                                if (array_key_exists("name", $_attachment))
3925                                {
[5134]3926                                        $returnFiles[$ii]['name'] = base64_encode($_attachment['name']);
3927                                        $returnFiles[$ii]['size'] = $_attachment['size'];
3928                                        $ii++;
[271]3929                        }
[5134]3930                                else if($_attachment[2])
[4795]3931                        {
[5134]3932                                        $returnFiles[$ii]['name'] = base64_encode($_attachment[2]);
3933                                        $returnFiles[$ii]['size'] = $_attachment[5];         
3934                                        $ii++;
[4795]3935                        }
[271]3936                }
[4795]3937                }
[5134]3938                $return['files'] = serialize($returnFiles);
3939                $return["subject"] = $params['input_subject'];
3940                if (!$return['append']) $return['append'] = imap_last_error();
[2]3941                return $return;
3942        }
[1472]3943
[2]3944        function set_messages_flag($params)
3945        {
3946                $folder = $params['folder'];
[5134]3947                $msgs_to_set = $params['msgs_to_set'];
[2]3948                $flag = $params['flag'];
3949                $return = array();
[5134]3950                $return["msgs_to_set"] = $msgs_to_set;
[2]3951                $return["flag"] = $flag;
[1472]3952
[5182]3953                $return["msgs_not_to_set"] = "";
3954                       
[411]3955                if(!$this->mbox && !is_resource($this->mbox))
[51]3956                        $this->mbox = $this->open_mbox($folder);
[5182]3957                if ($flag == "unseen"){
3958                        $return["msgs_to_set"] = "";
3959                        $msgs = explode(",",$msgs_to_set);
3960                        foreach($msgs as $men){
3961                                if (imap_clearflag_full($this->mbox, $men, "\\Seen", ST_UID))
3962                                        $return["msgs_to_set"] .= $men.",";
3963                                else
3964                                        $return["msgs_not_to_set"] .= $men.",";
3965                        }
3966                        $return["status"] = true;
3967                }elseif ($flag == "seen"){
3968                        $return["msgs_to_set"] = "";
3969                        $msgs = explode(",",$msgs_to_set);
3970                        foreach($msgs as $men){
3971                                if (imap_setflag_full($this->mbox, $men, "\\Seen", ST_UID))
3972                                        $return["msgs_to_set"] .= $men.",";
3973                                else
3974                                        $return["msgs_not_to_set"] .= $men.",";
3975                        }
3976                        $return["status"] = true;
3977                }elseif ($flag == "answered"){
[51]3978                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
3979                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]3980                }
3981                elseif ($flag == "forwarded")
[51]3982                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]3983                elseif ($flag == "flagged")
[51]3984                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[614]3985                elseif ($flag == "unflagged") {
3986                        $flag_importance = false;
3987                        $msgs_number = explode(",",$msgs_to_set);
[659]3988                        $unflagged_msgs = "";
[614]3989                        foreach($msgs_number as $msg_number) {
3990                                preg_match('/importance *: *(.*)\r/i',
3991                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]3992                                        ,$importance);
[673]3993                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]3994                                        $flag_importance=true;
3995                                }
[659]3996                                else {
3997                                        $unflagged_msgs.=$msg_number.",";
[1472]3998                                }
[614]3999                        }
4000
[659]4001                        if($unflagged_msgs!="") {
4002                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
4003                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
4004                        }
4005                        else {
4006                                $return["msgs_unflageds"] = false;
4007                        }
4008
[673]4009                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]4010                                $return["status"] = false;
4011                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
4012                        }
[659]4013                        else {
4014                                $return["status"] = true;
4015                        }
[614]4016                }
[5182]4017               
4018                if(($flag == "seen") || ($flag == "unseen")){
4019                        if ($return["msgs_not_to_set"] != ""){
4020                                $return["msgs_not_to_set"] = substr($return["msgs_not_to_set"], 0, -1);
4021                        }
4022                        if($return["msgs_to_set"] != ""){
4023                                $return["msgs_to_set"] = substr($return["msgs_to_set"], 0, -1);
4024                        }
4025                }
[411]4026                if($this->mbox && is_resource($this->mbox))
[51]4027                        imap_close($this->mbox);
[5182]4028                                               
[2]4029                return $return;
4030        }
[1472]4031
[2]4032        function get_file_type($file_name)
4033        {
4034                $file_name = strtolower($file_name);
4035                $strFileType = strrev(substr(strrev($file_name),0,4));
[5134]4036                if ($strFileType == ".eml")
4037                        return "message/rfc822";
[1472]4038                if ($strFileType == ".asf")
[2]4039                        return "video/x-ms-asf";
4040                if ($strFileType == ".avi")
4041                        return "video/avi";
4042                if ($strFileType == ".doc")
4043                        return "application/msword";
4044                if ($strFileType == ".zip")
4045                        return "application/zip";
4046                if ($strFileType == ".xls")
4047                        return "application/vnd.ms-excel";
4048                if ($strFileType == ".gif")
4049                        return "image/gif";
4050                if ($strFileType == ".jpg" || $strFileType == "jpeg")
4051                        return "image/jpeg";
4052                if ($strFileType == ".png")
4053                        return "image/png";
4054                if ($strFileType == ".wav")
4055                        return "audio/wav";
4056                if ($strFileType == ".mp3")
4057                        return "audio/mpeg3";
4058                if ($strFileType == ".mpg" || $strFileType == "mpeg")
4059                        return "video/mpeg";
4060                if ($strFileType == ".rtf")
4061                        return "application/rtf";
4062                if ($strFileType == ".htm" || $strFileType == "html")
4063                        return "text/html";
[1472]4064                if ($strFileType == ".xml")
[2]4065                        return "text/xml";
[1472]4066                if ($strFileType == ".xsl")
[2]4067                        return "text/xsl";
[1472]4068                if ($strFileType == ".css")
[2]4069                        return "text/css";
[1472]4070                if ($strFileType == ".php")
[2]4071                        return "text/php";
[1472]4072                if ($strFileType == ".asp")
[2]4073                        return "text/asp";
4074                if ($strFileType == ".pdf")
4075                        return "application/pdf";
4076                if ($strFileType == ".txt")
4077                        return "text/plain";
4078                if ($strFileType == ".wmv")
4079                        return "video/x-ms-wmv";
4080                if ($strFileType == ".sxc")
4081                        return "application/vnd.sun.xml.calc";
4082                if ($strFileType == ".stc")
4083                        return "application/vnd.sun.xml.calc.template";
4084                if ($strFileType == ".sxd")
4085                        return "application/vnd.sun.xml.draw";
4086                if ($strFileType == ".std")
4087                        return "application/vnd.sun.xml.draw.template";
4088                if ($strFileType == ".sxi")
4089                        return "application/vnd.sun.xml.impress";
4090                if ($strFileType == ".sti")
4091                        return "application/vnd.sun.xml.impress.template";
4092                if ($strFileType == ".sxm")
4093                        return "application/vnd.sun.xml.math";
4094                if ($strFileType == ".sxw")
4095                        return "application/vnd.sun.xml.writer";
4096                if ($strFileType == ".sxq")
4097                        return "application/vnd.sun.xml.writer.global";
4098                if ($strFileType == ".stw")
4099                        return "application/vnd.sun.xml.writer.template";
[1472]4100
4101
4102                return "application/octet-stream";
[2]4103        }
[1472]4104
[2]4105        function htmlspecialchars_encode($str)
4106        {
[449]4107                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]4108        }
4109        function htmlspecialchars_decode($str)
4110        {
[449]4111                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]4112        }
[1472]4113
[828]4114        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
4115        {
4116                if(!$this->mbox || !is_resource($this->mbox))
[51]4117                        $this->mbox = $this->open_mbox($folder);
[432]4118
[828]4119                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
4120        }
[1472]4121
[53]4122        function get_info_next_msg($params)
4123        {
4124                $msg_number = $params['msg_number'];
4125                $folder = $params['msg_folder'];
4126                $sort_box_type = $params['sort_box_type'];
4127                $sort_box_reverse = $params['sort_box_reverse'];
4128                $reuse_border = $params['reuse_border'];
4129                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[1472]4130                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
4131
[320]4132                $success = false;
4133                if (is_array($sort_array_msg))
[2]4134                {
[320]4135                        foreach ($sort_array_msg as $i => $value){
4136                                if ($value == $msg_number)
4137                                {
4138                                        $success = true;
4139                                        break;
4140                                }
4141                        }
[2]4142                }
4143
[320]4144                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]4145                {
4146                        $params['status'] = 'false';
4147                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4148                        return $params;
4149                }
[1472]4150
[2]4151                $params = array();
4152                $params['msg_number'] = $sort_array_msg[($i+1)];
4153                $params['msg_folder'] = $folder;
[1472]4154
4155                $return = $this->get_info_msg($params);
[2]4156                $return["reuse_border"] = $reuse_border;
4157                return $return;
4158        }
4159
4160        function get_info_previous_msg($params)
4161        {
4162                $msg_number = $params['msgs_number'];
4163                $folder = $params['folder'];
4164                $sort_box_type = $params['sort_box_type'];
4165                $sort_box_reverse = $params['sort_box_reverse'];
4166                $reuse_border = $params['reuse_border'];
[53]4167                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
4168                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[1472]4169
[320]4170                $success = false;
4171                if (is_array($sort_array_msg))
[2]4172                {
[320]4173                        foreach ($sort_array_msg as $i => $value){
4174                                if ($value == $msg_number)
4175                                {
4176                                        $success = true;
4177                                        break;
4178                                }
4179                        }
[2]4180                }
[320]4181                if (! $success || $i == 0)
4182                {
[2]4183                        $params['status'] = 'false';
4184                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4185                        return $params;
4186                }
[1472]4187
[2]4188                $params = array();
4189                $params['msg_number'] = $sort_array_msg[($i-1)];
4190                $params['msg_folder'] = $folder;
[1472]4191
[2]4192                $return = $this->get_info_msg($params);
4193                $return["reuse_border"] = $reuse_border;
4194                return $return;
4195        }
[1472]4196
[2]4197        // This function updates the values: quota, paging and new messages menu.
4198        function get_menu_values($params){
4199                $return_array = array();
4200                $return_array = $this->get_quota($params);
[1472]4201
[2]4202                $mbox_stream = $this->open_mbox($params['folder']);
[1472]4203                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
[51]4204                if($mbox_stream)
4205                        imap_close($mbox_stream);
[1472]4206
4207                return $return_array;
[2]4208        }
[1472]4209
[325]4210        function get_quota($params){
[449]4211                // folder_id = user/{uid} for shared folders
4212                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
4213                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
[1472]4214                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
[449]4215                }
4216                // folder_id = INBOX for inbox folders
4217                else
4218                        $folder_id = "INBOX";
[1472]4219
[1035]4220                if(!$this->mbox || !is_resource($this->mbox))
[51]4221                        $this->mbox = $this->open_mbox();
[345]4222
[325]4223                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]4224                if($this->mbox && is_resource($this->mbox))
[51]4225                        imap_close($this->mbox);
[1472]4226
[2]4227                if (!$quota){
4228                        return array(
4229                                'quota_percent' => 0,
4230                                'quota_used' => 0,
4231                                'quota_limit' =>  0
4232                        );
4233                }
[1472]4234
[2]4235                if(count($quota) && $quota['limit']) {
[3064]4236                        $quota_limit = $quota['limit'];
4237                        $quota_used  = $quota['usage'];
[2]4238                        if($quota_used >= $quota_limit)
[650]4239                        {
4240                                $quotaPercent = 100;
4241                        }
4242                        else
4243                        {
[2]4244                        $quotaPercent = ($quota_used / $quota_limit)*100;
4245                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
[650]4246                        }
[2]4247                        return array(
4248                                'quota_percent' => floor($quotaPercent),
[3064]4249                                'quota_used' => $quota_used,
4250                                'quota_limit' =>  $quota_limit
[2]4251                        );
4252                }
[1472]4253                else
[2]4254                        return array();
4255        }
[1472]4256
[2]4257        function send_notification($params){
[3231]4258                include("../header.inc.php");
[2]4259                require_once("class.phpmailer.php");
4260                $mail = new PHPMailer();
[1472]4261
[2]4262                $toaddress = $params['notificationto'];
[1472]4263
[3231]4264                $subject = lang("Read receipt: %1",$params['subject']);
4265                $body = lang("Your message: %1",$params['subject']) . '<br>';
[4739]4266                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
[3231]4267                $body .= lang("Has been read by: %1 &lt; %2 &gt; at %3", $_SESSION['phpgw_info']['expressomail']['user']['fullname'], $_SESSION['phpgw_info']['expressomail']['user']['email'], date("d/m/Y H:i"));
[2]4268                $mail->SMTPDebug = false;
4269                $mail->IsSMTP();
4270                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
4271                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
4272                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4273                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
4274                $mail->AddAddress($toaddress);
4275                $mail->Subject = $this->htmlspecialchars_decode($subject);
4276
4277                $mail->IsHTML(true);
4278                $mail->Body = $body;
[1472]4279
[2]4280                if(!$mail->Send()){
4281                        return $mail->ErrorInfo;
4282                }
4283                else
4284                        return true;
4285        }
[1472]4286
[1965]4287        function empty_folder($params)
[2]4288        {
[1965]4289                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
[2]4290                $mbox_stream = $this->open_mbox($folder);
4291                $return = imap_delete($mbox_stream,'1:*');
[51]4292                if($mbox_stream)
4293                        imap_close($mbox_stream, CL_EXPUNGE);
[2]4294                return $return;
4295        }
[1472]4296
[2]4297        function search($params)
4298        {
[673]4299                include("class.imap_attachment.inc.php");
[1472]4300                $imap_attachment = new imap_attachment();
[2]4301                $criteria = $params['criteria'];
4302                $return = array();
4303                $folders = $this->get_folders_list();
[1472]4304
[2]4305                $j = 0;
4306                foreach($folders as $folder)
4307                {
4308                        $mbox_stream = $this->open_mbox($folder);
4309                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[1472]4310
[2]4311                        if ($messages == '')
4312                                continue;
[1472]4313
[2]4314                        $i = 0;
4315                        $return[$j] = array();
4316                        $return[$j]['folder_name'] = $folder['name'];
[1472]4317
[2]4318                        foreach($messages as $msg_number)
4319                        {
[535]4320                                $header = $this->get_header($msg_number);
[2]4321                                if (!is_object($header))
4322                                        return false;
[1472]4323
[2]4324                                $return[$j][$i]['msg_folder']   = $folder['name'];
4325                                $return[$j][$i]['msg_number']   = $msg_number;
4326                                $return[$j][$i]['Recent']               = $header->Recent;
4327                                $return[$j][$i]['Unseen']               = $header->Unseen;
4328                                $return[$j][$i]['Answered']     = $header->Answered;
4329                                $return[$j][$i]['Deleted']              = $header->Deleted;
4330                                $return[$j][$i]['Draft']                = $header->Draft;
4331                                $return[$j][$i]['Flagged']              = $header->Flagged;
[1472]4332
[535]4333                                $date_msg = gmdate("d/m/Y",$header->udate);
4334                                if (gmdate("d/m/Y") == $date_msg)
4335                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]4336                                else
4337                                        $return[$j][$i]['udate'] = $date_msg;
[1472]4338
[2]4339                                $fromaddress = imap_mime_header_decode($header->fromaddress);
4340                                $return[$j][$i]['fromaddress'] = '';
4341                                foreach ($fromaddress as $tmp)
4342                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[1472]4343
[2]4344                                $from = $header->from;
4345                                $return[$j][$i]['from'] = array();
4346                                $tmp = imap_mime_header_decode($from[0]->personal);
4347                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
4348                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]4349                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]4350
4351                                $to = $header->to;
4352                                $return[$j][$i]['to'] = array();
4353                                $tmp = imap_mime_header_decode($to[0]->personal);
4354                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
4355                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[1472]4356                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]4357
4358                                $subject = imap_mime_header_decode($header->fetchsubject);
4359                                $return[$j][$i]['subject'] = '';
4360                                foreach ($subject as $tmp)
4361                                        $return[$j][$i]['subject'] .= $tmp->text;
4362
4363                                $return[$j][$i]['Size'] = $header->Size;
4364                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]4365
[2]4366                                $return[$j][$i]['attachment'] = array();
4367                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[1472]4368
[2]4369                                $i++;
4370                        }
4371                        $j++;
[51]4372                        if($mbox_stream)
4373                                imap_close($mbox_stream);
[2]4374                }
[1472]4375
[2]4376                return $return;
4377        }
[3923]4378
4379
[1709]4380        function mobile_search($params)
4381        {
4382                include("class.imap_attachment.inc.php");
4383                $imap_attachment = new imap_attachment();
4384                $criterias = array ("TO","SUBJECT","FROM","CC");
4385                $return = array();
[3589]4386                if(!isset($params['folder'])) {
4387                        $folder_params = array("noSharedFolders"=>1);
4388                        if(isset($params['folderType']))
4389                                $folder_params['folderType'] = $params['folderType'];
4390                        $folders = $this->get_folders_list($folder_params);
4391                }
4392                else
4393                        $folders = array(0=>array('folder_id'=>$params['folder']));
[1709]4394                $num_msgs = 0;
[3923]4395                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
4396                $return["msgs"] = array();
4397               
4398                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
[1709]4399                foreach($folders as $id =>$folder)
4400                {
4401                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
4402                                foreach($criterias as $criteria_fixed)
[3923]4403                                {
4404                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
4405
[3573]4406                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
[3923]4407
4408                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
[1709]4409                                       
4410                                        if ($messages == ''){
4411                                                if($mbox_stream)
4412                                                        imap_close($mbox_stream);
4413                                                continue;       
4414                                        }
[3923]4415                                       
[1709]4416                                        foreach($messages as $msg_number)
[3923]4417                                        {
[1709]4418                                                $temp = $this->get_info_head_msg($msg_number);
4419                                                if(!$temp)
4420                                                        return false;
[3573]4421                                                $temp['msg_folder'] = $folder['folder_id'];
[3923]4422                                                $return["msgs"][$num_msgs] = $temp;
[1709]4423                                                $num_msgs++;
4424                                        }
[3923]4425
[1709]4426                                        if($mbox_stream)
4427                                                imap_close($mbox_stream);
4428                                }
[3923]4429                        }
[1709]4430                }
[3923]4431
4432                if(!function_exists("cmp_date")) {
4433                        function cmp_date($obj1, $obj2){
4434                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
4435                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
4436                        }
4437                }
4438                usort($return["msgs"], "cmp_date");
4439                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
4440                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
[4560]4441                $return["msgs"]['num_msgs'] = $num_msgs;
[3923]4442               
[1709]4443                return $return;
4444        }
[1472]4445
[2]4446        function delete_and_show_previous_message($params)
4447        {
4448                $return = $this->get_info_previous_msg($params);
[1472]4449
[2]4450                $params_tmp1 = array();
4451                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
4452                $params_tmp1['folder'] = $params['msg_folder'];
4453                $return_tmp1 = $this->delete_msg($params_tmp1);
[1472]4454
[2]4455                $return['msg_number_deleted'] = $return_tmp1;
[1472]4456
[2]4457                return $return;
4458        }
[1472]4459
4460
[2]4461        function automatic_trash_cleanness($params)
4462        {
4463                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
4464                $criteria =  'BEFORE "'.$before_date.'"';
[325]4465                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[3018]4466                // Free others requests
4467                session_write_close();
[2]4468                $messages = imap_search($mbox_stream, $criteria, SE_UID);
4469                if (is_array($messages)){
4470                        foreach ($messages as $msg_number){
4471                                imap_delete($mbox_stream, $msg_number, FT_UID);
4472                        }
4473                }
[51]4474                if($mbox_stream)
4475                        imap_close($mbox_stream, CL_EXPUNGE);
[2]4476                return $messages;
4477        }
4478//      Fix the search problem with special characters!!!!
4479        function remove_accents($string) {
[1472]4480                return strtr($string,
4481                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]4482                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
4483        }
4484
[4795]4485        function make_search_date($date,$before = false){
4486
[1622]4487            //TODO: Adaptar a data de acordo com o locale do sistema.
4488            list($day,$month,$year) = explode("/", $date);
[4795]4489            $before?$day=(int)$day+1:$day=(int)$day;
4490            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
4491            $search_date = date('d-M-Y',$timestamp);
[1622]4492            return $search_date;
4493
[4795]4494        }
[1622]4495
[3843]4496        function search_msg( $params = false )
4497        {
4498                $mbox_stream = "";
4499               
4500                if(strpos($params['condition'],"#")===false)
4501                { //local messages
4502                        $search=false;
4503                }
4504                else
4505                {
4506                        $search = explode(",",$params['condition']);
4507                }
4508               
4509                $params['page'] = $params['page'] * 1;
[689]4510
[3843]4511            if( is_array($search) )
4512            {
4513                        $search = array_unique($search); // Remove duplicated folders
4514                        $search_criteria = '';
4515                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
4516                        foreach($search as $tmp)
4517                        {
4518                                $tmp1 = explode("##",$tmp);
4519                                $sum = 0;
4520                                $name_box = $tmp1[0];
4521                                unset($filter);
4522                                foreach($tmp1 as $index => $criteria)
4523                                {
4524                                        if ($index != 0 && strlen($criteria) != 0)
4525                                        {
4526                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
4527                                                $filter .= " ".$filter_array[0];
4528                                                if (strlen($filter_array[1]) != 0)
4529                                                {
4530                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
4531                                                                 trim($filter_array[0]) != 'SINCE' &&
4532                                                                 trim($filter_array[0]) != 'ON')
4533                                                        {
4534                                                            $filter .= '"'.$filter_array[1].'"';
[5134]4535                                                        }else if(trim($filter_array[0]) == 'BEFORE' ){
[4795]4536                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
4537                                                        }else{
4538                                                            $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
4539                                                        }
[3843]4540                                                }
4541                                        }
4542                                }
4543                               
[5134]4544                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
[3843]4545                                $filter = $this->remove_accents($filter);
[1472]4546
[3843]4547                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
4548                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
4549                                {
4550                                        $folder_name = explode($this->imap_delimiter,$name_box);
4551                                        $this->ldap = new ldap_functions();
4552                                       
4553                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
4554                                        {
4555                                                $folder_name[1] = $cn;
4556                                        }
4557                                        $folder_name = implode($this->imap_delimiter,$folder_name);
[3391]4558                                }
[3843]4559                                else
[5134]4560                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
[3843]4561                               
4562                                if(!is_resource($mbox_stream))
4563                                        $mbox_stream = $this->open_mbox($name_box);
4564                                else
4565                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
4566                               
4567                                if (preg_match("/^.?\bALL\b/", $filter))
4568                                {
4569                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
4570                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
4571                                           
4572                                        foreach($all_criterias as $criteria_fixed)
4573                                        {
4574                                                $_filter = $criteria_fixed . substr($filter,4);
4575                                               
4576                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
4577                                               
4578                                                if(is_array($search_criteria))
4579                                                {
4580                                                        foreach($search_criteria as $new_search)
4581                                                        {
4582                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
[5134]4583                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
[4795]4584                                                                $elem['uid'] = $new_search;
4585                                                                /* compare dates in ordering */
4586                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
[3843]4587                                                                $retorno[] = $elem;
4588                                                        }
4589                                                }
4590                                        }
4591                                }
[4068]4592                                else{
[5134]4593                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
[4941]4594                                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
4595                                    {
4596                                        if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
4597                                        {
4598                                            $num_msgs = imap_num_msg($mbox_stream);
4599                                            $flagged_msgs = array();
4600                                            for ($i=$num_msgs; $i>0; $i--)
[4068]4601                                            {
[4941]4602                                                $iuid = @imap_uid($this->mbox,$i);
4603                                                $header = $this->get_header($iuid);
4604                                                if(trim($header->Flagged))
4605                                                {
4606                                                        $flagged_msgs[$i] = $iuid;
4607                                                }
[4068]4608                                            }
[5134]4609                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
[4941]4610                                            {
[5134]4611                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
4612                                                    foreach($arry_diff as $msg)
[4941]4613                                            {
[5134]4614                                                        $search_criteria[] = $msg;
[4941]4615                                            }
4616                                        }
[5134]4617                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
[4941]4618                                        {
[5134]4619                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
[4941]4620                                        }
4621                                    }
4622                                    }
4623
4624                                    if( is_array( $search_criteria) )
4625                                    {
4626                                        foreach($search_criteria as $new_search)
4627                                        {
4628                                            $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
[5134]4629                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
[4941]4630                                            $elem['uid'] = $new_search;
4631                                            /* compare dates in ordering */
4632                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
4633                                            $retorno[] = $elem;
4634                                        }
4635                                    }
[3843]4636                                }
4637                        }
4638                }
4639               
4640                if($mbox_stream)
4641                {
4642                        imap_close($mbox_stream);
[3803]4643            }
[3843]4644           
[3803]4645            $num_msgs = count($retorno);
[3223]4646
[3803]4647            /* Comparison functions, descendent is ascendent with parms inverted */
[4515]4648            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
[3803]4649            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
[3391]4650
[3803]4651            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
4652            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
4653
4654            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
4655            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
4656
4657            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
4658            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
4659
4660            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
4661            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
4662
[3843]4663            usort( $retorno, $params['sort_type']);
4664            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
4665           
4666            $arrayRetorno['num_msgs']   =  $num_msgs;
4667            $arrayRetorno['data']               =  $pageret;
[4158]4668            $arrayRetorno['currentTab'] =  $params['current_tab'];
[3803]4669
[3843]4670                if ($pageret)
4671                {
4672                        return $arrayRetorno;
4673                }
4674                else
4675                {
4676                        return 'none';
4677                }
[2]4678        }
[1472]4679
[3803]4680        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
[271]4681        {
[828]4682                $header = $this->get_header($uid_msg);
[3803]4683                require_once("class.imap_attachment.inc.php");
[828]4684                $imap_attachment = new imap_attachment();
4685                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
4686                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
4687                $flag = $header->Unseen
4688                        .$header->Recent
4689                        .$header->Flagged
4690                        .$header->Draft
4691                        .$header->Answered
4692                        .$header->Deleted
4693                        .$attachments;
4694
4695
[163]4696                $subject = $this->decode_string($header->fetchsubject);
4697                $from = $header->from[0]->mailbox;
[2]4698                if($header->from[0]->personal != "")
4699                        $from = $header->from[0]->personal;
[3843]4700                $ret_msg['from']        = $this->decode_string($from);
4701                $ret_msg['subject']     = $subject;
4702                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
4703                $ret_msg['size']        = $header->Size;
4704                $ret_msg['flag']        = $flag;
[1472]4705                return $ret_msg;
4706        }
[3391]4707
4708
4709        function size_msg($size){
4710                $var = floor($size/1024);
4711                if($var >= 1){
4712                        return $var." kb";
4713                }else{
4714                        return $size ." b";
4715                }
4716        }
4717       
[2]4718        function ob_array($the_object)
4719        {
4720           $the_array=array();
4721           if(!is_scalar($the_object))
4722           {
4723               foreach($the_object as $id => $object)
4724               {
4725                   if(is_scalar($object))
4726                   {
4727                       $the_array[$id]=$object;
4728                   }
4729                   else
4730                   {
4731                       $the_array[$id]=$this->ob_array($object);
4732                   }
4733               }
4734               return $the_array;
4735           }
4736           else
4737           {
4738               return $the_object;
4739           }
4740        }
[1472]4741
[2]4742        function getacl()
4743        {
4744                $this->ldap = new ldap_functions();
[1472]4745
[2]4746                $return = array();
[1472]4747                $mbox_stream = $this->open_mbox();
[2]4748                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]4749
[2]4750                $i = 0;
4751                foreach ($mbox_acl as $user => $acl)
4752                {
4753                        if ($user != $this->username)
4754                        {
4755                                $return[$i]['uid'] = $user;
4756                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
4757                        }
4758                        $i++;
4759                }
4760                return $return;
4761        }
[1472]4762
[2]4763        function setacl($params)
4764        {
4765                $old_users = $this->getacl();
4766                if (!count($old_users))
4767                        $old_users = array();
[1472]4768
[2]4769                $tmp_array = array();
4770                foreach ($old_users as $index => $user_info)
4771                {
4772                        $tmp_array[$index] = $user_info['uid'];
4773                }
4774                $old_users = $tmp_array;
[1472]4775
[2]4776                $users = unserialize($params['users']);
4777                if (!count($users))
4778                        $users = array();
[1472]4779
[2]4780                //$add_share = array_diff($users, $old_users);
4781                $remove_share = array_diff($old_users, $users);
4782
4783                $mbox_stream = $this->open_mbox();
4784
4785                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4786                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4787
4788                /*if (count($add_share))
4789                {
4790                        foreach ($add_share as $index=>$uid)
4791                        {
4792                        if (is_array($mailboxes_list))
4793                        {
4794                        foreach ($mailboxes_list as $key => $val)
4795                        {
4796                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4797                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
4798                        }
4799                        }
4800                        }
4801                }*/
[1472]4802
[2]4803                if (count($remove_share))
4804                {
4805                        foreach ($remove_share as $index=>$uid)
4806                        {
[4741]4807                            if (is_array($mailboxes_list))
4808                            {
4809                                foreach ($mailboxes_list as $key => $val)
4810                                {
4811                                    $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4812                                    $folder = str_replace("&-", "&", $folder);
4813                                    imap_setacl ($mbox_stream, $folder, "$uid", "");
4814                                }
4815                            }
[1472]4816                        }
[2]4817                }
[1472]4818
[2]4819                return true;
4820        }
[1472]4821
[2]4822        function getaclfromuser($params)
4823        {
4824                $useracl = $params['user'];
[1472]4825
[2]4826                $return = array();
4827                $return[$useracl] = 'false';
[1472]4828                $mbox_stream = $this->open_mbox();
[2]4829                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]4830
[2]4831                foreach ($mbox_acl as $user => $acl)
4832                {
4833                        if (($user != $this->username) && ($user == $useracl))
4834                        {
4835                                $return[$user] = $acl;
4836                        }
4837                }
4838                return $return;
4839        }
4840
4841        function getacltouser($user)
4842        {
4843                $return = array();
4844                $mbox_stream = $this->open_mbox();
[325]4845                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4846                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
4847                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
4848                if(substr($user,0,4) != 'user')
[449]4849                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]4850                else
[5134]4851                  $mbox_acl = @imap_getacl($mbox_stream, $user);
4852                if(isset($mbox_acl[$this->username]))
[2]4853                return $mbox_acl[$this->username];
[5134]4854                else
4855                    return '';
[2]4856        }
4857
[1472]4858
[2]4859        function setaclfromuser($params)
4860        {
4861                $user = $params['user'];
4862                $acl = $params['acl'];
[1472]4863
[2]4864                $mbox_stream = $this->open_mbox();
4865
4866                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4867                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4868
4869                if (is_array($mailboxes_list))
4870                {
4871                        foreach ($mailboxes_list as $key => $val)
4872                        {
[449]4873                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
4874                                $folder = str_replace("&-", "&", $folder);
[2]4875                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
4876                                {
[449]4877                                        $return = imap_last_error();
[2]4878                                }
4879                        }
4880                }
[449]4881                if (isset($return))
4882                        return $return;
4883                else
4884                        return true;
[2]4885        }
[1472]4886
[51]4887        function download_attachment($msg,$msgno)
4888        {
[1472]4889                $array_parts_attachments = array();
[3289]4890                //$array_parts_attachments['names'] = '';
[689]4891                include_once("class.imap_attachment.inc.php");
[1472]4892                $imap_attachment = new imap_attachment();
4893
[51]4894                if (count($msg->fname[$msgno]) > 0)
4895                {
4896                        $i = 0;
4897                        foreach ($msg->fname[$msgno] as $index=>$fname)
4898                        {
4899                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
[1397]4900                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
[51]4901                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
4902                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
[3289]4903                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
[51]4904                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
4905                                $i++;
4906                        }
4907                }
[3289]4908                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
[51]4909                return $array_parts_attachments;
[1472]4910        }
[69]4911
[4436]4912       
4913        /**
4914        * @license   http://www.gnu.org/copyleft/gpl.html GPL
4915        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
4916        * @param     $params
4917        */
4918        function spam($params)
[69]4919        {
[4416]4920               
4921                $mbox_stream = $this->open_mbox($params['folder']);
[69]4922                $msgs_number = explode(',',$params['msgs_number']);
4923
[4416]4924                $user = Array();
4925
4926                if(substr($params['folder'], 0, 4) == 'user')
4927                {
4928                    $ldapObject = new ldap_functions();
4929
4930                    $folderArray = Array();
4931                    $folderArray = explode($this->imap_delimiter, $params['folder']);
4932
4933                    $user['name'] = $folderArray[1];
4934                    $user['email'] = $ldapObject->getMailByUid($user['name']);
4935               
4936                }
4937                else
4938                {
4939                    $user['name'] = $this->username;
4940                    $user['email'] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4941                }
4942
4943                foreach($msgs_number as $msg_number)
4944                {
[877]4945                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
4946                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
4947                        $body = imap_body($mbox_stream, $imap_msg_number);
[69]4948                        $msg = $header . $body;
[4416]4949                        strtok($user['email'], '@');
[69]4950                        $domain = strtok('@');
4951
[4416]4952           
4953
[449]4954                        //Encontrar a assinatura do dspam no cabecalho
4955                        $v = explode("\r\n", $header);
4956                        foreach ($v as $linha){
[877]4957                                if (eregi("^Message-ID", $linha)) {
4958                                        $args = explode(" ", $linha);
4959                                        $msg_id = "'$args[1]'";
4960                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
[449]4961                                        $args = explode(" ",$linha);
4962                                        $signature = $args[1];
4963                                }
4964                        }
4965
[877]4966                        // Seleciona qual comando a ser executado
[4416]4967                        switch($params['spam']){
[449]4968                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
4969                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
4970                        }
[877]4971
[4416]4972                     
[877]4973                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
[4416]4974                        $cmd = str_replace($tags, array($user['email'], $user['name'], $domain, $signature, $msg_id), $cmd);
4975                       
[78]4976                        system($cmd);
[69]4977                }
[4416]4978
[69]4979                imap_close($mbox_stream);
4980                return false;
4981        }
[4436]4982       
4983       
[5134]4984/**
4985* Descrição do método
4986*
4987* @license    http://www.gnu.org/copyleft/gpl.html GPL
4988* @author     
4989* @sponsor    Caixa Econômica Federal
4990* @author     
4991* @param      <tipo> <$msg_number> <Número da mensagem>
4992* @return     <cabeçalho da mensagem>
4993* @access     <public>
4994*/     
[4436]4995        function get_header($msg_number)
4996        {
[4795]4997                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[535]4998                if (!is_object($header))
4999                        return false;
[1472]5000
[5134]5001                if($header->Flagged != "F" ) {
[659]5002                        $flag = preg_match('/importance *: *(.*)\r/i',
5003                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]5004                                                ,$importance);
[659]5005                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
5006                }
[1472]5007
[535]5008                return $header;
5009        }
[1000]5010
5011//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Insere emails no imap a partir do fonte do mesmo. Se o argumento timestamp for passado ele utiliza do script python
5012///expressoMail1_2/imap.py para inserir uma msg com o horário correto pois isso não é porssível com a função imap_append do php.
5013
[3911]5014    function insert_email($source,$folder,$timestamp,$flags){
[1000]5015        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
5016        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
5017        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
5018        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
5019        $imap_options = '/notls/novalidate-cert';
[5134]5020
5021       
5022        $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
5023
[1000]5024        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
[5134]5025       
5026        if(imap_last_error() === 'Mailbox already exists')
[1000]5027            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
5028        if($timestamp){
[4436]5029                        $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local)
5030                        $timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local.
[4457]5031                        /* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */
5032                        $file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
5033               
[1000]5034                $f = fopen($file,"w");
5035                fputs($f,base64_encode($source));
[4795]5036            fclose($f);
[5134]5037            $command = "python ".$_SESSION['rootPath']."/expressoMail1_2/imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
5038            $return['command']= exec($command);
[1000]5039        }else{
5040            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
5041        }
5042        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
[3872]5043                       
[1000]5044        $return['msg_no'] = $status->uidnext - 1;
[3911]5045        $return['error'] = imap_last_error();
5046        if(!$return['error'] && $flags != '' ){
[3872]5047
[3911]5048                  $flags_array=explode(':',$flags);
5049                  //"Answered","Draft","Flagged","Unseen"
5050                  $flags_fixed = "";
5051                  if($flags_array[0] == 'A')
5052                        $flags_fixed.="\\Answered ";
5053                  if($flags_array[1] == 'X')
5054                        $flags_fixed.="\\Draft ";
5055                  if($flags_array[2] == 'F')
5056                        $flags_fixed.="\\Flagged ";
5057                  if($flags_array[3] != 'U')
5058                        $flags_fixed.="\\Seen ";
[5184]5059                  if($flags_array[4] == 'F')
5060                        $flags_fixed.="\\Answered \\Draft ";
[3911]5061                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
5062                }
[5134]5063       
5064        //Ignorando erro de AUTH=Plain
5065        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN')
5066            $return['error'] = false;
5067                               
[1000]5068        if($mbox_stream)
[3911]5069            imap_close($mbox_stream);
[1000]5070        return $return;
5071    }
5072
[5134]5073        function show_decript($params,$dec=0){
[1035]5074        $source = $params['source'];
[5083]5075                 
[5134]5076        //error_log("source: $source\nversao: " . PHP_VERSION);         
5077        if ($dec == 0)
5078        {
5079            $source = str_replace(" ", "+", $source,$i);
[5083]5080                        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
5081                            if(!$source = base64_decode($source,true))
[5134]5082                    return "error ".$source."Espaï¿?os ".$i;
[5083]5083                 
5084                        }
5085                        else {
5086                            if(!$source = base64_decode($source))
[5134]5087                    return "error ".$source."Espaï¿?os ".$i;
5088            }
[1035]5089        }
[3803]5090
[1035]5091        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5092
5093                $get['msg_number'] = $insert['msg_no'];
5094                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
5095                $return = $this->get_info_msg($get);
5096                $get['msg_number'] = $params['ID'];
5097                $get['msg_folder'] = $params['folder'];
5098                $tmp = $this->get_info_msg($get);
5099                if(!$tmp['status_get_msg_info'])
5100                {
5101                        $return['msg_day']=$tmp['msg_day'];
5102                        $return['msg_hour']=$tmp['msg_hour'];
5103                        $return['fulldate']=$tmp['fulldate'];
5104                        $return['smalldate']=$tmp['smalldate'];
5105                }
5106                else
5107                {
5108                        $return['msg_day']='';
5109                        $return['msg_hour']='';
5110                        $return['fulldate']='';
5111                        $return['smalldate']='';
5112                }
5113        $return['msg_no'] =$insert['msg_no'];
5114        $return['error'] = $insert['error'];
5115        $return['folder'] = $params['folder'];
5116        //$return['acls'] = $insert['acls'];
5117        $return['original_ID'] =  $params['ID'];
5118
5119        return $return;
5120
5121    }
[1472]5122
[1000]5123//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Trata fontes de emails enviados via POST para o servidor por um xmlhttprequest, as partes codificados com
5124//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
5125
5126    function treat_base64_from_post($source){
5127            $offset = 0;
5128            do
5129            {
5130                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
5131                    {
5132                            $inicio = strpos($source, "\n\r", $inicio);
5133                            $fim = strpos($source, '--', $inicio);
5134                            if(!$fim)
5135                                    $fim = strpos($source,"\n\r", $inicio);
5136                            $length = $fim-$inicio;
5137                            $parte = substr( $source,$inicio,$length-1);
5138                            $parte = str_replace(" ", "+", $parte);
5139                            $source = substr_replace($source, $parte, $inicio, $length-1);
5140                    }
5141                    if($offset > $inicio)
5142                    $offset=FALSE;
5143                    else
5144                    $offset = $inicio;
5145            }
5146            while($offset);
5147            return $source;
5148    }
5149
5150//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
5151
5152    function unarchive_mail($params)
5153    {
5154        $dest_folder = $params['folder'];
5155        $sources = explode("#@#@#@",$params['source']);
[5134]5156        //Add user timeszone
5157        $timestamps     = $params['timestamp'] + $this->functions->CalculateDateOffset();
[3911]5158        $flags = explode("#@#@#@",$params['flags']);
[3872]5159
[5134]5160                foreach($sources as $index=>$src) {
5161                        if($src!=""){
[3911]5162                $source = $this->treat_base64_from_post($src);
[5134]5163                        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestamps,$flags[$index]);
[3911]5164            }
5165        }
[1000]5166        return $insert;
5167    }
5168
5169    function download_all_local_attachments($params)
5170    {
5171        $source = $params['source'];
5172        $source = $this->treat_base64_from_post($source);
5173        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5174        $exporteml = new ExportEml();
5175        $params['num_msg']=$insert['msg_no'];
5176        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
5177        return $exporteml->download_all_attachments($params);
5178    }
[4830]5179       
5180        /**
5181         * Método que envia um email reportando um erro no email do usuário
5182         * @license http://www.gnu.org/copyleft/gpl.html GPL
5183         * @author Prognus Software Livre (http://www.prognus.com.br)
5184         */ 
5185        function report_mail_error($params)
5186        {       
5187                $params = $params['params'];
5188                $array_params = explode(";;", $params);
5189                $id_msg   = $array_params[0];
5190                $msg_user = $array_params[1];
5191               
5192                if($msg_user == '')
5193                        $msg_user = "Sem mensagem!";
5194                         
5195                $toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
5196                 
5197                $exporteml    = new ExportEml();
5198                $mail_content = $exporteml->export_msg_data($id_msg, $msg_folder);
5199                $this->open_mbox($msg_folder); 
5200                $title = "Erro de email reportado";
5201                $body  = "<body>O usuário <strong>$toname</strong> reportou um erro na tentativa de acesso ao conteúdo do email.<br><br>Segue em anexo o fonte da mensagem" .                           " reportada.<br><br><hr><strong><u>Mensagem do usuário:</strong></u><br><br><br>" .
5202                                "$msg_user</body><br><br><hr>";
5203                             
[5134]5204                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
[4830]5205                $mailService = ServiceLocator::getService('mail');     
[5134]5206                $mailService->addStringAttachment($mail_content, 'report.eml', 'application/text');
5207                $mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body);
[4830]5208        }
5209       
[5134]5210        function array_msort($array, $cols)
5211        {
5212                $colarr = array();
5213                foreach ($cols as $col => $order) {
5214                        $colarr[$col] = array();
5215                        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
5216                }
5217                $params = array();
5218                foreach ($cols as $col => $order) {
5219                        $params[] =& $colarr[$col];
5220                        $params = array_merge($params, (array)$order);
5221                }
5222                call_user_func_array('array_multisort', $params);
5223                $ret = array();
5224                $keys = array();
5225                $first = true;
5226                foreach ($colarr as $col => $arr) {
5227                        foreach ($arr as $k => $v) {
5228                                if ($first) { $keys[$k] = substr($k,1); }
5229                                $k = $keys[$k];
5230                                if (!isset($ret[$k])) $ret[$k] = $array[$k];
5231                                $ret[$k][$col] = $array[$k][$col];
5232                        }
5233                        $first = false;
5234                }
5235               
5236                return $ret;
5237
5238        }
5239       
5240        function parseCriteriaSearchMail($search)
5241        {
5242            $criteria = '';
5243            $searchArray = explode(' ', $search);
5244
5245            foreach ($searchArray as $v)
5246                if(trim($v) !== '' )
5247                    $criteria .= 'TEXT "'.$v.'" ' ;
5248           
5249            return $criteria;
5250        }
5251       
5252        function quickSearchMail( $params )
5253        {
5254                $return = array();
5255                $return['folder'] = $params['folder'];
5256                if(!is_array($params['folder']))
5257                        $params['folder'] = array( $params['folder'] );
5258               
5259                if(!isset($params['sort']))
[5172]5260                        $params['sort'] = 'SORTDATE_REVERSE';
[5134]5261                               
5262                $params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
5263               
5264                $i = 0;         
5265                if(!isset($params['page'])) $params['page'] = 0;
5266                $end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));       
5267                $ini = $end - $this->prefs['max_email_per_page'] ;
5268                $count = 0;
5269               
5270                $search = $this->parseCriteriaSearchMail($params['search']);
5271                               
5272                foreach ($params['folder'] as $folder)
5273                {
5274                        $imap = $this->open_mbox( $folder ) ;
[5172]5275                        $msgIds = imap_sort( $imap , SORTDATE , 1 , SE_UID , $search ,'UTF-8');
[5134]5276                                               
5277                        $count += count($msgIds); 
5278                       
5279                        foreach ($msgIds as $ii => $v)
5280                        {                               
5281                                $msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) );
5282                                $return['msgs'][$i]['from'] = '';
5283                               
5284                                $from = $msg->from[0]->mailbox;
5285                                if($msg->from[0]->personal != "")
5286                                        $from = $msg->from[0]->personal;
5287                                $return['msgs'][$i]['from']     = mb_convert_encoding($this->decode_string($from), 'UTF-8');
5288                               
5289                                $return['msgs'][$i]['subject'] = ' ';
5290                               
5291                                $subject = imap_mime_header_decode($msg->subject);
5292                                foreach ($subject as $tmp)
[5189]5293                                        $return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
[5134]5294                               
[5189]5295                               
[5134]5296                                $return['msgs'][$i]['flag'] = ' ';
5297                                $return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
5298                                $return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';       
5299                                $return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';     
5300                                $return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : ''; 
5301                                $return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';   
5302                                $return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';     
5303                               
5304                                $return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset());
5305                                $return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2);
5306                            $return['msgs'][$i]['date'] =   $msg->udate;
5307                                $return['msgs'][$i]['size'] =  $msg->Size;
5308                                $return['msgs'][$i]['boxname'] = $folder;
5309                                $return['msgs'][$i]['uid'] = $v;
5310                                $i++;
5311                        }       
5312                }
5313               
5314                $return['num_msgs'] = $count;
5315               
5316                if(!isset($return['msgs']))
5317                        $return['msgs'] = array();
5318               
5319                define('SORTBOX', 69);
5320                define('SORTWHO', 2);
5321                define('SORTBOX_REVERSE', 69);
5322                define('SORTWHO_REVERSE', 2);
5323                define('SORTDATE_REVERSE', 0);
5324                define('SORTSUBJECT_REVERSE', 3);
5325                define('SORTSIZE_REVERSE', 6);
5326               
5327                switch (constant( $params['sort'] )){
5328                        case 0 : $sA = 'date'; break;
5329                        case 2 : $sA = 'from'; break;
5330                        case 69 : $sA = 'boxname'; break;
5331                        case 3 : $sA = 'subject'; break;
5332                        case 6 : $sA = 'size'; break;
5333        }
[4830]5334       
[5134]5335                       
[5172]5336                if($params['sort'] !== 'SORTDATE_REVERSE')
[5134]5337                if(strpos($params['sort'],'REVERSE') !== false)
[5172]5338                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_DESC));
5339                        else
5340                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
[5134]5341               
5342                $k = -1;
5343                $nMsgs = array();
5344               
5345                foreach ($return['msgs'] as $v)
5346                {               
5347                        $k++;
5348                        if($k < $ini || $k >= $end ) continue;                 
5349                        $nMsgs[] = $v;
5350                }
5351                $return['msgs'] = $nMsgs;
[5189]5352               
[5134]5353                $return = json_encode($return);         
5354                $return = base64_encode($return);
[4830]5355       
[5134]5356                return $return;
5357        }
5358       
[3157]5359    function get_quota_folders(){
5360
5361            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
5362            include_once("class.imapfp.inc.php");           
5363            $imapfp = new imapfp();
5364
5365            if(!$imapfp->open($this->imap_server,$this->imap_port))
5366                    return $imapfp->get_error();             
5367            if (!$imapfp->login( $this->username,$this->password ))
5368                    return $imapfp->get_error();
5369
5370            $response_array = $imapfp->get_mailboxes_size();
5371            if ($imapfp->error)
5372                    return $imapfp->get_error();
5373
5374            $data = array();
5375            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
5376            $data["quota_root"] = $quota_root;
5377
5378            foreach ($response_array as $idx=>$line) {
5379                    $line2 = str_replace('"', "", $line);
5380                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
5381                    list($folder,$size) = explode(";",$line2);
[3854]5382                    $quota_used = str_replace(")","",$size);
5383                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
[3157]5384                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
5385                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
5386                            $folder = $this->functions->getLang("Inbox");
5387                    }
5388                    else
5389                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
5390
5391                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
5392            }
5393            $imapfp->close();
5394            return $data;
5395    } 
[5134]5396   
5397    function getaclfrombox($mail)
5398        {
5399                $mailArray = explode('@', $mail);
5400                $boxacl = $mailArray[0];
5401                $return = array();
5402
5403                if(!$this->mbox)
5404                     $this->open_mbox();
5405
5406                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl);
5407
5408                foreach ($mbox_acl as $user => $acl)
5409                {
5410                        if ($user != $boxacl )
5411                            $return[$user] = $acl;
5412                }
5413                return $return;
5414        }
[2]5415}
[278]5416?>
Note: See TracBrowser for help on using the repository browser.