source: branches/2.0/expressoMail1_2/inc/class.imap_functions.inc.php @ 1954

Revision 1954, 124.7 KB checked in by niltonneto, 14 years ago (diff)

Ticket #758 - Melhorada a implementação que remove "INBOX/decifradas".

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