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

Revision 5435, 200.6 KB checked in by cristiano, 12 years ago (diff)

Ticket #2424 - Mensagem alterando o layout, adicionado interação dos blocos style

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