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

Revision 4863, 151.4 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #2163 - Revert da revisão 4859, por já haver uma pref. de tratamento.

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