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

Revision 4859, 151.2 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #2163 - Mensagem recebida em branco. Retirada do limite, em Kb, do corpo da mensagem.

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