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

Revision 5745, 202.7 KB checked in by cristiano, 12 years ago (diff)

Ticket #2469 - Trocada regex que limpa o css e problemas com envio de email em text/plain

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