source: sandbox/expresso-solr/expressoMail1_2/inc/class.imap_functions.inc.php @ 8056

Revision 8056, 230.3 KB checked in by gustavo, 11 years ago (diff)

Ticket #000 - Commit contendo o expresso com solr funcionando corretamente

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