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

Revision 5490, 201.4 KB checked in by gustavo, 12 years ago (diff)

Ticket #2484 - Melhorias na estrutura de diretórios do ExpressoMail?

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