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

Revision 5079, 160.3 KB checked in by airton, 13 years ago (diff)

Ticket #2266 - Atualizar documentacao dos arquivos PHP

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