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

Revision 6808, 209.1 KB checked in by eduardow, 12 years ago (diff)

Ticket #2961 - Exibindo warning erro com php versão 5.3.3-7.

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