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

Revision 6133, 205.5 KB checked in by gustavo, 12 years ago (diff)

Ticket #2705 - No momento em que o usuario anexa um arquivo superior ao tamanho especificado

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