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

Revision 6185, 205.7 KB checked in by marcieli, 12 years ago (diff)

Ticket #2731 - Corrigido listar destinatários no title da coluna Para da pasta Enviados.

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