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

Revision 7603, 217.0 KB checked in by douglasz, 11 years ago (diff)

Ticket #3216 - Problemas ao excluir a primeira mensagem da segunda paginação em diante.

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