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

Revision 4773, 155.7 KB checked in by airton, 13 years ago (diff)

Ticket #828 - Problema de codificacao na exibicao de assunto de mensagem

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