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

Revision 7907, 219.1 KB checked in by marcosw, 11 years ago (diff)

Ticket #3331 - Melhoria inserida no repositório trunk

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