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

Revision 8167, 224.3 KB checked in by cristiano, 11 years ago (diff)

Ticket #3456 - Otimizacao e implementacao de habilitar/desabilitar funcionalidades no ExpressoMail?

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