source: branches/2.0/expressoMail1_2/inc/class.imap_functions.inc.php @ 1950

Revision 1950, 124.5 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #879 - Replicando correção que inibe evento onerror em tags html para o branch2.0

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