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

Revision 5742, 202.8 KB checked in by thiago, 12 years ago (diff)

Ticket #2486 - funcionalidade de recuperação dos labels e acompanhamentos pelo php.

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