source: branches/2.4/expressoMail1_2/inc/class.imap_functions.inc.php @ 6520

Revision 6520, 204.0 KB checked in by eduardow, 12 years ago (diff)

Ticket #2857 - Realizado reparo no código atualizado.

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