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

Revision 5783, 202.6 KB checked in by wmerlotto, 12 years ago (diff)

Ticket #2398 - Mais algumas correções para compatibilização com PHP-5.3.x

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