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

Revision 1037, 122.6 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Correção de problema, usando caminho relativo

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