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

Revision 5620, 201.5 KB checked in by cristiano, 12 years ago (diff)

Ticket #2497 - Nova estrategia para o salvamento automatico de rascunhos

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