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

Revision 5482, 200.0 KB checked in by cristiano, 12 years ago (diff)

Ticket #2482 - Corrigida expressão regular que indentifica anexos

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