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

Revision 5373, 200.8 KB checked in by cristiano, 12 years ago (diff)

Ticket #2440 - Correção no decodeMimeString

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