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

Revision 5302, 200.9 KB checked in by thiago, 12 years ago (diff)

Ticket #2350 - Deixar dinamico o nome das pastas no codigo

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