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

Revision 6120, 205.4 KB checked in by airton, 12 years ago (diff)

Ticket #2701 - Inconsistencia na opcao de redirecionar emails da caixa de entrada na tela de filtros de mensagens

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