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

Revision 5516, 202.6 KB checked in by gustavo, 12 years ago (diff)

Ticket #2484 - Melhorias na estrutura de diretórios do ExpressoMail?

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