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

Revision 7551, 217.0 KB checked in by angelo, 11 years ago (diff)

Ticket #3197 - Reduzir tempo de carregamento do modulo Expresso MailexpressoMail1_2/js/draw_api.min.js

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