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

Revision 5787, 202.7 KB checked in by thiago, 12 years ago (diff)

Ticket #2556 - Quantidade de mensagens para anexo não está sendo exibida.

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