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

Revision 6265, 206.1 KB checked in by cristiano, 12 years ago (diff)

Ticket #2773 - Caracteres indevidos na identificação de nome de mensagens em anexo

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