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

Revision 5541, 209.9 KB checked in by adriano, 12 years ago (diff)

Ticket #2486 - correcoes de erros nas funcionalidades de marcadores e de sinalizadores de mensagens

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