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

Revision 5689, 201.6 KB checked in by thiago, 12 years ago (diff)

Ticket #2486 - Correção de abrir os e-mails pela model de alarme ou conclusão.

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