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

Revision 6178, 205.6 KB checked in by cristiano, 12 years ago (diff)

Ticket #2728 - Corrigida expressão regular que identifica anexos

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