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

Revision 4870, 152.6 KB checked in by brunocosta, 13 years ago (diff)

Ticket #2172 - Implementada solução do ticket #2132

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