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

Revision 6936, 207.9 KB checked in by eduardow, 12 years ago (diff)

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

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