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

Revision 5346, 201.8 KB checked in by gustavo, 12 years ago (diff)

Ticket #2433 - Adicionar a configuração da nova agenda no expressoMail

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3include_once("class.functions.inc.php");
4include_once("class.ldap_functions.inc.php");
5include_once("class.exporteml.inc.php");
6
7class imap_functions
8{
9        var $public_functions = array
10        (
11                'get_range_msgs'                                => True,
12                'get_info_msg'                                  => True,
13                'get_info_msgs'                                 => True,
14                'get_folders_list'                              => True,
15                'import_msgs'                                   => True,
16                'report_mail_error'             => True,
17                'msgs_to_archive'                               => True
18        );
19
20        var $ldap;
21        var $mbox;
22        var $imap_port;
23        var $has_cid;
24        var $imap_options = '';
25        var $functions;
26        var $prefs;
27        var $foldersLimit;
28        var $imap_sentfolder;
29        var $rawMessage;
30        var $folders;
31
32       
33        function imap_functions (){
34                $this->init();
35        }
36       
37        function init(){
38                $this->foldersLimit    = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] ?  $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] : 20000; //Limit of folders (mailboxes) user can see
39                $this->username            = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
40                $this->password            = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
41                $this->imap_server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
42                $this->imap_port           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
43                $this->imap_delimiter  = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
44                $this->functions           = new functions();
45                $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   : str_replace("*","", $this->functions->getLang("Sent"));
46                $this->has_cid = false;
47                $this->prefs               = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
48               
49                //armazena os caminhos das pastas ( sent, spam, drafts, trash )
50                $this->folders['sent']    =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']) ? 'Sent' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']; //Variavel folders armazena o caminho /sent
51                $this->folders['spam']    =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']) ? 'Spam' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
52                $this->folders['drafts']  =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']) ? 'Drafts' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
53                $this->folders['trash']   =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']) ? 'Trash' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
54
55                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
56                {
57                        $this->imap_options = '/tls/novalidate-cert';
58                }
59                else
60                {
61                        $this->imap_options = '/notls/novalidate-cert';
62                }
63        }
64       
65        function mount_url_folder($folders){
66                return implode($this->imap_delimiter,$folders);
67        }
68       
69        // BEGIN of functions.
70        function open_mbox($folder = False,$force_die=true)
71        {
72                $folder = mb_convert_encoding($folder, "UTF7-IMAP",'UTF-8, ISO-8859-1, UTF7-IMAP');
73                if (is_resource($this->mbox))
74                {
75                     if ($force_die)
76                     {
77                        @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
78                     }
79                     else
80                        {
81                            @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder);
82                        }
83                }
84                else
85                    {
86                        if($force_die)
87                        {
88                            $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
89                        }
90                        else
91                            {
92                                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password);
93                            }
94                       
95                    }
96                    return $this->mbox;
97         }
98
99        function parse_error($error, $field = ''){
100                // This error is returned from Imap.
101                if(strstr($error,'Connection refused')) {
102                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
103                }
104                else if(strstr($error,'virus')) {
105                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
106                }
107                else if(strstr($error,'Failed to add recipient:')) {
108                        preg_match_all('/:\s([\s\.";@!a-z0-9]+)\s\[SMTP:/', $error, $res);
109                        return  str_replace("%1", $res['1']['0'], $this->functions->getLang("SMTP Error: The following recipient addresses failed: %1"));
110                }
111                else if(strstr($error,'Recipient address rejected')) {
112                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Invalid recipients in the message").'.');
113                }
114                else if(strstr($error,'Invalid Mail:')) {
115                        return  str_replace("%1", $field, $this->functions->getLang("The recipients addresses failed %1"));
116                }
117                else if(strstr($error,'Message file too big')) {
118                        return ($this->functions->getLang("Message file too big."));
119                }
120                // This condition verifies if SESSION is expired.
121                elseif(!count($_SESSION))
122                        return "nosession";
123
124                return $error;
125        }
126
127        function get_range_msgs2($params)
128        {
129                // Free others requests
130                session_write_close();
131                $folder = $params['folder'];
132                $msg_range_begin = $params['msg_range_begin'];
133                $msg_range_end = $params['msg_range_end'];
134                $sort_box_type          = isset($params['sort_box_type']) ? $params['sort_box_type'] : '';
135                $sort_box_reverse       = isset($params['sort_box_reverse']) ? $params['sort_box_reverse'] : '';
136                $search_box_type        = (isset($params['search_box_type']) && $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" )? $params['search_box_type'] : false;
137
138                if( !$this->mbox || !is_resource( $this->mbox ) )
139                        $this->mbox = $this->open_mbox($folder);
140
141        $return = array();
142
143        $return['folder'] = $folder;
144
145        //Para enviar o offset entre o timezone definido pelo usuário e GMT
146        $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
147
148        if(!$search_box_type || $search_box_type=="UNSEEN" || $search_box_type=="SEEN") {
149                        $msgs_info = imap_status($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".mb_convert_encoding( $folder, "UTF7-IMAP", "ISO_8859-1" ) ,SA_ALL);
150
151
152                        $return['tot_unseen'] = $search_box_type == "SEEN" ? 0 : $msgs_info->unseen;
153
154                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
155
156                        $num_msgs = ($search_box_type=="UNSEEN") ? $msgs_info->unseen : (($search_box_type=="SEEN") ? ($msgs_info->messages - $msgs_info->unseen) : $msgs_info->messages);
157
158                        $i = 0;
159                        if(is_array($sort_array_msg)){
160                                foreach($sort_array_msg as $msg_number => $value)
161                                {
162                                        $temp = $this->get_info_head_msg($msg_number);
163                                        $temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
164                                        if(!$temp)
165                                                return false;
166
167                                        $return[$i] = $temp;
168                                        $i++;
169                                }
170                        }
171                        $return['num_msgs'] =  $num_msgs;
172                }
173                else {
174                        $num_msgs = imap_num_msg($this->mbox);
175                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
176
177
178                        $return['tot_unseen'] = 0;
179                        $i = 0;
180
181                        if(is_array($sort_array_msg)){
182
183                            foreach($sort_array_msg as $msg_number => $value)
184                            {
185                                $temp = $this->get_info_head_msg($msg_number);
186                                if(!$temp)
187                                    return false;
188
189                                if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
190                                                $return['tot_unseen']++;
191                                        }
192
193                                if($i <= ($msg_range_end-$msg_range_begin))
194                                    $return[$i] = $temp;
195                                $i++;
196                            }
197                        }
198                        $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
199                }
200                return $return;
201    }
202
203        function get_info_head_msg($msg_number)
204        {
205                $head_array = array();
206                include_once("class.imap_attachment.inc.php");
207
208                $imap_attachment = new imap_attachment();
209                //if ($this->prefs['use_important_flag'] )
210                //{
211                        /*Como eu preciso do atributo Importance para saber se o email é
212                         * importante ou não, uso abaixo a função imap_fetchheader e busco
213                         * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
214                         * duas vezes e de duas formas diferentes, mas em contrapartida, eu
215                         * não preciso reimplementar o método utilizando o fetchheader.
216                         * Como as mensagens são renderizadas em um número pequeno por vez,
217                         * não parece ter perda considerável de performance.
218                         */
219
220                        $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
221                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
222                //}
223                // Reimplementado código para identificação dos e-mails assinados e cifrados
224                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
225                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
226                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
227
228                $header = $this->get_header($msg_number);
229                if (!is_object($header))
230                        return false;
231                $head_array['Recent'] = $header->Recent;
232                $head_array['Unseen'] = $header->Unseen;
233                if($header->Answered =='A' && $header->Draft == 'X'){
234                        $head_array['Forwarded'] = 'F';
235                }
236                else {
237                        $head_array['Answered'] = $header->Answered;
238                        $head_array['Draft']    = $header->Draft;
239                }
240                $head_array['Deleted'] = $header->Deleted;
241                $head_array['Flagged'] = $header->Flagged;
242                $head_array['msg_number'] = $msg_number;
243                $head_array['udate'] = $header->udate;
244                $head_array['offsetToGMT'] = $this->functions->CalculateDateOffset();
245
246                $msgTimestamp = $header->udate + $head_array['offsetToGMT'];
247                $head_array['timestamp'] = $msgTimestamp;
248               
249                $date_msg = gmdate("d/m/Y",$msgTimestamp);
250//              if (date("d/m/Y") == $date_msg)
251//                      $return['udate'] = $header->udate;
252//              else
253
254                if (date("d/m/Y") == $date_msg) //no dia
255                {
256                        $head_array['smalldate'] = gmdate("H:i",$msgTimestamp);
257                }
258                else
259                {
260                        $head_array['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
261                }
262
263                if(isset($header->from))
264                $from = $header->from;
265                $head_array['from'] = array();
266                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
267                if(isset($from))
268                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
269                else
270                        $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@";
271                if(!$head_array['from']['name'] || trim($head_array['from']['name']) === '' )
272                        $head_array['from']['name'] = $head_array['from']['email'];
273                if(isset($header->to))
274                $to = $header->to;
275                $head_array['to'] = array();
276                if(isset($to[1]) && isset($to[1]->host) && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
277                        $head_array['to']['name'] = $head_array['to']['email'] = NULL;
278                }
279                else {
280                        $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
281                        $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
282                        $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
283                        if(!$head_array['to']['name'])
284                                $head_array['to']['name'] = $head_array['to']['email'];
285                }
286                $cc = null;
287                $cco = null;
288                if(isset($header->cc)){
289                $cc = $header->cc;
290                }
291                if(isset($header->bcc)){
292                $cco = $header->bcc;
293                }
294                if ( ($cc) && (!$head_array['to']['name']) ){
295                        $head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL;
296                        $head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host;
297                        if(!$head_array['to']['name']){
298                                $head_array['to']['name'] = $head_array['from']['name'];
299                                //$head_array['to']['email'] = $head_array['from']['email'];
300                        }
301                }
302                else if ( ($cco) && (!$head_array['to']['name']) ){
303                        $head_array['to']['name'] = ( isset( $cco[0]->personal ) ) ? $this->decode_string($cco[0]->personal) : NULL;
304                        $head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host;
305                        if(!$head_array['to']['name'])
306                                $head_array['to']['name'] = $head_array['from']['name'];
307                }
308                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
309                if($head_array['subject'] == "" || $head_array['subject'] == '' || $head_array['subject'] == null ){
310                        $head_array['subject'] = $this->functions->getLang("(no subject)   ");
311                }
312       
313                if($head_array['to']['name'] == 'undisclosed-recipients@' || $head_array['to']['name'] == '@'){
314                        $head_array['to']['name'] = $head_array['from']['name'];
315                        $head_array['to']['email'] = $head_array['from']['email'];
316                }
317
318                $head_array['Size'] = $header->Size;
319
320                $head_array['attachment'] = array();
321                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
322
323                return $head_array;
324        }
325
326        /**
327        *
328        * @license    http://www.gnu.org/copyleft/gpl.html GPL
329        * @param      string $string String a ser decodificada
330        * @return     string
331        * @todo       Verificar a possibilidade de se utilizar a função iconv_mime_decode, que é capaz de identificar a codificação por si só, mas que pode ser interpretada de forma diversa dependendo da implementação do sistema
332        * @todo       Executar testes suficientes para validar a funçao iconv_mime_decode em substituição à este método decode_string
333        */
334        function decode_string($string)
335        {
336        $return = '';
337        $decoded = '';
338                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
339                {
340                        $tmp = imap_mime_header_decode($string);
341                        foreach ($tmp as $tmp1)
342            {
343                                $return .= $this->htmlspecialchars_encode($tmp1->text);
344            }
345
346            return str_replace("\t", "", $return);
347                }
348                else if (strpos(strtolower($string), '=?utf-8') !== false)
349                {
350                        $elements = imap_mime_header_decode($string);
351
352                        for($i = 0;$i < count($elements);$i++)
353                        {
354                                $charset = strtolower($elements[$i]->charset);
355                                $text = $elements[$i]->text;
356                                if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
357                                $decoded .= $this->functions->utf8_to_ncr($text);
358                                else
359                                {
360                                        if( strcasecmp($charset,"default") )
361                                                $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
362                                        else
363                                                $decoded .= $this->htmlspecialchars_encode($text);
364                                }
365                        }
366
367              return str_replace("\t", "", $decoded);
368                }
369                else if(strpos(strtolower($string), '=?us-ascii') !== false)
370           {
371                        $retun = '';
372                        $tmp = imap_mime_header_decode($string);
373                        foreach ($tmp as $tmp1)
374                                $return .= $this->htmlspecialchars_encode(quoted_printable_decode($tmp1->text));
375               
376                        return str_replace("\t", "", $return);
377         
378            }
379        else if( strpos( $string , '=?' ) !== false )
380            return $this->htmlspecialchars_encode(iconv_mime_decode( $string ));
381       
382
383                        return $this->htmlspecialchars_encode($string);
384        }
385       
386       
387        /**
388        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
389        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
390        */
391        function import_msgs($params) {         
392                if(!$this->mbox)
393                        $this->mbox = $this->open_mbox();
394
395                if( preg_match('/local_/',$params["folder"]) ){
396                       
397                        // PLEASE, BE CAREFULL!!! YOU SHOULD USE EMAIL CONFIGURATION VALUES (EMAILADMIN MODULE)
398                        //$tmp_box = mb_convert_encoding('INBOX'.$this->folders['trash'].$this->imap_delimiter.'tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
399                        $tmp_box = mb_convert_encoding($this->mount_url_folder(array("INBOX",$this->folders['trash'],"tmpMoveToLocal")), "UTF7-IMAP", "UTF-8");
400                       
401                        if ( ! imap_createmailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" ) )
402                                return $this->functions->getLang( 'Import to Local : fail...' );
403                        imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
404                        $params["folder"] = $tmp_box;
405                }
406               
407                $errors = array();
408                $invalid_format = false;
409                $filename = $params['FILES'][0]['name'];
410                $params["folder"] = mb_convert_encoding($params["folder"], "UTF7-IMAP","ISO-8859-1, UTF-8");
411                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
412               
413                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
414                        return array( 'error' => $this->functions->getLang("fail in import:").
415                                                        " ".$this->functions->getLang("Over quota"));
416                }
417               
418                if(substr($filename,strlen($filename)-4)==".zip") {
419                        $zip = zip_open($params['FILES'][0]['tmp_name']);
420                        if ($zip) {
421                                while ($zip_entry = zip_read($zip)) {
422
423                                        if (zip_entry_open($zip, $zip_entry, "r")) {
424                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
425                                                $status = @imap_append($this->mbox,
426                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
427                                                                        $email
428                                                                        );
429                                                if(!$status)
430                                                        array_push($errors,zip_entry_name($zip_entry));
431                                                zip_entry_close($zip_entry);
432                                        }
433                                }
434                                zip_close($zip);
435                        }
436                        if (isset( $tmp_box ) && ! sizeof( $errors )){
437                                $mc = imap_check($this->mbox);
438                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
439                                $ids = array( );
440                                foreach ($result as $overview)
441                                        $ids[ ] = $overview -> uid;
442                                return implode( ',', $ids );
443                        }
444               
445                }else if(substr($filename,strlen($filename)-4)==".eml") {
446                        $email = implode("",file($params['FILES'][0]['tmp_name']));
447                        $status = imap_append($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],$email);
448                               
449                        if(!$status)
450                                return "Error importing";
451                       
452                        if ( isset( $tmp_box ) && ! sizeof( $errors ) ) {
453                                $mc = imap_check($this->mbox);
454
455                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
456
457                                $ids = array( );
458                                foreach ($result as $overview)
459                                        $ids[ ] = $overview -> uid;
460
461                                return implode( ',', $ids );
462                        }
463                }
464                else{
465                        if ( isset( $tmp_box ) )
466                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
467
468                        return array("error" => $this->functions->getLang("wrong file format"));
469                        $invalid_format = true;
470                }
471
472                if(!$invalid_format) {
473                        if(count($errors)>0) {
474                                $message = $this->functions->getLang("fail in import:")."\n";
475                                foreach($errors as $arquivo) {
476                                        $message.=$arquivo."\n";
477                                }
478                                return array("error" => $message);
479                        }
480                        else
481                                return $this->functions->getLang("The import was executed successfully.");
482                }
483        }
484        /*
485                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
486                a primeira parte do e-mail, que é o texto, sem anexos.
487                O método considera que o email é multpart.
488        */
489        function remove_attachments($params) {
490                include_once("class.message_components.inc.php");
491                if(!$this->mbox || !is_resource($this->mbox))
492                        $this->mbox = $this->open_mbox($params["folder"]);
493                $return["status"] = true;
494                $header = "";
495
496                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
497                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
498                        $head1 = explode(":",$head);
499                        if ( (strtoupper($head1[0]) == "TO") ||
500                                        (strtoupper($head1[0]) == "FROM") ||
501                                        (strtoupper($head1[0]) == "SUBJECT") ||
502                                        (strtoupper($head1[0]) == "DATE") )
503                                $header .= $head."\r\n";
504                }
505
506                $msg = new message_components($this->mbox);
507                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
508                                                             Então uso essa classe para verificar a codificação e o charset,
509                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
510
511                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][0]);
512                $all_body_encoding = $msg->encoding[$params["msg_num"]][0];
513                $all_body_charset = $msg->charset[$params["msg_num"]][0];
514               
515                if($all_body_type=='multipart/alternative') {
516                        if(strtolower($msg->file_type[$params["msg_num"]][2]=='text/html') &&
517                                        $msg->pid[$params["msg_num"]][2] == '1.2') {
518                                $body_part_to_show = '1.2';
519                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][2]);
520                                $all_body_encoding = $msg->encoding[$params["msg_num"]][2];
521                                $all_body_charset = $msg->charset[$params["msg_num"]][2];
522                        }
523                        else {
524                                $body_part_to_show = '1.1';
525                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][1]);
526                                $all_body_encoding = $msg->encoding[$params["msg_num"]][1];
527                                $all_body_charset = $msg->charset[$params["msg_num"]][1];
528                        }
529                }
530                else
531                        $body_part_to_show = '1';
532
533                $status = imap_append($this->mbox,
534                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
535                                        $header.
536                                        "Content-Type: ".$all_body_type."; charset = \"".$all_body_charset."\"".
537                                        "\r\n".
538                                        "Content-Transfer-Encoding: ".$all_body_encoding.
539                                        "\r\n".
540                                        "\r\n".
541                                        str_replace("\n","\r\n",preg_replace("/<img[^>]+\>/i", " ", $this->decodeBody(
542                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
543                                                        $all_body_encoding, $all_body_charset
544                                                        ))
545                                        ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos. //Remove imagens do corpo, pois estas estão na lista de anexo e serão removidas.
546
547                if(!$status)
548                {
549                        $return["status"] = false;
550                        $return["msg"] = lang("error appending mail on delete attachments");
551                }
552                else
553                {
554                        $status = imap_status($this->mbox, "{".$this->imap_server.":".$this->imap_port."}".$params['folder'], SA_UIDNEXT);
555                        $return['msg_no'] = $status->uidnext - 1;
556                        imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"]));
557                        imap_expunge($this->mbox);
558                }
559
560                return $return;
561
562        }
563       
564        function msgs_to_archive($params) {
565               
566                $folder = $params['folder'];
567                $all_ids = $this-> get_msgs($folder, 'SORTARRIVAL', false, 0,-1,-1);
568
569                $messages_not_to_copy = explode(",",$params['mails']);
570                $ids = array();
571               
572                $cont = 0;
573               
574                foreach($all_ids as $each_id=>$value) {
575                        if(!in_array($each_id,$messages_not_to_copy)) {
576                                array_push($ids,$each_id);
577                                $cont++;
578                        }
579                        if($cont>=100)
580                                break;
581                }
582
583                if (empty($ids))
584                        return array();
585
586                $params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
587               
588               
589                return $this->get_info_msgs($params);
590               
591               
592        }
593
594/**
595         *
596         * @return
597         * @param $params Object
598         */
599        function get_info_msgs($params) {
600                include_once("class.exporteml.inc.php");
601               
602                if(array_key_exists('messages', $params)){
603                        $sel_msgs = explode(",", $params['messages']);
604                        @reset($sel_msgs);
605                        $sorted_msgs = array();
606                        foreach($sel_msgs as $idx => $sel_msg) {
607                                $sel_msg = explode(";", $sel_msg);
608                                if(array_key_exists($sel_msg[0], $sorted_msgs)){
609                                        $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
610                                }
611                                else {
612                                        $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
613                                }
614                        }
615                        unset($sorted_msgs['']);       
616               
617                        $return = array();
618                        $array_names_keys = array_keys($sorted_msgs);
619                       
620                        for($i = 0; $i < count($sorted_msgs); $i++){
621                       
622                                $new_params = array();
623                                $attach_params = array();
624                       
625                                $new_params["msg_folder"]= $array_names_keys[$i];
626                                $attach_params["folder"] = $params["folder"];
627                                $msgs = explode(",",$sorted_msgs[$array_names_keys[$i]]);
628                                $exporteml = new ExportEml();
629                                $unseen_msgs = array();
630                                foreach($msgs as $msg_number) {
631                                        $new_params["msg_number"] = $msg_number;
632                                        //ini_set("display_errors","1");
633                                        $msg_info = $this->get_info_msg($new_params);
634
635                                        $this->mbox = $this->open_mbox($array_names_keys[$i]); //Não sei porque, mas se não abrir de novo a caixa dá erro.
636                                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
637
638                                        $attach_params["num_msg"] = $msg_number;
639                                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
640                                        imap_close($this->mbox);
641                                        $this->mbox=false;
642                                        array_push($return,serialize($msg_info));
643                               
644                                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
645                                                        array_push($unseen_msgs,$msg_number);
646                                        }
647                                }
648                        }
649                        if($unseen_msgs){
650                                $msgs_list = implode(",",$unseen_msgs);
651                                $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
652                                $this->set_messages_flag($array_msgs);
653                        }
654                        return $return;
655                }else{
656                $return = array();
657                $new_params = array();
658                $attach_params = array();
659                $new_params["msg_folder"]=$params["folder"];
660                $attach_params["folder"] = $params["folder"];
661                $msgs = explode(",",$params["msgs_number"]);
662                $exporteml = new ExportEml();
663                $unseen_msgs = array();
664                foreach($msgs as $msg_number) {
665                        $new_params["msg_number"] = $msg_number;
666                        //ini_set("display_errors","1");
667                        $msg_info = $this->get_info_msg($new_params);
668
669                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
670                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
671
672                        $attach_params["num_msg"] = $msg_number;
673                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
674                        imap_close($this->mbox);
675                        $this->mbox=false;
676                        array_push($return,serialize($msg_info));
677
678                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
679                                        array_push($unseen_msgs,$msg_number);
680                        }
681                }
682                if($unseen_msgs){
683                        $msgs_list = implode(",",$unseen_msgs);
684                        $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
685                        $this->set_messages_flag($array_msgs);
686                }
687                return $return;
688        }
689        }
690
691        /**
692        * @license    http://www.gnu.org/copyleft/gpl.html GPL
693        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
694        * @param     $msg_number numero da mensagem
695        */
696        function getRawHeader($msg_number)
697    {
698                return imap_fetchheader($this->mbox, $msg_number, FT_UID);
699        }
700       
701        /**
702        * @license    http://www.gnu.org/copyleft/gpl.html GPL
703        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
704        * @param     $msg_number numero da mensagem
705        */
706        function getRawBody($msg_number)
707    {
708                return  imap_body($this->mbox, $msg_number, FT_UID);   
709        }
710
711       
712        /**
713        * @license    http://www.gnu.org/copyleft/gpl.html GPL
714        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
715        * @param     $msg mensagem
716        */
717        function builderMsgHeader($msg)
718    {
719
720 
721            $fromMail =  str_replace('<','', str_replace('>','',$msg->headers['from']));
722            $tosMails =  str_replace('<','', str_replace('>','',$msg->headers['to']));
723
724            $tos = explode(',',$tosMails);
725            $to = '';
726            foreach ($tos as $value)
727            {
728                $to .= '<a href="mailto:'.str_replace(' ','',$value).'">'.$value.'</a>, ';
729            }
730
731            $header = '
732                <table style="margin: 2px; border: 1px solid black; background: none repeat scroll 0% 0% rgb(234, 234, 234);">
733                <tbody>
734                <tr><td><b>'.$this->functions->getLang('Subject').':</b></td><td>'.$msg->headers['subject'].'</td></tr>
735                <tr><td><b>'.$this->functions->getLang('From').':</b></td><td><a href="mailto:'.$fromMail.'">'.$fromMail.'</a></td></tr>
736                <tr><td><b>'.$this->functions->getLang('Date').':</b></td><td>'.$msg->headers['date'].'</td></tr>
737                <tr><td><b>'.$this->functions->getLang('To').':</b></td><td>'.$to.'</td></tr>
738                </tbody>
739                </table>
740                <br />'
741            ;
742
743          return $header;
744    }
745       
746        /**
747        * Constroe o corpo da msg direto na variavel de conteudo
748        * @param Mail_mimeDecode $structure
749        * @param <type> $content Ponteiro para Variavel de conteudo da msg
750        */
751        function builderMsgBody($structure , &$content , $printHeader = false)
752        {
753            if(strtolower($structure->ctype_primary) == 'multipart' && strtolower($structure->ctype_secondary) == 'alternative')
754            {
755                $numParts = count($structure->parts) - 1;
756
757                for($i = $numParts; $i >= 0; $i--)
758                {
759                    $part = $structure->parts[$i];
760
761                    switch (strtolower($part->ctype_primary))
762                    {
763                       case 'text':
764                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
765                           if($disposition != 'attachment')
766                           {
767                                if(strtolower($part->ctype_secondary) == 'html')
768                                {
769                                   if($printHeader)
770                                        $content .= $this->builderMsgHeader($part);
771
772                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
773                                }
774
775                                if(strtolower($part->ctype_secondary) == 'plain' )
776                                {
777                                  if($printHeader)
778                                      $content .= $this->builderMsgHeader($part);
779
780                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
781                                }
782                                if(strtolower($part->ctype_secondary) == 'calendar')
783                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
784
785                           }
786
787                            $i = -1;
788                            break;
789
790                       case 'multipart':
791
792                            if($printHeader)
793                               $content .= $this->builderMsgHeader($part);
794
795                            $this->builderMsgBody($part,$content);
796
797                            $i = -1;
798                            break;
799
800                       case 'message':
801
802                            if(!is_array($part->parts))
803                            {
804                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
805                                $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body, $structure->ctype_parameters['charset'],false)).'</pre>';
806                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
807                            }
808                            else
809                                $this->builderMsgBody($part,$content,true);
810
811                            $i = -1;
812                            break;
813                    }
814                }
815            }
816            else
817            {
818                foreach ($structure->parts  as $index => $part)
819                {
820                   switch (strtolower($part->ctype_primary))
821                   {
822                       case 'text':
823                           $disposition = '';
824                           if(isset($part->disposition))
825                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
826                           if($disposition != 'attachment')
827                           {
828                                if(strtolower($part->ctype_secondary) == 'html')
829                                {
830                                   if($printHeader)
831                                        $content .= $this->builderMsgHeader($part);
832
833                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
834                                }
835
836                                if(strtolower($part->ctype_secondary) == 'plain')
837                                {
838                                  if($printHeader)
839                                      $content .= $this->builderMsgHeader($part);
840
841                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
842                                }
843                                if(strtolower($part->ctype_secondary) == 'calendar')
844                                    $content .= $this->builderMsgCalendar($part->body);
845                       
846                           }
847                            break;
848                       case 'multipart':
849
850                            if($printHeader)
851                               $content .= $this->builderMsgHeader($part);
852
853                            $this->builderMsgBody($part,$content);
854
855                            break;
856                       case 'message':
857                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != '1')
858                        {
859                            if(!is_array($part->parts))
860                            {
861                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
862                                $content .= '<pre>'.  htmlentities($this->decodeMailPart($part->body, $structure->ctype_parameters['charset'],false)).'</pre>';
863                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
864                            }
865                            else
866                                $this->builderMsgBody($part,$content,true);
867                        break;
868                 }
869               }
870            }
871        }
872        }
873       
874       
875        /**
876        * @license    http://www.gnu.org/copyleft/gpl.html GPL
877        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
878        * @param     $msg_number numero da mensagem
879        */
880        function get_msg_sample($msg_number)
881        {
882        $content = '';
883
884                $return = "";
885                if( (!isset($this->prefs['preview_msg_subject']) || ($this->prefs['preview_msg_subject'] != "1")) &&
886                        (!isset($this->prefs['preview_msg_tip']    ) || ($this->prefs['preview_msg_tip']     != "1")) )
887                {
888                        $return['body'] = "";
889                        return $return;
890                }
891
892                include_once("class.message_components.inc.php");
893                $msg = new message_components($this->mbox);
894                $msg->fetch_structure($msg_number); 
895
896                if(!isset($msg->structure[$msg_number]->parts))
897                {
898                        $content = '';
899                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
900                        {
901                                $content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
902                        }
903                }
904                else
905                {
906                        foreach($msg->pid[$msg_number] as $values => $msg_part)
907                        {
908
909                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
910                                if($file_type == "text/plain" || $file_type == "text/html") {
911                                        $content = $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID|FT_PEEK), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
912                                        break;
913                                }
914                        }
915                }
916     
917                $tags_replace = array("<br>","<br/>","<br />");
918                $content = str_replace($tags_replace," ", nl2br($content));
919                $content = $this->html2txt($content);   
920                $content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
921                $return['body'] = base64_encode(mb_convert_encoding(substr($return['body'], 0, 305),'ISO-8859-1'));
922                return $return;
923        }
924    function html2txt($document){
925        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
926                       '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
927                       '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
928                       '@<![\s\S]*?--[ \t\n\r]*>@si'         // Strip multi-line comments including CDATA                   
929        );
930        $text = preg_replace($search, '', $document);
931        return html_entity_decode($text);
932    }
933
934    function ope_msg_part($params)
935    {
936        $return = array();
937        require_once dirname(__FILE__).'/class.attachment.inc.php';
938       
939        $atObj = new attachment();
940        $atObj->setStructureFromMail($params['msg_folder'],$params['msg_number']);
941        $mbox_stream = $this->open_mbox($params['save_folder']);
942        $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], $atObj->getAttachment($params['msg_part']), "\\Seen \\Draft");
943        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], SA_UIDNEXT);
944       
945        $return['msg_folder']  = $params['save_folder'];
946        $return['msg_number'] = $status->uidnext - 1;       
947
948        return $return;
949
950    }
951       
952        function get_info_msg($params)
953        {
954                $return = array();
955                $msg_number = $params['msg_number'];
956                $msg_folder = urldecode($params['msg_folder']);
957               
958                if(preg_match('/(.+)(_[a-zA-Z0-9]+)/',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.
959                        $msg_number = $matches[1];
960                        $plus_id = $matches[2];
961                }
962                else {
963                        $plus_id = '';
964                }
965
966                if(!$this->mbox || !is_resource($this->mbox))
967                        $this->mbox = $this->open_mbox($msg_folder);
968               
969                $header = $this->get_header($msg_number);
970                if (!$header) {
971                        $return['status_get_msg_info'] = "false";
972                        return $return;
973                }
974
975                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
976                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
977                $body = $return_get_body['body'];
978                if($return_get_body['body']=='isCripted'){
979                        $exporteml = new ExportEml();
980                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
981                        $return['body']                 = "";
982                        $return['attachments']  =  "";
983                        $return['thumbs']               =  "";
984                        $return['signature']    =  "";
985                        //return $return;
986                }else{
987            $return['body']             = $body;
988            $return['attachments']      = $return_get_body['attachments'];
989            $return['thumbs']           = $return_get_body['thumbs'];
990            //$return['signature']      = $return_get_body['signature'];
991                }
992                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
993                if (preg_match($pattern, $header_, $fields))
994                {
995                        if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
996                                $return['DispositionNotificationTo'] = "<".$matches[0].">";
997                        }
998                }
999
1000                $return['Recent']       = $header->Recent;
1001                $return['Unseen']       = $header->Unseen;
1002                $return['Deleted']      = $header->Deleted;
1003                $return['Flagged']      = $header->Flagged;
1004
1005                if($header->Answered =='A' && $header->Draft == 'X'){
1006                        $return['Forwarded'] = 'F';
1007                }
1008
1009                else {
1010                        $return['Answered']     = $header->Answered;
1011                        $return['Draft']        = $header->Draft;
1012                }
1013
1014                $return['msg_number'] = $msg_number.$plus_id;
1015                $return['msg_folder'] = $msg_folder;
1016
1017               
1018               
1019                $msgTimesTamp = $header->udate + $this->functions->CalculateDateOffset(); //Aplica offset do usuario
1020                $date_msg = gmdate("d/m/Y",$msgTimesTamp);
1021
1022//      Removido codigo pois a o método send_nofication precisa da data completa.
1023//              if (date("d/m/Y") == $date_msg)
1024//                      $return['udate'] = gmdate("H:i",$header->udate);
1025//              else
1026
1027//      Passa o a data completa para mensagem.         
1028                $return['udate'] = $header->udate;
1029
1030                $return['msg_day'] = $date_msg;
1031                $return['msg_hour'] = gmdate("H:i",$msgTimesTamp);
1032
1033                if (date("d/m/Y") == $date_msg) //no dia
1034                {
1035                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
1036                        $return['smalldate'] = gmdate("H:i",$msgTimesTamp);
1037                       
1038
1039                                $timestamp_now = strtotime("now");
1040                        //      removido offset nao esta sendo parametrizado
1041                        //      $timestamp_now = strtotime("now") + $offset;
1042                       
1043                       
1044                        $timestamp_msg_time = $msgTimesTamp;
1045                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
1046                        // The variable $timestamp_diff is calculated without MailDate TZ.
1047                        $pdate = date_parse($header->MailDate);
1048                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
1049
1050                        if (gmdate("H",$timestamp_diff) > 0)
1051                        {
1052                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
1053                        }
1054                        else
1055                        {
1056                                if (gmdate("i",$timestamp_diff) == 0){
1057                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
1058                                }
1059                                elseif (gmdate("i",$timestamp_diff) == 1){
1060                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
1061                                }
1062                                else{
1063                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
1064                                }
1065                        }
1066                }
1067                else{
1068                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
1069                        $return['smalldate'] = gmdate("d/m/Y",$msgTimesTamp);
1070                }
1071
1072                $from = $header->from;
1073                $return['from'] = array();
1074                $return['from']['name'] = isset($sender[0]->personal) ? $this->decode_string($from[0]->personal) : '';
1075                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
1076                if ($return['from']['name'])
1077                {
1078                        if (substr($return['from']['name'], 0, 1) == '"')
1079                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
1080                        else
1081                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
1082                }
1083                else
1084                        $return['from']['full'] = $return['from']['email'];
1085
1086                // Sender attribute
1087                $sender = $header->sender;
1088                $return['sender'] = array();
1089                $return['sender']['name'] = isset($sender[0]->personal) ? $this->decode_string($sender[0]->personal): '';
1090                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
1091               
1092                if ($return['sender']['name'])
1093                {
1094                        if (substr($return['sender']['name'], 0, 1) == '"')
1095                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
1096                        else
1097                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
1098                }
1099                else
1100                        $return['sender']['full'] = $return['sender']['email'];
1101
1102                if($return['from']['full'] == $return['sender']['full'])
1103                        $return['sender'] = null;
1104                $to = $header->to;
1105                $return['toaddress2'] = "";
1106                if (!empty($to))
1107                {
1108                        foreach ($to as $tmp)
1109                        {
1110                                if (!empty($tmp->personal))
1111                                {
1112                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
1113                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
1114                                        $return['toaddress2'] .= " ";
1115                                        $return['toaddress2'] .= "&lt;";
1116                                        if ($tmp->host != 'unspecified-domain')
1117                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
1118                                        else
1119                                                $return['toaddress2'] .= $tmp->mailbox;
1120                                        $return['toaddress2'] .= "&gt;";
1121                                        $return['toaddress2'] .= ", ";
1122                                }
1123                                else
1124                                {
1125                                        if ($tmp->host != 'unspecified-domain')
1126                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
1127                                        else
1128                                                $return['toaddress2'] .= $tmp->mailbox;
1129                                        $return['toaddress2'] .= ", ";
1130                                }
1131                        }
1132                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
1133                }
1134                else
1135                {
1136                        $return['toaddress2'] = "";
1137                }       
1138                if(isset($header->cc))
1139                $cc = $header->cc;
1140                $return['cc'] = "";
1141                if (!empty($cc))
1142                {
1143                        foreach ($cc as $tmp_cc)
1144                        {
1145                                if (!empty($tmp_cc->personal))
1146                                {
1147                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
1148                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
1149                                        $return['cc'] .= " ";
1150                                        $return['cc'] .= "&lt;";
1151                                        if ($tmp_cc->host != 'unspecified-domain')
1152                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
1153                                        else
1154                                                $return['cc'] .= $tmp_cc->mailbox;
1155                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
1156                                        $return['cc'] .= "&gt;";
1157                                        $return['cc'] .= ", ";
1158                                }
1159                                else
1160                                {
1161                                        if ($tmp_cc->host != 'unspecified-domain')
1162                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
1163                                        else
1164                                                $return['cc'] .= $tmp_cc->mailbox;
1165                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
1166                                        $return['cc'] .= ", ";
1167                                }
1168                        }
1169                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
1170                }
1171                else
1172                {
1173                        $return['cc'] = "";
1174                }
1175
1176                ##
1177                # @AUTHOR Rodrigo Souza dos Santos
1178                # @DATE 2008/09/12
1179                # @BRIEF Adding the BCC field.
1180                ##
1181        if(isset($header->bcc)){       
1182                $bcc = $header->bcc;
1183                }
1184                $return['bcc'] = "";
1185                if (!empty($bcc))
1186                {
1187                        foreach ($bcc as $tmp_bcc)
1188                        {
1189                                if (!empty($tmp_bcc->personal))
1190                                {
1191                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
1192                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
1193                                        $return['bcc'] .= " ";
1194                                        $return['bcc'] .= "&lt;";
1195                                        if ($tmp_bcc->host != 'unspecified-domain')
1196                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
1197                                        else
1198                                                $return['bcc'] .= $tmp_bcc->mailbox;
1199                                        $return['bcc'] .= "&gt;";
1200                                        $return['bcc'] .= ", ";
1201                                }
1202                                else
1203                                {
1204                                        if ($tmp_bcc->host != 'unspecified-domain')
1205                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
1206                                        else
1207                                                $return['bcc'] .= $tmp_bcc->mailbox;
1208                                        //$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
1209                                        $return['bcc'] .= ", ";
1210                                }
1211                        }
1212                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
1213                }
1214                else
1215                {
1216                        $return['bcc'] = "";
1217                }
1218
1219                $reply_to = $header->reply_to;
1220                $return['reply_to'] = "";
1221                if (is_object($reply_to[0]))
1222                {
1223                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
1224                        {
1225                                if (!empty($reply_to[0]->personal))
1226                                {
1227                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
1228                                        if(!empty($personal_reply_to[0]->text)) {
1229                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
1230                                                $return['reply_to'] .= " ";
1231                                                $return['reply_to'] .= "&lt;";
1232                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1233                                                $return['reply_to'] .= "&gt;";
1234                                        }
1235                                        else {
1236                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1237                                        }
1238                                }
1239                                else
1240                                {
1241                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1242                                }
1243                        }
1244                }
1245                $return['reply_to'] = $this->decode_string($return['reply_to']);
1246                $return['subject'] = $this->decode_string($header->fetchsubject);
1247
1248                if($return['subject'] == $this->functions->getLang("(no subject)   ")){
1249                        $return['subject'] = str_replace(" ","", $return['subject']);
1250                }
1251                if($return['subject'] == '' || $return['subject'] == null){
1252                        $return['subject'] = $this->functions->getLang("(no subject)   ");
1253                }
1254                $return['Size'] = $header->Size;
1255                $return['reply_toaddress'] = $header->reply_toaddress;
1256
1257                //All this is to help in local messages
1258                $return['timestamp'] = $header->udate;
1259                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
1260                $return['reply_toaddress'] = $header->reply_toaddress;
1261               
1262                if(($return['from']['email'] ==  '@unspecified-domain' || $return['sender']['email'] == null) && $return['msg_folder'] == 'INBOX/Drafts'){
1263                        $return['from']['email'] = "Rascunho";
1264                }
1265                if($return['toaddress2'] == 'undisclosed-recipients@, @'){
1266                        $return['toaddress2'] = $this->functions->getLang('without destination');
1267                }
1268                return $return;
1269        }
1270
1271       
1272        /*
1273        * Converte textos utf8 para o padrão html.
1274         * Modificado por Cristiano Corrêa Schmidt
1275         * @link http://php.net/manual/en/function.utf8-decode.php
1276        * @author     luka8088 <luka8088@gmail.com>
1277        */     
1278        function utf8_to_html ($data)
1279        {
1280            return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '$this->_utf8_to_html("\\1")', $data);
1281        }
1282
1283        function _utf8_to_html ($data)
1284                {
1285            $ret = 0;
1286                foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
1287                        $ret += (ord($v) % 128) * pow(64, $k);
1288                    return html_entity_decode("&#$ret;" , ENT_QUOTES);
1289                }
1290        //------------------------------------------------------------------------------//
1291
1292
1293                /**
1294         * Decodifica uma part da mensagem para iso-8859-1
1295         * @param <type> $part parte do email
1296         * @param <type> $encode codificação da parte
1297         * @return <type> string decodificada
1298                */
1299        function decodeMailPart($part, $encode, $html = true)
1300                {
1301            switch (strtolower($encode))
1302                        {
1303                case 'iso-8859-1':
1304                    return $part;
1305                    break;
1306
1307                case 'utf-8':
1308                    if ($html) return  $this->utf8_to_html($part);
1309                    else       return  utf8_decode ($part);
1310                    break;
1311
1312                default:
1313                    return mb_convert_encoding($part, 'iso-8859-1');
1314                                        break;
1315                                }
1316                        }
1317
1318       
1319        function get_body_msg($msg_number, $msg_folder)
1320        {
1321            /*
1322             * Requires of librarys
1323             */
1324            require_once dirname(__FILE__).'/../../library/mime/mimePart.php';
1325            require_once dirname(__FILE__).'/../../library/mime/mimeDecode.php';
1326            require_once dirname(__FILE__).'/class.attachment.inc.php';
1327            //include_once("class.message_components.inc.php");
1328            //--------------------------------------------------------------------//
1329
1330            $return = array();
1331
1332//            $msg = new message_components($this->mbox);
1333//            $msg->fetch_structure($msg_number);
1334
1335            $content = '';
1336
1337            /*
1338            * Chamada original  $this->getRawHeader($msg_number)."\r\n".$this->getRawBody($msg_number);
1339            * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios
1340            */
1341            $rawMessageData = str_replace("\r\n\t", '', $this->getRawHeader($msg_number))."\r\n".$this->getRawBody($msg_number);
1342
1343            $decoder = new Mail_mimeDecode($rawMessageData);
1344
1345            $params['include_bodies'] = true;
1346            $params['decode_bodies']  = true;
1347            $params['decode_headers'] = true;
1348                        if(array_key_exists('nested_messages_are_shown', $_SESSION['phpgw_info']['user']['preferences']['expressoMail']) && ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] == '1'))
1349                                $params['rfc_822bodies']  = true;
1350            $structure = $decoder->decode($params);
1351
1352            /*
1353             * Inicia Gerenciador de Anexos
1354             */
1355            $attachmentManager = new attachment();
1356            $attachmentManager->setStructure($structure);
1357            //----------------------------------------------//
1358
1359            /*
1360             * Monta informações dos anexos para o cabecalhos
1361             */
1362            $attachments = $attachmentManager->getAttachmentsInfo();
1363            $return['attachments'] = $attachments;
1364            //----------------------------------------------//
1365
1366            /*
1367             * Monta informações das imagens
1368             */
1369            $images = $attachmentManager->getEmbeddedImagesInfo();
1370            //----------------------------------------------//
1371
1372                if(!$this->has_cid)
1373                {
1374                    $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
1375               // $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
1376                }
1377
1378            switch (strtolower($structure->ctype_primary))
1379                {
1380                        case 'text':
1381                                        if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
1382                                        {
1383                                $return['body']='isCripted';
1384                                return $return;
1385                        }
1386                        $attachment = array();
1387
1388                        $msg_subtype = strtolower($structure->ctype_secondary);
1389                    if(isset($structure->disposition))
1390                        $disposition = strtolower($structure->disposition);
1391                    else
1392                        $disposition = '';
1393
1394                        if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
1395                        {
1396                                if(strtolower($msg_subtype) == 'plain')
1397                                        {
1398                        if(isset($structure->ctype_parameters['charset']))
1399                                        $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false);
1400                        else
1401                            $content = $this->decodeMailPart($structure->body, null,false);
1402                                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );
1403                                                $content = htmlentities( $content );
1404                                        $this->replace_links($content);
1405                                                $content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content );
1406                                                $content = '<pre>' . $content . '</pre>';
1407                                                $return[ 'body' ] = $content;
1408                                                return $return;
1409                                        }
1410                                                                $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']);
1411                                }
1412                    if(strtolower($structure->ctype_secondary) == 'calendar')
1413                           $content .= $this->builderMsgCalendar($structure->body);
1414
1415                    break;
1416
1417               case 'multipart':
1418                    $this->builderMsgBody($structure , $content);
1419
1420                    break;
1421
1422               case 'message':
1423                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != 1)
1424                    {
1425                    if(!is_array($structure->parts))
1426                                {
1427                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
1428                        $content .= '<pre>'.htmlentities($this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false)).'</pre>';
1429                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
1430                                                }
1431                                            else
1432                        $this->builderMsgBody($structure , $content,true);
1433                    }
1434                    break;
1435
1436            case 'application':
1437                if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
1438                {   
1439                  //  $return['body']='isCripted';
1440                  // return $return;
1441                                 
1442                                  //TODO: Descartar código após atualização do módulo de segurança da SERPRO
1443                                        $rawMessageData2 = $this->extractSignedContents($rawMessageData);
1444                                        if($rawMessageData2 === false){
1445                                                $return['body']='isCripted';
1446                                                return $return;
1447                                        }
1448                                        $decoder2 = new Mail_mimeDecode($rawMessageData2);
1449                            $structure2 = $decoder2->decode($params);
1450                            $this-> builderMsgBody($structure2 , $content); 
1451                 
1452                            $attachmentManager->setStructure($structure2);
1453                            /*
1454                            * Monta informações dos anexos para o cabecarios
1455                            */
1456                            $attachments = $attachmentManager->getAttachmentsInfo();
1457                        $return['attachments'] = $attachments;
1458
1459                            //----------------------------------------------//
1460                 
1461                            /*
1462                        * Monta informações das imagens
1463                            */
1464                            $images = $attachmentManager->getEmbeddedImagesInfo();
1465                            //----------------------------------------------//
1466                 
1467                            if(!$this->has_cid){
1468                                $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
1469                                $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
1470                            }
1471                }
1472                        ///////////////////////////////////////////////////////////////////////////////////////////
1473               default:
1474                    if(count($attachments) > 0)
1475                       $content .= '';
1476                    break;
1477                                                                }
1478
1479                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
1480                $this->set_messages_flag($params);
1481                $content = $this->process_embedded_images($images,$msg_number,$content, $msg_folder);
1482                $content = $this->replace_special_characters($content);
1483                $this->replace_links($content);
1484                $return['body'] = &$content;
1485               
1486                return $return;
1487        }
1488
1489       
1490        //TODO: Descartar código após atualização do módulo de segurança da SERPRO
1491        function extractSignedContents( $data )
1492    {
1493                $pipes_desc = array(
1494                        0 => array('pipe', 'r'),
1495                        1 => array('pipe', 'w')
1496            );
1497         
1498            $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes);
1499            if (!is_resource($fp)) {
1500                        return false;
1501            }
1502         
1503            $output = '';
1504         
1505                /* $pipes[0] => writeable handle connected to child stdin
1506                $pipes[1] => readable handle connected to child stdout */
1507            fwrite($pipes[0], $data);
1508            fclose($pipes[0]);
1509         
1510            while (!feof($pipes[1])) {
1511                        $output .= fgets($pipes[1], 1024);
1512            }
1513            fclose($pipes[1]);
1514            proc_close($fp);
1515         
1516            return $output;
1517        }
1518    ///////////////////////////////////////////////////////////////////////////////////////
1519   
1520        function builderMsgCalendar($calendar)
1521        {
1522            $icalService = ServiceLocator::getService('ical');
1523
1524            $codificao =  mb_detect_encoding($calendar.'x', 'UTF-8, ISO-8859-1');
1525            if($codificao == 'UTF-8')
1526                $calendar = utf8_decode($calendar);
1527
1528            if($icalService->setIcal($calendar))
1529            {
1530                $content = '';
1531
1532                switch ($icalService->getMethod()) {
1533
1534                    case 'REPLY':
1535                          include_once(dirname(__FILE__).'/../../header.inc.php');
1536                          include_once(dirname(__FILE__).'/../../calendar/inc/class.boicalendar.inc.php');
1537                          $boicalendar = new boicalendar();
1538
1539                          $ical = $icalService->getComponent('vevent');
1540                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
1541                          $content.= '<span style="font-size: 12" >';
1542                          $notExist = false;
1543
1544                          foreach ($ical['attendee'] as $attendee)
1545                          {
1546                                if($attendee['params']['PARTSTAT'] == 'ACCEPTED')
1547                                {
1548                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'ACCEPTED',$attendee['params']['CN']))
1549                                    {
1550                                        $content.= $this->functions->getLang('User').' ';
1551                                        if($attendee['params']['CN'])
1552                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1553                                        else
1554                                            $content.= '<b>'.$attendee['value'].'</b> ';
1555
1556                                        $content.= $this->functions->getLang('accepted your event');
1557                                    }
1558                                    else
1559                                        $notExist = true;
1560                                }
1561
1562                                if($attendee['params']['PARTSTAT'] == 'TENTATIVE')
1563                                {
1564                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'TENTATIVE',$attendee['params']['CN']))
1565                                    {
1566                                        $content.= $this->functions->getLang('User').' ';
1567                                        if($attendee['params']['CN'])
1568                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1569                                        else
1570                                            $content.= '<b>'.$attendee['value'].'</b> ';
1571
1572                                        if($ical['description']['value'])
1573                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1574                                        else
1575                                            $content.= $this->functions->getLang('provisionally accepted you event');
1576                                    }
1577                                    else
1578                                         $notExist = true;
1579                                }
1580
1581                                if($attendee['params']['PARTSTAT'] == 'DECLINED')
1582                                {
1583                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'DECLINED',$attendee['params']['CN']))
1584                                    {
1585                                        $content.= $this->functions->getLang('User').' ';
1586                                        if($attendee['params']['CN'])
1587                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1588                                        else
1589                                            $content.= '<b>'.$attendee['value'].'</b> ';
1590
1591                                        if($ical['description']['value'])
1592                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1593                                        else
1594                                            $content.= $this->functions->getLang('provisionally decline you event');
1595                                    }
1596                                    else
1597                                        $notExist = true;
1598                                }
1599                          }
1600                          if($notExist)
1601                            $content.= '<b><span style="color:red">'.$this->functions->getLang('This event does not exist on its agenda').'.</span></b>';
1602                          $content.= '</span><br /><br />';
1603
1604                        break;
1605
1606                      case 'CANCEL':
1607
1608                          $ical = $icalService->getComponent('vevent');
1609                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
1610                          $content.= '<span style="font-size: 12" >';
1611                          $content.= '<b><span style="color:red">'.$this->functions->getLang('Your event has been canceled').'</span></b>';
1612   
1613                          if($ical['description']['value'])
1614                              $content.= ' <br /> <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1615
1616                          $content.= '<br /><b>* '.$this->functions->getLang('To remove the event from your calendar to import the iCal file attached').'.</b>';
1617                          $content.= '</span><br /><br />';
1618                        break;
1619
1620                    case 'REQUEST':
1621
1622                        $ical = $icalService->getComponent('vevent');
1623                        if($ical['dtstart']['value']['tz'] == 'Z')
1624                        {
1625                            $tz = $_SESSION['phpgw_info']['user']['preferences']['common']['tz_offset'];
1626                            $ical['dtstart']['value']['hour'] += $tz;
1627                            $ical['dtend']['value']['hour'] += $tz;
1628                        }
1629                       
1630                        $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br />'.
1631                                   ' <br /> <b>'.$this->functions->getLang('Title').': </b>'.$ical['summary']['value'].
1632                                   ' <br /> <b>'.$this->functions->getLang('Location').': </b>'.$ical['location']['value'].
1633                                   ' <br /> <b>'.$this->functions->getLang('Details').': </b>'. str_replace('\n','<br />',nl2br($ical['description']['value']));
1634                        $content.= ' <br /> <b>'.$this->functions->getLang('Start') . ':  </b>' . $ical['dtstart']['value']['day'] . "/" . $ical['dtstart']['value']['month']  . "/" . $ical['dtstart']['value']['year']  . " - " . $ical['dtstart']['value']['hour']  . ":" . $ical['dtstart']['value']['min'] ;
1635                        $content.= ' <br /> <b>'.$this->functions->getLang('End') . ': </b>' . $ical['dtend']['value']['day'] . "/" . $ical['dtend']['value']['month']  . "/" . $ical['dtend']['value']['year']  . " - " . $ical['dtend']['value']['hour']  . ":" . $ical['dtend']['value']['min'] ;
1636
1637                        if($ical['organizer']['params']['CN'])
1638                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b>'.$ical['organizer']['params']['CN'].' -  <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a></li>' ;
1639                        else
1640                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b> <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a>' ;
1641
1642                        if($ical['attendee'])
1643                        {
1644                            $att = ' <br /> <b>'.$this->functions->getLang('Participants').': </b>';
1645                            $att .= '<ul> ';
1646                            foreach ($ical['attendee'] as $attendee)
1647                            {
1648                                if($attendee['params']['CN'])
1649                                    $att .= '<li>'.$attendee['params']['CN'].' -  <a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
1650                                else
1651                                    $att .= '<li><a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
1652                            }
1653                            $att .= '</ul> <br />'  ;
1654                        }
1655                        $content.= $att;
1656
1657                        break;
1658                    default:
1659                        break;
1660                }
1661     
1662            }
1663            return $content;
1664        }
1665       
1666        function htmlfilter($body)
1667        {
1668                require_once('htmlfilter.inc');
1669
1670                $tag_list = Array(
1671                                false,
1672                                'blink',
1673                                'object',
1674                                'meta',
1675                                'html',
1676                                'link',
1677                                'frame',
1678                                'iframe',
1679                                'layer',
1680                                'ilayer',
1681                                'plaintext'
1682                );
1683
1684                /**
1685                * A very exclusive set:
1686                */
1687                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
1688                $rm_tags_with_content = Array(
1689                                'script',
1690                                'style',
1691                                'applet',
1692                                'embed',
1693                                'head',
1694                                'frameset',
1695                                'xml',
1696                                'xmp'
1697                );
1698
1699                $self_closing_tags =  Array(
1700                                'img',
1701                                'br',
1702                                'hr',
1703                                'input'
1704                );
1705
1706                $force_tag_closing = true;
1707
1708                $rm_attnames = Array(
1709                        '/.*/' =>
1710                                Array(
1711                                        '/target/i',
1712                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
1713                                        '/^dynsrc/i',
1714                                        '/^datasrc/i',
1715                                        '/^data.*/i',
1716                                        '/^lowsrc/i'
1717                                )
1718                );
1719
1720                /**
1721                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
1722                 * some idea of what's going on here. :)
1723                 */
1724
1725                $bad_attvals = Array(
1726                '/.*/' =>
1727                Array(
1728                      '/.*/' =>
1729                              Array(
1730                                Array(
1731                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1732                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1733                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1734                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1735                                      ),
1736                            Array(
1737                                              '\\1oddjob:\\2\\1',
1738                                          //'\\1uucp:\\2\\1', -> doclinks notes
1739                                      '\\1amaretto:\\2\\1',
1740                                          '\\1round:\\2\\1'
1741                                        )
1742                                    ),
1743
1744                          '/^style/i' =>
1745                              Array(
1746                                        Array(
1747                                          '/expression/i',
1748                                              '/behaviou*r/i',
1749                                          '/binding/i',
1750                                              '/include-source/i',
1751                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1752                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1753                                         ),
1754                                        Array(
1755                                          'idiocy',
1756                                              'idiocy',
1757                                          'idiocy',
1758                                              'idiocy',
1759                                          'url(\\1http://securityfocus.com/\\1)',
1760                                          'url(\\1http://securityfocus.com/\\1)'
1761                                         )
1762                                )
1763                          )
1764                    );
1765
1766                $add_attr_to_tag = Array(
1767                                '/^a$/i' => Array('target' => '"_new"')
1768                );
1769
1770
1771                $trusted_body = sanitize($body,
1772                                $tag_list,
1773                                $rm_tags_with_content,
1774                                $self_closing_tags,
1775                                $force_tag_closing,
1776                                $rm_attnames,
1777                                $bad_attvals,
1778                                $add_attr_to_tag
1779                );
1780
1781            return $trusted_body;
1782        }
1783
1784        function decodeBody($body, $encoding, $charset=null)
1785        {
1786
1787                if ($encoding == 'quoted-printable')
1788                {
1789                        $body = quoted_printable_decode($body);
1790
1791                        }
1792        else if ($encoding == 'base64')
1793        {
1794                $body = base64_decode($body);
1795        }
1796                // All other encodings are returned raw.
1797                if (strtolower($charset) == "utf-8")
1798                        return utf8_decode($body);
1799        else
1800                        return $body;
1801        }
1802
1803                               
1804        /**
1805        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1806        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1807        * @param     $images
1808        * @param     $msgno
1809        * @param     $body
1810        * @param     $msg_folder
1811        */                     
1812        function process_embedded_images($images, $msgno, $body, $msg_folder)
1813        {
1814
1815            foreach ($images as $image)
1816                {
1817                $image['cid'] = eregi_replace("<", "", $image['cid']);
1818                $image['cid'] = eregi_replace(">", "", $image['cid']);
1819                               
1820                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\" ", $body);
1821                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
1822                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
1823                        }
1824                return $body;
1825        }
1826
1827        function replace_special_characters($body)
1828        {
1829            // Suspected TAGS!
1830            // $tag_list = Array('blink','object','meta','html','link','frame','iframe','layer','ilayer','plaintext','script','style','img','applet','embed','head','frameset','xml','xmp');
1831            // remove MS Office's proprietary tag
1832            //$body = mb_ereg_replace('<!\-\-\[if [^!]* mso .*\]>.*<!\[endif\]\-\->', '', $body);
1833            // Layout problem: Change html elements
1834            // with absolute position to relate position, CASE INSENSITIVE.
1835            $body = @mb_eregi_replace("POSITION: ABSOLUTE;", "", $body);
1836
1837            //Remove Comentario Expresso
1838            $findExpCom[] = '<!-- TAG <';
1839            $findExpCom[] = '> Removed by ExpressoMail -->';
1840            $body = str_replace($findExpCom, '', $body);
1841            ///--------------------------------//
1842            // tags to be removed doe to security reasons
1843            $tag_list = Array(
1844                'blink', 'object', 'frame', 'iframe',
1845                'layer', 'ilayer', 'plaintext', 'script',
1846                'applet', 'embed', 'frameset', 'xml', 'xmp'
1847            );
1848
1849            foreach ($tag_list as $index => $tag)
1850                $body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body);
1851           
1852
1853            $body = @mb_eregi_replace("<meta[^>]*>", '', $body);
1854            $body = @mb_eregi_replace("<base[^>]*>", '', $body);
1855
1856            //try to wrap CSS code instead of remove STYLE tags
1857            require_once('../library/csstidy/class.csstidy.php');
1858            $css = new csstidy();
1859            $css->set_cfg('preserve_css', false);
1860
1861            $regs_found = array();
1862            $tags_found = preg_match_all("@<style[^>]*>.*?</style[^>]*>@s", $body, $regs_found);
1863            $wrapper_class = 'ExpressoCssWrapper' . time();
1864                       
1865            foreach ($regs_found as $block_found) {
1866                $n_start = strpos($block_found[0], '>') + 1;
1867                $n_length = strrpos($block_found[0], '<') - $n_start;
1868                $bf_innerHTML = substr($block_found[0], $n_start, $n_length);
1869                             
1870                $bf_innerHTML = mb_ereg_replace('<!--', '', $bf_innerHTML);
1871                $bf_innerHTML = mb_ereg_replace('-->', '', $bf_innerHTML);
1872             
1873                $css->parse($bf_innerHTML);
1874
1875                $prefix = ".$wrapper_class ";
1876                if (isset($css->css[41]) && count($css->css[41] > 0))
1877                    foreach ($css->css[41] as $key => $value) {
1878                        //explode multiple selectors per block
1879                        $selectors = explode(',', $key);
1880
1881                        foreach ($selectors as $selector) {
1882                            if (ereg('\*', $key)) {
1883                                //skip selecto '*'
1884                                continue;
1885                            }
1886
1887                            $selector = eregi_replace('[^#\.]*body.*', '', $selector);
1888                            $css->css[41][$prefix . trim($selector)] = $value;
1889                        }
1890                        unset($css->css[41][$key]);
1891                    }
1892                                             
1893                $body = str_replace($block_found, '<style>' . $css->print->plain() . '</style>', $body);
1894        }
1895
1896
1897        // Malicious Code Remove
1898        $dirtyCodePattern = "/(<([\w]+[\w0-9]*)(.*)on(mouse(move|over|down|up)|load|blur|change|error|click|dblclick|focus|key(down|up|press)|select)([\n\ ]*)=([\n\ ]*)[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/misU";
1899        preg_match_all($dirtyCodePattern, $body, $rest, PREG_PATTERN_ORDER);
1900        foreach ($rest[0] as $i => $val) {
1901            if (!(preg_match("/javascript:window\.open\(\"([^'\"]*)\/index\.php\?menuaction=calendar\.uicalendar\.set_action\&cal_id=([^;'\"]+);?['\"]/i", $rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
1902                $body = str_replace($rest[1][$i], "<" . $rest[2][$i] . $rest[3][$i] . $rest[7][$i] . ">", $body);
1903        }
1904
1905        /*
1906         * Remove deslocamento a esquerda colocado pelo Outlook.
1907         * Este delocamento faz com que algumas palavras fiquem escondidas atras da barra lateral do expresso.
1908         */
1909        $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1910        $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1911        $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1912        //--------------------------------------------------------------------------------------------//       
1913        //Remoção de tags <span></span> para correção de erro no firefox
1914        //Comentado pois estes replaces geram erros no html da msg, não se pode garantir que o os </span></span> sejam realmente os fechamentos dos <span><span>.
1915        //Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo.
1916        //              $body = mb_eregi_replace("<span><span>","",$body);
1917        //              $body = mb_eregi_replace("</span></span>","",$body);
1918        //Correção para compatibilização com Outlook, ao visualizar a mensagem
1919        $body = mb_ereg_replace('<!--\[', '<!-- [', $body);
1920        $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1921
1922        return "<div class=\"$wrapper_class\"><span>" . $body . '</span></div>';
1923    }
1924       
1925        function replace_links_callback($matches) 
1926        {
1927            if($matches[3])
1928                    $pref = $matches[3];
1929            else
1930                    $pref = $matches[3] = 'http';
1931
1932            return '<a href="'.$pref.'://'.$matches[4].$matches[5].'" target="_blank">'.$matches[0].'</a>';
1933        }
1934
1935
1936        /**
1937        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1938        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1939        * @param     $body corpo da mensagem
1940        */
1941        function replace_links(&$body)
1942        {
1943                // Trata urls do tipo aaaa.bbb.empresa 
1944                // Usadas na intranet. 
1945                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])(((http|https|ftp|ftps)?:\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';   
1946                $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body);
1947
1948        }
1949
1950        function get_signature($msg, $msg_number, $msg_folder)
1951        {
1952            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1953            include_once("class.db_functions.inc.php");
1954            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1955            {
1956                $sign = array();
1957                $temp = $this->get_info_head_msg($msg_number);
1958                if($temp['ContentType'] =='normal') return $sign;
1959                $file_type = strtolower($file_type);
1960                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1961                {
1962                    if ($temp['ContentType'] == 'signature')
1963                    {
1964                        if(!$this->mbox || !is_resource($this->mbox))
1965                        $this->mbox = $this->open_mbox($msg_folder);
1966
1967                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1968
1969                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1970                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1971
1972                        $certificado = new certificadoB();
1973                        $validade = $certificado->verificar($imap_msg);
1974                                        $sign[] = $certificado->msg_sem_assinatura;
1975                        if ($certificado->apresentado)
1976                        {
1977                            $from = $header->from;
1978                            foreach ($from as $id => $object)
1979                            {
1980                                $fromname = $object->personal;
1981                                $fromaddress = $object->mailbox . "@" . $object->host;
1982                            }
1983                            foreach ($certificado->erros_ssl as $item)
1984                            {
1985                                $sign[] = $item . "#@#";
1986                            }
1987
1988                            if (count($certificado->erros_ssl) < 1)
1989                            {
1990                                $check_msg = 'Message untouched';
1991                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1992                                {
1993                                    $check_msg .= ' and authentic###';
1994                                }
1995                                else
1996                                {
1997                                    $check_msg .= ' with signer different from sender#@#';
1998                                }
1999                                $sign[] = $check_msg;
2000                            }
2001                                               
2002                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
2003                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
2004                            $sign[] = 'Mail from: ###' . $fromaddress;
2005                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
2006                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
2007                            $sign[] = 'Message date: ###' . $header->Date;
2008
2009                            $cert = openssl_x509_parse($certificado->cert_assinante);
2010
2011                            $sign_alert = array();
2012                            $sign_alert[] = 'Certificate Owner###:\n';
2013                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
2014                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
2015                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
2016                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
2017                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
2018                            $sign_alert[] = 'Personal Data###:' . '\n';
2019                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
2020                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
2021                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
2022                            $sign_alert[]= 'Certificate Issuer###:\n';
2023                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
2024                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
2025                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
2026                            $sign_alert[]= 'Validity###:\n';
2027                            $H = data_hora($cert[validFrom]);
2028                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2029                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
2030                            $H = data_hora($cert[validTo]);
2031                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2032                            $sign_alert[]= 'Valid Until### ' . $X;
2033                            $sign[] = $sign_alert;
2034
2035                            $this->db = new db_functions();
2036                           
2037                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
2038                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
2039                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
2040                        }
2041                        else
2042                        {
2043                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
2044                            foreach($certificado->erros_ssl as $item)
2045                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
2046                        }
2047                    }
2048                }
2049            }
2050            return $sign;
2051        }
2052
2053       
2054        /**
2055        * @license   http://www.gnu.org/copyleft/gpl.html GPL
2056        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2057        * @param     $images
2058        * @param     $msg_number
2059        * @param     $msg_folder
2060        */
2061        function get_thumbs($images, $msg_number, $msg_folder)
2062        {
2063
2064                if (!count($images)) return '';
2065               
2066                foreach ($images as $key => $value) {                   
2067                        $images[$key]['width']  = 160;
2068                        $images[$key]['height'] = 120;
2069                        $images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$value['pid']."&image=true";
2070                }
2071
2072                return json_encode($images);
2073        }
2074
2075        /*function delete_msg($params)
2076        {
2077                $folder = $params['folder'];
2078                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
2079
2080                $mbox_stream = $this->open_mbox($folder);
2081
2082                foreach ($msgs_to_delete as $msg_number){
2083                        imap_delete($mbox_stream, $msg_number, FT_UID);
2084                }
2085                imap_close($mbox_stream, CL_EXPUNGE);
2086                return $params['msgs_to_delete'];
2087        }*/
2088
2089        // Novo
2090        function delete_msgs($params)
2091        {
2092
2093                $folder = $params['folder'];
2094                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
2095                $msgs_number = explode(",",$params['msgs_number']);
2096                if(array_key_exists('border_ID' ,$params))
2097                $border_ID = $params['border_ID'];
2098                else
2099                        $border_ID = '';
2100                $return = array();
2101
2102                if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){
2103                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2104                        // Fix problem in unserialize function JS.
2105                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2106                }
2107
2108                //$mbox_stream = $this->open_mbox($folder);
2109                $mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
2110
2111                foreach ($msgs_number as $msg_number)
2112                {
2113                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
2114                                $return['msgs_number'][] = $msg_number;
2115                }
2116
2117                $return['folder'] = $folder;
2118                $return['border_ID'] = $border_ID;
2119
2120                if($mbox_stream)
2121                        imap_close($mbox_stream, CL_EXPUNGE);
2122                       
2123                $return['status'] = true;
2124                return $return;
2125        }
2126
2127
2128        function refresh($params)
2129        {
2130
2131                $return = array();
2132                $return['new_msgs'] = 0;
2133                $folder = $params['folder'];
2134                $msg_range_begin = $params['msg_range_begin'];
2135                $msg_range_end = $params['msg_range_end'];
2136                $msgs_existent = $params['msgs_existent'];
2137                $sort_box_type = $params['sort_box_type'];
2138                $sort_box_reverse = $params['sort_box_reverse'];
2139                $msgs_in_the_server = array();
2140                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2141                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2142                $msgs_in_the_server = array_keys($msgs_in_the_server);
2143
2144                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
2145
2146                $dif = ($params['msg_range_end'] - $params['msg_range_begin']) +1;
2147                if(!count($msgs_in_the_server)){
2148                        $msg_range_begin -= $dif;
2149                        $msg_range_end -= $dif;
2150                        $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2151                        $msgs_in_the_server = array_keys($msgs_in_the_server); 
2152                        $num_msgs = NULL;
2153                        $return['msg_range_begin'] = $msg_range_begin;
2154                        $return['msg_range_end'] = $msg_range_end;
2155                }               
2156                $return['new_msgs'] = imap_num_recent($this->mbox);
2157               
2158                $msgs_in_the_client = explode(",", $msgs_existent);
2159
2160                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
2161
2162                if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){
2163                        $aux = 0;
2164                        while(array_key_exists($aux, $msg_to_insert)){
2165                                if($msg_to_insert[$aux] > $msgs_in_the_client[0]){
2166                                        $return['new_msgs'] += 1;
2167                                }
2168                                $aux++;
2169                        }
2170                }else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){
2171                        $aux = 0;
2172                        while(array_key_exists($aux, $msg_to_insert)){
2173                                if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){
2174                                        $return['new_msgs'] += 1;
2175                                }
2176                                $aux++;
2177                        }
2178                }else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0 && $msg_range_end == $dif){
2179                        $return['tot_msgs'] = $num_msgs;
2180                }
2181               
2182                if(!count($msgs_in_the_server)){
2183                        return Array();
2184                }       
2185
2186                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
2187                $msgs_to_exec = array();
2188                foreach($msg_to_insert as $msg_number)
2189                        $msgs_to_exec[] = $msg_number;
2190                //sort($msgs_to_exec);
2191                $i = 0;
2192                foreach($msgs_to_exec as $msg_number)
2193                {
2194                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
2195                        * atributos do cabeçalho. Como eu preciso do atributo Importance
2196                        * para saber se o email é importante ou não, uso abaixo a função
2197                        * imap_fetchheader e busco o atributo importance nela para passar
2198                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
2199                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
2200                        * não preciso reimplementar o método utilizando o fetchheader.
2201                        */
2202   
2203                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
2204                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
2205                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
2206
2207                        $msg_sample = $this->get_msg_sample($msg_number);
2208                        $return[$i]['msg_sample'] = $msg_sample;
2209
2210                        $header = $this->get_header($msg_number);
2211                        if (!is_object($header))
2212                                continue;
2213
2214                        $return[$i]['msg_number']       = $msg_number;
2215                       
2216                        //get the next msg number to append this msg in the view in a correct place
2217                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
2218                       
2219                        $return[$i]['msg_key_position'] = $msg_key_position;
2220                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1,$msgs_in_the_server) !== false)
2221                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
2222                        else
2223                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position];
2224
2225                        $return[$i]['msg_folder']       = $folder;
2226                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
2227                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
2228                        $return[$i]['Recent']           = $header->Recent;
2229                        $return[$i]['Unseen']           = $header->Unseen;
2230                        $return[$i]['Answered']         = $header->Answered;
2231                        $return[$i]['Deleted']          = $header->Deleted;
2232                        $return[$i]['Draft']            = $header->Draft;
2233                        $return[$i]['Flagged']          = $header->Flagged;
2234
2235                        $return[$i]['udate'] = $header->udate;
2236               
2237                        $from = $header->from;
2238                        $return[$i]['from'] = array();
2239                        $tmp = imap_mime_header_decode($from[0]->personal);
2240                        $return[$i]['from']['name'] = $tmp[0]->text;
2241                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
2242                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
2243                        if(!$return[$i]['from']['name'] || trim($return[$i]['from']['name']) === '')
2244                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
2245
2246                        /*$toaddress = imap_mime_header_decode($header->toaddress);
2247                        $return[$i]['toaddress'] = '';
2248                        foreach ($toaddress as $tmp)
2249                                $return[$i]['toaddress'] .= $tmp->text;*/
2250                        $to = $header->to;
2251                        $return[$i]['to'] = array();
2252                        if(isset($to[0]->personal))
2253                        $tmp = imap_mime_header_decode($to[0]->personal);
2254                        if(trim($return[$i]['to']['name']) === '')
2255                                $return[$i]['to']['name'] = $to[0]->mailbox . "@" . $to[0]->host;
2256                        else
2257                        $return[$i]['to']['name'] = $tmp[0]->text;
2258                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2259                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
2260                        if(isset($header->cc))
2261                        $cc = $header->cc;
2262
2263                        if ( isset($cc) && (!$return[$i]['to']['name'] || $return[$i]['to']['name'] == '@') ){
2264                                $return[$i]['to']['name'] =  $cc[0]->personal;
2265                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
2266                        }
2267                        $return[$i]['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
2268                        if($return[$i]['subject'] == "" || $return[$i]['subject'] == '' || $return[$i]['subject'] == null ){
2269                                $return[$i]['subject'] = $this->functions->getLang("(no subject)   ");
2270                        }
2271                        $return[$i]['Size'] = $header->Size;
2272                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
2273
2274                        if($return[$i]['to']['email'] == '@' || $return[$i]['to']['email'] =='undisclosed-recipients@' || $return[$i]['to']['name'] =='undisclosed-recipients@'
2275                                || $return[$i]['to']['name'] == null){
2276                                $return[$i]['to']['email'] = $return[$i]['from']['email'];
2277                                $return[$i]['to']['name'] = $return[$i]['from']['name'];
2278                                $return[$i]['to']['full'] = $return[$i]['reply_toaddress'];
2279                        }
2280                       
2281                        $return[$i]['attachment'] = array();
2282                        if (!isset($imap_attachment))
2283                        {
2284                                include_once("class.imap_attachment.inc.php");
2285                                $imap_attachment = new imap_attachment();
2286                        }
2287                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
2288                        $i++;
2289                }
2290                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
2291                $return['sort_box_type'] = $params['sort_box_type'];
2292                if(!$this->mbox || !is_resource($this->mbox))
2293                {
2294                    $this->open_mbox($folder);
2295                }
2296
2297                $return['msgs_to_delete'] = $msg_to_delete;
2298                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
2299                if($this->mbox && is_resource($this->mbox))
2300                        imap_close($this->mbox);
2301
2302                return $return;
2303        }
2304
2305     /**
2306     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
2307     * assinado ou cifrado.
2308     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
2309     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
2310     * @param $msg_number O número da mesagem
2311     * @return Retorna o tipo da mensagem (normal, signature, cipher).
2312     */
2313    function getMessageType($msg_number, $headers = false){
2314            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2315            $contentType = "normal";
2316            if (!$headers){
2317                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
2318            }
2319           
2320            if (preg_match("/pkcs7-signature/i", $headers) == 1){
2321                $contentType = "signature";
2322            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
2323                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
2324            }
2325
2326            return $contentType;
2327    }
2328   
2329                /**
2330        * Retorna a posição que a pasta esta dentro do array de pastas
2331        *
2332        * @license    www.gnu.org/copyleft/gpl.html GPL
2333        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2334        * @sponsor    Caixa Econômica Federal
2335        * @author     Cristiano Corrêa Schmidt
2336        * @access     public
2337                */
2338               
2339        function getFolderPos(&$array , $find)
2340        {           
2341                foreach($array as $i => $v)
2342                        if($v['id'] === $find)
2343                                return $i;
2344                return false;
2345        }
2346       
2347        /**
2348        * Ordenas as pastas padrões do usuario na ordem INBOX > SENT > DRAFTS > SPAM > TRASH > OTHERS
2349        *
2350        * @license    http://www.gnu.org/copyleft/gpl.html GPL
2351        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2352        * @sponsor    Caixa Econômica Federal
2353        * @author     Cristiano Corrêa Schmidt
2354        * @access     public
2355        */
2356        function orderDefaultFolders( &$folders , $user)
2357        {
2358                $principals = array();
2359                for($x = 0; $x < 5 ; $x++)
2360                {
2361                        switch ($x) {
2362                                case 0:                             
2363                                        if( ($p = $this->getFolderPos($folders , $user )) || $p === 0 )
2364                                                $principals[] = $folders[$p];
2365                                        break;
2366                                case 1:
2367                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['drafts'])) )) || $p === 0 )
2368                                                $principals[] = $folders[$p];
2369                                        break;
2370                                case 2:
2371                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['sent'])) )) || $p === 0 )
2372                                                $principals[] = $folders[$p];
2373                                        break;
2374                                case 3:
2375                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['spam'])) )) || $p === 0 )
2376                                                $principals[] = $folders[$p];
2377                                        break;
2378                                case 4:
2379                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['trash'])) )) || $p === 0  )
2380                                                $principals[] = $folders[$p];                                           
2381                                        break;
2382                        }
2383                        if($p !== false)
2384                                unset($folders[$p]);
2385                }
2386                $folders = array_merge($principals, $folders);
2387        }
2388       
2389        /**
2390        * Retorna lista de pastas do usuario no padrão que a lib javascript espera.
2391        *
2392        * @license    http://www.gnu.org/copyleft/gpl.html GPL
2393        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2394        * @sponsor    Caixa Econômica Federal
2395        * @author     Cristiano Corrêa Schmidt
2396        * @access     public
2397        */
2398        function get_folders_list($params = null)
2399        {
2400                ///Define Variaveis
2401                $prefixShared = 'user'; //Prefixo das pastas compartilhadas
2402                $uid2cn = (isset($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'])) ? $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] : false;
2403                $mboxStream = $this->open_mbox(); //abre conexão imap
2404                $currentFolder = isset($params['folder']) ? $params['folder'] : 'INBOX';
2405                $folders = array();
2406                $return = array();
2407                ///////////////////////////////////////////////////////////////
2408                   
2409                if( isset($params['onload']) && $_SESSION['phpgw_info']['expressomail']['server']['certificado'])
2410                        $this->delete_mailbox(array('del_past' => 'INBOX'.$this->imap_delimiter.'decifradas')); //Deleta Pasta decifradas
2411               
2412                session_write_close(); // Free others requests
2413                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2414               
2415                if ( isset($params['noSharedFolders']) )
2416                        $folders_list = array_merge(imap_getmailboxes($mboxStream, $serverString, 'INBOX' ), imap_getmailboxes($mboxStream, $serverString, 'INBOX/*' ) );
2417                else
2418                        $folders_list = imap_getmailboxes($mboxStream, $serverString, '*' );
2419
2420                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
2421
2422                if (!is_array($folders_list)) return false;
2423                        if($uid2cn)
2424                                $this->ldap = new ldap_functions();
2425               
2426                foreach ($folders_list as $i => $v ) //Separando Pastas e informações
2427                {
2428                        $folderId = substr($v->name,(strpos($v->name , '}') + 1));
2429                        $nameArray = explode($this->imap_delimiter, $folderId);
2430                        $nameCount = count($nameArray);
2431                        $decifrada = mb_convert_encoding('INBOX'.$this->imap_delimiter.'decifradas','UTF7-IMAP','ISO-8859-1'); //Ignorar esta pasta decifrada
2432                        $parent = ($nameCount > 1 && $nameArray[($nameCount - 2)] !== 'INBOX') ? implode($this->imap_delimiter, array_slice($nameArray, 0, ($nameCount - 1))): ''; //Pega folder pai
2433                        if($nameArray[0] === 'user')
2434                                $folders[$prefixShared.$this->imap_delimiter.$nameArray[1]][] = array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes , 'name' => $nameArray[($nameCount-1)] , 'user' => $nameArray[1] ,'parent' => $parent);
2435                        else if( $folderId !== $decifrada) //Escapa pasta decifrada
2436                                $folders['INBOX'][] =  array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes ,'name' => $nameArray[($nameCount-1)] , 'parent' => $parent);
2437                }
2438                unset($folders_list); //destroy array de objetos desnecessarios
2439                foreach($folders as $i => $v) //Ordenando e resgatando novas informações
2440                {
2441                        $this->orderDefaultFolders($folders[$i] , $i);  //Ordenando Pastas Padrões
2442                       
2443                        foreach ($folders[$i] as $ii => $vv)
2444                        {
2445                                $append = array();                             
2446                                $append['folder_id'] = mb_convert_encoding($vv['id'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA ID DAS PASTAS COM ACENTOS
2447                                $append['folder_name'] = (($uid2cn && isset($vv['user'])) && ($cn = $this->ldap->uid2cn($vv['user']))) ? $cn : $vv['name'];
2448                                $append['folder_name'] = mb_convert_encoding($append['folder_name'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA NOME DAS PASTAS COM ACENTOS
2449                                $status = imap_status($mboxStream, $vv['stream'], SA_UNSEEN); //Resgata Numero de mensagens não lidas
2450                                $append['folder_unseen'] = isset($status->unseen) ? $status->unseen : 0 ;
2451                                $append['folder_hasChildren'] = (($vv['attributes'] == 32) && ($vv['name'] != 'INBOX')) ? 1 : 0;
2452                                $append['folder_parent'] = mb_convert_encoding($vv['parent'],'ISO-8859-1','UTF7-IMAP');
2453                                $return[] = $append;
2454                        }
2455                }
2456               
2457                $quotaInfo =  (!isset($params['noQuotaInfo'])) ? $this->get_quota( array('folder_id' => $currentFolder)) : false; //VERIFICA SE O USUARIO TEM COTA
2458
2459                return ( ( is_array($quotaInfo) ) ?  array_merge($return, $quotaInfo) : $return );       
2460        }
2461   
2462
2463        function create_mailbox($arr)
2464        {
2465                $namebox        = $arr['newp'];
2466                $mbox_stream = $this->open_mbox();
2467                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2468                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
2469
2470                $result = "Ok";
2471                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
2472                {
2473                        $result = implode("<br />\n", imap_errors());
2474                }
2475
2476                if($mbox_stream)
2477                        imap_close($mbox_stream);
2478
2479                return $result;
2480
2481        }
2482
2483        function create_extra_mailbox($arr)
2484        {
2485                $nameboxs = explode(";",$arr['nw_folders']);
2486                $result = "";
2487                $mbox_stream = $this->open_mbox();
2488                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2489                foreach($nameboxs as $key=>$tmp){
2490                        if($tmp != ""){
2491                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
2492                                        $result = implode("<br />\n", imap_errors());
2493                                        if($mbox_stream)
2494                                                imap_close($mbox_stream);
2495                                        return $result;
2496                                }
2497                        }
2498                }
2499                if($mbox_stream)
2500                        imap_close($mbox_stream);
2501                return true;
2502        }
2503
2504        function delete_mailbox($arr)
2505        {
2506                $namebox = $arr['del_past'];
2507                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2508                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
2509                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
2510
2511                $result = "Ok";
2512                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2513                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2514                {
2515                        $result = implode("<br />\n", imap_errors());
2516                }
2517                /*
2518                if($mbox_stream)
2519                        imap_close($mbox_stream);
2520                */
2521                return $result;
2522        }
2523
2524        function ren_mailbox($arr)
2525        {
2526                $namebox = $arr['current'];
2527                $new_box = $arr['rename'];
2528                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2529                $mbox_stream = $this->open_mbox();
2530                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
2531
2532                $result = "Ok";
2533                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2534                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
2535
2536                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2537                {
2538                        $result = imap_errors();
2539                }
2540                if($mbox_stream)
2541                        imap_close($mbox_stream);
2542                return $result;
2543
2544        }
2545
2546        function get_num_msgs($params)
2547        {
2548                $folder = $params['folder'];
2549                if(!$this->mbox || !is_resource($this->mbox)) {
2550                        $this->mbox = $this->open_mbox($folder);
2551                        if(!$this->mbox || !is_resource($this->mbox))
2552                        return imap_last_error();
2553                }
2554                $num_msgs = imap_num_msg($this->mbox);
2555                if($this->mbox && is_resource($this->mbox))
2556                        imap_close($this->mbox);
2557
2558                return $num_msgs;
2559        }
2560
2561        function folder_exists($folder){
2562                $mbox =  $this->open_mbox();
2563                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2564                $list = imap_getmailboxes($mbox,$serverString, $folder);
2565                $return = is_array($list);             
2566                imap_close($mbox);
2567                return $return;
2568        }
2569       
2570        function send_mail($params)
2571        {
2572                require_once dirname(__FILE__) . '/../../API/class.servicelocator.php';
2573                $mailService = ServiceLocator::getService('mail');
2574
2575                include_once("class.db_functions.inc.php");
2576                $db = new db_functions();
2577                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
2578                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
2579               
2580                ##
2581                # @AUTHOR Rodrigo Souza dos Santos
2582                # @DATE 2008/09/17$fileName
2583                # @BRIEF Checks if the user has permission to send an email with the email address used.
2584                ##
2585                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2586                {
2587                        $deny = true;
2588                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2589                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2590                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2591
2592                        if ( $deny )
2593                                return "The server denied your request to send a mail, you cannot use this mail address.";
2594                }           
2595
2596                $toaddress = $db->getAddrs(explode(',',$params['input_to']));//implode(',',);
2597                $ccaddress = $db->getAddrs(explode(',',$params['input_cc']));//implode(',',);
2598                $ccoaddress = $db->getAddrs(explode(',',$params['input_cco']));//implode(',',);
2599
2600                if($toaddress["False"] || $ccaddress["False"] || $ccoaddress["False"]){
2601                        return $this->parse_error("Invalid Mail:", ($toaddress["False"] ? $toaddress["False"] : ($ccaddress["False"] ? $ccaddress["False"] : $ccoaddress["False"])));
2602                }
2603               
2604                $toaddress = implode(',', $toaddress);
2605                $ccaddress = implode(',', $ccaddress);
2606                $ccoaddress = implode(',', $ccoaddress);
2607               
2608                if($toaddress == "" && $ccaddress == "" && $ccoaddress == ""){
2609                        return $this->parse_error("Invalid Mail:", ($params['input_to'] ? $params['input_to'] :($params['input_cc'] ? $params['input_cc'] : $params['input_cco'])) );
2610                }
2611
2612                $toaddress  = preg_replace('/<\s+/', '<', $toaddress);                 
2613                $toaddress  = preg_replace('/\s+>/', '>', $toaddress);
2614                       
2615                $ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
2616                $ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
2617               
2618                $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
2619                $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
2620               
2621                $replytoaddress = $params['input_replyto'];
2622                $subject = $params['input_subject'];
2623                $msg_uid = $params['msg_id'];
2624                $return_receipt = $params['input_return_receipt'];
2625                $is_important = $params['input_important_message'];
2626        $encrypt = $params['input_return_cripto'];
2627                $signed = $params['input_return_digital'];
2628
2629                $message_attachments = $params['message_attachments'];
2630                 
2631                if(substr($params['input_to'],-1) == ',')
2632                    $params['input_to'] = substr($params['input_to'],0,-1);
2633
2634                if(substr($params['input_cc'],-1) == ',')
2635                    $params['input_cc'] = substr($params['input_cc'],0,-1);
2636
2637                if(substr($params['input_cco'],-1) == ',')
2638                    $params['input_cco'] = substr($params['input_cco'],0,-1);
2639
2640                // Valida numero Maximo de Destinatarios
2641                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0)
2642                {
2643                    $sendersNumber = count(explode(',',$params['input_to']));
2644
2645                    if($params['input_cc'])
2646                        $sendersNumber +=  count(explode(',',$params['input_cc']));
2647                    if($params['input_cco'])
2648                        $sendersNumber +=  count(explode(',',$params['input_cco']));
2649
2650                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username);
2651                    if($userMaxmimumSenders)
2652                    {
2653                        if($sendersNumber > $userMaxmimumSenders)
2654                            return $this->functions->getLang('Number of recipients greater than allowed');
2655                    }
2656                    else
2657                    {
2658                        $ldap = new ldap_functions();
2659                        $groupsToUser = $ldap->get_user_groups($this->username);
2660
2661                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser);
2662
2663                        if($groupMaxmimumSenders > 0)
2664                        {
2665                            if($sendersNumber > $groupMaxmimumSenders)
2666                                return $this->functions->getLang('Number of recipients greater than allowed');
2667                        }
2668                        else
2669                        {
2670                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'])
2671                             return $this->functions->getLang('Number of recipients greater than allowed');
2672                        }
2673                    }
2674
2675                }
2676                //Fim Valida numero maximo de destinatarios
2677               
2678               
2679                //Valida envio de email para shared accounts
2680                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
2681                {
2682                    $ldap = new ldap_functions();
2683                    $arrayF = explode(';', $params['input_from']);
2684
2685                    /*
2686                     * Verifica se o remetente n?o ? uma conta compartilhada
2687                     */
2688                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
2689                    {
2690                        $groupsToUser = $ldap->get_user_groups($this->username);
2691                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
2692
2693                        /*
2694                         * Pega o UID do remetente
2695                         */
2696                        $uidFrom = $ldap->mail2uid($arrayF[1]);
2697
2698                         /*
2699                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
2700                         */
2701                        foreach ($sharedAccounts as $key => $value)
2702                        {
2703                            if($value)
2704                                 $acl = $this->getaclfrombox($value);
2705
2706                             if (array_key_exists($uidFrom, $acl))
2707                                 unset($sharedAccounts[$key]);
2708
2709                        }
2710
2711                        /*
2712                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
2713                         */
2714                        if(count($sharedAccounts) > 0)
2715                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
2716
2717                        /*
2718                         * Retorna as contas compartilhadas bloqueadas
2719                         */
2720                        if(count($accountsBlockeds) > 0)
2721                        {
2722                            $return = '';
2723
2724                            foreach ($accountsBlockeds as $accountBlocked)
2725                                $return.= $accountBlocked.', ';
2726
2727                             $return = substr($return,0,-2);
2728
2729                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
2730                        }
2731                    }
2732                }
2733                // Fim Valida envio de email para shared accounts
2734               
2735               
2736//          TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
2737            if($params['smime'] AND false)
2738        {
2739            $body = $params['smime'];
2740            $mail->SMIME = true;
2741            // A MSG assinada deve ser testada neste ponto.
2742            // Testar o certificado e a integridade da msg....
2743            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2744            $erros_acumulados = '';
2745            $certificado = new certificadoB();
2746            $validade = $certificado->verificar($body);
2747            if(!$validade)
2748            {
2749                foreach($certificado->erros_ssl as $linha_erro)
2750                {
2751                    $erros_acumulados .= $linha_erro;
2752                }
2753            }
2754            else
2755            {
2756                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2757                if ($certificado->apresentado)
2758                {
2759                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
2760                    $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'])&&$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']!=''?$_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']]:$this->username;
2761                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
2762                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2763                }
2764                else
2765                {
2766                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2767                }
2768            }
2769            if(!$erros_acumulados =='')
2770            {
2771                return $erros_acumulados;
2772            }
2773        }
2774        else
2775        {
2776            //Compatibilização com Outlook, ao encaminhar a mensagem
2777                        $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
2778        }
2779
2780                $attachments = $_FILES;
2781                $forwarding_attachments = $params['forwarding_attachments'];
2782                $local_attachments = $params['local_attachments'];
2783
2784                //Test if must be saved in shared folder and change if necessary
2785                if( $fromaddress[2] == 'y' ){
2786                        //build shared folder path
2787                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2788                        if($this->folder_exists($newfolder))
2789                                $folder = $newfolder;
2790                        else
2791                                $folder = $params['folder'];
2792                       
2793                } else  {
2794                        $folder = $params['folder'];                   
2795                }
2796               
2797                $folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
2798                $folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
2799                $folder_name = $params['folder_name'];
2800
2801//              TODO - tratar assinatura e remover o AND false
2802                if($signed && !$params['smime'] AND false)
2803                {
2804            $mail->Mailer = "smime";
2805                        $mail->SignedBody = true;
2806                }
2807
2808
2809                if($fromaddress)
2810                        $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
2811               else
2812                        $mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
2813                //$mailService->addTo($toaddress);
2814                //$mailService->addCc($ccaddress);
2815                $bol = $this->add_recipients('to', $toaddress, $mailService);
2816                if(!$bol){
2817                        return $this->parse_error("Invalid Mail:", $toaddress);
2818                }
2819                $bol = $this->add_recipients('cc', $ccaddress, $mailService);
2820                if(!$bol){
2821                        return $this->parse_error("Invalid Mail:", $ccaddress);
2822                }
2823                $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy'];
2824                 
2825                if($allow)
2826                                {
2827                        //$mailService->addBcc($ccoaddress);
2828                        $bol = $this->add_recipients('cco', $ccoaddress, $mailService);
2829
2830                        if(!$bol){
2831                                return $this->parse_error("Invalid Mail:", $ccoaddress);
2832                        }
2833                                }
2834
2835                $mailService->setSubject($subject);
2836                $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ?
2837                                                strtolower($params['type']) != 'plain' : true );
2838       
2839
2840//              TODO - tratar mensagem criptografada e remover o AND false abaixo
2841        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)      // a msg deve ser enviada cifrada...
2842                {
2843                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2844            $email = explode(",",$email);
2845            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2846            // Deve ser verificado um numero limite de destinatarios.
2847            // Deve ser verificado se os certificados sao validos.
2848            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2849            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2850            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2851            $erros_acumulados = "";
2852            $aux_mails = array();
2853            $mail_list = array();
2854            if(count($email) > $numero_maximo)
2855            {
2856                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2857                return $erros_acumulados;
2858            }
2859            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2860            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2861            foreach($email as $item)
2862            {
2863                $certificate = $db->get_certificate(strtolower($item));
2864                if(!$certificate)
2865                {
2866                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2867                    return $erros_acumulados;
2868                }
2869
2870                if (array_key_exists("dberr1", $certificate))
2871                {
2872
2873                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2874                    return $erros_acumulados;
2875                                }
2876                if (array_key_exists("dberr2", $certificate))
2877                {
2878                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2879                    //continue;
2880                }
2881                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2882                if (!array_key_exists("certs", $certificate))
2883                {
2884                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2885                    continue;
2886                }
2887            */
2888                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2889
2890                foreach ($certificate['certs'] as $registro)
2891                {
2892                    $c1 = new certificadoB();
2893                    $c1->certificado($registro['chave_publica']);
2894                    if ($c1->apresentado)
2895                    {
2896                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2897                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2898                        {
2899                            $aux_mails[] = $registro['chave_publica'];
2900                            $mail_list[] = strtolower($item);
2901                        }
2902                        else
2903                        {
2904                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2905                            {
2906                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2907                                    $c1->dados['EXPIRADO'],$c2->revogado);
2908                            }
2909
2910                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2911                            foreach($c2->erros_ssl as $linha)
2912                            {
2913                                $erros_acumulados .=  $linha . chr(0x0A);
2914                            }
2915                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2916                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2917                        }
2918                    }
2919                    else
2920                    {
2921                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2922                    }
2923                }
2924                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2925                                {
2926                                        return $erros_acumulados;
2927                        }
2928            }
2929
2930            $mail->Certs_crypt = $aux_mails;
2931        }
2932                                               
2933                if( count($forwarding_attachments) > 0 )// Build CID images
2934                        $this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body);
2935
2936                //      Build Uploading Attachments!!!
2937                if (count($attachments)>0) //Caso seja forward normal...
2938                {
2939                        $total_uploaded_size = 0;
2940                        foreach ($attachments as $attach)
2941                        {
2942                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2943                                    return $this->parse_error("message file too big");
2944                                if($attach['name']=='Unknown')
2945                                        continue;
2946                                $mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
2947                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2948                        }
2949                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
2950                        {
2951         
2952                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2953                            if( $total_uploaded_size > $upload_max_filesize)
2954                                return $this->parse_error("message file too big");
2955                        }
2956                }
2957                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2958
2959                        $total_uploaded_size = 0;
2960                       
2961                        foreach($local_attachments as $local_attachment) {
2962                                $file_description = unserialize(rawurldecode($local_attachment));
2963                                $tmp = array_values($file_description);
2964                                foreach($file_description as $i => $descriptor){
2965                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2966                                }
2967                                $mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
2968                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2969                        }
2970                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
2971                        {
2972                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2973                            if( $total_uploaded_size > $upload_max_filesize)
2974                                   return $this->parse_error("message file too big");
2975                        }
2976                }
2977
2978                //      Build Forwarding Attachments!!!
2979                if (count($forwarding_attachments) > 0)
2980                {
2981                        // Bug fixed for array_search function
2982                        $name_cid_files = array();
2983                        if(count($name_cid_files) > 0) {
2984                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2985                                $name_cid_files[0] = null;
2986                        }
2987
2988                        foreach($forwarding_attachments as $forwarding_attachment)
2989                        {
2990                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2991                               
2992                                foreach($file_description as $i => $item)
2993                                        $file_description[$i] = urldecode($item);
2994                               
2995                                $tmp = array_values($file_description);
2996                                foreach($file_description as $i => $descriptor){
2997                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2998                                }
2999                                $file_description = $tmp;
3000                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
3001                                $fileName = $file_description[2];
3002                                if(!array_search(trim($fileName),$name_cid_files)) {
3003                                        $filename_dec = html_entity_decode(rawurldecode($fileName));
3004                                        $mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
3005
3006                                }
3007                        }
3008                }
3009               
3010                //Build Message Attachments!!!
3011                if(count($message_attachments) > 0 )
3012                {
3013                        foreach($message_attachments as $folder_name => $messages)
3014                        {
3015                                foreach ($messages as $message_number => $message_subject)
3016                                {
3017                                        if (!$message_subject)
3018                                                $message_subject  = 'no title.eml';
3019                                        else
3020                                                $message_subject .= '.eml';
3021                                       
3022                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3023                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3024                                        else{
3025                                                $mbox_stream = $this->open_mbox($folder_name);
3026                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
3027                                        }
3028                                                       
3029                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3030                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
3031                                }
3032                        }
3033                }
3034               
3035                $message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
3036                $message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
3037               
3038                ////////////////////////////////////////////////////////////////////////////////////////////////////   
3039                /**
3040                * Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão.
3041                 */
3042                $default_max_size_rule = $db->get_default_max_size_rule();     
3043                if(!$default_max_size_rule)
3044                {
3045                        $default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */
3046                }
3047                else
3048                {
3049                        foreach($default_max_size_rule as $i=>$value)
3050                        {               
3051                                $default_max_size_rule = $value['config_value'];
3052                        }                               
3053                }
3054               
3055                $default_max_size_rule = $default_max_size_rule * 1024 * 1024;            /* Tamanho da regra padrão, em bytes */
3056                $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];   
3057               
3058               
3059                $ldap = new ldap_functions();
3060                $groups_user = $ldap->get_user_groups($id_user);
3061
3062                $size_rule_by_group = array(); 
3063                foreach($groups_user as $k=>$value_)
3064                {       
3065                        $rule_in_group = $db->get_rule_by_user_in_groups($k);
3066                        if ($rule_in_group != "")
3067                                array_push($size_rule_by_group, $rule_in_group);
3068                }       
3069               
3070                $n_rule_groups = 0;
3071                $maior_valor_regra_grupo = 0;
3072                foreach($size_rule_by_group as $i=>$value)
3073                {
3074                        if(is_array($value[0]))
3075                        {
3076                                $n_rule_groups++;
3077                                if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
3078                                        $maior_valor_regra_grupo = $value[0]['email_max_recipient'];
3079                        }
3080                }
3081               
3082                if($default_max_size_rule)
3083                {
3084                        $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
3085
3086                        if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */
3087                        {
3088                                if($message_size_total > $default_max_size_rule)
3089                                        return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
3090                        }
3091
3092                        else
3093                        {
3094                                if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
3095                                {
3096                                        $regra_mais_permissiva = 0;
3097                                        foreach($size_rule as $i=>$value)
3098                                        {       
3099                                                if($regra_mais_permissiva < $value['email_max_recipient'])
3100                                                        $regra_mais_permissiva = $value['email_max_recipient'];
3101                                        }
3102                                        $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;                 
3103                                        if($message_size_total > $regra_mais_permissiva)
3104                                                return $this->functions->getLang("Message size greater than allowed (Rule By User)");
3105                                }
3106                                else /* Regra por grupo */
3107                                {               
3108                                        $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;                     
3109                                        if($message_size_total > $maior_valor_regra_grupo)
3110                                                return $this->functions->getLang("Message size greater than allowed (Rule By Group)"); 
3111                               
3112                               
3113                                }
3114                        }
3115                }
3116                /**
3117         * Fim da validação do tamanho da regra do tamanho de mensagem.
3118                 */
3119                 ////////////////////////////////////////////////////////////////////////////////////////////////////
3120               
3121               
3122               
3123               
3124               
3125                if($isHTML)
3126                        $mailService->setBodyHtml($body);
3127                else
3128                        $mailService->setBodyText($body);
3129
3130                if($is_important)
3131                        $mailService->addHeaderField('Importance','High');
3132
3133                if($return_receipt)
3134                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
3135
3136
3137                if ($folder != 'null'){
3138                        $mbox_stream = $this->open_mbox($folder);
3139                        @imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
3140                }
3141
3142                $sent = $mailService->send();
3143
3144                if($sent !== true)
3145                {
3146                        return $this->parse_error($sent);
3147                }
3148                else
3149                {
3150            if ($signed && !$params['smime'])
3151                        {
3152                                return $sent;
3153                        }
3154                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
3155                        {
3156                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3157                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
3158                                $now = date("d/m/y H:i:s");
3159                                $addrs = $toaddress.$ccaddress.$ccoaddress;
3160                                $sent = trim($sent);
3161                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
3162                        }
3163                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
3164                                $contacts = new dynamic_contacts();
3165                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
3166                                return array("success" => true, "new_contacts" => $new_contacts);
3167                        }
3168                        return array("success" => true);
3169                }
3170        }
3171       
3172       
3173        /**
3174        * @license   http://www.gnu.org/copyleft/gpl.html GPL
3175        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
3176        * @param     $mail email
3177        * @param     $msg_uid uid da mensagem
3178        * @param     $forwarding_attachments anexos
3179        */
3180
3181        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
3182        {
3183                //Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
3184                $pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';
3185                $cid_imgs = '';
3186                preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
3187                //-------------------------------------------------------------------//
3188
3189                $attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
3190
3191                foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
3192                        $desc = unserialize(rawurldecode($v));
3193                        $attPostions[$desc[3]] = $i;
3194                }
3195
3196                //Intera as imagens encontradas
3197                foreach($cid_imgs[6] as $j => $val)
3198        {               
3199                        $cid = base_convert(microtime().$j, 10, 36); //Gera um cid
3200                        $body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'"', $body ); //tira o src da imagem e coloca o cid.
3201                        $count    = strlen($cid_imgs[6][$j]);
3202                                       
3203                        $attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
3204                        $file_description = unserialize(rawurldecode($attach_img));
3205                       
3206                        if (is_array($file_description))
3207                                foreach($file_description as $i => $descriptor)                         
3208                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);
3209
3210                        // The image is not in the same mail?
3211                        if ($msg_uid != $cid_imgs[4][$j])
3212                        {
3213                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
3214                $fileContent = &$fa['binary'];
3215                                $fileName = $fa['name'];
3216                                $fileCode = $fa['encoding'];
3217                                $fileType =  $fa['type'];
3218                                $file_attached[0] = $cid_imgs[2][$j];
3219                                $file_attached[1] = $cid_imgs[4][$j];
3220                                $file_attached[2] = $fileName;
3221                                $file_attached[3] = '0.'.(string)($j+1);
3222                                $file_attached[4] = 'base64';
3223                                $file_attached[5] = strlen($fileContent); //Size of file
3224                                $file_attached[6] = $cid_imgs[6][$j];
3225                                $return_forward[] = $file_attached;
3226
3227                                if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
3228                                        unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
3229                               
3230                        }
3231                        else
3232                        {
3233                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
3234                                $fileName = $file_description[2];
3235                                $fileCode = $file_description[4];
3236                                $file_description[3] = '0.'.(string)($j+1);
3237                                $file_description[6] = $cid_imgs[6][$j];
3238                                $fileType = $this->get_file_type($file_description[2]);
3239                                unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
3240                                if (!empty($file_description))
3241                                {
3242                                        $file_description[5] = strlen($fileContent); //Size of file
3243                                        $return_forward[] = $file_description;
3244                                }
3245                        }
3246
3247                        if ($fileContent)
3248                                $mail->addStringImage($fileContent,$fileType,$fileName, $cid);                                 
3249                }
3250
3251                return $return_forward;
3252        }
3253        function add_recipients_cert($full_address)
3254        {
3255                $result = "";
3256                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
3257                foreach ($parse_address as $val)
3258                {
3259                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3260                        if ($val->mailbox == "INVALID_ADDRESS")
3261                                continue;
3262                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
3263                                continue;
3264                        if (empty($val->personal))
3265                                $result .= $val->mailbox."@".$val->host . ",";
3266                        else
3267                                $result .= $val->mailbox."@".$val->host . ",";
3268                }
3269
3270                return substr($result,0,-1);
3271        }
3272
3273        function add_recipients($recipient_type, $full_address, $mail, $mobile = false)
3274        {
3275                //remove a comma if is given two unexpected commas
3276                $full_address = preg_replace("/, ?,/",",",$full_address);
3277                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
3278
3279                $bolean = true;         
3280                foreach ($parse_address as $val)
3281                {
3282                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3283                        if ($val->mailbox == "INVALID_ADDRESS")
3284                                continue;
3285                        switch($recipient_type)
3286                        {
3287                                case "to":
3288                                        if($mobile){
3289                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
3290                                        }else{
3291                                                $mail->AddTo( ($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3292                                        }
3293                                        break;
3294                                case "cc":
3295                                        if($mobile){
3296                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
3297                                        }else{
3298                                                $mail->AddCC( ($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3299                                        }
3300                                        break;
3301                                case "cco":
3302                                        $mail->AddBcc(($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3303                                        break;
3304                        }
3305                        if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){
3306                                $bolean = false;
3307                        }
3308                }
3309                return $bolean;
3310        }
3311
3312        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
3313        {
3314            include_once dirname(__FILE__).'/class.attachment.inc.php';
3315            $attachment = new attachment();
3316                        $attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo.
3317            $attachment->setStructureFromMail($msg_folder, $msg_number);
3318            return $attachment->getAttachment($msg_part);
3319        }
3320
3321        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding)
3322        {
3323            include_once dirname(__FILE__).'/class.attachment.inc.php';
3324            $attachment = new attachment();
3325            $attachment->setStructureFromMail($msg_folder, $msg_number);
3326            $return = $attachment->getAttachmentInfo($msg_part);
3327            $return['binary'] = $attachment->getAttachment($msg_part);
3328            return $return;
3329        }
3330
3331        function del_last_caracter($string)
3332        {
3333                $string = substr($string,0,(strlen($string) - 1));
3334                return $string;
3335        }
3336
3337        function del_last_two_caracters($string)
3338        {
3339                $string = substr($string,0,(strlen($string) - 2));
3340                return $string;
3341        }
3342
3343        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
3344        {
3345                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
3346                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
3347                        foreach($imapsort as $iuid)
3348                                $sort[$iuid] = "";
3349                       
3350                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
3351                                $slice_array = false;
3352                        else
3353                                $slice_array = true;
3354                }
3355                else
3356                {
3357                        $sort = array();
3358                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
3359                        $num_msgs = imap_num_msg($this->mbox);
3360                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
3361                        $slice_array = true;
3362
3363                        for ($i=$num_msgs; $i>0; $i--)
3364                        {
3365                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
3366                                        break;
3367                                $iuid = @imap_uid($this->mbox,$i);
3368                                $header = $this->get_header($iuid);
3369                                // List UNSEEN messages.
3370                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
3371                                        continue;
3372                                }
3373                                // List SEEN messages.
3374                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
3375                                        continue;
3376                                }
3377                                // List ANSWERED messages.
3378                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
3379                                        continue;
3380                                }
3381                                // List FLAGGED messages.
3382                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
3383                                        continue;
3384                                }
3385
3386                                if($sort_box_type=='SORTFROM') {
3387                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
3388                                                $from = $header->to;
3389                                        else
3390                                                $from = $header->from;
3391                                        if(isset($from[0]->personal))
3392                                        $tmp = imap_mime_header_decode($from[0]->personal);
3393                                        else
3394                                                $tmp = null;
3395                                        if (isset($tmp[0]->text))
3396                                                $sort[$iuid] = $tmp[0]->text;
3397                                        else
3398                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
3399                                }
3400                                else if($sort_box_type=='SORTSUBJECT') {
3401                                        $sort[$iuid] = $header->subject;
3402                                }
3403                                else if($sort_box_type=='SORTSIZE') {
3404                                        $sort[$iuid] = $header->Size;
3405                                }
3406                                else {
3407                                        $sort[$iuid] = $header->udate;
3408                                }
3409
3410                        }
3411                        natcasesort($sort);
3412
3413                        if ($sort_box_reverse)
3414                                $sort = array_reverse($sort,true);
3415                }
3416                if(empty($sort) or !is_array($sort)){
3417                        $sort = array();
3418                }
3419               
3420                       
3421
3422
3423                if ($slice_array)
3424                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
3425
3426
3427                return $sort;
3428
3429        }
3430
3431        function move_delete_search_messages($params){
3432                $move = false;
3433                $msg_no_move = "";
3434       
3435                $params['selected_messages'] = urldecode($params['selected_messages_move']);
3436                $params['new_folder'] = urldecode($params['new_folder_move']);
3437                $params['new_folder_name'] = urldecode($params['new_folder_name_move']);
3438                $sel_msgs = explode(",", $params['selected_messages']);
3439                @reset($sel_msgs);
3440                $sorted_msgs = array();
3441                foreach($sel_msgs as $idx => $sel_msg) {
3442                        $sel_msg = explode(";", $sel_msg);
3443                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3444                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3445                         }
3446                         else {
3447                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3448                         }
3449                }               
3450                @ksort($sorted_msgs);
3451                $last_return = false;
3452                foreach($sorted_msgs as $folder => $msgs_number) {
3453                        $params['msgs_number'] = $msgs_number;
3454                        $params['folder'] = $folder;
3455                               
3456                        $last_return = $this->move_messages($params);
3457                       
3458                        if($last_return['status']){
3459                                $move = true;
3460                        }else{
3461                                $msg_no_move =  $params['msgs_number'];
3462                        }
3463                }
3464                $sel_msgs = null;               
3465                $params['selected_messages'] = urldecode($params['selected_messages_delete']);
3466                $params['new_folder'] = urldecode($params['new_folder_delete']);
3467                $params['new_folder_name'] = urldecode($params['new_folder_name_delete']);
3468                $sel_msgs = explode(",", $params['selected_messages']);
3469                @reset($sel_msgs);
3470                $sorted_msgs = array();
3471                foreach($sel_msgs as $idx => $sel_msg) {
3472                        $sel_msg = explode(";", $sel_msg);
3473                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3474                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3475                         }
3476                         else {
3477                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3478                         }
3479                }
3480                @ksort($sorted_msgs);
3481                $last_return = false;
3482                foreach($sorted_msgs as $folder => $msgs_number) {
3483                        $params['msgs_number'] = $msgs_number;
3484                        $params['folder'] = $folder;
3485               
3486                        $params['folder'] = $params['new_folder_delete'];
3487                        $last_return = $this->delete_msgs($params);
3488                        $last_return['deleted'] = true;
3489                        if($last_return['status']){
3490                                $move = true;
3491                        }else{
3492                                $msg_no_move =  $params['msgs_number'];
3493                        }
3494               
3495                }
3496       
3497                if($move)
3498                        $last_return['move'] = true;
3499                       
3500                if($msg_no_move != "")
3501                        $last_return['no_move'] = $msg_no_move;
3502               
3503                return $last_return;
3504        }
3505
3506        function move_search_messages($params){
3507                $params['selected_messages'] = str_replace('/',$this->imap_delimiter,urldecode($params['selected_messages']));
3508                $params['new_folder'] = str_replace('/',$this->imap_delimiter,urldecode($params['new_folder']));
3509                $params['new_folder_name'] = urldecode($params['new_folder_name']);
3510                $sel_msgs = explode(",", $params['selected_messages']);
3511                $move = false;
3512                $msg_no_move = "";
3513               
3514                @reset($sel_msgs);
3515                $sorted_msgs = array();
3516                foreach($sel_msgs as $idx => $sel_msg) {
3517                        $sel_msg = explode(";", $sel_msg);
3518                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3519                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3520                         }
3521                         else {
3522                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3523                         }
3524                }
3525                @ksort($sorted_msgs);
3526                $last_return = false;
3527                foreach($sorted_msgs as $folder => $msgs_number) {
3528                        $params['msgs_number'] = $msgs_number;
3529                        $params['folder'] = $folder;
3530                       
3531                if($params['delete'] === 'true'){
3532                        $params['folder'] = $params['new_folder'];
3533                        $last_return = $this->delete_msgs($params);
3534                                $last_return['deleted'] = true;
3535                       
3536                        if($last_return['status']){
3537                                $move = true;
3538                        }else{
3539                                $msg_no_move =  $params['msgs_number'];
3540                        }
3541                       
3542                }else{
3543                                $last_return = $this->move_messages($params);
3544                               
3545                                if($last_return['status']){
3546                                        $move = true;
3547                                }else{
3548                                        $msg_no_move =  $params['msgs_number'];
3549                        }
3550                }
3551                }
3552               
3553                if($move)
3554                        $last_return['move'] = true;
3555                       
3556                if($msg_no_move != "")
3557                        $last_return['no_move'] = $msg_no_move;
3558                       
3559                return $last_return;
3560        }
3561
3562        function move_messages($params)
3563        {
3564                $folder = $params['folder'];
3565                $mbox_stream = $this->open_mbox($folder);
3566                $newmailbox = ($params['new_folder']);
3567                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO-8859-1, UTF-8, UTF7-IMAP");
3568                $new_folder_name = $params['new_folder_name'];
3569                $msgs_number = $params['msgs_number'];
3570                $return = array('msgs_number' => $msgs_number,
3571                                                'folder' => $folder,
3572                                                'new_folder_name' => $new_folder_name,
3573                                                'border_ID' => $params['border_ID'],
3574                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
3575
3576                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
3577        if (substr($folder,0,4) == 'user'){
3578                $acl = $this->getacltouser($folder);
3579                /*
3580                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
3581                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
3582                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
3583                 *   w - write (STORE flags other than SEEN and DELETED)
3584                 *   i - insert (perform APPEND, COPY into mailbox)
3585                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
3586                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
3587                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
3588                 *   a - administer (perform SETACL)
3589                        */
3590                        if (strpos($acl, "d") === false){
3591                                $return['status'] = false;
3592                                return $return;
3593                        }
3594        }
3595        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
3596        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){
3597        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
3598            if (substr($new_folder_name,0,4) == 'user'){
3599                $this->ldap = new ldap_functions();
3600                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
3601                $return['new_folder_name'] = array_pop($tmp_folder_name);
3602                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
3603                {
3604                    $return['new_folder_name'] = $cn;
3605                }
3606            }
3607        }
3608                }
3609
3610                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
3611                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
3612                {
3613                        $return['previous_msg'] = $this->get_info_previous_msg($params);
3614                        // Fix problem in unserialize function JS.
3615                        if(array_key_exists('body', $return['previous_msg']))
3616                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
3617                }
3618
3619                $mbox_stream = $this->open_mbox($folder);
3620                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3621                        imap_expunge($mbox_stream);
3622                        if($mbox_stream)
3623                                imap_close($mbox_stream);
3624                        return $return;
3625                }else {
3626                        if(strstr(imap_last_error(),'Over quota')) {
3627                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
3628                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
3629                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3630                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3631                                $mbox           = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
3632                                if(!$mbox)
3633                                        return imap_last_error();
3634                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
3635                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
3636                                        if($mbox_stream)
3637                                                imap_close($mbox_stream);
3638                                        if($mbox)
3639                                                imap_close($mbox);
3640                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
3641                                }
3642                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3643                                        imap_expunge($mbox_stream);
3644                                        if($mbox_stream)
3645                                                imap_close($mbox_stream);
3646                                        // return to original quota limit.
3647                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
3648                                                if($mbox)
3649                                                        imap_close($mbox);
3650                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
3651                                        }
3652                                        return $return;
3653                                }
3654                                else {
3655                                        if($mbox_stream)
3656                                                imap_close($mbox_stream);
3657                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
3658                                                if($mbox)
3659                                                        imap_close($mbox);
3660                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
3661                                        }
3662                                        return imap_last_error();
3663                                }
3664
3665                        }
3666                        else {
3667                                if($mbox_stream)
3668                                        imap_close($mbox_stream);
3669                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
3670                        }
3671                }
3672        }
3673
3674
3675        function save_msg($params)
3676        {
3677       
3678                require_once dirname(__FILE__) . '/../../API/class.servicelocator.php';
3679                $mailService = ServiceLocator::getService('mail');
3680
3681                $return_receipt = $params['input_return_receipt'];
3682                $is_important = $params['input_important_message'];
3683               
3684                $msg_uid = $params['msg_id'];
3685                $body = $params['body'];
3686                $body = str_replace("%nbsp;","&nbsp;",$body);
3687                $body = preg_replace("/\n/"," ",$body);
3688                $body = preg_replace("/\r/","" ,$body);
3689                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
3690                $forwarding_attachments = $params['forwarding_attachments'];
3691                $message_attachments    = $params['message_attachments'];
3692                $attachments = $params['FILES'];
3693                $return_files = $params['FILES'];
3694                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
3695
3696                if(is_array($params['local_attachments'])){
3697                    foreach ($params['local_attachments'] as $key => $local_attach) {
3698                       $tmp = unserialize(urldecode($local_attach));
3699                           $attachments[$key]['name'] = urldecode($tmp[2]);
3700                           $return_files[$key]['name'] = urldecode($tmp[2]);
3701                    }
3702                }
3703
3704                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
3705                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
3706
3707                $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
3708                $mailService->addTo($params['input_to']);
3709                $mailService->addCc( $params['input_cc']);
3710                $mailService->addBcc($params['input_cco']);
3711                $mailService->setSubject($params['input_subject']);
3712
3713                if($is_important){
3714                        $mailService->addHeaderField('Importance','High');
3715                }
3716
3717                if($return_receipt)
3718                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
3719
3720                $isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
3721
3722               
3723                if( count($forwarding_attachments) > 0 )
3724                        $return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
3725                       
3726                //Build Message Attachments!!!
3727                if(count($message_attachments) > 0 )
3728                {
3729                        foreach($message_attachments as $folder_name => $messages)
3730                        {
3731                                foreach ($messages as $message_number => $message_subject)
3732                                {
3733                                        if (!$message_subject)
3734                                                $message_subject  = 'no title.eml';
3735                                        else
3736                                                $message_subject .= '.eml';
3737                                       
3738                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3739                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3740                                        else{
3741                                                $mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
3742                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
3743                                        }
3744                                                                                       
3745                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3746                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
3747                                }
3748                        }
3749                }
3750               
3751                $imagesParts = array();
3752
3753                if(count($return_forward) > 0 )
3754                foreach ($return_forward as $value)
3755                        $imagesParts[$value[6]] = $value[3];   
3756
3757                //Build Forwarding Attachments!!!
3758                if(count($forwarding_attachments) > 0 )
3759                {
3760                        foreach($forwarding_attachments as $forwarding_attachment)
3761                        {
3762
3763                                $file_description = unserialize(rawurldecode($forwarding_attachment));
3764                                foreach($file_description as $i => $item)
3765                                        $file_description[$i] = urldecode($item);                               
3766                       
3767                                $file_description = array_values($file_description);
3768                                       
3769                                foreach($file_description as $i => $descriptor)
3770                                                        $file_description[$i] = eregi_replace('\'*\'','',$descriptor);
3771                               
3772                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
3773                                $file_description[2] = html_entity_decode($file_description[2]);
3774
3775                                $file_description[5] = strlen($fileContent); //Size of file
3776                                $return_forward[] = $file_description;
3777                                $mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
3778                        }
3779                        }
3780
3781                if ((count($return_forward) > 0) && (count($return_files) > 0))
3782                        $return_files = array_merge_recursive($return_forward,$return_files);
3783                else if (count($return_files) < 1)
3784                                $return_files = $return_forward;
3785
3786                //Build Uploading Attachments!!!
3787                $sizeof_attachments = count($attachments);     
3788                if ($sizeof_attachments)
3789                        foreach ($attachments as $numb => $attach)
3790                                $mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
3791
3792
3793                if (!$body)
3794                        $body = ' ';
3795               
3796                if($isHTML)
3797                        $mailService->setBodyHtml($body);
3798                else
3799                        $mailService->setBodyText($body);
3800
3801
3802                $mbox_stream = $this->open_mbox($folder);
3803                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
3804
3805                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3806                $return['msg_no'] = $status->uidnext - 1;
3807                $return['folder_id'] = $folder;
3808                $return['imagesParts'] = $imagesParts;
3809
3810                if($mbox_stream)
3811                        imap_close($mbox_stream);
3812                       
3813                $returnFiles = array();                 
3814                $ii = 0;
3815                               
3816                if(count($return_files) > 0)
3817                {
3818                        foreach ($return_files as $index => $_attachment)
3819                        {
3820                                if (array_key_exists("name", $_attachment))
3821                                {
3822                                        $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment['name'], 'UTF-8', 'UTF-8, ISO-8859-1') );
3823                                        $returnFiles[$ii]['size'] = $_attachment['size'];
3824                                        $ii++;
3825                        }
3826                                else if($_attachment[2])
3827                        {
3828                                        $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment[2], 'UTF-8', 'UTF-8, ISO-8859-1'));
3829                                        $returnFiles[$ii]['size'] = $_attachment[5];         
3830                                        $ii++;
3831                        }
3832                }
3833                }
3834                $return['files'] = serialize($returnFiles);
3835                $return["subject"] = $params['input_subject'];
3836                if (!$return['append']) $return['append'] = imap_last_error();
3837                       
3838                return $return;
3839        }
3840
3841       
3842        function set_messages_flag_from_search($params){               
3843                $error = False;
3844                $fileNames = "";
3845               
3846                $sel_msgs = explode(",", $params['msg_to_flag']);
3847                @reset($sel_msgs);
3848                $sorted_msgs = array();
3849                foreach($sel_msgs as $idx => $sel_msg) {
3850                        $sel_msg = explode(";", $sel_msg);
3851                        if(array_key_exists($sel_msg[0], $sorted_msgs)){
3852                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3853                        }
3854                        else {
3855                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3856                        }
3857                }
3858                unset($sorted_msgs['']);                       
3859                $array_names_keys = array_keys($sorted_msgs);   
3860                // Verifica se as n mensagens selecionadas
3861                // se encontram em um mesmo folder
3862                if (count($sorted_msgs)==1){
3863                        $param['folder'] = $array_names_keys[0];
3864                        $param['msgs_to_set'] = $sorted_msgs[$array_names_keys[0]];
3865                        $param['flag'] = $params['flag'];
3866                        $returns[0] = $this->set_messages_flag($param);
3867                        return $returns;
3868                }else{
3869                        for($i = 0; $i < count($array_names_keys); $i++){
3870                                $param['folder'] = $array_names_keys[$i];
3871                                $param['msgs_to_set'] = $sorted_msgs[$array_names_keys[$i]];
3872                                $param['flag'] = $params['flag'];
3873                                $returns[$i] = $this->set_messages_flag($param);
3874                }
3875        }
3876        return $returns;
3877}
3878        function set_messages_flag($params)
3879        {               
3880                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
3881                $msgs_to_set = $params['msgs_to_set'];
3882                $flag = $params['flag'];
3883                $return = array();
3884                $return["msgs_to_set"] = $msgs_to_set;
3885                $return["flag"] = $flag;
3886                $return["msgs_not_to_set"] = "";
3887                       
3888                $this->mbox = $this->open_mbox($folder);
3889                       
3890                if ($flag == "unseen"){
3891                        $return["msgs_to_set"] = "";
3892                        $msgs = explode(",",$msgs_to_set);
3893                        foreach($msgs as $men){
3894                                if (imap_clearflag_full($this->mbox, $men, "\\Seen", ST_UID))
3895                                        $return["msgs_to_set"] .= $men.",";
3896                                else
3897                                        $return["msgs_not_to_set"] .= $men.",";
3898                        }
3899                        $return["status"] = true;
3900                }elseif ($flag == "seen"){
3901                        $return["msgs_to_set"] = "";
3902                        $msgs = explode(",",$msgs_to_set);
3903                        foreach($msgs as $men){
3904                                if (imap_setflag_full($this->mbox, $men, "\\Seen", ST_UID))
3905                                        $return["msgs_to_set"] .= $men.",";
3906                                else
3907                                        $return["msgs_not_to_set"] .= $men.",";
3908                        }
3909                        $return["status"] = true;
3910                }elseif ($flag == "answered"){
3911                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
3912                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
3913                }
3914                elseif ($flag == "forwarded")
3915                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
3916                elseif ($flag == "flagged")
3917                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
3918                elseif ($flag == "unflagged") {
3919                        $flag_importance = false;
3920                        $msgs_number = explode(",",$msgs_to_set);
3921                        $unflagged_msgs = "";
3922                        foreach($msgs_number as $msg_number) {
3923                                preg_match('/importance *: *(.*)\r/i',
3924                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3925                                        ,$importance);
3926                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3927                                        $flag_importance=true;
3928                                }
3929                                else {
3930                                        $unflagged_msgs.=$msg_number.",";
3931                                }
3932                        }
3933
3934                        if($unflagged_msgs!="") {
3935                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
3936                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
3937                        }
3938                        else {
3939                                $return["msgs_unflageds"] = false;
3940                        }
3941
3942                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3943                                $return["status"] = false;
3944                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
3945                        }
3946                        else {
3947                                $return["status"] = true;
3948                        }
3949                }
3950               
3951                if(($flag == "seen") || ($flag == "unseen")){
3952                        if ($return["msgs_not_to_set"] != ""){
3953                                $return["msgs_not_to_set"] = substr($return["msgs_not_to_set"], 0, -1);
3954                                $return["status"] = false;
3955                        }
3956                        if($return["msgs_to_set"] != ""){
3957                                $return["msgs_to_set"] = substr($return["msgs_to_set"], 0, -1);
3958                        }
3959                }
3960                if($this->mbox && is_resource($this->mbox))
3961                        imap_close($this->mbox);               
3962                return $return;
3963        }
3964
3965        function get_file_type($file_name)
3966        {
3967                $file_name = strtolower($file_name);
3968                $strFileType = strrev(substr(strrev($file_name),0,4));
3969                if ($strFileType == ".eml")
3970                        return "message/rfc822";
3971                if ($strFileType == ".asf")
3972                        return "video/x-ms-asf";
3973                if ($strFileType == ".avi")
3974                        return "video/avi";
3975                if ($strFileType == ".doc")
3976                        return "application/msword";
3977                if ($strFileType == ".zip")
3978                        return "application/zip";
3979                if ($strFileType == ".xls")
3980                        return "application/vnd.ms-excel";
3981                if ($strFileType == ".gif")
3982                        return "image/gif";
3983                if ($strFileType == ".jpg" || $strFileType == "jpeg")
3984                        return "image/jpeg";
3985                if ($strFileType == ".png")
3986                        return "image/png";
3987                if ($strFileType == ".wav")
3988                        return "audio/wav";
3989                if ($strFileType == ".mp3")
3990                        return "audio/mpeg3";
3991                if ($strFileType == ".mpg" || $strFileType == "mpeg")
3992                        return "video/mpeg";
3993                if ($strFileType == ".rtf")
3994                        return "application/rtf";
3995                if ($strFileType == ".htm" || $strFileType == "html")
3996                        return "text/html";
3997                if ($strFileType == ".xml")
3998                        return "text/xml";
3999                if ($strFileType == ".xsl")
4000                        return "text/xsl";
4001                if ($strFileType == ".css")
4002                        return "text/css";
4003                if ($strFileType == ".php")
4004                        return "text/php";
4005                if ($strFileType == ".asp")
4006                        return "text/asp";
4007                if ($strFileType == ".pdf")
4008                        return "application/pdf";
4009                if ($strFileType == ".txt")
4010                        return "text/plain";
4011                if ($strFileType == ".wmv")
4012                        return "video/x-ms-wmv";
4013                if ($strFileType == ".sxc")
4014                        return "application/vnd.sun.xml.calc";
4015                if ($strFileType == ".stc")
4016                        return "application/vnd.sun.xml.calc.template";
4017                if ($strFileType == ".sxd")
4018                        return "application/vnd.sun.xml.draw";
4019                if ($strFileType == ".std")
4020                        return "application/vnd.sun.xml.draw.template";
4021                if ($strFileType == ".sxi")
4022                        return "application/vnd.sun.xml.impress";
4023                if ($strFileType == ".sti")
4024                        return "application/vnd.sun.xml.impress.template";
4025                if ($strFileType == ".sxm")
4026                        return "application/vnd.sun.xml.math";
4027                if ($strFileType == ".sxw")
4028                        return "application/vnd.sun.xml.writer";
4029                if ($strFileType == ".sxq")
4030                        return "application/vnd.sun.xml.writer.global";
4031                if ($strFileType == ".stw")
4032                        return "application/vnd.sun.xml.writer.template";
4033
4034
4035                return "application/octet-stream";
4036        }
4037
4038        function htmlspecialchars_encode($str)
4039        {
4040                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
4041        }
4042        function htmlspecialchars_decode($str)
4043        {
4044                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
4045        }
4046
4047        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
4048        {
4049                if(!$this->mbox || !is_resource($this->mbox))
4050                        $this->mbox = $this->open_mbox($folder);
4051
4052                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
4053        }
4054
4055        function get_info_next_msg($params)
4056        {
4057                $msg_number = $params['msg_number'];
4058                $folder = $params['msg_folder'];
4059                $sort_box_type = $params['sort_box_type'];
4060                $sort_box_reverse = $params['sort_box_reverse'];
4061                $reuse_border = $params['reuse_border'];
4062                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
4063                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
4064
4065                $success = false;
4066                if (is_array($sort_array_msg))
4067                {
4068                        foreach ($sort_array_msg as $i => $value){
4069                                if ($value == $msg_number)
4070                                {
4071                                        $success = true;
4072                                        break;
4073                                }
4074                        }
4075                }
4076
4077                if (! $success || $i >= sizeof($sort_array_msg)-1)
4078                {
4079                        $params['status'] = 'false';
4080                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4081                        return $params;
4082                }
4083
4084                $params = array();
4085                $params['msg_number'] = $sort_array_msg[($i+1)];
4086                $params['msg_folder'] = $folder;
4087
4088                $return = $this->get_info_msg($params);
4089                $return["reuse_border"] = $reuse_border;
4090                return $return;
4091        }
4092
4093        function get_info_previous_msg($params)
4094        {
4095                $msg_number = $params['msgs_number'];
4096                $folder = $params['folder'];
4097                $sort_box_type = $params['sort_box_type'];
4098                $sort_box_reverse = $params['sort_box_reverse'];
4099                $reuse_border = $params['reuse_border'];
4100                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
4101                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
4102
4103                $success = false;
4104                if (is_array($sort_array_msg))
4105                {
4106                        foreach ($sort_array_msg as $i => $value){
4107                                if ($value == $msg_number)
4108                                {
4109                                        $success = true;
4110                                        break;
4111                                }
4112                        }
4113                }
4114                if (! $success || $i == 0)
4115                {
4116                        $params['status'] = 'false';
4117                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4118                        return $params;
4119                }
4120
4121                $params = array();
4122                $params['msg_number'] = $sort_array_msg[($i-1)];
4123                $params['msg_folder'] = $folder;
4124
4125                $return = $this->get_info_msg($params);
4126                $return["reuse_border"] = $reuse_border;
4127                return $return;
4128        }
4129
4130        // This function updates the values: quota, paging and new messages menu.
4131        function get_menu_values($params){
4132                $return_array = array();
4133                $return_array = $this->get_quota($params);
4134
4135                $mbox_stream = $this->open_mbox($params['folder']);
4136                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
4137                if($mbox_stream)
4138                        imap_close($mbox_stream);
4139
4140                return $return_array;
4141        }
4142
4143        function get_quota($params){
4144                // folder_id = user/{uid} for shared folders
4145                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
4146                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
4147                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
4148                }
4149                // folder_id = INBOX for inbox folders
4150                else
4151                        $folder_id = "INBOX";
4152
4153                if(!$this->mbox || !is_resource($this->mbox))
4154                        $this->mbox = $this->open_mbox();
4155
4156                $quota = imap_get_quotaroot($this->mbox, $folder_id);
4157                if($this->mbox && is_resource($this->mbox))
4158                        imap_close($this->mbox);
4159
4160                if (!$quota){
4161                        return array(
4162                                'quota_percent' => 0,
4163                                'quota_used' => 0,
4164                                'quota_limit' =>  0
4165                        );
4166                }
4167
4168                if(count($quota) && $quota['limit']) {
4169                        $quota_limit = $quota['limit'];
4170                        $quota_used  = $quota['usage'];
4171                        if($quota_used >= $quota_limit)
4172                        {
4173                                $quotaPercent = 100;
4174                        }
4175                        else
4176                        {
4177                        $quotaPercent = ($quota_used / $quota_limit)*100;
4178                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
4179                        }
4180                        return array(
4181                                'quota_percent' => floor($quotaPercent),
4182                                'quota_used' => $quota_used,
4183                                'quota_limit' =>  $quota_limit
4184                        );
4185                }
4186                else
4187                        return array();
4188        }
4189
4190        function send_notification($params){
4191                include("../header.inc.php");
4192                require_once("class.phpmailer.php");
4193                $mail = new PHPMailer();
4194
4195                $toaddress = $params['notificationto'];
4196
4197                $subject = lang("Read receipt: %1",$params['subject']);
4198                $body = lang("Your message: %1",$params['subject']) . '<br>';
4199                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
4200                $body .= lang("Has been read by: %1 &lt; %2 &gt; at %3", $_SESSION['phpgw_info']['expressomail']['user']['fullname'], $_SESSION['phpgw_info']['expressomail']['user']['email'], date("d/m/Y H:i"));
4201                $mail->SMTPDebug = false;
4202                $mail->IsSMTP();
4203                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
4204                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
4205                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4206                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
4207                $mail->AddAddress($toaddress);
4208                $mail->Subject = $this->htmlspecialchars_decode($subject);
4209
4210                $mail->IsHTML(true);
4211                $mail->Body = $body;
4212
4213                if(!$mail->Send()){
4214                        return $mail->ErrorInfo;
4215                }
4216                else
4217                        return true;
4218        }
4219
4220        function empty_folder($params)
4221        {
4222                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
4223                $mbox_stream = $this->open_mbox($folder);
4224                $return = imap_delete($mbox_stream,'1:*');
4225                if($mbox_stream)
4226                        imap_close($mbox_stream, CL_EXPUNGE);
4227                return $return;
4228        }
4229
4230        function search($params)
4231        {
4232                include("class.imap_attachment.inc.php");
4233                $imap_attachment = new imap_attachment();
4234                $criteria = $params['criteria'];
4235                $return = array();
4236                $folders = $this->get_folders_list();
4237
4238                $j = 0;
4239                foreach($folders as $folder)
4240                {
4241                        $mbox_stream = $this->open_mbox($folder);
4242                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
4243
4244                        if ($messages == '')
4245                                continue;
4246
4247                        $i = 0;
4248                        $return[$j] = array();
4249                        $return[$j]['folder_name'] = $folder['name'];
4250
4251                        foreach($messages as $msg_number)
4252                        {
4253                                $header = $this->get_header($msg_number);
4254                                if (!is_object($header))
4255                                        return false;
4256
4257                                $return[$j][$i]['msg_folder']   = $folder['name'];
4258                                $return[$j][$i]['msg_number']   = $msg_number;
4259                                $return[$j][$i]['Recent']               = $header->Recent;
4260                                $return[$j][$i]['Unseen']               = $header->Unseen;
4261                                $return[$j][$i]['Answered']     = $header->Answered;
4262                                $return[$j][$i]['Deleted']              = $header->Deleted;
4263                                $return[$j][$i]['Draft']                = $header->Draft;
4264                                $return[$j][$i]['Flagged']              = $header->Flagged;
4265
4266                                $date_msg = gmdate("d/m/Y",$header->udate);
4267                                if (gmdate("d/m/Y") == $date_msg)
4268                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
4269                                else
4270                                        $return[$j][$i]['udate'] = $date_msg;
4271
4272                                $fromaddress = imap_mime_header_decode($header->fromaddress);
4273                                $return[$j][$i]['fromaddress'] = '';
4274                                foreach ($fromaddress as $tmp)
4275                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
4276
4277                                $from = $header->from;
4278                                $return[$j][$i]['from'] = array();
4279                                $tmp = imap_mime_header_decode($from[0]->personal);
4280                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
4281                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
4282                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
4283
4284                                $to = $header->to;
4285                                $return[$j][$i]['to'] = array();
4286                                $tmp = imap_mime_header_decode($to[0]->personal);
4287                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
4288                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
4289                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
4290
4291                                $subject = imap_mime_header_decode($header->fetchsubject);
4292                                $return[$j][$i]['subject'] = '';
4293                                foreach ($subject as $tmp)
4294                                        $return[$j][$i]['subject'] .= $tmp->text;
4295
4296                                $return[$j][$i]['Size'] = $header->Size;
4297                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
4298
4299                                $return[$j][$i]['attachment'] = array();
4300                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
4301
4302                                $i++;
4303                        }
4304                        $j++;
4305                        if($mbox_stream)
4306                                imap_close($mbox_stream);
4307                }
4308
4309                return $return;
4310        }
4311
4312
4313        function mobile_search($params)
4314        {
4315                include("class.imap_attachment.inc.php");
4316                $imap_attachment = new imap_attachment();
4317                $criterias = array ("TO","SUBJECT","FROM","CC");
4318                $return = array();
4319                if(!isset($params['folder'])) {
4320                        $folder_params = array("noSharedFolders"=>1);
4321                        if(isset($params['folderType']))
4322                                $folder_params['folderType'] = $params['folderType'];
4323                        $folders = $this->get_folders_list($folder_params);
4324                }
4325                else
4326                        $folders = array(0=>array('folder_id'=>$params['folder']));
4327                $num_msgs = 0;
4328                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
4329                $return["msgs"] = array();
4330               
4331                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
4332                foreach($folders as $id =>$folder)
4333                {
4334                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
4335                                foreach($criterias as $criteria_fixed)
4336                                {
4337                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
4338
4339                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
4340
4341                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
4342                                       
4343                                        if ($messages == ''){
4344                                                if($mbox_stream)
4345                                                        imap_close($mbox_stream);
4346                                                continue;       
4347                                        }
4348                                       
4349                                        foreach($messages as $msg_number)
4350                                        {
4351                                                $temp = $this->get_info_head_msg($msg_number);
4352                                                if(!$temp)
4353                                                        return false;
4354                                                $temp['msg_folder'] = $folder['folder_id'];
4355                                                $return["msgs"][$num_msgs] = $temp;
4356                                                $num_msgs++;
4357                                        }
4358
4359                                        if($mbox_stream)
4360                                                imap_close($mbox_stream);
4361                                }
4362                        }
4363                }
4364
4365                if(!function_exists("cmp_date")) {
4366                        function cmp_date($obj1, $obj2){
4367                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
4368                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
4369                        }
4370                }
4371                usort($return["msgs"], "cmp_date");
4372                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
4373                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
4374                $return["msgs"]['num_msgs'] = $num_msgs;
4375               
4376                return $return;
4377        }
4378
4379        function delete_and_show_previous_message($params)
4380        {
4381                $return = $this->get_info_previous_msg($params);
4382
4383                $params_tmp1 = array();
4384                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
4385                $params_tmp1['folder'] = $params['msg_folder'];
4386                $return_tmp1 = $this->delete_msg($params_tmp1);
4387
4388                $return['msg_number_deleted'] = $return_tmp1;
4389
4390                return $return;
4391        }
4392
4393
4394        function automatic_trash_cleanness($params)
4395        {
4396                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
4397                $criteria =  'BEFORE "'.$before_date.'"';
4398                //$mbox_stream = $this->open_mbox('INBOX'.$this->folders['trash']);
4399                $mbox_stream = $this->open_mbox($this->mount_url_folder(array("INBOX",$this->folders['trash'])));
4400               
4401                // Free others requests
4402                session_write_close();
4403                $messages = imap_search($mbox_stream, $criteria, SE_UID);
4404                if (is_array($messages)){
4405                        foreach ($messages as $msg_number){
4406                                imap_delete($mbox_stream, $msg_number, FT_UID);
4407                        }
4408                }
4409                if($mbox_stream)
4410                        imap_close($mbox_stream, CL_EXPUNGE);
4411                return $messages;
4412        }
4413//      Fix the search problem with special characters!!!!
4414        function remove_accents($string) {
4415                return strtr($string,
4416                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
4417                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
4418        }
4419
4420        function make_search_date($date,$before = false){
4421
4422            //TODO: Adaptar a data de acordo com o locale do sistema.
4423            list($day,$month,$year) = explode("/", $date);
4424            $before?$day=(int)$day+1:$day=(int)$day;
4425            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
4426            $search_date = date('d-M-Y',$timestamp);
4427            return $search_date;
4428
4429        }
4430
4431        function search_msg( $params = false )
4432        {
4433                $mbox_stream = "";
4434               
4435                if(strpos($params['condition'],"#")===false)
4436                { //local messages
4437                        $search=false;
4438                }
4439                else
4440                {
4441                        $search = explode(",",$params['condition']);
4442                }
4443               
4444                $params['page'] = $params['page'] * 1;
4445
4446            if( is_array($search) )
4447            {
4448                        $search = array_unique($search); // Remove duplicated folders
4449                        $search_criteria = '';
4450                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
4451                        foreach($search as $tmp)
4452                        {
4453                                $tmp1 = explode("##",$tmp);
4454                                $sum = 0;
4455                                $name_box = $tmp1[0];
4456                                unset($filter);
4457                                foreach($tmp1 as $index => $criteria)
4458                                {
4459                                        if ($index != 0 && strlen($criteria) != 0)
4460                                        {
4461                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
4462                                                $filter .= " ".$filter_array[0];
4463                                                if (strlen($filter_array[1]) != 0)
4464                                                {
4465                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
4466                                                                 trim($filter_array[0]) != 'SINCE' &&
4467                                                                 trim($filter_array[0]) != 'ON')
4468                                                        {
4469                                                            $filter .= '"'.$filter_array[1].'"';
4470                                                        }else if(trim($filter_array[0]) == 'BEFORE' ){
4471                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
4472                                                        }else{
4473                                                            $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
4474                                                        }
4475                                                }
4476                                        }
4477                                }
4478                               
4479                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
4480                                $filter = $this->remove_accents($filter);
4481
4482                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
4483                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
4484                                {
4485                                        $folder_name = explode($this->imap_delimiter,$name_box);
4486                                        $this->ldap = new ldap_functions();
4487                                       
4488                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
4489                                        {
4490                                                $folder_name[1] = $cn;
4491                                        }
4492                                        $folder_name = implode($this->imap_delimiter,$folder_name);
4493                                }
4494                                else
4495                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
4496                               
4497                                if(!is_resource($mbox_stream))
4498                                        $mbox_stream = $this->open_mbox($name_box);
4499                                else
4500                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
4501                               
4502                                if (preg_match("/^.?\bALL\b/", $filter))
4503                                {
4504                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
4505                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
4506                                           
4507                                        foreach($all_criterias as $criteria_fixed)
4508                                        {
4509                                                $_filter = $criteria_fixed . substr($filter,4);
4510                                               
4511                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
4512                                               
4513                                                if(is_array($search_criteria))
4514                                                {
4515                                                        foreach($search_criteria as $new_search)
4516                                                        {
4517                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
4518                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
4519                                                                $elem['uid'] = $new_search;
4520                                                                /* compare dates in ordering */
4521                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
4522                                                                $retorno[] = $elem;
4523                                                        }
4524                                                }
4525                                        }
4526                                }
4527                                else{
4528                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
4529                                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
4530                                    {
4531                                        if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
4532                                        {
4533                                            $num_msgs = imap_num_msg($mbox_stream);
4534                                            $flagged_msgs = array();
4535                                            for ($i=$num_msgs; $i>0; $i--)
4536                                            {
4537                                                $iuid = @imap_uid($this->mbox,$i);
4538                                                $header = $this->get_header($iuid);
4539                                                if(trim($header->Flagged))
4540                                                {
4541                                                        $flagged_msgs[$i] = $iuid;
4542                                                }
4543                                            }
4544                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
4545                                            {
4546                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
4547                                                    foreach($arry_diff as $msg)
4548                                            {
4549                                                        $search_criteria[] = $msg;
4550                                            }
4551                                        }
4552                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
4553                                        {
4554                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
4555                                        }
4556                                    }
4557                                    }
4558
4559                                    if( is_array( $search_criteria) )
4560                                    {
4561                                        foreach($search_criteria as $new_search)
4562                                        {
4563                                            $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
4564                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
4565                                            $elem['uid'] = $new_search;
4566                                            /* compare dates in ordering */
4567                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
4568                                            $retorno[] = $elem;
4569                                        }
4570                                    }
4571                                }
4572                        }
4573                }
4574               
4575                if($mbox_stream)
4576                {
4577                        imap_close($mbox_stream);
4578            }
4579           
4580            $num_msgs = count($retorno);
4581
4582            /* Comparison functions, descendent is ascendent with parms inverted */
4583            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
4584            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
4585
4586            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
4587            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
4588
4589            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
4590            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
4591
4592            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
4593            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
4594
4595            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
4596            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
4597
4598            usort( $retorno, $params['sort_type']);
4599            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
4600           
4601            $arrayRetorno['num_msgs']   =  $num_msgs;
4602            $arrayRetorno['data']               =  $pageret;
4603            $arrayRetorno['currentTab'] =  $params['current_tab'];
4604
4605                if ($pageret)
4606                {
4607                        return $arrayRetorno;
4608                }
4609                else
4610                {
4611                        return 'none';
4612                }
4613        }
4614
4615        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
4616        {
4617                $header = $this->get_header($uid_msg);
4618                require_once("class.imap_attachment.inc.php");
4619                $imap_attachment = new imap_attachment();
4620                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
4621                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
4622                $flag = $header->Unseen
4623                        .$header->Recent
4624                        .$header->Flagged
4625                        .$header->Draft
4626                        .$header->Answered
4627                        .$header->Deleted
4628                        .$attachments;
4629
4630
4631                $subject = $this->decode_string($header->fetchsubject);
4632                $from = $header->from[0]->mailbox;
4633                if($header->from[0]->personal != "")
4634                        $from = $header->from[0]->personal;
4635                $ret_msg['from']        = $this->decode_string($from);
4636                $ret_msg['subject']     = $subject;
4637                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
4638                $ret_msg['size']        = $header->Size;
4639                $ret_msg['flag']        = $flag;
4640                return $ret_msg;
4641        }
4642
4643
4644        function size_msg($size){
4645                $var = floor($size/1024);
4646                if($var >= 1){
4647                        return $var." kb";
4648                }else{
4649                        return $size ." b";
4650                }
4651        }
4652       
4653        function ob_array($the_object)
4654        {
4655           $the_array=array();
4656           if(!is_scalar($the_object))
4657           {
4658               foreach($the_object as $id => $object)
4659               {
4660                   if(is_scalar($object))
4661                   {
4662                       $the_array[$id]=$object;
4663                   }
4664                   else
4665                   {
4666                       $the_array[$id]=$this->ob_array($object);
4667                   }
4668               }
4669               return $the_array;
4670           }
4671           else
4672           {
4673               return $the_object;
4674           }
4675        }
4676
4677        function getacl()
4678        {
4679                $this->ldap = new ldap_functions();
4680
4681                $return = array();
4682                $mbox_stream = $this->open_mbox();
4683                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
4684
4685                $i = 0;
4686                foreach ($mbox_acl as $user => $acl)
4687                {
4688                        if ($user != $this->username)
4689                        {
4690                                $return[$i]['uid'] = $user;
4691                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
4692                        }
4693                        $i++;
4694                }
4695                return $return;
4696        }
4697
4698        function setacl($params)
4699        {
4700                $old_users = $this->getacl();
4701                if (!count($old_users))
4702                        $old_users = array();
4703
4704                $tmp_array = array();
4705                foreach ($old_users as $index => $user_info)
4706                {
4707                        $tmp_array[$index] = $user_info['uid'];
4708                }
4709                $old_users = $tmp_array;
4710
4711                $users = unserialize($params['users']);
4712                if (!count($users))
4713                        $users = array();
4714
4715                //$add_share = array_diff($users, $old_users);
4716                $remove_share = array_diff($old_users, $users);
4717
4718                $mbox_stream = $this->open_mbox();
4719
4720                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4721                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4722
4723                /*if (count($add_share))
4724                {
4725                        foreach ($add_share as $index=>$uid)
4726                        {
4727                        if (is_array($mailboxes_list))
4728                        {
4729                        foreach ($mailboxes_list as $key => $val)
4730                        {
4731                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4732                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
4733                        }
4734                        }
4735                        }
4736                }*/
4737
4738                if (count($remove_share))
4739                {
4740                        foreach ($remove_share as $index=>$uid)
4741                        {
4742                            if (is_array($mailboxes_list))
4743                            {
4744                                foreach ($mailboxes_list as $key => $val)
4745                                {
4746                                    $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4747                                    $folder = str_replace("&-", "&", $folder);
4748                                    imap_setacl ($mbox_stream, $folder, "$uid", "");
4749                                }
4750                            }
4751                        }
4752                }
4753
4754                return true;
4755        }
4756
4757        function getaclfromuser($params)
4758        {
4759                $useracl = $params['user'];
4760
4761                $return = array();
4762                $return[$useracl] = 'false';
4763                $mbox_stream = $this->open_mbox();
4764                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
4765
4766                foreach ($mbox_acl as $user => $acl)
4767                {
4768                        if (($user != $this->username) && ($user == $useracl))
4769                        {
4770                                $return[$user] = $acl;
4771                        }
4772                }
4773                return $return;
4774        }
4775
4776        function getacltouser($user)
4777        {
4778                $return = array();
4779                $mbox_stream = $this->open_mbox();
4780                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4781                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
4782                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
4783                if(substr($user,0,4) != 'user')
4784                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4785                else
4786                  $mbox_acl = @imap_getacl($mbox_stream, $user);
4787                if(isset($mbox_acl[$this->username]))
4788                return $mbox_acl[$this->username];
4789                else
4790                    return '';
4791        }
4792
4793
4794        function setaclfromuser($params)
4795        {
4796                $user = $params['user'];
4797                $acl = $params['acl'];
4798
4799                $mbox_stream = $this->open_mbox();
4800
4801                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4802                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4803
4804                if (is_array($mailboxes_list))
4805                {
4806                        foreach ($mailboxes_list as $key => $val)
4807                        {
4808                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
4809                                $folder = str_replace("&-", "&", $folder);
4810                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
4811                                {
4812                                        $return = imap_last_error();
4813                                }
4814                        }
4815                }
4816                if (isset($return))
4817                        return $return;
4818                else
4819                        return true;
4820        }
4821
4822        function download_attachment($msg,$msgno)
4823        {
4824                $array_parts_attachments = array();
4825                //$array_parts_attachments['names'] = '';
4826                include_once("class.imap_attachment.inc.php");
4827                $imap_attachment = new imap_attachment();
4828
4829                if (count($msg->fname[$msgno]) > 0)
4830                {
4831                        $i = 0;
4832                        foreach ($msg->fname[$msgno] as $index=>$fname)
4833                        {
4834                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
4835                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
4836                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
4837                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
4838                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
4839                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
4840                                $i++;
4841                        }
4842                }
4843                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
4844                return $array_parts_attachments;
4845        }
4846
4847       
4848        /**
4849        * @license   http://www.gnu.org/copyleft/gpl.html GPL
4850        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
4851        * @param     $params
4852        */
4853        function spam($params)
4854        {
4855               
4856                $mbox_stream = $this->open_mbox($params['folder']);
4857                $msgs_number = explode(',',$params['msgs_number']);
4858
4859                $user = Array();
4860
4861                if(substr($params['folder'], 0, 4) == 'user')
4862                {
4863                    $ldapObject = new ldap_functions();
4864
4865                    $folderArray = Array();
4866                    $folderArray = explode($this->imap_delimiter, $params['folder']);
4867
4868                    $user['name'] = $folderArray[1];
4869                    $user['email'] = $ldapObject->getMailByUid($user['name']);
4870               
4871                }
4872                else
4873                {
4874                    $user['name'] = $this->username;
4875                    $user['email'] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4876                }
4877
4878                foreach($msgs_number as $msg_number)
4879                {
4880                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
4881                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
4882                        $body = imap_body($mbox_stream, $imap_msg_number);
4883                        $msg = $header . $body;
4884                        strtok($user['email'], '@');
4885                        $domain = strtok('@');
4886
4887           
4888
4889                        //Encontrar a assinatura do dspam no cabecalho
4890                        $v = explode("\r\n", $header);
4891                        foreach ($v as $linha){
4892                                if (eregi("^Message-ID", $linha)) {
4893                                        $args = explode(" ", $linha);
4894                                        $msg_id = "'$args[1]'";
4895                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
4896                                        $args = explode(" ",$linha);
4897                                        $signature = $args[1];
4898                                }
4899                        }
4900
4901                        // Seleciona qual comando a ser executado
4902                        switch($params['spam']){
4903                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
4904                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
4905                        }
4906
4907                     
4908                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
4909                        $cmd = str_replace($tags, array($user['email'], $user['name'], $domain, $signature, $msg_id), $cmd);
4910                       
4911                        system($cmd);
4912                }
4913
4914                imap_close($mbox_stream);
4915                return false;
4916        }
4917       
4918       
4919/**
4920* Descrição do método
4921*
4922* @license    http://www.gnu.org/copyleft/gpl.html GPL
4923* @author     
4924* @sponsor    Caixa Econômica Federal
4925* @author     
4926* @param      <tipo> <$msg_number> <Número da mensagem>
4927* @return     <cabeçalho da mensagem>
4928* @access     <public>
4929*/     
4930        function get_header($msg_number)
4931        {
4932                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
4933                if (!is_object($header))
4934                        return false;
4935
4936                if($header->Flagged != "F" ) {
4937                        $flag = preg_match('/importance *: *(.*)\r/i',
4938                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
4939                                                ,$importance);
4940                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
4941                }
4942
4943                return $header;
4944        }
4945
4946//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Insere emails no imap a partir do fonte do mesmo. Se o argumento timestamp for passado ele utiliza do script python
4947///expressoMail1_2/imap.py para inserir uma msg com o horário correto pois isso não é porssível com a função imap_append do php.
4948
4949
4950    function insert_email($source,$folder,$timestamp,$flags){
4951               
4952        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
4953        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
4954        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
4955        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
4956        $imap_options = '/notls/novalidate-cert';
4957
4958       
4959        $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
4960
4961        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
4962       
4963        if(imap_last_error() === 'Mailbox already exists')
4964            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
4965        if($timestamp){
4966                        $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local)
4967                        $timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local.
4968                        /* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */
4969                        $file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
4970               
4971                $f = fopen($file,"w");
4972                fputs($f,base64_encode($source));
4973            fclose($f);
4974            $command = "python ".dirname(__FILE__)."/../imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
4975            $return['command']= exec($command);
4976        }else{
4977            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
4978        }
4979        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
4980                       
4981        $return['msg_no'] = $status->uidnext - 1;
4982        $return['error'] = imap_last_error();
4983        if(!$return['error'] && $flags != '' ){
4984
4985                  $flags_array=explode(':',$flags);
4986                  //"Answered","Draft","Flagged","Unseen"
4987                  $flags_fixed = "";
4988                  if($flags_array[0] == 'A')
4989                        $flags_fixed.="\\Answered ";
4990                  if($flags_array[1] == 'X')
4991                        $flags_fixed.="\\Draft ";
4992                  if($flags_array[2] == 'F')
4993                        $flags_fixed.="\\Flagged ";
4994                  if($flags_array[3] != 'U')
4995                        $flags_fixed.="\\Seen ";
4996                  if($flags_array[4] == 'F')
4997                        $flags_fixed.="\\Answered \\Draft ";
4998                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
4999                }
5000       
5001        //Ignorando erro de AUTH=Plain
5002        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN')
5003            $return['error'] = false;
5004                               
5005        if($mbox_stream)
5006            imap_close($mbox_stream);
5007        return $return;
5008    }
5009
5010        function show_decript($params,$dec=0){
5011        $source = $params['source'];
5012                 
5013        //error_log("source: $source\nversao: " . PHP_VERSION);         
5014        if ($dec == 0)
5015        {
5016            $source = str_replace(" ", "+", $source,$i);
5017                        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
5018                            if(!$source = base64_decode($source,true))
5019                    return "error ".$source."Espaï¿?os ".$i;
5020                 
5021                        }
5022                        else {
5023                            if(!$source = base64_decode($source))
5024                    return "error ".$source."Espaï¿?os ".$i;
5025            }
5026        }
5027
5028        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5029
5030                $get['msg_number'] = $insert['msg_no'];
5031                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
5032                $return = $this->get_info_msg($get);
5033                $get['msg_number'] = $params['ID'];
5034                $get['msg_folder'] = $params['folder'];
5035                $tmp = $this->get_info_msg($get);
5036                if(!$tmp['status_get_msg_info'])
5037                {
5038                        $return['msg_day']=$tmp['msg_day'];
5039                        $return['msg_hour']=$tmp['msg_hour'];
5040                        $return['fulldate']=$tmp['fulldate'];
5041                        $return['smalldate']=$tmp['smalldate'];
5042                }
5043                else
5044                {
5045                        $return['msg_day']='';
5046                        $return['msg_hour']='';
5047                        $return['fulldate']='';
5048                        $return['smalldate']='';
5049                }
5050        $return['msg_no'] =$insert['msg_no'];
5051        $return['error'] = $insert['error'];
5052        $return['folder'] = $params['folder'];
5053        //$return['acls'] = $insert['acls'];
5054        $return['original_ID'] =  $params['ID'];
5055
5056        return $return;
5057
5058    }
5059
5060//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Trata fontes de emails enviados via POST para o servidor por um xmlhttprequest, as partes codificados com
5061//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
5062
5063    function treat_base64_from_post($source){
5064            $offset = 0;
5065            do
5066            {
5067                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
5068                    {
5069                            $inicio = strpos($source, "\n\r", $inicio);
5070                            $fim = strpos($source, '--', $inicio);
5071                            if(!$fim)
5072                                    $fim = strpos($source,"\n\r", $inicio);
5073                            $length = $fim-$inicio;
5074                            $parte = substr( $source,$inicio,$length-1);
5075                            $parte = str_replace(" ", "+", $parte);
5076                            $source = substr_replace($source, $parte, $inicio, $length-1);
5077                    }
5078                    if($offset > $inicio)
5079                    $offset=FALSE;
5080                    else
5081                    $offset = $inicio;
5082            }
5083            while($offset);
5084            return $source;
5085    }
5086
5087//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
5088
5089    function unarchive_mail($params)
5090    {           
5091        $dest_folder = $params['folder'];
5092        $sources = explode("#@#@#@",$params['source']);
5093        //Add user timeszone
5094        $timestamps = explode("#@#@#@",$params['timestamp']);
5095
5096
5097        $flags = explode("#@#@#@",$params['flags']);
5098               
5099                foreach($sources as $index=>$src) {
5100                        if($src!=""){
5101                $source = $this->treat_base64_from_post($src);
5102                $timestampsactual = $timestamps[$index] + $this->functions->CalculateDateOffset();
5103                        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestampsactual,$flags[$index]);
5104            }
5105        }
5106        return $insert;
5107    }
5108
5109    function download_all_local_attachments($params)
5110    {
5111        $source = $params['source'];
5112        $source = $this->treat_base64_from_post($source);
5113        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5114        $exporteml = new ExportEml();
5115        $params['num_msg']=$insert['msg_no'];
5116        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
5117        return $exporteml->download_all_attachments($params);
5118    }
5119       
5120        /**
5121         * Método que envia um email reportando um erro no email do usuário
5122         * @license http://www.gnu.org/copyleft/gpl.html GPL
5123         * @author Prognus Software Livre (http://www.prognus.com.br)
5124         */ 
5125        function report_mail_error($params)
5126        {       
5127                $params = $params['params'];
5128                $array_params = explode(";;", $params);
5129                $id_msg   = $array_params[0];
5130                $msg_user = $array_params[1];
5131               
5132                if($msg_user == '')
5133                        $msg_user = "Sem mensagem!";
5134                         
5135                $toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
5136                 
5137                $exporteml    = new ExportEml();
5138                $mail_content = $exporteml->export_msg_data($id_msg, $msg_folder);
5139                $this->open_mbox($msg_folder); 
5140                $title = "Erro de email reportado";
5141                $body  = "<body>O usuário <strong>$toname</strong> reportou um erro na tentativa de acesso ao conteúdo do email.<br><br>Segue em anexo o fonte da mensagem" .                           " reportada.<br><br><hr><strong><u>Mensagem do usuário:</strong></u><br><br><br>" .
5142                                "$msg_user</body><br><br><hr>";
5143                             
5144                require_once dirname(__FILE__) . '/../../API/class.servicelocator.php';
5145                $mailService = ServiceLocator::getService('mail');     
5146                $mailService->addStringAttachment($mail_content, 'report.eml', 'application/text');
5147                $mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body);
5148        }
5149       
5150        function array_msort($array, $cols)
5151        {
5152                $colarr = array();
5153                foreach ($cols as $col => $order) {
5154                        $colarr[$col] = array();
5155                        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
5156                }
5157                $params = array();
5158                foreach ($cols as $col => $order) {
5159                        $params[] =& $colarr[$col];
5160                        $params = array_merge($params, (array)$order);
5161                }
5162                call_user_func_array('array_multisort', $params);
5163                $ret = array();
5164                $keys = array();
5165                $first = true;
5166                foreach ($colarr as $col => $arr) {
5167                        foreach ($arr as $k => $v) {
5168                                if ($first) { $keys[$k] = substr($k,1); }
5169                                $k = $keys[$k];
5170                                if (!isset($ret[$k])) $ret[$k] = $array[$k];
5171                                $ret[$k][$col] = $array[$k][$col];
5172                        }
5173                        $first = false;
5174                }
5175               
5176                return $ret;
5177
5178        }
5179       
5180        function parseCriteriaSearchMail($search)
5181        {
5182            $criteria = '';
5183            $searchArray = explode(' ', $search);
5184
5185            foreach ($searchArray as $v)
5186                if(trim($v) !== '' )
5187                    $criteria .= 'TEXT "'.$v.'" ' ;
5188           
5189            return $criteria;
5190        }
5191       
5192        function quickSearchMail( $params )
5193        {
5194                $return = array();
5195                $return['folder'] = $params['folder'];
5196                if(!is_array($params['folder']))
5197                        $params['folder'] = array( $params['folder'] );
5198               
5199                if(!isset($params['sort']))
5200                        $params['sort'] = 'SORTDATE_REVERSE';
5201                               
5202                $params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
5203               
5204                $i = 0;         
5205                if(!isset($params['page'])) $params['page'] = 0;
5206                $end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));       
5207                $ini = $end - $this->prefs['max_email_per_page'] ;
5208                $count = 0;
5209               
5210                $search = $this->parseCriteriaSearchMail($params['search']);
5211                               
5212                foreach ($params['folder'] as $folder)
5213                {
5214                        $imap = $this->open_mbox( $folder ) ;
5215                        $msgIds = imap_sort( $imap , SORTDATE , 1 , SE_UID , $search ,'UTF-8');
5216                                               
5217                        $count += count($msgIds); 
5218                       
5219                        foreach ($msgIds as $ii => $v)
5220                        {                               
5221                                $msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) );
5222                                $return['msgs'][$i]['from'] = '';
5223                               
5224                                $from = $msg->from[0]->mailbox;
5225                                if($msg->from[0]->personal != "")
5226                                        $from = $msg->from[0]->personal;
5227                                $return['msgs'][$i]['from']     = mb_convert_encoding($this->decode_string($from), 'UTF-8');
5228                               
5229                                $return['msgs'][$i]['subject'] = ' ';
5230                               
5231                                $subject = imap_mime_header_decode($msg->subject);
5232                                foreach ($subject as $tmp)
5233                                        $return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
5234                               
5235                               
5236                                $return['msgs'][$i]['flag'] = ' ';
5237                                $return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
5238                                $return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';       
5239                                $return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';     
5240                                $return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : ''; 
5241                                $return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';   
5242                                $return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';     
5243                               
5244                                $return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset());
5245                                $return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2);
5246                            $return['msgs'][$i]['date'] =   $msg->udate;
5247                                $return['msgs'][$i]['size'] =  $msg->Size;
5248                                $return['msgs'][$i]['boxname'] = $folder;
5249                                $return['msgs'][$i]['uid'] = $v;
5250                                $i++;
5251                        }       
5252                }
5253               
5254                $return['num_msgs'] = $count;
5255               
5256                if(!isset($return['msgs']))
5257                        $return['msgs'] = array();
5258               
5259                define('SORTBOX', 69);
5260                define('SORTWHO', 2);
5261                define('SORTBOX_REVERSE', 69);
5262                define('SORTWHO_REVERSE', 2);
5263                define('SORTDATE_REVERSE', 0);
5264                define('SORTSUBJECT_REVERSE', 3);
5265                define('SORTSIZE_REVERSE', 6);
5266               
5267                switch (constant( $params['sort'] )){
5268                        case 0 : $sA = 'date'; break;
5269                        case 2 : $sA = 'from'; break;
5270                        case 69 : $sA = 'boxname'; break;
5271                        case 3 : $sA = 'subject'; break;
5272                        case 6 : $sA = 'size'; break;
5273        }
5274       
5275                       
5276                if($params['sort'] !== 'SORTDATE_REVERSE')
5277                if(strpos($params['sort'],'REVERSE') !== false)
5278                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_DESC));
5279                        else
5280                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
5281               
5282                $k = -1;
5283                $nMsgs = array();
5284               
5285                foreach ($return['msgs'] as $v)
5286                {               
5287                        $k++;
5288                        if($k < $ini || $k >= $end ) continue;                 
5289                        $nMsgs[] = $v;
5290                }
5291                $return['msgs'] = $nMsgs;
5292               
5293                $return = json_encode($return);         
5294                $return = base64_encode($return);
5295       
5296                return $return;
5297        }
5298       
5299    function get_quota_folders(){
5300
5301            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
5302            include_once("class.imapfp.inc.php");           
5303            $imapfp = new imapfp();
5304
5305            if(!$imapfp->open($this->imap_server,$this->imap_port))
5306                    return $imapfp->get_error();             
5307            if (!$imapfp->login( $this->username,$this->password ))
5308                    return $imapfp->get_error();
5309
5310            $response_array = $imapfp->get_mailboxes_size();
5311            if ($imapfp->error)
5312                    return $imapfp->get_error();
5313
5314            $data = array();
5315            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
5316            $data["quota_root"] = $quota_root;
5317
5318            foreach ($response_array as $idx=>$line) {
5319                    $line2 = str_replace('"', "", $line);
5320                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
5321                    list($folder,$size) = explode(";",$line2);
5322                    $quota_used = str_replace(")","",$size);
5323                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
5324                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
5325                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
5326                            $folder = $this->functions->getLang("Inbox");
5327                    }
5328                    else
5329                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
5330
5331                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
5332            }
5333            $imapfp->close();
5334            return $data;
5335    } 
5336   
5337    function getaclfrombox($mail)
5338        {
5339                $mailArray = explode('@', $mail);
5340                $boxacl = $mailArray[0];
5341                $return = array();
5342
5343                if(!$this->mbox)
5344                     $this->open_mbox();
5345
5346                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl);
5347
5348                foreach ($mbox_acl as $user => $acl)
5349                {
5350                        if ($user != $boxacl )
5351                            $return[$user] = $acl;
5352                }
5353                return $return;
5354        }
5355}
5356?>
Note: See TracBrowser for help on using the repository browser.