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

Revision 7067, 210.8 KB checked in by marcosw, 12 years ago (diff)

Ticket #3053 - Realizado atualização de permissões IMAP para mover/excluir

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