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

Revision 3923, 146.0 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #1684 - Corrigido mecanismo de ordenação do mobile.

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