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

Revision 5520, 202.7 KB checked in by gustavo, 12 years ago (diff)

Ticket #2484 - Melhorias na estrutura de diretórios do ExpressoMail?

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