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

Revision 6866, 207.9 KB checked in by eduardow, 12 years ago (diff)

Ticket #2980 - Reportar erro em mensagem gera anexo de mensagem inválido.

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