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

Revision 5509, 202.1 KB checked in by gustavo, 12 years ago (diff)

Ticket #2488 - Adicionar cabecalho de licenca em arquivos que nao o possuem

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