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

Revision 6430, 202.3 KB checked in by cristiano, 12 years ago (diff)

Ticket #2839 - Inconsistência ao abrir email de confirmação de agendamento

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