source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 3138

Revision 3138, 136.7 KB checked in by amuller, 14 years ago (diff)

Ticket #1154 - Arruma problema de buscas duplicadas no expressoMail

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