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

Revision 5375, 200.5 KB checked in by cristiano, 12 years ago (diff)

Ticket #2424 - Adicionado codigo para remover tag LINK da apresentação do email

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