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

Revision 3289, 138.4 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1275 - anexos com caracteres especiais convertidos para underline.

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