source: companies/serpro/expressoMail1_2/inc/class.imap_functions.inc.php @ 903

Revision 903, 117.9 KB checked in by niltonneto, 15 years ago (diff)

Importacao inicial do Expresso do Serpro

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