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

Revision 8098, 221.6 KB checked in by marcieli, 11 years ago (diff)

Ticket #3429 - Corrigida inconsistencia na exibicao da flag importante nas msgs retornadas da busca avancada.

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