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

Revision 6922, 207.7 KB checked in by marcosw, 12 years ago (diff)

Ticket #2989 - Correção do horário na janela filtro por remetente

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