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

Revision 8097, 221.4 KB checked in by marcosw, 11 years ago (diff)

Ticket #3428 - Correção ao exportar mensagens locais

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