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

Revision 5740, 203.9 KB checked in by thiago, 12 years ago (diff)

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

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