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

Revision 5372, 200.7 KB checked in by cristiano, 12 years ago (diff)

Ticket #2440 - Correção de bugs set de flag seen automatica , tradução

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