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

Revision 5359, 200.5 KB checked in by cristiano, 12 years ago (diff)

Ticket #2440 - Melhorias no carregamento de mensagens de e-mail do usuário

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