source: sandbox/2.4.1-1/expressoMail1_2/inc/class.imap_functions.inc.php @ 6350

Revision 6350, 207.8 KB checked in by marcosw, 12 years ago (diff)

Ticket #2764 - Insersão do método self::decodeMimeString() para fazer o decode da string subject

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