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

Revision 6333, 206.6 KB checked in by natan, 12 years ago (diff)

Ticket #2808 - Problema na navegação em mensagens de pastas acentuadas - Corrigido

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