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

Revision 828, 98.4 KB checked in by niltonneto, 15 years ago (diff)

Ticket 432 - Otimização do tempo de resposta na leitura de caixas grandes.

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