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

Revision 2099, 140.0 KB checked in by niltonneto, 14 years ago (diff)

Ticket #934 - Corrigido problema gerado por include, quando display_errors = on

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