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

Revision 7673, 217.3 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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