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

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