source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 3427

Revision 3427, 142.3 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1332 - Imagens quebradas no IE após o envio.

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