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

Revision 1035, 122.3 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #558 - Adicionada funcionalidade de assinatura e criptografia de e-mails.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
RevLine 
[2]1<?php
2include_once("class.functions.inc.php");
3include_once("class.ldap_functions.inc.php");
[91]4include_once("class.exporteml.inc.php");
5
[2]6class imap_functions
7{
8        var $public_functions = array
[449]9        (       
[2]10                'get_range_msgs'                                => True,
11                'get_info_msg'                                  => True,
[689]12                'get_info_msgs'                                 => True,
[615]13                'get_folders_list'                              => True,
14                'import_msgs'                                   => True
[2]15        );
16
17        var $ldap;
18        var $mbox;
19        var $imap_port;
20        var $has_cid;
21        var $imap_options = '';
22        var $functions;
[650]23        var $foldersLimit;
[2]24
25        function imap_functions (){
[650]26                $this->foldersLimit = 200; //Limit of folders (mailboxes) user can see
[2]27                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
28                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
29                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
30                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
31                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
[449]32                $this->functions          = new functions();           
[2]33                $this->has_cid = false;
[449]34               
[2]35                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
36                {
37                        $this->imap_options = '/tls/novalidate-cert';
38                }
39                else
40                {
41                        $this->imap_options = '/notls/novalidate-cert';
42                }
43        }
44        // BEGIN of functions.
45        function open_mbox($folder = False)
46        {
[828]47                if (is_resource($this->mbox))
48                        return $this->mbox;
[51]49                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[504]50                $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()))));
[2]51                return $this->mbox;
52         }
53
[504]54        function parse_error($error){
55                // This error is returned from Imap.
56                if(strstr($error,'Connection refused')) {
57                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
58                }
59                // This error is returned from Postfix.
60                elseif(strstr($error,'message file too big')) {
61                        return str_replace("%1", ini_get('upload_max_filesize'),$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));                 
62                }
[628]63                elseif(strstr($error,'virus')) {
64                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
65                }
[504]66                // This condition verifies if SESSION is expired.
67                elseif(!count($_SESSION))                       
68                        return "nosession";
69
70                return $error;
71        }
72       
[2]73        function get_range_msgs2($params)
74        {
[53]75                $folder = $params['folder'];
[2]76                $msg_range_begin = $params['msg_range_begin'];
77                $msg_range_end = $params['msg_range_end'];
[449]78                $sort_box_type = $params['sort_box_type'];             
[53]79                $sort_box_reverse = $params['sort_box_reverse'];
[51]80                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]81                $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
[449]82               
[2]83                $return = array();
84                $i = 0;
[828]85                $num_msgs = imap_num_msg($this->mbox);
86                if(is_array($sort_array_msg)){
87                        foreach($sort_array_msg as $msg_number => $value)
[689]88                        {
89                                $temp = $this->get_info_head_msg($msg_number);
90                                if(!$temp)
91                                        return false;
[828]92
[689]93                                $return[$i] = $temp;
94                                $i++;
95                        }
96                }
[828]97                $return['num_msgs'] = $num_msgs;
98
[689]99                return $return;
100        }
[828]101
[689]102        function get_info_head_msg($msg_number) {
103                $head_array = array();
104                include_once("class.imap_attachment.inc.php");
105                $imap_attachment = new imap_attachment();
[828]106
[830]107
108
[828]109                /*Como eu preciso do atributo Importance para saber se o email é
110                 * importante ou não, uso abaixo a função imap_fetchheader e busco
111                 * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
112                 * duas vezes e de duas formas diferentes, mas em contrapartida, eu
113                 * não preciso reimplementar o método utilizando o fetchheader.
114                 * Como as mensagens são renderizadas em um número pequeno por vez,
115                 * não parece ter perda considerável de performance.
116                 */
[689]117                $flag = preg_match('/importance *: *(.*)\r/i',
[828]118                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number)),
119                        $importance);
[689]120                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
121
[828]122
[689]123                $header = $this->get_header($msg_number);
[828]124                if (!is_object($header))
125                        return false;
[689]126                $head_array['Recent'] = $header->Recent;
127                $head_array['Unseen'] = $header->Unseen;
128                if($header->Answered =='A' && $header->Draft == 'X'){
129                        $head_array['Forwarded'] = 'F';
[2]130                }
[689]131                else {
132                        $head_array['Answered'] = $header->Answered;
[828]133                        $head_array['Draft']    = $header->Draft;
[46]134                }
[689]135                $head_array['Deleted'] = $header->Deleted;
136                $head_array['Flagged'] = $header->Flagged;
[828]137
[689]138                $head_array['msg_number'] = $msg_number;
[828]139                //$head_array['msg_folder'] = $folder;
140
[693]141                $date_msg = gmdate("d/m/Y",$header->udate);
[872]142                if ( date("d/m/Y") == $date_msg)
[693]143                        $head_array['udate'] = gmdate("H:i",$header->udate);
[689]144                else
[872]145                {
[689]146                        $head_array['udate'] = $date_msg;
[872]147                        if ( date("d/m/Y", time() - 86400) == gmdate("d/m/Y",$header->udate) )
148                                $head_array['udate'] = $this -> functions -> getLang( 'Yesterday' );
149                        if ( date("d/m/Y", time() - 172800) == gmdate("d/m/Y",$header->udate) )
150                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
151                        if ( date("d/m/Y", time() - 259200) == gmdate("d/m/Y",$header->udate) )
152                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
153                }
[828]154
[689]155                $head_array['aux_date'] = $date_msg; //Auxiliar apenas para mensagens locais.
[828]156
[689]157                $from = $header->from;
158                $head_array['from'] = array();
159                $tmp = imap_mime_header_decode($from[0]->personal);
160                $head_array['from']['name'] = $this->decode_string($tmp[0]->text);
161                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
162                if(!$head_array['from']['name'])
163                        $head_array['from']['name'] = $head_array['from']['email'];
164                $to = $header->to;
165                $head_array['to'] = array();
166                $tmp = imap_mime_header_decode($to[0]->personal);
167                $head_array['to']['name'] = $this->decode_string($this->decode_string($tmp[0]->text));
168                $head_array['to']['email'] = $this->decode_string($to[0]->mailbox) . "@" . $to[0]->host;
169                if(!$head_array['to']['name'])
170                        $head_array['to']['name'] = $head_array['to']['email'];
171                $head_array['subject'] = $this->decode_string($header->fetchsubject);
[828]172
[689]173                $head_array['Size'] = $header->Size;
[828]174
[689]175                $head_array['attachment'] = array();
176                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[828]177
[689]178                return $head_array;
[2]179        }
[828]180
[2]181        function decode_string($string)
[449]182        {       
[2]183                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
184                {
185                        $tmp = imap_mime_header_decode($string);
186                        foreach ($tmp as $tmp1)
187                                $return .= $this->htmlspecialchars_encode($tmp1->text);
188                        return $return;
189                }
190                else if (strpos(strtolower($string), '=?utf-8') !== false)
191                {
192                        $elements = imap_mime_header_decode($string);
193                        for($i = 0;$i < count($elements);$i++) {
194                                $charset = $elements[$i]->charset;
195                                $text =$elements[$i]->text;
196                                if(!strcasecmp($charset, "utf-8") ||
197                                !strcasecmp($charset, "utf-7")) {
198                                $text = iconv($charset, "ISO-8859-1", $text);
199                        }
200                                $decoded .= $this->htmlspecialchars_encode($text);
201                        }
202                        return $decoded;
203                }
204                else
205                        return $this->htmlspecialchars_encode($string);
206        }
[615]207        /**
208        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
209        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
210        */
[1000]211/**
212        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
213        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
214        */
[660]215        function import_msgs($params) {
[1000]216                if(!$this->mbox)
[660]217                        $this->mbox = $this->open_mbox();
[1000]218
219                if( preg_match('/local_/',$params["folder"]) )
220                {
221
222                        $tmp_box = mb_convert_encoding('INBOX/Lixeira/tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
223                        if ( ! imap_createmailbox( $this -> mbox,"{".$this -> imap_server."}$tmp_box" ) )
224                                return $this->functions->getLang( 'Import to Local : fail...' );
225                        imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
226                        $params["folder"] = $tmp_box;
227                }
[615]228                $errors = array();
229                $invalid_format = false;
[660]230                $filename = $params['FILES'][0]['name'];
231                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
232                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
233                        return array( 'error' => $this->functions->getLang("fail in import:").
[1000]234                                                        " ".$this->functions->getLang("Over quota"));
[660]235                }
[615]236                if(substr($filename,strlen($filename)-4)==".zip") {
[660]237                        $zip = zip_open($params['FILES'][0]['tmp_name']);
[615]238
239                        if ($zip) {
240                                while ($zip_entry = zip_read($zip)) {
[1000]241
[615]242                                        if (zip_entry_open($zip, $zip_entry, "r")) {
243                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
244                                                $status = @imap_append($this->mbox,
[660]245                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
[615]246                                                                        $email
247                                                                        );
248                                                if(!$status)
249                                                        array_push($errors,zip_entry_name($zip_entry));
250                                                zip_entry_close($zip_entry);
251                                        }
252                                }
[660]253                                zip_close($zip);
[615]254                        }
[1000]255
256                        if ( isset( $tmp_box ) && ! sizeof( $errors ) )
257                        {
258
259                                $mc = imap_check($this->mbox);
260
261                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
262
263                                $ids = array( );
264                                foreach ($result as $overview)
265                                        $ids[ ] = $overview -> uid;
266
267                                return implode( ',', $ids );
[830]268                        }
[1000]269                        }
[615]270                else if(substr($filename,strlen($filename)-4)==".eml") {
[660]271                        $email = implode("",file($params['FILES'][0]['tmp_name']));
[615]272                        $status = @imap_append($this->mbox,
[660]273                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
[615]274                                                                        $email
275                                                                        );
[660]276                        if(!$status){
[615]277                                array_push($errors,zip_entry_name($zip_entry));
[660]278                                zip_entry_close($zip_entry);
279                        }
[615]280                }
[1000]281                else
[615]282                {
[1000]283                        if ( isset( $tmp_box ) )
284                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
285
[660]286                        return array("error" => $this->functions->getLang("wrong file format"));
[615]287                        $invalid_format = true;
288                }
[1000]289
[615]290                if(!$invalid_format) {
291                        if(count($errors)>0) {
[660]292                                $message = $this->functions->getLang("fail in import:")."\n";
[615]293                                foreach($errors as $arquivo) {
294                                        $message.=$arquivo."\n";
295                                }
[660]296                                return array("error" => $message);
[615]297                        }
298                        else
[1000]299                                return $this->functions->getLang("The import was executed successfully.");
[615]300                }
[1000]301        }
302        /*
[613]303                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
304                a primeira parte do e-mail, que é o texto, sem anexos.
305                O método considera que o email é multpart.
306        */
307        function remove_attachments($params) {
308                include_once("class.message_components.inc.php");
309                if(!$this->mbox || !is_resource($this->mbox))
310                        $this->mbox = $this->open_mbox($params["folder"]);
311                $return["status"] = true;
312                $return["msg_num"] = $params["msg_num"];
313                $header = "";
314               
315                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
316                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
317                        $head1 = explode(":",$head);
318                        if ( (strtoupper($head1[0]) == strtoupper("to")) ||
319                                        (strtoupper($head1[0]) == strtoupper("from")) ||
320                                        (strtoupper($head1[0]) == strtoupper("subject")) ||
321                                        (strtoupper($head1[0]) == strtoupper("date")) )
322                                $header .= $head."\r\n";
323                }
324                               
325                $msg = &new message_components($this->mbox);
326                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
327                                                             Então uso essa classe para verificar a codificação e o charset,
328                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
329               
330                $status = @imap_append($this->mbox,
331                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
332                                        $header.
333                                        "\r\n".
334                                        str_replace("\n","\r\n",$this->decodeBody(
335                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),"1"),
336                                                        $msg->encoding[$params["msg_num"]][0], $msg->charset[$params["msg_num"]][0]
337                                                        )                                       
338                                        )); //Append do novo email, só com header e conteúdo sem anexos.
339               
340                if(!$status) {
341                        $return["status"] = false;
342                        $return["msg"] = lang("error appending mail on delete attachments");
343                }
[650]344       
[613]345                @imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"])); //Insere o novo e-mail sem anexos.
346                @imap_expunge($this->mbox); //Deleta o e-mail com anexos
347               
348                return $return;
349               
350        }
351
[689]352/**
353         *
354         * @return
355         * @param $params Object
356         */
357        function get_info_msgs($params) {
358                include_once("class.exporteml.inc.php");
359                $return = array();
360                $new_params = array();
361                $attach_params = array();
362                $new_params["msg_folder"]=$params["folder"];
363                $attach_params["folder"] = $params["folder"];
364                $msgs = explode(",",$params["msgs_number"]);
365                $exporteml = new ExportEml();
366                foreach($msgs as $msg_number) {
367                        $new_params["msg_number"] = $msg_number;
368                        //ini_set("display_errors","1");
369                        $msg_info = $this->get_info_msg($new_params);
370
371                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
372                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
373
374                        $attach_params["num_msg"] = $msg_number;
375                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
376                        $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
377                        imap_close($this->mbox);
378                        $this->mbox=false;
379                        array_push($return,serialize($msg_info));
380                }
381                return $return;
382        }
383
[2]384        function get_info_msg($params)
385        {
[51]386                $return = array();
[2]387                $msg_number = $params['msg_number'];
[205]388                $msg_folder = $params['msg_folder'];
[449]389               
[411]390                if(!$this->mbox || !is_resource($this->mbox))
[449]391                        $this->mbox = $this->open_mbox($msg_folder);           
392               
[535]393                $header = $this->get_header($msg_number);
[205]394                if (!$header) {
[535]395                        $return['status_get_msg_info'] = "false";                       
[205]396                        return $return;
397                }
[535]398               
[828]399                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
400
[51]401                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
[449]402               
[603]403                //Substituição de links em email para abrir no próprio expresso
404                $body = ereg_replace("<a[^>]*href=[\'\"]mailto:([^\"\']+)[\'\"]>([^<]+)</a>","<a href=\"javascript:new_message_to('\\1')\">\\2</a>",$return_get_body['body']);
[828]405
[1035]406                if($return_get_body['body']=='isCripted'){
407                        $exporteml = new ExportEml();
408                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
409                        $return['body']                 = "";
410                        $return['attachments']  =  "";
411                        $return['thumbs']               =  "";
412                        $return['signature']    =  "";
413                        //return $return;
414                }else{
415            $return['body']             = $body;
416            $return['attachments']      = $return_get_body['attachments'];
417            $return['thumbs']           = $return_get_body['thumbs'];
418            $return['signature']        = $return_get_body['signature'];
419        }
[828]420                $pattern = '/^[ \t]*Disposition-Notification-To(^:)*:(.+)*@(.+)*$/isUm';
421                if (preg_match($pattern, $header_, $fields))
422                {
423                        preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches);
424                        $return['DispositionNotificationTo'] = "<".$matches[0].">";
[2]425                }
[828]426
[2]427                $return['Recent']       = $header->Recent;
428                $return['Unseen']       = $header->Unseen;
[449]429                $return['Deleted']      = $header->Deleted;             
[2]430                $return['Flagged']      = $header->Flagged;
431
432                if($header->Answered =='A' && $header->Draft == 'X'){
433                        $return['Forwarded'] = 'F';
434                }
[535]435 
[2]436                else {
437                        $return['Answered']     = $header->Answered;
[449]438                        $return['Draft']        = $header->Draft;       
[2]439                }
440
441                $return['msg_number'] = $msg_number;
442                $return['msg_folder'] = $msg_folder;
[449]443       
[535]444                $date_msg = gmdate("d/m/Y",$header->udate);
[2]445                if (date("d/m/Y") == $date_msg)
[535]446                        $return['udate'] = gmdate("H:i",$header->udate);
[2]447                else
448                        $return['udate'] = $date_msg;
[449]449               
450                $return['msg_day'] = $date_msg;
[535]451                $return['msg_hour'] = gmdate("H:i",$header->udate);
[449]452               
[2]453                if (date("d/m/Y") == $date_msg) //no dia
454                {
[535]455                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
456                        $return['smalldate'] = gmdate("H:i",$header->udate);
[605]457
[535]458                        $timestamp_now = strtotime("now");                     
[605]459                        $timestamp_msg_time = $header->udate;
[535]460                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
461                        // The variable $timestamp_diff is calculated without MailDate TZ.
462                        $pdate = date_parse($header->MailDate);
463                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
[449]464                       
[2]465                        if (gmdate("H",$timestamp_diff) > 0)
466                        {
[197]467                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
[2]468                        }
469                        else
470                        {
471                                if (gmdate("i",$timestamp_diff) == 0){
[197]472                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
[2]473                                }
474                                elseif (gmdate("i",$timestamp_diff) == 1){
[197]475                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
[2]476                                }
477                                else{
[197]478                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
[2]479                                }
480                        }
481                }
482                else{
[535]483                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
484                        $return['smalldate'] = gmdate("d/m/Y",$header->udate);
[2]485                }
[449]486               
[2]487                $from = $header->from;
488                $return['from'] = array();
489                $tmp = imap_mime_header_decode($from[0]->personal);
490                $return['from']['name'] = $this->decode_string($tmp[0]->text);
491                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
492                if ($return['from']['name'])
493                {
494                        if (substr($return['from']['name'], 0, 1) == '"')
495                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
496                        else
497                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
498                }
499                else
500                        $return['from']['full'] = $return['from']['email'];
[449]501               
[2]502                // Sender attribute
503                $sender = $header->sender;
504                $return['sender'] = array();
505                $tmp = imap_mime_header_decode($sender[0]->personal);
506                $return['sender']['name'] = $this->decode_string($tmp[0]->text);
507                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
508                if ($return['sender']['name'])
509                {
510                        if (substr($return['sender']['name'], 0, 1) == '"')
511                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
512                        else
513                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
514                }
515                else
516                        $return['sender']['full'] = $return['sender']['email'];
517
518                if($return['from']['full'] == $return['sender']['full'])
519                        $return['sender'] = null;
520                $to = $header->to;
521                $return['toaddress2'] = "";
522                if (!empty($to))
523                {
524                        foreach ($to as $tmp)
525                        {
526                                if (!empty($tmp->personal))
527                                {
528                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
529                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
530                                        $return['toaddress2'] .= " ";
531                                        $return['toaddress2'] .= "&lt;";
[320]532                                        if ($tmp->host != 'unspecified-domain')
533                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
534                                        else
535                                                $return['toaddress2'] .= $tmp->mailbox;
[2]536                                        $return['toaddress2'] .= "&gt;";
537                                        $return['toaddress2'] .= ", ";
538                                }
539                                else
540                                {
[320]541                                        if ($tmp->host != 'unspecified-domain')
542                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
543                                        else
544                                                $return['toaddress2'] .= $tmp->mailbox;
[2]545                                        $return['toaddress2'] .= ", ";
546                                }
547                        }
548                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
549                }
550                else
551                {
552                        $return['toaddress2'] = "&lt;Empty&gt;";
[449]553                }       
554               
[2]555                $cc = $header->cc;
556                $return['cc'] = "";
557                if (!empty($cc))
558                {
559                        foreach ($cc as $tmp_cc)
560                        {
561                                if (!empty($tmp_cc->personal))
562                                {
563                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
564                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
565                                        $return['cc'] .= " ";
566                                        $return['cc'] .= "&lt;";
567                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
568                                        $return['cc'] .= "&gt;";
569                                        $return['cc'] .= ", ";
570                                }
571                                else
572                                {
573                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
574                                        $return['cc'] .= ", ";
575                                }
576                        }
577                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
578                }
579                else
580                {
581                        $return['cc'] = "";
[449]582                }       
583
584                ##
585                # @AUTHOR Rodrigo Souza dos Santos
586                # @DATE 2008/09/12
587                # @BRIEF Adding the BCC field.
588                ##
589                $bcc = $header->bcc;
590                $return['bcc'] = "";
591                if (!empty($bcc))
592                {
593                        foreach ($bcc as $tmp_bcc)
594                        {
595                                if (!empty($tmp_bcc->personal))
596                                {
597                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
598                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
599                                        $return['bcc'] .= " ";
600                                        $return['bcc'] .= "&lt;";
601                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
602                                        $return['bcc'] .= "&gt;";
603                                        $return['bcc'] .= ", ";
604                                }
605                                else
606                                {
607                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
608                                        $return['bcc'] .= ", ";
609                                }
610                        }
611                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
[426]612                }
[449]613                else
614                {
615                        $return['bcc'] = "";
616                }       
[426]617
[2]618                $reply_to = $header->reply_to;
619                $return['reply_to'] = "";
620                if (is_object($reply_to[0]))
621                {
622                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
623                        {
624                                if (!empty($reply_to[0]->personal))
625                                {
626                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
[41]627                                        if(!empty($personal_reply_to[0]->text)) {
628                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
629                                                $return['reply_to'] .= " ";
630                                                $return['reply_to'] .= "&lt;";
631                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
632                                                $return['reply_to'] .= "&gt;";
633                                        }
634                                        else {
635                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
636                                        }
[2]637                                }
638                                else
639                                {
640                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
641                                }
642                        }
643                }
644                $return['reply_to'] = $this->decode_string($return['reply_to']);
645                $return['subject'] = $this->decode_string($header->fetchsubject);
646                $return['Size'] = $header->Size;
[828]647                $return['reply_toaddress'] = $header->reply_toaddress;
648
[689]649                //All this is to help in local messages
650                $return['timestamp'] = $header->udate;
651                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
652                $return['reply_toaddress'] = $header->reply_toaddress;
[828]653
[2]654                return $return;
655        }
[449]656       
[2]657        function get_body_msg($msg_number, $msg_folder)
658        {
659                include_once("class.message_components.inc.php");
[51]660                $msg = &new message_components($this->mbox);
[2]661                $msg->fetch_structure($msg_number);
[51]662                $return = array();
[449]663                $return['attachments'] = $this-> download_attachment($msg,$msg_number);         
[51]664                if(!$this->has_cid)
[91]665                {
[178]666                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
[91]667                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
[449]668                }                       
669               
[2]670                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
671                {
[1035]672            if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
673                $return['body']='isCripted';
674                return $return;
675            }
676
[2]677                        $attachment = array(); //No attachments
[1035]678
679            if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
680                                        $return['body']='isCripted';
681                                        return $return;
682                        }
683
[2]684                        $content = '';
685                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
686                        {
[51]687                                $content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
[2]688                        }
689                        else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
690                        {
[51]691                                $content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
[2]692                        }
693                }
[449]694                else
[2]695                { //Complicated message, multiple parts
696                        $html_body = '';
697                        $content = '';
698                        $has_multipart = true;
699                        $this->has_cid = false;
[449]700                       
[2]701                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
702                                $this->has_cid = true;
[449]703                       
[469]704                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
705                                $show_only_html = false;
706                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
[432]707                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
708                                        if($file_type == "text/html")
[469]709                                                $show_only_html = true;                 
[432]710                                }
[469]711                        }
[2]712                        else
713                                $show_only_html = false;
714
715                        foreach($msg->pid[$msg_number] as $values => $msg_part)
716                        {
[449]717                               
[2]718                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
719                                if($file_type == "message/rfc822")
720                                        $has_multipart = false;
[449]721       
[2]722                                if($file_type == "multipart/alternative")
723                                        $has_multipart = false;
[449]724       
725                                if(($file_type == "text/plain"
[2]726                                        || $file_type == "text/html")
727                                        && $file_type != 'attachment')
728                                {
729                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
730                                        {
731                                                // if TXT file size > 100kb, then it will not expand.
732                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
[449]733                                                        $content .= nl2br(htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])));                                                     
[2]734                                                }
735                                        }
736                                        // if HTML attachment file size > 300kb, then it will not expand.
[449]737                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
[2]738                                        {
[51]739                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
[2]740                                                $show_only_html = true;
741                                        }
742                                }
743                                else if($file_type == "message/delivery-status"){
744                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[449]745                                        $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));                                           
[2]746
747                                }
[65]748                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
[449]749                                       
[2]750                                        include_once("class.imap_attachment.inc.php");
751                                        $att = new imap_attachment();
[51]752                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
[449]753                                        if($attachments['number_attachments'] > 0) {                                                                                           
[2]754                                                foreach($attachments ['attachment'] as $index => $attachment){
755                                                        if(strtolower($attachment['type']) == "delivery-status" ||
[449]756                                                                strtolower($attachment['type']) == "rfc822" ||                                                         
[65]757                                                                strtolower($attachment['type']) == "rfc822-headers" ||
[2]758                                                                strtolower($attachment['type']) == "plain"
759                                                        ){
[449]760                                                                $obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);                                   
761                                                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";                                   
[2]762                                                                $content .= "<br><table  style='margin:2px;border:1px solid black;background:#EAEAEA'>";
763                                                                $content .= "<tr><td><b>".$this->functions->getLang("Subject").":</b></td><td>".$this->decode_string($obj->subject)."</td></tr>";
764                                                                $content .= "<tr><td><b>".$this->functions->getLang("From").":</b></td><td>".$this->decode_string($obj->from[0]->mailbox."@".$obj->from[0]->host)."</td></tr>";
765                                                                $content .= "<tr><td><b>".$this->functions->getLang("Date").":</b></td><td>".$obj->date."</td></tr>";
766                                                                $content .= "<tr><td><b>".$this->functions->getLang("TO").":</b></td><td>".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)."</td></tr>";
[449]767                                                                $content .= !$obj->cc ? "</table><br>" :"<tr><td><b>".$this->functions->getLang("CC").":</b></td><td>".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)."</td></tr></table><br>";                                                               
[2]768                                                                $ix_part =      strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
[449]769                                                                $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, ($attachment['part_in_msg']+$ix_part).".1", FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));                                                         
770                                                                break;                 
[2]771                                                        }
772                                                }
773                                        }
774                                }
775                        }
776                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
777                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
[51]778                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
[25]779                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
[449]780                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));                         
[2]781                        }
[449]782                }
[2]783                // Force message with flag Seen (imap_fetchbody not works correctly)
[449]784                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");                               
[2]785                $this->set_messages_flag($params);
[205]786                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
[2]787                $content = $this->replace_special_characters($content);
[51]788                $return['body'] = $content;
789                return $return;
[2]790        }
[449]791       
[2]792        function htmlfilter($body)
793        {
794                require_once('htmlfilter.inc');
[449]795               
[2]796                $tag_list = Array(
797                                false,
798                                'blink',
799                                'object',
800                                'meta',
801                                'html',
802                                'link',
803                                'frame',
804                                'iframe',
805                                'layer',
806                                'ilayer',
807                                'plaintext'
808                );
809
810                /**
811                * A very exclusive set:
812                */
813                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
814                $rm_tags_with_content = Array(
815                                'script',
816                                'style',
817                                'applet',
818                                'embed',
819                                'head',
820                                'frameset',
821                                'xml',
822                                'xmp'
823                );
824
825                $self_closing_tags =  Array(
826                                'img',
827                                'br',
828                                'hr',
829                                'input'
830                );
831
832                $force_tag_closing = true;
833
834                $rm_attnames = Array(
835                        '/.*/' =>
836                                Array(
837                                        '/target/i',
838                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
839                                        '/^dynsrc/i',
840                                        '/^datasrc/i',
841                                        '/^data.*/i',
842                                        '/^lowsrc/i'
843                                )
844                );
845
846                /**
847                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
848                 * some idea of what's going on here. :)
849                 */
850
851                $bad_attvals = Array(
852                '/.*/' =>
853                Array(
854                      '/.*/' =>
855                              Array(
856                                Array(
857                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
858                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
859                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
860                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
861                                      ),
862                            Array(
863                                              '\\1oddjob:\\2\\1',
864                                          //'\\1uucp:\\2\\1', -> doclinks notes
865                                      '\\1amaretto:\\2\\1',
866                                          '\\1round:\\2\\1'
867                                        )
[449]868                                    ),     
869         
[2]870                          '/^style/i' =>
871                              Array(
872                                        Array(
873                                          '/expression/i',
874                                              '/behaviou*r/i',
875                                          '/binding/i',
876                                              '/include-source/i',
877                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
878                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
879                                         ),
880                                        Array(
881                                          'idiocy',
882                                              'idiocy',
883                                          'idiocy',
884                                              'idiocy',
885                                          'url(\\1http://securityfocus.com/\\1)',
886                                          'url(\\1http://securityfocus.com/\\1)'
887                                         )
888                                )
889                          )
890                    );
891
892                $add_attr_to_tag = Array(
893                                '/^a$/i' => Array('target' => '"_new"')
894                );
[449]895       
896       
[2]897                $trusted_body = sanitize($body,
898                                $tag_list,
899                                $rm_tags_with_content,
900                                $self_closing_tags,
901                                $force_tag_closing,
902                                $rm_attnames,
903                                $bad_attvals,
904                                $add_attr_to_tag
905                );
[449]906       
[2]907            return $trusted_body;
908        }
[449]909       
[2]910        function decodeBody($body, $encoding, $charset=null)
911        {
912                /**
913                * replace e-mail by anchor.
914                */
915                // HTML Filter
[13]916                //$body = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=# onclick=\"javascript:new_message('new_by_message', '\\2@\\3')\">\\2@\\3</a>", $body);
[828]917        //$body = str_replace("\r\n", "\n", $body);
[2]918                if ($encoding == 'quoted-printable')
[828]919                {
920                        /*
[449]921                       
[2]922                        for($i=0;$i<256;$i++) {
923                                $c1=dechex($i);
924                                if(strlen($c1)==1){$c1="0".$c1;}
925                                $c1="=".$c1;
926                                $myqprinta[]=$c1;
927                                $myqprintb[]=chr($i);
[449]928                        }               
[828]929                         */
[2]930                        $body = str_replace($myqprinta,$myqprintb,($body));
931                        $body = quoted_printable_decode($body);
[449]932                while (ereg("=\n", $body))
[2]933                {
934                        $body = ereg_replace ("=\n", '', $body);
935                }
936        }
[449]937        else if ($encoding == 'base64')
[2]938        {
939                $body = base64_decode($body);
940        }
[828]941        else if ($encoding == '7bit')
[12]942        {
[449]943                $body = quoted_printable_decode($body);                                         
[828]944        }
[2]945                // All other encodings are returned raw.
946                if (strtolower($charset) == "utf-8")
947                        return utf8_decode($body);
948        else
949                        return $body;
950        }
[449]951       
[205]952        function process_embedded_images($msg, $msgno, $body, $msg_folder)
[2]953        {
954                if (count($msg->inline_id[$msgno]) > 0)
955                {
956                        foreach ($msg->inline_id[$msgno] as $index => $cid)
957                        {
958                                $cid = eregi_replace("<", "", $cid);
959                                $cid = eregi_replace(">", "", $cid);
960                                $msg_part = $msg->pid[$msgno][$index];
961                                //$body = eregi_replace("alt=\"\"", "", $body);
962                                $body = eregi_replace("<br/>", "", $body);
963                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
964                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
965                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
966                        }
967                }
[449]968               
[2]969                return $body;
970        }
[449]971       
[2]972        function replace_special_characters($body)
973        {
974                // Suspected TAGS!
[449]975                /*$tag_list = Array(   
[2]976                        'blink','object','meta',
977                        'html','link','frame',
978                        'iframe','layer','ilayer',
979                        'plaintext','script','style','img',
980                        'applet','embed','head',
981                        'frameset','xml','xmp');
982                */
983
[449]984                // Layout problem: Change html elements
985                // with absolute position to relate position, CASE INSENSITIVE.
[6]986                $body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
987
[2]988                $tag_list = Array('head','blink','object','frame',
989                        'iframe','layer','ilayer','plaintext','script',
[63]990                        'applet','embed','frameset','xml','xmp','style');
[2]991
992                $body = $this-> replace_links($body);
[449]993                $blocked_tags = array();               
[2]994                foreach($tag_list as $index => $tag) {
995                        $new_body = eregi_replace("<$tag", "<!--$tag", $body);
996                        if($body != $new_body) {
997                                $blocked_tags[] = $tag;
998                        }
999                        $body = eregi_replace("</$tag>", "</$tag-->", $new_body);
1000                }
[650]1001                // Malicious Code Remove
1002                $dirtyCodePattern = "/(<([\w]+)([^>]*)on(mouse(move|over|down|up)|load|blur|change|click|dblclick|focus|key(down|up|press)|select)=[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/isU";
1003                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1004                foreach($rest[0] as $i => $val)
1005                        if (!(preg_match("/window\.open/i",$rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
1006                                $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
[2]1007
1008                return  "<span>".$body;
1009        }
1010
[449]1011        function replace_links($body) {                                 
1012                $matches = array();
[2]1013                // Verify exception.
[449]1014                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
[2]1015                // It no has exception,then open the link in new window.
[449]1016                if(count($matches))
1017                        return $body;
1018       
1019                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
1020                $replacement = '<a href="http$3://$4$5" target="_blank">$1</a>';
1021                return preg_replace($pattern, $replacement, $body);
1022               
1023                // Original
1024                //return preg_replace('/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', '<a href="http$3://$4$5" target="_blank">http$3://$4$5</a>', $body);
[2]1025        }
1026
[91]1027        function get_signature($msg, $msg_number, $msg_folder)
[1035]1028        {
1029        include_once("../seguranca/classes/CertificadoB.php");
1030                include_once("class.db_functions.inc.php");
[91]1031                foreach ($msg->file_type[$msg_number] as $index => $file_type)
1032                {
[1035]1033            $sign = array();
1034                        $temp = $this->get_info_head_msg($msg_number);
1035                        if($temp['ContentType'] =='normal') return $sign;
[91]1036                        $file_type = strtolower($file_type);
[449]1037                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]1038                        {
[650]1039                                if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
[91]1040                                {
[1035]1041                                        if(!$this->mbox || !is_resource($this->mbox))
1042                                        $this->mbox = $this->open_mbox($msg_folder);
1043
1044                                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1045
1046                                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1047                                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1048
1049                                        $certificado = new certificadoB();
1050                                        $validade = $certificado->verificar($imap_msg);
1051
1052                                        if ($certificado->apresentado)
[109]1053                                        {
[1035]1054                                                $from = $header->from;
1055                                                foreach ($from as $id => $object) {
1056                                                        $fromname = $object->personal;
1057                                                    $fromaddress = $object->mailbox . "@" . $object->host;
[109]1058                                        }
[1035]1059                                                $sign_alert = '';
1060                                                foreach ($certificado->erros_ssl as $item)
1061                                                {
1062                                                        $check_error_msg = $this->functions->getLang($item);
1063                                                        /*
1064                                                         * Desabilite o teste abaixo para mostrar todas as mensagem
1065                                                         * de erro.
1066                                                         */
1067                                                        //if (!strpos($check_error_msg,'*',strlen($check_error_msg-1)))
1068                                                        //{
1069                                                        $sign[] = "<span style=color:red>" . $check_error_msg . " </span>";
1070                                                        //}
1071                                                }
1072                                                if (count($certificado->erros_ssl) < 1)
1073                                                {
1074                                                        $check_msg = $this->functions->getLang('Message untouched') . " ";
1075                                                        if($fromaddress == $certificado->dados['EMAIL'])
1076                                                        {
1077                                                                $check_msg .= $this->functions->getLang('and') . " ";
1078                                                                $check_msg .= $this->functions->getLang('authentic');
1079                                                        }
1080                                                        $sign[] = "<strong>".$check_msg."</strong>";
1081                                                }
1082                                                if($fromaddress != $certificado->dados['EMAIL'])
1083                                                {
1084                                                        $sign[] =       "<span style=color:red>" .
1085                                                                                $this->functions->getLang('message') . " " .
1086                                                                        $this->functions->getLang('with signer different from sender') .
1087                                                                        " </span>";
1088                                                }
1089                                                $sign[] = "<strong>" . $this->functions->getLang('Message signed by: ') . "</strong>" . $certificado->dados['NOME'];
1090                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate email: ') . "</strong>" . $certificado->dados['EMAIL'];
1091                                                $sign[] = "<strong>" . $this->functions->getLang('Mail from: ') . "</strong>" . $fromaddress;
1092                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate Authority: ') . "</strong>" . $certificado->dados['EMISSOR'];
1093                                                $sign[] = "<strong>" . $this->functions->getLang('Validity of certificate: ') . "</strong>" . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1094                                                $sign[] = "<strong>" . $this->functions->getLang('Message date: ') . "</strong>" . $header->Date;
1095
1096                                            $cert = openssl_x509_parse($certificado->cert_assinante);
1097                                                /*
1098                                                $sign[] = '<table>';
1099                                                $sign[] = '<tr><td colspan=1><b>Expedido para:</b></td></tr>';
1100                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[subject]['CN'] .  '</td></tr>';
1101                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1102                                                $sign[] = '<tr><td>Data de nascimento </td><td>' . $certificado->dados['NASCIMENTO'] .  '</td></tr>';
1103                                                $sign[] = '<tr><td>CPF </td><td>' . $certificado->dados['CPF'] .  '</td></tr>';
1104                                                $sign[] = '<tr><td>Documento identidade </td><td>' . $certificado->dados['RG'] .  '</td></tr>';
1105                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[subject]['O'] .  '</td></tr>';
1106                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[subject]['OU'][0] .  '</td></tr>';
1107                                                //$sign[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1108                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1109                                                $sign[] = '<tr><td colspan=1><b>Expedido por:</b></td></tr>';
1110                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[issuer]['CN'] .  '</td></tr>';
1111                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[issuer]['O'] .  '</td></tr>';
1112                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[issuer]['OU'][0] .  '</td></tr>';
1113                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1114                                                $sign[] = '<tr><td colspan=1><b>Validade:</b></td></tr>';
1115                                                $H = data_hora($cert[validFrom]);
1116                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1117                                                $sign[] = '<tr><td>Expedido em </td><td>' . $X .  '</td></tr>';
1118                                                $H = data_hora($cert[validTo]);
1119                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1120                                                $sign[] = '<tr><td>Valido ate </td><td>' . $X .  '</td></tr>';
1121                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1122                                                $sign[] = '</table>';
1123                                                */
1124                                                $sign_alert .= 'Expedido para:\n';
1125                                                $sign_alert .= 'Nome Comum (CN)  ' . $cert[subject]['CN'] .  '\n';
1126                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1127                                                $sign_alert .= 'Data de nascimento ' . $X .  '\n';
1128                                                $sign_alert .= 'CPF ' . $certificado->dados['CPF'] .  '\n';
1129                                                $sign_alert .= 'Documento identidade ' . $certificado->dados['RG'] .  '\n';
1130                                                $sign_alert .= 'Empresa (O)  ' . $cert[subject]['O'] .  '\n';
1131                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[subject]['OU'][0] .  '\n';
1132                                                //$sign_alert[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1133                                                $sign_alert .= '\n';
1134                                                $sign_alert .= 'Expedido por:\n';
1135                                                $sign_alert .= 'Nome Comum (CN) ' . $cert[issuer]['CN'] . '\n';
1136                                                $sign_alert .= 'Empresa (O)  ' . $cert[issuer]['O'] .  '\n';
1137                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[issuer]['OU'][0] .  '\n';
1138                                                $sign_alert .= '\n';
1139                                                $sign_alert .= 'Validade:\n';
1140                                                $H = data_hora($cert[validFrom]);
1141                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1142                                                $sign_alert .= 'Expedido em ' . $X .  '\n';
1143                                                $H = data_hora($cert[validTo]);
1144                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1145                                                $sign_alert .= 'Valido ate ' . $X .  '\n';
1146
1147                                                $sign[] = "<a onclick=\"javascript:alert('" . $sign_alert . "')\"><b><font color=\"#0000FF\">".$this->functions->getLang("More")."...</font></b></a>";
1148                                                $this->db = new db_functions();
1149
1150                                                // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1151                        if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1152                            $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1153                                        }
[91]1154                                     else
[1035]1155                                    {
1156                                        $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1157                                        foreach($certificado->erros_ssl as $item)
1158                                        $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1159                    }
[91]1160                                }
1161                        }
1162                }
[449]1163                return $sign;   
[91]1164        }
1165
[51]1166        function get_thumbs($msg, $msg_number, $msg_folder)
[2]1167        {
1168                $thumbs_array = array();
1169                $i = 0;
1170        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1171        {
1172                $file_type = strtolower($file_type);
1173                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1174                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1175                                $img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
[1005]1176                                $href = "<a onMouseDown='save_image(event,this,\"".$file_type."\")' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
[2]1177                                        $thumbs_array[] = $href;
1178                        }
1179                        $i++;
1180                }
1181        }
1182        return $thumbs_array;
1183        }
[449]1184               
[2]1185        /*function delete_msg($params)
1186        {
1187                $folder = $params['folder'];
1188                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[449]1189               
[2]1190                $mbox_stream = $this->open_mbox($folder);
[449]1191               
[2]1192                foreach ($msgs_to_delete as $msg_number){
1193                        imap_delete($mbox_stream, $msg_number, FT_UID);
1194                }
1195                imap_close($mbox_stream, CL_EXPUNGE);
1196                return $params['msgs_to_delete'];
1197        }*/
1198
1199        // Novo
1200        function delete_msgs($params)
1201        {
[449]1202               
[2]1203                $folder = $params['folder'];
[51]1204                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]1205                $msgs_number = explode(",",$params['msgs_number']);
1206                $border_ID = $params['border_ID'];
[449]1207               
[2]1208                $return = array();
[449]1209               
1210                if ($params['get_previous_msg']){
[2]1211                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]1212                        // Fix problem in unserialize function JS.
1213                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1214                }
[2]1215
[504]1216                //$mbox_stream = $this->open_mbox($folder);             
1217                $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()))));
[449]1218               
[2]1219                foreach ($msgs_number as $msg_number)
1220                {
1221                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1222                                $return['msgs_number'][] = $msg_number;
1223                }
[449]1224               
[2]1225                $return['folder'] = $folder;
1226                $return['border_ID'] = $border_ID;
[449]1227               
[51]1228                if($mbox_stream)
1229                        imap_close($mbox_stream, CL_EXPUNGE);
[2]1230                return $return;
1231        }
1232
[449]1233               
[2]1234        function refresh($params)
1235        {
[689]1236                include_once("class.imap_attachment.inc.php");
[449]1237                $imap_attachment = new imap_attachment();               
[2]1238                $folder = $params['folder'];
1239                $msg_range_begin = $params['msg_range_begin'];
1240                $msg_range_end = $params['msg_range_end'];
1241                $msgs_existent = $params['msgs_existent'];
[449]1242                $sort_box_type = $params['sort_box_type'];             
[2]1243                $sort_box_reverse = $params['sort_box_reverse'];
1244                $msgs_in_the_server = array();
[53]1245                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]1246                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1247                $msgs_in_the_server = array_keys($msgs_in_the_server);
1248                if(!count($msgs_in_the_server))
[51]1249                        return array();
[449]1250                       
[828]1251                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1252                $msgs_in_the_client = explode(",", $msgs_existent);     
[51]1253
[2]1254                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[271]1255                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[449]1256               
[2]1257                $msgs_to_exec = array();
1258                if ((count($msg_to_insert)) && ($msgs_existent))
1259                {
1260                        foreach($msg_to_insert as $index => $msg_number)
1261                        {
1262                                if ($msgs_in_the_server[$index+1])
1263                                {
1264                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1265                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1266                                }
1267                                else
1268                                {
1269                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1270                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1271                                }
1272                        }
1273                        ksort($msgs_to_exec);
1274                }
1275                elseif(!$msgs_existent)
1276                {
1277                        foreach($msgs_in_the_server as $index => $msg_number)
1278                        {
1279                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1280                        }
1281                }
[449]1282               
[2]1283                $return = array();
1284                $i = 0;
1285                foreach($msgs_to_exec as $msg_number => $command)
1286                {
[614]1287                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1288                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1289                        * para saber se o email é importante ou não, uso abaixo a função
1290                        * imap_fetchheader e busco o atributo importance nela para passar
1291                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1292                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1293                        * não preciso reimplementar o método utilizando o fetchheader.
1294                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1295                        * a perda em performance é insignificante.
1296                        */
[1035]1297            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1298                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[689]1299                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
[614]1300                       
[535]1301                        $header = $this->get_header($msg_number);
[2]1302                        if (!is_object($header))
[828]1303                                continue;
1304
[2]1305                        $return[$i]['msg_number']       = $msg_number;
1306                        $return[$i]['command']          = $command;
[449]1307                       
[2]1308                        $return[$i]['msg_folder']       = $folder;
[1035]1309            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1310            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
[2]1311                        $return[$i]['Recent']           = $header->Recent;
1312                        $return[$i]['Unseen']           = $header->Unseen;
1313                        $return[$i]['Answered']         = $header->Answered;
1314                        $return[$i]['Deleted']          = $header->Deleted;
1315                        $return[$i]['Draft']            = $header->Draft;
1316                        $return[$i]['Flagged']          = $header->Flagged;
1317
[535]1318                        $date_msg = gmdate("d/m/Y",$header->udate);
1319                        if (gmdate("d/m/Y") == $date_msg)
1320                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
[2]1321                        else
1322                                $return[$i]['udate'] = $date_msg;
[449]1323                       
[2]1324                        $from = $header->from;
1325                        $return[$i]['from'] = array();
1326                        $tmp = imap_mime_header_decode($from[0]->personal);
1327                        $return[$i]['from']['name'] = $tmp[0]->text;
1328                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[449]1329                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[2]1330                        if(!$return[$i]['from']['name'])
1331                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[449]1332                       
[2]1333                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1334                        $return[$i]['toaddress'] = '';
1335                        foreach ($toaddress as $tmp)
1336                                $return[$i]['toaddress'] .= $tmp->text;*/
1337                        $to = $header->to;
1338                        $return[$i]['to'] = array();
1339                        $tmp = imap_mime_header_decode($to[0]->personal);
1340                        $return[$i]['to']['name'] = $tmp[0]->text;
1341                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1342                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[449]1343                       
[2]1344                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1345
1346                        $return[$i]['Size'] = $header->Size;
1347                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[449]1348                       
[2]1349                        $return[$i]['attachment'] = array();
[51]1350                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]1351                        $i++;
1352                }
[51]1353                $return['new_msgs'] = imap_num_recent($this->mbox);
[271]1354                $return['msgs_to_delete'] = $msg_to_delete;
[411]1355                if($this->mbox && is_resource($this->mbox))
[51]1356                        imap_close($this->mbox);
[828]1357
[2]1358                return $return;
1359        }
1360
[1035]1361     /**
1362     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1363     * assinado ou cifrado.
1364     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1365     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1366     * @param $msg_number O número da mesagem
1367     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1368     */
1369    function getMessageType($msg_number, $headers = false){
1370
1371            $contentType = "normal";
1372            if (!$headers){
1373                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1374            }
1375            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1376            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1377                $contentType = "signature";
1378            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1379                $contentType = "cipher";
1380            }
1381
1382            return $contentType;
1383    }
1384
[449]1385        function get_folders_list($params = null)
[2]1386        {
[449]1387                $mbox_stream = $this->open_mbox();             
[115]1388                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[2]1389                $folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
[650]1390                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1391
[2]1392                $tmp = array();
1393                $result = array();
[449]1394               
[2]1395                if (is_array($folders_list)) {
1396                        reset($folders_list);
[1035]1397            $this->ldap = new ldap_functions();
[449]1398                       
[2]1399                        $i = 0;
1400                        while (list($key, $val) = each($folders_list)) {
1401                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
[1035]1402
[2]1403                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1404                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
[1035]1405                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas'){
1406                    //error_log('passou', 3,'/tmp/imap_get_list.log');
1407                    //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1408                    continue;
1409                }
1410                $result[$i]['folder_unseen'] = $status->unseen;
[2]1411                                $folder_id = $tmp_folder_id[1];
1412                                $result[$i]['folder_id'] = $folder_id;
[449]1413                               
[2]1414                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1415                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
[96]1416                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
[325]1417                                if (is_numeric($result[$i]['folder_name']))     {
[1035]1418                                        //$this->ldap = new ldap_functions();
[432]1419                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
[325]1420                                                $result[$i]['folder_name'] = $cn;
1421                                        }
1422                                }
[449]1423                               
[2]1424                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1425                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[449]1426                                       
[96]1427                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
[2]1428                                        $result[$i]['folder_hasChildren'] = 1;
1429                                else
1430                                        $result[$i]['folder_hasChildren'] = 0;
1431
[449]1432                                $i++;                           
[2]1433                        }
1434                }
[449]1435               
[2]1436                foreach ($result as $folder_info)
1437                {
1438                        $array_tmp[] = $folder_info['folder_id'];
1439                }
[449]1440               
[2]1441                natcasesort($array_tmp);
[449]1442               
[2]1443                foreach ($array_tmp as $key => $folder_id)
1444                {
1445                        $result2[] = $result[$key];
1446                }
[449]1447               
1448                $current_folder = "INBOX";
1449                if($params && $params['folder'])
1450                        $current_folder = $params['folder'];
1451                return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
[2]1452        }
[449]1453       
[2]1454        function create_mailbox($arr)
1455        {
1456                $namebox        = $arr['newp'];
1457                $mbox_stream = $this->open_mbox();
1458                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]1459                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[449]1460               
[2]1461                $result = "Ok";
[51]1462                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]1463                {
1464                        $result = implode("<br />\n", imap_errors());
[449]1465                }       
1466               
[51]1467                if($mbox_stream)
1468                        imap_close($mbox_stream);
[449]1469                                       
[2]1470                return $result;
[449]1471               
[2]1472        }
[449]1473       
[2]1474        function create_extra_mailbox($arr)
1475        {
1476                $nameboxs = explode(";",$arr['nw_folders']);
1477                $result = "";
1478                $mbox_stream = $this->open_mbox();
1479                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[449]1480                foreach($nameboxs as $key=>$tmp){                       
[2]1481                        if($tmp != ""){
1482                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1483                                        $result = implode("<br />\n", imap_errors());
[51]1484                                        if($mbox_stream)
[449]1485                                                imap_close($mbox_stream);                                       
[2]1486                                        return $result;
1487                                }
1488                        }
1489                }
[51]1490                if($mbox_stream)
1491                        imap_close($mbox_stream);
[2]1492                return true;
1493        }
[449]1494       
[2]1495        function delete_mailbox($arr)
1496        {
1497                $namebox = $arr['del_past'];
1498                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1499                $mbox_stream = $this->open_mbox();
1500                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[449]1501               
[2]1502                $result = "Ok";
1503                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1504                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1505                {
1506                        $result = implode("<br />\n", imap_errors());
1507                }
[51]1508                if($mbox_stream)
1509                        imap_close($mbox_stream);
[2]1510                return $result;
1511        }
[449]1512       
[2]1513        function ren_mailbox($arr)
1514        {
1515                $namebox = $arr['current'];
1516                $new_box = $arr['rename'];
1517                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1518                $mbox_stream = $this->open_mbox();
1519                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[449]1520               
[2]1521                $result = "Ok";
1522                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]1523                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[449]1524               
[2]1525                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1526                {
[449]1527                        $result = imap_errors();                       
[2]1528                }
[51]1529                if($mbox_stream)
1530                        imap_close($mbox_stream);
[2]1531                return $result;
[449]1532               
[2]1533        }
[449]1534       
[2]1535        function get_num_msgs($params)
1536        {
1537                $folder = $params['folder'];
[411]1538                if(!$this->mbox || !is_resource($this->mbox)) {
[2]1539                        $this->mbox = $this->open_mbox($folder);
[411]1540                        if(!$this->mbox || !is_resource($this->mbox))
[2]1541                        return imap_last_error();
[449]1542                }               
[2]1543                $num_msgs = imap_num_msg($this->mbox);
[432]1544                if($this->mbox && is_resource($this->mbox))
[51]1545                        imap_close($this->mbox);
[449]1546               
[2]1547                return $num_msgs;
1548        }
[449]1549       
[2]1550        function send_mail($params)
1551        {
1552                include_once("class.phpmailer.php");
1553                $mail = new PHPMailer();
1554                include_once("class.db_functions.inc.php");
1555                $db = new db_functions();
1556                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[449]1557                ##
1558                # @AUTHOR Rodrigo Souza dos Santos
1559                # @DATE 2008/09/17
1560                # @BRIEF Checks if the user has permission to send an email with the email address used.
1561                ##
1562                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1563                {
1564                        $deny = true;
1565                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1566                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1567                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1568
1569                        if ( $deny )
1570                                return "The server denied your request to send a mail, you cannot use this mail address.";
1571                }
[828]1572
[707]1573                //new_message_to backs to mailto: pattern
[708]1574                $params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
[828]1575
[2]1576                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1577                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1578                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1579                $subject = $params['input_subject'];
[271]1580                $msg_uid = $params['msg_id'];
[2]1581                $return_receipt = $params['input_return_receipt'];
[614]1582                $is_important = $params['input_important_message'];
[1035]1583        $encrypt = $params['input_return_cripto'];
1584                $signed = $params['input_return_digital'];
1585
1586                if($params['smime'])
1587        {
1588            $body = $params['smime'];
1589            $mail->SMIME = true;
1590            // A MSG assinada deve ser testada neste ponto.
1591            // Testar o certificado e a integridade da msg....
1592            include_once("../seguranca/classes/CertificadoB.php");
1593            $erros_acumulados = '';
1594            $certificado = new certificadoB();
1595            $validade = $certificado->verificar($body);
1596            if(!$validade)
1597            {
1598                foreach($certificado->erros_ssl as $linha_erro)
1599                {
1600                    $erros_acumulados .= $linha_erro;
1601                }
1602            }
1603            else
1604            {
1605                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1606                if ($certificado->apresentado)
1607                {
1608                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1609                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1610                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1611                }
1612                else
1613                {
1614                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1615                }
1616            }
1617            if(!$erros_acumulados =='')
1618            {
1619                return $erros_acumulados;
1620            }
1621        }
1622        else
1623        {
1624            $body = $params['body'];
1625        }
[2]1626                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1627                $attachments = $params['FILES'];
1628                $forwarding_attachments = $params['forwarding_attachments'];
[689]1629                $local_attachments = $params['local_attachments'];
[449]1630                 
[51]1631                $folder =$params['folder'];
[449]1632                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1633                $folder_name = $params['folder_name'];         
[6]1634                // Fix problem with cyrus delimiter changes.
[449]1635                // Dots in names: enabled/disabled.                             
[6]1636                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1637                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1638                // End Fix.
[449]1639                if ($folder != 'null'){                 
[2]1640                        $mail->SaveMessageInFolder = $folder;
1641                }
1642////////////////////////////////////////////////////////////////////////////////////////////////////
1643                $mail->SMTPDebug = false;
[1035]1644
1645                if($signed && !$params['smime'])
1646                {
1647            $mail->Mailer = "smime";
1648                        $mail->SignedBody = true;
1649                }
1650                else
1651            $mail->IsSMTP();
1652           
[2]1653                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1654                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1655                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1656                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1657                if($fromaddress){
1658                        $mail->Sender = $mail->From;
1659                        $mail->SenderName = $mail->FromName;
1660                        $mail->FromName = $fromaddress[0];
1661                        $mail->From = $fromaddress[1];
1662                }
[449]1663                               
[2]1664                $this->add_recipients("to", $toaddress, &$mail);
1665                $this->add_recipients("cc", $ccaddress, &$mail);
1666                $this->add_recipients("cco", $ccoaddress, &$mail);
1667                $mail->Subject = $subject;
1668                $mail->IsHTML(true);
[1035]1669                $mail->Body = $body;
[271]1670
[1035]1671        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
1672                {
1673                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
1674            $email = explode(",",$email);
1675            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
1676            // Deve ser verificado um numero limite de destinatarios.
1677            // Deve ser verificado se os certificados sao validos.
1678            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
1679            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
1680            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
1681            $erros_acumulados = "";
1682            $aux_mails = array();
1683            $mail_list = array();
1684            if(count($email) > $numero_maximo)
1685            {
1686                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
1687                return $erros_acumulados;
1688            }
1689            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
1690            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1691            foreach($email as $item)
1692            {
1693                $certificate = $db->get_certificate(strtolower($item));
1694                if(!$certificate)
1695                {
1696                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
1697                    return $erros_acumulados;
1698                }
1699
1700                if (array_key_exists("dberr1", $certificate))
1701                {
1702
1703                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
1704                    return $erros_acumulados;
1705                                }
1706                if (array_key_exists("dberr2", $certificate))
1707                {
1708                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1709                    //continue;
1710                }
1711                        /*  Retirado este teste para evitar mensagem de erro duplicada.
1712                if (!array_key_exists("certs", $certificate))
1713                {
1714                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1715                    continue;
1716                }
1717            */
1718                include_once("../seguranca/classes/CertificadoB.php");
1719
1720                foreach ($certificate['certs'] as $registro)
1721                {
1722                    $c1 = new certificadoB();
1723                    $c1->certificado($registro['chave_publica']);
1724                    if ($c1->apresentado)
1725                    {
1726                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
1727                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
1728                        {
1729                            $aux_mails[] = $registro['chave_publica'];
1730                            $mail_list[] = strtolower($item);
1731                        }
1732                        else
1733                        {
1734                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
1735                            {
1736                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
1737                                    $c1->dados['EXPIRADO'],$c2->revogado);
1738                            }
1739
1740                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
1741                            foreach($c2->erros_ssl as $linha)
1742                            {
1743                                $erros_acumulados .=  $linha . chr(0x0A);
1744                            }
1745                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
1746                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
1747                        }
1748                    }
1749                    else
1750                    {
1751                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
1752                    }
1753                }
1754                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
1755                                {
1756                                        return $erros_acumulados;
1757                        }
1758            }
1759
1760            $mail->Certs_crypt = $aux_mails;
1761        }
1762
[2]1763////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1764                //      Build CID for embedded Images!!!
[449]1765                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[271]1766                $cid_imgs = '';
1767                $name_cid_files = array();
1768                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1769                $cid_array = array();
[449]1770                foreach($cid_imgs[6] as $j => $val){
1771                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[271]1772                        {
[449]1773                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[271]1774                        }
[449]1775                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[271]1776                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[449]1777                       
1778                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[271]1779                                {
[449]1780                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
[271]1781                                        $fileName = "image_".($j).".jpg";
1782                                        $fileCode = "base64";
1783                                        $fileType = "image/jpg";
1784                                }
1785                                else
1786                                {
[449]1787                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[271]1788                                        $file_description = unserialize(rawurldecode($attach_img));
1789
[449]1790                                        foreach($file_description as $i => $descriptor){                               
[271]1791                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1792                                        }
1793                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1794                                        $fileName = $file_description[2];
1795                                        $fileCode = $file_description[4];
1796                                        $fileType = $this->get_file_type($file_description[2]);
[449]1797                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[271]1798                                }
1799                                $tempDir = ini_get("session.save_path");
[449]1800                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
[271]1801                                $f = fopen($tempDir.'/'.$file,"w");
1802                                fputs($f,$fileContent);
1803                                fclose($f);
1804                                if ($fileContent)
1805                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1806                                //else
[449]1807                                //      return "Error loading image attachment content";                                               
[271]1808
1809                }
1810////////////////////////////////////////////////////////////////////////////////////////////////////
[2]1811                //      Build Uploading Attachments!!!
[689]1812                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
[2]1813                {
1814                        $total_uploaded_size = 0;
1815                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
1816                        foreach ($attachments as $attach)
1817                        {
1818                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
1819                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
1820                        }
1821                        if( $total_uploaded_size > $upload_max_filesize)
[504]1822                                return $this->parse_error("message file too big");                     
[828]1823                }
[689]1824                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
[828]1825
[689]1826                        $total_uploaded_size = 0;
1827                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;                       
1828                        foreach($local_attachments as $local_attachment) {
1829                                $file_description = unserialize(rawurldecode($local_attachment));
1830                                $tmp = array_values($file_description);
1831                                foreach($file_description as $i => $descriptor){                               
1832                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1833                                }
1834                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
1835                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
1836                        }
1837                        if( $total_uploaded_size > $upload_max_filesize)
[828]1838                                return 'false';
[689]1839                }
[2]1840////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1841                //      Build Forwarding Attachments!!!
[2]1842                if (count($forwarding_attachments) > 0)
1843                {
1844                        // Bug fixed for array_search function
1845                        if(count($name_cid_files) > 0) {
1846                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
1847                                $name_cid_files[0] = null;
[449]1848                        }                       
1849                       
[2]1850                        foreach($forwarding_attachments as $forwarding_attachment)
1851                        {
[271]1852                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1853                                        $tmp = array_values($file_description);
[449]1854                                        foreach($file_description as $i => $descriptor){                               
[271]1855                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1856                                        }
[449]1857                                        $file_description = $tmp;                                       
[271]1858                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1859                                        $fileName = $file_description[2];
1860                                        if(!array_search(trim($fileName),$name_cid_files)) {
1861                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
[63]1862                                }
[2]1863                        }
1864                }
[37]1865
[2]1866////////////////////////////////////////////////////////////////////////////////////////////////////
[614]1867                // Important message
1868                if($is_important)
1869                        $mail->isImportant();
1870
1871////////////////////////////////////////////////////////////////////////////////////////////////////
[2]1872                // Disposition-Notification-To
1873                if ($return_receipt)
1874                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1875////////////////////////////////////////////////////////////////////////////////////////////////////
[504]1876
[117]1877                $sent = $mail->Send();
[504]1878               
[117]1879                if(!$sent)
[2]1880                {
[504]1881                        return $this->parse_error($mail->ErrorInfo);
[2]1882                }
1883                else
1884                {
[1035]1885            if ($signed && !$params['smime'])
1886                        {
1887                                return $sent;
1888                        }
[449]1889                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]1890                        {
1891                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1892                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
1893                                $now = date("d/m/y H:i:s");
1894                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[449]1895                                $sent = trim($sent);                                                                                           
[117]1896                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1897                        }
[485]1898                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
1899                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]1900                                $contacts = new dynamic_contacts();
[485]1901                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
1902                                return array("success" => true, "new_contacts" => $new_contacts);
[413]1903                        }
[485]1904                        return array("success" => true);
[2]1905                }
1906        }
1907
[1035]1908    function add_recipients_cert($full_address)
1909        {
1910                $result = "";
1911                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
1912                foreach ($parse_address as $val)
1913                {
1914                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1915                        if ($val->mailbox == "INVALID_ADDRESS")
1916                                continue;
1917                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
1918                                continue;
1919                        if (empty($val->personal))
1920                                $result .= $val->mailbox."@".$val->host . ",";
1921                        else
1922                                $result .= $val->mailbox."@".$val->host . ",";
1923                }
1924
1925                return substr($result,0,-1);
1926        }
1927
[2]1928        function add_recipients($recipient_type, $full_address, $mail)
1929        {
[449]1930                $parse_address = imap_rfc822_parse_adrlist($full_address, "");         
1931                foreach ($parse_address as $val)
[2]1932                {
1933                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1934                        if ($val->mailbox == "INVALID_ADDRESS")
1935                                continue;
[449]1936                       
[2]1937                        if (empty($val->personal))
1938                        {
1939                                switch($recipient_type)
1940                                {
1941                                        case "to":
1942                                                $mail->AddAddress($val->mailbox."@".$val->host);
1943                                                break;
1944                                        case "cc":
1945                                                $mail->AddCC($val->mailbox."@".$val->host);
1946                                                break;
1947                                        case "cco":
1948                                                $mail->AddBCC($val->mailbox."@".$val->host);
1949                                                break;
1950                                }
1951                        }
1952                        else
1953                        {
1954                                switch($recipient_type)
1955                                {
1956                                        case "to":
1957                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
1958                                                break;
1959                                        case "cc":
1960                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
1961                                                break;
1962                                        case "cco":
1963                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
1964                                                break;
1965                                }
1966                        }
1967                }
1968                return true;
1969        }
[449]1970       
[2]1971        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
1972        {
[828]1973                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
[449]1974                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);           
[2]1975                if($encoding == 'base64')
[449]1976                        # The function imap_base64 adds a new line
1977                        # at ASCII text, with CRLF line terminators.
1978                        # So is being exchanged for base64_decode.
1979                        #
1980                        #$fileContent = imap_base64($fileContent);
1981                        $fileContent = base64_decode($fileContent);
[2]1982                else if($encoding == 'quoted-printable')
[449]1983                        $fileContent = quoted_printable_decode($fileContent);                           
[2]1984                return $fileContent;
1985        }
[449]1986       
[2]1987        function del_last_caracter($string)
1988        {
1989                $string = substr($string,0,(strlen($string) - 1));
[449]1990                return $string;
[2]1991        }
[449]1992       
[2]1993        function del_last_two_caracters($string)
1994        {
1995                $string = substr($string,0,(strlen($string) - 2));
[449]1996                return $string;
[2]1997        }
[449]1998       
[828]1999        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
[659]2000        {
[990]2001                if ($sort_box_type != "SORTFROM"){
[970]2002                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2003                        foreach($imapsort as $iuid)
2004                                $sort[$iuid] = "";
2005                        $slice_array = true;
2006                }
2007                else
[659]2008                {
[970]2009                        $sort = array();
2010                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2011                        $num_msgs = imap_num_msg($this->mbox);
2012                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
[975]2013                        $slice_array = true;
2014
[983]2015                        for ($i=$num_msgs; $i>0; $i--)
[828]2016                        {
[983]2017                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2018                                        break;
[970]2019                                $iuid = @imap_uid($this->mbox,$i);
2020                                $header = $this->get_header($iuid);
2021                                // List UNSEEN messages.
2022                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2023                                        continue;
2024                                }
2025                                // List SEEN messages.
2026                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2027                                        continue;
2028                                }
2029                                // List ANSWERED messages.
2030                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2031                                        continue;
2032                                }
2033                                // List FLAGGED messages.
2034                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2035                                        continue;
2036                                }
2037
2038                                if($sort_box_type=='SORTFROM') {
2039                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2040                                                $from = $header->to;
2041                                        else
2042                                                $from = $header->from;
2043
2044                                        $tmp = imap_mime_header_decode($from[0]->personal);
2045
2046                                        if ($tmp[0]->text != "")
2047                                                $sort[$iuid] = $tmp[0]->text;
2048                                        else
2049                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2050                                }
2051                                else if($sort_box_type=='SORTSUBJECT') {
2052                                        $sort[$iuid] = $header->subject;
2053                                }
2054                                else if($sort_box_type=='SORTSIZE') {
2055                                        $sort[$iuid] = $header->Size;
2056                                }
2057                                else {
2058                                        $sort[$iuid] = $header->udate;
2059                                }
2060
[659]2061                        }
[970]2062                        natcasesort($sort);
[828]2063
[970]2064                        if ($sort_box_reverse)
2065                                $sort = array_reverse($sort,true);
[659]2066                }
[828]2067
[972]2068                if(!is_array($sort))
2069                        $sort = array();
2070                       
2071                if ($slice_array)
[828]2072                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
[972]2073                       
[970]2074
[828]2075                return $sort;
2076
[659]2077        }
[970]2078
2079
[449]2080        function move_search_messages($params){         
2081                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]2082                $params['new_folder'] = urldecode($params['new_folder']);
2083                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2084                $sel_msgs = explode(",", $params['selected_messages']);
[449]2085                @reset($sel_msgs);     
[163]2086                $sorted_msgs = array();
2087                foreach($sel_msgs as $idx => $sel_msg) {
2088                        $sel_msg = explode(";", $sel_msg);
2089                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2090                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[449]2091                         }     
[163]2092                         else {
2093                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2094                         }
2095                }
2096                @ksort($sorted_msgs);
[449]2097                $last_return = false;           
2098                foreach($sorted_msgs as $folder => $msgs_number) {                     
[163]2099                        $params['msgs_number'] = $msgs_number;
[449]2100                        $params['folder'] = $folder;   
[163]2101                        if($params['new_folder'] && $folder != $params['new_folder']){
[449]2102                                $last_return = $this -> move_messages($params);                         
[163]2103                        }
2104                        elseif(!$params['new_folder'] || $params['delete'] ){
2105                                $last_return = $this -> delete_msgs($params);
2106                                $last_return['deleted'] = true;
2107                        }
2108                }
2109                return $last_return;
2110        }
[449]2111       
[2]2112        function move_messages($params)
2113        {
[449]2114                $folder = $params['folder'];           
2115                $mbox_stream = $this->open_mbox($folder);               
[51]2116                $newmailbox = ($params['new_folder']);
2117                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
[2]2118                $new_folder_name = $params['new_folder_name'];
2119                $msgs_number = $params['msgs_number'];
2120                $return = array('msgs_number' => $msgs_number,
2121                                                'folder' => $folder,
2122                                                'new_folder_name' => $new_folder_name,
[325]2123                                                'border_ID' => $params['border_ID'],
2124                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[449]2125               
[325]2126                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2127        if (substr($folder,0,4) == 'user'){
2128                $acl = $this->getacltouser($folder);
2129                /*
2130                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2131                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2132                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2133                 *   w - write (STORE flags other than SEEN and DELETED)
2134                 *   i - insert (perform APPEND, COPY into mailbox)
2135                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2136                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2137                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2138                 *   a - administer (perform SETACL)
2139                        */
2140                        if (strpos($acl, "d") === false){
2141                                $return['status'] = false;
2142                                return $return;
2143                        }
2144        }
[432]2145        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2146        if (substr($new_folder_name,0,4) == 'user'){
2147                $this->ldap = new ldap_functions();
2148                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2149                        $return['new_folder_name'] = array_pop($tmp_folder_name);
2150                        if (is_numeric($return['new_folder_name']))
2151                                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2152                                        $return['new_folder_name'] = $cn;
2153        }
[828]2154               
[449]2155                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
[51]2156                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]2157                {
[2]2158                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]2159                        // Fix problem in unserialize function JS.
2160                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2161                }
2162               
2163                $mbox_stream = $this->open_mbox($folder);       
[2]2164                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2165                        imap_expunge($mbox_stream);
[51]2166                        if($mbox_stream)
2167                                imap_close($mbox_stream);
[2]2168                        return $return;
2169                }else {
[449]2170                        if(strstr(imap_last_error(),'Over quota')) {                           
[2]2171                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[449]2172                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
2173                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
[2]2174                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]2175                                $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]2176                                if(!$mbox)
2177                                        return imap_last_error();
[449]2178                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
[2]2179                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]2180                                        if($mbox_stream)
2181                                                imap_close($mbox_stream);
[449]2182                                        if($mbox)                                                                       
[51]2183                                                imap_close($mbox);
[449]2184                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
[2]2185                                }
2186                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2187                                        imap_expunge($mbox_stream);
[51]2188                                        if($mbox_stream)
2189                                                imap_close($mbox_stream);
[2]2190                                        // return to original quota limit.
2191                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2192                                                if($mbox)
2193                                                        imap_close($mbox);
[449]2194                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
[2]2195                                        }
[449]2196                                        return $return;                                                                                                 
[2]2197                                }
2198                                else {
[51]2199                                        if($mbox_stream)
2200                                                imap_close($mbox_stream);
[2]2201                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2202                                                if($mbox)
2203                                                        imap_close($mbox);
[449]2204                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
[2]2205                                        }
[449]2206                                        return imap_last_error();                               
[2]2207                                }
[449]2208                               
[2]2209                        }
2210                        else {
[51]2211                                if($mbox_stream)
2212                                        imap_close($mbox_stream);
2213                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]2214                        }
[449]2215                }               
[2]2216        }
[449]2217       
[2]2218        function save_msg($params)
2219        {
[449]2220               
[271]2221                include_once("class.phpmailer.php");
2222                $mail = new PHPMailer();
2223                include_once("class.db_functions.inc.php");
2224                $toaddress = $params['input_to'];
2225                $ccaddress = $params['input_cc'];
2226                $subject = $params['input_subject'];
[320]2227                $msg_uid = $params['msg_id'];
[2]2228                $body = $params['body'];
2229                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
[155]2230                $body = preg_replace("/\n/"," ",$body);
[51]2231                $body = preg_replace("/\r/","",$body);
[271]2232                $forwarding_attachments = $params['forwarding_attachments'];
2233                $attachments = $params['FILES'];
2234                $return_files = $params['FILES'];
[449]2235                 
[271]2236                $folder = $params['folder'];
[449]2237                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
[271]2238                // Fix problem with cyrus delimiter changes.
[449]2239                // Dots in names: enabled/disabled.                             
[271]2240                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2241                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2242                // End Fix.
[449]2243                                       
[271]2244                $mail->SaveMessageInFolder = $folder;
2245                $mail->SMTPDebug = false;
[449]2246                                               
[271]2247                $mail->IsSMTP();
2248                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2249                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2250                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2251                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
[449]2252               
[271]2253                $mail->Sender = $mail->From;
2254                $mail->SenderName = $mail->FromName;
2255                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2256                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]2257                               
[271]2258                $this->add_recipients("to", $toaddress, &$mail);
2259                $this->add_recipients("cc", $ccaddress, &$mail);
2260                $mail->Subject = $subject;
2261                $mail->IsHTML(true);
2262                $mail->Body = $body;
[449]2263               
[320]2264                //      Build CID for embedded Images!!!
[449]2265                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[320]2266                $cid_imgs = '';
2267                $name_cid_files = array();
2268                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2269                $cid_array = array();
[449]2270                foreach($cid_imgs[6] as $j => $val){
2271                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[320]2272                        {
[449]2273                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[320]2274                        }
[449]2275                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[320]2276                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[449]2277                       
2278                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[320]2279                                {
[449]2280                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2281                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
[320]2282                                        $fileName = "image_".($j).".jpg";
2283                                        $fileCode = "base64";
2284                                        $fileType = "image/jpg";
[449]2285                                        $file_attached[0] = $cid_imgs[2][$j];
2286                                        $file_attached[1] = $cid_imgs[4][$j];
2287                                        $file_attached[2] = $fileName;
2288                                        $file_attached[3] = $cid_imgs[6][$j];
2289                                        $file_attached[4] = 'base64';
2290                                        $file_attached[5] = strlen($fileContent); //Size of file
2291                                        $return_forward[] = $file_attached;
[320]2292                                }
2293                                else
2294                                {
[449]2295                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[320]2296                                        $file_description = unserialize(rawurldecode($attach_img));
[449]2297                                        foreach($file_description as $i => $descriptor){                               
[320]2298                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2299                                        }
2300                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2301                                        $fileName = $file_description[2];
2302                                        $fileCode = $file_description[4];
2303                                        $fileType = $this->get_file_type($file_description[2]);
[449]2304                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[320]2305                                        if (!empty($file_description))
2306                                        {
2307                                                $file_description[5] = strlen($fileContent); //Size of file
2308                                                $return_forward[] = $file_description;
2309                                        }
2310                                }
2311                                $tempDir = ini_get("session.save_path");
[449]2312                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
[320]2313                                $f = fopen($tempDir.'/'.$file,"w");
2314                                fputs($f,$fileContent);
2315                                fclose($f);
2316                                if ($fileContent)
2317                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2318                                //else
[449]2319                                //      return "Error loading image attachment content";                                               
[320]2320
2321                }
[449]2322       
2323        //      Build Forwarding Attachments!!!         
[271]2324                if (count($forwarding_attachments) > 0)
2325                {
2326                        foreach($forwarding_attachments as $forwarding_attachment)
2327                        {
2328                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2329                                $tmp = array_values($file_description);
[449]2330                                foreach($file_description as $i => $descriptor){                               
[271]2331                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2332                                }
2333                                $file_description = $tmp;
[449]2334                               
[271]2335                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2336                                $fileName = $file_description[2];
[449]2337                               
[271]2338                                $file_description[5] = strlen($fileContent); //Size of file
2339                                $return_forward[] = $file_description;
[449]2340                       
[271]2341                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2342                        }
2343                }
[449]2344               
[271]2345                if ((count($return_forward) > 0) && (count($return_files) > 0))
2346                        $return_files = array_merge_recursive($return_forward,$return_files);
2347                else
2348                        if (count($return_files) < 1)
2349                                $return_files = $return_forward;
[449]2350       
[271]2351                //      Build Uploading Attachments!!!
[1005]2352                $sizeof_attachments = count($attachments);
2353                if ($sizeof_attachments)
2354                        foreach ($attachments as $numb => $attach){
2355                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2356                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2357                                        switch ($image_type)
2358                                        {
2359                                        case 1: $image_big = imagecreatefromgif($attach['tmp_name']); break;
2360                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2361                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2362                                        case 6:
2363                                                include_once("gd_functions.php");
2364                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2365                                        default:
2366                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2367                                                break;
2368                                        }
2369                                        header('Content-type: image/jpeg');
2370                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2371                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2372                                        if ($width < $max_resolution && $height < $max_resolution){
2373                                                $new_width = $width;
2374                                                $new_height = $height;
2375                                        }
2376                                        else if ($width > $max_resolution){
2377                                                $new_width = $max_resolution;
2378                                                $new_height = $height*($new_width/$width);
2379                                        }
2380                                        else {
2381                                                $new_height = $max_resolution;
2382                                                $new_width = $width*($new_height/$height);
2383                                        }
2384                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2385                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2386                                        $tmpDir = ini_get("session.save_path");
2387                                        $_file = "cid_image_".base_convert(microtime(), 10, 36).".dat";
2388                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2389                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2390                                }
2391                                else
2392                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2393                                // optional name
2394                                }
[449]2395       
2396       
[1005]2397       
[449]2398               
[271]2399                if(!empty($mail->AltBody))
2400            $mail->ContentType = "multipart/alternative";
2401
[828]2402                $mail->error_count = 0; // reset errors
2403                $mail->SetMessageType();
2404                $header = $mail->CreateHeader();
2405                $body = $mail->CreateBody();
2406
[830]2407                $mbox_stream = $this->open_mbox($folder);       
[271]2408                $new_header = str_replace("\n", "\r\n", $header);
2409                $new_body = str_replace("\n", "\r\n", $body);
[830]2410                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
[271]2411                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2412                $return['msg_no'] = $status->uidnext - 1;
2413                $return['folder_id'] = $folder;
[828]2414
[51]2415                if($mbox_stream)
2416                        imap_close($mbox_stream);
[673]2417                if (is_array($return_files))             
[828]2418                        foreach ($return_files as $index => $_attachment) {
2419                                if (array_key_exists("name",$_attachment)){
[271]2420                                unset($return_files[$index]);
2421                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2422                        }
2423                        else
2424                        {
2425                                unset($return_files[$index]);
2426                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2427                        }
2428                }
[449]2429               
[271]2430                $return['files'] = serialize($return_files);
[673]2431                $return["subject"] = $subject;
[449]2432                               
[2]2433                if (!$return['append'])
2434                        $return['append'] = imap_last_error();
[449]2435               
[2]2436                return $return;
2437        }
[449]2438       
[2]2439        function set_messages_flag($params)
2440        {
2441                $folder = $params['folder'];
2442                $msgs_to_set = $params['msgs_to_set'];
2443                $flag = $params['flag'];
2444                $return = array();
2445                $return["msgs_to_set"] = $msgs_to_set;
2446                $return["flag"] = $flag;
[449]2447               
[411]2448                if(!$this->mbox && !is_resource($this->mbox))
[51]2449                        $this->mbox = $this->open_mbox($folder);
[449]2450               
[2]2451                if ($flag == "unseen")
[51]2452                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]2453                elseif ($flag == "seen")
[51]2454                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]2455                elseif ($flag == "answered"){
[51]2456                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2457                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]2458                }
2459                elseif ($flag == "forwarded")
[51]2460                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]2461                elseif ($flag == "flagged")
[51]2462                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[614]2463                elseif ($flag == "unflagged") {
2464                        $flag_importance = false;
2465                        $msgs_number = explode(",",$msgs_to_set);
[659]2466                        $unflagged_msgs = "";
[614]2467                        foreach($msgs_number as $msg_number) {
2468                                preg_match('/importance *: *(.*)\r/i',
2469                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2470                                        ,$importance);         
[673]2471                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]2472                                        $flag_importance=true;
2473                                }
[659]2474                                else {
2475                                        $unflagged_msgs.=$msg_number.",";
2476                                }                               
[614]2477                        }
2478
[659]2479                        if($unflagged_msgs!="") {
2480                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2481                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2482                        }
2483                        else {
2484                                $return["msgs_unflageds"] = false;
2485                        }
2486
[673]2487                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]2488                                $return["status"] = false;
2489                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2490                        }
[659]2491                        else {
2492                                $return["status"] = true;
2493                        }
[614]2494                }
[449]2495               
[411]2496                if($this->mbox && is_resource($this->mbox))
[51]2497                        imap_close($this->mbox);
[2]2498                return $return;
2499        }
[449]2500       
[2]2501        function get_file_type($file_name)
2502        {
2503                $file_name = strtolower($file_name);
2504                $strFileType = strrev(substr(strrev($file_name),0,4));
[449]2505                if ($strFileType == ".asf")
[2]2506                        return "video/x-ms-asf";
2507                if ($strFileType == ".avi")
2508                        return "video/avi";
2509                if ($strFileType == ".doc")
2510                        return "application/msword";
2511                if ($strFileType == ".zip")
2512                        return "application/zip";
2513                if ($strFileType == ".xls")
2514                        return "application/vnd.ms-excel";
2515                if ($strFileType == ".gif")
2516                        return "image/gif";
2517                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2518                        return "image/jpeg";
2519                if ($strFileType == ".png")
2520                        return "image/png";
2521                if ($strFileType == ".wav")
2522                        return "audio/wav";
2523                if ($strFileType == ".mp3")
2524                        return "audio/mpeg3";
2525                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2526                        return "video/mpeg";
2527                if ($strFileType == ".rtf")
2528                        return "application/rtf";
2529                if ($strFileType == ".htm" || $strFileType == "html")
2530                        return "text/html";
[449]2531                if ($strFileType == ".xml")
[2]2532                        return "text/xml";
[449]2533                if ($strFileType == ".xsl")
[2]2534                        return "text/xsl";
[449]2535                if ($strFileType == ".css")
[2]2536                        return "text/css";
[449]2537                if ($strFileType == ".php")
[2]2538                        return "text/php";
[449]2539                if ($strFileType == ".asp")
[2]2540                        return "text/asp";
2541                if ($strFileType == ".pdf")
2542                        return "application/pdf";
2543                if ($strFileType == ".txt")
2544                        return "text/plain";
2545                if ($strFileType == ".wmv")
2546                        return "video/x-ms-wmv";
2547                if ($strFileType == ".sxc")
2548                        return "application/vnd.sun.xml.calc";
2549                if ($strFileType == ".stc")
2550                        return "application/vnd.sun.xml.calc.template";
2551                if ($strFileType == ".sxd")
2552                        return "application/vnd.sun.xml.draw";
2553                if ($strFileType == ".std")
2554                        return "application/vnd.sun.xml.draw.template";
2555                if ($strFileType == ".sxi")
2556                        return "application/vnd.sun.xml.impress";
2557                if ($strFileType == ".sti")
2558                        return "application/vnd.sun.xml.impress.template";
2559                if ($strFileType == ".sxm")
2560                        return "application/vnd.sun.xml.math";
2561                if ($strFileType == ".sxw")
2562                        return "application/vnd.sun.xml.writer";
2563                if ($strFileType == ".sxq")
2564                        return "application/vnd.sun.xml.writer.global";
2565                if ($strFileType == ".stw")
2566                        return "application/vnd.sun.xml.writer.template";
[449]2567               
2568               
2569                return "application/octet-stream";             
[2]2570        }
[449]2571       
[2]2572        function htmlspecialchars_encode($str)
2573        {
[449]2574                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]2575        }
2576        function htmlspecialchars_decode($str)
2577        {
[449]2578                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]2579        }
[449]2580       
[828]2581        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2582        {
2583                if(!$this->mbox || !is_resource($this->mbox))
[51]2584                        $this->mbox = $this->open_mbox($folder);
[432]2585
[828]2586                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2587        }
[449]2588       
[53]2589        function get_info_next_msg($params)
2590        {
2591                $msg_number = $params['msg_number'];
2592                $folder = $params['msg_folder'];
2593                $sort_box_type = $params['sort_box_type'];
2594                $sort_box_reverse = $params['sort_box_reverse'];
2595                $reuse_border = $params['reuse_border'];
2596                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[449]2597                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
2598               
[320]2599                $success = false;
2600                if (is_array($sort_array_msg))
[2]2601                {
[320]2602                        foreach ($sort_array_msg as $i => $value){
2603                                if ($value == $msg_number)
2604                                {
2605                                        $success = true;
2606                                        break;
2607                                }
2608                        }
[2]2609                }
2610
[320]2611                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]2612                {
2613                        $params['status'] = 'false';
2614                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2615                        return $params;
2616                }
[449]2617               
[2]2618                $params = array();
2619                $params['msg_number'] = $sort_array_msg[($i+1)];
2620                $params['msg_folder'] = $folder;
[449]2621               
2622                $return = $this->get_info_msg($params);         
[2]2623                $return["reuse_border"] = $reuse_border;
2624                return $return;
2625        }
2626
2627        function get_info_previous_msg($params)
2628        {
2629                $msg_number = $params['msgs_number'];
2630                $folder = $params['folder'];
2631                $sort_box_type = $params['sort_box_type'];
2632                $sort_box_reverse = $params['sort_box_reverse'];
2633                $reuse_border = $params['reuse_border'];
[53]2634                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2635                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[449]2636               
[320]2637                $success = false;
2638                if (is_array($sort_array_msg))
[2]2639                {
[320]2640                        foreach ($sort_array_msg as $i => $value){
2641                                if ($value == $msg_number)
2642                                {
2643                                        $success = true;
2644                                        break;
2645                                }
2646                        }
[2]2647                }
[320]2648                if (! $success || $i == 0)
2649                {
[2]2650                        $params['status'] = 'false';
2651                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2652                        return $params;
2653                }
[449]2654               
[2]2655                $params = array();
2656                $params['msg_number'] = $sort_array_msg[($i-1)];
2657                $params['msg_folder'] = $folder;
[449]2658               
[2]2659                $return = $this->get_info_msg($params);
2660                $return["reuse_border"] = $reuse_border;
2661                return $return;
2662        }
[449]2663       
[2]2664        // This function updates the values: quota, paging and new messages menu.
2665        function get_menu_values($params){
2666                $return_array = array();
2667                $return_array = $this->get_quota($params);
[449]2668               
[2]2669                $mbox_stream = $this->open_mbox($params['folder']);
[449]2670                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
[51]2671                if($mbox_stream)
2672                        imap_close($mbox_stream);
[449]2673                               
2674                return $return_array;
[2]2675        }
[449]2676       
[325]2677        function get_quota($params){
[449]2678                // folder_id = user/{uid} for shared folders
2679                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2680                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2681                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];             
2682                }
2683                // folder_id = INBOX for inbox folders
2684                else
2685                        $folder_id = "INBOX";
2686               
[1035]2687                if(!$this->mbox || !is_resource($this->mbox))
[51]2688                        $this->mbox = $this->open_mbox();
[345]2689
[325]2690                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]2691                if($this->mbox && is_resource($this->mbox))
[51]2692                        imap_close($this->mbox);
[449]2693                       
[2]2694                if (!$quota){
2695                        return array(
2696                                'quota_percent' => 0,
2697                                'quota_used' => 0,
2698                                'quota_limit' =>  0
2699                        );
2700                }
[449]2701               
[2]2702                if(count($quota) && $quota['limit']) {
2703                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2704                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2705                        if($quota_used >= $quota_limit)
[650]2706                        {
2707                                $quotaPercent = 100;
2708                        }
2709                        else
2710                        {
[2]2711                        $quotaPercent = ($quota_used / $quota_limit)*100;
2712                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
[650]2713                        }
[2]2714                        return array(
2715                                'quota_percent' => floor($quotaPercent),
2716                                'quota_used' => floor($quota_used),
2717                                'quota_limit' =>  floor($quota_limit)
2718                        );
2719                }
[449]2720                else
[2]2721                        return array();
2722        }
[449]2723       
[2]2724        function send_notification($params){
2725                require_once("class.phpmailer.php");
2726                $mail = new PHPMailer();
[449]2727                 
[2]2728                $toaddress = $params['notificationto'];
[449]2729               
2730                $subject = 'Confirmação de leitura: ' . $params['subject'];
[2]2731                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2732                $body .= 'foi lida por: ' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . ' &lt;' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '&gt; em ' . date("d/m/Y H:i");
2733                $mail->SMTPDebug = false;
2734                $mail->IsSMTP();
2735                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2736                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2737                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2738                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2739                $mail->AddAddress($toaddress);
2740                $mail->Subject = $this->htmlspecialchars_decode($subject);
2741
2742                $mail->IsHTML(true);
2743                $mail->Body = $body;
[449]2744               
[2]2745                if(!$mail->Send()){
2746                        return $mail->ErrorInfo;
2747                }
2748                else
2749                        return true;
2750        }
[449]2751       
[2]2752        function empty_trash()
2753        {
[449]2754                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[2]2755                $mbox_stream = $this->open_mbox($folder);
2756                $return = imap_delete($mbox_stream,'1:*');
[51]2757                if($mbox_stream)
2758                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2759                return $return;
2760        }
[449]2761       
[2]2762        function search($params)
2763        {
[673]2764                include("class.imap_attachment.inc.php");
[449]2765                $imap_attachment = new imap_attachment();                               
[2]2766                $criteria = $params['criteria'];
2767                $return = array();
2768                $folders = $this->get_folders_list();
[449]2769               
[2]2770                $j = 0;
2771                foreach($folders as $folder)
2772                {
2773                        $mbox_stream = $this->open_mbox($folder);
2774                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[449]2775                       
[2]2776                        if ($messages == '')
2777                                continue;
[449]2778               
[2]2779                        $i = 0;
2780                        $return[$j] = array();
2781                        $return[$j]['folder_name'] = $folder['name'];
[449]2782                       
[2]2783                        foreach($messages as $msg_number)
2784                        {
[535]2785                                $header = $this->get_header($msg_number);
[2]2786                                if (!is_object($header))
2787                                        return false;
[449]2788                               
[2]2789                                $return[$j][$i]['msg_folder']   = $folder['name'];
2790                                $return[$j][$i]['msg_number']   = $msg_number;
2791                                $return[$j][$i]['Recent']               = $header->Recent;
2792                                $return[$j][$i]['Unseen']               = $header->Unseen;
2793                                $return[$j][$i]['Answered']     = $header->Answered;
2794                                $return[$j][$i]['Deleted']              = $header->Deleted;
2795                                $return[$j][$i]['Draft']                = $header->Draft;
2796                                $return[$j][$i]['Flagged']              = $header->Flagged;
[449]2797       
[535]2798                                $date_msg = gmdate("d/m/Y",$header->udate);
2799                                if (gmdate("d/m/Y") == $date_msg)
2800                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]2801                                else
2802                                        $return[$j][$i]['udate'] = $date_msg;
[449]2803                       
[2]2804                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2805                                $return[$j][$i]['fromaddress'] = '';
2806                                foreach ($fromaddress as $tmp)
2807                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[449]2808                       
[2]2809                                $from = $header->from;
2810                                $return[$j][$i]['from'] = array();
2811                                $tmp = imap_mime_header_decode($from[0]->personal);
2812                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2813                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[449]2814                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]2815
2816                                $to = $header->to;
2817                                $return[$j][$i]['to'] = array();
2818                                $tmp = imap_mime_header_decode($to[0]->personal);
2819                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2820                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[449]2821                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]2822
2823                                $subject = imap_mime_header_decode($header->fetchsubject);
2824                                $return[$j][$i]['subject'] = '';
2825                                foreach ($subject as $tmp)
2826                                        $return[$j][$i]['subject'] .= $tmp->text;
2827
2828                                $return[$j][$i]['Size'] = $header->Size;
2829                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[449]2830                       
[2]2831                                $return[$j][$i]['attachment'] = array();
2832                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[449]2833                                               
[2]2834                                $i++;
2835                        }
2836                        $j++;
[51]2837                        if($mbox_stream)
2838                                imap_close($mbox_stream);
[2]2839                }
[449]2840       
[2]2841                return $return;
2842        }
[449]2843       
[2]2844        function delete_and_show_previous_message($params)
2845        {
2846                $return = $this->get_info_previous_msg($params);
[449]2847               
[2]2848                $params_tmp1 = array();
2849                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2850                $params_tmp1['folder'] = $params['msg_folder'];
2851                $return_tmp1 = $this->delete_msg($params_tmp1);
[449]2852               
[2]2853                $return['msg_number_deleted'] = $return_tmp1;
[449]2854               
[2]2855                return $return;
2856        }
[449]2857               
2858       
[2]2859        function automatic_trash_cleanness($params)
2860        {
2861                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2862                $criteria =  'BEFORE "'.$before_date.'"';
[325]2863                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[2]2864                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2865                if (is_array($messages)){
2866                        foreach ($messages as $msg_number){
2867                                imap_delete($mbox_stream, $msg_number, FT_UID);
2868                        }
2869                }
[51]2870                if($mbox_stream)
2871                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2872                return $messages;
2873        }
2874//      Fix the search problem with special characters!!!!
2875        function remove_accents($string) {
[449]2876                return strtr($string,
2877                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]2878                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2879        }
2880
[469]2881        function search_msg($params = ''){             
[2]2882                $retorno = "";
[271]2883                $mbox_stream = "";
[689]2884                if(strpos($params['condition'],"#")===false) { //local messages
2885                        $search=false;
2886                }
2887                else {
2888                        $search = explode(",",$params['condition']);                   
2889                }
2890
[2]2891                if($search){
2892                        $search_criteria = '';
[673]2893                        foreach($search as $tmp)
2894                        {
[2]2895                                $tmp1 = explode("##",$tmp);
2896                                $name_box = $tmp1[0];
[372]2897                                unset($filter);
2898                                foreach($tmp1 as $index => $criteria)
2899                                {
2900                                        if ($index != 0 && strlen($criteria) != 0)
2901                                        {
2902                                                $filter_array = explode("<=>",rawurldecode($criteria));
2903                                                $filter .= " ".$filter_array[0];
2904                                                $filter .= '"'.$filter_array[1].'"';
2905                                        }
[449]2906                                }               
2907                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
[372]2908                                $filter = $this->remove_accents($filter);
[650]2909                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
[432]2910                                $folder_name = explode($this->imap_delimiter,$name_box);
[469]2911                                if (is_numeric($folder_name[1])) {
2912                                        $this->ldap = new ldap_functions();
2913                                        if ($cn = $this->ldap->uid2cn($folder_name[1])) {
2914                                                $folder_name[1] = $cn;
[432]2915                                        }
2916                                }
2917                                $folder_name = implode($this->imap_delimiter,$folder_name);
[449]2918                               
[271]2919                                if(!is_resource($mbox_stream))
[372]2920                                        $mbox_stream = $this->open_mbox($name_box);
[271]2921                                else
2922                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
[449]2923                       
2924                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2925                               
[271]2926                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2927                                        foreach($all_criterias as $criteria_fixed)
2928                                        {
[372]2929                                                $_filter = $criteria_fixed . substr($filter,4);
[449]2930                                       
[372]2931                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
[449]2932                                               
[271]2933                                                if($search_criteria && count($search_criteria) < 50)
2934                                                {
[2]2935                                                        foreach($search_criteria as $new_search){
[449]2936                                                                $m_token = trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
[271]2937                                                                if(!@strstr($retorno,$m_token))
[2]2938                                                                        $retorno .= $m_token;
2939                                                        }
[449]2940                                                }                                               
2941                                                else if(count($search_criteria) >= 50)                                                 
2942                                                        return "many results";                                         
[2]2943                                        }
[271]2944                                }
[2]2945                                else {
[271]2946                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
[372]2947                                        if( is_array( $search_criteria) )
2948                                        {
2949                                                foreach($search_criteria as $new_search)
[449]2950                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
[2]2951                                        }
2952                                }
2953                        }
[271]2954                }
2955                if($mbox_stream)
[449]2956                        imap_close($mbox_stream);               
2957                                               
[2]2958                return $retorno ? $retorno : "none";
2959        }
[449]2960       
[271]2961        function get_msg($uid_msg,$name_box, $mbox_stream )
2962        {
[828]2963                $header = $this->get_header($uid_msg);
2964                include_once("class.imap_attachment.inc.php");
2965                $imap_attachment = new imap_attachment();
2966                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
2967                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
2968                $flag = $header->Unseen
2969                        .$header->Recent
2970                        .$header->Flagged
2971                        .$header->Draft
2972                        .$header->Answered
2973                        .$header->Deleted
2974                        .$attachments;
2975
2976
[163]2977                $subject = $this->decode_string($header->fetchsubject);
2978                $from = $header->from[0]->mailbox;
[2]2979                if($header->from[0]->personal != "")
2980                        $from = $header->from[0]->personal;
[650]2981                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
[449]2982                return $ret_msg;                   
2983        }       
[828]2984
[2]2985        function size_msg($size){
2986                $var = floor($size/1024);
2987                if($var >= 1){
[449]2988                        return $var." kb";     
[2]2989                }else{
[449]2990                        return $size ." b";     
[2]2991                }
2992        }
2993
2994        function ob_array($the_object)
2995        {
2996           $the_array=array();
2997           if(!is_scalar($the_object))
2998           {
2999               foreach($the_object as $id => $object)
3000               {
3001                   if(is_scalar($object))
3002                   {
3003                       $the_array[$id]=$object;
3004                   }
3005                   else
3006                   {
3007                       $the_array[$id]=$this->ob_array($object);
3008                   }
3009               }
3010               return $the_array;
3011           }
3012           else
3013           {
3014               return $the_object;
3015           }
3016        }
[449]3017       
[2]3018        function getacl()
3019        {
3020                $this->ldap = new ldap_functions();
[449]3021               
[2]3022                $return = array();
[449]3023                $mbox_stream = $this->open_mbox();     
[2]3024                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[449]3025               
[2]3026                $i = 0;
3027                foreach ($mbox_acl as $user => $acl)
3028                {
3029                        if ($user != $this->username)
3030                        {
3031                                $return[$i]['uid'] = $user;
3032                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3033                        }
3034                        $i++;
3035                }
3036                return $return;
3037        }
[449]3038       
[2]3039        function setacl($params)
3040        {
3041                $old_users = $this->getacl();
3042                if (!count($old_users))
3043                        $old_users = array();
[449]3044               
[2]3045                $tmp_array = array();
3046                foreach ($old_users as $index => $user_info)
3047                {
3048                        $tmp_array[$index] = $user_info['uid'];
3049                }
3050                $old_users = $tmp_array;
[449]3051               
[2]3052                $users = unserialize($params['users']);
3053                if (!count($users))
3054                        $users = array();
[449]3055               
[2]3056                //$add_share = array_diff($users, $old_users);
3057                $remove_share = array_diff($old_users, $users);
3058
3059                $mbox_stream = $this->open_mbox();
3060
3061                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3062                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3063
3064                /*if (count($add_share))
3065                {
3066                        foreach ($add_share as $index=>$uid)
3067                        {
3068                        if (is_array($mailboxes_list))
3069                        {
3070                        foreach ($mailboxes_list as $key => $val)
3071                        {
3072                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3073                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3074                        }
3075                        }
3076                        }
3077                }*/
[449]3078               
[2]3079                if (count($remove_share))
3080                {
3081                        foreach ($remove_share as $index=>$uid)
3082                        {
3083                        if (is_array($mailboxes_list))
3084                        {
3085                        foreach ($mailboxes_list as $key => $val)
3086                        {
3087                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3088                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3089                        }
3090                        }
[449]3091                        }       
[2]3092                }
[449]3093               
[2]3094                return true;
3095        }
[449]3096       
[2]3097        function getaclfromuser($params)
3098        {
3099                $useracl = $params['user'];
[449]3100               
[2]3101                $return = array();
3102                $return[$useracl] = 'false';
[449]3103                $mbox_stream = $this->open_mbox();     
[2]3104                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[449]3105               
[2]3106                foreach ($mbox_acl as $user => $acl)
3107                {
3108                        if (($user != $this->username) && ($user == $useracl))
3109                        {
3110                                $return[$user] = $acl;
3111                        }
3112                }
3113                return $return;
3114        }
3115
3116        function getacltouser($user)
3117        {
3118                $return = array();
3119                $mbox_stream = $this->open_mbox();
[325]3120                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3121                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3122                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3123                if(substr($user,0,4) != 'user')
[449]3124                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]3125                else
3126                  $mbox_acl = imap_getacl($mbox_stream, $user);
[2]3127                return $mbox_acl[$this->username];
3128        }
[449]3129       
[2]3130
3131        function setaclfromuser($params)
3132        {
3133                $user = $params['user'];
3134                $acl = $params['acl'];
[449]3135               
[2]3136                $mbox_stream = $this->open_mbox();
3137
3138                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3139                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3140
3141                if (is_array($mailboxes_list))
3142                {
3143                        foreach ($mailboxes_list as $key => $val)
3144                        {
[449]3145                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3146                                $folder = str_replace("&-", "&", $folder);
[2]3147                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3148                                {
[449]3149                                        $return = imap_last_error();
[2]3150                                }
3151                        }
3152                }
[449]3153                if (isset($return))
3154                        return $return;
3155                else
3156                        return true;
[2]3157        }
[449]3158       
[51]3159        function download_attachment($msg,$msgno)
3160        {
[449]3161                $array_parts_attachments = array();             
[51]3162                $array_parts_attachments['names'] = '';
[689]3163                include_once("class.imap_attachment.inc.php");
[449]3164                $imap_attachment = new imap_attachment();               
3165               
[51]3166                if (count($msg->fname[$msgno]) > 0)
3167                {
3168                        $i = 0;
3169                        foreach ($msg->fname[$msgno] as $index=>$fname)
3170                        {
3171                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3172                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
3173                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3174                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3175                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3176                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3177                                $i++;
3178                        }
3179                }
3180                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3181                return $array_parts_attachments;
[449]3182        }       
[69]3183
3184        function spam($params)
3185        {
3186                $is_spam = $params['spam'];
3187                $folder = $params['folder'];
3188                $mbox_stream = $this->open_mbox($folder);
3189                $msgs_number = explode(',',$params['msgs_number']);
3190
3191                foreach($msgs_number as $msg_number) {
[877]3192                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3193                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3194                        $body = imap_body($mbox_stream, $imap_msg_number);
[69]3195                        $msg = $header . $body;
3196                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]3197                        $username = $this->username;
[69]3198                        strtok($email, '@');
3199                        $domain = strtok('@');
3200
[449]3201                        //Encontrar a assinatura do dspam no cabecalho
3202                        $v = explode("\r\n", $header);
3203                        foreach ($v as $linha){
[877]3204                                if (eregi("^Message-ID", $linha)) {
3205                                        $args = explode(" ", $linha);
3206                                        $msg_id = "'$args[1]'";
3207                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
[449]3208                                        $args = explode(" ",$linha);
3209                                        $signature = $args[1];
3210                                }
3211                        }
3212
[877]3213                        // Seleciona qual comando a ser executado
[449]3214                        switch($is_spam){
3215                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3216                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3217                        }
[877]3218
3219                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3220                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
[78]3221                        system($cmd);
[69]3222                }
3223                imap_close($mbox_stream);
3224                return false;
3225        }
[535]3226        function get_header($msg_number){
3227                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3228                if (!is_object($header))
3229                        return false;
3230                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3231                $pdate = date_parse($header->MailDate);
3232                $header->udate +=  $pdate['zone']*(-60);
[659]3233               
[673]3234                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[659]3235                        $flag = preg_match('/importance *: *(.*)\r/i',
3236                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3237                                                ,$importance);         
3238                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3239                }
3240               
[535]3241                return $header;
3242        }
[1000]3243
3244//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
3245///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.
3246
3247    function insert_email($source,$folder,$timestamp){
3248        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3249        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3250        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3251        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3252        $imap_options = '/notls/novalidate-cert';
3253        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3254        if(imap_last_error())
3255        {
3256            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3257       }
3258        if($timestamp){
3259            $tempDir = ini_get("session.save_path");
3260            $file = $tempDir."imap_".md5(microtime());
3261                $f = fopen($file,"w");
3262                fputs($f,base64_encode($source));
3263            fclose($f);
[1012]3264            $command = "python ".$_SERVER['DOCUMENT_ROOT']."expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." ".escapeshellarg($folder)." ".escapeshellarg($file);
3265            $return['command']=exec(escapeshellcmd($command));
[1000]3266        }else{
3267            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3268        }
3269        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3270        $return['msg_no'] = $status->uidnext - 1;
3271                $return['error'] = imap_last_error();
3272        if($mbox_stream)
3273                        imap_close($mbox_stream);
3274        return $return;
3275
3276    }
3277
[1035]3278    function show_decript($params){
3279        $source = $params['source'];
3280        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3281        $source = str_replace(" ", "+", $source,$i);
3282       
3283        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3284            if(!$source = base64_decode($source,true))
3285                return "error ".$source."Espaços ".$i;
3286
3287        }
3288        else {
3289            if(!$source = base64_decode($source))
3290                return "error ".$source."Espaços ".$i;
3291        }
3292
3293        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3294
3295                $get['msg_number'] = $insert['msg_no'];
3296                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3297                $return = $this->get_info_msg($get);
3298                $get['msg_number'] = $params['ID'];
3299                $get['msg_folder'] = $params['folder'];
3300                $tmp = $this->get_info_msg($get);
3301                if(!$tmp['status_get_msg_info'])
3302                {
3303                        $return['msg_day']=$tmp['msg_day'];
3304                        $return['msg_hour']=$tmp['msg_hour'];
3305                        $return['fulldate']=$tmp['fulldate'];
3306                        $return['smalldate']=$tmp['smalldate'];
3307                }
3308                else
3309                {
3310                        $return['msg_day']='';
3311                        $return['msg_hour']='';
3312                        $return['fulldate']='';
3313                        $return['smalldate']='';
3314                }
3315        $return['msg_no'] =$insert['msg_no'];
3316        $return['error'] = $insert['error'];
3317        $return['folder'] = $params['folder'];
3318        //$return['acls'] = $insert['acls'];
3319        $return['original_ID'] =  $params['ID'];
3320
3321        return $return;
3322
3323    }
3324   
[1000]3325//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
3326//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3327
3328    function treat_base64_from_post($source){
3329            $offset = 0;
3330            do
3331            {
3332                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3333                    {
3334                            $inicio = strpos($source, "\n\r", $inicio);
3335                            $fim = strpos($source, '--', $inicio);
3336                            if(!$fim)
3337                                    $fim = strpos($source,"\n\r", $inicio);
3338                            $length = $fim-$inicio;
3339                            $parte = substr( $source,$inicio,$length-1);
3340                            $parte = str_replace(" ", "+", $parte);
3341                            $source = substr_replace($source, $parte, $inicio, $length-1);
3342                    }
3343                    if($offset > $inicio)
3344                    $offset=FALSE;
3345                    else
3346                    $offset = $inicio;
3347            }
3348            while($offset);
3349            return $source;
3350    }
3351
3352//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.
3353
3354    function unarchive_mail($params)
3355    {
3356        $dest_folder = $params['folder'];
3357        $sources = explode("#@#@#@",$params['source']);
3358        $timestamps = explode("#@#@#@",$params['timestamp']);
3359        foreach($sources as $index=>$src) {
3360                        if($src!=""){
3361                                $source = $this->treat_base64_from_post($src);
3362                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3363                        }
3364                }
3365        return $insert;
3366    }
3367
3368    function download_all_local_attachments($params)
3369    {
3370        $source = $params['source'];
3371        $source = $this->treat_base64_from_post($source);
3372        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3373        $exporteml = new ExportEml();
3374        $params['num_msg']=$insert['msg_no'];
3375        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3376        return $exporteml->download_all_attachments($params);
3377    }
[2]3378}
[278]3379?>
Note: See TracBrowser for help on using the repository browser.