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

Revision 1897, 134.3 KB checked in by rodsouza, 14 years ago (diff)

Ticket #859 - Alterado a forma de manipular links na visualização do e-mail

  • 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) {
[1897]871                                                foreach($attachments ['attachment'] as $index => $attachment)
872                                                {
873                                                        if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) )
874                                                        {
875                                                                $obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] );
876
877                                                                $content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">';
878                                                                $content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">';
879
880                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Subject")
881                                                                        . ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>';
882
883                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>'
884                                                                        . $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) )
885                                                                        . '</td></tr>';
886
887                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>';
888
889                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>'
890                                                                        . $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) )
891                                                                        . '</td></tr>';
892
893                                                                if ( $obj->cc )
894                                                                        $content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>'
895                                                                                . $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) )
896                                                                                . '</td></tr>';
897
898                                                                $content .= '</table><br>';
899
[1489]900                                                                $content .= $this->decodeBody(
901                                                                        imap_fetchbody(
902                                                                                $this->mbox,
903                                                                                $msg_number,
904                                                                                ( $attachment['part_in_msg'] + (
905                                                                                        ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? 0 : 1 )
906                                                                                ) . ".1",
907                                                                                FT_UID
908                                                                        ),
909                                                                        $msg->encoding[ $msg_number ][ $values ],
910                                                                        $msg->charset[ $msg_number ][ $values ]
911                                                                );
[1472]912                                                                break;
[2]913                                                        }
914                                                }
915                                        }
916                                }
917                        }
918                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
919                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
[51]920                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
[25]921                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
[1472]922                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
[2]923                        }
[1472]924                }
[2]925                // Force message with flag Seen (imap_fetchbody not works correctly)
[1472]926                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
[2]927                $this->set_messages_flag($params);
[205]928                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
[2]929                $content = $this->replace_special_characters($content);
[51]930                $return['body'] = $content;
931                return $return;
[2]932        }
[1472]933
[2]934        function htmlfilter($body)
935        {
936                require_once('htmlfilter.inc');
[1472]937
[2]938                $tag_list = Array(
939                                false,
940                                'blink',
941                                'object',
942                                'meta',
943                                'html',
944                                'link',
945                                'frame',
946                                'iframe',
947                                'layer',
948                                'ilayer',
949                                'plaintext'
950                );
951
952                /**
953                * A very exclusive set:
954                */
955                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
956                $rm_tags_with_content = Array(
957                                'script',
958                                'style',
959                                'applet',
960                                'embed',
961                                'head',
962                                'frameset',
963                                'xml',
964                                'xmp'
965                );
966
967                $self_closing_tags =  Array(
968                                'img',
969                                'br',
970                                'hr',
971                                'input'
972                );
973
974                $force_tag_closing = true;
975
976                $rm_attnames = Array(
977                        '/.*/' =>
978                                Array(
979                                        '/target/i',
980                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
981                                        '/^dynsrc/i',
982                                        '/^datasrc/i',
983                                        '/^data.*/i',
984                                        '/^lowsrc/i'
985                                )
986                );
987
988                /**
989                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
990                 * some idea of what's going on here. :)
991                 */
992
993                $bad_attvals = Array(
994                '/.*/' =>
995                Array(
996                      '/.*/' =>
997                              Array(
998                                Array(
999                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1000                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1001                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1002                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1003                                      ),
1004                            Array(
1005                                              '\\1oddjob:\\2\\1',
1006                                          //'\\1uucp:\\2\\1', -> doclinks notes
1007                                      '\\1amaretto:\\2\\1',
1008                                          '\\1round:\\2\\1'
1009                                        )
[1472]1010                                    ),
1011
[2]1012                          '/^style/i' =>
1013                              Array(
1014                                        Array(
1015                                          '/expression/i',
1016                                              '/behaviou*r/i',
1017                                          '/binding/i',
1018                                              '/include-source/i',
1019                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1020                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1021                                         ),
1022                                        Array(
1023                                          'idiocy',
1024                                              'idiocy',
1025                                          'idiocy',
1026                                              'idiocy',
1027                                          'url(\\1http://securityfocus.com/\\1)',
1028                                          'url(\\1http://securityfocus.com/\\1)'
1029                                         )
1030                                )
1031                          )
1032                    );
1033
1034                $add_attr_to_tag = Array(
1035                                '/^a$/i' => Array('target' => '"_new"')
1036                );
[1472]1037
1038
[2]1039                $trusted_body = sanitize($body,
1040                                $tag_list,
1041                                $rm_tags_with_content,
1042                                $self_closing_tags,
1043                                $force_tag_closing,
1044                                $rm_attnames,
1045                                $bad_attvals,
1046                                $add_attr_to_tag
1047                );
[1472]1048
[2]1049            return $trusted_body;
1050        }
[1472]1051
[2]1052        function decodeBody($body, $encoding, $charset=null)
1053        {
1054                /**
1055                * replace e-mail by anchor.
1056                */
1057                // HTML Filter
[13]1058                //$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]1059        //$body = str_replace("\r\n", "\n", $body);
[2]1060                if ($encoding == 'quoted-printable')
[828]1061                {
1062                        /*
[1472]1063
[2]1064                        for($i=0;$i<256;$i++) {
1065                                $c1=dechex($i);
1066                                if(strlen($c1)==1){$c1="0".$c1;}
1067                                $c1="=".$c1;
1068                                $myqprinta[]=$c1;
1069                                $myqprintb[]=chr($i);
[1472]1070                        }
[828]1071                         */
[2]1072                        $body = str_replace($myqprinta,$myqprintb,($body));
1073                        $body = quoted_printable_decode($body);
[1472]1074                while (ereg("=\n", $body))
[2]1075                {
1076                        $body = ereg_replace ("=\n", '', $body);
1077                }
1078        }
[1472]1079        else if ($encoding == 'base64')
[2]1080        {
1081                $body = base64_decode($body);
1082        }
[1792]1083
[2]1084                // All other encodings are returned raw.
1085                if (strtolower($charset) == "utf-8")
1086                        return utf8_decode($body);
1087        else
1088                        return $body;
1089        }
[1472]1090
[205]1091        function process_embedded_images($msg, $msgno, $body, $msg_folder)
[2]1092        {
1093                if (count($msg->inline_id[$msgno]) > 0)
1094                {
1095                        foreach ($msg->inline_id[$msgno] as $index => $cid)
1096                        {
1097                                $cid = eregi_replace("<", "", $cid);
1098                                $cid = eregi_replace(">", "", $cid);
1099                                $msg_part = $msg->pid[$msgno][$index];
1100                                //$body = eregi_replace("alt=\"\"", "", $body);
1101                                $body = eregi_replace("<br/>", "", $body);
1102                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1103                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1104                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1105                        }
1106                }
[1472]1107
[2]1108                return $body;
1109        }
[1472]1110
[2]1111        function replace_special_characters($body)
1112        {
1113                // Suspected TAGS!
[1472]1114                /*$tag_list = Array(
[2]1115                        'blink','object','meta',
1116                        'html','link','frame',
1117                        'iframe','layer','ilayer',
1118                        'plaintext','script','style','img',
1119                        'applet','embed','head',
1120                        'frameset','xml','xmp');
1121                */
1122
[1472]1123                // Layout problem: Change html elements
1124                // with absolute position to relate position, CASE INSENSITIVE.
[1233]1125                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
[6]1126
[2]1127                $tag_list = Array('head','blink','object','frame',
1128                        'iframe','layer','ilayer','plaintext','script',
[63]1129                        'applet','embed','frameset','xml','xmp','style');
[2]1130
[1472]1131                $blocked_tags = array();
[2]1132                foreach($tag_list as $index => $tag) {
[1233]1133                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
[2]1134                        if($body != $new_body) {
1135                                $blocked_tags[] = $tag;
1136                        }
[1233]1137                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
[2]1138                }
[650]1139                // Malicious Code Remove
[1057]1140                $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]1141                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1142                foreach($rest[0] as $i => $val)
[1270]1143                        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]1144                        $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
[2]1145
[1707]1146                return  "<span>".$this-> replace_links($body);
[2]1147        }
1148
[1897]1149        function replace_links( $body )
1150        {
1151                $matches = array( );
[2]1152                // Verify exception.
[1897]1153                @preg_match( "/<a href=\"notes:\/\/\//", $body, $matches );
1154
1155                // If there is no exception, then open the link in new window.
1156                if ( count( $matches ) )
[449]1157                        return $body;
[1472]1158
[1897]1159                // All links should be moderated and they should only have the attribute 'target="blank"'.
[1707]1160                $pattern = '/<a[^>]+href="([^>"]+)"[^>]*>(.*)<\/a>/im';
1161                $replacement = '<a href="$1" target="_blank">$2</a>';
[1897]1162                $body = preg_replace( $pattern, $replacement, $body );
[1707]1163
[1897]1164                // Url found in the text and which is not a link yet should be replaced by one.
1165                $pattern = '/(^|\w>|[ \(\[])((http(s)?:\/\/)?([\w\d_\-@]{2,}(\.[\w\d~?\/_=&#;\-:@$]+)+))/im';
1166                $replacement = '$1<a href="http$4://$5" target="_blank">$2</a>';
1167                $body = preg_replace( $pattern, $replacement, $body );
[1707]1168
[1897]1169                // E-mail address in the text should create a new e-mail on ExpressoMail
1170                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1171                $replacement = '$1<a href="javascript:new_message_to(\'$2\')">$2</a>$3';
1172                $body = preg_replace( $pattern, $replacement, $body );
[1707]1173
[1897]1174                // If there is an link with a "mailto:" in href attribute, it will changed to create a new e-mail on ExpressoMail.
1175                $pattern = '/<a[^>]+href=["\']mailto:([^"]+)["\'][^>]*>([^<]+)<\/a>/im';
1176                $replacement = '<a href="javascript:new_message_to(\'$1\')">$2</a>';
1177                $body = preg_replace( $pattern, $replacement, $body );
[1707]1178
1179                return $body;
[2]1180        }
1181
[91]1182        function get_signature($msg, $msg_number, $msg_folder)
[1035]1183        {
[1174]1184        include_once("../security/classes/CertificadoB.php");
[1035]1185                include_once("class.db_functions.inc.php");
[91]1186                foreach ($msg->file_type[$msg_number] as $index => $file_type)
1187                {
[1035]1188            $sign = array();
1189                        $temp = $this->get_info_head_msg($msg_number);
1190                        if($temp['ContentType'] =='normal') return $sign;
[91]1191                        $file_type = strtolower($file_type);
[1472]1192                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]1193                        {
[1472]1194                                if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
[91]1195                                {
[1035]1196                                        if(!$this->mbox || !is_resource($this->mbox))
1197                                        $this->mbox = $this->open_mbox($msg_folder);
1198
1199                                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1200
1201                                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1202                                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1203
1204                                        $certificado = new certificadoB();
1205                                        $validade = $certificado->verificar($imap_msg);
1206
1207                                        if ($certificado->apresentado)
[109]1208                                        {
[1035]1209                                                $from = $header->from;
1210                                                foreach ($from as $id => $object) {
1211                                                        $fromname = $object->personal;
1212                                                    $fromaddress = $object->mailbox . "@" . $object->host;
[109]1213                                        }
[1035]1214                                                $sign_alert = '';
1215                                                foreach ($certificado->erros_ssl as $item)
1216                                                {
1217                                                        $check_error_msg = $this->functions->getLang($item);
1218                                                        /*
1219                                                         * Desabilite o teste abaixo para mostrar todas as mensagem
1220                                                         * de erro.
1221                                                         */
1222                                                        //if (!strpos($check_error_msg,'*',strlen($check_error_msg-1)))
1223                                                        //{
1224                                                        $sign[] = "<span style=color:red>" . $check_error_msg . " </span>";
1225                                                        //}
1226                                                }
1227                                                if (count($certificado->erros_ssl) < 1)
1228                                                {
1229                                                        $check_msg = $this->functions->getLang('Message untouched') . " ";
[1630]1230                                                        if(strtoupper($fromaddress) != strtoupper($certificado->dados['EMAIL']))
[1035]1231                                                        {
1232                                                                $check_msg .= $this->functions->getLang('and') . " ";
1233                                                                $check_msg .= $this->functions->getLang('authentic');
1234                                                        }
1235                                                        $sign[] = "<strong>".$check_msg."</strong>";
1236                                                }
[1630]1237                                                if(strtoupper($fromaddress) != strtoupper($certificado->dados['EMAIL']))
[1035]1238                                                {
1239                                                        $sign[] =       "<span style=color:red>" .
1240                                                                                $this->functions->getLang('message') . " " .
1241                                                                        $this->functions->getLang('with signer different from sender') .
1242                                                                        " </span>";
1243                                                }
1244                                                $sign[] = "<strong>" . $this->functions->getLang('Message signed by: ') . "</strong>" . $certificado->dados['NOME'];
1245                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate email: ') . "</strong>" . $certificado->dados['EMAIL'];
1246                                                $sign[] = "<strong>" . $this->functions->getLang('Mail from: ') . "</strong>" . $fromaddress;
1247                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate Authority: ') . "</strong>" . $certificado->dados['EMISSOR'];
1248                                                $sign[] = "<strong>" . $this->functions->getLang('Validity of certificate: ') . "</strong>" . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1249                                                $sign[] = "<strong>" . $this->functions->getLang('Message date: ') . "</strong>" . $header->Date;
1250
1251                                            $cert = openssl_x509_parse($certificado->cert_assinante);
1252                                                /*
1253                                                $sign[] = '<table>';
1254                                                $sign[] = '<tr><td colspan=1><b>Expedido para:</b></td></tr>';
1255                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[subject]['CN'] .  '</td></tr>';
1256                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1257                                                $sign[] = '<tr><td>Data de nascimento </td><td>' . $certificado->dados['NASCIMENTO'] .  '</td></tr>';
1258                                                $sign[] = '<tr><td>CPF </td><td>' . $certificado->dados['CPF'] .  '</td></tr>';
1259                                                $sign[] = '<tr><td>Documento identidade </td><td>' . $certificado->dados['RG'] .  '</td></tr>';
1260                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[subject]['O'] .  '</td></tr>';
1261                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[subject]['OU'][0] .  '</td></tr>';
1262                                                //$sign[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1263                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1264                                                $sign[] = '<tr><td colspan=1><b>Expedido por:</b></td></tr>';
1265                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[issuer]['CN'] .  '</td></tr>';
1266                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[issuer]['O'] .  '</td></tr>';
1267                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[issuer]['OU'][0] .  '</td></tr>';
1268                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1269                                                $sign[] = '<tr><td colspan=1><b>Validade:</b></td></tr>';
1270                                                $H = data_hora($cert[validFrom]);
1271                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1272                                                $sign[] = '<tr><td>Expedido em </td><td>' . $X .  '</td></tr>';
1273                                                $H = data_hora($cert[validTo]);
1274                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1275                                                $sign[] = '<tr><td>Valido ate </td><td>' . $X .  '</td></tr>';
1276                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1277                                                $sign[] = '</table>';
1278                                                */
1279                                                $sign_alert .= 'Expedido para:\n';
1280                                                $sign_alert .= 'Nome Comum (CN)  ' . $cert[subject]['CN'] .  '\n';
1281                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1282                                                $sign_alert .= 'Data de nascimento ' . $X .  '\n';
1283                                                $sign_alert .= 'CPF ' . $certificado->dados['CPF'] .  '\n';
1284                                                $sign_alert .= 'Documento identidade ' . $certificado->dados['RG'] .  '\n';
1285                                                $sign_alert .= 'Empresa (O)  ' . $cert[subject]['O'] .  '\n';
1286                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[subject]['OU'][0] .  '\n';
1287                                                //$sign_alert[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1288                                                $sign_alert .= '\n';
1289                                                $sign_alert .= 'Expedido por:\n';
1290                                                $sign_alert .= 'Nome Comum (CN) ' . $cert[issuer]['CN'] . '\n';
1291                                                $sign_alert .= 'Empresa (O)  ' . $cert[issuer]['O'] .  '\n';
1292                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[issuer]['OU'][0] .  '\n';
1293                                                $sign_alert .= '\n';
1294                                                $sign_alert .= 'Validade:\n';
1295                                                $H = data_hora($cert[validFrom]);
1296                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1297                                                $sign_alert .= 'Expedido em ' . $X .  '\n';
1298                                                $H = data_hora($cert[validTo]);
1299                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1300                                                $sign_alert .= 'Valido ate ' . $X .  '\n';
1301
1302                                                $sign[] = "<a onclick=\"javascript:alert('" . $sign_alert . "')\"><b><font color=\"#0000FF\">".$this->functions->getLang("More")."...</font></b></a>";
1303                                                $this->db = new db_functions();
1304
1305                                                // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1306                        if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1307                            $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1308                                        }
[91]1309                                     else
[1035]1310                                    {
1311                                        $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1312                                        foreach($certificado->erros_ssl as $item)
1313                                        $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1314                    }
[91]1315                                }
1316                        }
1317                }
[1472]1318                return $sign;
[91]1319        }
1320
[51]1321        function get_thumbs($msg, $msg_number, $msg_folder)
[2]1322        {
1323                $thumbs_array = array();
1324                $i = 0;
1325        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1326        {
1327                $file_type = strtolower($file_type);
1328                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1329                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1330                                $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]1331                                $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]1332                                        $thumbs_array[] = $href;
1333                        }
1334                        $i++;
1335                }
1336        }
1337        return $thumbs_array;
1338        }
[1472]1339
[2]1340        /*function delete_msg($params)
1341        {
1342                $folder = $params['folder'];
1343                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[1472]1344
[2]1345                $mbox_stream = $this->open_mbox($folder);
[1472]1346
[2]1347                foreach ($msgs_to_delete as $msg_number){
1348                        imap_delete($mbox_stream, $msg_number, FT_UID);
1349                }
1350                imap_close($mbox_stream, CL_EXPUNGE);
1351                return $params['msgs_to_delete'];
1352        }*/
1353
1354        // Novo
1355        function delete_msgs($params)
1356        {
[1472]1357
[2]1358                $folder = $params['folder'];
[51]1359                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]1360                $msgs_number = explode(",",$params['msgs_number']);
1361                $border_ID = $params['border_ID'];
[1472]1362
[2]1363                $return = array();
[1472]1364
[449]1365                if ($params['get_previous_msg']){
[2]1366                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]1367                        // Fix problem in unserialize function JS.
1368                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1369                }
[2]1370
[1472]1371                //$mbox_stream = $this->open_mbox($folder);
[504]1372                $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]1373
[2]1374                foreach ($msgs_number as $msg_number)
1375                {
1376                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1377                                $return['msgs_number'][] = $msg_number;
1378                }
[1472]1379
[2]1380                $return['folder'] = $folder;
1381                $return['border_ID'] = $border_ID;
[1472]1382
[51]1383                if($mbox_stream)
1384                        imap_close($mbox_stream, CL_EXPUNGE);
[2]1385                return $return;
1386        }
1387
[1472]1388
[2]1389        function refresh($params)
1390        {
[689]1391                include_once("class.imap_attachment.inc.php");
[1472]1392                $imap_attachment = new imap_attachment();
[2]1393                $folder = $params['folder'];
1394                $msg_range_begin = $params['msg_range_begin'];
1395                $msg_range_end = $params['msg_range_end'];
1396                $msgs_existent = $params['msgs_existent'];
[1472]1397                $sort_box_type = $params['sort_box_type'];
[2]1398                $sort_box_reverse = $params['sort_box_reverse'];
1399                $msgs_in_the_server = array();
[53]1400                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]1401                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1402                $msgs_in_the_server = array_keys($msgs_in_the_server);
1403                if(!count($msgs_in_the_server))
[51]1404                        return array();
[1472]1405
[828]1406                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
[1472]1407                $msgs_in_the_client = explode(",", $msgs_existent);
[51]1408
[2]1409                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[271]1410                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[1472]1411
[2]1412                $msgs_to_exec = array();
1413                if ((count($msg_to_insert)) && ($msgs_existent))
1414                {
1415                        foreach($msg_to_insert as $index => $msg_number)
1416                        {
1417                                if ($msgs_in_the_server[$index+1])
1418                                {
1419                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1420                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1421                                }
1422                                else
1423                                {
1424                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1425                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1426                                }
1427                        }
1428                        ksort($msgs_to_exec);
1429                }
1430                elseif(!$msgs_existent)
1431                {
1432                        foreach($msgs_in_the_server as $index => $msg_number)
1433                        {
1434                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1435                        }
1436                }
[1472]1437
[2]1438                $return = array();
1439                $i = 0;
1440                foreach($msgs_to_exec as $msg_number => $command)
1441                {
[614]1442                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
[1472]1443                        * atributos do cabeçalho. Como eu preciso do atributo Importance
[614]1444                        * para saber se o email é importante ou não, uso abaixo a função
1445                        * imap_fetchheader e busco o atributo importance nela para passar
1446                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1447                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1448                        * não preciso reimplementar o método utilizando o fetchheader.
1449                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1450                        * a perda em performance é insignificante.
1451                        */
[1035]1452            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1453                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[689]1454                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
[1472]1455
[1752]1456                        $msg_sample = $this->get_msg_sample($msg_number);
1457                        $return[$i]['msg_sample'] = $msg_sample;
1458
[535]1459                        $header = $this->get_header($msg_number);
[2]1460                        if (!is_object($header))
[828]1461                                continue;
1462
[2]1463                        $return[$i]['msg_number']       = $msg_number;
1464                        $return[$i]['command']          = $command;
[1472]1465
[2]1466                        $return[$i]['msg_folder']       = $folder;
[1035]1467            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1468            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
[2]1469                        $return[$i]['Recent']           = $header->Recent;
1470                        $return[$i]['Unseen']           = $header->Unseen;
1471                        $return[$i]['Answered']         = $header->Answered;
1472                        $return[$i]['Deleted']          = $header->Deleted;
1473                        $return[$i]['Draft']            = $header->Draft;
1474                        $return[$i]['Flagged']          = $header->Flagged;
1475
[535]1476                        $date_msg = gmdate("d/m/Y",$header->udate);
1477                        if (gmdate("d/m/Y") == $date_msg)
1478                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
[2]1479                        else
1480                                $return[$i]['udate'] = $date_msg;
[1472]1481
[2]1482                        $from = $header->from;
1483                        $return[$i]['from'] = array();
1484                        $tmp = imap_mime_header_decode($from[0]->personal);
1485                        $return[$i]['from']['name'] = $tmp[0]->text;
1486                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]1487                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[2]1488                        if(!$return[$i]['from']['name'])
1489                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[1472]1490
[2]1491                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1492                        $return[$i]['toaddress'] = '';
1493                        foreach ($toaddress as $tmp)
1494                                $return[$i]['toaddress'] .= $tmp->text;*/
1495                        $to = $header->to;
1496                        $return[$i]['to'] = array();
1497                        $tmp = imap_mime_header_decode($to[0]->personal);
1498                        $return[$i]['to']['name'] = $tmp[0]->text;
1499                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1500                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[1472]1501
[2]1502                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1503
1504                        $return[$i]['Size'] = $header->Size;
1505                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]1506
[2]1507                        $return[$i]['attachment'] = array();
[51]1508                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]1509                        $i++;
1510                }
[51]1511                $return['new_msgs'] = imap_num_recent($this->mbox);
[271]1512                $return['msgs_to_delete'] = $msg_to_delete;
[411]1513                if($this->mbox && is_resource($this->mbox))
[51]1514                        imap_close($this->mbox);
[828]1515
[2]1516                return $return;
1517        }
1518
[1035]1519     /**
1520     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1521     * assinado ou cifrado.
1522     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1523     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1524     * @param $msg_number O número da mesagem
1525     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1526     */
1527    function getMessageType($msg_number, $headers = false){
1528
1529            $contentType = "normal";
1530            if (!$headers){
1531                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1532            }
1533            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1534            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1535                $contentType = "signature";
1536            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1537                $contentType = "cipher";
1538            }
1539
1540            return $contentType;
1541    }
1542
[1375]1543         /**
1544     * Metodo que retorna todas as pastas do usuario logado.
1545     * @param $params array opcional para repassar os argumentos ao metodo.
1546     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1547     * excluindo as compartilhadas para ele.
[1472]1548     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
[1375]1549     * folder_id, folder_name, folder_parent e folder_hasChildren.
[1472]1550     */
[449]1551        function get_folders_list($params = null)
[2]1552        {
[1472]1553                $mbox_stream = $this->open_mbox();
[115]1554                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[1375]1555                $folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
[650]1556                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1557
[2]1558                $tmp = array();
[1816]1559                $resultMine = array();
1560                $resultDefault = array();
[1472]1561
[1824]1562                $inbox = 'INBOX';
1563                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1564                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1565                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1566                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
[1816]1567
[2]1568                if (is_array($folders_list)) {
1569                        reset($folders_list);
[1816]1570                        $this->ldap = new ldap_functions();
[1472]1571
[2]1572                        $i = 0;
1573                        while (list($key, $val) = each($folders_list)) {
1574                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
[1035]1575
[2]1576                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1577                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
[1816]1578                                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1579                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1580                                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1581                                        continue;
1582                                }
1583                                $result[$i]['folder_unseen'] = $status->unseen;
[2]1584                                $folder_id = $tmp_folder_id[1];
1585                                $result[$i]['folder_id'] = $folder_id;
[1472]1586
[2]1587                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1588                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
[96]1589                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
[1816]1590                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($folder_id,0,4) == 'user') {
[1340]1591                                        //$this->ldap = new ldap_functions();
[1816]1592                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
[325]1593                                                $result[$i]['folder_name'] = $cn;
1594                                        }
1595                                }
[1472]1596
[2]1597                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1598                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[1472]1599
[96]1600                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
[2]1601                                        $result[$i]['folder_hasChildren'] = 1;
1602                                else
1603                                        $result[$i]['folder_hasChildren'] = 0;
1604
[1816]1605                                switch ($tmp_folder_id[1]) {
[1824]1606                                        case $inbox:
1607                                        case $sent:
1608                                        case $drafts:
1609                                        case $spam:
1610                                        case $trash:
[1816]1611                                                $resultDefault[]=$result[$i];
1612                                        default:
1613                                                $resultMine[]=$result[$i];
1614                                }
1615
[1472]1616                                $i++;
[2]1617                        }
1618                }
[1472]1619
[1816]1620                // Sorting resultMine
1621                foreach ($resultMine as $folder_info)
[2]1622                {
1623                        $array_tmp[] = $folder_info['folder_id'];
1624                }
[1472]1625
[2]1626                natcasesort($array_tmp);
[1472]1627
[2]1628                foreach ($array_tmp as $key => $folder_id)
1629                {
[1816]1630                        $result2[] = $resultMine[$key];
[2]1631                }
[1816]1632               
1633                $resultDefault2=$resultDefault;
1634                // Sorting resultDefault
1635                foreach ($resultDefault as $key => $folder_id)
1636                {
[1472]1637
[1816]1638                        switch ($resultDefault[$key]['folder_id']) {
[1824]1639                                case $inbox:
[1816]1640                                        $resultDefault2[0] = $resultDefault[$key];
1641                                        break;
[1824]1642                                case $sent:
[1816]1643                                        $resultDefault2[1] = $resultDefault[$key];
1644                                        break;
[1824]1645                                case $drafts:
[1816]1646                                        $resultDefault2[2] = $resultDefault[$key];
1647                                        break;
[1824]1648                                case $spam:
[1816]1649                                        $resultDefault2[3] = $resultDefault[$key];
1650                                        break;
[1824]1651                                case $trash:
[1816]1652                                        $resultDefault2[4] = $resultDefault[$key];
1653                                        break;
1654                        }
1655                }
1656
1657                // Merge default folders and mines
1658                $result2 = array_merge($resultDefault2, $result2);
1659               
[449]1660                $current_folder = "INBOX";
1661                if($params && $params['folder'])
1662                        $current_folder = $params['folder'];
[1739]1663                return array_merge($result2, $this->get_quota(array('folder_id' => $current_folder)));
[2]1664        }
[1472]1665
[2]1666        function create_mailbox($arr)
1667        {
1668                $namebox        = $arr['newp'];
1669                $mbox_stream = $this->open_mbox();
1670                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]1671                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[1472]1672
[2]1673                $result = "Ok";
[51]1674                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]1675                {
1676                        $result = implode("<br />\n", imap_errors());
[1472]1677                }
1678
[51]1679                if($mbox_stream)
1680                        imap_close($mbox_stream);
[1472]1681
[2]1682                return $result;
[1472]1683
[2]1684        }
[1472]1685
[2]1686        function create_extra_mailbox($arr)
1687        {
1688                $nameboxs = explode(";",$arr['nw_folders']);
1689                $result = "";
1690                $mbox_stream = $this->open_mbox();
1691                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1472]1692                foreach($nameboxs as $key=>$tmp){
[2]1693                        if($tmp != ""){
1694                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1695                                        $result = implode("<br />\n", imap_errors());
[51]1696                                        if($mbox_stream)
[1472]1697                                                imap_close($mbox_stream);
[2]1698                                        return $result;
1699                                }
1700                        }
1701                }
[51]1702                if($mbox_stream)
1703                        imap_close($mbox_stream);
[2]1704                return true;
1705        }
[1472]1706
[2]1707        function delete_mailbox($arr)
1708        {
1709                $namebox = $arr['del_past'];
1710                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1711                $mbox_stream = $this->open_mbox();
1712                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[1472]1713
[2]1714                $result = "Ok";
1715                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1716                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1717                {
1718                        $result = implode("<br />\n", imap_errors());
1719                }
[51]1720                if($mbox_stream)
1721                        imap_close($mbox_stream);
[2]1722                return $result;
1723        }
[1472]1724
[2]1725        function ren_mailbox($arr)
1726        {
1727                $namebox = $arr['current'];
1728                $new_box = $arr['rename'];
1729                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1730                $mbox_stream = $this->open_mbox();
1731                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[1472]1732
[2]1733                $result = "Ok";
1734                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]1735                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[1472]1736
[2]1737                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1738                {
[1472]1739                        $result = imap_errors();
[2]1740                }
[51]1741                if($mbox_stream)
1742                        imap_close($mbox_stream);
[2]1743                return $result;
[1472]1744
[2]1745        }
[1472]1746
[2]1747        function get_num_msgs($params)
1748        {
1749                $folder = $params['folder'];
[411]1750                if(!$this->mbox || !is_resource($this->mbox)) {
[2]1751                        $this->mbox = $this->open_mbox($folder);
[411]1752                        if(!$this->mbox || !is_resource($this->mbox))
[2]1753                        return imap_last_error();
[1472]1754                }
[2]1755                $num_msgs = imap_num_msg($this->mbox);
[432]1756                if($this->mbox && is_resource($this->mbox))
[51]1757                        imap_close($this->mbox);
[1472]1758
[2]1759                return $num_msgs;
1760        }
[1472]1761
[2]1762        function send_mail($params)
1763        {
1764                include_once("class.phpmailer.php");
1765                $mail = new PHPMailer();
1766                include_once("class.db_functions.inc.php");
1767                $db = new db_functions();
1768                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[449]1769                ##
1770                # @AUTHOR Rodrigo Souza dos Santos
1771                # @DATE 2008/09/17
1772                # @BRIEF Checks if the user has permission to send an email with the email address used.
1773                ##
1774                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1775                {
1776                        $deny = true;
1777                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1778                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1779                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1780
1781                        if ( $deny )
1782                                return "The server denied your request to send a mail, you cannot use this mail address.";
1783                }
[828]1784
[707]1785                //new_message_to backs to mailto: pattern
[708]1786                $params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
[828]1787
[2]1788                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1789                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1790                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1791                $subject = $params['input_subject'];
[271]1792                $msg_uid = $params['msg_id'];
[2]1793                $return_receipt = $params['input_return_receipt'];
[614]1794                $is_important = $params['input_important_message'];
[1035]1795        $encrypt = $params['input_return_cripto'];
1796                $signed = $params['input_return_digital'];
1797
1798                if($params['smime'])
1799        {
1800            $body = $params['smime'];
1801            $mail->SMIME = true;
1802            // A MSG assinada deve ser testada neste ponto.
1803            // Testar o certificado e a integridade da msg....
[1174]1804            include_once("../security/classes/CertificadoB.php");
[1035]1805            $erros_acumulados = '';
1806            $certificado = new certificadoB();
1807            $validade = $certificado->verificar($body);
1808            if(!$validade)
1809            {
1810                foreach($certificado->erros_ssl as $linha_erro)
1811                {
1812                    $erros_acumulados .= $linha_erro;
1813                }
1814            }
1815            else
1816            {
1817                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1818                if ($certificado->apresentado)
1819                {
1820                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1821                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1822                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1823                }
1824                else
1825                {
1826                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1827                }
1828            }
1829            if(!$erros_acumulados =='')
1830            {
1831                return $erros_acumulados;
1832            }
1833        }
1834        else
1835        {
1836            $body = $params['body'];
1837        }
[1247]1838                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
[2]1839                $attachments = $params['FILES'];
1840                $forwarding_attachments = $params['forwarding_attachments'];
[689]1841                $local_attachments = $params['local_attachments'];
[1472]1842
[51]1843                $folder =$params['folder'];
[1472]1844                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1845                $folder_name = $params['folder_name'];
[6]1846                // Fix problem with cyrus delimiter changes.
[1472]1847                // Dots in names: enabled/disabled.
[6]1848                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1849                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1850                // End Fix.
[1472]1851                if ($folder != 'null'){
[2]1852                        $mail->SaveMessageInFolder = $folder;
1853                }
1854////////////////////////////////////////////////////////////////////////////////////////////////////
1855                $mail->SMTPDebug = false;
[1035]1856
1857                if($signed && !$params['smime'])
1858                {
1859            $mail->Mailer = "smime";
1860                        $mail->SignedBody = true;
1861                }
1862                else
1863            $mail->IsSMTP();
[1472]1864
[2]1865                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1866                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1867                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1868                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1869                if($fromaddress){
1870                        $mail->Sender = $mail->From;
1871                        $mail->SenderName = $mail->FromName;
1872                        $mail->FromName = $fromaddress[0];
1873                        $mail->From = $fromaddress[1];
1874                }
[1472]1875
[2]1876                $this->add_recipients("to", $toaddress, &$mail);
1877                $this->add_recipients("cc", $ccaddress, &$mail);
1878                $this->add_recipients("cco", $ccoaddress, &$mail);
1879                $mail->Subject = $subject;
1880                $mail->IsHTML(true);
[1035]1881                $mail->Body = $body;
[271]1882
[1035]1883        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
1884                {
1885                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
1886            $email = explode(",",$email);
1887            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
1888            // Deve ser verificado um numero limite de destinatarios.
1889            // Deve ser verificado se os certificados sao validos.
1890            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
1891            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
1892            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
1893            $erros_acumulados = "";
1894            $aux_mails = array();
1895            $mail_list = array();
1896            if(count($email) > $numero_maximo)
1897            {
1898                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
1899                return $erros_acumulados;
1900            }
1901            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
1902            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1903            foreach($email as $item)
1904            {
1905                $certificate = $db->get_certificate(strtolower($item));
1906                if(!$certificate)
1907                {
1908                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
1909                    return $erros_acumulados;
1910                }
1911
1912                if (array_key_exists("dberr1", $certificate))
1913                {
1914
1915                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
1916                    return $erros_acumulados;
1917                                }
1918                if (array_key_exists("dberr2", $certificate))
1919                {
1920                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1921                    //continue;
1922                }
1923                        /*  Retirado este teste para evitar mensagem de erro duplicada.
1924                if (!array_key_exists("certs", $certificate))
1925                {
1926                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1927                    continue;
1928                }
1929            */
[1174]1930                include_once("../security/classes/CertificadoB.php");
[1035]1931
1932                foreach ($certificate['certs'] as $registro)
1933                {
1934                    $c1 = new certificadoB();
1935                    $c1->certificado($registro['chave_publica']);
1936                    if ($c1->apresentado)
1937                    {
1938                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
1939                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
1940                        {
1941                            $aux_mails[] = $registro['chave_publica'];
1942                            $mail_list[] = strtolower($item);
1943                        }
1944                        else
1945                        {
1946                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
1947                            {
1948                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
1949                                    $c1->dados['EXPIRADO'],$c2->revogado);
1950                            }
1951
1952                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
1953                            foreach($c2->erros_ssl as $linha)
1954                            {
1955                                $erros_acumulados .=  $linha . chr(0x0A);
1956                            }
1957                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
1958                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
1959                        }
1960                    }
1961                    else
1962                    {
1963                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
1964                    }
1965                }
1966                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
1967                                {
1968                                        return $erros_acumulados;
1969                        }
1970            }
1971
1972            $mail->Certs_crypt = $aux_mails;
1973        }
1974
[2]1975////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1976                //      Build CID for embedded Images!!!
[449]1977                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[271]1978                $cid_imgs = '';
1979                $name_cid_files = array();
1980                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1981                $cid_array = array();
[449]1982                foreach($cid_imgs[6] as $j => $val){
1983                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[271]1984                        {
[449]1985                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[271]1986                        }
[1472]1987                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[271]1988                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[1472]1989
[1711]1990                                if (!$forwarding_attachments[$cid_imgs[6][$j]-2]) // The image isn't in the same mail?
[271]1991                                {
[449]1992                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
[271]1993                                        $fileName = "image_".($j).".jpg";
1994                                        $fileCode = "base64";
1995                                        $fileType = "image/jpg";
1996                                }
1997                                else
1998                                {
[449]1999                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[271]2000                                        $file_description = unserialize(rawurldecode($attach_img));
2001
[1472]2002                                        foreach($file_description as $i => $descriptor){
[271]2003                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2004                                        }
[1711]2005                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $cid_imgs[4][$j], $file_description[3], 'base64');
[271]2006                                        $fileName = $file_description[2];
2007                                        $fileCode = $file_description[4];
2008                                        $fileType = $this->get_file_type($file_description[2]);
[449]2009                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[271]2010                                }
2011                                $tempDir = ini_get("session.save_path");
[1472]2012                                $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";
[271]2013                                $f = fopen($tempDir.'/'.$file,"w");
2014                                fputs($f,$fileContent);
2015                                fclose($f);
2016                                if ($fileContent)
2017                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2018                                //else
[1472]2019                                //      return "Error loading image attachment content";
[271]2020
2021                }
2022////////////////////////////////////////////////////////////////////////////////////////////////////
[2]2023                //      Build Uploading Attachments!!!
[689]2024                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
[2]2025                {
2026                        $total_uploaded_size = 0;
[1264]2027                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
[2]2028                        foreach ($attachments as $attach)
2029                        {
2030                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2031                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2032                        }
[1247]2033                        if( $total_uploaded_size > $upload_max_filesize)
[1472]2034                                return $this->parse_error("message file too big");
[828]2035                }
[689]2036                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
[828]2037
[689]2038                        $total_uploaded_size = 0;
[1472]2039                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
[689]2040                        foreach($local_attachments as $local_attachment) {
2041                                $file_description = unserialize(rawurldecode($local_attachment));
2042                                $tmp = array_values($file_description);
[1472]2043                                foreach($file_description as $i => $descriptor){
[689]2044                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2045                                }
2046                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2047                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2048                        }
2049                        if( $total_uploaded_size > $upload_max_filesize)
[828]2050                                return 'false';
[689]2051                }
[2]2052////////////////////////////////////////////////////////////////////////////////////////////////////
[271]2053                //      Build Forwarding Attachments!!!
[2]2054                if (count($forwarding_attachments) > 0)
2055                {
2056                        // Bug fixed for array_search function
2057                        if(count($name_cid_files) > 0) {
2058                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2059                                $name_cid_files[0] = null;
[1472]2060                        }
2061
[2]2062                        foreach($forwarding_attachments as $forwarding_attachment)
2063                        {
[271]2064                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2065                                        $tmp = array_values($file_description);
[1472]2066                                        foreach($file_description as $i => $descriptor){
[271]2067                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2068                                        }
[1472]2069                                        $file_description = $tmp;
[271]2070                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2071                                        $fileName = $file_description[2];
2072                                        if(!array_search(trim($fileName),$name_cid_files)) {
2073                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
[63]2074                                }
[2]2075                        }
2076                }
[37]2077
[2]2078////////////////////////////////////////////////////////////////////////////////////////////////////
[614]2079                // Important message
2080                if($is_important)
2081                        $mail->isImportant();
2082
2083////////////////////////////////////////////////////////////////////////////////////////////////////
[2]2084                // Disposition-Notification-To
2085                if ($return_receipt)
2086                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2087////////////////////////////////////////////////////////////////////////////////////////////////////
[504]2088
[117]2089                $sent = $mail->Send();
[1472]2090
[117]2091                if(!$sent)
[2]2092                {
[504]2093                        return $this->parse_error($mail->ErrorInfo);
[2]2094                }
2095                else
2096                {
[1035]2097            if ($signed && !$params['smime'])
2098                        {
2099                                return $sent;
2100                        }
[1472]2101                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]2102                        {
2103                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2104                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2105                                $now = date("d/m/y H:i:s");
2106                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[1472]2107                                $sent = trim($sent);
[117]2108                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2109                        }
[1472]2110                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
[485]2111                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]2112                                $contacts = new dynamic_contacts();
[485]2113                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2114                                return array("success" => true, "new_contacts" => $new_contacts);
[413]2115                        }
[485]2116                        return array("success" => true);
[2]2117                }
2118        }
2119
[1035]2120    function add_recipients_cert($full_address)
2121        {
2122                $result = "";
2123                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2124                foreach ($parse_address as $val)
2125                {
2126                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2127                        if ($val->mailbox == "INVALID_ADDRESS")
2128                                continue;
2129                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2130                                continue;
2131                        if (empty($val->personal))
2132                                $result .= $val->mailbox."@".$val->host . ",";
2133                        else
2134                                $result .= $val->mailbox."@".$val->host . ",";
2135                }
2136
2137                return substr($result,0,-1);
2138        }
2139
[2]2140        function add_recipients($recipient_type, $full_address, $mail)
2141        {
[1472]2142                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2143                foreach ($parse_address as $val)
[2]2144                {
2145                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2146                        if ($val->mailbox == "INVALID_ADDRESS")
2147                                continue;
[1472]2148
[2]2149                        if (empty($val->personal))
2150                        {
2151                                switch($recipient_type)
2152                                {
2153                                        case "to":
2154                                                $mail->AddAddress($val->mailbox."@".$val->host);
2155                                                break;
2156                                        case "cc":
2157                                                $mail->AddCC($val->mailbox."@".$val->host);
2158                                                break;
2159                                        case "cco":
2160                                                $mail->AddBCC($val->mailbox."@".$val->host);
2161                                                break;
2162                                }
2163                        }
2164                        else
2165                        {
2166                                switch($recipient_type)
2167                                {
2168                                        case "to":
2169                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2170                                                break;
2171                                        case "cc":
2172                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2173                                                break;
2174                                        case "cco":
2175                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2176                                                break;
2177                                }
2178                        }
2179                }
2180                return true;
2181        }
[1472]2182
[2]2183        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2184        {
[828]2185                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
[1472]2186                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
[2]2187                if($encoding == 'base64')
[449]2188                        # The function imap_base64 adds a new line
2189                        # at ASCII text, with CRLF line terminators.
2190                        # So is being exchanged for base64_decode.
2191                        #
2192                        #$fileContent = imap_base64($fileContent);
2193                        $fileContent = base64_decode($fileContent);
[2]2194                else if($encoding == 'quoted-printable')
[1472]2195                        $fileContent = quoted_printable_decode($fileContent);
[2]2196                return $fileContent;
2197        }
[1472]2198
[2]2199        function del_last_caracter($string)
2200        {
2201                $string = substr($string,0,(strlen($string) - 1));
[1472]2202                return $string;
[2]2203        }
[1472]2204
[2]2205        function del_last_two_caracters($string)
2206        {
2207                $string = substr($string,0,(strlen($string) - 2));
[1472]2208                return $string;
[2]2209        }
[1472]2210
[828]2211        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
[659]2212        {
[1625]2213                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
[970]2214                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2215                        foreach($imapsort as $iuid)
2216                                $sort[$iuid] = "";
[1518]2217                       
2218                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2219                                $slice_array = false;
2220                        else
2221                                $slice_array = true;
[970]2222                }
2223                else
[659]2224                {
[970]2225                        $sort = array();
2226                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2227                        $num_msgs = imap_num_msg($this->mbox);
2228                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
[975]2229                        $slice_array = true;
2230
[983]2231                        for ($i=$num_msgs; $i>0; $i--)
[828]2232                        {
[983]2233                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2234                                        break;
[970]2235                                $iuid = @imap_uid($this->mbox,$i);
2236                                $header = $this->get_header($iuid);
2237                                // List UNSEEN messages.
2238                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2239                                        continue;
2240                                }
2241                                // List SEEN messages.
2242                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2243                                        continue;
2244                                }
2245                                // List ANSWERED messages.
2246                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2247                                        continue;
2248                                }
2249                                // List FLAGGED messages.
2250                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2251                                        continue;
2252                                }
2253
2254                                if($sort_box_type=='SORTFROM') {
2255                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2256                                                $from = $header->to;
2257                                        else
2258                                                $from = $header->from;
2259
2260                                        $tmp = imap_mime_header_decode($from[0]->personal);
2261
2262                                        if ($tmp[0]->text != "")
2263                                                $sort[$iuid] = $tmp[0]->text;
2264                                        else
2265                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2266                                }
2267                                else if($sort_box_type=='SORTSUBJECT') {
2268                                        $sort[$iuid] = $header->subject;
2269                                }
2270                                else if($sort_box_type=='SORTSIZE') {
2271                                        $sort[$iuid] = $header->Size;
2272                                }
2273                                else {
2274                                        $sort[$iuid] = $header->udate;
2275                                }
2276
[659]2277                        }
[970]2278                        natcasesort($sort);
[828]2279
[970]2280                        if ($sort_box_reverse)
2281                                $sort = array_reverse($sort,true);
[659]2282                }
[828]2283
[972]2284                if(!is_array($sort))
2285                        $sort = array();
[1472]2286
[1808]2287
[972]2288                if ($slice_array)
[828]2289                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
[970]2290
[1472]2291
[828]2292                return $sort;
2293
[659]2294        }
[970]2295
2296
[1472]2297        function move_search_messages($params){
2298                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]2299                $params['new_folder'] = urldecode($params['new_folder']);
2300                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2301                $sel_msgs = explode(",", $params['selected_messages']);
[1472]2302                @reset($sel_msgs);
[163]2303                $sorted_msgs = array();
2304                foreach($sel_msgs as $idx => $sel_msg) {
2305                        $sel_msg = explode(";", $sel_msg);
2306                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2307                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[1472]2308                         }
[163]2309                         else {
2310                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2311                         }
2312                }
2313                @ksort($sorted_msgs);
[1472]2314                $last_return = false;
2315                foreach($sorted_msgs as $folder => $msgs_number) {
[163]2316                        $params['msgs_number'] = $msgs_number;
[1472]2317                        $params['folder'] = $folder;
[163]2318                        if($params['new_folder'] && $folder != $params['new_folder']){
[1472]2319                                $last_return = $this -> move_messages($params);
[163]2320                        }
2321                        elseif(!$params['new_folder'] || $params['delete'] ){
2322                                $last_return = $this -> delete_msgs($params);
2323                                $last_return['deleted'] = true;
2324                        }
2325                }
2326                return $last_return;
2327        }
[1472]2328
[2]2329        function move_messages($params)
2330        {
[1472]2331                $folder = $params['folder'];
2332                $mbox_stream = $this->open_mbox($folder);
[51]2333                $newmailbox = ($params['new_folder']);
2334                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
[2]2335                $new_folder_name = $params['new_folder_name'];
2336                $msgs_number = $params['msgs_number'];
2337                $return = array('msgs_number' => $msgs_number,
2338                                                'folder' => $folder,
2339                                                'new_folder_name' => $new_folder_name,
[325]2340                                                'border_ID' => $params['border_ID'],
2341                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[1472]2342
[325]2343                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2344        if (substr($folder,0,4) == 'user'){
2345                $acl = $this->getacltouser($folder);
2346                /*
2347                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2348                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2349                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2350                 *   w - write (STORE flags other than SEEN and DELETED)
2351                 *   i - insert (perform APPEND, COPY into mailbox)
2352                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2353                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2354                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2355                 *   a - administer (perform SETACL)
2356                        */
2357                        if (strpos($acl, "d") === false){
2358                                $return['status'] = false;
2359                                return $return;
2360                        }
2361        }
[432]2362        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[1747]2363        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2364            if (substr($new_folder_name,0,4) == 'user'){
2365                $this->ldap = new ldap_functions();
2366                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2367                $return['new_folder_name'] = array_pop($tmp_folder_name);
2368                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2369                {
2370                    $return['new_folder_name'] = $cn;
2371                }
2372            }
[432]2373        }
[1472]2374
2375                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
[51]2376                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]2377                {
[2]2378                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]2379                        // Fix problem in unserialize function JS.
2380                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2381                }
[1472]2382
2383                $mbox_stream = $this->open_mbox($folder);
[2]2384                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2385                        imap_expunge($mbox_stream);
[51]2386                        if($mbox_stream)
2387                                imap_close($mbox_stream);
[2]2388                        return $return;
2389                }else {
[1472]2390                        if(strstr(imap_last_error(),'Over quota')) {
[2]2391                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[1472]2392                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2393                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
[2]2394                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]2395                                $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]2396                                if(!$mbox)
2397                                        return imap_last_error();
[1472]2398                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
[2]2399                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]2400                                        if($mbox_stream)
2401                                                imap_close($mbox_stream);
[1472]2402                                        if($mbox)
[51]2403                                                imap_close($mbox);
[1472]2404                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
[2]2405                                }
2406                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2407                                        imap_expunge($mbox_stream);
[51]2408                                        if($mbox_stream)
2409                                                imap_close($mbox_stream);
[2]2410                                        // return to original quota limit.
2411                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2412                                                if($mbox)
2413                                                        imap_close($mbox);
[1472]2414                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]2415                                        }
[1472]2416                                        return $return;
[2]2417                                }
2418                                else {
[51]2419                                        if($mbox_stream)
2420                                                imap_close($mbox_stream);
[2]2421                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2422                                                if($mbox)
2423                                                        imap_close($mbox);
[1472]2424                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]2425                                        }
[1472]2426                                        return imap_last_error();
[2]2427                                }
[1472]2428
[2]2429                        }
2430                        else {
[51]2431                                if($mbox_stream)
2432                                        imap_close($mbox_stream);
2433                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]2434                        }
[1472]2435                }
[2]2436        }
[1472]2437
[2]2438        function save_msg($params)
2439        {
[1472]2440
[271]2441                include_once("class.phpmailer.php");
2442                $mail = new PHPMailer();
2443                include_once("class.db_functions.inc.php");
2444                $toaddress = $params['input_to'];
2445                $ccaddress = $params['input_cc'];
[1638]2446                $ccoaddress = $params['input_cco'];
[271]2447                $subject = $params['input_subject'];
[320]2448                $msg_uid = $params['msg_id'];
[2]2449                $body = $params['body'];
2450                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
[155]2451                $body = preg_replace("/\n/"," ",$body);
[51]2452                $body = preg_replace("/\r/","",$body);
[271]2453                $forwarding_attachments = $params['forwarding_attachments'];
2454                $attachments = $params['FILES'];
2455                $return_files = $params['FILES'];
[1472]2456
[271]2457                $folder = $params['folder'];
[1472]2458                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[271]2459                // Fix problem with cyrus delimiter changes.
[1472]2460                // Dots in names: enabled/disabled.
[271]2461                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2462                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2463                // End Fix.
[1638]2464                if(strtoupper($folder) == 'INBOX/DRAFTS')
2465                    {
2466                        $mail->SaveMessageAsDraft = $folder;
2467                    }
[271]2468                $mail->SaveMessageInFolder = $folder;
2469                $mail->SMTPDebug = false;
[1472]2470
[271]2471                $mail->IsSMTP();
2472                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2473                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2474                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2475                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
[1472]2476
[271]2477                $mail->Sender = $mail->From;
2478                $mail->SenderName = $mail->FromName;
2479                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2480                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
[1472]2481
[271]2482                $this->add_recipients("to", $toaddress, &$mail);
2483                $this->add_recipients("cc", $ccaddress, &$mail);
[1638]2484                $this->add_recipients("cco", $ccoaddress, &$mail);
[271]2485                $mail->Subject = $subject;
2486                $mail->IsHTML(true);
2487                $mail->Body = $body;
[1472]2488
[320]2489                //      Build CID for embedded Images!!!
[449]2490                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[320]2491                $cid_imgs = '';
2492                $name_cid_files = array();
2493                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2494                $cid_array = array();
[449]2495                foreach($cid_imgs[6] as $j => $val){
2496                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[320]2497                        {
[449]2498                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[320]2499                        }
[1472]2500                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[320]2501                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[1472]2502
[449]2503                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[320]2504                                {
[449]2505                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2506                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
[320]2507                                        $fileName = "image_".($j).".jpg";
2508                                        $fileCode = "base64";
2509                                        $fileType = "image/jpg";
[449]2510                                        $file_attached[0] = $cid_imgs[2][$j];
2511                                        $file_attached[1] = $cid_imgs[4][$j];
2512                                        $file_attached[2] = $fileName;
2513                                        $file_attached[3] = $cid_imgs[6][$j];
2514                                        $file_attached[4] = 'base64';
2515                                        $file_attached[5] = strlen($fileContent); //Size of file
2516                                        $return_forward[] = $file_attached;
[320]2517                                }
2518                                else
2519                                {
[449]2520                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[320]2521                                        $file_description = unserialize(rawurldecode($attach_img));
[1472]2522                                        foreach($file_description as $i => $descriptor){
[320]2523                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2524                                        }
2525                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2526                                        $fileName = $file_description[2];
2527                                        $fileCode = $file_description[4];
2528                                        $fileType = $this->get_file_type($file_description[2]);
[449]2529                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[320]2530                                        if (!empty($file_description))
2531                                        {
2532                                                $file_description[5] = strlen($fileContent); //Size of file
2533                                                $return_forward[] = $file_description;
2534                                        }
2535                                }
2536                                $tempDir = ini_get("session.save_path");
[1472]2537                                $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";
[320]2538                                $f = fopen($tempDir.'/'.$file,"w");
2539                                fputs($f,$fileContent);
2540                                fclose($f);
2541                                if ($fileContent)
2542                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2543                                //else
[1472]2544                                //      return "Error loading image attachment content";
[320]2545
2546                }
[1472]2547
2548        //      Build Forwarding Attachments!!!
[271]2549                if (count($forwarding_attachments) > 0)
2550                {
2551                        foreach($forwarding_attachments as $forwarding_attachment)
2552                        {
2553                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2554                                $tmp = array_values($file_description);
[1472]2555                                foreach($file_description as $i => $descriptor){
[271]2556                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2557                                }
2558                                $file_description = $tmp;
[1472]2559
[271]2560                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2561                                $fileName = $file_description[2];
[1472]2562
[271]2563                                $file_description[5] = strlen($fileContent); //Size of file
2564                                $return_forward[] = $file_description;
[1472]2565
[271]2566                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2567                        }
2568                }
[1472]2569
[271]2570                if ((count($return_forward) > 0) && (count($return_files) > 0))
2571                        $return_files = array_merge_recursive($return_forward,$return_files);
2572                else
2573                        if (count($return_files) < 1)
2574                                $return_files = $return_forward;
[1472]2575
[271]2576                //      Build Uploading Attachments!!!
[1005]2577                $sizeof_attachments = count($attachments);
2578                if ($sizeof_attachments)
2579                        foreach ($attachments as $numb => $attach){
2580                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2581                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2582                                        switch ($image_type)
2583                                        {
[1380]2584                                        // Do not corrupt animated gif
2585                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
[1005]2586                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2587                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2588                                        case 6:
[1247]2589                                                require_once("gd_functions.php");
[1005]2590                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2591                                        default:
2592                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2593                                                break;
2594                                        }
2595                                        header('Content-type: image/jpeg');
2596                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2597                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2598                                        if ($width < $max_resolution && $height < $max_resolution){
2599                                                $new_width = $width;
2600                                                $new_height = $height;
2601                                        }
2602                                        else if ($width > $max_resolution){
2603                                                $new_width = $max_resolution;
2604                                                $new_height = $height*($new_width/$width);
2605                                        }
2606                                        else {
2607                                                $new_height = $max_resolution;
2608                                                $new_width = $width*($new_height/$height);
2609                                        }
2610                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2611                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2612                                        $tmpDir = ini_get("session.save_path");
[1472]2613                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
[1005]2614                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2615                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2616                                }
2617                                else
2618                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2619                                // optional name
2620                                }
[1472]2621
2622
2623
2624
[271]2625                if(!empty($mail->AltBody))
2626            $mail->ContentType = "multipart/alternative";
2627
[828]2628                $mail->error_count = 0; // reset errors
2629                $mail->SetMessageType();
2630                $header = $mail->CreateHeader();
[1472]2631                $body = $mail->CreateBody();
[828]2632
[1472]2633                $mbox_stream = $this->open_mbox($folder);
[271]2634                $new_header = str_replace("\n", "\r\n", $header);
2635                $new_body = str_replace("\n", "\r\n", $body);
[830]2636                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
[271]2637                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2638                $return['msg_no'] = $status->uidnext - 1;
2639                $return['folder_id'] = $folder;
[828]2640
[51]2641                if($mbox_stream)
2642                        imap_close($mbox_stream);
[1472]2643                if (is_array($return_files))
[828]2644                        foreach ($return_files as $index => $_attachment) {
2645                                if (array_key_exists("name",$_attachment)){
[271]2646                                unset($return_files[$index]);
2647                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2648                        }
2649                        else
2650                        {
2651                                unset($return_files[$index]);
2652                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2653                        }
2654                }
[1472]2655
[271]2656                $return['files'] = serialize($return_files);
[673]2657                $return["subject"] = $subject;
[1472]2658
[2]2659                if (!$return['append'])
2660                        $return['append'] = imap_last_error();
[1472]2661
[2]2662                return $return;
2663        }
[1472]2664
[2]2665        function set_messages_flag($params)
2666        {
2667                $folder = $params['folder'];
2668                $msgs_to_set = $params['msgs_to_set'];
2669                $flag = $params['flag'];
2670                $return = array();
2671                $return["msgs_to_set"] = $msgs_to_set;
2672                $return["flag"] = $flag;
[1472]2673
[411]2674                if(!$this->mbox && !is_resource($this->mbox))
[51]2675                        $this->mbox = $this->open_mbox($folder);
[1472]2676
[2]2677                if ($flag == "unseen")
[51]2678                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]2679                elseif ($flag == "seen")
[51]2680                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]2681                elseif ($flag == "answered"){
[51]2682                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2683                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]2684                }
2685                elseif ($flag == "forwarded")
[51]2686                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]2687                elseif ($flag == "flagged")
[51]2688                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[614]2689                elseif ($flag == "unflagged") {
2690                        $flag_importance = false;
2691                        $msgs_number = explode(",",$msgs_to_set);
[659]2692                        $unflagged_msgs = "";
[614]2693                        foreach($msgs_number as $msg_number) {
2694                                preg_match('/importance *: *(.*)\r/i',
2695                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]2696                                        ,$importance);
[673]2697                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]2698                                        $flag_importance=true;
2699                                }
[659]2700                                else {
2701                                        $unflagged_msgs.=$msg_number.",";
[1472]2702                                }
[614]2703                        }
2704
[659]2705                        if($unflagged_msgs!="") {
2706                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2707                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2708                        }
2709                        else {
2710                                $return["msgs_unflageds"] = false;
2711                        }
2712
[673]2713                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]2714                                $return["status"] = false;
2715                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2716                        }
[659]2717                        else {
2718                                $return["status"] = true;
2719                        }
[614]2720                }
[1472]2721
[411]2722                if($this->mbox && is_resource($this->mbox))
[51]2723                        imap_close($this->mbox);
[2]2724                return $return;
2725        }
[1472]2726
[2]2727        function get_file_type($file_name)
2728        {
2729                $file_name = strtolower($file_name);
2730                $strFileType = strrev(substr(strrev($file_name),0,4));
[1472]2731                if ($strFileType == ".asf")
[2]2732                        return "video/x-ms-asf";
2733                if ($strFileType == ".avi")
2734                        return "video/avi";
2735                if ($strFileType == ".doc")
2736                        return "application/msword";
2737                if ($strFileType == ".zip")
2738                        return "application/zip";
2739                if ($strFileType == ".xls")
2740                        return "application/vnd.ms-excel";
2741                if ($strFileType == ".gif")
2742                        return "image/gif";
2743                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2744                        return "image/jpeg";
2745                if ($strFileType == ".png")
2746                        return "image/png";
2747                if ($strFileType == ".wav")
2748                        return "audio/wav";
2749                if ($strFileType == ".mp3")
2750                        return "audio/mpeg3";
2751                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2752                        return "video/mpeg";
2753                if ($strFileType == ".rtf")
2754                        return "application/rtf";
2755                if ($strFileType == ".htm" || $strFileType == "html")
2756                        return "text/html";
[1472]2757                if ($strFileType == ".xml")
[2]2758                        return "text/xml";
[1472]2759                if ($strFileType == ".xsl")
[2]2760                        return "text/xsl";
[1472]2761                if ($strFileType == ".css")
[2]2762                        return "text/css";
[1472]2763                if ($strFileType == ".php")
[2]2764                        return "text/php";
[1472]2765                if ($strFileType == ".asp")
[2]2766                        return "text/asp";
2767                if ($strFileType == ".pdf")
2768                        return "application/pdf";
2769                if ($strFileType == ".txt")
2770                        return "text/plain";
2771                if ($strFileType == ".wmv")
2772                        return "video/x-ms-wmv";
2773                if ($strFileType == ".sxc")
2774                        return "application/vnd.sun.xml.calc";
2775                if ($strFileType == ".stc")
2776                        return "application/vnd.sun.xml.calc.template";
2777                if ($strFileType == ".sxd")
2778                        return "application/vnd.sun.xml.draw";
2779                if ($strFileType == ".std")
2780                        return "application/vnd.sun.xml.draw.template";
2781                if ($strFileType == ".sxi")
2782                        return "application/vnd.sun.xml.impress";
2783                if ($strFileType == ".sti")
2784                        return "application/vnd.sun.xml.impress.template";
2785                if ($strFileType == ".sxm")
2786                        return "application/vnd.sun.xml.math";
2787                if ($strFileType == ".sxw")
2788                        return "application/vnd.sun.xml.writer";
2789                if ($strFileType == ".sxq")
2790                        return "application/vnd.sun.xml.writer.global";
2791                if ($strFileType == ".stw")
2792                        return "application/vnd.sun.xml.writer.template";
[1472]2793
2794
2795                return "application/octet-stream";
[2]2796        }
[1472]2797
[2]2798        function htmlspecialchars_encode($str)
2799        {
[449]2800                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]2801        }
2802        function htmlspecialchars_decode($str)
2803        {
[449]2804                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]2805        }
[1472]2806
[828]2807        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2808        {
2809                if(!$this->mbox || !is_resource($this->mbox))
[51]2810                        $this->mbox = $this->open_mbox($folder);
[432]2811
[828]2812                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2813        }
[1472]2814
[53]2815        function get_info_next_msg($params)
2816        {
2817                $msg_number = $params['msg_number'];
2818                $folder = $params['msg_folder'];
2819                $sort_box_type = $params['sort_box_type'];
2820                $sort_box_reverse = $params['sort_box_reverse'];
2821                $reuse_border = $params['reuse_border'];
2822                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[1472]2823                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2824
[320]2825                $success = false;
2826                if (is_array($sort_array_msg))
[2]2827                {
[320]2828                        foreach ($sort_array_msg as $i => $value){
2829                                if ($value == $msg_number)
2830                                {
2831                                        $success = true;
2832                                        break;
2833                                }
2834                        }
[2]2835                }
2836
[320]2837                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]2838                {
2839                        $params['status'] = 'false';
2840                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2841                        return $params;
2842                }
[1472]2843
[2]2844                $params = array();
2845                $params['msg_number'] = $sort_array_msg[($i+1)];
2846                $params['msg_folder'] = $folder;
[1472]2847
2848                $return = $this->get_info_msg($params);
[2]2849                $return["reuse_border"] = $reuse_border;
2850                return $return;
2851        }
2852
2853        function get_info_previous_msg($params)
2854        {
2855                $msg_number = $params['msgs_number'];
2856                $folder = $params['folder'];
2857                $sort_box_type = $params['sort_box_type'];
2858                $sort_box_reverse = $params['sort_box_reverse'];
2859                $reuse_border = $params['reuse_border'];
[53]2860                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2861                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[1472]2862
[320]2863                $success = false;
2864                if (is_array($sort_array_msg))
[2]2865                {
[320]2866                        foreach ($sort_array_msg as $i => $value){
2867                                if ($value == $msg_number)
2868                                {
2869                                        $success = true;
2870                                        break;
2871                                }
2872                        }
[2]2873                }
[320]2874                if (! $success || $i == 0)
2875                {
[2]2876                        $params['status'] = 'false';
2877                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2878                        return $params;
2879                }
[1472]2880
[2]2881                $params = array();
2882                $params['msg_number'] = $sort_array_msg[($i-1)];
2883                $params['msg_folder'] = $folder;
[1472]2884
[2]2885                $return = $this->get_info_msg($params);
2886                $return["reuse_border"] = $reuse_border;
2887                return $return;
2888        }
[1472]2889
[2]2890        // This function updates the values: quota, paging and new messages menu.
2891        function get_menu_values($params){
2892                $return_array = array();
2893                $return_array = $this->get_quota($params);
[1472]2894
[2]2895                $mbox_stream = $this->open_mbox($params['folder']);
[1472]2896                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
[51]2897                if($mbox_stream)
2898                        imap_close($mbox_stream);
[1472]2899
2900                return $return_array;
[2]2901        }
[1472]2902
[325]2903        function get_quota($params){
[449]2904                // folder_id = user/{uid} for shared folders
2905                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2906                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
[1472]2907                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
[449]2908                }
2909                // folder_id = INBOX for inbox folders
2910                else
2911                        $folder_id = "INBOX";
[1472]2912
[1035]2913                if(!$this->mbox || !is_resource($this->mbox))
[51]2914                        $this->mbox = $this->open_mbox();
[345]2915
[325]2916                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]2917                if($this->mbox && is_resource($this->mbox))
[51]2918                        imap_close($this->mbox);
[1472]2919
[2]2920                if (!$quota){
2921                        return array(
2922                                'quota_percent' => 0,
2923                                'quota_used' => 0,
2924                                'quota_limit' =>  0
2925                        );
2926                }
[1472]2927
[2]2928                if(count($quota) && $quota['limit']) {
2929                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2930                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2931                        if($quota_used >= $quota_limit)
[650]2932                        {
2933                                $quotaPercent = 100;
2934                        }
2935                        else
2936                        {
[2]2937                        $quotaPercent = ($quota_used / $quota_limit)*100;
2938                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
[650]2939                        }
[2]2940                        return array(
2941                                'quota_percent' => floor($quotaPercent),
2942                                'quota_used' => floor($quota_used),
2943                                'quota_limit' =>  floor($quota_limit)
2944                        );
2945                }
[1472]2946                else
[2]2947                        return array();
2948        }
[1472]2949
[2]2950        function send_notification($params){
2951                require_once("class.phpmailer.php");
2952                $mail = new PHPMailer();
[1472]2953
[2]2954                $toaddress = $params['notificationto'];
[1472]2955
[449]2956                $subject = 'Confirmação de leitura: ' . $params['subject'];
[2]2957                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2958                $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");
2959                $mail->SMTPDebug = false;
2960                $mail->IsSMTP();
2961                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2962                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2963                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2964                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2965                $mail->AddAddress($toaddress);
2966                $mail->Subject = $this->htmlspecialchars_decode($subject);
2967
2968                $mail->IsHTML(true);
2969                $mail->Body = $body;
[1472]2970
[2]2971                if(!$mail->Send()){
2972                        return $mail->ErrorInfo;
2973                }
2974                else
2975                        return true;
2976        }
[1472]2977
[2]2978        function empty_trash()
2979        {
[1472]2980                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[2]2981                $mbox_stream = $this->open_mbox($folder);
2982                $return = imap_delete($mbox_stream,'1:*');
[51]2983                if($mbox_stream)
2984                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2985                return $return;
2986        }
[1472]2987
[2]2988        function search($params)
2989        {
[673]2990                include("class.imap_attachment.inc.php");
[1472]2991                $imap_attachment = new imap_attachment();
[2]2992                $criteria = $params['criteria'];
2993                $return = array();
2994                $folders = $this->get_folders_list();
[1472]2995
[2]2996                $j = 0;
2997                foreach($folders as $folder)
2998                {
2999                        $mbox_stream = $this->open_mbox($folder);
3000                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[1472]3001
[2]3002                        if ($messages == '')
3003                                continue;
[1472]3004
[2]3005                        $i = 0;
3006                        $return[$j] = array();
3007                        $return[$j]['folder_name'] = $folder['name'];
[1472]3008
[2]3009                        foreach($messages as $msg_number)
3010                        {
[535]3011                                $header = $this->get_header($msg_number);
[2]3012                                if (!is_object($header))
3013                                        return false;
[1472]3014
[2]3015                                $return[$j][$i]['msg_folder']   = $folder['name'];
3016                                $return[$j][$i]['msg_number']   = $msg_number;
3017                                $return[$j][$i]['Recent']               = $header->Recent;
3018                                $return[$j][$i]['Unseen']               = $header->Unseen;
3019                                $return[$j][$i]['Answered']     = $header->Answered;
3020                                $return[$j][$i]['Deleted']              = $header->Deleted;
3021                                $return[$j][$i]['Draft']                = $header->Draft;
3022                                $return[$j][$i]['Flagged']              = $header->Flagged;
[1472]3023
[535]3024                                $date_msg = gmdate("d/m/Y",$header->udate);
3025                                if (gmdate("d/m/Y") == $date_msg)
3026                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]3027                                else
3028                                        $return[$j][$i]['udate'] = $date_msg;
[1472]3029
[2]3030                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3031                                $return[$j][$i]['fromaddress'] = '';
3032                                foreach ($fromaddress as $tmp)
3033                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[1472]3034
[2]3035                                $from = $header->from;
3036                                $return[$j][$i]['from'] = array();
3037                                $tmp = imap_mime_header_decode($from[0]->personal);
3038                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3039                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]3040                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]3041
3042                                $to = $header->to;
3043                                $return[$j][$i]['to'] = array();
3044                                $tmp = imap_mime_header_decode($to[0]->personal);
3045                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3046                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[1472]3047                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]3048
3049                                $subject = imap_mime_header_decode($header->fetchsubject);
3050                                $return[$j][$i]['subject'] = '';
3051                                foreach ($subject as $tmp)
3052                                        $return[$j][$i]['subject'] .= $tmp->text;
3053
3054                                $return[$j][$i]['Size'] = $header->Size;
3055                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]3056
[2]3057                                $return[$j][$i]['attachment'] = array();
3058                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[1472]3059
[2]3060                                $i++;
3061                        }
3062                        $j++;
[51]3063                        if($mbox_stream)
3064                                imap_close($mbox_stream);
[2]3065                }
[1472]3066
[2]3067                return $return;
3068        }
[1709]3069       
3070       
3071        function mobile_search($params)
3072        {
3073                include("class.imap_attachment.inc.php");
3074                $imap_attachment = new imap_attachment();
3075                $criterias = array ("TO","SUBJECT","FROM","CC");
3076                $return = array();
3077                $folders = $this->get_folders_list();
3078                $num_msgs = 0;
3079                                         
3080                foreach($folders as $id =>$folder)
3081                {
3082                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3083                                foreach($criterias as $criteria_fixed)
3084                    {
3085                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3086                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3087       
3088                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3089                                       
3090                                        if ($messages == ''){
3091                                                if($mbox_stream)
3092                                                        imap_close($mbox_stream);
3093                                                continue;       
3094                                        }
3095                                                                       
3096                                        foreach($messages as $msg_number)
3097                                        {                                       
3098                                                $temp = $this->get_info_head_msg($msg_number);
3099                                                if(!$temp)
3100                                                        return false;
3101               
3102                                                $return[$num_msgs] = $temp;
3103                                                $num_msgs++;
3104                                        }
3105                                        $return['num_msgs'] = $num_msgs;
3106                                       
3107                                        if($mbox_stream)
3108                                                imap_close($mbox_stream);
3109                                }
3110                        }
3111                               
3112                }
3113                return $return;
3114        }
[1472]3115
[2]3116        function delete_and_show_previous_message($params)
3117        {
3118                $return = $this->get_info_previous_msg($params);
[1472]3119
[2]3120                $params_tmp1 = array();
3121                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3122                $params_tmp1['folder'] = $params['msg_folder'];
3123                $return_tmp1 = $this->delete_msg($params_tmp1);
[1472]3124
[2]3125                $return['msg_number_deleted'] = $return_tmp1;
[1472]3126
[2]3127                return $return;
3128        }
[1472]3129
3130
[2]3131        function automatic_trash_cleanness($params)
3132        {
3133                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3134                $criteria =  'BEFORE "'.$before_date.'"';
[325]3135                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[2]3136                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3137                if (is_array($messages)){
3138                        foreach ($messages as $msg_number){
3139                                imap_delete($mbox_stream, $msg_number, FT_UID);
3140                        }
3141                }
[51]3142                if($mbox_stream)
3143                        imap_close($mbox_stream, CL_EXPUNGE);
[2]3144                return $messages;
3145        }
3146//      Fix the search problem with special characters!!!!
3147        function remove_accents($string) {
[1472]3148                return strtr($string,
3149                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]3150                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3151        }
3152
[1622]3153        function make_search_date($date){
3154
3155            $months = array(
3156                1   => 'jan',
3157                2   => 'feb',
3158                3   => 'mar',
3159                4   => 'apr',
3160                5   => 'may',
3161                6   => 'jun',
3162                7   => 'jul',
3163                8   => 'aug',
3164                9   => 'sep',
3165                10  => 'oct',
3166                11  => 'nov',
3167                12  => 'dec'
3168            );
3169
3170            //TODO: Adaptar a data de acordo com o locale do sistema.
3171            list($day,$month,$year) = explode("/", $date);
3172            $search_date = $day."-".$months[intval($month)]."-".$year;
3173            return $search_date;
3174
3175        }
3176
[1472]3177        function search_msg($params = ''){
[1614]3178            $retorno = "";
3179            $mbox_stream = "";
3180            if(strpos($params['condition'],"#")===false) { //local messages
3181                    $search=false;
3182            }
3183            else {
3184                    $search = explode(",",$params['condition']);
3185            }
[689]3186
[1614]3187            if($search){
3188                $search_criteria = '';
3189                $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3190                foreach($search as $tmp)
3191                {
3192                    $tmp1 = explode("##",$tmp);
3193                    $sum = 0;
3194                    $name_box = $tmp1[0];
3195                    unset($filter);
3196                    foreach($tmp1 as $index => $criteria)
3197                    {
3198                        if ($index != 0 && strlen($criteria) != 0)
3199                        {
3200                            $filter_array = explode("<=>",rawurldecode($criteria));
3201                            $filter .= " ".$filter_array[0];
[1622]3202                            if (strlen($filter_array[1]) != 0){
3203                                if (trim($filter_array[0]) != 'BEFORE' &&
3204                                    trim($filter_array[0]) != 'SINCE' &&
3205                                    trim($filter_array[0]) != 'ON')
3206                                {
3207                                    $filter .= '"'.$filter_array[1].'"';
3208                                }
3209                                else
3210                                    {
3211                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3212                                    }
3213                            }
[1614]3214                        }
3215                    }
3216                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3217                    $filter = $this->remove_accents($filter);
3218                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
[1747]3219                    if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
[1614]3220                    {
[1747]3221                        $folder_name = explode($this->imap_delimiter,$name_box);
[1614]3222                        $this->ldap = new ldap_functions();
3223                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3224                        {
3225                            $folder_name[1] = $cn;
3226                        }
[1747]3227                        $folder_name = implode($this->imap_delimiter,$folder_name);
[1614]3228                    }
[1747]3229                    else
3230                    {
3231                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3232                    }
[1472]3233
[1614]3234                    if(!is_resource($mbox_stream))
3235                    {
3236                        $mbox_stream = $this->open_mbox($name_box);
3237                    }
3238                    else
3239                        {
3240                            imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3241                        }
[1472]3242
[1614]3243                    if (preg_match("/^.?\bALL\b/", $filter))
3244                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
[1472]3245
[1614]3246                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3247                        foreach($all_criterias as $criteria_fixed)
3248                        {
3249                            $_filter = $criteria_fixed . substr($filter,4);
[1472]3250
[1614]3251                            $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
[1472]3252
[1614]3253                            if($search_criteria) //&& count($search_criteria) < 50)
3254                            {
3255                                foreach($search_criteria as $new_search)
3256                                {
3257                                    if ($search_result_number != '65536' && $sum == $search_result_number)
[1608]3258                                    {
[1614]3259                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
[1608]3260                                    }
3261
[1614]3262                                    $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");
3263                                    if(!@strstr($retorno,$m_token))
3264                                    {
3265                                        $retorno .= $m_token;
3266                                        $sum ++;
3267                                    }
3268                                }
3269                            }
3270                        }
3271                    }
3272                    else {
3273                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3274                        if( is_array( $search_criteria) )
3275                        {
3276                            foreach($search_criteria as $new_search)
3277                            {
3278                                if ($search_result_number != '65536' && $sum == $search_result_number)
[1608]3279                                {
[1614]3280                                    return $retorno ? $sum . "=sumResults=" . $retorno : "none";
[1608]3281                                }
[1614]3282                                $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
3283                                $sum++;
3284                            }
3285                        }
3286                    }
3287                }
3288            }
3289            if($mbox_stream)
3290            {
3291                imap_close($mbox_stream);
3292            }
[1472]3293
[1614]3294            if ($retorno)
3295            {
3296                return $retorno;
3297            }
3298            else
3299            {
3300                return 'none';
3301            }
[2]3302        }
[1472]3303
[271]3304        function get_msg($uid_msg,$name_box, $mbox_stream )
3305        {
[828]3306                $header = $this->get_header($uid_msg);
3307                include_once("class.imap_attachment.inc.php");
3308                $imap_attachment = new imap_attachment();
3309                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3310                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3311                $flag = $header->Unseen
3312                        .$header->Recent
3313                        .$header->Flagged
3314                        .$header->Draft
3315                        .$header->Answered
3316                        .$header->Deleted
3317                        .$attachments;
3318
3319
[163]3320                $subject = $this->decode_string($header->fetchsubject);
3321                $from = $header->from[0]->mailbox;
[2]3322                if($header->from[0]->personal != "")
3323                        $from = $header->from[0]->personal;
[650]3324                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
[1472]3325                return $ret_msg;
3326        }
[828]3327
[2]3328        function size_msg($size){
3329                $var = floor($size/1024);
3330                if($var >= 1){
[1472]3331                        return $var." kb";
[2]3332                }else{
[1472]3333                        return $size ." b";
[2]3334                }
3335        }
3336
3337        function ob_array($the_object)
3338        {
3339           $the_array=array();
3340           if(!is_scalar($the_object))
3341           {
3342               foreach($the_object as $id => $object)
3343               {
3344                   if(is_scalar($object))
3345                   {
3346                       $the_array[$id]=$object;
3347                   }
3348                   else
3349                   {
3350                       $the_array[$id]=$this->ob_array($object);
3351                   }
3352               }
3353               return $the_array;
3354           }
3355           else
3356           {
3357               return $the_object;
3358           }
3359        }
[1472]3360
[2]3361        function getacl()
3362        {
3363                $this->ldap = new ldap_functions();
[1472]3364
[2]3365                $return = array();
[1472]3366                $mbox_stream = $this->open_mbox();
[2]3367                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]3368
[2]3369                $i = 0;
3370                foreach ($mbox_acl as $user => $acl)
3371                {
3372                        if ($user != $this->username)
3373                        {
3374                                $return[$i]['uid'] = $user;
3375                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3376                        }
3377                        $i++;
3378                }
3379                return $return;
3380        }
[1472]3381
[2]3382        function setacl($params)
3383        {
3384                $old_users = $this->getacl();
3385                if (!count($old_users))
3386                        $old_users = array();
[1472]3387
[2]3388                $tmp_array = array();
3389                foreach ($old_users as $index => $user_info)
3390                {
3391                        $tmp_array[$index] = $user_info['uid'];
3392                }
3393                $old_users = $tmp_array;
[1472]3394
[2]3395                $users = unserialize($params['users']);
3396                if (!count($users))
3397                        $users = array();
[1472]3398
[2]3399                //$add_share = array_diff($users, $old_users);
3400                $remove_share = array_diff($old_users, $users);
3401
3402                $mbox_stream = $this->open_mbox();
3403
3404                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3405                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3406
3407                /*if (count($add_share))
3408                {
3409                        foreach ($add_share as $index=>$uid)
3410                        {
3411                        if (is_array($mailboxes_list))
3412                        {
3413                        foreach ($mailboxes_list as $key => $val)
3414                        {
3415                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3416                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3417                        }
3418                        }
3419                        }
3420                }*/
[1472]3421
[2]3422                if (count($remove_share))
3423                {
3424                        foreach ($remove_share as $index=>$uid)
3425                        {
3426                        if (is_array($mailboxes_list))
3427                        {
3428                        foreach ($mailboxes_list as $key => $val)
3429                        {
3430                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3431                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3432                        }
3433                        }
[1472]3434                        }
[2]3435                }
[1472]3436
[2]3437                return true;
3438        }
[1472]3439
[2]3440        function getaclfromuser($params)
3441        {
3442                $useracl = $params['user'];
[1472]3443
[2]3444                $return = array();
3445                $return[$useracl] = 'false';
[1472]3446                $mbox_stream = $this->open_mbox();
[2]3447                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]3448
[2]3449                foreach ($mbox_acl as $user => $acl)
3450                {
3451                        if (($user != $this->username) && ($user == $useracl))
3452                        {
3453                                $return[$user] = $acl;
3454                        }
3455                }
3456                return $return;
3457        }
3458
3459        function getacltouser($user)
3460        {
3461                $return = array();
3462                $mbox_stream = $this->open_mbox();
[325]3463                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3464                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3465                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3466                if(substr($user,0,4) != 'user')
[449]3467                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]3468                else
3469                  $mbox_acl = imap_getacl($mbox_stream, $user);
[2]3470                return $mbox_acl[$this->username];
3471        }
3472
[1472]3473
[2]3474        function setaclfromuser($params)
3475        {
3476                $user = $params['user'];
3477                $acl = $params['acl'];
[1472]3478
[2]3479                $mbox_stream = $this->open_mbox();
3480
3481                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3482                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3483
3484                if (is_array($mailboxes_list))
3485                {
3486                        foreach ($mailboxes_list as $key => $val)
3487                        {
[449]3488                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3489                                $folder = str_replace("&-", "&", $folder);
[2]3490                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3491                                {
[449]3492                                        $return = imap_last_error();
[2]3493                                }
3494                        }
3495                }
[449]3496                if (isset($return))
3497                        return $return;
3498                else
3499                        return true;
[2]3500        }
[1472]3501
[51]3502        function download_attachment($msg,$msgno)
3503        {
[1472]3504                $array_parts_attachments = array();
[51]3505                $array_parts_attachments['names'] = '';
[689]3506                include_once("class.imap_attachment.inc.php");
[1472]3507                $imap_attachment = new imap_attachment();
3508
[51]3509                if (count($msg->fname[$msgno]) > 0)
3510                {
3511                        $i = 0;
3512                        foreach ($msg->fname[$msgno] as $index=>$fname)
3513                        {
3514                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
[1397]3515                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
[51]3516                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3517                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3518                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3519                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3520                                $i++;
3521                        }
3522                }
3523                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3524                return $array_parts_attachments;
[1472]3525        }
[69]3526
3527        function spam($params)
3528        {
3529                $is_spam = $params['spam'];
3530                $folder = $params['folder'];
3531                $mbox_stream = $this->open_mbox($folder);
3532                $msgs_number = explode(',',$params['msgs_number']);
3533
3534                foreach($msgs_number as $msg_number) {
[877]3535                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3536                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3537                        $body = imap_body($mbox_stream, $imap_msg_number);
[69]3538                        $msg = $header . $body;
3539                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]3540                        $username = $this->username;
[69]3541                        strtok($email, '@');
3542                        $domain = strtok('@');
3543
[449]3544                        //Encontrar a assinatura do dspam no cabecalho
3545                        $v = explode("\r\n", $header);
3546                        foreach ($v as $linha){
[877]3547                                if (eregi("^Message-ID", $linha)) {
3548                                        $args = explode(" ", $linha);
3549                                        $msg_id = "'$args[1]'";
3550                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
[449]3551                                        $args = explode(" ",$linha);
3552                                        $signature = $args[1];
3553                                }
3554                        }
3555
[877]3556                        // Seleciona qual comando a ser executado
[449]3557                        switch($is_spam){
3558                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3559                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3560                        }
[877]3561
3562                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3563                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
[78]3564                        system($cmd);
[69]3565                }
3566                imap_close($mbox_stream);
3567                return false;
3568        }
[535]3569        function get_header($msg_number){
3570                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3571                if (!is_object($header))
3572                        return false;
3573                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3574                $pdate = date_parse($header->MailDate);
3575                $header->udate +=  $pdate['zone']*(-60);
[1472]3576
[673]3577                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[659]3578                        $flag = preg_match('/importance *: *(.*)\r/i',
3579                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]3580                                                ,$importance);
[659]3581                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3582                }
[1472]3583
[535]3584                return $header;
3585        }
[1000]3586
3587//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
3588///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.
3589
3590    function insert_email($source,$folder,$timestamp){
3591        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3592        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3593        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3594        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3595        $imap_options = '/notls/novalidate-cert';
3596        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3597        if(imap_last_error())
3598        {
3599            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3600       }
3601        if($timestamp){
3602            $tempDir = ini_get("session.save_path");
[1247]3603            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
[1000]3604                $f = fopen($file,"w");
3605                fputs($f,base64_encode($source));
3606            fclose($f);
[1586]3607            $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]3608            $return['command']=exec(escapeshellcmd($command));
[1000]3609        }else{
3610            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3611        }
3612        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3613        $return['msg_no'] = $status->uidnext - 1;
3614                $return['error'] = imap_last_error();
3615        if($mbox_stream)
3616                        imap_close($mbox_stream);
3617        return $return;
3618
3619    }
3620
[1035]3621    function show_decript($params){
3622        $source = $params['source'];
3623        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3624        $source = str_replace(" ", "+", $source,$i);
[1472]3625
[1035]3626        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3627            if(!$source = base64_decode($source,true))
3628                return "error ".$source."Espaços ".$i;
3629
3630        }
3631        else {
3632            if(!$source = base64_decode($source))
3633                return "error ".$source."Espaços ".$i;
3634        }
3635
3636        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3637
3638                $get['msg_number'] = $insert['msg_no'];
3639                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3640                $return = $this->get_info_msg($get);
3641                $get['msg_number'] = $params['ID'];
3642                $get['msg_folder'] = $params['folder'];
3643                $tmp = $this->get_info_msg($get);
3644                if(!$tmp['status_get_msg_info'])
3645                {
3646                        $return['msg_day']=$tmp['msg_day'];
3647                        $return['msg_hour']=$tmp['msg_hour'];
3648                        $return['fulldate']=$tmp['fulldate'];
3649                        $return['smalldate']=$tmp['smalldate'];
3650                }
3651                else
3652                {
3653                        $return['msg_day']='';
3654                        $return['msg_hour']='';
3655                        $return['fulldate']='';
3656                        $return['smalldate']='';
3657                }
3658        $return['msg_no'] =$insert['msg_no'];
3659        $return['error'] = $insert['error'];
3660        $return['folder'] = $params['folder'];
3661        //$return['acls'] = $insert['acls'];
3662        $return['original_ID'] =  $params['ID'];
3663
3664        return $return;
3665
3666    }
[1472]3667
[1000]3668//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
3669//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3670
3671    function treat_base64_from_post($source){
3672            $offset = 0;
3673            do
3674            {
3675                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3676                    {
3677                            $inicio = strpos($source, "\n\r", $inicio);
3678                            $fim = strpos($source, '--', $inicio);
3679                            if(!$fim)
3680                                    $fim = strpos($source,"\n\r", $inicio);
3681                            $length = $fim-$inicio;
3682                            $parte = substr( $source,$inicio,$length-1);
3683                            $parte = str_replace(" ", "+", $parte);
3684                            $source = substr_replace($source, $parte, $inicio, $length-1);
3685                    }
3686                    if($offset > $inicio)
3687                    $offset=FALSE;
3688                    else
3689                    $offset = $inicio;
3690            }
3691            while($offset);
3692            return $source;
3693    }
3694
3695//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.
3696
3697    function unarchive_mail($params)
3698    {
3699        $dest_folder = $params['folder'];
3700        $sources = explode("#@#@#@",$params['source']);
3701        $timestamps = explode("#@#@#@",$params['timestamp']);
3702        foreach($sources as $index=>$src) {
3703                        if($src!=""){
3704                                $source = $this->treat_base64_from_post($src);
3705                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3706                        }
3707                }
3708        return $insert;
3709    }
3710
3711    function download_all_local_attachments($params)
3712    {
3713        $source = $params['source'];
3714        $source = $this->treat_base64_from_post($source);
3715        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3716        $exporteml = new ExportEml();
3717        $params['num_msg']=$insert['msg_no'];
3718        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3719        return $exporteml->download_all_attachments($params);
3720    }
[2]3721}
[278]3722?>
Note: See TracBrowser for help on using the repository browser.