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

Revision 1012, 105.4 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #550 - Escapando comandos que são executados no shell na função "insert_mail".

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