source: branches/1.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 1342

Revision 1342, 95.6 KB checked in by niltonneto, 15 years ago (diff)

Ticket #561 - Correção das diferenças entre versão publicada e branch 1.2

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