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

Revision 3831, 145.7 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1565 - Resolvendo problema quando não há nada no campo to.

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