source: sandbox/2.2.0.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4560

Revision 4560, 155.1 KB checked in by airton, 13 years ago (diff)

Ticket #1820 - mobile - Ajuste para exibir a resposta da pesquisa - r4535

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