source: branches/2.3/expressoMail1_2/inc/class.imap_functions.inc.php @ 6702

Revision 6702, 164.8 KB checked in by brunocosta, 12 years ago (diff)

Ticket #2930 - Trata caracteres especiais que são escapado incorretamente pelo javascript.

  • 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,
16                'msgs_to_archive'                               => True
[2]17        );
18
19        var $ldap;
20        var $mbox;
21        var $imap_port;
22        var $has_cid;
23        var $imap_options = '';
24        var $functions;
[3071]25        var $prefs;
[650]26        var $foldersLimit;
[1912]27        var $imap_sentfolder;
[2]28
29        function imap_functions (){
[3226]30                $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]31                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
32                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
33                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
34                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
35                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
[1472]36                $this->functions          = new functions();
[1912]37                $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   : str_replace("*","", $this->functions->getLang("Sent"));
[2]38                $this->has_cid = false;
[3071]39                $this->prefs = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
[1472]40
[3071]41
[2]42                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
43                {
44                        $this->imap_options = '/tls/novalidate-cert';
45                }
46                else
47                {
48                        $this->imap_options = '/notls/novalidate-cert';
49                }
50        }
51        // BEGIN of functions.
[3391]52        function open_mbox($folder = False,$force_die=true)
[2]53        {
[3394]54                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[828]55                if (is_resource($this->mbox))
[3394]56                {
57                     if ($force_die)
58                     {
59                        @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()))));
60                     }
61                     else
62                        {
63                            @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder);
64                        }
65                }
66                else
67                    {
68                        if($force_die)
69                        {
70                            $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()))));
71                        }
72                        else
73                            {
74                                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password);
75                            }
76                       
77                    }
78                    return $this->mbox;
[2]79         }
80
[504]81        function parse_error($error){
82                // This error is returned from Imap.
83                if(strstr($error,'Connection refused')) {
84                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
85                }
86                // This error is returned from Postfix.
87                elseif(strstr($error,'message file too big')) {
[1264]88                        return str_replace("%1",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'],$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));
[504]89                }
[628]90                elseif(strstr($error,'virus')) {
91                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
92                }
[504]93                // This condition verifies if SESSION is expired.
[1472]94                elseif(!count($_SESSION))
[504]95                        return "nosession";
96
97                return $error;
98        }
[1472]99
[2]100        function get_range_msgs2($params)
[4025]101        {
[4044]102                // Free others requests
103                session_write_close();
[5000]104                $folder = urldecode($params['folder']);
[4162]105                $msg_range_begin = $params['msg_range_begin'];
106                $msg_range_end = $params['msg_range_end'];
107                $sort_box_type = $params['sort_box_type'];
108                $sort_box_reverse = $params['sort_box_reverse'];
109                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[1472]110
[4044]111                $folder                         = $params['folder'];
112                $msg_range_begin        = $params['msg_range_begin'];
113                $msg_range_end          = $params['msg_range_end'];
114                $sort_box_type          = $params['sort_box_type'];
115                $sort_box_reverse       = $params['sort_box_reverse'];
116                $search_box_type        = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
117
118                if( !$this->mbox || !is_resource( $this->mbox ) )
[3392]119                        $this->mbox = $this->open_mbox($folder);
120
[4044]121        $return = array();
[4050]122
[4169]123        $return['folder'] = $folder;
124
[4044]125        //Para enviar o offset entre o timezone definido pelo usuário e GMT
126        $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
[3392]127
[4162]128        if(!$search_box_type || $search_box_type=="UNSEEN" || $search_box_type=="SEEN") {
129                        $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]130
131
[4162]132                        $return['tot_unseen'] = $search_box_type == "SEEN" ? 0 : $msgs_info->unseen;
[828]133
[4162]134                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
[3392]135
[4162]136                        $num_msgs = ($search_box_type=="UNSEEN") ? $msgs_info->unseen : (($search_box_type=="SEEN") ? ($msgs_info->messages - $msgs_info->unseen) : $msgs_info->messages);
137
[4025]138                        $i = 0;
[4162]139                        if(is_array($sort_array_msg)){
140                                foreach($sort_array_msg as $msg_number => $value)
141                                {
142                                        $temp = $this->get_info_head_msg($msg_number);
[4168]143                                        $temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
[4162]144                                        if(!$temp)
145                                                return false;
[4025]146
[4162]147                                        $return[$i] = $temp;
148                                        $i++;
149                                }
150                        }
151                        $return['num_msgs'] =  $num_msgs;
152                }
153                else {
154                        $num_msgs = imap_num_msg($this->mbox);
155                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
[828]156
[4044]157
[4162]158                        $return['tot_unseen'] = 0;
159                        $i = 0;
[4044]160
[4162]161                        if(is_array($sort_array_msg)){
162
163                            foreach($sort_array_msg as $msg_number => $value)
164                            {
165                                $temp = $this->get_info_head_msg($msg_number);
166                                if(!$temp)
167                                    return false;
168
169                                if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
170                                                $return['tot_unseen']++;
171                                        }
172
173                                if($i <= ($msg_range_end-$msg_range_begin))
174                                    $return[$i] = $temp;
175                                $i++;
176                            }
177                        }
178                        $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
179                }
180                return $return;
[4044]181    }
182
183        function get_info_head_msg($msg_number)
184        {
[689]185                $head_array = array();
186                include_once("class.imap_attachment.inc.php");
[828]187
[3271]188                $imap_attachment = new imap_attachment();
189                //if ($this->prefs['use_important_flag'] )
190                //{
[3071]191                        /*Como eu preciso do atributo Importance para saber se o email é
192                         * importante ou não, uso abaixo a função imap_fetchheader e busco
193                         * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
194                         * duas vezes e de duas formas diferentes, mas em contrapartida, eu
195                         * não preciso reimplementar o método utilizando o fetchheader.
196                         * Como as mensagens são renderizadas em um número pequeno por vez,
197                         * não parece ter perda considerável de performance.
198                         */
[830]199
[3071]200                        $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
201                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[3271]202                //}
203                // Reimplementado código para identificação dos e-mails assinados e cifrados
204                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
205                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
206                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
[1174]207
[689]208                $header = $this->get_header($msg_number);
[828]209                if (!is_object($header))
210                        return false;
[689]211                $head_array['Recent'] = $header->Recent;
212                $head_array['Unseen'] = $header->Unseen;
213                if($header->Answered =='A' && $header->Draft == 'X'){
214                        $head_array['Forwarded'] = 'F';
[2]215                }
[689]216                else {
217                        $head_array['Answered'] = $header->Answered;
[828]218                        $head_array['Draft']    = $header->Draft;
[46]219                }
[689]220                $head_array['Deleted'] = $header->Deleted;
221                $head_array['Flagged'] = $header->Flagged;
222                $head_array['msg_number'] = $msg_number;
[3057]223                $head_array['udate'] = $header->udate;
[3923]224                $head_array['offsetToGMT'] = $this->functions->CalculateDateOffset();
[828]225
[3923]226                $msgTimestamp = $header->udate + $head_array['offsetToGMT'];
227                $head_array['timestamp'] = $msgTimestamp;
228               
[3499]229                $date_msg = gmdate("d/m/Y",$msgTimestamp);
230//              if (date("d/m/Y") == $date_msg)
231//                      $return['udate'] = $header->udate;
232//              else
233
234                if (date("d/m/Y") == $date_msg) //no dia
235                {
236                        $head_array['smalldate'] = gmdate("H:i",$msgTimestamp);
237                }
238                else
239                {
240                        $head_array['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
241                }
242
[689]243                $from = $header->from;
244                $head_array['from'] = array();
[1740]245                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
[689]246                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
247                if(!$head_array['from']['name'])
248                        $head_array['from']['name'] = $head_array['from']['email'];
249                $to = $header->to;
250                $head_array['to'] = array();
[3831]251                if($to[1] && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
252                        $head_array['to']['name'] = $head_array['to']['email'] = NULL;
253                }
254                else {
255                        $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
256                        $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
257                        $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
258                        if(!$head_array['to']['name'])
259                                $head_array['to']['name'] = $head_array['to']['email'];
260                }
[3777]261                $cc = $header->cc;
[3831]262                $cco = $header->bcc;
[3777]263                if ( ($cc) && (!$head_array['to']['name']) ){
264                        $head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL;
265                        $head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host;
266                        if(!$head_array['to']['name'])
267                                $head_array['to']['name'] = $head_array['from']['email'];
268                }
[3831]269                else if ( ($cco) && (!$head_array['to']['name']) ){
270                        $head_array['to']['name'] = ( isset( $cco[0]->personal ) ) ? $this->decode_string($cco[0]->personal) : NULL;
271                        $head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host;
272                        if(!$head_array['to']['name'])
273                                $head_array['to']['name'] = $head_array['from']['email'];
274                }
[1751]275                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
[828]276
[689]277                $head_array['Size'] = $header->Size;
[828]278
[689]279                $head_array['attachment'] = array();
280                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[828]281
[689]282                return $head_array;
[2]283        }
[828]284
[2]285        function decode_string($string)
[1472]286        {
287
[2]288                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
289                {
[1740]290                        $return = '';
[2]291                        $tmp = imap_mime_header_decode($string);
292                        foreach ($tmp as $tmp1)
293                                $return .= $this->htmlspecialchars_encode($tmp1->text);
[1472]294
[3560]295                        $return = str_replace("\t", "", $return);
[2]296                        return $return;
297                }
298                else if (strpos(strtolower($string), '=?utf-8') !== false)
299                {
[1401]300                        $elements = imap_mime_header_decode($string);
301
302                        for($i = 0;$i < count($elements);$i++)
303                        {
[1384]304                                $charset = strtolower($elements[$i]->charset);
[1401]305                                $text = $elements[$i]->text;
306
307                                if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
308                                {
[1384]309                                $decoded .= $this->functions->utf8_to_ncr($text);
310                        }
311                                else
[1401]312                                {
313                                        if( strcasecmp($charset,"default") )
314                                                $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
315                                        else
316                                                $decoded .= $this->htmlspecialchars_encode($text);
317                                }
[1384]318                        }
[2]319                        return $decoded;
320                }
321                else
322                        return $this->htmlspecialchars_encode($string);
323        }
[615]324        /**
325        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
326        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
327        */
[5014]328        function import_msgs($params)
329        {
330            //abre a caixa de mensagem
331            if(!$this->mbox)
332                $this->mbox = $this->open_mbox();
[1472]333
[5014]334            //cria o diretório temporário de importação se for para importar direto para a pasta local
335            if( preg_match('/local_/', $params["folder"]) )
336            {
337                // PLEASE, BE CAREFULL!!! YOU SHOULD USE EMAIL CONFIGURATION VALUES (EMAILADMIN MODULE)
338                $tmp_box = mb_convert_encoding('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'].$this->imap_delimiter.'tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
339                if ( ! imap_createmailbox( $this -> mbox,"{".$this -> imap_server."}$tmp_box" ) )
340                    return array( 'error' =>  $this->functions->getLang('Import to Local : fail...'));
341                imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
342                $params["folder"] = $tmp_box;
343            }
344            $params["folder"] = mb_convert_encoding($params["folder"], "UTF7-IMAP","ISO_8859-1");
[615]345
[5014]346            //testa se o arquivo importado já não supera o tamanho da cota de disco
347            $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
348            if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size'])
349                return array( 'error' => $this->functions->getLang("fail in import:") . " " . $this->functions->getLang("Over quota"));
350           
351            $ids = array();
352            $errors = array();
353            $filename = $params['FILES'][0]['name'];
354           
355            $strFileExtension = substr($filename, strlen($filename) - 4);
356            $folder = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"];
357            switch ($strFileExtension)
358            {
359                 case ".eml":
360                    //reconstrói o email
361                    $email = implode("", file($params['FILES'][0]['tmp_name']));
362                    //coloca o email na pasta selecionada
363                    $status = @imap_append($this->mbox, $folder, $email);
364                    if($status)
365                    {
366                        $status = imap_status($this->mbox, $folder, SA_UIDNEXT);
367                        $ids[] = $status->uidnext - 1;
368                    }
369                    else
370                    {
371                        $error[] = imap_last_error();
372                    }
373                    break;
374                case ".zip":
375                    $zip = zip_open($params['FILES'][0]['tmp_name']);
376               
377                    if ($zip) {
378                        while ($zip_entry = zip_read($zip))
379                        {
380                            $filename = zip_entry_name($zip_entry);
381                            if (substr($filename, strlen($filename) - 4) == '.eml')
382                            {
383                                if (zip_entry_open($zip, $zip_entry, "r"))
384                                {
385                                    $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
386                                    $status = @imap_append($this->mbox, $folder, $email);
387                                    if($status)
388                                    {
389                                        $status = imap_status($this->mbox, $folder, SA_UIDNEXT);
390                                        $ids[] = $status->uidnext - 1;
391                                    }
392                                    else
393                                    {
394                                        $error[] = imap_last_error();
395                                    }
396                                    zip_entry_close($zip_entry);
397                                }
398                            }
399                        }
400                        zip_close($zip);
401                    }
402                    break;
403                default:
404                    if ( isset( $tmp_box ) )
405                        imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
406                    $error[] = $this->functions->getLang("wrong file format");
407            }
408           
409            if(count($errors)>0)
410            {
411                return array("error" => $this->functions->getLang("fail in import:") . "\n" . implode("\n", $errors));
412            }
413            else
414            {
415                return implode(",", $ids);
416                //return $this->functions->getLang("The import was executed successfully.");
417            }
418                           
[1000]419        }
420        /*
[613]421                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
422                a primeira parte do e-mail, que é o texto, sem anexos.
423                O método considera que o email é multpart.
424        */
425        function remove_attachments($params) {
426                include_once("class.message_components.inc.php");
427                if(!$this->mbox || !is_resource($this->mbox))
428                        $this->mbox = $this->open_mbox($params["folder"]);
429                $return["status"] = true;
430                $header = "";
[1472]431
[613]432                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
433                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
434                        $head1 = explode(":",$head);
[1472]435                        if ( (strtoupper($head1[0]) == "TO") ||
[3566]436                                        (strtoupper($head1[0]) == "FROM") ||
437                                        (strtoupper($head1[0]) == "SUBJECT") ||
438                                        (strtoupper($head1[0]) == "DATE") )
439                                $header .= $head."\r\n";
[613]440                }
[1472]441
[613]442                $msg = &new message_components($this->mbox);
[1472]443                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
444                                                             Então uso essa classe para verificar a codificação e o charset,
[613]445                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
[1472]446
[3566]447                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][0]);
448                $all_body_encoding = $msg->encoding[$params["msg_num"]][0];
449                $all_body_charset = $msg->charset[$params["msg_num"]][0];
450               
451                if($all_body_type=='multipart/alternative') {
452                        if(strtolower($msg->file_type[$params["msg_num"]][2]=='text/html') &&
453                                        $msg->pid[$params["msg_num"]][2] == '1.2') {
454                                $body_part_to_show = '1.2';
455                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][2]);
456                                $all_body_encoding = $msg->encoding[$params["msg_num"]][2];
457                                $all_body_charset = $msg->charset[$params["msg_num"]][2];
458                        }
459                        else {
460                                $body_part_to_show = '1.1';
461                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][1]);
462                                $all_body_encoding = $msg->encoding[$params["msg_num"]][1];
463                                $all_body_charset = $msg->charset[$params["msg_num"]][1];
464                        }
465                }
466                else
467                        $body_part_to_show = '1';
468
[1319]469                $status = imap_append($this->mbox,
[613]470                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
471                                        $header.
[3566]472                                        "Content-Type: ".$all_body_type."; charset = \"".$all_body_charset."\"".
[613]473                                        "\r\n".
[3566]474                                        "Content-Transfer-Encoding: ".$all_body_encoding.
475                                        "\r\n".
476                                        "\r\n".
[613]477                                        str_replace("\n","\r\n",$this->decodeBody(
[3566]478                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
479                                                        $all_body_encoding, $all_body_charset
[1472]480                                                        )
[1319]481                                        ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos.
[1472]482
[1319]483                if(!$status)
484                {
[613]485                        $return["status"] = false;
486                        $return["msg"] = lang("error appending mail on delete attachments");
487                }
[1319]488                else
489                {
490                        $status = imap_status($this->mbox, "{".$this->imap_server.":".$this->imap_port."}".$params['folder'], SA_UIDNEXT);
[1472]491                        $return['msg_no'] = $status->uidnext - 1;
[1319]492                        imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"]));
493                        imap_expunge($this->mbox);
494                }
[1472]495
[613]496                return $return;
[1472]497
[613]498        }
[1518]499       
500        function msgs_to_archive($params) {
501               
502                $folder = $params['folder'];
[1931]503                $all_ids = $this-> get_msgs($folder, 'SORTARRIVAL', false, 0,-1,-1);
[613]504
[1518]505                $messages_not_to_copy = explode(",",$params['mails']);
506                $ids = array();
507               
[1931]508                $cont = 0;
509               
[1518]510                foreach($all_ids as $each_id=>$value) {
[1931]511                        if(!in_array($each_id,$messages_not_to_copy)) {
[1518]512                                array_push($ids,$each_id);
[1931]513                                $cont++;
514                        }
515                        if($cont>=100)
516                                break;
[1518]517                }
518
519                if (empty($ids))
520                        return array();
521
522                $params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
523               
524               
525                return $this->get_info_msgs($params);
526               
527               
528        }
529
[689]530/**
[1472]531         *
532         * @return
[689]533         * @param $params Object
534         */
535        function get_info_msgs($params) {
536                include_once("class.exporteml.inc.php");
537                $return = array();
538                $new_params = array();
539                $attach_params = array();
540                $new_params["msg_folder"]=$params["folder"];
541                $attach_params["folder"] = $params["folder"];
542                $msgs = explode(",",$params["msgs_number"]);
543                $exporteml = new ExportEml();
[1382]544                $unseen_msgs = array();
[689]545                foreach($msgs as $msg_number) {
546                        $new_params["msg_number"] = $msg_number;
547                        //ini_set("display_errors","1");
548                        $msg_info = $this->get_info_msg($new_params);
549
550                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
551                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
552
553                        $attach_params["num_msg"] = $msg_number;
554                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
555                        $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
556                        imap_close($this->mbox);
557                        $this->mbox=false;
558                        array_push($return,serialize($msg_info));
[1472]559
[1388]560                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
[1472]561                                        array_push($unseen_msgs,$msg_number);
562                        }
563                }
[1382]564                if($unseen_msgs){
565                        $msgs_list = implode(",",$unseen_msgs);
566                        $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
[1472]567                        $this->set_messages_flag($array_msgs);
[689]568                }
[1472]569
[689]570                return $return;
571        }
572
[2]573        function get_info_msg($params)
574        {
[51]575                $return = array();
[2]576                $msg_number = $params['msg_number'];
[3427]577                if(@preg_match('(.+)(_[a-zA-Z0-9]+)',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.
[1969]578                        $msg_number = $matches[1];
579                        $plus_id = $matches[2];
580                }
581                else {
582                        $plus_id = '';
583                }
[1724]584                $msg_folder = urldecode($params['msg_folder']);
[1472]585
[411]586                if(!$this->mbox || !is_resource($this->mbox))
[1472]587                        $this->mbox = $this->open_mbox($msg_folder);
[535]588                $header = $this->get_header($msg_number);
[205]589                if (!$header) {
[1472]590                        $return['status_get_msg_info'] = "false";
[205]591                        return $return;
592                }
[1472]593
[828]594                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
595
[51]596                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
[1707]597               
598                $body = $return_get_body['body'];
[1808]599
[1035]600                if($return_get_body['body']=='isCripted'){
601                        $exporteml = new ExportEml();
602                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
603                        $return['body']                 = "";
604                        $return['attachments']  =  "";
605                        $return['thumbs']               =  "";
606                        $return['signature']    =  "";
607                        //return $return;
608                }else{
[3576]609            $return['body']             = $body;
610            $return['attachments']      = $return_get_body['attachments'];
611            $return['thumbs']           = $return_get_body['thumbs'];
612            $return['signature']        = $return_get_body['signature'];
[1707]613                }
[4869]614
[3798]615                $flag = preg_match('/importance *: *(.*)\r/i', $header_, $importance);
616                $return['Importance'] = ($flag == 0) ? "Normal" : $importance[1];
[1707]617
[3018]618                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
[828]619                if (preg_match($pattern, $header_, $fields))
620                {
[3018]621                        if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
622                                $return['DispositionNotificationTo'] = "<".$matches[0].">";
623                        }
[2]624                }
[828]625
[2]626                $return['Recent']       = $header->Recent;
627                $return['Unseen']       = $header->Unseen;
[1472]628                $return['Deleted']      = $header->Deleted;
[2]629                $return['Flagged']      = $header->Flagged;
630
631                if($header->Answered =='A' && $header->Draft == 'X'){
632                        $return['Forwarded'] = 'F';
633                }
[1472]634
[2]635                else {
636                        $return['Answered']     = $header->Answered;
[1472]637                        $return['Draft']        = $header->Draft;
[2]638                }
639
[1969]640                $return['msg_number'] = $msg_number.$plus_id;
[2]641                $return['msg_folder'] = $msg_folder;
[1472]642
[3798]643                $offset = $this->functions->CalculateDateOffset();
644                $msgTimestamp = $header->udate + $offset;
[3493]645
646                $date_msg = gmdate("d/m/Y",$msgTimestamp);
[3499]647//              if (date("d/m/Y") == $date_msg)
648//                      $return['udate'] = $header->udate;
649//              else
650                $return['udate'] = $header->udate;
[1472]651
652                $return['msg_day'] = $date_msg;
[3493]653                $return['msg_hour'] = gmdate("H:i",$msgTimestamp);
[1472]654
[2]655                if (date("d/m/Y") == $date_msg) //no dia
656                {
[3493]657                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimestamp);
658                        $return['smalldate'] = gmdate("H:i",$msgTimestamp);
[605]659
[4478]660                        $timestamp_now = strtotime("now") + $offset;
[3493]661                        $timestamp_msg_time = $msgTimestamp;
662                        // $timestamp_now and $timestamp_msg_time are GMT.
[535]663                        // The variable $timestamp_diff is calculated without MailDate TZ.
[3493]664                        $timestamp_diff = $timestamp_now - $timestamp_msg_time;
[1472]665
[2]666                        if (gmdate("H",$timestamp_diff) > 0)
667                        {
[197]668                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
[2]669                        }
670                        else
671                        {
672                                if (gmdate("i",$timestamp_diff) == 0){
[197]673                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
[2]674                                }
675                                elseif (gmdate("i",$timestamp_diff) == 1){
[197]676                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
[2]677                                }
678                                else{
[197]679                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
[2]680                                }
681                        }
682                }
683                else{
[3493]684                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimestamp);
685                        $return['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
[2]686                }
[1472]687
[2]688                $from = $header->from;
689                $return['from'] = array();
[1384]690                $return['from']['name'] = $this->decode_string($from[0]->personal);
[2]691                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
692                if ($return['from']['name'])
693                {
694                        if (substr($return['from']['name'], 0, 1) == '"')
695                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
696                        else
697                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
698                }
699                else
700                        $return['from']['full'] = $return['from']['email'];
[1472]701
[2]702                // Sender attribute
703                $sender = $header->sender;
[1472]704                $return['sender'] = array();
[1384]705                $return['sender']['name'] = $this->decode_string($sender[0]->personal);
[2]706                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
707                if ($return['sender']['name'])
708                {
709                        if (substr($return['sender']['name'], 0, 1) == '"')
710                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
711                        else
712                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
713                }
714                else
715                        $return['sender']['full'] = $return['sender']['email'];
716
717                if($return['from']['full'] == $return['sender']['full'])
718                        $return['sender'] = null;
719                $to = $header->to;
720                $return['toaddress2'] = "";
721                if (!empty($to))
722                {
723                        foreach ($to as $tmp)
724                        {
725                                if (!empty($tmp->personal))
726                                {
727                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
728                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
729                                        $return['toaddress2'] .= " ";
730                                        $return['toaddress2'] .= "&lt;";
[320]731                                        if ($tmp->host != 'unspecified-domain')
732                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
733                                        else
734                                                $return['toaddress2'] .= $tmp->mailbox;
[2]735                                        $return['toaddress2'] .= "&gt;";
736                                        $return['toaddress2'] .= ", ";
737                                }
738                                else
739                                {
[320]740                                        if ($tmp->host != 'unspecified-domain')
741                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
742                                        else
743                                                $return['toaddress2'] .= $tmp->mailbox;
[2]744                                        $return['toaddress2'] .= ", ";
745                                }
746                        }
747                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
748                }
[1472]749
[2]750                $cc = $header->cc;
751                $return['cc'] = "";
752                if (!empty($cc))
753                {
754                        foreach ($cc as $tmp_cc)
755                        {
756                                if (!empty($tmp_cc->personal))
757                                {
758                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
759                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
760                                        $return['cc'] .= " ";
761                                        $return['cc'] .= "&lt;";
762                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
763                                        $return['cc'] .= "&gt;";
764                                        $return['cc'] .= ", ";
765                                }
766                                else
767                                {
768                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
769                                        $return['cc'] .= ", ";
770                                }
771                        }
772                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
773                }
774                else
775                {
776                        $return['cc'] = "";
[1472]777                }
[449]778
779                ##
780                # @AUTHOR Rodrigo Souza dos Santos
781                # @DATE 2008/09/12
782                # @BRIEF Adding the BCC field.
783                ##
784                $bcc = $header->bcc;
785                $return['bcc'] = "";
786                if (!empty($bcc))
787                {
788                        foreach ($bcc as $tmp_bcc)
789                        {
790                                if (!empty($tmp_bcc->personal))
791                                {
792                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
793                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
794                                        $return['bcc'] .= " ";
795                                        $return['bcc'] .= "&lt;";
796                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
797                                        $return['bcc'] .= "&gt;";
798                                        $return['bcc'] .= ", ";
799                                }
800                                else
801                                {
802                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
803                                        $return['bcc'] .= ", ";
804                                }
805                        }
806                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
[426]807                }
[449]808                else
809                {
810                        $return['bcc'] = "";
[1472]811                }
[426]812
[2]813                $reply_to = $header->reply_to;
814                $return['reply_to'] = "";
815                if (is_object($reply_to[0]))
816                {
817                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
818                        {
819                                if (!empty($reply_to[0]->personal))
820                                {
821                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
[41]822                                        if(!empty($personal_reply_to[0]->text)) {
823                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
824                                                $return['reply_to'] .= " ";
825                                                $return['reply_to'] .= "&lt;";
826                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
827                                                $return['reply_to'] .= "&gt;";
828                                        }
829                                        else {
830                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
831                                        }
[2]832                                }
833                                else
834                                {
835                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
836                                }
837                        }
838                }
839                $return['reply_to'] = $this->decode_string($return['reply_to']);
840                $return['subject'] = $this->decode_string($header->fetchsubject);
841                $return['Size'] = $header->Size;
[828]842                $return['reply_toaddress'] = $header->reply_toaddress;
843
[689]844                //All this is to help in local messages
[3399]845                //$return['timestamp'] = $header->udate;
[3499]846                $return['timestamp'] = $header->udate;
[689]847                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
848                $return['reply_toaddress'] = $header->reply_toaddress;
[3394]849               
850                if($return_get_body['body']=='isSigned'){
851                    imap_close($this->mbox);
852                    $new_mail = $this->show_decript($return_get_body,$dec = 1);
853                    //$new_mail['signature'] =  $return_get_body['signature'];
854                    $return['body']             = $new_mail['body'];
855                    $return['attachments']      = $new_mail['attachments'];
856                    $return['thumbs']           = $new_mail['thumbs'];
857                    $return['folder'] = $return['msg_folder'];
858                    $return['original_ID'] =  $return['msg_number'];
859                    $return['msg_folder']       = 'INBOX'.$this->imap_delimiter.'decifradas';
860                    $return['msg_number']       = $new_mail['msg_no'];
861                    //$return['signature']      = $return_get_body['signature'];
862                }
[2]863                return $return;
864        }
[1472]865
[1940]866        function get_msg_sample($msg_number)
[1752]867        {
868
[3049]869                $return = "";
[4144]870                if( (!isset($this->prefs['preview_msg_subject']) || ($this->prefs['preview_msg_subject'] != "1")) &&
871                        (!isset($this->prefs['preview_msg_tip']    ) || ($this->prefs['preview_msg_tip']     != "1")) )
[3049]872                {
873                        $return['body'] = "";
874                        return $return;
875                }
[1752]876
877                include_once("class.message_components.inc.php");
878                $msg = &new message_components($this->mbox);
[3049]879                $msg->fetch_structure($msg_number); 
[1752]880
881                if(!$msg->structure[$msg_number]->parts)
882                {
883                        $content = '';
884                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
885                        {
886                                $content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
887                        }
888                }
889                else
890                {
891                        foreach($msg->pid[$msg_number] as $values => $msg_part)
892                        {
893
894                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
895                                if($file_type == "text/plain" || $file_type == "text/html") {
896                                        $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]);
897                                        break;
898                                }
899                        }
900                }
901                $content = $this->replace_special_characters($content);
902                $tags_replace = array("<br>","<br/>","<br />");
903                $content = str_replace($tags_replace," ", $content);
904                $content = strip_tags($content);
905                $content = str_replace(array("{","}","&nbsp;"), " ", $content);
906                $content = trim($content);
[3249]907                $content = html_entity_decode(substr($content,0,300));
[1752]908                $content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
909                return $return;
910        }
911
[2]912        function get_body_msg($msg_number, $msg_folder)
913        {
914                include_once("class.message_components.inc.php");
[51]915                $msg = &new message_components($this->mbox);
[2]916                $msg->fetch_structure($msg_number);
[51]917                $return = array();
[1472]918                $return['attachments'] = $this-> download_attachment($msg,$msg_number);
[51]919                if(!$this->has_cid)
[91]920                {
[178]921                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
[91]922                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
[1472]923                }
924
[2]925                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
926                {
[4869]927                        if((preg_match("/pkcs7-mime/i", $msg->structure[$msg_number]->subtype) == 1) && (count($return['signature']) == 0 ) ){
[3018]928                                $return['body']='isCripted';
929                                return $return;
930                        }
[1035]931
[2]932                        $attachment = array(); //No attachments
[1035]933
[4869]934                        if (preg_match("/pkcs7-mime/i", $msg->structure[$msg_number]->subtype) == 1)
[3394]935                        {
936                                $return['body']='isSigned';
937                                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
938                                $header_body_array = explode('MIME-Version: 1.0', $headers);
939                                $show_pkcs7 = $header_body_array[0] . 'MIME-Version: 1.0' . chr(0x0D) .chr(0x0A). $return['signature'][0];
940                                $return['source']=$show_pkcs7;
941                                array_shift($return['signature']);
942                                $return['signature'];
943                                //$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
944                                imap_close($this->mbox);
945                                return $return;
[1035]946                        }
947
[3018]948                        $content = '';
949                        // If simple message is subtype 'html' or 'plain', then get content body.
950                        if(strtolower($msg->structure[$msg_number]->subtype) == "html" || 
951                                strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain'){
952
953                                        $content = $this->decodeBody(
954                                                imap_body( $this -> mbox, $msg_number, FT_UID ),
955                                                $msg -> encoding[ $msg_number ][ 0 ],
956                                                $msg -> charset[ $msg_number ][ 0 ]
957                                        );
958
959                                        if ( strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain' )
960                                        {
961                                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );
962                                                $content = htmlentities( $content );
963                                                $content = $this -> replace_links( $content );
964                                                $content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content );
[3130]965                                                $content = '<pre>' . $content . '</pre>';
[3912]966                                                $content = str_replace("\x00", '', $content);
967                                                $return[ 'body' ] = $content;
[3018]968
969                                                return $return;
970                                        }
971                                }
[2]972                }
[1472]973                else
[2]974                { //Complicated message, multiple parts
975                        $html_body = '';
976                        $content = '';
977                        $has_multipart = true;
[3922]978                        $is_alternative = false;
[2]979                        $this->has_cid = false;
[3922]980                        $alternative_content;
[3394]981                        array_shift($return['signature']);
[2]982                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
983                                $this->has_cid = true;
[1472]984
[469]985                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
[3922]986                                $is_alternative = true;
[469]987                                $show_only_html = false;
988                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
[432]989                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
990                                        if($file_type == "text/html")
[1472]991                                                $show_only_html = true;
[432]992                                }
[469]993                        }
[2]994                        else
995                                $show_only_html = false;
996
997                        foreach($msg->pid[$msg_number] as $values => $msg_part)
998                        {
[1472]999
[2]1000                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
[3018]1001                                if($file_type == "message/rfc822" || $file_type == "multipart/alternative")
1002                                {
1003                                        // Show only 'text/html' part, when message/rfc822 format contains 'text/plain' alternative part.
1004                                        if(array_key_exists($values+1, $msg->file_type[$msg_number]) &&
1005                                                strtolower($msg->file_type[$msg_number][$values+1]) == 'text/plain' &&
1006                                                array_key_exists($values+2, $msg->file_type[$msg_number]) &&
1007                                                strtolower($msg->file_type[$msg_number][$values+2]) == 'text/html') {
1008                                                        $has_multipart = false;
1009                                                }
1010                                }       
[1472]1011
1012                                if(($file_type == "text/plain"
[2]1013                                        || $file_type == "text/html")
[3018]1014                                                && $file_type != 'attachment')
[2]1015                                {
[3414]1016
1017                                       
1018                                       if($this->prefs['max_msg_size'] == "1")
1019                                            $max_size = 1048576;
1020                                        else
1021                                            $max_size = 102400;
1022
[2]1023                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
1024                                        {
1025                                                // if TXT file size > 100kb, then it will not expand.
[3414]1026                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > $max_size)) {
[3018]1027                                                         $content .= htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
[3414]1028                                                        $content = '<pre>' . $content . '</pre>';
[2]1029                                                }
1030                                        }
1031                                        // if HTML attachment file size > 300kb, then it will not expand.
[3414]1032                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < $max_size*3)
[2]1033                                        {
[3922]1034                                            if ($is_alternative)
1035                                            {
[4798]1036                                                $alternative_content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
[3922]1037                                            }
1038                                            else
1039                                                {
1040                                                    $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
1041                                                    $show_only_html = true;
1042                                                }
[2]1043                                        }
1044                                }
[3018]1045                                 else if($file_type == "message/delivery-status" || $file_type == "message/feedback-report"){
[2]1046                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[3039]1047                                        $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
[3130]1048                    $content = '<pre>' . $content . '</pre>';
[2]1049                                }
[65]1050                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
[1472]1051
[2]1052                                        include_once("class.imap_attachment.inc.php");
1053                                        $att = new imap_attachment();
[51]1054                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
[3018]1055                                        if($attachments['number_attachments'] > 0) {
1056                                                foreach($attachments ['attachment'] as $index => $attachment)
1057                                                {
1058                                                        if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) )
1059                                                        {
1060                                                                $obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] );
[1897]1061
[3018]1062                                                                $content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">';
1063                                                                $content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">';
[1897]1064
[3018]1065                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Subject")
1066                                                                        . ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>';
[1897]1067
[3018]1068                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>'
1069                                                                        . $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) )
1070                                                                        . '</td></tr>';
[1897]1071
[3018]1072                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>';
[1897]1073
[3018]1074                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>'
1075                                                                        . $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) )
1076                                                                        . '</td></tr>';
[1897]1077
[3018]1078                                                                if ( $obj->cc )
1079                                                                        $content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>'
1080                                                                                . $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) )
1081                                                                                . '</td></tr>';
[1897]1082
[3018]1083                                                                $content .= '</table><br>';
[1897]1084
[3018]1085
1086                                                                $id = ( ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? false : true );
1087                                                                if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' )
1088                                                                {
1089                                                                        $id = !$id;
1090                                                                        if ( $msg->structure[$msg_number]->parts[1]->parts[0]->encoding == 4 )
1091                                                                                $msg->encoding[ $msg_number ][ $values ] = 'quoted-printable';
1092                                                                }
[6474]1093
[6482]1094                                                                /*$body = $this->decodeBody(
[6474]1095                                                                        imap_fetchbody(
[3018]1096                                                                                $this->mbox,
1097                                                                                $msg_number,
1098                                                                                ( $attachment['part_in_msg'] + ( ( int ) $id ) ) . ".1",
1099                                                                                FT_UID
1100                                                                        ),
1101                                                                        $msg->encoding[ $msg_number ][ $values ],
1102                                                                        $msg->charset[ $msg_number ][ $values ]
[6482]1103                                                                ); */
1104                                                               
1105                                                               $body = $this->decodeBody(
1106                                                                        imap_fetchbody(
1107                                                                                $this->mbox,
1108                                                                                $msg_number,
1109                                                                                $attachment['part_in_msg'] . ".1",
1110                                                                                FT_UID
1111                                                                        ),
1112                                                                        $msg->encoding[ $msg_number ][ $values ],
1113                                                                        $msg->charset[ $msg_number ][ $values ]
1114                                                                );
[6474]1115
[3018]1116                                                                if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' )
1117                                                                {
1118                                                                        $body = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $body );
1119                                                                        $body = htmlentities( $body );
1120                                                                        $body = $this -> replace_links( $body );
1121                                                                        $body = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $body );
[3130]1122                                                                        $body = '<pre>' . $body . '</pre>';
[3018]1123                                                                }
1124
1125                                                                $content .= $body;
1126                                                                break;
[2]1127                                                        }
1128                                                }
1129                                        }
1130                                }
1131                        }
[3922]1132                        if ($is_alternative && !empty($alternative_content))
1133                        {
1134                            $content .= $alternative_content;
1135                        }
[2]1136                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
1137                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
[51]1138                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
[25]1139                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
[1472]1140                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
[2]1141                        }
[1472]1142                }
[2]1143                // Force message with flag Seen (imap_fetchbody not works correctly)
[1472]1144                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
[2]1145                $this->set_messages_flag($params);
[205]1146                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
[2]1147                $content = $this->replace_special_characters($content);
[51]1148                $return['body'] = $content;
1149                return $return;
[2]1150        }
[1472]1151
[2]1152        function htmlfilter($body)
1153        {
1154                require_once('htmlfilter.inc');
[1472]1155
[2]1156                $tag_list = Array(
1157                                false,
1158                                'blink',
1159                                'object',
1160                                'meta',
1161                                'html',
1162                                'link',
1163                                'frame',
1164                                'iframe',
1165                                'layer',
1166                                'ilayer',
1167                                'plaintext'
1168                );
1169
1170                /**
1171                * A very exclusive set:
1172                */
1173                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
1174                $rm_tags_with_content = Array(
1175                                'script',
1176                                'style',
1177                                'applet',
1178                                'embed',
1179                                'head',
1180                                'frameset',
1181                                'xml',
1182                                'xmp'
1183                );
1184
1185                $self_closing_tags =  Array(
1186                                'img',
1187                                'br',
1188                                'hr',
1189                                'input'
1190                );
1191
1192                $force_tag_closing = true;
1193
1194                $rm_attnames = Array(
1195                        '/.*/' =>
1196                                Array(
1197                                        '/target/i',
1198                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
1199                                        '/^dynsrc/i',
1200                                        '/^datasrc/i',
1201                                        '/^data.*/i',
1202                                        '/^lowsrc/i'
1203                                )
1204                );
1205
1206                /**
1207                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
1208                 * some idea of what's going on here. :)
1209                 */
1210
1211                $bad_attvals = Array(
1212                '/.*/' =>
1213                Array(
1214                      '/.*/' =>
1215                              Array(
1216                                Array(
1217                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1218                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1219                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1220                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1221                                      ),
1222                            Array(
1223                                              '\\1oddjob:\\2\\1',
1224                                          //'\\1uucp:\\2\\1', -> doclinks notes
1225                                      '\\1amaretto:\\2\\1',
1226                                          '\\1round:\\2\\1'
1227                                        )
[1472]1228                                    ),
1229
[2]1230                          '/^style/i' =>
1231                              Array(
1232                                        Array(
1233                                          '/expression/i',
1234                                              '/behaviou*r/i',
1235                                          '/binding/i',
1236                                              '/include-source/i',
1237                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1238                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1239                                         ),
1240                                        Array(
1241                                          'idiocy',
1242                                              'idiocy',
1243                                          'idiocy',
1244                                              'idiocy',
1245                                          'url(\\1http://securityfocus.com/\\1)',
1246                                          'url(\\1http://securityfocus.com/\\1)'
1247                                         )
1248                                )
1249                          )
1250                    );
1251
1252                $add_attr_to_tag = Array(
1253                                '/^a$/i' => Array('target' => '"_new"')
1254                );
[1472]1255
1256
[2]1257                $trusted_body = sanitize($body,
1258                                $tag_list,
1259                                $rm_tags_with_content,
1260                                $self_closing_tags,
1261                                $force_tag_closing,
1262                                $rm_attnames,
1263                                $bad_attvals,
1264                                $add_attr_to_tag
1265                );
[1472]1266
[2]1267            return $trusted_body;
1268        }
[1472]1269
[2]1270        function decodeBody($body, $encoding, $charset=null)
1271        {
1272                /**
1273                * replace e-mail by anchor.
1274                */
1275                // HTML Filter
[13]1276                //$body = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=# onclick=\"javascript:new_message('new_by_message', '\\2@\\3')\">\\2@\\3</a>", $body);
[828]1277        //$body = str_replace("\r\n", "\n", $body);
[2]1278                if ($encoding == 'quoted-printable')
[828]1279                {
1280                        /*
[1472]1281
[2]1282                        for($i=0;$i<256;$i++) {
1283                                $c1=dechex($i);
1284                                if(strlen($c1)==1){$c1="0".$c1;}
1285                                $c1="=".$c1;
1286                                $myqprinta[]=$c1;
1287                                $myqprintb[]=chr($i);
[1472]1288                        }
[828]1289                         */
[2]1290                        $body = str_replace($myqprinta,$myqprintb,($body));
1291                        $body = quoted_printable_decode($body);
[1472]1292                while (ereg("=\n", $body))
[2]1293                {
1294                        $body = ereg_replace ("=\n", '', $body);
1295                }
1296        }
[1472]1297        else if ($encoding == 'base64')
[2]1298        {
1299                $body = base64_decode($body);
1300        }
[1792]1301
[2]1302                // All other encodings are returned raw.
1303                if (strtolower($charset) == "utf-8")
1304                        return utf8_decode($body);
1305        else
1306                        return $body;
1307        }
[1472]1308
[205]1309        function process_embedded_images($msg, $msgno, $body, $msg_folder)
[2]1310        {
1311                if (count($msg->inline_id[$msgno]) > 0)
1312                {
1313                        foreach ($msg->inline_id[$msgno] as $index => $cid)
1314                        {
1315                                $cid = eregi_replace("<", "", $cid);
1316                                $cid = eregi_replace(">", "", $cid);
1317                                $msg_part = $msg->pid[$msgno][$index];
1318                                //$body = eregi_replace("alt=\"\"", "", $body);
1319                                $body = eregi_replace("<br/>", "", $body);
1320                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1321                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1322                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1323                        }
1324                }
[1472]1325
[2]1326                return $body;
1327        }
[1472]1328
[2]1329        function replace_special_characters($body)
1330        {
1331                // Suspected TAGS!
[1472]1332                /*$tag_list = Array(
[2]1333                        'blink','object','meta',
1334                        'html','link','frame',
1335                        'iframe','layer','ilayer',
1336                        'plaintext','script','style','img',
1337                        'applet','embed','head',
1338                        'frameset','xml','xmp');
1339                */
1340
[1472]1341                // Layout problem: Change html elements
1342                // with absolute position to relate position, CASE INSENSITIVE.
[3912]1343                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
[6]1344
[2]1345                $tag_list = Array('head','blink','object','frame',
1346                        'iframe','layer','ilayer','plaintext','script',
[63]1347                        'applet','embed','frameset','xml','xmp','style');
[2]1348
[1472]1349                $blocked_tags = array();
[2]1350                foreach($tag_list as $index => $tag) {
[1233]1351                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
[2]1352                        if($body != $new_body) {
1353                                $blocked_tags[] = $tag;
1354                        }
[1233]1355                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
[2]1356                }
[650]1357                // Malicious Code Remove
[1923]1358                $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]1359                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1360                foreach($rest[0] as $i => $val)
[1270]1361                        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]1362                                $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
[2]1363
[3250]1364                $body = $this-> replace_links($body);
1365
[4945]1366                //Remoção de tags <span></span> para correção de erro no firefox
[4977]1367//               if($_SESSION['phpgw_session']['phpgw_app_sessions']['phpgwapi']['browser_agent']['content'] != 'IE'){
1368//                   $body = mb_eregi_replace("<span><span>","",$body);
1369//                   $body = mb_eregi_replace("</span></span>","",$body);
1370//               }
1371
[4870]1372                $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
1373                $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
1374                $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
1375//Correção para compatibilização com Outlook, ao visualizar a mensagem
[3250]1376                $body = mb_ereg_replace('<!--\[','<!-- [',$body);
[3294]1377                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
[4946]1378                $body = mb_ereg_replace('<!\[endif\]-->', '<!--[endif]--->', $body);
1379                $body = str_replace("\x00", '', $body);
[3912]1380               
[3250]1381                return  "<span>".$body;
[2]1382        }
1383
[5119]1384        function replace_links_aux( $body )
[4649]1385        {
[5119]1386               // Trata urls do tipo aaaa.bbb.empresa
1387                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])(((http|https|ftp|ftps)?:\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
[4649]1388                $replacement = '<a href="$3://$4$5" target="_blank">$4$5</a>';
1389                $body = preg_replace($pattern, $replacement, $body);
[5119]1390                $body = preg_replace('/href=":\/\//', 'href="http://', $body);
1391
1392                // Trata tags <a href="    sem protocolo....
1393                $body_aux = explode('<a href="',$body);
1394                $body = $body_aux[0];
1395                $protocolos = array('http','https','ftp','ftps');
1396                for ($i=1;$i<count($body_aux);$i++)
1397                {
1398                    $flgproto = false;
1399                    foreach($protocolos as $protocolo)
1400                    {
1401                       if(substr($body_aux[$i],0,strlen($protocolo)) == $protocolo)
1402                       {
1403                           $flgproto = true;
1404                           break;
1405                       }
1406                    }
1407                    if(!$flgproto)
1408                    {
1409                        $body = $body . '<a target="_blanck" href="http://' . $body_aux[$i];
1410                    }
1411                    else
1412                    {
1413                        $body = $body . '<a href="' . $body_aux[$i];
1414                    }
1415                }
[4649]1416                return $body;
1417        }
1418
[5119]1419        function replace_links( $body )
[1897]1420        {
[5119]1421                // Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
1422                // See more informations in www.iana.org
1423                $octets = array(
1424                        'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
1425                        'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
1426                        'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
1427                );
[1897]1428
[5119]1429                $ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
[1472]1430
[5119]1431                $top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
1432                        . 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
1433                        . 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
1434                        . 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
1435                        . 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
1436                        . 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
1437                        . 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
1438                        . 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
1439                        . 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
1440                        . 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
1441                        . 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
1442                        . 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
1443                        . 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
[1707]1444
[5119]1445                $path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
1446                $port = '(?>:\d{2,5})?';
1447                $domain = '(?>[\w\d_\-]+)';
1448                $subdomain = "(?>{$domain}\.)*";
1449                $protocol = '(?>(http|ftp)(s)?:\/\/)?';
1450                $url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
[1707]1451
[3018]1452                $pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
[5119]1453                ini_set( 'pcre.backtrack_limit', 300000 );
[3018]1454
[5119]1455                /*
1456                // PHP 5.3
1457                $replace = function( $matches )
1458                {
1459                        if ( $matches[ 1 ] )
1460                                return $matches[ 0 ];
[3018]1461
[5119]1462                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1463                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1464                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1465                };
1466                $body = preg_replace_callback( $pattern, $replace, $body );
1467                 */
[3018]1468
[5119]1469                // PHP 5.2.x - Remover assim que possível
1470                $body = preg_replace_callback( $pattern,
1471                        create_function(
1472                                '$matches',
1473                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
[3018]1474                                . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1475                                . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1476                                . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1477                        ), $body
1478                );
[5119]1479                ini_set( 'pcre.backtrack_limit', 100000 );
[1897]1480                // E-mail address in the text should create a new e-mail on ExpressoMail
[5119]1481                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
[3018]1482                $replacement = '$1<a href="mailto:$2">$2</a>$3';
[1897]1483                $body = preg_replace( $pattern, $replacement, $body );
[1707]1484
[5119]1485                return $this->replace_links_aux($body);
[2]1486        }
1487
[91]1488        function get_signature($msg, $msg_number, $msg_folder)
[1035]1489        {
[3352]1490            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1491            include_once("class.db_functions.inc.php");
1492            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1493            {
1494                $sign = array();
1495                $temp = $this->get_info_head_msg($msg_number);
1496                if($temp['ContentType'] =='normal') return $sign;
1497                $file_type = strtolower($file_type);
1498                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]1499                {
[3394]1500                    if ($temp['ContentType'] == 'signature')
[3352]1501                    {
[3394]1502                        if(!$this->mbox || !is_resource($this->mbox))
1503                        $this->mbox = $this->open_mbox($msg_folder);
[1035]1504
[3352]1505                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[1035]1506
[3352]1507                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1508                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
[1035]1509
[3352]1510                        $certificado = new certificadoB();
1511                        $validade = $certificado->verificar($imap_msg);
[3394]1512                                        $sign[] = $certificado->msg_sem_assinatura;
[3352]1513                        if ($certificado->apresentado)
1514                        {
1515                            $from = $header->from;
1516                            foreach ($from as $id => $object)
1517                            {
1518                                $fromname = $object->personal;
1519                                $fromaddress = $object->mailbox . "@" . $object->host;
1520                            }
1521                            foreach ($certificado->erros_ssl as $item)
1522                            {
1523                                $sign[] = $item . "#@#";
1524                            }
[1035]1525
[3352]1526                            if (count($certificado->erros_ssl) < 1)
1527                            {
1528                                $check_msg = 'Message untouched';
1529                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1530                                {
1531                                    $check_msg .= ' and authentic###';
1532                                }
1533                                else
1534                                {
1535                                    $check_msg .= ' with signer different from sender#@#';
1536                                }
1537                                $sign[] = $check_msg;
1538                            }
1539                                               
1540                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1541                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1542                            $sign[] = 'Mail from: ###' . $fromaddress;
1543                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
1544                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1545                            $sign[] = 'Message date: ###' . $header->Date;
[1035]1546
[3352]1547                            $cert = openssl_x509_parse($certificado->cert_assinante);
[1035]1548
[3352]1549                            $sign_alert = array();
1550                            $sign_alert[] = 'Certificate Owner###:\n';
1551                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
1552                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1553                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
1554                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
1555                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
1556                            $sign_alert[] = 'Personal Data###:' . '\n';
1557                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
1558                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
1559                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
1560                            $sign_alert[]= 'Certificate Issuer###:\n';
1561                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
1562                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
1563                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
1564                            $sign_alert[]= 'Validity###:\n';
1565                            $H = data_hora($cert[validFrom]);
1566                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1567                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
1568                            $H = data_hora($cert[validTo]);
1569                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1570                            $sign_alert[]= 'Valid Until### ' . $X;
1571                            $sign[] = $sign_alert;
1572
1573                            $this->db = new db_functions();
1574                           
[6474]1575                            // TODO: testar se existe um certificado no banco e verificar qual é o mais atual.
[3352]1576                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1577                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
[91]1578                        }
[3352]1579                        else
1580                        {
1581                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1582                            foreach($certificado->erros_ssl as $item)
1583                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1584                        }
1585                    }
[91]1586                }
[3352]1587            }
1588            return $sign;
[91]1589        }
1590
[51]1591        function get_thumbs($msg, $msg_number, $msg_folder)
[2]1592        {
1593                $thumbs_array = array();
1594                $i = 0;
1595        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1596        {
1597                $file_type = strtolower($file_type);
1598                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1599                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1600                                $img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
[1005]1601                                $href = "<a onMouseDown='save_image(event,this,\"".$file_type."\")' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
[2]1602                                        $thumbs_array[] = $href;
1603                        }
1604                        $i++;
1605                }
1606        }
1607        return $thumbs_array;
1608        }
[1472]1609
[2]1610        /*function delete_msg($params)
1611        {
1612                $folder = $params['folder'];
1613                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[1472]1614
[2]1615                $mbox_stream = $this->open_mbox($folder);
[1472]1616
[2]1617                foreach ($msgs_to_delete as $msg_number){
1618                        imap_delete($mbox_stream, $msg_number, FT_UID);
1619                }
1620                imap_close($mbox_stream, CL_EXPUNGE);
1621                return $params['msgs_to_delete'];
1622        }*/
1623
1624        // Novo
1625        function delete_msgs($params)
1626        {
[1472]1627
[2]1628                $folder = $params['folder'];
[51]1629                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]1630                $msgs_number = explode(",",$params['msgs_number']);
1631                $border_ID = $params['border_ID'];
[1472]1632
[2]1633                $return = array();
[1472]1634
[449]1635                if ($params['get_previous_msg']){
[2]1636                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]1637                        // Fix problem in unserialize function JS.
1638                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1639                }
[2]1640
[1472]1641                //$mbox_stream = $this->open_mbox($folder);
[504]1642                $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()))));
[1472]1643
[2]1644                foreach ($msgs_number as $msg_number)
1645                {
1646                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1647                                $return['msgs_number'][] = $msg_number;
1648                }
[1472]1649
[2]1650                $return['folder'] = $folder;
1651                $return['border_ID'] = $border_ID;
[1472]1652
[51]1653                if($mbox_stream)
1654                        imap_close($mbox_stream, CL_EXPUNGE);
[2]1655                return $return;
1656        }
1657
[1472]1658
[2]1659        function refresh($params)
1660        {
[3265]1661
[2]1662                $folder = $params['folder'];
1663                $msg_range_begin = $params['msg_range_begin'];
1664                $msg_range_end = $params['msg_range_end'];
1665                $msgs_existent = $params['msgs_existent'];
[1472]1666                $sort_box_type = $params['sort_box_type'];
[2]1667                $sort_box_reverse = $params['sort_box_reverse'];
1668                $msgs_in_the_server = array();
[53]1669                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]1670                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1671                $msgs_in_the_server = array_keys($msgs_in_the_server);
1672                if(!count($msgs_in_the_server))
[51]1673                        return array();
[1472]1674
[828]1675                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
[1472]1676                $msgs_in_the_client = explode(",", $msgs_existent);
[51]1677
[2]1678                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[271]1679                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[1472]1680
[2]1681                $msgs_to_exec = array();
[3265]1682                foreach($msg_to_insert as $msg_number)
1683                        $msgs_to_exec[] = $msg_number;
[4611]1684                //sort($msgs_to_exec);
[1472]1685
[2]1686                $return = array();
[4682]1687                $return['new_msgs'] = imap_num_recent($this->mbox);
[2]1688                $i = 0;
[3265]1689                foreach($msgs_to_exec as $msg_number)
[2]1690                {
[614]1691                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
[1472]1692                        * atributos do cabeçalho. Como eu preciso do atributo Importance
[614]1693                        * para saber se o email é importante ou não, uso abaixo a função
1694                        * imap_fetchheader e busco o atributo importance nela para passar
1695                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1696                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1697                        * não preciso reimplementar o método utilizando o fetchheader.
1698                        */
[3955]1699   
1700                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
[1035]1701                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[689]1702                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
[1472]1703
[1752]1704                        $msg_sample = $this->get_msg_sample($msg_number);
1705                        $return[$i]['msg_sample'] = $msg_sample;
1706
[535]1707                        $header = $this->get_header($msg_number);
[2]1708                        if (!is_object($header))
[828]1709                                continue;
1710
[2]1711                        $return[$i]['msg_number']       = $msg_number;
[3955]1712                       
1713                        //get the next msg number to append this msg in the view in a correct place
1714                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
1715                       
[4611]1716                        $return[$i]['msg_key_position'] = $msg_key_position;
1717                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1,$msgs_in_the_server) !== false)
[3955]1718                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
[4611]1719                        else
1720                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position];
[1472]1721
[2]1722                        $return[$i]['msg_folder']       = $folder;
[3955]1723                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
[3265]1724                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
[2]1725                        $return[$i]['Recent']           = $header->Recent;
1726                        $return[$i]['Unseen']           = $header->Unseen;
1727                        $return[$i]['Answered']         = $header->Answered;
1728                        $return[$i]['Deleted']          = $header->Deleted;
1729                        $return[$i]['Draft']            = $header->Draft;
1730                        $return[$i]['Flagged']          = $header->Flagged;
1731
[3106]1732                        $return[$i]['udate'] = $header->udate;
1733               
[2]1734                        $from = $header->from;
1735                        $return[$i]['from'] = array();
1736                        $tmp = imap_mime_header_decode($from[0]->personal);
1737                        $return[$i]['from']['name'] = $tmp[0]->text;
1738                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]1739                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[2]1740                        if(!$return[$i]['from']['name'])
1741                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[1472]1742
[2]1743                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1744                        $return[$i]['toaddress'] = '';
1745                        foreach ($toaddress as $tmp)
1746                                $return[$i]['toaddress'] .= $tmp->text;*/
1747                        $to = $header->to;
1748                        $return[$i]['to'] = array();
1749                        $tmp = imap_mime_header_decode($to[0]->personal);
1750                        $return[$i]['to']['name'] = $tmp[0]->text;
1751                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1752                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[3777]1753                        $cc = $header->cc;
1754                        if ( ($cc) && (!$return[$i]['to']['name']) ){
1755                                $return[$i]['to']['name'] =  $cc[0]->personal;
1756                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
1757                        }
[2]1758                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1759
1760                        $return[$i]['Size'] = $header->Size;
1761                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]1762
[2]1763                        $return[$i]['attachment'] = array();
[3265]1764                        if (!isset($imap_attachment))
1765                        {
1766                                include_once("class.imap_attachment.inc.php");
1767                                $imap_attachment = new imap_attachment();
1768                        }
[51]1769                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]1770                        $i++;
1771                }
[3265]1772                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
1773                $return['sort_box_type'] = $params['sort_box_type'];
[3427]1774                if(!$this->mbox || !is_resource($this->mbox))
1775                {
1776                    $this->open_mbox($folder);
1777                }
[4682]1778
[271]1779                $return['msgs_to_delete'] = $msg_to_delete;
[3493]1780                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
[411]1781                if($this->mbox && is_resource($this->mbox))
[51]1782                        imap_close($this->mbox);
[828]1783
[2]1784                return $return;
1785        }
1786
[1035]1787     /**
1788     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1789     * assinado ou cifrado.
1790     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1791     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1792     * @param $msg_number O número da mesagem
1793     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1794     */
1795    function getMessageType($msg_number, $headers = false){
[3394]1796            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]1797            $contentType = "normal";
1798            if (!$headers){
1799                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1800            }
[3394]1801           
1802            if (preg_match("/pkcs7-signature/i", $headers) == 1){
[1035]1803                $contentType = "signature";
[3394]1804            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
1805                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
[1035]1806            }
1807
1808            return $contentType;
1809    }
1810
[1375]1811         /**
1812     * Metodo que retorna todas as pastas do usuario logado.
1813     * @param $params array opcional para repassar os argumentos ao metodo.
1814     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1815     * excluindo as compartilhadas para ele.
[3553]1816     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
1817     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
1818     * Se usar $params['folderType'] = null irá retornar todas as pastas
[1472]1819     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
[1375]1820     * folder_id, folder_name, folder_parent e folder_hasChildren.
[1472]1821     */
[449]1822        function get_folders_list($params = null)
[2]1823        {
[1472]1824                $mbox_stream = $this->open_mbox();
[1953]1825                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1826                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1827                }
[650]1828
[1824]1829                $inbox = 'INBOX';
1830                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[3018]1831                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1832                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1833                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1834                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1835                // Free others requests
1836                session_write_close();
[1816]1837
[3018]1838                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[3790]1839               
[3192]1840                if ( $params && $params['noSharedFolders'] )
[3790]1841                        $folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
1842                else
1843                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, '*' );
[3761]1844
[3018]1845                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1846
1847                $tmp = array();
1848                $resultMine = array();
1849                $resultDefault = array();
1850
[2]1851                if (is_array($folders_list)) {
[3761]1852                        reset($folders_list);
1853                        $this->ldap = new ldap_functions();
[1472]1854
[2]1855                        $i = 0;
[3761]1856                        while (list($key, $val) = each($folders_list)) {
[6474]1857                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
[1035]1858
[6474]1859                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1860                                $tmp_folder_id = explode("}", $val->name );
[3761]1861
[6474]1862                                $folderUser = trim( strpos( $tmp_folder_id[1], $this->imap_delimiter , 5 ) );
[4693]1863
[6474]1864                            $folderUser = trim( substr( $tmp_folder_id[1], 0, $folderUser ) );
1865
1866                            $Permission = true;
1867
1868                            if( $folderUser != "INBOX" && $folderUser != "" )
[4693]1869                            {
[6474]1870                               $Permission = imap_getacl( $mbox_stream, $folderUser );
[4693]1871                            }
1872
[6474]1873                            if( $Permission )
1874                            {
1875                                $tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" );
[4693]1876
[6474]1877                                if( $tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas')
1878                                {
1879                                        continue;
1880                                }
1881                                $result[$i]['folder_unseen'] = $status->unseen;
1882                                $folder_id = $tmp_folder_id[1];
1883                                $result[$i]['folder_id'] = $folder_id;
[1472]1884
[6474]1885                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1886                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1887                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1888                       
1889                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1890                                        //$this->ldap = new ldap_functions();
1891                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1892                                                $result[$i]['folder_name'] = $cn;
1893                                        }
1894                                }
[1472]1895
[6474]1896                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1897                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[1472]1898
[6474]1899                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1900                                        $result[$i]['folder_hasChildren'] = 1;
1901                                else
1902                                        $result[$i]['folder_hasChildren'] = 0;
1903
1904                                switch ($tmp_folder_id[1]) {
1905                                        case $inbox:
1906                                        case $sent:
1907                                        case $drafts:
1908                                        case $spam:
1909                                        case $trash:
1910                                                $resultDefault[]=$result[$i];
1911                                                break;
1912                                        default:
1913                                                $resultMine[]=$result[$i];
1914                                }
1915
[4693]1916                            }
1917                            $i++;
1918                        }
[2]1919                }
[1472]1920
[3564]1921                if ( $params && !$params['noQuotaInfo'] ) {
1922                        //Get quota info of current folder
1923                        $current_folder = "INBOX";
1924                        if($params && $params['folder'])
1925                                $current_folder = $params['folder'];
[3790]1926
[3564]1927                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
1928                } else {
1929                        $arr_quota_info = array();
1930                }
[3790]1931
[1816]1932                // Sorting resultMine
1933                foreach ($resultMine as $folder_info)
[2]1934                {
1935                        $array_tmp[] = $folder_info['folder_id'];
1936                }
[1472]1937
[2]1938                natcasesort($array_tmp);
[3575]1939               
[3790]1940                $result2 = array();
[1472]1941
[2]1942                foreach ($array_tmp as $key => $folder_id)
1943                {
[1816]1944                        $result2[] = $resultMine[$key];
[2]1945                }
[1816]1946               
1947                // Sorting resultDefault
1948                foreach ($resultDefault as $key => $folder_id)
1949                {
1950                        switch ($resultDefault[$key]['folder_id']) {
[1824]1951                                case $inbox:
[1816]1952                                        $resultDefault2[0] = $resultDefault[$key];
1953                                        break;
[1824]1954                                case $sent:
[1816]1955                                        $resultDefault2[1] = $resultDefault[$key];
1956                                        break;
[1824]1957                                case $drafts:
[1816]1958                                        $resultDefault2[2] = $resultDefault[$key];
1959                                        break;
[1824]1960                                case $spam:
[1816]1961                                        $resultDefault2[3] = $resultDefault[$key];
1962                                        break;
[1824]1963                                case $trash:
[1816]1964                                        $resultDefault2[4] = $resultDefault[$key];
1965                                        break;
1966                        }
1967                }
[3553]1968               
1969                if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
[3790]1970                        return array_merge($resultDefault2, $arr_quota_info);
[1816]1971
[3553]1972                if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
[3790]1973                        return array_merge($result2, $arr_quota_info);
1974
[3553]1975                // Merge default folders and personal
[3790]1976                $result2 = array_merge($resultDefault2, $result2);
[1816]1977               
[3553]1978                return array_merge($result2, $arr_quota_info);
[2]1979        }
[1472]1980
[2]1981        function create_mailbox($arr)
1982        {
1983                $namebox        = $arr['newp'];
1984                $mbox_stream = $this->open_mbox();
1985                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]1986                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[1472]1987
[2]1988                $result = "Ok";
[51]1989                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]1990                {
1991                        $result = implode("<br />\n", imap_errors());
[1472]1992                }
1993
[51]1994                if($mbox_stream)
1995                        imap_close($mbox_stream);
[1472]1996
[2]1997                return $result;
[1472]1998
[2]1999        }
[1472]2000
[2]2001        function create_extra_mailbox($arr)
2002        {
2003                $nameboxs = explode(";",$arr['nw_folders']);
2004                $result = "";
2005                $mbox_stream = $this->open_mbox();
2006                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1472]2007                foreach($nameboxs as $key=>$tmp){
[2]2008                        if($tmp != ""){
2009                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
2010                                        $result = implode("<br />\n", imap_errors());
[51]2011                                        if($mbox_stream)
[1472]2012                                                imap_close($mbox_stream);
[2]2013                                        return $result;
2014                                }
2015                        }
2016                }
[51]2017                if($mbox_stream)
2018                        imap_close($mbox_stream);
[2]2019                return true;
2020        }
[1472]2021
[2]2022        function delete_mailbox($arr)
2023        {
2024                $namebox = $arr['del_past'];
2025                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1953]2026                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
[2]2027                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[1472]2028
[2]2029                $result = "Ok";
2030                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2031                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2032                {
2033                        $result = implode("<br />\n", imap_errors());
2034                }
[1953]2035                /*
[51]2036                if($mbox_stream)
2037                        imap_close($mbox_stream);
[1953]2038                */
[2]2039                return $result;
2040        }
[1472]2041
[2]2042        function ren_mailbox($arr)
2043        {
2044                $namebox = $arr['current'];
2045                $new_box = $arr['rename'];
2046                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2047                $mbox_stream = $this->open_mbox();
2048                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[1472]2049
[2]2050                $result = "Ok";
2051                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]2052                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[1472]2053
[2]2054                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2055                {
[1472]2056                        $result = imap_errors();
[2]2057                }
[51]2058                if($mbox_stream)
2059                        imap_close($mbox_stream);
[2]2060                return $result;
[1472]2061
[2]2062        }
[1472]2063
[2]2064        function get_num_msgs($params)
2065        {
2066                $folder = $params['folder'];
[411]2067                if(!$this->mbox || !is_resource($this->mbox)) {
[2]2068                        $this->mbox = $this->open_mbox($folder);
[411]2069                        if(!$this->mbox || !is_resource($this->mbox))
[2]2070                        return imap_last_error();
[1472]2071                }
[2]2072                $num_msgs = imap_num_msg($this->mbox);
[432]2073                if($this->mbox && is_resource($this->mbox))
[51]2074                        imap_close($this->mbox);
[1472]2075
[2]2076                return $num_msgs;
2077        }
[1472]2078
[1912]2079        function folder_exists($folder){
2080                $mbox =  $this->open_mbox();
2081                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2082                $list = imap_getmailboxes($mbox,$serverString, $folder);
2083                $return = is_array($list);             
2084                imap_close($mbox);
2085                return $return;
2086        }
[6702]2087
[2]2088        function send_mail($params)
2089        {
2090                include_once("class.phpmailer.php");
2091                $mail = new PHPMailer();
2092                include_once("class.db_functions.inc.php");
2093                $db = new db_functions();
2094                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[449]2095                ##
2096                # @AUTHOR Rodrigo Souza dos Santos
[3369]2097                # @DATE 2008/09/17$fileName
[449]2098                # @BRIEF Checks if the user has permission to send an email with the email address used.
2099                ##
2100                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2101                {
2102                        $deny = true;
2103                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2104                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2105                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2106
2107                        if ( $deny )
2108                                return "The server denied your request to send a mail, you cannot use this mail address.";
2109                }
[828]2110
[2]2111                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
2112                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
2113                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
[3527]2114                $replytoaddress = $params['input_replyto'];
[2]2115                $subject = $params['input_subject'];
[271]2116                $msg_uid = $params['msg_id'];
[2]2117                $return_receipt = $params['input_return_receipt'];
[614]2118                $is_important = $params['input_important_message'];
[1035]2119        $encrypt = $params['input_return_cripto'];
2120                $signed = $params['input_return_digital'];
2121
2122                if($params['smime'])
2123        {
2124            $body = $params['smime'];
2125            $mail->SMIME = true;
2126            // A MSG assinada deve ser testada neste ponto.
2127            // Testar o certificado e a integridade da msg....
[3271]2128            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2129            $erros_acumulados = '';
2130            $certificado = new certificadoB();
2131            $validade = $certificado->verificar($body);
2132            if(!$validade)
2133            {
2134                foreach($certificado->erros_ssl as $linha_erro)
2135                {
2136                    $erros_acumulados .= $linha_erro;
2137                }
2138            }
2139            else
2140            {
2141                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2142                if ($certificado->apresentado)
2143                {
2144                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
[4243]2145                    $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;
2146                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
[1035]2147                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2148                }
2149                else
2150                {
2151                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2152                }
2153            }
2154            if(!$erros_acumulados =='')
2155            {
2156                return $erros_acumulados;
2157            }
2158        }
2159        else
2160        {
2161            $body = $params['body'];
[3250]2162            //Compatibilização com Outlook, ao encaminhar a mensagem
2163            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
[1035]2164        }
[1247]2165                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
[3900]2166                $attachments = $_FILES;
[2]2167                $forwarding_attachments = $params['forwarding_attachments'];
[689]2168                $local_attachments = $params['local_attachments'];
[3369]2169
[1912]2170                //Test if must be saved in shared folder and change if necessary
2171                if( $fromaddress[2] == 'y' ){
2172                        //build shared folder path
2173                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2174                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
2175                        else $folder =  $params['folder'];                     
2176                } else  {
2177                        $folder = $params['folder'];                   
2178                }
2179               
[1472]2180                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2181                $folder_name = $params['folder_name'];
[6]2182                // Fix problem with cyrus delimiter changes.
[1472]2183                // Dots in names: enabled/disabled.
[6]2184                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2185                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2186                // End Fix.
[1472]2187                if ($folder != 'null'){
[2]2188                        $mail->SaveMessageInFolder = $folder;
2189                }
2190////////////////////////////////////////////////////////////////////////////////////////////////////
2191                $mail->SMTPDebug = false;
[1035]2192
2193                if($signed && !$params['smime'])
2194                {
2195            $mail->Mailer = "smime";
2196                        $mail->SignedBody = true;
2197                }
2198                else
2199            $mail->IsSMTP();
[1472]2200
[2]2201                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2202                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2203                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2204                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2205                if($fromaddress){
2206                        $mail->Sender = $mail->From;
2207                        $mail->SenderName = $mail->FromName;
2208                        $mail->FromName = $fromaddress[0];
2209                        $mail->From = $fromaddress[1];
2210                }
[1472]2211
[2]2212                $this->add_recipients("to", $toaddress, &$mail);
2213                $this->add_recipients("cc", $ccaddress, &$mail);
2214                $this->add_recipients("cco", $ccoaddress, &$mail);
[5022]2215                if ($replytoaddress !="")
2216                    {
2217                        $mail->AddReplyTo($replytoaddress);
2218                    }
[2]2219                $mail->Subject = $subject;
[4252]2220                $mail->IsHTML( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
[1035]2221                $mail->Body = $body;
[271]2222
[1035]2223        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2224                {
2225                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2226            $email = explode(",",$email);
2227            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2228            // Deve ser verificado um numero limite de destinatarios.
2229            // Deve ser verificado se os certificados sao validos.
2230            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2231            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2232            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2233            $erros_acumulados = "";
2234            $aux_mails = array();
2235            $mail_list = array();
2236            if(count($email) > $numero_maximo)
2237            {
2238                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2239                return $erros_acumulados;
2240            }
2241            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2242            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2243            foreach($email as $item)
2244            {
2245                $certificate = $db->get_certificate(strtolower($item));
2246                if(!$certificate)
2247                {
2248                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2249                    return $erros_acumulados;
2250                }
2251
2252                if (array_key_exists("dberr1", $certificate))
2253                {
2254
2255                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2256                    return $erros_acumulados;
2257                                }
2258                if (array_key_exists("dberr2", $certificate))
2259                {
2260                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2261                    //continue;
2262                }
2263                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2264                if (!array_key_exists("certs", $certificate))
2265                {
2266                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2267                    continue;
2268                }
2269            */
[3271]2270                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2271
2272                foreach ($certificate['certs'] as $registro)
2273                {
2274                    $c1 = new certificadoB();
2275                    $c1->certificado($registro['chave_publica']);
2276                    if ($c1->apresentado)
2277                    {
2278                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2279                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2280                        {
2281                            $aux_mails[] = $registro['chave_publica'];
2282                            $mail_list[] = strtolower($item);
2283                        }
2284                        else
2285                        {
2286                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2287                            {
2288                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2289                                    $c1->dados['EXPIRADO'],$c2->revogado);
2290                            }
2291
2292                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2293                            foreach($c2->erros_ssl as $linha)
2294                            {
2295                                $erros_acumulados .=  $linha . chr(0x0A);
2296                            }
2297                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2298                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2299                        }
2300                    }
2301                    else
2302                    {
2303                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2304                    }
2305                }
2306                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2307                                {
2308                                        return $erros_acumulados;
2309                        }
2310            }
2311
2312            $mail->Certs_crypt = $aux_mails;
2313        }
[3018]2314                // Build CID images
2315                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
[1035]2316
[2]2317                //      Build Uploading Attachments!!!
[3387]2318                if (count($attachments)>0) //Caso seja forward normal...
[2]2319                {
2320                        $total_uploaded_size = 0;
[1264]2321                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
[2]2322                        foreach ($attachments as $attach)
2323                        {
[3900]2324                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2325                                    return $this->parse_error("message file too big");
[3387]2326                                if($attach['name']=='Unknown')
2327                                        continue;
[2]2328                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2329                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2330                        }
[3387]2331                        if( $total_uploaded_size > $upload_max_filesize){
[1472]2332                                return $this->parse_error("message file too big");
[3387]2333                        }
[828]2334                }
[3387]2335                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
[828]2336
[689]2337                        $total_uploaded_size = 0;
[1472]2338                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
[689]2339                        foreach($local_attachments as $local_attachment) {
2340                                $file_description = unserialize(rawurldecode($local_attachment));
2341                                $tmp = array_values($file_description);
[1472]2342                                foreach($file_description as $i => $descriptor){
[689]2343                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2344                                }
2345                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2346                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2347                        }
2348                        if( $total_uploaded_size > $upload_max_filesize)
[828]2349                                return 'false';
[689]2350                }
[2]2351////////////////////////////////////////////////////////////////////////////////////////////////////
[271]2352                //      Build Forwarding Attachments!!!
[2]2353                if (count($forwarding_attachments) > 0)
2354                {
2355                        // Bug fixed for array_search function
[3018]2356                        $name_cid_files = array();
[2]2357                        if(count($name_cid_files) > 0) {
2358                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2359                                $name_cid_files[0] = null;
[1472]2360                        }
2361
[2]2362                        foreach($forwarding_attachments as $forwarding_attachment)
2363                        {
[6702]2364                           
2365                                        $forwarding_attachment = ereg_replace('%u([[:alnum:]]{4})', '_',rawurldecode($forwarding_attachment));
2366                                        $file_description = unserialize($forwarding_attachment);
[271]2367                                        $tmp = array_values($file_description);
[1472]2368                                        foreach($file_description as $i => $descriptor){
[271]2369                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2370                                        }
[1472]2371                                        $file_description = $tmp;
[271]2372                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2373                                        $fileName = $file_description[2];
2374                                        if(!array_search(trim($fileName),$name_cid_files)) {
[3369]2375                                                $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
[63]2376                                }
[2]2377                        }
2378                }
[37]2379
[2]2380////////////////////////////////////////////////////////////////////////////////////////////////////
[614]2381                // Important message
2382                if($is_important)
2383                        $mail->isImportant();
2384
2385////////////////////////////////////////////////////////////////////////////////////////////////////
[2]2386                // Disposition-Notification-To
2387                if ($return_receipt)
2388                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2389////////////////////////////////////////////////////////////////////////////////////////////////////
[504]2390
[117]2391                $sent = $mail->Send();
[1472]2392
[117]2393                if(!$sent)
[2]2394                {
[504]2395                        return $this->parse_error($mail->ErrorInfo);
[2]2396                }
2397                else
2398                {
[1035]2399            if ($signed && !$params['smime'])
2400                        {
2401                                return $sent;
2402                        }
[1472]2403                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]2404                        {
2405                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2406                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2407                                $now = date("d/m/y H:i:s");
2408                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[1472]2409                                $sent = trim($sent);
[117]2410                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2411                        }
[1472]2412                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
[485]2413                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]2414                                $contacts = new dynamic_contacts();
[485]2415                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2416                                return array("success" => true, "new_contacts" => $new_contacts);
[413]2417                        }
[485]2418                        return array("success" => true);
[2]2419                }
2420        }
[3018]2421        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2422        {
2423                //      Build CID for embedded Images!!!
2424                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2425                $cid_imgs = '';
2426                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2427                $cid_array = array();
2428                foreach($cid_imgs[6] as $j => $val){
2429                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2430                        {
2431                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2432                        }
2433                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2434                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[2]2435
[3018]2436                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2437                        {
2438                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2439                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2440                                $fileName = "image_".($j).".jpg";
2441                                $fileCode = "base64";
2442                                $fileType = "image/jpg";
2443                                $file_attached[0] = $cid_imgs[2][$j];
2444                                $file_attached[1] = $cid_imgs[4][$j];
2445                                $file_attached[2] = $fileName;
2446                                $file_attached[3] = $cid_imgs[6][$j];
2447                                $file_attached[4] = 'base64';
2448                                $file_attached[5] = strlen($fileContent); //Size of file
2449                                $return_forward[] = $file_attached;
2450
2451                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2452                                if ($file_attached[3] == $attachment_[3])
2453                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2454                        }
2455                        else
2456                        {
2457                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2458                                $file_description = unserialize(rawurldecode($attach_img));
2459                                if (is_array($file_description))
2460                                        foreach($file_description as $i => $descriptor){                                 
2461                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2462                                        }
2463                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2464                                $fileName = $file_description[2];
2465                                $fileCode = $file_description[4];
2466                                $fileType = $this->get_file_type($file_description[2]);
2467                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2468                                if (!empty($file_description))
2469                                {
2470                                        $file_description[5] = strlen($fileContent); //Size of file
2471                                        $return_forward[] = $file_description;
2472                                }
2473                        }
2474                        $tempDir = ini_get("session.save_path");
2475                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2476                        $f = fopen($tempDir.'/'.$file,"w");
2477                        fputs($f,$fileContent);
2478                        fclose($f);
2479                        if ($fileContent)
2480                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2481                        //else
2482                        //      return "Error loading image attachment content";                                                 
2483
2484                }
2485                return $return_forward;
2486        }
2487        function add_recipients_cert($full_address)
[1035]2488        {
2489                $result = "";
2490                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2491                foreach ($parse_address as $val)
2492                {
2493                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2494                        if ($val->mailbox == "INVALID_ADDRESS")
2495                                continue;
2496                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2497                                continue;
2498                        if (empty($val->personal))
2499                                $result .= $val->mailbox."@".$val->host . ",";
2500                        else
2501                                $result .= $val->mailbox."@".$val->host . ",";
2502                }
2503
2504                return substr($result,0,-1);
2505        }
2506
[2]2507        function add_recipients($recipient_type, $full_address, $mail)
2508        {
[3932]2509                //remove a comma if is given two unexpected commas
2510                $full_address = preg_replace("/, ?,/",",",$full_address);
[1472]2511                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2512                foreach ($parse_address as $val)
[2]2513                {
2514                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2515                        if ($val->mailbox == "INVALID_ADDRESS")
2516                                continue;
[1472]2517
[2]2518                        if (empty($val->personal))
2519                        {
2520                                switch($recipient_type)
2521                                {
2522                                        case "to":
2523                                                $mail->AddAddress($val->mailbox."@".$val->host);
2524                                                break;
2525                                        case "cc":
2526                                                $mail->AddCC($val->mailbox."@".$val->host);
2527                                                break;
2528                                        case "cco":
2529                                                $mail->AddBCC($val->mailbox."@".$val->host);
2530                                                break;
2531                                }
2532                        }
2533                        else
2534                        {
2535                                switch($recipient_type)
2536                                {
2537                                        case "to":
2538                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2539                                                break;
2540                                        case "cc":
2541                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2542                                                break;
2543                                        case "cco":
2544                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2545                                                break;
2546                                }
2547                        }
2548                }
2549                return true;
2550        }
[1472]2551
[2]2552        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2553        {
[828]2554                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
[1472]2555                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
[2]2556                if($encoding == 'base64')
[449]2557                        # The function imap_base64 adds a new line
2558                        # at ASCII text, with CRLF line terminators.
2559                        # So is being exchanged for base64_decode.
2560                        #
2561                        #$fileContent = imap_base64($fileContent);
2562                        $fileContent = base64_decode($fileContent);
[2]2563                else if($encoding == 'quoted-printable')
[1472]2564                        $fileContent = quoted_printable_decode($fileContent);
[2]2565                return $fileContent;
2566        }
[1472]2567
[2]2568        function del_last_caracter($string)
2569        {
2570                $string = substr($string,0,(strlen($string) - 1));
[1472]2571                return $string;
[2]2572        }
[1472]2573
[2]2574        function del_last_two_caracters($string)
2575        {
2576                $string = substr($string,0,(strlen($string) - 2));
[1472]2577                return $string;
[2]2578        }
[1472]2579
[828]2580        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
[659]2581        {
[1625]2582                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
[970]2583                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2584                        foreach($imapsort as $iuid)
2585                                $sort[$iuid] = "";
[1518]2586                       
2587                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2588                                $slice_array = false;
2589                        else
2590                                $slice_array = true;
[970]2591                }
2592                else
[659]2593                {
[970]2594                        $sort = array();
2595                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2596                        $num_msgs = imap_num_msg($this->mbox);
2597                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
[975]2598                        $slice_array = true;
2599
[983]2600                        for ($i=$num_msgs; $i>0; $i--)
[828]2601                        {
[983]2602                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2603                                        break;
[970]2604                                $iuid = @imap_uid($this->mbox,$i);
2605                                $header = $this->get_header($iuid);
2606                                // List UNSEEN messages.
2607                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2608                                        continue;
2609                                }
2610                                // List SEEN messages.
2611                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2612                                        continue;
2613                                }
2614                                // List ANSWERED messages.
2615                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2616                                        continue;
2617                                }
2618                                // List FLAGGED messages.
2619                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2620                                        continue;
2621                                }
2622
2623                                if($sort_box_type=='SORTFROM') {
[5106]2624                                        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['from_to_sent']!="1") {
2625                                                if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2626                                                        $from = $header->to;
2627                                                else
2628                                                        $from = $header->from;
2629                                        }
2630                                        else {
[970]2631                                                $from = $header->from;
[5106]2632                                        }
[970]2633
2634                                        $tmp = imap_mime_header_decode($from[0]->personal);
2635
2636                                        if ($tmp[0]->text != "")
2637                                                $sort[$iuid] = $tmp[0]->text;
2638                                        else
2639                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2640                                }
2641                                else if($sort_box_type=='SORTSUBJECT') {
2642                                        $sort[$iuid] = $header->subject;
2643                                }
2644                                else if($sort_box_type=='SORTSIZE') {
2645                                        $sort[$iuid] = $header->Size;
2646                                }
2647                                else {
2648                                        $sort[$iuid] = $header->udate;
2649                                }
2650
[659]2651                        }
[970]2652                        natcasesort($sort);
[828]2653
[970]2654                        if ($sort_box_reverse)
2655                                $sort = array_reverse($sort,true);
[659]2656                }
[828]2657
[972]2658                if(!is_array($sort))
2659                        $sort = array();
[1472]2660
[1808]2661
[972]2662                if ($slice_array)
[828]2663                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
[970]2664
[1472]2665
[828]2666                return $sort;
2667
[659]2668        }
[970]2669
2670
[1472]2671        function move_search_messages($params){
2672                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]2673                $params['new_folder'] = urldecode($params['new_folder']);
2674                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2675                $sel_msgs = explode(",", $params['selected_messages']);
[1472]2676                @reset($sel_msgs);
[163]2677                $sorted_msgs = array();
2678                foreach($sel_msgs as $idx => $sel_msg) {
2679                        $sel_msg = explode(";", $sel_msg);
2680                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2681                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[1472]2682                         }
[163]2683                         else {
2684                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2685                         }
2686                }
2687                @ksort($sorted_msgs);
[1472]2688                $last_return = false;
2689                foreach($sorted_msgs as $folder => $msgs_number) {
[163]2690                        $params['msgs_number'] = $msgs_number;
[1472]2691                        $params['folder'] = $folder;
[163]2692                        if($params['new_folder'] && $folder != $params['new_folder']){
[1472]2693                                $last_return = $this -> move_messages($params);
[163]2694                        }
2695                        elseif(!$params['new_folder'] || $params['delete'] ){
2696                                $last_return = $this -> delete_msgs($params);
2697                                $last_return['deleted'] = true;
2698                        }
2699                }
2700                return $last_return;
2701        }
[1472]2702
[2]2703        function move_messages($params)
2704        {
[5000]2705                $folder = urldecode($params['folder']);
[1472]2706                $mbox_stream = $this->open_mbox($folder);
[4982]2707                $newmailbox = urldecode($params['new_folder']);
2708                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2709                $new_folder_name = urldecode($params['new_folder_name']);
2710                $msgs_number = $params['msgs_number'];
[2]2711                $return = array('msgs_number' => $msgs_number,
2712                                                'folder' => $folder,
2713                                                'new_folder_name' => $new_folder_name,
[325]2714                                                'border_ID' => $params['border_ID'],
2715                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[1472]2716
[325]2717                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2718        if (substr($folder,0,4) == 'user'){
2719                $acl = $this->getacltouser($folder);
2720                /*
2721                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2722                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2723                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2724                 *   w - write (STORE flags other than SEEN and DELETED)
2725                 *   i - insert (perform APPEND, COPY into mailbox)
2726                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2727                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2728                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2729                 *   a - administer (perform SETACL)
2730                        */
2731                        if (strpos($acl, "d") === false){
2732                                $return['status'] = false;
2733                                return $return;
2734                        }
2735        }
[432]2736        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[1747]2737        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2738            if (substr($new_folder_name,0,4) == 'user'){
2739                $this->ldap = new ldap_functions();
2740                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2741                $return['new_folder_name'] = array_pop($tmp_folder_name);
2742                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2743                {
2744                    $return['new_folder_name'] = $cn;
2745                }
2746            }
[432]2747        }
[1472]2748
2749                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
[51]2750                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]2751                {
[2]2752                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]2753                        // Fix problem in unserialize function JS.
2754                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2755                }
[1472]2756
2757                $mbox_stream = $this->open_mbox($folder);
[2]2758                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2759                        imap_expunge($mbox_stream);
[51]2760                        if($mbox_stream)
2761                                imap_close($mbox_stream);
[2]2762                        return $return;
2763                }else {
[1472]2764                        if(strstr(imap_last_error(),'Over quota')) {
[2]2765                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[1472]2766                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2767                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
[2]2768                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]2769                                $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]2770                                if(!$mbox)
2771                                        return imap_last_error();
[1472]2772                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
[2]2773                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]2774                                        if($mbox_stream)
2775                                                imap_close($mbox_stream);
[1472]2776                                        if($mbox)
[51]2777                                                imap_close($mbox);
[1472]2778                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
[2]2779                                }
2780                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2781                                        imap_expunge($mbox_stream);
[51]2782                                        if($mbox_stream)
2783                                                imap_close($mbox_stream);
[2]2784                                        // return to original quota limit.
2785                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2786                                                if($mbox)
2787                                                        imap_close($mbox);
[1472]2788                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]2789                                        }
[1472]2790                                        return $return;
[2]2791                                }
2792                                else {
[51]2793                                        if($mbox_stream)
2794                                                imap_close($mbox_stream);
[2]2795                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2796                                                if($mbox)
2797                                                        imap_close($mbox);
[1472]2798                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]2799                                        }
[1472]2800                                        return imap_last_error();
[2]2801                                }
[1472]2802
[2]2803                        }
2804                        else {
[51]2805                                if($mbox_stream)
2806                                        imap_close($mbox_stream);
2807                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]2808                        }
[1472]2809                }
[2]2810        }
[1472]2811
[2]2812        function save_msg($params)
2813        {
[1472]2814
[271]2815                include_once("class.phpmailer.php");
2816                $mail = new PHPMailer();
2817                include_once("class.db_functions.inc.php");
2818                $toaddress = $params['input_to'];
2819                $ccaddress = $params['input_cc'];
[3798]2820                $ccoaddress = $params['input_cco'];
2821                $return_receipt = $params['input_return_receipt'];
2822                $is_important = $params['input_important_message'];
[271]2823                $subject = $params['input_subject'];
[320]2824                $msg_uid = $params['msg_id'];
[2]2825                $body = $params['body'];
[4683]2826                $body = str_replace("%nbsp;","&nbsp;",$body);
[155]2827                $body = preg_replace("/\n/"," ",$body);
[51]2828                $body = preg_replace("/\r/","",$body);
[271]2829                $forwarding_attachments = $params['forwarding_attachments'];
2830                $attachments = $params['FILES'];
2831                $return_files = $params['FILES'];
[1472]2832
[4653]2833                if(is_array($params['local_attachments'])){
2834                    foreach ($params['local_attachments'] as $key => $local_attach) {
2835                       $tmp = unserialize(urldecode($local_attach));
2836                       $attachments[$key]['name'] = $tmp[2];
2837                       $return_files[$key]['name'] = $tmp[2];
2838                    }
2839                }
2840
2841
[271]2842                $folder = $params['folder'];
[1472]2843                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[271]2844                // Fix problem with cyrus delimiter changes.
[1472]2845                // Dots in names: enabled/disabled.
[271]2846                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2847                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2848                // End Fix.
[3798]2849                if(strtoupper($folder) == 'INBOX/DRAFTS') $mail->SaveMessageAsDraft = $folder;
2850
[271]2851                $mail->SaveMessageInFolder = $folder;
2852                $mail->SMTPDebug = false;
[1472]2853
[271]2854                $mail->IsSMTP();
2855                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2856                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2857                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2858                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
[1472]2859
[271]2860                $mail->Sender = $mail->From;
2861                $mail->SenderName = $mail->FromName;
2862                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2863                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
[1472]2864
[271]2865                $this->add_recipients("to", $toaddress, &$mail);
2866                $this->add_recipients("cc", $ccaddress, &$mail);
[4653]2867                $this->add_recipients("cco", $ccoaddress, &$mail);
[3527]2868                $mail->AddReplyTo($replytoaddress);
[271]2869                $mail->Subject = $subject;
2870                $mail->IsHTML(true);
2871                $mail->Body = $body;
[3798]2872               
2873                // Important message
2874                if($is_important)
2875                        $mail->isImportant();
[1472]2876
[3798]2877                // Disposition-Notification-To
2878                if ($return_receipt)
2879                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2880
[3018]2881                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
[1472]2882
2883        //      Build Forwarding Attachments!!!
[271]2884                if (count($forwarding_attachments) > 0)
2885                {
2886                        foreach($forwarding_attachments as $forwarding_attachment)
2887                        {
2888                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2889                                $tmp = array_values($file_description);
[1472]2890                                foreach($file_description as $i => $descriptor){
[271]2891                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2892                                }
2893                                $file_description = $tmp;
[1472]2894
[271]2895                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2896                                $fileName = $file_description[2];
[1472]2897
[271]2898                                $file_description[5] = strlen($fileContent); //Size of file
2899                                $return_forward[] = $file_description;
[1472]2900
[271]2901                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2902                        }
2903                }
[1472]2904
[271]2905                if ((count($return_forward) > 0) && (count($return_files) > 0))
2906                        $return_files = array_merge_recursive($return_forward,$return_files);
2907                else
2908                        if (count($return_files) < 1)
2909                                $return_files = $return_forward;
[1472]2910
[271]2911                //      Build Uploading Attachments!!!
[1005]2912                $sizeof_attachments = count($attachments);
2913                if ($sizeof_attachments)
2914                        foreach ($attachments as $numb => $attach){
2915                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2916                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2917                                        switch ($image_type)
2918                                        {
[1380]2919                                        // Do not corrupt animated gif
2920                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
[1005]2921                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2922                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2923                                        case 6:
[1247]2924                                                require_once("gd_functions.php");
[1005]2925                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2926                                        default:
2927                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2928                                                break;
2929                                        }
2930                                        header('Content-type: image/jpeg');
2931                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2932                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2933                                        if ($width < $max_resolution && $height < $max_resolution){
2934                                                $new_width = $width;
2935                                                $new_height = $height;
2936                                        }
2937                                        else if ($width > $max_resolution){
2938                                                $new_width = $max_resolution;
2939                                                $new_height = $height*($new_width/$width);
2940                                        }
2941                                        else {
2942                                                $new_height = $max_resolution;
2943                                                $new_width = $width*($new_height/$height);
2944                                        }
2945                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2946                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2947                                        $tmpDir = ini_get("session.save_path");
[1472]2948                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
[1005]2949                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2950                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
[4653]2951                                }else{
[1005]2952                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
[4653]2953                                }// optional name
2954                        }
[1472]2955
2956
2957
2958
[271]2959                if(!empty($mail->AltBody))
2960            $mail->ContentType = "multipart/alternative";
2961
[828]2962                $mail->error_count = 0; // reset errors
2963                $mail->SetMessageType();
2964                $header = $mail->CreateHeader();
[1472]2965                $body = $mail->CreateBody();
[828]2966
[1472]2967                $mbox_stream = $this->open_mbox($folder);
[271]2968                $new_header = str_replace("\n", "\r\n", $header);
2969                $new_body = str_replace("\n", "\r\n", $body);
[830]2970                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
[271]2971                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2972                $return['msg_no'] = $status->uidnext - 1;
2973                $return['folder_id'] = $folder;
[828]2974
[51]2975                if($mbox_stream)
2976                        imap_close($mbox_stream);
[1472]2977                if (is_array($return_files))
[828]2978                        foreach ($return_files as $index => $_attachment) {
2979                                if (array_key_exists("name",$_attachment)){
[271]2980                                unset($return_files[$index]);
2981                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2982                        }
2983                        else
2984                        {
2985                                unset($return_files[$index]);
2986                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2987                        }
2988                }
[1472]2989
[271]2990                $return['files'] = serialize($return_files);
[673]2991                $return["subject"] = $subject;
[1472]2992
[3571]2993                if (!$return['append']) {
[2]2994                        $return['append'] = imap_last_error();
[3571]2995                        $return['has_error'] = true;
2996                }
[1472]2997
[2]2998                return $return;
2999        }
[1472]3000
[2]3001        function set_messages_flag($params)
3002        {
3003                $folder = $params['folder'];
[4782]3004                $rowids_to_set = $params['msgs_to_set']; // contains the row ids
[2]3005                $flag = $params['flag'];
3006                $return = array();
[4782]3007                $return["rowids_to_set"] = $rowids_to_set;
[2]3008                $return["flag"] = $flag;
[1472]3009
[4782]3010                $msgs_to_set = '';
3011                foreach (explode(',',$rowids_to_set) as $msg) {//extracting message ids
3012                        $pos = strpos($msg,'_');
3013                        if ($pos===false)
3014                                $msgs_to_set .= ','.$msg;
3015                        else
3016                                $msgs_to_set .= ','.substr($msg,0,$pos);
3017                }
3018                $msgs_to_set = substr($msgs_to_set,1);
3019                $return["msgs_to_set"] = $msgs_to_set;
3020
[411]3021                if(!$this->mbox && !is_resource($this->mbox))
[51]3022                        $this->mbox = $this->open_mbox($folder);
[1472]3023
[2]3024                if ($flag == "unseen")
[51]3025                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]3026                elseif ($flag == "seen")
[51]3027                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]3028                elseif ($flag == "answered"){
[51]3029                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
3030                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]3031                }
3032                elseif ($flag == "forwarded")
[51]3033                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]3034                elseif ($flag == "flagged")
[51]3035                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[614]3036                elseif ($flag == "unflagged") {
3037                        $flag_importance = false;
3038                        $msgs_number = explode(",",$msgs_to_set);
[659]3039                        $unflagged_msgs = "";
[614]3040                        foreach($msgs_number as $msg_number) {
3041                                preg_match('/importance *: *(.*)\r/i',
3042                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]3043                                        ,$importance);
[673]3044                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]3045                                        $flag_importance=true;
3046                                }
[659]3047                                else {
3048                                        $unflagged_msgs.=$msg_number.",";
[1472]3049                                }
[614]3050                        }
3051
[659]3052                        if($unflagged_msgs!="") {
3053                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
3054                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
3055                        }
3056                        else {
3057                                $return["msgs_unflageds"] = false;
3058                        }
3059
[673]3060                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]3061                                $return["status"] = false;
3062                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
3063                        }
[659]3064                        else {
3065                                $return["status"] = true;
3066                        }
[614]3067                }
[1472]3068
[411]3069                if($this->mbox && is_resource($this->mbox))
[51]3070                        imap_close($this->mbox);
[2]3071                return $return;
3072        }
[1472]3073
[2]3074        function get_file_type($file_name)
3075        {
3076                $file_name = strtolower($file_name);
3077                $strFileType = strrev(substr(strrev($file_name),0,4));
[1472]3078                if ($strFileType == ".asf")
[2]3079                        return "video/x-ms-asf";
3080                if ($strFileType == ".avi")
3081                        return "video/avi";
3082                if ($strFileType == ".doc")
3083                        return "application/msword";
3084                if ($strFileType == ".zip")
3085                        return "application/zip";
3086                if ($strFileType == ".xls")
3087                        return "application/vnd.ms-excel";
3088                if ($strFileType == ".gif")
3089                        return "image/gif";
3090                if ($strFileType == ".jpg" || $strFileType == "jpeg")
3091                        return "image/jpeg";
3092                if ($strFileType == ".png")
3093                        return "image/png";
3094                if ($strFileType == ".wav")
3095                        return "audio/wav";
3096                if ($strFileType == ".mp3")
3097                        return "audio/mpeg3";
3098                if ($strFileType == ".mpg" || $strFileType == "mpeg")
3099                        return "video/mpeg";
3100                if ($strFileType == ".rtf")
3101                        return "application/rtf";
3102                if ($strFileType == ".htm" || $strFileType == "html")
3103                        return "text/html";
[1472]3104                if ($strFileType == ".xml")
[2]3105                        return "text/xml";
[1472]3106                if ($strFileType == ".xsl")
[2]3107                        return "text/xsl";
[1472]3108                if ($strFileType == ".css")
[2]3109                        return "text/css";
[1472]3110                if ($strFileType == ".php")
[2]3111                        return "text/php";
[1472]3112                if ($strFileType == ".asp")
[2]3113                        return "text/asp";
3114                if ($strFileType == ".pdf")
3115                        return "application/pdf";
3116                if ($strFileType == ".txt")
3117                        return "text/plain";
3118                if ($strFileType == ".wmv")
3119                        return "video/x-ms-wmv";
3120                if ($strFileType == ".sxc")
3121                        return "application/vnd.sun.xml.calc";
3122                if ($strFileType == ".stc")
3123                        return "application/vnd.sun.xml.calc.template";
3124                if ($strFileType == ".sxd")
3125                        return "application/vnd.sun.xml.draw";
3126                if ($strFileType == ".std")
3127                        return "application/vnd.sun.xml.draw.template";
3128                if ($strFileType == ".sxi")
3129                        return "application/vnd.sun.xml.impress";
3130                if ($strFileType == ".sti")
3131                        return "application/vnd.sun.xml.impress.template";
3132                if ($strFileType == ".sxm")
3133                        return "application/vnd.sun.xml.math";
3134                if ($strFileType == ".sxw")
3135                        return "application/vnd.sun.xml.writer";
3136                if ($strFileType == ".sxq")
3137                        return "application/vnd.sun.xml.writer.global";
3138                if ($strFileType == ".stw")
3139                        return "application/vnd.sun.xml.writer.template";
[1472]3140
3141
3142                return "application/octet-stream";
[2]3143        }
[1472]3144
[2]3145        function htmlspecialchars_encode($str)
3146        {
[449]3147                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]3148        }
3149        function htmlspecialchars_decode($str)
3150        {
[449]3151                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]3152        }
[1472]3153
[828]3154        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
3155        {
3156                if(!$this->mbox || !is_resource($this->mbox))
[51]3157                        $this->mbox = $this->open_mbox($folder);
[432]3158
[828]3159                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
3160        }
[1472]3161
[53]3162        function get_info_next_msg($params)
3163        {
3164                $msg_number = $params['msg_number'];
3165                $folder = $params['msg_folder'];
3166                $sort_box_type = $params['sort_box_type'];
3167                $sort_box_reverse = $params['sort_box_reverse'];
3168                $reuse_border = $params['reuse_border'];
3169                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[1472]3170                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3171
[320]3172                $success = false;
3173                if (is_array($sort_array_msg))
[2]3174                {
[320]3175                        foreach ($sort_array_msg as $i => $value){
3176                                if ($value == $msg_number)
3177                                {
3178                                        $success = true;
3179                                        break;
3180                                }
3181                        }
[2]3182                }
3183
[320]3184                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]3185                {
3186                        $params['status'] = 'false';
3187                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3188                        return $params;
3189                }
[1472]3190
[2]3191                $params = array();
3192                $params['msg_number'] = $sort_array_msg[($i+1)];
3193                $params['msg_folder'] = $folder;
[1472]3194
3195                $return = $this->get_info_msg($params);
[2]3196                $return["reuse_border"] = $reuse_border;
3197                return $return;
3198        }
3199
3200        function get_info_previous_msg($params)
3201        {
3202                $msg_number = $params['msgs_number'];
3203                $folder = $params['folder'];
3204                $sort_box_type = $params['sort_box_type'];
3205                $sort_box_reverse = $params['sort_box_reverse'];
3206                $reuse_border = $params['reuse_border'];
[53]3207                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3208                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[1472]3209
[320]3210                $success = false;
3211                if (is_array($sort_array_msg))
[2]3212                {
[320]3213                        foreach ($sort_array_msg as $i => $value){
3214                                if ($value == $msg_number)
3215                                {
3216                                        $success = true;
3217                                        break;
3218                                }
3219                        }
[2]3220                }
[320]3221                if (! $success || $i == 0)
3222                {
[2]3223                        $params['status'] = 'false';
3224                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3225                        return $params;
3226                }
[1472]3227
[2]3228                $params = array();
3229                $params['msg_number'] = $sort_array_msg[($i-1)];
3230                $params['msg_folder'] = $folder;
[1472]3231
[2]3232                $return = $this->get_info_msg($params);
3233                $return["reuse_border"] = $reuse_border;
3234                return $return;
3235        }
[1472]3236
[2]3237        // This function updates the values: quota, paging and new messages menu.
3238        function get_menu_values($params){
3239                $return_array = array();
3240                $return_array = $this->get_quota($params);
[1472]3241
[2]3242                $mbox_stream = $this->open_mbox($params['folder']);
[1472]3243                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
[51]3244                if($mbox_stream)
3245                        imap_close($mbox_stream);
[1472]3246
3247                return $return_array;
[2]3248        }
[1472]3249
[325]3250        function get_quota($params){
[449]3251                // folder_id = user/{uid} for shared folders
3252                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
3253                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
[1472]3254                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
[449]3255                }
3256                // folder_id = INBOX for inbox folders
3257                else
[6516]3258                {   
[449]3259                        $folder_id = "INBOX";
[6657]3260                        $folderQuotas = $this->get_quotaroot(array('folder' => 'INBOX/Arquivo Remoto'));
3261                        if($folderQuotas['quota_limit'] == 0)
3262                            $folderQuotas = false;
[6516]3263                }
[6474]3264               
3265               
[1035]3266                if(!$this->mbox || !is_resource($this->mbox))
[51]3267                        $this->mbox = $this->open_mbox();
[345]3268
[325]3269                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]3270                if($this->mbox && is_resource($this->mbox))
[51]3271                        imap_close($this->mbox);
[1472]3272
[2]3273                if (!$quota){
3274                        return array(
3275                                'quota_percent' => 0,
3276                                'quota_used' => 0,
3277                                'quota_limit' =>  0
3278                        );
3279                }
[1472]3280
[2]3281                if(count($quota) && $quota['limit']) {
[3064]3282                        $quota_limit = $quota['limit'];
3283                        $quota_used  = $quota['usage'];
[2]3284                        if($quota_used >= $quota_limit)
[650]3285                        {
3286                                $quotaPercent = 100;
3287                        }
3288                        else
3289                        {
[2]3290                        $quotaPercent = ($quota_used / $quota_limit)*100;
3291                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
[650]3292                        }
[6474]3293                       
[2]3294                        return array(
3295                                'quota_percent' => floor($quotaPercent),
[3064]3296                                'quota_used' => $quota_used,
[6474]3297                                'quota_limit' =>  $quota_limit,
3298                                'quota_folder' => $folderQuotas
[2]3299                        );
[6474]3300                       
[2]3301                }
[1472]3302                else
[2]3303                        return array();
3304        }
[1472]3305
[6474]3306        function get_quotaroot($params){
3307                if(!$this->mbox || !is_resource($this->mbox))
3308                        $this->mbox = $this->open_mbox();
3309
3310                $quota = imap_get_quotaroot($this->mbox, $params['folder']);
3311                if($this->mbox && is_resource($this->mbox))
3312                        imap_close($this->mbox);
3313
3314                if (!$quota){
3315                        return array(
3316                                'quota_percent' => 0,
3317                                'quota_used' => 0,
3318                                'quota_limit' =>  0,
3319                                'quota_root' => ''
3320                        );
3321                }
3322
3323                // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3324                include_once("class.imapfp.inc.php");
3325                $imapfp = new imapfp();
3326
3327                if(!$imapfp->open($this->imap_server,$this->imap_port))
3328                        return $imapfp->get_error();
3329                if (!$imapfp->login($this->username,$this->password))
3330                        return $imapfp->get_error();
3331
3332                if ($imapfp->put_line($imapfp->tag." GETQUOTAROOT \"".$params['folder']."\"")) {
3333                        $response=$imapfp->get_server_responce();
3334
3335                        if(substr($response,strpos($response,"$imapfp->tag ")+strlen($imapfp->tag)+1,2)!="OK") {
3336                                $imapfp->error= "Error : $response !<br>";
3337                                return $imapfp->get_error();
3338                        }
3339                }
3340                else
3341                {
3342                        $imapfp->error= "Error : Could not send User request. <br>";
3343                        return $imapfp->get_error();
3344                }
3345                $response_array = split("\r\n", $response);
3346                array_pop($response_array);
3347                array_pop($response_array);
3348                array_shift($response_array);
3349               
3350                $response_array[0]=substr($response_array[0],strpos($response_array[0],"QUOTAROOT"));
3351                $quota['quota_root']=substr(str_replace("\"","",$response_array[0]),/*strlen("QUOTAROOT ... ")=*/11+strlen($params['folder']));
3352                $imapfp->close();
3353
3354                if(count($quota) && $quota['limit']) {
3355                        $quota_limit = $quota['limit'];
3356                        $quota_used  = $quota['usage'];
3357                        $quota_root  = $quota['quota_root'];
3358                        if($quota_used >= $quota_limit)
3359                        {
3360                                $quotaPercent = 100;
3361                        }
3362                        else
3363                        {
3364                        $quotaPercent = ($quota_used / $quota_limit)*100;
3365                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3366                        }
3367                        return array(
3368                                'quota_percent' => floor($quotaPercent),
3369                                'quota_used' => $quota_used,
3370                                'quota_limit' =>  $quota_limit,
3371                                'quota_root' => $quota_root
3372                        );
3373                }
3374                else
3375                        return array();
3376        }
3377
[2]3378        function send_notification($params){
[3231]3379                include("../header.inc.php");
[2]3380                require_once("class.phpmailer.php");
3381                $mail = new PHPMailer();
[1472]3382
[2]3383                $toaddress = $params['notificationto'];
[1472]3384
[3231]3385                $subject = lang("Read receipt: %1",$params['subject']);
3386                $body = lang("Your message: %1",$params['subject']) . '<br>';
[4578]3387                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
[3231]3388                $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]3389                $mail->SMTPDebug = false;
3390                $mail->IsSMTP();
3391                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
3392                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
3393                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3394                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
3395                $mail->AddAddress($toaddress);
3396                $mail->Subject = $this->htmlspecialchars_decode($subject);
3397
3398                $mail->IsHTML(true);
3399                $mail->Body = $body;
[1472]3400
[2]3401                if(!$mail->Send()){
3402                        return $mail->ErrorInfo;
3403                }
3404                else
3405                        return true;
3406        }
[1472]3407
[1965]3408        function empty_folder($params)
[2]3409        {
[1965]3410                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
[2]3411                $mbox_stream = $this->open_mbox($folder);
3412                $return = imap_delete($mbox_stream,'1:*');
[51]3413                if($mbox_stream)
3414                        imap_close($mbox_stream, CL_EXPUNGE);
[2]3415                return $return;
3416        }
[1472]3417
[2]3418        function search($params)
3419        {
[673]3420                include("class.imap_attachment.inc.php");
[1472]3421                $imap_attachment = new imap_attachment();
[2]3422                $criteria = $params['criteria'];
3423                $return = array();
3424                $folders = $this->get_folders_list();
[1472]3425
[2]3426                $j = 0;
3427                foreach($folders as $folder)
3428                {
3429                        $mbox_stream = $this->open_mbox($folder);
3430                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[1472]3431
[2]3432                        if ($messages == '')
3433                                continue;
[1472]3434
[2]3435                        $i = 0;
3436                        $return[$j] = array();
3437                        $return[$j]['folder_name'] = $folder['name'];
[1472]3438
[2]3439                        foreach($messages as $msg_number)
3440                        {
[535]3441                                $header = $this->get_header($msg_number);
[2]3442                                if (!is_object($header))
3443                                        return false;
[1472]3444
[2]3445                                $return[$j][$i]['msg_folder']   = $folder['name'];
3446                                $return[$j][$i]['msg_number']   = $msg_number;
3447                                $return[$j][$i]['Recent']               = $header->Recent;
3448                                $return[$j][$i]['Unseen']               = $header->Unseen;
3449                                $return[$j][$i]['Answered']     = $header->Answered;
3450                                $return[$j][$i]['Deleted']              = $header->Deleted;
3451                                $return[$j][$i]['Draft']                = $header->Draft;
3452                                $return[$j][$i]['Flagged']              = $header->Flagged;
[1472]3453
[535]3454                                $date_msg = gmdate("d/m/Y",$header->udate);
3455                                if (gmdate("d/m/Y") == $date_msg)
3456                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]3457                                else
3458                                        $return[$j][$i]['udate'] = $date_msg;
[1472]3459
[2]3460                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3461                                $return[$j][$i]['fromaddress'] = '';
3462                                foreach ($fromaddress as $tmp)
3463                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[1472]3464
[2]3465                                $from = $header->from;
3466                                $return[$j][$i]['from'] = array();
3467                                $tmp = imap_mime_header_decode($from[0]->personal);
3468                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3469                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]3470                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]3471
3472                                $to = $header->to;
3473                                $return[$j][$i]['to'] = array();
3474                                $tmp = imap_mime_header_decode($to[0]->personal);
3475                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3476                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[1472]3477                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]3478
3479                                $subject = imap_mime_header_decode($header->fetchsubject);
3480                                $return[$j][$i]['subject'] = '';
3481                                foreach ($subject as $tmp)
3482                                        $return[$j][$i]['subject'] .= $tmp->text;
3483
3484                                $return[$j][$i]['Size'] = $header->Size;
3485                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]3486
[2]3487                                $return[$j][$i]['attachment'] = array();
3488                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[1472]3489
[2]3490                                $i++;
3491                        }
3492                        $j++;
[51]3493                        if($mbox_stream)
3494                                imap_close($mbox_stream);
[2]3495                }
[1472]3496
[2]3497                return $return;
3498        }
[3923]3499
[5107]3500        function ac_search($params)
3501        {
3502                include("class.imap_attachment.inc.php");
3503                $imap_attachment = new imap_attachment();
3504                $criterias = array ("TO","SUBJECT","FROM","CC");
3505                $return = array();
3506                $folders = $this->get_folders_list();
3507                $num_msgs = 0;
[3923]3508
[5107]3509                foreach($folders as $id =>$folder)
3510                {
3511                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3512                                foreach($criterias as $criteria_fixed)
3513                    {
3514                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3515                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3516
3517                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3518
3519                                        if ($messages == ''){
3520                                                if($mbox_stream)
3521                                                        imap_close($mbox_stream);
3522                                                continue;
3523                                        }
3524
3525                                        foreach($messages as $msg_number)
3526                                        {
3527                                                $temp = $this->get_info_head_msg($msg_number);
3528                                                if(!$temp)
3529                                                        return false;
3530
3531                                                $return[$num_msgs] = $temp;
3532                                                $num_msgs++;
3533                                        }
3534                                        $return['num_msgs'] = $num_msgs;
3535
3536                                        if($mbox_stream)
3537                                                imap_close($mbox_stream);
3538                                }
3539                        }
3540
3541                }
3542                return $return;
3543        }
3544
[1709]3545        function mobile_search($params)
3546        {
3547                include("class.imap_attachment.inc.php");
3548                $imap_attachment = new imap_attachment();
3549                $criterias = array ("TO","SUBJECT","FROM","CC");
3550                $return = array();
[3589]3551                if(!isset($params['folder'])) {
3552                        $folder_params = array("noSharedFolders"=>1);
3553                        if(isset($params['folderType']))
3554                                $folder_params['folderType'] = $params['folderType'];
3555                        $folders = $this->get_folders_list($folder_params);
3556                }
3557                else
3558                        $folders = array(0=>array('folder_id'=>$params['folder']));
[1709]3559                $num_msgs = 0;
[3923]3560                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
3561                $return["msgs"] = array();
3562               
3563                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
[1709]3564                foreach($folders as $id =>$folder)
3565                {
3566                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3567                                foreach($criterias as $criteria_fixed)
[3923]3568                                {
3569                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3570
[3573]3571                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
[3923]3572
3573                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
[1709]3574                                       
3575                                        if ($messages == ''){
3576                                                if($mbox_stream)
3577                                                        imap_close($mbox_stream);
3578                                                continue;       
3579                                        }
[3923]3580                                       
[1709]3581                                        foreach($messages as $msg_number)
[3923]3582                                        {
[1709]3583                                                $temp = $this->get_info_head_msg($msg_number);
3584                                                if(!$temp)
3585                                                        return false;
[3573]3586                                                $temp['msg_folder'] = $folder['folder_id'];
[3923]3587                                                $return["msgs"][$num_msgs] = $temp;
[1709]3588                                                $num_msgs++;
3589                                        }
[3923]3590
[1709]3591                                        if($mbox_stream)
3592                                                imap_close($mbox_stream);
3593                                }
[3923]3594                        }
[1709]3595                }
[3923]3596
3597                if(!function_exists("cmp_date")) {
3598                        function cmp_date($obj1, $obj2){
3599                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
3600                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
3601                        }
3602                }
3603                usort($return["msgs"], "cmp_date");
3604                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
3605                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
[4535]3606                $return["msgs"]['num_msgs'] = $num_msgs;
[3923]3607               
[1709]3608                return $return;
3609        }
[1472]3610
[2]3611        function delete_and_show_previous_message($params)
3612        {
3613                $return = $this->get_info_previous_msg($params);
[1472]3614
[2]3615                $params_tmp1 = array();
3616                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3617                $params_tmp1['folder'] = $params['msg_folder'];
3618                $return_tmp1 = $this->delete_msg($params_tmp1);
[1472]3619
[2]3620                $return['msg_number_deleted'] = $return_tmp1;
[1472]3621
[2]3622                return $return;
3623        }
[1472]3624
3625
[2]3626        function automatic_trash_cleanness($params)
3627        {
3628                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3629                $criteria =  'BEFORE "'.$before_date.'"';
[325]3630                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[3018]3631                // Free others requests
3632                session_write_close();
[2]3633                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3634                if (is_array($messages)){
3635                        foreach ($messages as $msg_number){
3636                                imap_delete($mbox_stream, $msg_number, FT_UID);
3637                        }
3638                }
[51]3639                if($mbox_stream)
3640                        imap_close($mbox_stream, CL_EXPUNGE);
[2]3641                return $messages;
3642        }
3643//      Fix the search problem with special characters!!!!
3644        function remove_accents($string) {
[1472]3645                return strtr($string,
3646                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]3647                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3648        }
3649
[4430]3650        function make_search_date($date,$before = false){
[1622]3651
3652
3653            //TODO: Adaptar a data de acordo com o locale do sistema.
3654            list($day,$month,$year) = explode("/", $date);
[4430]3655            $before?$day=(int)$day+1:$day=(int)$day;
3656            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
3657            $search_date = date('d-M-Y',$timestamp);
[1622]3658            return $search_date;
3659
3660        }
3661
[3843]3662        function search_msg( $params = false )
3663        {
3664                $mbox_stream = "";
3665               
3666                if(strpos($params['condition'],"#")===false)
3667                { //local messages
3668                        $search=false;
3669                }
3670                else
3671                {
3672                        $search = explode(",",$params['condition']);
3673                }
3674               
3675                $params['page'] = $params['page'] * 1;
[689]3676
[3843]3677            if( is_array($search) )
3678            {
3679                        $search = array_unique($search); // Remove duplicated folders
3680                        $search_criteria = '';
3681                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3682                        foreach($search as $tmp)
3683                        {
3684                                $tmp1 = explode("##",$tmp);
3685                                $sum = 0;
3686                                $name_box = $tmp1[0];
3687                                unset($filter);
3688                                foreach($tmp1 as $index => $criteria)
3689                                {
3690                                        if ($index != 0 && strlen($criteria) != 0)
3691                                        {
3692                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3693                                                $filter .= " ".$filter_array[0];
3694                                                if (strlen($filter_array[1]) != 0)
3695                                                {
3696                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
3697                                                                 trim($filter_array[0]) != 'SINCE' &&
3698                                                                 trim($filter_array[0]) != 'ON')
3699                                                        {
3700                                                            $filter .= '"'.$filter_array[1].'"';
[4430]3701                                                        }else if(trim($filter_array[0]) == 'BEFORE' )
[3843]3702                                                        {
[4430]3703                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
3704                                                        }else{
3705                                                            $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3706                                                        }
[3843]3707                                                }
3708                                        }
3709                                }
3710                               
3711                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3712                                $filter = $this->remove_accents($filter);
[1472]3713
[3843]3714                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3715                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3716                                {
3717                                        $folder_name = explode($this->imap_delimiter,$name_box);
3718                                        $this->ldap = new ldap_functions();
3719                                       
3720                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3721                                        {
3722                                                $folder_name[1] = $cn;
3723                                        }
3724                                        $folder_name = implode($this->imap_delimiter,$folder_name);
[3391]3725                                }
[3843]3726                                else
3727                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3728                               
3729                                if(!is_resource($mbox_stream))
3730                                        $mbox_stream = $this->open_mbox($name_box);
3731                                else
3732                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3733                               
3734                                if (preg_match("/^.?\bALL\b/", $filter))
3735                                {
3736                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
3737                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3738                                           
3739                                        foreach($all_criterias as $criteria_fixed)
3740                                        {
3741                                                $_filter = $criteria_fixed . substr($filter,4);
3742                                               
3743                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3744                                               
3745                                                if(is_array($search_criteria))
3746                                                {
3747                                                        foreach($search_criteria as $new_search)
3748                                                        {
3749                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3750                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
[4485]3751                                                                $elem['uid'] = $new_search;
3752                                                                /* compare dates in ordering */
3753                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
[3843]3754                                                                $retorno[] = $elem;
3755                                                        }
3756                                                }
3757                                        }
3758                                }
[4068]3759                                else{
[4927]3760                                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
3761                                    {
3762                                        if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
3763                                        {
3764                                            $num_msgs = imap_num_msg($mbox_stream);
3765                                            $flagged_msgs = array();
3766                                            for ($i=$num_msgs; $i>0; $i--)
[4068]3767                                            {
[4927]3768                                                $iuid = @imap_uid($this->mbox,$i);
3769                                                $header = $this->get_header($iuid);
3770                                                if(trim($header->Flagged))
3771                                                {
3772                                                        $flagged_msgs[$i] = $iuid;
3773                                                }
[4068]3774                                            }
3775
[4927]3776                                            $new_filter = trim(preg_replace('/UNFLAGGED|FLAGGED/','',$filter));
3777
3778                                            $search_without_flagged = imap_search($mbox_stream, $new_filter, SE_UID);
3779
3780                                            if (strpos($filter,"UNFLAGGED") === false)
3781                                            {
3782                                                $search_criteria = array_intersect($search_without_flagged, $flagged_msgs);
3783                                            }
3784                                            else
3785                                            {
3786                                                $search_criteria = array_diff($search_without_flagged,$flagged_msgs);
3787                                            }
3788                                        }
3789                                        else
3790                                        {
3791                                            $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3792                                        }
3793                                    }
3794                                    else
3795                                    {
3796                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3797                                    }
3798
3799                                    if( is_array( $search_criteria) )
3800                                    {
3801                                        foreach($search_criteria as $new_search)
3802                                        {
3803                                            $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3804                                            $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3805                                            $elem['uid'] = $new_search;
3806                                            /* compare dates in ordering */
3807                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
3808                                            $retorno[] = $elem;
3809                                        }
3810                                    }
[3843]3811                                }
3812                        }
3813                }
3814               
3815                if($mbox_stream)
3816                {
3817                        imap_close($mbox_stream);
[3803]3818            }
[3843]3819           
[3803]3820            $num_msgs = count($retorno);
[3223]3821
[3803]3822            /* Comparison functions, descendent is ascendent with parms inverted */
[4485]3823            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
[3803]3824            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
[3391]3825
[3803]3826            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
3827            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
3828
3829            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
3830            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
3831
3832            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
3833            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
3834
3835            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
3836            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
3837
[3843]3838            usort( $retorno, $params['sort_type']);
3839            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
3840           
3841            $arrayRetorno['num_msgs']   =  $num_msgs;
3842            $arrayRetorno['data']               =  $pageret;
[4158]3843            $arrayRetorno['currentTab'] =  $params['current_tab'];
[3803]3844
[3843]3845                if ($pageret)
3846                {
3847                        return $arrayRetorno;
3848                }
3849                else
3850                {
3851                        return 'none';
3852                }
[2]3853        }
[1472]3854
[3803]3855        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
[271]3856        {
[828]3857                $header = $this->get_header($uid_msg);
[3803]3858                require_once("class.imap_attachment.inc.php");
[828]3859                $imap_attachment = new imap_attachment();
3860                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3861                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3862                $flag = $header->Unseen
3863                        .$header->Recent
3864                        .$header->Flagged
3865                        .$header->Draft
3866                        .$header->Answered
3867                        .$header->Deleted
3868                        .$attachments;
3869
3870
[163]3871                $subject = $this->decode_string($header->fetchsubject);
3872                $from = $header->from[0]->mailbox;
[2]3873                if($header->from[0]->personal != "")
3874                        $from = $header->from[0]->personal;
[3843]3875                $ret_msg['from']        = $this->decode_string($from);
3876                $ret_msg['subject']     = $subject;
3877                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
3878                $ret_msg['size']        = $header->Size;
3879                $ret_msg['flag']        = $flag;
[1472]3880                return $ret_msg;
3881        }
[3391]3882
3883
3884        function size_msg($size){
3885                $var = floor($size/1024);
3886                if($var >= 1){
3887                        return $var." kb";
3888                }else{
3889                        return $size ." b";
3890                }
3891        }
3892       
[2]3893        function ob_array($the_object)
3894        {
3895           $the_array=array();
3896           if(!is_scalar($the_object))
3897           {
3898               foreach($the_object as $id => $object)
3899               {
3900                   if(is_scalar($object))
3901                   {
3902                       $the_array[$id]=$object;
3903                   }
3904                   else
3905                   {
3906                       $the_array[$id]=$this->ob_array($object);
3907                   }
3908               }
3909               return $the_array;
3910           }
3911           else
3912           {
3913               return $the_object;
3914           }
3915        }
[1472]3916
[2]3917        function getacl()
3918        {
3919                $this->ldap = new ldap_functions();
[1472]3920
[2]3921                $return = array();
[1472]3922                $mbox_stream = $this->open_mbox();
[2]3923                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]3924
[2]3925                $i = 0;
3926                foreach ($mbox_acl as $user => $acl)
3927                {
3928                        if ($user != $this->username)
3929                        {
3930                                $return[$i]['uid'] = $user;
3931                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3932                        }
3933                        $i++;
3934                }
3935                return $return;
3936        }
[1472]3937
[2]3938        function setacl($params)
3939        {
3940                $old_users = $this->getacl();
3941                if (!count($old_users))
3942                        $old_users = array();
[1472]3943
[2]3944                $tmp_array = array();
3945                foreach ($old_users as $index => $user_info)
3946                {
3947                        $tmp_array[$index] = $user_info['uid'];
3948                }
3949                $old_users = $tmp_array;
[1472]3950
[2]3951                $users = unserialize($params['users']);
3952                if (!count($users))
3953                        $users = array();
[1472]3954
[2]3955                //$add_share = array_diff($users, $old_users);
3956                $remove_share = array_diff($old_users, $users);
3957
3958                $mbox_stream = $this->open_mbox();
3959
3960                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3961                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3962
3963                /*if (count($add_share))
3964                {
3965                        foreach ($add_share as $index=>$uid)
3966                        {
3967                        if (is_array($mailboxes_list))
3968                        {
3969                        foreach ($mailboxes_list as $key => $val)
3970                        {
3971                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3972                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3973                        }
3974                        }
3975                        }
3976                }*/
[1472]3977
[2]3978                if (count($remove_share))
3979                {
3980                        foreach ($remove_share as $index=>$uid)
3981                        {
[4579]3982                            if (is_array($mailboxes_list))
3983                            {
3984                                foreach ($mailboxes_list as $key => $val)
3985                                {
3986                                    $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3987                                    $folder = str_replace("&-", "&", $folder);
3988                                    imap_setacl ($mbox_stream, $folder, "$uid", "");
3989                                }
3990                            }
[1472]3991                        }
[2]3992                }
[1472]3993
[2]3994                return true;
3995        }
[1472]3996
[2]3997        function getaclfromuser($params)
3998        {
3999                $useracl = $params['user'];
[1472]4000
[2]4001                $return = array();
4002                $return[$useracl] = 'false';
[1472]4003                $mbox_stream = $this->open_mbox();
[2]4004                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]4005
[2]4006                foreach ($mbox_acl as $user => $acl)
4007                {
4008                        if (($user != $this->username) && ($user == $useracl))
4009                        {
4010                                $return[$user] = $acl;
4011                        }
4012                }
4013                return $return;
4014        }
4015
4016        function getacltouser($user)
4017        {
4018                $return = array();
4019                $mbox_stream = $this->open_mbox();
[325]4020                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4021                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
4022                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
4023                if(substr($user,0,4) != 'user')
[449]4024                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]4025                else
4026                  $mbox_acl = imap_getacl($mbox_stream, $user);
[2]4027                return $mbox_acl[$this->username];
4028        }
4029
[1472]4030
[2]4031        function setaclfromuser($params)
4032        {
4033                $user = $params['user'];
4034                $acl = $params['acl'];
[1472]4035
[2]4036                $mbox_stream = $this->open_mbox();
4037
4038                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4039                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4040
4041                if (is_array($mailboxes_list))
4042                {
4043                        foreach ($mailboxes_list as $key => $val)
4044                        {
[449]4045                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
4046                                $folder = str_replace("&-", "&", $folder);
[2]4047                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
4048                                {
[449]4049                                        $return = imap_last_error();
[2]4050                                }
4051                        }
4052                }
[449]4053                if (isset($return))
4054                        return $return;
4055                else
4056                        return true;
[2]4057        }
[1472]4058
[51]4059        function download_attachment($msg,$msgno)
4060        {
[1472]4061                $array_parts_attachments = array();
[3289]4062                //$array_parts_attachments['names'] = '';
[689]4063                include_once("class.imap_attachment.inc.php");
[1472]4064                $imap_attachment = new imap_attachment();
4065
[51]4066                if (count($msg->fname[$msgno]) > 0)
4067                {
4068                        $i = 0;
4069                        foreach ($msg->fname[$msgno] as $index=>$fname)
4070                        {
4071                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
[1397]4072                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
[51]4073                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
4074                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
[3289]4075                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
[51]4076                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
4077                                $i++;
4078                        }
4079                }
[3289]4080                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
[51]4081                return $array_parts_attachments;
[1472]4082        }
[69]4083
4084        function spam($params)
4085        {
4086                $is_spam = $params['spam'];
4087                $folder = $params['folder'];
4088                $mbox_stream = $this->open_mbox($folder);
4089                $msgs_number = explode(',',$params['msgs_number']);
4090
4091                foreach($msgs_number as $msg_number) {
[877]4092                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
4093                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
4094                        $body = imap_body($mbox_stream, $imap_msg_number);
[69]4095                        $msg = $header . $body;
4096                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]4097                        $username = $this->username;
[69]4098                        strtok($email, '@');
4099                        $domain = strtok('@');
4100
[449]4101                        //Encontrar a assinatura do dspam no cabecalho
4102                        $v = explode("\r\n", $header);
4103                        foreach ($v as $linha){
[877]4104                                if (eregi("^Message-ID", $linha)) {
4105                                        $args = explode(" ", $linha);
4106                                        $msg_id = "'$args[1]'";
4107                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
[449]4108                                        $args = explode(" ",$linha);
4109                                        $signature = $args[1];
4110                                }
4111                        }
4112
[877]4113                        // Seleciona qual comando a ser executado
[449]4114                        switch($is_spam){
4115                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
4116                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
4117                        }
[877]4118
4119                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
4120                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
[78]4121                        system($cmd);
[69]4122                }
4123                imap_close($mbox_stream);
4124                return false;
4125        }
[535]4126        function get_header($msg_number){
[3493]4127                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[535]4128                if (!is_object($header))
4129                        return false;
[1472]4130
[673]4131                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[659]4132                        $flag = preg_match('/importance *: *(.*)\r/i',
4133                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]4134                                                ,$importance);
[659]4135                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
4136                }
[1472]4137
[535]4138                return $header;
4139        }
[1000]4140
[3911]4141    function insert_email($source,$folder,$timestamp,$flags){
[1000]4142        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
4143        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
4144        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
4145        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
4146        $imap_options = '/notls/novalidate-cert';
[6561]4147        $mbox_stream = $this->open_mbox($folder);
4148        //$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
4149        if($folder == "INBOX/decifradas" && imap_last_error() && imap_last_error() != "SECURITY PROBLEM: insecure server advertised AUTH=PLAIN")
[1000]4150        {
4151            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
[5187]4152        }
[6482]4153        $return = array();
[1000]4154        if($timestamp){
[6561]4155            if(version_compare(PHP_VERSION, '5.3.2', '>=')){
4156                $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"), $source,'',date('d-M-Y H:i:s O',$timestamp));
4157            }else{
4158                $tempDir = $_SESSION['phpgw_info']['server']['temp_dir'];
4159                $file = $tempDir."/imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
4160                    $f = fopen($file,"w");
4161                    fputs($f,base64_encode($source));
4162                fclose($f);
[6657]4163                $folder = base64_encode(mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"));
[6561]4164                $command = "python ".$_SERVER['DOCUMENT_ROOT']."/expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." '".$folder."' ".escapeshellarg($file);
4165                $return['command']=exec(escapeshellcmd($command));
4166            }
[1000]4167        }else{
[6561]4168            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"), $source, "\\Seen");
[1000]4169        }
[6482]4170       
4171        if (!empty($return['command']))
4172        {
4173            list ($result, $msg) = explode(':',$return['command']);
4174            if (strtoupper($result) === 'NO')
4175            {
4176                $return['error'] = $msg;
4177                return $return;
4178            }
4179        }
4180       
[6561]4181        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"), SA_UIDNEXT);
[5187]4182
[1000]4183        $return['msg_no'] = $status->uidnext - 1;
[5187]4184        $return['error'] = '';
4185        if(imap_last_error() && imap_last_error() != "SECURITY PROBLEM: insecure server advertised AUTH=PLAIN")
4186            $return['error'] = imap_last_error();
[3872]4187
[5187]4188        if(!$return['error'] && $flags != '' ){
4189
[3911]4190                  $flags_array=explode(':',$flags);
4191                  //"Answered","Draft","Flagged","Unseen"
4192                  $flags_fixed = "";
4193                  if($flags_array[0] == 'A')
4194                        $flags_fixed.="\\Answered ";
4195                  if($flags_array[1] == 'X')
4196                        $flags_fixed.="\\Draft ";
4197                  if($flags_array[2] == 'F')
4198                        $flags_fixed.="\\Flagged ";
4199                  if($flags_array[3] != 'U')
4200                        $flags_fixed.="\\Seen ";
4201
4202                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
4203                }
[1000]4204        if($mbox_stream)
[3911]4205            imap_close($mbox_stream);
[1000]4206        return $return;
4207    }
4208
[4869]4209    function show_decript($params,$dec=0){
[1035]4210        $source = $params['source'];
[4869]4211        //error_log("source: $source\nversao: " . PHP_VERSION);
[1472]4212
[4869]4213        if ($dec == 0)
4214        {
4215            $source = str_replace(" ", "+", $source,$i);
4216            if (version_compare(PHP_VERSION, '5.2.0', '>=')){
4217                if(!$source = base64_decode($source,true))
[6474]4218                    return "error ".$source."Espaï¿?os ".$i;
[1035]4219
[4869]4220            }
4221            else {
4222                if(!$source = base64_decode($source))
[6474]4223                    return "error ".$source."Espaï¿?os ".$i;
[4869]4224            }
4225
[1035]4226        }
[3803]4227
[1035]4228        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4229
4230                $get['msg_number'] = $insert['msg_no'];
4231                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
4232                $return = $this->get_info_msg($get);
4233                $get['msg_number'] = $params['ID'];
4234                $get['msg_folder'] = $params['folder'];
4235                $tmp = $this->get_info_msg($get);
4236                if(!$tmp['status_get_msg_info'])
4237                {
4238                        $return['msg_day']=$tmp['msg_day'];
4239                        $return['msg_hour']=$tmp['msg_hour'];
4240                        $return['fulldate']=$tmp['fulldate'];
4241                        $return['smalldate']=$tmp['smalldate'];
4242                }
4243                else
4244                {
4245                        $return['msg_day']='';
4246                        $return['msg_hour']='';
4247                        $return['fulldate']='';
4248                        $return['smalldate']='';
4249                }
4250        $return['msg_no'] =$insert['msg_no'];
4251        $return['error'] = $insert['error'];
4252        $return['folder'] = $params['folder'];
4253        //$return['acls'] = $insert['acls'];
4254        $return['original_ID'] =  $params['ID'];
4255
4256        return $return;
4257
4258    }
[1472]4259
[1000]4260//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
4261//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
4262
4263    function treat_base64_from_post($source){
4264            $offset = 0;
4265            do
4266            {
4267                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
4268                    {
4269                            $inicio = strpos($source, "\n\r", $inicio);
4270                            $fim = strpos($source, '--', $inicio);
4271                            if(!$fim)
4272                                    $fim = strpos($source,"\n\r", $inicio);
4273                            $length = $fim-$inicio;
4274                            $parte = substr( $source,$inicio,$length-1);
4275                            $parte = str_replace(" ", "+", $parte);
4276                            $source = substr_replace($source, $parte, $inicio, $length-1);
4277                    }
4278                    if($offset > $inicio)
4279                    $offset=FALSE;
4280                    else
4281                    $offset = $inicio;
4282            }
4283            while($offset);
4284            return $source;
4285    }
4286
4287//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.
4288
4289    function unarchive_mail($params)
4290    {
[6561]4291        $dest_folder = urldecode($params['folder']);
[1000]4292        $sources = explode("#@#@#@",$params['source']);
4293        $timestamps = explode("#@#@#@",$params['timestamp']);
[3911]4294        $flags = explode("#@#@#@",$params['flags']);
[6264]4295        $ids = explode("#@#@#@",$params['id']);
[6340]4296        $return = array();
4297        $archived = array();
4298        $error = array();
[3872]4299
[3843]4300        foreach($sources as $index=>$src)
4301        {
4302            if($src!="")
4303            {
[3911]4304                $source = $this->treat_base64_from_post($src);
4305                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
[6340]4306                if($insert['error'])
4307                {
4308                    $error[] = $ids[$index];
[6474]4309            }
[6340]4310                else
4311                {
4312                    $archived[] = $ids[$index];
[6474]4313        }
[3911]4314            }
4315        }
[3843]4316       
[6340]4317        if (!empty($error))
4318        {
4319            $return['error'] = $error;
[6474]4320    }
[6340]4321        if (!empty($archived))
4322        {
4323            $return['archived'] = $archived;
4324        }
[6474]4325
[6264]4326        return $return;
[1000]4327    }
4328
4329    function download_all_local_attachments($params)
4330    {
4331        $source = $params['source'];
4332        $source = $this->treat_base64_from_post($source);
4333        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4334        $exporteml = new ExportEml();
4335        $params['num_msg']=$insert['msg_no'];
4336        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
4337        return $exporteml->download_all_attachments($params);
4338    }
[3157]4339    function get_quota_folders(){
4340
4341            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
4342            include_once("class.imapfp.inc.php");           
4343            $imapfp = new imapfp();
4344
4345            if(!$imapfp->open($this->imap_server,$this->imap_port))
4346                    return $imapfp->get_error();             
4347            if (!$imapfp->login( $this->username,$this->password ))
4348                    return $imapfp->get_error();
4349
4350            $response_array = $imapfp->get_mailboxes_size();
4351            if ($imapfp->error)
4352                    return $imapfp->get_error();
4353
[6474]4354            $data = array();
[6508]4355                $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
4356                $data["quota_root"] = $quota_root;
[3157]4357
4358            foreach ($response_array as $idx=>$line) {
4359                    $line2 = str_replace('"', "", $line);
4360                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
[6508]4361                    list($folder,$size) = explode(";",$line2);
4362                   
[6474]4363                    $quota=$this->get_quotaroot(array('folder' => $folder));
4364                    $isroot=(strpos($quota['quota_root'],$folder)!==false);
[6508]4365                    $quota_used = $isroot?$quota['quota_used']*1024:str_replace(")","",$size);
4366                    $hasquota=($quota['quota_root']!="");
4367                    $quotaPercent = ($hasquota?(($quota_used / 1024) / $quota['quota_limit'])*100:0);
[3157]4368                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
4369                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
4370                            $folder = $this->functions->getLang("Inbox");
4371                    }
4372                    else
4373                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
4374
[6474]4375                    $data[$folder] = array("quota_percent" => ($hasquota?sprintf("%.1f",round($quotaPercent,1)):''), "quota_used" => $quota_used, "quota_limit" => ($isroot && $folder!=$this->functions->getLang("Inbox")?$quota['quota_limit']:''));
[3157]4376            }
4377            $imapfp->close();
4378            return $data;
[6474]4379    }
4380        function get_folders_with_quota(){
4381
4382            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
4383            include_once("class.imapfp.inc.php");           
4384            $imapfp = new imapfp();
[6508]4385               
[6474]4386            if(!$imapfp->open($this->imap_server,$this->imap_port))
4387                    return $imapfp->get_error();             
4388            if (!$imapfp->login( $this->username,$this->password ))
4389                    return $imapfp->get_error();
4390
4391            $response_array = $imapfp->get_mailboxes_size();
4392            if ($imapfp->error)
4393                    return $imapfp->get_error();
4394
4395            $data = array();
4396
[6508]4397            foreach ($response_array as $idx=>$line) {
4398                    if($idx == 0)
4399                        continue;
4400                    $line2 = str_replace('"', "", $line);
[6474]4401                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
[6508]4402                    list($folder,$size) = explode(";",$line2);
[6474]4403                    $quota=$this->get_quotaroot(array('folder' => $folder));
4404                    $isroot=(strpos($quota['quota_root'],$folder)!==false);
4405                    if($isroot){
[6508]4406                        return $quota;
[6474]4407                    }
4408            }
4409            $imapfp->close();
4410            return false;
4411    }
4412   
4413   
[2]4414}
[6474]4415?>
Note: See TracBrowser for help on using the repository browser.