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

Revision 7414, 216.3 KB checked in by marcosw, 12 years ago (diff)

Ticket #3088 - Realização de merge da melhoria do MailArchiver?

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