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

Revision 5184, 200.8 KB checked in by clairson, 12 years ago (diff)

Ticket #2324 - Eroo ao desarquivar uma mensagem da pasta local com flag encaminhada

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