source: branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php @ 8232

Revision 8232, 224.4 KB checked in by douglas, 10 years ago (diff)

Ticket #0000 - Copiadas as alterações do Trunk. Versão final 2.5.1.

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