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

Revision 7674, 217.3 KB checked in by angelo, 11 years ago (diff)

Ticket #3246 - Problema com a navegacao entre mensagens atraves de atalhos

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