source: sandbox/2.4.2-expresso2/expressoMail1_2/inc/class.imap_functions.inc.php @ 6900

Revision 6900, 210.6 KB checked in by gustavo, 12 years ago (diff)

Ticket #2971 - Edicao de pastas compartilhadas na propria arvore de pastas

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