source: branches/2.4/expressoMail1_2/inc/class.imap_functions.inc.php @ 7050

Revision 7050, 209.2 KB checked in by eduardow, 12 years ago (diff)

Ticket #3025 - Correção para exibição correta de mensagem ao remover.

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