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

Revision 1940, 134.8 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #890 - Corrigindo assinatura da função get_msg_sample

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