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

Revision 5453, 201.5 KB checked in by douglas, 12 years ago (diff)

Ticket #2470 - adicionar suporte à propriedade In Reply To nas mensagens

  • 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 != ('unspecified-domain' || '.SYNTAX-ERROR.')) )? '@'. $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 (isset($tmp->host) && $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_ireplace('\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 = str_ireplace('POSITION: ABSOLUTE;','', $body);
1837
1838            ///--------------------------------//
1839            // tags to be removed doe to security reasons
1840            $tag_list = Array(
1841                'blink', 'object', 'frame', 'iframe',
1842                'layer', 'ilayer', 'plaintext', 'script',
1843                'applet', 'embed', 'frameset', 'xml', 'xmp'
1844            );
1845
1846            foreach ($tag_list as $index => $tag)
1847                $body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body);
1848           
1849            $body = preg_replace('/<(meta|base|link)[^>]*>/i', '', $body);
1850
1851            //try to wrap CSS code instead of remove STYLE tags
1852            require_once('../library/csstidy/class.csstidy.php');
1853            $css = new csstidy();
1854            $css->set_cfg('preserve_css', false);
1855
1856            $regs_found = array();
1857            $tags_found = preg_match_all("@<style[^>]*>.*?</style[^>]*>@si", $body, $regs_found);
1858            $wrapper_class = 'ExpressoCssWrapper' . time();
1859                       
1860            foreach ($regs_found as $k => &$v) {
1861                foreach ($v as $kk => $vv) {
1862                    $n_start = strpos($vv, '>') + 1;
1863                    $n_length = strrpos($vv, '<') - $n_start;
1864                    $bf_innerHTML = substr($vv, $n_start, $n_length);
1865                    $bf_innerHTML = mb_ereg_replace('<!--', '', $bf_innerHTML);
1866                    $bf_innerHTML = mb_ereg_replace('-->', '', $bf_innerHTML);
1867                   
1868                    $css->parse($bf_innerHTML);
1869
1870                    $prefix = ".$wrapper_class ";
1871                    if (isset($css->css[41]) && count($css->css[41] > 0))
1872                        foreach ($css->css[41] as $key => $value) {
1873                            //explode multiple selectors per block
1874                            $selectors = explode(',', $key);
1875
1876                            foreach ($selectors as $selector) {
1877                                if (ereg('\*', $key)) {
1878                                    //skip selecto '*'
1879                                    continue;
1880                                }
1881
1882                                $selector = eregi_replace('[^#\.]*body.*', '', $selector);
1883                                $css->css[41][$prefix . trim($selector)] = $value;
1884                            }
1885                            unset($css->css[41][$key]);
1886                        }
1887
1888                    $body = str_replace($vv, '<style>' . $css->print->plain() . '</style>', $body);
1889                }
1890            }
1891           
1892        // Malicious Code Remove
1893        $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";
1894        preg_match_all($dirtyCodePattern, $body, $rest, PREG_PATTERN_ORDER);
1895        foreach ($rest[0] as $i => $val) {
1896            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
1897                $body = str_replace($rest[1][$i], "<" . $rest[2][$i] . $rest[3][$i] . $rest[7][$i] . ">", $body);
1898        }
1899
1900        /*
1901         * Remove deslocamento a esquerda colocado pelo Outlook.
1902         * Este delocamento faz com que algumas palavras fiquem escondidas atras da barra lateral do expresso.
1903         */
1904        $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1905        $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1906        $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1907        //--------------------------------------------------------------------------------------------//       
1908        //Remoção de tags <span></span> para correção de erro no firefox
1909        //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>.
1910        //Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo.
1911        //              $body = mb_eregi_replace("<span><span>","",$body);
1912        //              $body = mb_eregi_replace("</span></span>","",$body);
1913        //Correção para compatibilização com Outlook, ao visualizar a mensagem
1914        $body = mb_ereg_replace('<!--\[', '<!-- [', $body);
1915        $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1916
1917        return "<div class=\"$wrapper_class\"><span>" . $body . '</span></div>';
1918    }
1919       
1920        function replace_links_callback($matches) 
1921        {
1922            if($matches[3])
1923                    $pref = $matches[3];
1924            else
1925                    $pref = $matches[3] = 'http';
1926
1927            return '<a href="'.$pref.'://'.$matches[4].$matches[5].'" target="_blank">'.$matches[0].'</a>';
1928        }
1929
1930
1931        /**
1932        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1933        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1934        * @param     $body corpo da mensagem
1935        */
1936        function replace_links(&$body)
1937        {
1938                // Trata urls do tipo aaaa.bbb.empresa 
1939                // Usadas na intranet. 
1940                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])(((http|https|ftp|ftps)?:\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';   
1941                $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body);
1942
1943        }
1944
1945        function get_signature($msg, $msg_number, $msg_folder)
1946        {
1947            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1948            include_once("class.db_functions.inc.php");
1949            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1950            {
1951                $sign = array();
1952                $temp = $this->get_info_head_msg($msg_number);
1953                if($temp['ContentType'] =='normal') return $sign;
1954                $file_type = strtolower($file_type);
1955                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1956                {
1957                    if ($temp['ContentType'] == 'signature')
1958                    {
1959                        if(!$this->mbox || !is_resource($this->mbox))
1960                        $this->mbox = $this->open_mbox($msg_folder);
1961
1962                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1963
1964                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1965                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1966
1967                        $certificado = new certificadoB();
1968                        $validade = $certificado->verificar($imap_msg);
1969                                        $sign[] = $certificado->msg_sem_assinatura;
1970                        if ($certificado->apresentado)
1971                        {
1972                            $from = $header->from;
1973                            foreach ($from as $id => $object)
1974                            {
1975                                $fromname = $object->personal;
1976                                $fromaddress = $object->mailbox . "@" . $object->host;
1977                            }
1978                            foreach ($certificado->erros_ssl as $item)
1979                            {
1980                                $sign[] = $item . "#@#";
1981                            }
1982
1983                            if (count($certificado->erros_ssl) < 1)
1984                            {
1985                                $check_msg = 'Message untouched';
1986                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1987                                {
1988                                    $check_msg .= ' and authentic###';
1989                                }
1990                                else
1991                                {
1992                                    $check_msg .= ' with signer different from sender#@#';
1993                                }
1994                                $sign[] = $check_msg;
1995                            }
1996                                               
1997                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1998                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1999                            $sign[] = 'Mail from: ###' . $fromaddress;
2000                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
2001                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
2002                            $sign[] = 'Message date: ###' . $header->Date;
2003
2004                            $cert = openssl_x509_parse($certificado->cert_assinante);
2005
2006                            $sign_alert = array();
2007                            $sign_alert[] = 'Certificate Owner###:\n';
2008                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
2009                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
2010                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
2011                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
2012                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
2013                            $sign_alert[] = 'Personal Data###:' . '\n';
2014                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
2015                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
2016                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
2017                            $sign_alert[]= 'Certificate Issuer###:\n';
2018                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
2019                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
2020                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
2021                            $sign_alert[]= 'Validity###:\n';
2022                            $H = data_hora($cert[validFrom]);
2023                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2024                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
2025                            $H = data_hora($cert[validTo]);
2026                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2027                            $sign_alert[]= 'Valid Until### ' . $X;
2028                            $sign[] = $sign_alert;
2029
2030                            $this->db = new db_functions();
2031                           
2032                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
2033                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
2034                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
2035                        }
2036                        else
2037                        {
2038                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
2039                            foreach($certificado->erros_ssl as $item)
2040                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
2041                        }
2042                    }
2043                }
2044            }
2045            return $sign;
2046        }
2047
2048       
2049        /**
2050        * @license   http://www.gnu.org/copyleft/gpl.html GPL
2051        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2052        * @param     $images
2053        * @param     $msg_number
2054        * @param     $msg_folder
2055        */
2056        function get_thumbs($images, $msg_number, $msg_folder)
2057        {
2058
2059                if (!count($images)) return '';
2060               
2061                foreach ($images as $key => $value) {                   
2062                        $images[$key]['width']  = 160;
2063                        $images[$key]['height'] = 120;
2064                        $images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$value['pid']."&image=true";
2065                }
2066
2067                return json_encode($images);
2068        }
2069
2070        /*function delete_msg($params)
2071        {
2072                $folder = $params['folder'];
2073                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
2074
2075                $mbox_stream = $this->open_mbox($folder);
2076
2077                foreach ($msgs_to_delete as $msg_number){
2078                        imap_delete($mbox_stream, $msg_number, FT_UID);
2079                }
2080                imap_close($mbox_stream, CL_EXPUNGE);
2081                return $params['msgs_to_delete'];
2082        }*/
2083
2084        // Novo
2085        function delete_msgs($params)
2086        {
2087
2088                $folder = $params['folder'];
2089                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
2090                $msgs_number = explode(",",$params['msgs_number']);
2091                if(array_key_exists('border_ID' ,$params))
2092                $border_ID = $params['border_ID'];
2093                else
2094                        $border_ID = '';
2095                $return = array();
2096
2097                if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){
2098                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2099                        // Fix problem in unserialize function JS.
2100                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2101                }
2102
2103                //$mbox_stream = $this->open_mbox($folder);
2104                $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()))));
2105
2106                foreach ($msgs_number as $msg_number)
2107                {
2108                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
2109                                $return['msgs_number'][] = $msg_number;
2110                }
2111
2112                $return['folder'] = $folder;
2113                $return['border_ID'] = $border_ID;
2114
2115                if($mbox_stream)
2116                        imap_close($mbox_stream, CL_EXPUNGE);
2117                       
2118                $return['status'] = true;
2119                return $return;
2120        }
2121
2122
2123        function refresh($params)
2124        {
2125
2126                $return = array();
2127                $return['new_msgs'] = 0;
2128                $folder = $params['folder'];
2129                $msg_range_begin = $params['msg_range_begin'];
2130                $msg_range_end = $params['msg_range_end'];
2131                $msgs_existent = $params['msgs_existent'];
2132                $sort_box_type = $params['sort_box_type'];
2133                $sort_box_reverse = $params['sort_box_reverse'];
2134                $msgs_in_the_server = array();
2135                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2136                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2137                $msgs_in_the_server = array_keys($msgs_in_the_server);
2138                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
2139                $dif = ($params['msg_range_end'] - $params['msg_range_begin']) +1;
2140                if(!count($msgs_in_the_server)){
2141                        $msg_range_begin -= $dif;
2142                        $msg_range_end -= $dif;
2143                        $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2144                        $msgs_in_the_server = array_keys($msgs_in_the_server); 
2145                        $num_msgs = NULL;
2146                        $return['msg_range_begin'] = $msg_range_begin;
2147                        $return['msg_range_end'] = $msg_range_end;
2148                }               
2149                $return['new_msgs'] = imap_num_recent($this->mbox);
2150               
2151                $msgs_in_the_client = explode(",", $msgs_existent);
2152
2153                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
2154
2155                if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){
2156                        $aux = 0;
2157                        while(array_key_exists($aux, $msg_to_insert)){
2158                                if($msg_to_insert[$aux] > $msgs_in_the_client[0]){
2159                                        $return['new_msgs'] += 1;
2160                                }
2161                                $aux++;
2162                        }
2163                }else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){
2164                        $aux = 0;
2165                        while(array_key_exists($aux, $msg_to_insert)){
2166                                if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){
2167                                        $return['new_msgs'] += 1;
2168                                }
2169                                $aux++;
2170                        }
2171                }else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0 && $msg_range_end == $dif){
2172                        $return['tot_msgs'] = $num_msgs;
2173                }
2174               
2175                if(!count($msgs_in_the_server)){
2176                        return Array();
2177                }       
2178
2179                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
2180                $msgs_to_exec = array();
2181                foreach($msg_to_insert as $msg_number)
2182                        $msgs_to_exec[] = $msg_number;
2183                //sort($msgs_to_exec);
2184                $i = 0;
2185                foreach($msgs_to_exec as $msg_number)
2186                {
2187                    $sample = false;
2188                    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')) )
2189                          $sample = true;
2190                   
2191                    $return[$i] = $this->get_info_head_msg($msg_number , $sample );
2192                   
2193                    //get the next msg number to append this msg in the view in a correct place
2194                    $msg_key_position = array_search($msg_number, $msgs_in_the_server);
2195                       
2196                    $return[$i]['msg_key_position'] = $msg_key_position;
2197                    if($msg_key_position !== false && array_key_exists($msg_key_position + 1,$msgs_in_the_server) !== false)
2198                        $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
2199                    else
2200                        $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position];
2201
2202                    $return[$i]['msg_folder'] = $folder;
2203                    $i++;
2204                }
2205                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
2206                $return['sort_box_type'] = $params['sort_box_type'];
2207                if(!$this->mbox || !is_resource($this->mbox))
2208                    $this->open_mbox($folder);
2209               
2210                $return['msgs_to_delete'] = $msg_to_delete;
2211                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
2212                if($this->mbox && is_resource($this->mbox))
2213                        imap_close($this->mbox);
2214
2215                return $return;
2216        }
2217
2218     /**
2219     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
2220     * assinado ou cifrado.
2221     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
2222     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
2223     * @param $msg_number O número da mesagem
2224     * @return Retorna o tipo da mensagem (normal, signature, cipher).
2225     */
2226    function getMessageType($msg_number, $headers = false , &$body = false){
2227            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2228            $contentType = "normal";
2229         
2230            if (!$headers)
2231                $headers = imap_fetchheader($this->mbox, $msg_number, FT_UID);
2232
2233            if (preg_match("/pkcs7-signature/i", $headers) == 1)
2234                $contentType = "signature";
2235             else if (preg_match("/pkcs7-mime/i", $headers) == 1)
2236                $contentType = testa_p7m(  $body ? $body :  imap_body($this->mbox, $msg_number , FT_UID )) ;
2237 
2238            return $contentType;
2239    }
2240   
2241                /**
2242        * Retorna a posição que a pasta esta dentro do array de pastas
2243        *
2244        * @license    www.gnu.org/copyleft/gpl.html GPL
2245        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2246        * @sponsor    Caixa Econômica Federal
2247        * @author     Cristiano Corrêa Schmidt
2248        * @access     public
2249                */
2250               
2251        function getFolderPos(&$array , $find)
2252        {           
2253                foreach($array as $i => $v)
2254                        if($v['id'] === $find)
2255                                return $i;
2256                return false;
2257        }
2258       
2259        /**
2260        * Ordenas as pastas padrões do usuario na ordem INBOX > SENT > DRAFTS > SPAM > TRASH > OTHERS
2261        *
2262        * @license    http://www.gnu.org/copyleft/gpl.html GPL
2263        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2264        * @sponsor    Caixa Econômica Federal
2265        * @author     Cristiano Corrêa Schmidt
2266        * @access     public
2267        */
2268        function orderDefaultFolders( &$folders , $user)
2269        {
2270                $principals = array();
2271                for($x = 0; $x < 5 ; $x++)
2272                {
2273                        switch ($x) {
2274                                case 0:                             
2275                                        if( ($p = $this->getFolderPos($folders , $user )) || $p === 0 )
2276                                                $principals[] = $folders[$p];
2277                                        break;
2278                                case 1:
2279                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['drafts'])) )) || $p === 0 )
2280                                                $principals[] = $folders[$p];
2281                                        break;
2282                                case 2:
2283                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['sent'])) )) || $p === 0 )
2284                                                $principals[] = $folders[$p];
2285                                        break;
2286                                case 3:
2287                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['spam'])) )) || $p === 0 )
2288                                                $principals[] = $folders[$p];
2289                                        break;
2290                                case 4:
2291                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['trash'])) )) || $p === 0  )
2292                                                $principals[] = $folders[$p];                                           
2293                                        break;
2294                        }
2295                        if($p !== false)
2296                                unset($folders[$p]);
2297                }
2298                $folders = array_merge($principals, $folders);
2299        }
2300       
2301        /**
2302        * Retorna lista de pastas do usuario no padrão que a lib javascript espera.
2303        *
2304        * @license    http://www.gnu.org/copyleft/gpl.html GPL
2305        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2306        * @sponsor    Caixa Econômica Federal
2307        * @author     Cristiano Corrêa Schmidt
2308        * @access     public
2309        */
2310        function get_folders_list($params = null)
2311        {
2312                ///Define Variaveis
2313                $prefixShared = 'user'; //Prefixo das pastas compartilhadas
2314                $uid2cn = (isset($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'])) ? $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] : false;
2315                $mboxStream = $this->open_mbox(); //abre conexão imap
2316                $currentFolder = isset($params['folder']) ? $params['folder'] : 'INBOX';
2317                $folders = array();
2318                $return = array();
2319                ///////////////////////////////////////////////////////////////
2320                   
2321                if( isset($params['onload']) && $_SESSION['phpgw_info']['expressomail']['server']['certificado'])
2322                        $this->delete_mailbox(array('del_past' => 'INBOX'.$this->imap_delimiter.'decifradas')); //Deleta Pasta decifradas
2323               
2324                session_write_close(); // Free others requests
2325                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2326               
2327                if ( isset($params['noSharedFolders']) )
2328                        $folders_list = array_merge(imap_getmailboxes($mboxStream, $serverString, 'INBOX' ), imap_getmailboxes($mboxStream, $serverString, 'INBOX/*' ) );
2329                else
2330                        $folders_list = imap_getmailboxes($mboxStream, $serverString, '*' );
2331
2332                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
2333
2334                if (!is_array($folders_list)) return false;
2335                        if($uid2cn)
2336                                $this->ldap = new ldap_functions();
2337               
2338                foreach ($folders_list as $i => $v ) //Separando Pastas e informações
2339                {
2340                        $folderId = substr($v->name,(strpos($v->name , '}') + 1));
2341                        $nameArray = explode($this->imap_delimiter, $folderId);
2342                        $nameCount = count($nameArray);
2343                        $decifrada = mb_convert_encoding('INBOX'.$this->imap_delimiter.'decifradas','UTF7-IMAP','ISO-8859-1'); //Ignorar esta pasta decifrada
2344                        $parent = ($nameCount > 1 && $nameArray[($nameCount - 2)] !== 'INBOX') ? implode($this->imap_delimiter, array_slice($nameArray, 0, ($nameCount - 1))): ''; //Pega folder pai
2345                        if($nameArray[0] === 'user')
2346                                $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);
2347                        else if( $folderId !== $decifrada) //Escapa pasta decifrada
2348                                $folders['INBOX'][] =  array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes ,'name' => $nameArray[($nameCount-1)] , 'parent' => $parent);
2349                }
2350                unset($folders_list); //destroy array de objetos desnecessarios
2351                foreach($folders as $i => $v) //Ordenando e resgatando novas informações
2352                {
2353                        $this->orderDefaultFolders($folders[$i] , $i);  //Ordenando Pastas Padrões
2354                       
2355                        foreach ($folders[$i] as $ii => $vv)
2356                        {
2357                                $append = array();                             
2358                                $append['folder_id'] = mb_convert_encoding($vv['id'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA ID DAS PASTAS COM ACENTOS
2359                                $append['folder_name'] = (($uid2cn && isset($vv['user'])) && ($cn = $this->ldap->uid2cn($vv['user']))) ? $cn : $vv['name'];
2360                                $append['folder_name'] = mb_convert_encoding($append['folder_name'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA NOME DAS PASTAS COM ACENTOS
2361                                $status = imap_status($mboxStream, $vv['stream'], SA_UNSEEN); //Resgata Numero de mensagens não lidas
2362                                $append['folder_unseen'] = isset($status->unseen) ? $status->unseen : 0 ;
2363                                $append['folder_hasChildren'] = (($vv['attributes'] == 32) && ($vv['name'] != 'INBOX')) ? 1 : 0;
2364                                $append['folder_parent'] = mb_convert_encoding($vv['parent'],'ISO-8859-1','UTF7-IMAP');
2365                                $return[] = $append;
2366                        }
2367                }
2368               
2369                $quotaInfo =  (!isset($params['noQuotaInfo'])) ? $this->get_quota( array('folder_id' => $currentFolder)) : false; //VERIFICA SE O USUARIO TEM COTA
2370
2371                return ( ( is_array($quotaInfo) ) ?  array_merge($return, $quotaInfo) : $return );       
2372        }
2373   
2374
2375        function create_mailbox($arr)
2376        {
2377                $namebox        = $arr['newp'];
2378                $mbox_stream = $this->open_mbox();
2379                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2380                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
2381
2382                $result = "Ok";
2383                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
2384                {
2385                        $result = implode("<br />\n", imap_errors());
2386                }
2387
2388                if($mbox_stream)
2389                        imap_close($mbox_stream);
2390
2391                return $result;
2392
2393        }
2394
2395        function create_extra_mailbox($arr)
2396        {
2397                $nameboxs = explode(";",$arr['nw_folders']);
2398                $result = "";
2399                $mbox_stream = $this->open_mbox();
2400                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2401                foreach($nameboxs as $key=>$tmp){
2402                        if($tmp != ""){
2403                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
2404                                        $result = implode("<br />\n", imap_errors());
2405                                        if($mbox_stream)
2406                                                imap_close($mbox_stream);
2407                                        return $result;
2408                                }
2409                        }
2410                }
2411                if($mbox_stream)
2412                        imap_close($mbox_stream);
2413                return true;
2414        }
2415
2416        function delete_mailbox($arr)
2417        {
2418                $namebox = $arr['del_past'];
2419                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2420                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
2421                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
2422
2423                $result = "Ok";
2424                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2425                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2426                {
2427                        $result = implode("<br />\n", imap_errors());
2428                }
2429                /*
2430                if($mbox_stream)
2431                        imap_close($mbox_stream);
2432                */
2433                return $result;
2434        }
2435
2436        function ren_mailbox($arr)
2437        {
2438                $namebox = $arr['current'];
2439                $new_box = $arr['rename'];
2440                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2441                $mbox_stream = $this->open_mbox();
2442                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
2443
2444                $result = "Ok";
2445                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2446                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
2447
2448                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2449                {
2450                        $result = imap_errors();
2451                }
2452                if($mbox_stream)
2453                        imap_close($mbox_stream);
2454                return $result;
2455
2456        }
2457
2458        function get_num_msgs($params)
2459        {
2460                $folder = $params['folder'];
2461                if(!$this->mbox || !is_resource($this->mbox)) {
2462                        $this->mbox = $this->open_mbox($folder);
2463                        if(!$this->mbox || !is_resource($this->mbox))
2464                        return imap_last_error();
2465                }
2466                $num_msgs = imap_num_msg($this->mbox);
2467                if($this->mbox && is_resource($this->mbox))
2468                        imap_close($this->mbox);
2469
2470                return $num_msgs;
2471        }
2472
2473        function folder_exists($folder){
2474                $mbox =  $this->open_mbox();
2475                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2476                $list = imap_getmailboxes($mbox,$serverString, $folder);
2477                $return = is_array($list);             
2478                imap_close($mbox);
2479                return $return;
2480        }
2481       
2482        function send_mail($params)
2483        {
2484                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
2485                $mailService = ServiceLocator::getService('mail');
2486
2487                include_once("class.db_functions.inc.php");
2488                $db = new db_functions();
2489                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
2490                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
2491               
2492                ##
2493                # @AUTHOR Rodrigo Souza dos Santos
2494                # @DATE 2008/09/17$fileName
2495                # @BRIEF Checks if the user has permission to send an email with the email address used.
2496                ##
2497                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2498                {
2499                        $deny = true;
2500                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2501                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2502                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2503
2504                        if ( $deny )
2505                                return "The server denied your request to send a mail, you cannot use this mail address.";
2506                }           
2507
2508                $toaddress = $db->getAddrs(explode(',',$params['input_to']));//implode(',',);
2509                $ccaddress = $db->getAddrs(explode(',',$params['input_cc']));//implode(',',);
2510                $ccoaddress = $db->getAddrs(explode(',',$params['input_cco']));//implode(',',);
2511
2512                if($toaddress["False"] || $ccaddress["False"] || $ccoaddress["False"]){
2513                        return $this->parse_error("Invalid Mail:", ($toaddress["False"] ? $toaddress["False"] : ($ccaddress["False"] ? $ccaddress["False"] : $ccoaddress["False"])));
2514                }
2515               
2516                $toaddress = implode(',', $toaddress);
2517                $ccaddress = implode(',', $ccaddress);
2518                $ccoaddress = implode(',', $ccoaddress);
2519               
2520                if($toaddress == "" && $ccaddress == "" && $ccoaddress == ""){
2521                        return $this->parse_error("Invalid Mail:", ($params['input_to'] ? $params['input_to'] :($params['input_cc'] ? $params['input_cc'] : $params['input_cco'])) );
2522                }
2523
2524                $toaddress  = preg_replace('/<\s+/', '<', $toaddress);                 
2525                $toaddress  = preg_replace('/\s+>/', '>', $toaddress);
2526                       
2527                $ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
2528                $ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
2529               
2530                $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
2531                $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
2532               
2533                $replytoaddress = $params['input_replyto'];
2534                $subject = $params['input_subject'];
2535                $msg_uid = $params['msg_id'];
2536                $return_receipt = $params['input_return_receipt'];
2537                $is_important = $params['input_important_message'];
2538        $encrypt = $params['input_return_cripto'];
2539                $signed = $params['input_return_digital'];
2540
2541                $message_attachments = $params['message_attachments'];
2542                 
2543                if(substr($params['input_to'],-1) == ',')
2544                    $params['input_to'] = substr($params['input_to'],0,-1);
2545
2546                if(substr($params['input_cc'],-1) == ',')
2547                    $params['input_cc'] = substr($params['input_cc'],0,-1);
2548
2549                if(substr($params['input_cco'],-1) == ',')
2550                    $params['input_cco'] = substr($params['input_cco'],0,-1);
2551
2552                // Valida numero Maximo de Destinatarios
2553                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0)
2554                {
2555                    $sendersNumber = count(explode(',',$params['input_to']));
2556
2557                    if($params['input_cc'])
2558                        $sendersNumber +=  count(explode(',',$params['input_cc']));
2559                    if($params['input_cco'])
2560                        $sendersNumber +=  count(explode(',',$params['input_cco']));
2561
2562                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username);
2563                    if($userMaxmimumSenders)
2564                    {
2565                        if($sendersNumber > $userMaxmimumSenders)
2566                            return $this->functions->getLang('Number of recipients greater than allowed');
2567                    }
2568                    else
2569                    {
2570                        $ldap = new ldap_functions();
2571                        $groupsToUser = $ldap->get_user_groups($this->username);
2572
2573                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser);
2574
2575                        if($groupMaxmimumSenders > 0)
2576                        {
2577                            if($sendersNumber > $groupMaxmimumSenders)
2578                                return $this->functions->getLang('Number of recipients greater than allowed');
2579                        }
2580                        else
2581                        {
2582                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'])
2583                             return $this->functions->getLang('Number of recipients greater than allowed');
2584                        }
2585                    }
2586
2587                }
2588                //Fim Valida numero maximo de destinatarios
2589               
2590               
2591                //Valida envio de email para shared accounts
2592                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
2593                {
2594                    $ldap = new ldap_functions();
2595                    $arrayF = explode(';', $params['input_from']);
2596
2597                    /*
2598                     * Verifica se o remetente n?o ? uma conta compartilhada
2599                     */
2600                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
2601                    {
2602                        $groupsToUser = $ldap->get_user_groups($this->username);
2603                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
2604
2605                        /*
2606                         * Pega o UID do remetente
2607                         */
2608                        $uidFrom = $ldap->mail2uid($arrayF[1]);
2609
2610                         /*
2611                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
2612                         */
2613                        foreach ($sharedAccounts as $key => $value)
2614                        {
2615                            if($value)
2616                                 $acl = $this->getaclfrombox($value);
2617
2618                             if (array_key_exists($uidFrom, $acl))
2619                                 unset($sharedAccounts[$key]);
2620
2621                        }
2622
2623                        /*
2624                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
2625                         */
2626                        if(count($sharedAccounts) > 0)
2627                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
2628
2629                        /*
2630                         * Retorna as contas compartilhadas bloqueadas
2631                         */
2632                        if(count($accountsBlockeds) > 0)
2633                        {
2634                            $return = '';
2635
2636                            foreach ($accountsBlockeds as $accountBlocked)
2637                                $return.= $accountBlocked.', ';
2638
2639                             $return = substr($return,0,-2);
2640
2641                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
2642                        }
2643                    }
2644                }
2645                // Fim Valida envio de email para shared accounts
2646               
2647               
2648//          TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
2649            if($params['smime'] AND false)
2650        {
2651            $body = $params['smime'];
2652            $mail->SMIME = true;
2653            // A MSG assinada deve ser testada neste ponto.
2654            // Testar o certificado e a integridade da msg....
2655            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2656            $erros_acumulados = '';
2657            $certificado = new certificadoB();
2658            $validade = $certificado->verificar($body);
2659            if(!$validade)
2660            {
2661                foreach($certificado->erros_ssl as $linha_erro)
2662                {
2663                    $erros_acumulados .= $linha_erro;
2664                }
2665            }
2666            else
2667            {
2668                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2669                if ($certificado->apresentado)
2670                {
2671                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
2672                    $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;
2673                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
2674                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2675                }
2676                else
2677                {
2678                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2679                }
2680            }
2681            if(!$erros_acumulados =='')
2682            {
2683                return $erros_acumulados;
2684            }
2685        }
2686        else
2687        {
2688            //Compatibilização com Outlook, ao encaminhar a mensagem
2689                        $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
2690        }
2691
2692                $attachments = $_FILES;
2693                $forwarding_attachments = $params['forwarding_attachments'];
2694                $local_attachments = $params['local_attachments'];
2695
2696                //Test if must be saved in shared folder and change if necessary
2697                if( $fromaddress[2] == 'y' ){
2698                        //build shared folder path
2699                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2700                        if($this->folder_exists($newfolder))
2701                                $folder = $newfolder;
2702                        else
2703                                $folder = $params['folder'];
2704                       
2705                } else  {
2706                        $folder = $params['folder'];                   
2707                }
2708               
2709                $folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
2710                $folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
2711                $folder_name = $params['folder_name'];
2712
2713//              TODO - tratar assinatura e remover o AND false
2714                if($signed && !$params['smime'] AND false)
2715                {
2716            $mail->Mailer = "smime";
2717                        $mail->SignedBody = true;
2718                }
2719
2720
2721                if($fromaddress)
2722                        $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
2723               else
2724                        $mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
2725                //$mailService->addTo($toaddress);
2726                //$mailService->addCc($ccaddress);
2727                $bol = $this->add_recipients('to', $toaddress, $mailService);
2728                if(!$bol){
2729                        return $this->parse_error("Invalid Mail:", $toaddress);
2730                }
2731                $bol = $this->add_recipients('cc', $ccaddress, $mailService);
2732                if(!$bol){
2733                        return $this->parse_error("Invalid Mail:", $ccaddress);
2734                }
2735                $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy'];
2736                 
2737                if($allow)
2738                                {
2739                        //$mailService->addBcc($ccoaddress);
2740                        $bol = $this->add_recipients('cco', $ccoaddress, $mailService);
2741
2742                        if(!$bol){
2743                                return $this->parse_error("Invalid Mail:", $ccoaddress);
2744                        }
2745                }
2746
2747                //Implementação para o In-Reply-To e References                         
2748                $msg_numb = $params['messageNum'];
2749                $msg_folder = $params['messageFolder'];
2750                $this->mbox = $this->open_mbox($msg_folder);           
2751       
2752                $header = $this->get_header($msg_numb);
2753                $header_ = imap_fetchheader($this->mbox, $msg_numb, FT_UID);
2754                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
2755                if (preg_match($pattern, $header_, $fields))
2756                {
2757                        if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
2758                                $return['DispositionNotificationTo'] = "<".$matches[0].">";
2759                        }
2760                }
2761               
2762                $message_id = $header->message_id;
2763                $references = array();
2764                if($message_id != "")
2765                {
2766                   $mailService->addHeaderField('In-Reply-To',$message_id);
2767
2768                   if(isset($header->references)){
2769                        array_push($references, $header->references);
2770                   }           
2771                        array_push($references, $message_id);
2772                        $mailService->addHeaderField('References',$references);
2773
2774                }
2775       
2776
2777                $mailService->setSubject($subject);
2778                $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ?
2779                                                strtolower($params['type']) != 'plain' : true );
2780       
2781
2782//              TODO - tratar mensagem criptografada e remover o AND false abaixo
2783        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)      // a msg deve ser enviada cifrada...
2784                {
2785                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2786            $email = explode(",",$email);
2787            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2788            // Deve ser verificado um numero limite de destinatarios.
2789            // Deve ser verificado se os certificados sao validos.
2790            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2791            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2792            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2793            $erros_acumulados = "";
2794            $aux_mails = array();
2795            $mail_list = array();
2796            if(count($email) > $numero_maximo)
2797            {
2798                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2799                return $erros_acumulados;
2800            }
2801            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2802            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2803            foreach($email as $item)
2804            {
2805                $certificate = $db->get_certificate(strtolower($item));
2806                if(!$certificate)
2807                {
2808                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2809                    return $erros_acumulados;
2810                }
2811
2812                if (array_key_exists("dberr1", $certificate))
2813                {
2814
2815                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2816                    return $erros_acumulados;
2817                                }
2818                if (array_key_exists("dberr2", $certificate))
2819                {
2820                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2821                    //continue;
2822                }
2823                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2824                if (!array_key_exists("certs", $certificate))
2825                {
2826                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2827                    continue;
2828                }
2829            */
2830                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2831
2832                foreach ($certificate['certs'] as $registro)
2833                {
2834                    $c1 = new certificadoB();
2835                    $c1->certificado($registro['chave_publica']);
2836                    if ($c1->apresentado)
2837                    {
2838                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2839                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2840                        {
2841                            $aux_mails[] = $registro['chave_publica'];
2842                            $mail_list[] = strtolower($item);
2843                        }
2844                        else
2845                        {
2846                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2847                            {
2848                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2849                                    $c1->dados['EXPIRADO'],$c2->revogado);
2850                            }
2851
2852                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2853                            foreach($c2->erros_ssl as $linha)
2854                            {
2855                                $erros_acumulados .=  $linha . chr(0x0A);
2856                            }
2857                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2858                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2859                        }
2860                    }
2861                    else
2862                    {
2863                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2864                    }
2865                }
2866                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2867                                {
2868                                        return $erros_acumulados;
2869                        }
2870            }
2871
2872            $mail->Certs_crypt = $aux_mails;
2873        }
2874                                               
2875                if( count($forwarding_attachments) > 0 )// Build CID images
2876                        $this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body);
2877
2878                //      Build Uploading Attachments!!!
2879                if (count($attachments)>0) //Caso seja forward normal...
2880                {
2881                        $total_uploaded_size = 0;
2882                        foreach ($attachments as $attach)
2883                        {
2884                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2885                                    return $this->parse_error("message file too big");
2886                                if($attach['name']=='Unknown')
2887                                        continue;
2888                                $mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
2889                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2890                        }
2891                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
2892                        {
2893         
2894                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2895                            if( $total_uploaded_size > $upload_max_filesize)
2896                                return $this->parse_error("message file too big");
2897                        }
2898                }
2899                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2900
2901                        $total_uploaded_size = 0;
2902                       
2903                        foreach($local_attachments as $local_attachment) {
2904                                $file_description = unserialize(rawurldecode($local_attachment));
2905                                $tmp = array_values($file_description);
2906                                foreach($file_description as $i => $descriptor){
2907                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2908                                }
2909                                $mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
2910                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2911                        }
2912                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
2913                        {
2914                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2915                            if( $total_uploaded_size > $upload_max_filesize)
2916                                   return $this->parse_error("message file too big");
2917                        }
2918                }
2919
2920                //      Build Forwarding Attachments!!!
2921                if (count($forwarding_attachments) > 0)
2922                {
2923                        // Bug fixed for array_search function
2924                        $name_cid_files = array();
2925                        if(count($name_cid_files) > 0) {
2926                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2927                                $name_cid_files[0] = null;
2928                        }
2929
2930                        foreach($forwarding_attachments as $forwarding_attachment)
2931                        {
2932                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2933                               
2934                                foreach($file_description as $i => $item)
2935                                        $file_description[$i] = urldecode($item);
2936                               
2937                                $tmp = array_values($file_description);
2938                                foreach($file_description as $i => $descriptor){
2939                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2940                                }
2941                                $file_description = $tmp;
2942                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2943                                $fileName = $file_description[2];
2944                                if(!array_search(trim($fileName),$name_cid_files)) {
2945                                        $filename_dec = html_entity_decode(rawurldecode($fileName));
2946                                        $mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
2947
2948                                }
2949                        }
2950                }
2951               
2952                //Build Message Attachments!!!
2953                if(count($message_attachments) > 0 )
2954                {
2955                        foreach($message_attachments as $folder_name => $messages)
2956                        {
2957                                foreach ($messages as $message_number => $message_subject)
2958                                {
2959                                        if (!$message_subject)
2960                                                $message_subject  = 'no title.eml';
2961                                        else
2962                                                $message_subject .= '.eml';
2963                                       
2964                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
2965                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
2966                                        else{
2967                                                $mbox_stream = $this->open_mbox($folder_name);
2968                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
2969                                        }
2970                                                       
2971                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
2972                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
2973                                }
2974                        }
2975                }
2976               
2977                $message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
2978                $message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
2979               
2980                ////////////////////////////////////////////////////////////////////////////////////////////////////   
2981                /**
2982                * 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.
2983                 */
2984                $default_max_size_rule = $db->get_default_max_size_rule();     
2985                if(!$default_max_size_rule)
2986                {
2987                        $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 */
2988                }
2989                else
2990                {
2991                        foreach($default_max_size_rule as $i=>$value)
2992                        {               
2993                                $default_max_size_rule = $value['config_value'];
2994                        }                               
2995                }
2996               
2997                $default_max_size_rule = $default_max_size_rule * 1024 * 1024;            /* Tamanho da regra padrão, em bytes */
2998                $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];   
2999               
3000               
3001                $ldap = new ldap_functions();
3002                $groups_user = $ldap->get_user_groups($id_user);
3003
3004                $size_rule_by_group = array(); 
3005                foreach($groups_user as $k=>$value_)
3006                {       
3007                        $rule_in_group = $db->get_rule_by_user_in_groups($k);
3008                        if ($rule_in_group != "")
3009                                array_push($size_rule_by_group, $rule_in_group);
3010                }       
3011               
3012                $n_rule_groups = 0;
3013                $maior_valor_regra_grupo = 0;
3014                foreach($size_rule_by_group as $i=>$value)
3015                {
3016                        if(is_array($value[0]))
3017                        {
3018                                $n_rule_groups++;
3019                                if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
3020                                        $maior_valor_regra_grupo = $value[0]['email_max_recipient'];
3021                        }
3022                }
3023               
3024                if($default_max_size_rule)
3025                {
3026                        $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
3027
3028                        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. */
3029                        {
3030                                if($message_size_total > $default_max_size_rule)
3031                                        return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
3032                        }
3033
3034                        else
3035                        {
3036                                if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
3037                                {
3038                                        $regra_mais_permissiva = 0;
3039                                        foreach($size_rule as $i=>$value)
3040                                        {       
3041                                                if($regra_mais_permissiva < $value['email_max_recipient'])
3042                                                        $regra_mais_permissiva = $value['email_max_recipient'];
3043                                        }
3044                                        $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;                 
3045                                        if($message_size_total > $regra_mais_permissiva)
3046                                                return $this->functions->getLang("Message size greater than allowed (Rule By User)");
3047                                }
3048                                else /* Regra por grupo */
3049                                {               
3050                                        $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;                     
3051                                        if($message_size_total > $maior_valor_regra_grupo)
3052                                                return $this->functions->getLang("Message size greater than allowed (Rule By Group)"); 
3053                               
3054                               
3055                                }
3056                        }
3057                }
3058                /**
3059         * Fim da validação do tamanho da regra do tamanho de mensagem.
3060                 */
3061                 ////////////////////////////////////////////////////////////////////////////////////////////////////
3062               
3063               
3064               
3065               
3066               
3067                if($isHTML)
3068                        $mailService->setBodyHtml($body);
3069                else
3070                        $mailService->setBodyText($body);
3071
3072                if($is_important)
3073                        $mailService->addHeaderField('Importance','High');
3074
3075                if($return_receipt)
3076                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
3077
3078
3079                if ($folder != 'null'){
3080                        $mbox_stream = $this->open_mbox($folder);
3081                        @imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
3082                }
3083
3084                $sent = $mailService->send();
3085
3086                if($sent !== true)
3087                {
3088                        return $this->parse_error($sent);
3089                }
3090                else
3091                {
3092            if ($signed && !$params['smime'])
3093                        {
3094                                return $sent;
3095                        }
3096                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
3097                        {
3098                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3099                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
3100                                $now = date("d/m/y H:i:s");
3101                                $addrs = $toaddress.$ccaddress.$ccoaddress;
3102                                $sent = trim($sent);
3103                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
3104                        }
3105                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
3106                                $contacts = new dynamic_contacts();
3107                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
3108                                return array("success" => true, "new_contacts" => $new_contacts);
3109                        }
3110                        return array("success" => true);
3111                }
3112        }
3113       
3114       
3115        /**
3116        * @license   http://www.gnu.org/copyleft/gpl.html GPL
3117        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
3118        * @param     $mail email
3119        * @param     $msg_uid uid da mensagem
3120        * @param     $forwarding_attachments anexos
3121        */
3122
3123        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
3124        {
3125                //Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
3126                $pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';
3127                $cid_imgs = '';
3128                preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
3129                //-------------------------------------------------------------------//
3130
3131                $attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
3132
3133                foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
3134                        $desc = unserialize(rawurldecode($v));
3135                        $attPostions[$desc[3]] = $i;
3136                }
3137
3138                //Intera as imagens encontradas
3139                foreach($cid_imgs[6] as $j => $val)
3140        {               
3141                        $cid = base_convert(microtime().$j, 10, 36); //Gera um cid
3142                        $body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'"', $body ); //tira o src da imagem e coloca o cid.
3143                        $count    = strlen($cid_imgs[6][$j]);
3144                                       
3145                        $attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
3146                        $file_description = unserialize(rawurldecode($attach_img));
3147                       
3148                        if (is_array($file_description))
3149                                foreach($file_description as $i => $descriptor)                         
3150                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);
3151
3152                        // The image is not in the same mail?
3153                        if ($msg_uid != $cid_imgs[4][$j])
3154                        {
3155                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
3156                $fileContent = &$fa['binary'];
3157                                $fileName = $fa['name'];
3158                                $fileCode = $fa['encoding'];
3159                                $fileType =  $fa['type'];
3160                                $file_attached[0] = $cid_imgs[2][$j];
3161                                $file_attached[1] = $cid_imgs[4][$j];
3162                                $file_attached[2] = $fileName;
3163                                $file_attached[3] = '0.'.(string)($j+1);
3164                                $file_attached[4] = 'base64';
3165                                $file_attached[5] = strlen($fileContent); //Size of file
3166                                $file_attached[6] = $cid_imgs[6][$j];
3167                                $return_forward[] = $file_attached;
3168
3169                                if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
3170                                        unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
3171                               
3172                        }
3173                        else
3174                        {
3175                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
3176                                $fileName = $file_description[2];
3177                                $fileCode = $file_description[4];
3178                                $file_description[3] = '0.'.(string)($j+1);
3179                                $file_description[6] = $cid_imgs[6][$j];
3180                                $fileType = $this->get_file_type($file_description[2]);
3181                                unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
3182                                if (!empty($file_description))
3183                                {
3184                                        $file_description[5] = strlen($fileContent); //Size of file
3185                                        $return_forward[] = $file_description;
3186                                }
3187                        }
3188
3189                        if ($fileContent)
3190                                $mail->addStringImage($fileContent,$fileType,$fileName, $cid);                                 
3191                }
3192
3193                return $return_forward;
3194        }
3195        function add_recipients_cert($full_address)
3196        {
3197                $result = "";
3198                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
3199                foreach ($parse_address as $val)
3200                {
3201                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3202                        if ($val->mailbox == "INVALID_ADDRESS")
3203                                continue;
3204                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
3205                                continue;
3206                        if (empty($val->personal))
3207                                $result .= $val->mailbox."@".$val->host . ",";
3208                        else
3209                                $result .= $val->mailbox."@".$val->host . ",";
3210                }
3211
3212                return substr($result,0,-1);
3213        }
3214
3215        function add_recipients($recipient_type, $full_address, $mail, $mobile = false)
3216        {
3217                //remove a comma if is given two unexpected commas
3218                $full_address = preg_replace("/, ?,/",",",$full_address);
3219                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
3220
3221                $bolean = true;         
3222                foreach ($parse_address as $val)
3223                {
3224                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3225                        if ($val->mailbox == "INVALID_ADDRESS")
3226                                continue;
3227                        switch($recipient_type)
3228                        {
3229                                case "to":
3230                                        if($mobile){
3231                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
3232                                        }else{
3233                                                $mail->AddTo( ($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3234                                        }
3235                                        break;
3236                                case "cc":
3237                                        if($mobile){
3238                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
3239                                        }else{
3240                                                $mail->AddCC( ($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3241                                        }
3242                                        break;
3243                                case "cco":
3244                                        $mail->AddBcc(($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3245                                        break;
3246                        }
3247                        if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){
3248                                $bolean = false;
3249                        }
3250                }
3251                return $bolean;
3252        }
3253
3254        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
3255        {
3256            include_once dirname(__FILE__).'/class.attachment.inc.php';
3257            $attachment = new attachment();
3258                        $attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo.
3259            $attachment->setStructureFromMail($msg_folder, $msg_number);
3260            return $attachment->getAttachment($msg_part);
3261        }
3262
3263        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding)
3264        {
3265            include_once dirname(__FILE__).'/class.attachment.inc.php';
3266            $attachment = new attachment();
3267            $attachment->setStructureFromMail($msg_folder, $msg_number);
3268            $return = $attachment->getAttachmentInfo($msg_part);
3269            $return['binary'] = $attachment->getAttachment($msg_part);
3270            return $return;
3271        }
3272
3273        function del_last_caracter($string)
3274        {
3275                $string = substr($string,0,(strlen($string) - 1));
3276                return $string;
3277        }
3278
3279        function del_last_two_caracters($string)
3280        {
3281                $string = substr($string,0,(strlen($string) - 2));
3282                return $string;
3283        }
3284
3285        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
3286        {
3287                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
3288                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
3289                        foreach($imapsort as $iuid)
3290                                $sort[$iuid] = "";
3291                       
3292                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
3293                                $slice_array = false;
3294                        else
3295                                $slice_array = true;
3296                }
3297                else
3298                {
3299                        $sort = array();
3300                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
3301                        $num_msgs = imap_num_msg($this->mbox);
3302                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
3303                        $slice_array = true;
3304                 
3305                        for ($i=$num_msgs; $i>0; $i--)
3306                        {
3307                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
3308                                        break;
3309                                $iuid = @imap_uid($this->mbox,$i);
3310                                $header = $this->get_header($iuid);
3311                                // List UNSEEN messages.
3312                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
3313                                        continue;
3314                                }
3315                                // List SEEN messages.
3316                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
3317                                        continue;
3318                                }
3319                                // List ANSWERED messages.
3320                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
3321                                        continue;
3322                                }
3323                                // List FLAGGED messages.
3324                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
3325                                        continue;
3326                                }
3327
3328                                if($sort_box_type=='SORTFROM') {
3329                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
3330                                                $from = $header->to;
3331                                        else
3332                                                $from = $header->from;
3333                                        if(isset($from[0]->personal))
3334                                        $tmp = imap_mime_header_decode($from[0]->personal);
3335                                        else
3336                                                $tmp = null;
3337                                        if (isset($tmp[0]->text))
3338                                                $sort[$iuid] = $tmp[0]->text;
3339                                        else
3340                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
3341                                }
3342                                else if($sort_box_type=='SORTSUBJECT') {
3343                                        $sort[$iuid] = $header->subject;
3344                                }
3345                                else if($sort_box_type=='SORTSIZE') {
3346                                        $sort[$iuid] = $header->Size;
3347                                }
3348                                else {
3349                                        $sort[$iuid] = $header->udate;
3350                                }
3351
3352                        }
3353                        natcasesort($sort);
3354
3355                        if ($sort_box_reverse)
3356                                $sort = array_reverse($sort,true);
3357                }
3358                if(empty($sort) or !is_array($sort)){
3359                        $sort = array();
3360                }
3361               
3362                       
3363
3364
3365                if ($slice_array)
3366                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
3367
3368
3369                return $sort;
3370
3371        }
3372
3373        function move_delete_search_messages($params){
3374                $move = false;
3375                $msg_no_move = "";
3376       
3377                $params['selected_messages'] = urldecode($params['selected_messages_move']);
3378                $params['new_folder'] = urldecode($params['new_folder_move']);
3379                $params['new_folder_name'] = urldecode($params['new_folder_name_move']);
3380                $sel_msgs = explode(",", $params['selected_messages']);
3381                @reset($sel_msgs);
3382                $sorted_msgs = array();
3383                foreach($sel_msgs as $idx => $sel_msg) {
3384                        $sel_msg = explode(";", $sel_msg);
3385                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3386                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3387                         }
3388                         else {
3389                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3390                         }
3391                }               
3392                @ksort($sorted_msgs);
3393                $last_return = false;
3394                foreach($sorted_msgs as $folder => $msgs_number) {
3395                        $params['msgs_number'] = $msgs_number;
3396                        $params['folder'] = $folder;
3397                               
3398                        $last_return = $this->move_messages($params);
3399                       
3400                        if($last_return['status']){
3401                                $move = true;
3402                        }else{
3403                                $msg_no_move =  $params['msgs_number'];
3404                        }
3405                }
3406                $sel_msgs = null;               
3407                $params['selected_messages'] = urldecode($params['selected_messages_delete']);
3408                $params['new_folder'] = urldecode($params['new_folder_delete']);
3409                $params['new_folder_name'] = urldecode($params['new_folder_name_delete']);
3410                $sel_msgs = explode(",", $params['selected_messages']);
3411                @reset($sel_msgs);
3412                $sorted_msgs = array();
3413                foreach($sel_msgs as $idx => $sel_msg) {
3414                        $sel_msg = explode(";", $sel_msg);
3415                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3416                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3417                         }
3418                         else {
3419                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3420                         }
3421                }
3422                @ksort($sorted_msgs);
3423                $last_return = false;
3424                foreach($sorted_msgs as $folder => $msgs_number) {
3425                        $params['msgs_number'] = $msgs_number;
3426                        $params['folder'] = $folder;
3427               
3428                        $params['folder'] = $params['new_folder_delete'];
3429                        $last_return = $this->delete_msgs($params);
3430                        $last_return['deleted'] = true;
3431                        if($last_return['status']){
3432                                $move = true;
3433                        }else{
3434                                $msg_no_move =  $params['msgs_number'];
3435                        }
3436               
3437                }
3438       
3439                if($move)
3440                        $last_return['move'] = true;
3441                       
3442                if($msg_no_move != "")
3443                        $last_return['no_move'] = $msg_no_move;
3444               
3445                return $last_return;
3446        }
3447
3448        function move_search_messages($params){
3449                $params['selected_messages'] = str_replace('/',$this->imap_delimiter,urldecode($params['selected_messages']));
3450                $params['new_folder'] = str_replace('/',$this->imap_delimiter,urldecode($params['new_folder']));
3451                $params['new_folder_name'] = urldecode($params['new_folder_name']);
3452                $sel_msgs = explode(",", $params['selected_messages']);
3453                $move = false;
3454                $msg_no_move = "";
3455               
3456                @reset($sel_msgs);
3457                $sorted_msgs = array();
3458                foreach($sel_msgs as $idx => $sel_msg) {
3459                        $sel_msg = explode(";", $sel_msg);
3460                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3461                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3462                         }
3463                         else {
3464                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3465                         }
3466                }
3467                @ksort($sorted_msgs);
3468                $last_return = false;
3469                foreach($sorted_msgs as $folder => $msgs_number) {
3470                        $params['msgs_number'] = $msgs_number;
3471                        $params['folder'] = $folder;
3472                       
3473                if($params['delete'] === 'true'){
3474                        $params['folder'] = $params['new_folder'];
3475                        $last_return = $this->delete_msgs($params);
3476                                $last_return['deleted'] = true;
3477                       
3478                        if($last_return['status']){
3479                                $move = true;
3480                        }else{
3481                                $msg_no_move =  $params['msgs_number'];
3482                        }
3483                       
3484                }else{
3485                                $last_return = $this->move_messages($params);
3486                               
3487                                if($last_return['status']){
3488                                        $move = true;
3489                                }else{
3490                                        $msg_no_move =  $params['msgs_number'];
3491                        }
3492                }
3493                }
3494               
3495                if($move)
3496                        $last_return['move'] = true;
3497                       
3498                if($msg_no_move != "")
3499                        $last_return['no_move'] = $msg_no_move;
3500                       
3501                return $last_return;
3502        }
3503
3504        function move_messages($params)
3505        {
3506                $folder = $params['folder'];
3507                $mbox_stream = $this->open_mbox($folder);
3508                $newmailbox = ($params['new_folder']);
3509                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO-8859-1, UTF-8, UTF7-IMAP");
3510                $new_folder_name = $params['new_folder_name'];
3511                $msgs_number = $params['msgs_number'];
3512                $return = array('msgs_number' => $msgs_number,
3513                                                'folder' => $folder,
3514                                                'new_folder_name' => $new_folder_name,
3515                                                'border_ID' => $params['border_ID'],
3516                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
3517
3518                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
3519        if (substr($folder,0,4) == 'user'){
3520                $acl = $this->getacltouser($folder);
3521                /*
3522                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
3523                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
3524                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
3525                 *   w - write (STORE flags other than SEEN and DELETED)
3526                 *   i - insert (perform APPEND, COPY into mailbox)
3527                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
3528                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
3529                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
3530                 *   a - administer (perform SETACL)
3531                        */
3532                        if (strpos($acl, "d") === false){
3533                                $return['status'] = false;
3534                                return $return;
3535                        }
3536        }
3537        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
3538        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){
3539        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
3540            if (substr($new_folder_name,0,4) == 'user'){
3541                $this->ldap = new ldap_functions();
3542                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
3543                $return['new_folder_name'] = array_pop($tmp_folder_name);
3544                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
3545                {
3546                    $return['new_folder_name'] = $cn;
3547                }
3548            }
3549        }
3550                }
3551
3552                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
3553                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
3554                {
3555                        $return['previous_msg'] = $this->get_info_previous_msg($params);
3556                        // Fix problem in unserialize function JS.
3557                        if(array_key_exists('body', $return['previous_msg']))
3558                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
3559                }
3560
3561                $mbox_stream = $this->open_mbox($folder);
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 $return;
3567                }else {
3568                        if(strstr(imap_last_error(),'Over quota')) {
3569                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
3570                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
3571                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3572                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3573                                $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()))));
3574                                if(!$mbox)
3575                                        return imap_last_error();
3576                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
3577                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
3578                                        if($mbox_stream)
3579                                                imap_close($mbox_stream);
3580                                        if($mbox)
3581                                                imap_close($mbox);
3582                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
3583                                }
3584                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3585                                        imap_expunge($mbox_stream);
3586                                        if($mbox_stream)
3587                                                imap_close($mbox_stream);
3588                                        // return to original quota limit.
3589                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
3590                                                if($mbox)
3591                                                        imap_close($mbox);
3592                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
3593                                        }
3594                                        return $return;
3595                                }
3596                                else {
3597                                        if($mbox_stream)
3598                                                imap_close($mbox_stream);
3599                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
3600                                                if($mbox)
3601                                                        imap_close($mbox);
3602                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
3603                                        }
3604                                        return imap_last_error();
3605                                }
3606
3607                        }
3608                        else {
3609                                if($mbox_stream)
3610                                        imap_close($mbox_stream);
3611                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
3612                        }
3613                }
3614        }
3615
3616
3617        function save_msg($params)
3618        {
3619       
3620                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
3621                $mailService = ServiceLocator::getService('mail');
3622
3623                $return_receipt = $params['input_return_receipt'];
3624                $is_important = $params['input_important_message'];
3625               
3626                $msg_uid = $params['msg_id'];
3627                $body = $params['body'];
3628                $body = str_replace("%nbsp;","&nbsp;",$body);
3629                $body = preg_replace("/\n/"," ",$body);
3630                $body = preg_replace("/\r/","" ,$body);
3631                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
3632                $forwarding_attachments = $params['forwarding_attachments'];
3633                $message_attachments    = $params['message_attachments'];
3634                $attachments = $params['FILES'];
3635                $return_files = $params['FILES'];
3636                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
3637
3638                if(is_array($params['local_attachments'])){
3639                    foreach ($params['local_attachments'] as $key => $local_attach) {
3640                       $tmp = unserialize(urldecode($local_attach));
3641                           $attachments[$key]['name'] = urldecode($tmp[2]);
3642                           $return_files[$key]['name'] = urldecode($tmp[2]);
3643                    }
3644                }
3645
3646                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
3647                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
3648
3649                $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
3650                $mailService->addTo($params['input_to']);
3651                $mailService->addCc( $params['input_cc']);
3652                $mailService->addBcc($params['input_cco']);
3653                $mailService->setSubject($params['input_subject']);
3654
3655                if($is_important){
3656                        $mailService->addHeaderField('Importance','High');
3657                }
3658
3659                if($return_receipt)
3660                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
3661
3662                $isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
3663
3664               
3665                if( count($forwarding_attachments) > 0 )
3666                        $return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
3667                       
3668                //Build Message Attachments!!!
3669                if(count($message_attachments) > 0 )
3670                {
3671                        foreach($message_attachments as $folder_name => $messages)
3672                        {
3673                                foreach ($messages as $message_number => $message_subject)
3674                                {
3675                                        if (!$message_subject)
3676                                                $message_subject  = 'no title.eml';
3677                                        else
3678                                                $message_subject .= '.eml';
3679                                       
3680                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3681                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3682                                        else{
3683                                                $mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
3684                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
3685                                        }
3686                                                                                       
3687                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3688                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
3689                                }
3690                        }
3691                }
3692               
3693                $imagesParts = array();
3694
3695                if(count($return_forward) > 0 )
3696                foreach ($return_forward as $value)
3697                        $imagesParts[$value[6]] = $value[3];   
3698
3699                //Build Forwarding Attachments!!!
3700                if(count($forwarding_attachments) > 0 )
3701                {
3702                        foreach($forwarding_attachments as $forwarding_attachment)
3703                        {
3704
3705                                $file_description = unserialize(rawurldecode($forwarding_attachment));
3706                                foreach($file_description as $i => $item)
3707                                        $file_description[$i] = urldecode($item);                               
3708                       
3709                                $file_description = array_values($file_description);
3710                                       
3711                                foreach($file_description as $i => $descriptor)
3712                                                        $file_description[$i] = eregi_replace('\'*\'','',$descriptor);
3713                               
3714                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
3715                                $file_description[2] = html_entity_decode($file_description[2]);
3716
3717                                $file_description[5] = strlen($fileContent); //Size of file
3718                                $return_forward[] = $file_description;
3719                                $mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
3720                        }
3721                        }
3722
3723                if ((count($return_forward) > 0) && (count($return_files) > 0))
3724                        $return_files = array_merge_recursive($return_forward,$return_files);
3725                else if (count($return_files) < 1)
3726                                $return_files = $return_forward;
3727
3728                //Build Uploading Attachments!!!
3729                $sizeof_attachments = count($attachments);     
3730                if ($sizeof_attachments)
3731                        foreach ($attachments as $numb => $attach)
3732                                $mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
3733
3734
3735                if (!$body)
3736                        $body = ' ';
3737               
3738                if($isHTML)
3739                        $mailService->setBodyHtml($body);
3740                else
3741                        $mailService->setBodyText($body);
3742
3743
3744                $mbox_stream = $this->open_mbox($folder);
3745                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
3746
3747                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3748                $return['msg_no'] = $status->uidnext - 1;
3749                $return['folder_id'] = $folder;
3750                $return['imagesParts'] = $imagesParts;
3751
3752                if($mbox_stream)
3753                        imap_close($mbox_stream);
3754                       
3755                $returnFiles = array();                 
3756                $ii = 0;
3757                               
3758                if(count($return_files) > 0)
3759                {
3760                        foreach ($return_files as $index => $_attachment)
3761                        {
3762                                if (array_key_exists("name", $_attachment))
3763                                {
3764                                        $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment['name'], 'UTF-8', 'UTF-8, ISO-8859-1') );
3765                                        $returnFiles[$ii]['size'] = $_attachment['size'];
3766                                        $ii++;
3767                        }
3768                                else if($_attachment[2])
3769                        {
3770                                        $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment[2], 'UTF-8', 'UTF-8, ISO-8859-1'));
3771                                        $returnFiles[$ii]['size'] = $_attachment[5];         
3772                                        $ii++;
3773                        }
3774                }
3775                }
3776                $return['files'] = serialize($returnFiles);
3777                $return["subject"] = $params['input_subject'];
3778                if (!$return['append']) $return['append'] = imap_last_error();
3779                       
3780                return $return;
3781        }
3782
3783       
3784        function set_messages_flag_from_search($params){               
3785                $error = False;
3786                $fileNames = "";
3787               
3788                $sel_msgs = explode(",", $params['msg_to_flag']);
3789                @reset($sel_msgs);
3790                $sorted_msgs = array();
3791                foreach($sel_msgs as $idx => $sel_msg) {
3792                        $sel_msg = explode(";", $sel_msg);
3793                        if(array_key_exists($sel_msg[0], $sorted_msgs)){
3794                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3795                        }
3796                        else {
3797                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3798                        }
3799                }
3800                unset($sorted_msgs['']);                       
3801                $array_names_keys = array_keys($sorted_msgs);   
3802                // Verifica se as n mensagens selecionadas
3803                // se encontram em um mesmo folder
3804                if (count($sorted_msgs)==1){
3805                        $param['folder'] = $array_names_keys[0];
3806                        $param['msgs_to_set'] = $sorted_msgs[$array_names_keys[0]];
3807                        $param['flag'] = $params['flag'];
3808                        $returns[0] = $this->set_messages_flag($param);
3809                        return $returns;
3810                }else{
3811                        for($i = 0; $i < count($array_names_keys); $i++){
3812                                $param['folder'] = $array_names_keys[$i];
3813                                $param['msgs_to_set'] = $sorted_msgs[$array_names_keys[$i]];
3814                                $param['flag'] = $params['flag'];
3815                                $returns[$i] = $this->set_messages_flag($param);
3816                }
3817        }
3818        return $returns;
3819}
3820        function set_messages_flag($params)
3821        {               
3822                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
3823                $msgs_to_set = $params['msgs_to_set'];
3824                $flag = $params['flag'];
3825                $return = array();
3826                $return["msgs_to_set"] = $msgs_to_set;
3827                $return["flag"] = $flag;
3828                $return["msgs_not_to_set"] = "";
3829                       
3830                $this->mbox = $this->open_mbox($folder);
3831                       
3832                if ($flag == "unseen"){
3833                        $return["msgs_to_set"] = "";
3834                        $msgs = explode(",",$msgs_to_set);
3835                        foreach($msgs as $men){
3836                                if (imap_clearflag_full($this->mbox, $men, "\\Seen", ST_UID))
3837                                        $return["msgs_to_set"] .= $men.",";
3838                                else
3839                                        $return["msgs_not_to_set"] .= $men.",";
3840                        }
3841                        $return["status"] = true;
3842                }elseif ($flag == "seen"){
3843                        $return["msgs_to_set"] = "";
3844                        $msgs = explode(",",$msgs_to_set);
3845                        foreach($msgs as $men){
3846                                if (imap_setflag_full($this->mbox, $men, "\\Seen", ST_UID))
3847                                        $return["msgs_to_set"] .= $men.",";
3848                                else
3849                                        $return["msgs_not_to_set"] .= $men.",";
3850                        }
3851                        $return["status"] = true;
3852                }elseif ($flag == "answered"){
3853                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
3854                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
3855                }
3856                elseif ($flag == "forwarded")
3857                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
3858                elseif ($flag == "flagged")
3859                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
3860                elseif ($flag == "unflagged") {
3861                        $flag_importance = false;
3862                        $msgs_number = explode(",",$msgs_to_set);
3863                        $unflagged_msgs = "";
3864                        foreach($msgs_number as $msg_number) {
3865                                preg_match('/importance *: *(.*)\r/i',
3866                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3867                                        ,$importance);
3868                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3869                                        $flag_importance=true;
3870                                }
3871                                else {
3872                                        $unflagged_msgs.=$msg_number.",";
3873                                }
3874                        }
3875
3876                        if($unflagged_msgs!="") {
3877                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
3878                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
3879                        }
3880                        else {
3881                                $return["msgs_unflageds"] = false;
3882                        }
3883
3884                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3885                                $return["status"] = false;
3886                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
3887                        }
3888                        else {
3889                                $return["status"] = true;
3890                        }
3891                }
3892               
3893                if(($flag == "seen") || ($flag == "unseen")){
3894                        if ($return["msgs_not_to_set"] != ""){
3895                                $return["msgs_not_to_set"] = substr($return["msgs_not_to_set"], 0, -1);
3896                                $return["status"] = false;
3897                        }
3898                        if($return["msgs_to_set"] != ""){
3899                                $return["msgs_to_set"] = substr($return["msgs_to_set"], 0, -1);
3900                        }
3901                }
3902                if($this->mbox && is_resource($this->mbox))
3903                        imap_close($this->mbox);               
3904                return $return;
3905        }
3906
3907        function get_file_type($file_name)
3908        {
3909                $file_name = strtolower($file_name);
3910                $strFileType = strrev(substr(strrev($file_name),0,4));
3911                if ($strFileType == ".eml")
3912                        return "message/rfc822";
3913                if ($strFileType == ".asf")
3914                        return "video/x-ms-asf";
3915                if ($strFileType == ".avi")
3916                        return "video/avi";
3917                if ($strFileType == ".doc")
3918                        return "application/msword";
3919                if ($strFileType == ".zip")
3920                        return "application/zip";
3921                if ($strFileType == ".xls")
3922                        return "application/vnd.ms-excel";
3923                if ($strFileType == ".gif")
3924                        return "image/gif";
3925                if ($strFileType == ".jpg" || $strFileType == "jpeg")
3926                        return "image/jpeg";
3927                if ($strFileType == ".png")
3928                        return "image/png";
3929                if ($strFileType == ".wav")
3930                        return "audio/wav";
3931                if ($strFileType == ".mp3")
3932                        return "audio/mpeg3";
3933                if ($strFileType == ".mpg" || $strFileType == "mpeg")
3934                        return "video/mpeg";
3935                if ($strFileType == ".rtf")
3936                        return "application/rtf";
3937                if ($strFileType == ".htm" || $strFileType == "html")
3938                        return "text/html";
3939                if ($strFileType == ".xml")
3940                        return "text/xml";
3941                if ($strFileType == ".xsl")
3942                        return "text/xsl";
3943                if ($strFileType == ".css")
3944                        return "text/css";
3945                if ($strFileType == ".php")
3946                        return "text/php";
3947                if ($strFileType == ".asp")
3948                        return "text/asp";
3949                if ($strFileType == ".pdf")
3950                        return "application/pdf";
3951                if ($strFileType == ".txt")
3952                        return "text/plain";
3953                if ($strFileType == ".wmv")
3954                        return "video/x-ms-wmv";
3955                if ($strFileType == ".sxc")
3956                        return "application/vnd.sun.xml.calc";
3957                if ($strFileType == ".stc")
3958                        return "application/vnd.sun.xml.calc.template";
3959                if ($strFileType == ".sxd")
3960                        return "application/vnd.sun.xml.draw";
3961                if ($strFileType == ".std")
3962                        return "application/vnd.sun.xml.draw.template";
3963                if ($strFileType == ".sxi")
3964                        return "application/vnd.sun.xml.impress";
3965                if ($strFileType == ".sti")
3966                        return "application/vnd.sun.xml.impress.template";
3967                if ($strFileType == ".sxm")
3968                        return "application/vnd.sun.xml.math";
3969                if ($strFileType == ".sxw")
3970                        return "application/vnd.sun.xml.writer";
3971                if ($strFileType == ".sxq")
3972                        return "application/vnd.sun.xml.writer.global";
3973                if ($strFileType == ".stw")
3974                        return "application/vnd.sun.xml.writer.template";
3975
3976
3977                return "application/octet-stream";
3978        }
3979
3980        function htmlspecialchars_encode($str)
3981        {
3982                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
3983        }
3984        function htmlspecialchars_decode($str)
3985        {
3986                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
3987        }
3988
3989        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
3990        {
3991                if(!$this->mbox || !is_resource($this->mbox))
3992                        $this->mbox = $this->open_mbox($folder);
3993
3994                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
3995        }
3996
3997        function get_info_next_msg($params)
3998        {
3999                $msg_number = $params['msg_number'];
4000                $folder = $params['msg_folder'];
4001                $sort_box_type = $params['sort_box_type'];
4002                $sort_box_reverse = $params['sort_box_reverse'];
4003                $reuse_border = $params['reuse_border'];
4004                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
4005                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
4006
4007                $success = false;
4008                if (is_array($sort_array_msg))
4009                {
4010                        foreach ($sort_array_msg as $i => $value){
4011                                if ($value == $msg_number)
4012                                {
4013                                        $success = true;
4014                                        break;
4015                                }
4016                        }
4017                }
4018
4019                if (! $success || $i >= sizeof($sort_array_msg)-1)
4020                {
4021                        $params['status'] = 'false';
4022                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4023                        return $params;
4024                }
4025
4026                $params = array();
4027                $params['msg_number'] = $sort_array_msg[($i+1)];
4028                $params['msg_folder'] = $folder;
4029
4030                $return = $this->get_info_msg($params);
4031                $return["reuse_border"] = $reuse_border;
4032                return $return;
4033        }
4034
4035        function get_info_previous_msg($params)
4036        {
4037                $msg_number = $params['msgs_number'];
4038                $folder = $params['folder'];
4039                $sort_box_type = $params['sort_box_type'];
4040                $sort_box_reverse = $params['sort_box_reverse'];
4041                $reuse_border = $params['reuse_border'];
4042                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
4043                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
4044
4045                $success = false;
4046                if (is_array($sort_array_msg))
4047                {
4048                        foreach ($sort_array_msg as $i => $value){
4049                                if ($value == $msg_number)
4050                                {
4051                                        $success = true;
4052                                        break;
4053                                }
4054                        }
4055                }
4056                if (! $success || $i == 0)
4057                {
4058                        $params['status'] = 'false';
4059                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4060                        return $params;
4061                }
4062
4063                $params = array();
4064                $params['msg_number'] = $sort_array_msg[($i-1)];
4065                $params['msg_folder'] = $folder;
4066
4067                $return = $this->get_info_msg($params);
4068                $return["reuse_border"] = $reuse_border;
4069                return $return;
4070        }
4071
4072        // This function updates the values: quota, paging and new messages menu.
4073        function get_menu_values($params){
4074                $return_array = array();
4075                $return_array = $this->get_quota($params);
4076
4077                $mbox_stream = $this->open_mbox($params['folder']);
4078                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
4079                if($mbox_stream)
4080                        imap_close($mbox_stream);
4081
4082                return $return_array;
4083        }
4084
4085        function get_quota($params){
4086
4087                $folder_id = str_replace('/',$this->imap_delimiter,$params['folder_id']);
4088
4089                if(!$this->mbox || !is_resource($this->mbox))
4090                        $this->mbox = $this->open_mbox();
4091
4092                $quota = imap_get_quotaroot($this->mbox, $folder_id);
4093                if($this->mbox && is_resource($this->mbox))
4094                        imap_close($this->mbox);
4095
4096                if (!$quota){
4097                        return array(
4098                                'quota_percent' => 0,
4099                                'quota_used' => 0,
4100                                'quota_limit' =>  0
4101                        );
4102                }
4103
4104                if(count($quota) && $quota['limit']) {
4105                        $quota_limit = $quota['limit'];
4106                        $quota_used  = $quota['usage'];
4107                        if($quota_used >= $quota_limit)
4108                        {
4109                                $quotaPercent = 100;
4110                        }
4111                        else
4112                        {
4113                        $quotaPercent = ($quota_used / $quota_limit)*100;
4114                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
4115                        }
4116                        return array(
4117                                'quota_percent' => floor($quotaPercent),
4118                                'quota_used' => $quota_used,
4119                                'quota_limit' =>  $quota_limit
4120                        );
4121                }
4122                else
4123                        return array();
4124        }
4125
4126        function send_notification($params){
4127                include("../header.inc.php");
4128                require_once("class.phpmailer.php");
4129                $mail = new PHPMailer();
4130
4131                $toaddress = $params['notificationto'];
4132
4133                $subject = lang("Read receipt: %1",$params['subject']);
4134                $body = lang("Your message: %1",$params['subject']) . '<br>';
4135                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
4136                $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"));
4137                $mail->SMTPDebug = false;
4138                $mail->IsSMTP();
4139                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
4140                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
4141                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4142                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
4143                $mail->AddAddress($toaddress);
4144                $mail->Subject = $this->htmlspecialchars_decode($subject);
4145
4146                $mail->IsHTML(true);
4147                $mail->Body = $body;
4148
4149                if(!$mail->Send()){
4150                        return $mail->ErrorInfo;
4151                }
4152                else
4153                        return true;
4154        }
4155
4156        function empty_folder($params)
4157        {
4158                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
4159                $mbox_stream = $this->open_mbox($folder);
4160                $return = imap_delete($mbox_stream,'1:*');
4161                if($mbox_stream)
4162                        imap_close($mbox_stream, CL_EXPUNGE);
4163                return $return;
4164        }
4165
4166        function search($params)
4167        {
4168                include("class.imap_attachment.inc.php");
4169                $imap_attachment = new imap_attachment();
4170                $criteria = $params['criteria'];
4171                $return = array();
4172                $folders = $this->get_folders_list();
4173
4174                $j = 0;
4175                foreach($folders as $folder)
4176                {
4177                        $mbox_stream = $this->open_mbox($folder);
4178                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
4179
4180                        if ($messages == '')
4181                                continue;
4182
4183                        $i = 0;
4184                        $return[$j] = array();
4185                        $return[$j]['folder_name'] = $folder['name'];
4186
4187                        foreach($messages as $msg_number)
4188                        {
4189                                $header = $this->get_header($msg_number);
4190                                if (!is_object($header))
4191                                        return false;
4192
4193                                $return[$j][$i]['msg_folder']   = $folder['name'];
4194                                $return[$j][$i]['msg_number']   = $msg_number;
4195                                $return[$j][$i]['Recent']               = $header->Recent;
4196                                $return[$j][$i]['Unseen']               = $header->Unseen;
4197                                $return[$j][$i]['Answered']     = $header->Answered;
4198                                $return[$j][$i]['Deleted']              = $header->Deleted;
4199                                $return[$j][$i]['Draft']                = $header->Draft;
4200                                $return[$j][$i]['Flagged']              = $header->Flagged;
4201
4202                                $date_msg = gmdate("d/m/Y",$header->udate);
4203                                if (gmdate("d/m/Y") == $date_msg)
4204                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
4205                                else
4206                                        $return[$j][$i]['udate'] = $date_msg;
4207
4208                                $fromaddress = imap_mime_header_decode($header->fromaddress);
4209                                $return[$j][$i]['fromaddress'] = '';
4210                                foreach ($fromaddress as $tmp)
4211                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
4212
4213                                $from = $header->from;
4214                                $return[$j][$i]['from'] = array();
4215                                $tmp = imap_mime_header_decode($from[0]->personal);
4216                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
4217                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
4218                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
4219
4220                                $to = $header->to;
4221                                $return[$j][$i]['to'] = array();
4222                                $tmp = imap_mime_header_decode($to[0]->personal);
4223                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
4224                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
4225                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
4226
4227                                $subject = imap_mime_header_decode($header->fetchsubject);
4228                                $return[$j][$i]['subject'] = '';
4229                                foreach ($subject as $tmp)
4230                                        $return[$j][$i]['subject'] .= $tmp->text;
4231
4232                                $return[$j][$i]['Size'] = $header->Size;
4233                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
4234
4235                                $return[$j][$i]['attachment'] = array();
4236                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
4237
4238                                $i++;
4239                        }
4240                        $j++;
4241                        if($mbox_stream)
4242                                imap_close($mbox_stream);
4243                }
4244
4245                return $return;
4246        }
4247
4248
4249        function mobile_search($params)
4250        {
4251                include("class.imap_attachment.inc.php");
4252                $imap_attachment = new imap_attachment();
4253                $criterias = array ("TO","SUBJECT","FROM","CC");
4254                $return = array();
4255                if(!isset($params['folder'])) {
4256                        $folder_params = array("noSharedFolders"=>1);
4257                        if(isset($params['folderType']))
4258                                $folder_params['folderType'] = $params['folderType'];
4259                        $folders = $this->get_folders_list($folder_params);
4260                }
4261                else
4262                        $folders = array(0=>array('folder_id'=>$params['folder']));
4263                $num_msgs = 0;
4264                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
4265                $return["msgs"] = array();
4266               
4267                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
4268                foreach($folders as $id =>$folder)
4269                {
4270                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
4271                                foreach($criterias as $criteria_fixed)
4272                                {
4273                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
4274
4275                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
4276
4277                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
4278                                       
4279                                        if ($messages == ''){
4280                                                if($mbox_stream)
4281                                                        imap_close($mbox_stream);
4282                                                continue;       
4283                                        }
4284                                       
4285                                        foreach($messages as $msg_number)
4286                                        {
4287                                                $temp = $this->get_info_head_msg($msg_number);
4288                                                if(!$temp)
4289                                                        return false;
4290                                                $temp['msg_folder'] = $folder['folder_id'];
4291                                                $return["msgs"][$num_msgs] = $temp;
4292                                                $num_msgs++;
4293                                        }
4294
4295                                        if($mbox_stream)
4296                                                imap_close($mbox_stream);
4297                                }
4298                        }
4299                }
4300
4301                if(!function_exists("cmp_date")) {
4302                        function cmp_date($obj1, $obj2){
4303                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
4304                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
4305                        }
4306                }
4307                usort($return["msgs"], "cmp_date");
4308                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
4309                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
4310                $return["msgs"]['num_msgs'] = $num_msgs;
4311               
4312                return $return;
4313        }
4314
4315        function delete_and_show_previous_message($params)
4316        {
4317                $return = $this->get_info_previous_msg($params);
4318
4319                $params_tmp1 = array();
4320                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
4321                $params_tmp1['folder'] = $params['msg_folder'];
4322                $return_tmp1 = $this->delete_msg($params_tmp1);
4323
4324                $return['msg_number_deleted'] = $return_tmp1;
4325
4326                return $return;
4327        }
4328
4329
4330        function automatic_trash_cleanness($params)
4331        {
4332                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
4333                $criteria =  'BEFORE "'.$before_date.'"';
4334                //$mbox_stream = $this->open_mbox('INBOX'.$this->folders['trash']);
4335                $mbox_stream = $this->open_mbox($this->mount_url_folder(array("INBOX",$this->folders['trash'])));
4336               
4337                // Free others requests
4338                session_write_close();
4339                $messages = imap_search($mbox_stream, $criteria, SE_UID);
4340                if (is_array($messages)){
4341                        foreach ($messages as $msg_number){
4342                                imap_delete($mbox_stream, $msg_number, FT_UID);
4343                        }
4344                }
4345                if($mbox_stream)
4346                        imap_close($mbox_stream, CL_EXPUNGE);
4347                return $messages;
4348        }
4349//      Fix the search problem with special characters!!!!
4350        function remove_accents($string) {
4351                return strtr($string,
4352                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
4353                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
4354        }
4355
4356        function make_search_date($date,$before = false){
4357
4358            //TODO: Adaptar a data de acordo com o locale do sistema.
4359            list($day,$month,$year) = explode("/", $date);
4360            $before?$day=(int)$day+1:$day=(int)$day;
4361            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
4362            $search_date = date('d-M-Y',$timestamp);
4363            return $search_date;
4364
4365        }
4366
4367        function search_msg( $params = false )
4368        {
4369       
4370               
4371                if(strpos($params['condition'],"#")===false)
4372                { //local messages
4373                        $search=false;
4374                }
4375                else
4376                {
4377                        $search = explode(",",$params['condition']);
4378                }
4379               
4380                $params['page'] = $params['page'] * 1;
4381
4382            if( is_array($search) )
4383            {
4384                        $search = array_unique($search); // Remove duplicated folders
4385                        $search_criteria = '';
4386                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
4387                        foreach($search as $tmp)
4388                        {
4389                                $tmp1 = explode("##",$tmp);
4390                                $sum = 0;
4391                                $name_box = $tmp1[0];
4392                                unset($filter);
4393                                foreach($tmp1 as $index => $criteria)
4394                                {
4395                                        if ($index != 0 && strlen($criteria) != 0)
4396                                        {
4397                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
4398                                                $filter .= " ".$filter_array[0];
4399                                                if (strlen($filter_array[1]) != 0)
4400                                                {
4401                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
4402                                                                 trim($filter_array[0]) != 'SINCE' &&
4403                                                                 trim($filter_array[0]) != 'ON')
4404                                                        {
4405                                                            $filter .= '"'.$filter_array[1].'"';
4406                                                        }else if(trim($filter_array[0]) == 'BEFORE' ){
4407                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
4408                                                        }else{
4409                                                            $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
4410                                                        }
4411                                                }
4412                                        }
4413                                }
4414                               
4415                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
4416                                $filter = $this->remove_accents($filter);
4417
4418                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
4419                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
4420                                {
4421                                        $folder_name = explode($this->imap_delimiter,$name_box);
4422                                        $this->ldap = new ldap_functions();
4423                                       
4424                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
4425                                        {
4426                                                $folder_name[1] = $cn;
4427                                        }
4428                                        $folder_name = implode($this->imap_delimiter,$folder_name);
4429                                }
4430                                else
4431                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
4432                               
4433       
4434                                $this->open_mbox($name_box);
4435
4436                                if (preg_match("/^.?\bALL\b/", $filter))
4437                                {
4438                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
4439                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
4440                                           
4441                                        foreach($all_criterias as $criteria_fixed)
4442                                        {
4443                                                $_filter = $criteria_fixed . substr($filter,4);
4444                                               
4445                                                $search_criteria = imap_search($this->mbox, $_filter, SE_UID);
4446                                               
4447                                                if(is_array($search_criteria))
4448                                                {
4449                                                        foreach($search_criteria as $new_search)
4450                                                        {
4451                                                                $elem = $this->get_info_head_msg($new_search);
4452                                                                $elem['udate']       = gmdate('d/m/Y', $elem['udate'] + $this->functions->CalculateDateOffset());
4453                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
4454                                                                $elem['uid'] = $new_search;
4455                                                                /* compare dates in ordering */
4456                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
4457                                                                $retorno[] = $elem;
4458                                                        }
4459                                                }
4460                                        }
4461                                }
4462                                else{
4463                                        $search_criteria = imap_search($this->mbox, $filter, SE_UID);
4464                                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
4465                                    {
4466                                        if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
4467                                        {
4468                                            $num_msgs = imap_num_msg($this->mbox);
4469                                            $flagged_msgs = array();
4470                                            for ($i=$num_msgs; $i>0; $i--)
4471                                            {
4472                                                $iuid = @imap_uid($this->mbox,$i);
4473                                                $header = $this->get_header($iuid);
4474                                                if(trim($header->Flagged))
4475                                                {
4476                                                        $flagged_msgs[$i] = $iuid;
4477                                                }
4478                                            }
4479                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
4480                                            {
4481                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
4482                                                    foreach($arry_diff as $msg)
4483                                            {
4484                                                        $search_criteria[] = $msg;
4485                                            }
4486                                        }
4487                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
4488                                        {
4489                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
4490                                        }
4491                                    }
4492                                    }
4493
4494                                    if( is_array( $search_criteria) )
4495                                    {
4496                                        foreach($search_criteria as $new_search)
4497                                        {                                   
4498                                            $elem = $this->get_info_head_msg( $new_search );
4499                                            $elem['udate']       = gmdate('d/m/Y', $elem['udate'] + $this->functions->CalculateDateOffset());
4500                                            $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
4501                                            $elem['uid'] = $new_search;
4502                                            /* compare dates in ordering */
4503                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);                                                 
4504                                            $retorno[] = $elem;
4505                                        }
4506                                    }
4507                                }
4508                        }
4509                }
4510               
4511            imap_close($this->mbox);
4512            $num_msgs = count($retorno);
4513            /* Comparison functions, descendent is ascendent with parms inverted */
4514            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
4515            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
4516
4517            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
4518            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
4519
4520            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
4521            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
4522
4523            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
4524            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
4525
4526            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
4527            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
4528
4529            usort( $retorno, $params['sort_type']);
4530            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
4531           
4532            $arrayRetorno['num_msgs']   =  $num_msgs;
4533            $arrayRetorno['data']               =  $pageret;
4534            $arrayRetorno['currentTab'] =  $params['current_tab'];
4535
4536            return ($pageret) ? $arrayRetorno : 'none';
4537        }
4538
4539        function size_msg($size){
4540                $var = floor($size/1024);
4541                if($var >= 1){
4542                        return $var." kb";
4543                }else{
4544                        return $size ." b";
4545                }
4546        }
4547       
4548        function ob_array($the_object)
4549        {
4550           $the_array=array();
4551           if(!is_scalar($the_object))
4552           {
4553               foreach($the_object as $id => $object)
4554               {
4555                   if(is_scalar($object))
4556                   {
4557                       $the_array[$id]=$object;
4558                   }
4559                   else
4560                   {
4561                       $the_array[$id]=$this->ob_array($object);
4562                   }
4563               }
4564               return $the_array;
4565           }
4566           else
4567           {
4568               return $the_object;
4569           }
4570        }
4571
4572        function getacl()
4573        {
4574                $this->ldap = new ldap_functions();
4575
4576                $return = array();
4577                $mbox_stream = $this->open_mbox();
4578                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
4579
4580                $i = 0;
4581                foreach ($mbox_acl as $user => $acl)
4582                {
4583                        if ($user != $this->username)
4584                        {
4585                                $return[$i]['uid'] = $user;
4586                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
4587                        }
4588                        $i++;
4589                }
4590                return $return;
4591        }
4592
4593        function setacl($params)
4594        {
4595                $old_users = $this->getacl();
4596                if (!count($old_users))
4597                        $old_users = array();
4598
4599                $tmp_array = array();
4600                foreach ($old_users as $index => $user_info)
4601                {
4602                        $tmp_array[$index] = $user_info['uid'];
4603                }
4604                $old_users = $tmp_array;
4605
4606                $users = unserialize($params['users']);
4607                if (!count($users))
4608                        $users = array();
4609
4610                //$add_share = array_diff($users, $old_users);
4611                $remove_share = array_diff($old_users, $users);
4612
4613                $mbox_stream = $this->open_mbox();
4614
4615                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4616                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4617
4618                /*if (count($add_share))
4619                {
4620                        foreach ($add_share as $index=>$uid)
4621                        {
4622                        if (is_array($mailboxes_list))
4623                        {
4624                        foreach ($mailboxes_list as $key => $val)
4625                        {
4626                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4627                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
4628                        }
4629                        }
4630                        }
4631                }*/
4632
4633                if (count($remove_share))
4634                {
4635                        foreach ($remove_share as $index=>$uid)
4636                        {
4637                            if (is_array($mailboxes_list))
4638                            {
4639                                foreach ($mailboxes_list as $key => $val)
4640                                {
4641                                    $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4642                                    $folder = str_replace("&-", "&", $folder);
4643                                    imap_setacl ($mbox_stream, $folder, "$uid", "");
4644                                }
4645                            }
4646                        }
4647                }
4648
4649                return true;
4650        }
4651
4652        function getaclfromuser($params)
4653        {
4654                $useracl = $params['user'];
4655
4656                $return = array();
4657                $return[$useracl] = 'false';
4658                $mbox_stream = $this->open_mbox();
4659                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
4660
4661                foreach ($mbox_acl as $user => $acl)
4662                {
4663                        if (($user != $this->username) && ($user == $useracl))
4664                        {
4665                                $return[$user] = $acl;
4666                        }
4667                }
4668                return $return;
4669        }
4670
4671        function getacltouser($user)
4672        {
4673                $return = array();
4674                $mbox_stream = $this->open_mbox();
4675                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4676                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
4677                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
4678                if(substr($user,0,4) != 'user')
4679                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4680                else
4681                  $mbox_acl = @imap_getacl($mbox_stream, $user);
4682                if(isset($mbox_acl[$this->username]))
4683                return $mbox_acl[$this->username];
4684                else
4685                    return '';
4686        }
4687
4688
4689        function setaclfromuser($params)
4690        {
4691                $user = $params['user'];
4692                $acl = $params['acl'];
4693
4694                $mbox_stream = $this->open_mbox();
4695
4696                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4697                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4698
4699                if (is_array($mailboxes_list))
4700                {
4701                        foreach ($mailboxes_list as $key => $val)
4702                        {
4703                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
4704                                $folder = str_replace("&-", "&", $folder);
4705                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
4706                                {
4707                                        $return = imap_last_error();
4708                                }
4709                        }
4710                }
4711                if (isset($return))
4712                        return $return;
4713                else
4714                        return true;
4715        }
4716
4717        function download_attachment($msg,$msgno)
4718        {
4719                $array_parts_attachments = array();
4720                //$array_parts_attachments['names'] = '';
4721                include_once("class.imap_attachment.inc.php");
4722                $imap_attachment = new imap_attachment();
4723
4724                if (count($msg->fname[$msgno]) > 0)
4725                {
4726                        $i = 0;
4727                        foreach ($msg->fname[$msgno] as $index=>$fname)
4728                        {
4729                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
4730                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
4731                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
4732                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
4733                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
4734                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
4735                                $i++;
4736                        }
4737                }
4738                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
4739                return $array_parts_attachments;
4740        }
4741
4742       
4743        /**
4744        * @license   http://www.gnu.org/copyleft/gpl.html GPL
4745        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
4746        * @param     $params
4747        */
4748        function spam($params)
4749        {
4750               
4751                $mbox_stream = $this->open_mbox($params['folder']);
4752                $msgs_number = explode(',',$params['msgs_number']);
4753
4754                $user = Array();
4755
4756                if(substr($params['folder'], 0, 4) == 'user')
4757                {
4758                    $ldapObject = new ldap_functions();
4759
4760                    $folderArray = Array();
4761                    $folderArray = explode($this->imap_delimiter, $params['folder']);
4762
4763                    $user['name'] = $folderArray[1];
4764                    $user['email'] = $ldapObject->getMailByUid($user['name']);
4765               
4766                }
4767                else
4768                {
4769                    $user['name'] = $this->username;
4770                    $user['email'] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4771                }
4772
4773                foreach($msgs_number as $msg_number)
4774                {
4775                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
4776                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
4777                        $body = imap_body($mbox_stream, $imap_msg_number);
4778                        $msg = $header . $body;
4779                        strtok($user['email'], '@');
4780                        $domain = strtok('@');
4781
4782           
4783
4784                        //Encontrar a assinatura do dspam no cabecalho
4785                        $v = explode("\r\n", $header);
4786                        foreach ($v as $linha){
4787                                if (eregi("^Message-ID", $linha)) {
4788                                        $args = explode(" ", $linha);
4789                                        $msg_id = "'$args[1]'";
4790                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
4791                                        $args = explode(" ",$linha);
4792                                        $signature = $args[1];
4793                                }
4794                        }
4795
4796                        // Seleciona qual comando a ser executado
4797                        switch($params['spam']){
4798                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
4799                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
4800                        }
4801
4802                     
4803                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
4804                        $cmd = str_replace($tags, array($user['email'], $user['name'], $domain, $signature, $msg_id), $cmd);
4805                       
4806                        system($cmd);
4807                }
4808
4809                imap_close($mbox_stream);
4810                return false;
4811        }
4812       
4813       
4814/**
4815* Descrição do método
4816*
4817* @license    http://www.gnu.org/copyleft/gpl.html GPL
4818* @author     
4819* @sponsor    Caixa Econômica Federal
4820* @author     
4821* @param      <tipo> <$msg_number> <Número da mensagem>
4822* @return     <cabeçalho da mensagem>
4823* @access     <public>
4824*/     
4825        function get_header($msg_number)
4826        {
4827                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
4828                if (!is_object($header))
4829                        return false;
4830
4831                if($header->Flagged != "F" ) {
4832                        $flag = preg_match('/importance *: *(.*)\r/i',
4833                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
4834                                                ,$importance);
4835                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
4836                }
4837
4838                return $header;
4839        }
4840
4841//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
4842///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.
4843
4844
4845    function insert_email($source,$folder,$timestamp,$flags){
4846               
4847        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
4848        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
4849        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
4850        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
4851        $imap_options = '/notls/novalidate-cert';
4852
4853       
4854        $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
4855
4856        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
4857       
4858        if(imap_last_error() === 'Mailbox already exists')
4859            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
4860        if($timestamp){
4861                        $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local)
4862                        $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.
4863                        /* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */
4864                        $file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
4865               
4866                $f = fopen($file,"w");
4867                fputs($f,base64_encode($source));
4868            fclose($f);
4869            $command = "python ".dirname(__FILE__)."/../imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
4870            $return['command']= exec($command);
4871        }else{
4872            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
4873        }
4874        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
4875                       
4876        $return['msg_no'] = $status->uidnext - 1;
4877        $return['error'] = imap_last_error();
4878        if(!$return['error'] && $flags != '' ){
4879
4880                  $flags_array=explode(':',$flags);
4881                  //"Answered","Draft","Flagged","Unseen"
4882                  $flags_fixed = "";
4883                  if($flags_array[0] == 'A')
4884                        $flags_fixed.="\\Answered ";
4885                  if($flags_array[1] == 'X')
4886                        $flags_fixed.="\\Draft ";
4887                  if($flags_array[2] == 'F')
4888                        $flags_fixed.="\\Flagged ";
4889                  if($flags_array[3] != 'U')
4890                        $flags_fixed.="\\Seen ";
4891                  if($flags_array[4] == 'F')
4892                        $flags_fixed.="\\Answered \\Draft ";
4893                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
4894                }
4895       
4896        //Ignorando erro de AUTH=Plain
4897        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN')
4898            $return['error'] = false;
4899                               
4900        if($mbox_stream)
4901            imap_close($mbox_stream);
4902        return $return;
4903    }
4904
4905        function show_decript($params,$dec=0){
4906        $source = $params['source'];
4907                 
4908        //error_log("source: $source\nversao: " . PHP_VERSION);         
4909        if ($dec == 0)
4910        {
4911            $source = str_replace(" ", "+", $source,$i);
4912                        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
4913                            if(!$source = base64_decode($source,true))
4914                    return "error ".$source."Espaï¿?os ".$i;
4915                 
4916                        }
4917                        else {
4918                            if(!$source = base64_decode($source))
4919                    return "error ".$source."Espaï¿?os ".$i;
4920            }
4921        }
4922
4923        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4924
4925                $get['msg_number'] = $insert['msg_no'];
4926                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
4927                $return = $this->get_info_msg($get);
4928                $get['msg_number'] = $params['ID'];
4929                $get['msg_folder'] = $params['folder'];
4930                $tmp = $this->get_info_msg($get);
4931                if(!$tmp['status_get_msg_info'])
4932                {
4933                        $return['msg_day']=$tmp['msg_day'];
4934                        $return['msg_hour']=$tmp['msg_hour'];
4935                        $return['fulldate']=$tmp['fulldate'];
4936                        $return['smalldate']=$tmp['smalldate'];
4937                }
4938                else
4939                {
4940                        $return['msg_day']='';
4941                        $return['msg_hour']='';
4942                        $return['fulldate']='';
4943                        $return['smalldate']='';
4944                }
4945        $return['msg_no'] =$insert['msg_no'];
4946        $return['error'] = $insert['error'];
4947        $return['folder'] = $params['folder'];
4948        //$return['acls'] = $insert['acls'];
4949        $return['original_ID'] =  $params['ID'];
4950
4951        return $return;
4952
4953    }
4954
4955//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
4956//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
4957
4958    function treat_base64_from_post($source){
4959            $offset = 0;
4960            do
4961            {
4962                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
4963                    {
4964                            $inicio = strpos($source, "\n\r", $inicio);
4965                            $fim = strpos($source, '--', $inicio);
4966                            if(!$fim)
4967                                    $fim = strpos($source,"\n\r", $inicio);
4968                            $length = $fim-$inicio;
4969                            $parte = substr( $source,$inicio,$length-1);
4970                            $parte = str_replace(" ", "+", $parte);
4971                            $source = substr_replace($source, $parte, $inicio, $length-1);
4972                    }
4973                    if($offset > $inicio)
4974                    $offset=FALSE;
4975                    else
4976                    $offset = $inicio;
4977            }
4978            while($offset);
4979            return $source;
4980    }
4981
4982//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.
4983
4984    function unarchive_mail($params)
4985    {           
4986        $dest_folder = $params['folder'];
4987        $sources = explode("#@#@#@",$params['source']);
4988        //Add user timeszone
4989        $timestamps = explode("#@#@#@",$params['timestamp']);
4990
4991
4992        $flags = explode("#@#@#@",$params['flags']);
4993               
4994                foreach($sources as $index=>$src) {
4995                        if($src!=""){
4996                $source = $this->treat_base64_from_post($src);
4997                $timestampsactual = $timestamps[$index] + $this->functions->CalculateDateOffset();
4998                        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestampsactual,$flags[$index]);
4999            }
5000        }
5001        return $insert;
5002    }
5003
5004    function download_all_local_attachments($params)
5005    {
5006        $source = $params['source'];
5007        $source = $this->treat_base64_from_post($source);
5008        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5009        $exporteml = new ExportEml();
5010        $params['num_msg']=$insert['msg_no'];
5011        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
5012        return $exporteml->download_all_attachments($params);
5013    }
5014       
5015        /**
5016         * Método que envia um email reportando um erro no email do usuário
5017         * @license http://www.gnu.org/copyleft/gpl.html GPL
5018         * @author Prognus Software Livre (http://www.prognus.com.br)
5019         */ 
5020        function report_mail_error($params)
5021        {       
5022                $params = $params['params'];
5023                $array_params = explode(";;", $params);
5024                $id_msg   = $array_params[0];
5025                $msg_user = $array_params[1];
5026               
5027                if($msg_user == '')
5028                        $msg_user = "Sem mensagem!";
5029                         
5030                $toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
5031                 
5032                $exporteml    = new ExportEml();
5033                $mail_content = $exporteml->export_msg_data($id_msg, $msg_folder);
5034                $this->open_mbox($msg_folder); 
5035                $title = "Erro de email reportado";
5036                $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>" .
5037                                "$msg_user</body><br><br><hr>";
5038                             
5039                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
5040                $mailService = ServiceLocator::getService('mail');     
5041                $mailService->addStringAttachment($mail_content, 'report.eml', 'application/text');
5042                $mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body);
5043        }
5044       
5045        function array_msort($array, $cols)
5046        {
5047                $colarr = array();
5048                foreach ($cols as $col => $order) {
5049                        $colarr[$col] = array();
5050                        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
5051                }
5052                $params = array();
5053                foreach ($cols as $col => $order) {
5054                        $params[] =& $colarr[$col];
5055                        $params = array_merge($params, (array)$order);
5056                }
5057                call_user_func_array('array_multisort', $params);
5058                $ret = array();
5059                $keys = array();
5060                $first = true;
5061                foreach ($colarr as $col => $arr) {
5062                        foreach ($arr as $k => $v) {
5063                                if ($first) { $keys[$k] = substr($k,1); }
5064                                $k = $keys[$k];
5065                                if (!isset($ret[$k])) $ret[$k] = $array[$k];
5066                                $ret[$k][$col] = $array[$k][$col];
5067                        }
5068                        $first = false;
5069                }
5070               
5071                return $ret;
5072
5073        }
5074       
5075        function parseCriteriaSearchMail($search)
5076        {
5077            $criteria = '';
5078            $searchArray = explode(' ', $search);
5079
5080            foreach ($searchArray as $v)
5081                if(trim($v) !== '' )
5082                    $criteria .= 'TEXT "'.$v.'" ' ;
5083           
5084            return $criteria;
5085        }
5086       
5087        function quickSearchMail( $params )
5088        {
5089                $return = array();
5090                $return['folder'] = $params['folder'];
5091                if(!is_array($params['folder']))
5092                        $params['folder'] = array( $params['folder'] );
5093               
5094                if(!isset($params['sort']))
5095                        $params['sort'] = 'SORTDATE_REVERSE';
5096                               
5097                $params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
5098               
5099                $i = 0;         
5100                if(!isset($params['page'])) $params['page'] = 0;
5101                $end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));       
5102                $ini = $end - $this->prefs['max_email_per_page'] ;
5103                $count = 0;
5104               
5105                $search = $this->parseCriteriaSearchMail($params['search']);
5106                               
5107                foreach ($params['folder'] as $folder)
5108                {
5109                        $imap = $this->open_mbox( $folder ) ;
5110                        $msgIds = imap_sort( $imap , SORTDATE , 1 , SE_UID , $search ,'UTF-8');
5111                                               
5112                        $count += count($msgIds); 
5113                       
5114                        foreach ($msgIds as $ii => $v)
5115                        {                               
5116                                $msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) );
5117                                $return['msgs'][$i]['from'] = '';
5118                               
5119                                $from = $msg->from[0]->mailbox;
5120                                if($msg->from[0]->personal != "")
5121                                        $from = $msg->from[0]->personal;
5122                                $return['msgs'][$i]['from']     = mb_convert_encoding($this->decode_string($from), 'UTF-8');
5123                               
5124                                $return['msgs'][$i]['subject'] = ' ';
5125                               
5126                                $subject = imap_mime_header_decode($msg->subject);
5127                                foreach ($subject as $tmp)
5128                                        $return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
5129                               
5130                               
5131                                $return['msgs'][$i]['flag'] = ' ';
5132                                $return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
5133                                $return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';       
5134                                $return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';     
5135                                $return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : ''; 
5136                                $return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';   
5137                                $return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';     
5138                               
5139                                $return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset());
5140                                $return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2);
5141                            $return['msgs'][$i]['date'] =   $msg->udate;
5142                                $return['msgs'][$i]['size'] =  $msg->Size;
5143                                $return['msgs'][$i]['boxname'] = $folder;
5144                                $return['msgs'][$i]['uid'] = $v;
5145                                $i++;
5146                        }       
5147                }
5148               
5149                $return['num_msgs'] = $count;
5150               
5151                if(!isset($return['msgs']))
5152                        $return['msgs'] = array();
5153               
5154                define('SORTBOX', 69);
5155                define('SORTWHO', 2);
5156                define('SORTBOX_REVERSE', 69);
5157                define('SORTWHO_REVERSE', 2);
5158                define('SORTDATE_REVERSE', 0);
5159                define('SORTSUBJECT_REVERSE', 3);
5160                define('SORTSIZE_REVERSE', 6);
5161               
5162                switch (constant( $params['sort'] )){
5163                        case 0 : $sA = 'date'; break;
5164                        case 2 : $sA = 'from'; break;
5165                        case 69 : $sA = 'boxname'; break;
5166                        case 3 : $sA = 'subject'; break;
5167                        case 6 : $sA = 'size'; break;
5168        }
5169       
5170                       
5171                if($params['sort'] !== 'SORTDATE_REVERSE')
5172                if(strpos($params['sort'],'REVERSE') !== false)
5173                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_DESC));
5174                        else
5175                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
5176               
5177                $k = -1;
5178                $nMsgs = array();
5179               
5180                foreach ($return['msgs'] as $v)
5181                {               
5182                        $k++;
5183                        if($k < $ini || $k >= $end ) continue;                 
5184                        $nMsgs[] = $v;
5185                }
5186                $return['msgs'] = $nMsgs;
5187               
5188                $return = json_encode($return);         
5189                $return = base64_encode($return);
5190       
5191                return $return;
5192        }
5193       
5194    function get_quota_folders(){
5195
5196            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
5197            include_once("class.imapfp.inc.php");           
5198            $imapfp = new imapfp();
5199
5200            if(!$imapfp->open($this->imap_server,$this->imap_port))
5201                    return $imapfp->get_error();             
5202            if (!$imapfp->login( $this->username,$this->password ))
5203                    return $imapfp->get_error();
5204
5205            $response_array = $imapfp->get_mailboxes_size();
5206            if ($imapfp->error)
5207                    return $imapfp->get_error();
5208
5209            $data = array();
5210            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
5211            $data["quota_root"] = $quota_root;
5212
5213            foreach ($response_array as $idx=>$line) {
5214                    $line2 = str_replace('"', "", $line);
5215                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
5216                    list($folder,$size) = explode(";",$line2);
5217                    $quota_used = str_replace(")","",$size);
5218                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
5219                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
5220                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
5221                            $folder = $this->functions->getLang("Inbox");
5222                    }
5223                    else
5224                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
5225
5226                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
5227            }
5228            $imapfp->close();
5229            return $data;
5230    } 
5231   
5232    function getaclfrombox($mail)
5233        {
5234                $mailArray = explode('@', $mail);
5235                $boxacl = $mailArray[0];
5236                $return = array();
5237
5238                if(!$this->mbox)
5239                     $this->open_mbox();
5240
5241                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl);
5242
5243                foreach ($mbox_acl as $user => $acl)
5244                {
5245                        if ($user != $boxacl )
5246                            $return[$user] = $acl;
5247                }
5248                return $return;
5249        }
5250}
5251?>
Note: See TracBrowser for help on using the repository browser.