source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 1808

Revision 1808, 132.5 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #814 - Alteracoes referentes a melhoria descrita no ticket em questao

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