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

Revision 3352, 137.2 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1373 - Acerta traduções relativas ao uso do certificado digital

  • 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
[3298]305                                return ("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);
[3294]1183                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1184                $body = str_replace("\x00", '', $body);
[3250]1185                                         
1186                return  "<span>".$body;
[2]1187        }
1188
[1897]1189        function replace_links( $body )
1190        {
[3018]1191                // Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
1192                // See more informations in www.iana.org
1193                $octets = array(
1194                        'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
1195                        'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
1196                        'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
1197                );
[1897]1198
[3018]1199                $ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
[1472]1200
[3018]1201                $top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
1202                        . 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
1203                        . 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
1204                        . 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
1205                        . 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
1206                        . 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
1207                        . 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
1208                        . 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
1209                        . 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
1210                        . 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
1211                        . 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
1212                        . 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
1213                        . 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
[1707]1214
[3018]1215                $path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
1216                $port = '(?>:\d{2,5})?';
1217                $domain = '(?>[\w\d_\-]+)';
1218                $subdomain = "(?>{$domain}\.)*";
1219                $protocol = '(?>(http|ftp)(s)?:\/\/)?';
1220                $url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
[1707]1221
[3018]1222                $pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
1223                ini_set( 'pcre.backtrack_limit', 300000 );
1224
1225                /*
1226                // PHP 5.3
1227                $replace = function( $matches )
1228                {
1229                        if ( $matches[ 1 ] )
1230                                return $matches[ 0 ];
1231
1232                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1233                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1234                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1235                };
1236                $body = preg_replace_callback( $pattern, $replace, $body );
1237                 */
1238
1239                // PHP 5.2.x - Remover assim que possível
1240                $body = preg_replace_callback( $pattern,
1241                        create_function(
1242                                '$matches',
1243                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
1244                                . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1245                                . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1246                                . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1247                        ), $body
1248                );
1249                ini_set( 'pcre.backtrack_limit', 100000 );
[1897]1250                // E-mail address in the text should create a new e-mail on ExpressoMail
[3018]1251                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1252                $replacement = '$1<a href="mailto:$2">$2</a>$3';
[1897]1253                $body = preg_replace( $pattern, $replacement, $body );
[1707]1254
1255                return $body;
[2]1256        }
1257
[91]1258        function get_signature($msg, $msg_number, $msg_folder)
[1035]1259        {
[3352]1260            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1261            include_once("class.db_functions.inc.php");
1262            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1263            {
1264                $sign = array();
1265                $temp = $this->get_info_head_msg($msg_number);
1266                if($temp['ContentType'] =='normal') return $sign;
1267                $file_type = strtolower($file_type);
1268                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]1269                {
[3352]1270                    if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
1271                    {
1272                        if(!$this->mbox || !is_resource($this->mbox))
1273                            $this->mbox = $this->open_mbox($msg_folder);
[1035]1274
[3352]1275                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[1035]1276
[3352]1277                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1278                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
[1035]1279
[3352]1280                        $certificado = new certificadoB();
1281                        $validade = $certificado->verificar($imap_msg);
[1035]1282
[3352]1283                        if ($certificado->apresentado)
1284                        {
1285                            $from = $header->from;
1286                            foreach ($from as $id => $object)
1287                            {
1288                                $fromname = $object->personal;
1289                                $fromaddress = $object->mailbox . "@" . $object->host;
1290                            }
1291                            foreach ($certificado->erros_ssl as $item)
1292                            {
1293                                $sign[] = $item . "#@#";
1294                            }
[1035]1295
[3352]1296                            if (count($certificado->erros_ssl) < 1)
1297                            {
1298                                $check_msg = 'Message untouched';
1299                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1300                                {
1301                                    $check_msg .= ' and authentic###';
1302                                }
1303                                else
1304                                {
1305                                    $check_msg .= ' with signer different from sender#@#';
1306                                }
1307                                $sign[] = $check_msg;
1308                            }
1309                                               
1310                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1311                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1312                            $sign[] = 'Mail from: ###' . $fromaddress;
1313                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
1314                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1315                            $sign[] = 'Message date: ###' . $header->Date;
[1035]1316
[3352]1317                            $cert = openssl_x509_parse($certificado->cert_assinante);
[1035]1318
[3352]1319                            $sign_alert = array();
1320                            $sign_alert[] = 'Certificate Owner###:\n';
1321                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
1322                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1323                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
1324                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
1325                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
1326                            $sign_alert[] = 'Personal Data###:' . '\n';
1327                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
1328                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
1329                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
1330                            $sign_alert[]= 'Certificate Issuer###:\n';
1331                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
1332                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
1333                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
1334                            $sign_alert[]= 'Validity###:\n';
1335                            $H = data_hora($cert[validFrom]);
1336                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1337                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
1338                            $H = data_hora($cert[validTo]);
1339                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1340                            $sign_alert[]= 'Valid Until### ' . $X;
1341                            $sign[] = $sign_alert;
1342
1343                            $this->db = new db_functions();
1344                           
1345                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1346                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1347                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
[91]1348                        }
[3352]1349                        else
1350                        {
1351                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1352                            foreach($certificado->erros_ssl as $item)
1353                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1354                        }
1355                    }
[91]1356                }
[3352]1357            }
1358            return $sign;
[91]1359        }
1360
[51]1361        function get_thumbs($msg, $msg_number, $msg_folder)
[2]1362        {
1363                $thumbs_array = array();
1364                $i = 0;
1365        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1366        {
1367                $file_type = strtolower($file_type);
1368                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1369                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1370                                $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]1371                                $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]1372                                        $thumbs_array[] = $href;
1373                        }
1374                        $i++;
1375                }
1376        }
1377        return $thumbs_array;
1378        }
[1472]1379
[2]1380        /*function delete_msg($params)
1381        {
1382                $folder = $params['folder'];
1383                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[1472]1384
[2]1385                $mbox_stream = $this->open_mbox($folder);
[1472]1386
[2]1387                foreach ($msgs_to_delete as $msg_number){
1388                        imap_delete($mbox_stream, $msg_number, FT_UID);
1389                }
1390                imap_close($mbox_stream, CL_EXPUNGE);
1391                return $params['msgs_to_delete'];
1392        }*/
1393
1394        // Novo
1395        function delete_msgs($params)
1396        {
[1472]1397
[2]1398                $folder = $params['folder'];
[51]1399                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]1400                $msgs_number = explode(",",$params['msgs_number']);
1401                $border_ID = $params['border_ID'];
[1472]1402
[2]1403                $return = array();
[1472]1404
[449]1405                if ($params['get_previous_msg']){
[2]1406                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]1407                        // Fix problem in unserialize function JS.
1408                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1409                }
[2]1410
[1472]1411                //$mbox_stream = $this->open_mbox($folder);
[504]1412                $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]1413
[2]1414                foreach ($msgs_number as $msg_number)
1415                {
1416                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1417                                $return['msgs_number'][] = $msg_number;
1418                }
[1472]1419
[2]1420                $return['folder'] = $folder;
1421                $return['border_ID'] = $border_ID;
[1472]1422
[51]1423                if($mbox_stream)
1424                        imap_close($mbox_stream, CL_EXPUNGE);
[2]1425                return $return;
1426        }
1427
[1472]1428
[2]1429        function refresh($params)
1430        {
[3265]1431
[2]1432                $folder = $params['folder'];
1433                $msg_range_begin = $params['msg_range_begin'];
1434                $msg_range_end = $params['msg_range_end'];
1435                $msgs_existent = $params['msgs_existent'];
[1472]1436                $sort_box_type = $params['sort_box_type'];
[2]1437                $sort_box_reverse = $params['sort_box_reverse'];
1438                $msgs_in_the_server = array();
[53]1439                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]1440                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1441                $msgs_in_the_server = array_keys($msgs_in_the_server);
1442                if(!count($msgs_in_the_server))
[51]1443                        return array();
[1472]1444
[828]1445                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
[1472]1446                $msgs_in_the_client = explode(",", $msgs_existent);
[51]1447
[2]1448                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[271]1449                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[1472]1450
[2]1451                $msgs_to_exec = array();
[3265]1452                foreach($msg_to_insert as $msg_number)
1453                        $msgs_to_exec[] = $msg_number;
1454                sort($msgs_to_exec);
[1472]1455
[2]1456                $return = array();
1457                $i = 0;
[3265]1458                foreach($msgs_to_exec as $msg_number)
[2]1459                {
[614]1460                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
[1472]1461                        * atributos do cabeçalho. Como eu preciso do atributo Importance
[614]1462                        * para saber se o email é importante ou não, uso abaixo a função
1463                        * imap_fetchheader e busco o atributo importance nela para passar
1464                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1465                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1466                        * não preciso reimplementar o método utilizando o fetchheader.
1467                        */
[3352]1468                   
[3265]1469                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
[1035]1470                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[689]1471                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
[1472]1472
[1752]1473                        $msg_sample = $this->get_msg_sample($msg_number);
1474                        $return[$i]['msg_sample'] = $msg_sample;
1475
[535]1476                        $header = $this->get_header($msg_number);
[2]1477                        if (!is_object($header))
[828]1478                                continue;
1479
[2]1480                        $return[$i]['msg_number']       = $msg_number;
[1472]1481
[2]1482                        $return[$i]['msg_folder']       = $folder;
[3265]1483                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1484                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
[2]1485                        $return[$i]['Recent']           = $header->Recent;
1486                        $return[$i]['Unseen']           = $header->Unseen;
1487                        $return[$i]['Answered']         = $header->Answered;
1488                        $return[$i]['Deleted']          = $header->Deleted;
1489                        $return[$i]['Draft']            = $header->Draft;
1490                        $return[$i]['Flagged']          = $header->Flagged;
1491
[3106]1492                        $return[$i]['udate'] = $header->udate;
1493               
[2]1494                        $from = $header->from;
1495                        $return[$i]['from'] = array();
1496                        $tmp = imap_mime_header_decode($from[0]->personal);
1497                        $return[$i]['from']['name'] = $tmp[0]->text;
1498                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]1499                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[2]1500                        if(!$return[$i]['from']['name'])
1501                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[1472]1502
[2]1503                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1504                        $return[$i]['toaddress'] = '';
1505                        foreach ($toaddress as $tmp)
1506                                $return[$i]['toaddress'] .= $tmp->text;*/
1507                        $to = $header->to;
1508                        $return[$i]['to'] = array();
1509                        $tmp = imap_mime_header_decode($to[0]->personal);
1510                        $return[$i]['to']['name'] = $tmp[0]->text;
1511                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1512                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[1472]1513
[2]1514                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1515
1516                        $return[$i]['Size'] = $header->Size;
1517                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]1518
[2]1519                        $return[$i]['attachment'] = array();
[3265]1520                        if (!isset($imap_attachment))
1521                        {
1522                                include_once("class.imap_attachment.inc.php");
1523                                $imap_attachment = new imap_attachment();
1524                        }
[51]1525                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]1526                        $i++;
1527                }
[3265]1528                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
1529                $return['sort_box_type'] = $params['sort_box_type'];
[51]1530                $return['new_msgs'] = imap_num_recent($this->mbox);
[271]1531                $return['msgs_to_delete'] = $msg_to_delete;
[411]1532                if($this->mbox && is_resource($this->mbox))
[51]1533                        imap_close($this->mbox);
[828]1534
[2]1535                return $return;
1536        }
1537
[1035]1538     /**
1539     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1540     * assinado ou cifrado.
1541     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1542     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1543     * @param $msg_number O número da mesagem
1544     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1545     */
1546    function getMessageType($msg_number, $headers = false){
1547
1548            $contentType = "normal";
1549            if (!$headers){
1550                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1551            }
1552            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1553            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1554                $contentType = "signature";
1555            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1556                $contentType = "cipher";
1557            }
1558
1559            return $contentType;
1560    }
1561
[1375]1562         /**
1563     * Metodo que retorna todas as pastas do usuario logado.
1564     * @param $params array opcional para repassar os argumentos ao metodo.
1565     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1566     * excluindo as compartilhadas para ele.
[1472]1567     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
[1375]1568     * folder_id, folder_name, folder_parent e folder_hasChildren.
[1472]1569     */
[449]1570        function get_folders_list($params = null)
[2]1571        {
[1472]1572                $mbox_stream = $this->open_mbox();
[1953]1573                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1574                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1575                }
[650]1576
[1472]1577
[1824]1578                $inbox = 'INBOX';
1579                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[3018]1580                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1581                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1582                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1583                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1584                // Free others requests
1585                session_write_close();
[1816]1586
[3018]1587                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1588                $folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
[3192]1589                if ( $params && $params['noSharedFolders'] )
1590                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ) + $folders_list;
[3018]1591                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1592
1593                $tmp = array();
1594                $resultMine = array();
1595                $resultDefault = array();
1596
[2]1597                if (is_array($folders_list)) {
1598                        reset($folders_list);
[1816]1599                        $this->ldap = new ldap_functions();
[1472]1600
[2]1601                        $i = 0;
1602                        while (list($key, $val) = each($folders_list)) {
1603                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
[1035]1604
[2]1605                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1606                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
[1816]1607                                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1608                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1609                                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1610                                        continue;
1611                                }
1612                                $result[$i]['folder_unseen'] = $status->unseen;
[2]1613                                $folder_id = $tmp_folder_id[1];
1614                                $result[$i]['folder_id'] = $folder_id;
[1472]1615
[2]1616                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1617                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
[96]1618                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
[3018]1619                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
[1340]1620                                        //$this->ldap = new ldap_functions();
[1816]1621                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
[325]1622                                                $result[$i]['folder_name'] = $cn;
1623                                        }
1624                                }
[1472]1625
[2]1626                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1627                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[1472]1628
[96]1629                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
[2]1630                                        $result[$i]['folder_hasChildren'] = 1;
1631                                else
1632                                        $result[$i]['folder_hasChildren'] = 0;
1633
[1816]1634                                switch ($tmp_folder_id[1]) {
[1824]1635                                        case $inbox:
1636                                        case $sent:
1637                                        case $drafts:
1638                                        case $spam:
1639                                        case $trash:
[1816]1640                                                $resultDefault[]=$result[$i];
1641                                        default:
1642                                                $resultMine[]=$result[$i];
1643                                }
1644
[1472]1645                                $i++;
[2]1646                        }
1647                }
[1472]1648
[1816]1649                // Sorting resultMine
1650                foreach ($resultMine as $folder_info)
[2]1651                {
1652                        $array_tmp[] = $folder_info['folder_id'];
1653                }
[1472]1654
[2]1655                natcasesort($array_tmp);
[1472]1656
[2]1657                foreach ($array_tmp as $key => $folder_id)
1658                {
[1816]1659                        $result2[] = $resultMine[$key];
[2]1660                }
[1816]1661               
1662                $resultDefault2=$resultDefault;
1663                // Sorting resultDefault
1664                foreach ($resultDefault as $key => $folder_id)
1665                {
[1472]1666
[1816]1667                        switch ($resultDefault[$key]['folder_id']) {
[1824]1668                                case $inbox:
[1816]1669                                        $resultDefault2[0] = $resultDefault[$key];
1670                                        break;
[1824]1671                                case $sent:
[1816]1672                                        $resultDefault2[1] = $resultDefault[$key];
1673                                        break;
[1824]1674                                case $drafts:
[1816]1675                                        $resultDefault2[2] = $resultDefault[$key];
1676                                        break;
[1824]1677                                case $spam:
[1816]1678                                        $resultDefault2[3] = $resultDefault[$key];
1679                                        break;
[1824]1680                                case $trash:
[1816]1681                                        $resultDefault2[4] = $resultDefault[$key];
1682                                        break;
1683                        }
1684                }
1685
1686                // Merge default folders and mines
1687                $result2 = array_merge($resultDefault2, $result2);
1688               
[449]1689                $current_folder = "INBOX";
1690                if($params && $params['folder'])
1691                        $current_folder = $params['folder'];
[1739]1692                return array_merge($result2, $this->get_quota(array('folder_id' => $current_folder)));
[2]1693        }
[1472]1694
[2]1695        function create_mailbox($arr)
1696        {
1697                $namebox        = $arr['newp'];
1698                $mbox_stream = $this->open_mbox();
1699                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]1700                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[1472]1701
[2]1702                $result = "Ok";
[51]1703                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]1704                {
1705                        $result = implode("<br />\n", imap_errors());
[1472]1706                }
1707
[51]1708                if($mbox_stream)
1709                        imap_close($mbox_stream);
[1472]1710
[2]1711                return $result;
[1472]1712
[2]1713        }
[1472]1714
[2]1715        function create_extra_mailbox($arr)
1716        {
1717                $nameboxs = explode(";",$arr['nw_folders']);
1718                $result = "";
1719                $mbox_stream = $this->open_mbox();
1720                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1472]1721                foreach($nameboxs as $key=>$tmp){
[2]1722                        if($tmp != ""){
1723                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1724                                        $result = implode("<br />\n", imap_errors());
[51]1725                                        if($mbox_stream)
[1472]1726                                                imap_close($mbox_stream);
[2]1727                                        return $result;
1728                                }
1729                        }
1730                }
[51]1731                if($mbox_stream)
1732                        imap_close($mbox_stream);
[2]1733                return true;
1734        }
[1472]1735
[2]1736        function delete_mailbox($arr)
1737        {
1738                $namebox = $arr['del_past'];
1739                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1953]1740                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
[2]1741                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[1472]1742
[2]1743                $result = "Ok";
1744                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1745                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1746                {
1747                        $result = implode("<br />\n", imap_errors());
1748                }
[1953]1749                /*
[51]1750                if($mbox_stream)
1751                        imap_close($mbox_stream);
[1953]1752                */
[2]1753                return $result;
1754        }
[1472]1755
[2]1756        function ren_mailbox($arr)
1757        {
1758                $namebox = $arr['current'];
1759                $new_box = $arr['rename'];
1760                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1761                $mbox_stream = $this->open_mbox();
1762                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[1472]1763
[2]1764                $result = "Ok";
1765                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]1766                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[1472]1767
[2]1768                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1769                {
[1472]1770                        $result = imap_errors();
[2]1771                }
[51]1772                if($mbox_stream)
1773                        imap_close($mbox_stream);
[2]1774                return $result;
[1472]1775
[2]1776        }
[1472]1777
[2]1778        function get_num_msgs($params)
1779        {
1780                $folder = $params['folder'];
[411]1781                if(!$this->mbox || !is_resource($this->mbox)) {
[2]1782                        $this->mbox = $this->open_mbox($folder);
[411]1783                        if(!$this->mbox || !is_resource($this->mbox))
[2]1784                        return imap_last_error();
[1472]1785                }
[2]1786                $num_msgs = imap_num_msg($this->mbox);
[432]1787                if($this->mbox && is_resource($this->mbox))
[51]1788                        imap_close($this->mbox);
[1472]1789
[2]1790                return $num_msgs;
1791        }
[1472]1792
[1912]1793        function folder_exists($folder){
1794                $mbox =  $this->open_mbox();
1795                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
1796                $list = imap_getmailboxes($mbox,$serverString, $folder);
1797                $return = is_array($list);             
1798                imap_close($mbox);
1799                return $return;
1800        }
1801       
[2]1802        function send_mail($params)
1803        {
1804                include_once("class.phpmailer.php");
1805                $mail = new PHPMailer();
1806                include_once("class.db_functions.inc.php");
1807                $db = new db_functions();
1808                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[449]1809                ##
1810                # @AUTHOR Rodrigo Souza dos Santos
1811                # @DATE 2008/09/17
1812                # @BRIEF Checks if the user has permission to send an email with the email address used.
1813                ##
1814                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1815                {
1816                        $deny = true;
1817                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1818                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1819                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1820
1821                        if ( $deny )
1822                                return "The server denied your request to send a mail, you cannot use this mail address.";
1823                }
[828]1824
[2]1825                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1826                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1827                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1828                $subject = $params['input_subject'];
[271]1829                $msg_uid = $params['msg_id'];
[2]1830                $return_receipt = $params['input_return_receipt'];
[614]1831                $is_important = $params['input_important_message'];
[1035]1832        $encrypt = $params['input_return_cripto'];
1833                $signed = $params['input_return_digital'];
1834
1835                if($params['smime'])
1836        {
1837            $body = $params['smime'];
1838            $mail->SMIME = true;
1839            // A MSG assinada deve ser testada neste ponto.
1840            // Testar o certificado e a integridade da msg....
[3271]1841            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]1842            $erros_acumulados = '';
1843            $certificado = new certificadoB();
1844            $validade = $certificado->verificar($body);
1845            if(!$validade)
1846            {
1847                foreach($certificado->erros_ssl as $linha_erro)
1848                {
1849                    $erros_acumulados .= $linha_erro;
1850                }
1851            }
1852            else
1853            {
1854                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1855                if ($certificado->apresentado)
1856                {
1857                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1858                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1859                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1860                }
1861                else
1862                {
1863                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1864                }
1865            }
1866            if(!$erros_acumulados =='')
1867            {
1868                return $erros_acumulados;
1869            }
1870        }
1871        else
1872        {
1873            $body = $params['body'];
[3250]1874            //Compatibilização com Outlook, ao encaminhar a mensagem
1875            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
[1035]1876        }
[1247]1877                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
[2]1878                $attachments = $params['FILES'];
1879                $forwarding_attachments = $params['forwarding_attachments'];
[689]1880                $local_attachments = $params['local_attachments'];
[1912]1881               
1882                //Test if must be saved in shared folder and change if necessary
1883                if( $fromaddress[2] == 'y' ){
1884                        //build shared folder path
1885                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
1886                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
1887                        else $folder =  $params['folder'];                     
1888                } else  {
1889                        $folder = $params['folder'];                   
1890                }
1891               
[1472]1892                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1893                $folder_name = $params['folder_name'];
[6]1894                // Fix problem with cyrus delimiter changes.
[1472]1895                // Dots in names: enabled/disabled.
[6]1896                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1897                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1898                // End Fix.
[1472]1899                if ($folder != 'null'){
[2]1900                        $mail->SaveMessageInFolder = $folder;
1901                }
1902////////////////////////////////////////////////////////////////////////////////////////////////////
1903                $mail->SMTPDebug = false;
[1035]1904
1905                if($signed && !$params['smime'])
1906                {
1907            $mail->Mailer = "smime";
1908                        $mail->SignedBody = true;
1909                }
1910                else
1911            $mail->IsSMTP();
[1472]1912
[2]1913                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1914                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1915                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1916                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1917                if($fromaddress){
1918                        $mail->Sender = $mail->From;
1919                        $mail->SenderName = $mail->FromName;
1920                        $mail->FromName = $fromaddress[0];
1921                        $mail->From = $fromaddress[1];
1922                }
[1472]1923
[2]1924                $this->add_recipients("to", $toaddress, &$mail);
1925                $this->add_recipients("cc", $ccaddress, &$mail);
1926                $this->add_recipients("cco", $ccoaddress, &$mail);
1927                $mail->Subject = $subject;
[3024]1928                $mail->IsHTML($params['type'] != 'textplain');
[1035]1929                $mail->Body = $body;
[271]1930
[1035]1931        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
1932                {
1933                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
1934            $email = explode(",",$email);
1935            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
1936            // Deve ser verificado um numero limite de destinatarios.
1937            // Deve ser verificado se os certificados sao validos.
1938            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
1939            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
1940            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
1941            $erros_acumulados = "";
1942            $aux_mails = array();
1943            $mail_list = array();
1944            if(count($email) > $numero_maximo)
1945            {
1946                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
1947                return $erros_acumulados;
1948            }
1949            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
1950            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1951            foreach($email as $item)
1952            {
1953                $certificate = $db->get_certificate(strtolower($item));
1954                if(!$certificate)
1955                {
1956                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
1957                    return $erros_acumulados;
1958                }
1959
1960                if (array_key_exists("dberr1", $certificate))
1961                {
1962
1963                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
1964                    return $erros_acumulados;
1965                                }
1966                if (array_key_exists("dberr2", $certificate))
1967                {
1968                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1969                    //continue;
1970                }
1971                        /*  Retirado este teste para evitar mensagem de erro duplicada.
1972                if (!array_key_exists("certs", $certificate))
1973                {
1974                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1975                    continue;
1976                }
1977            */
[3271]1978                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]1979
1980                foreach ($certificate['certs'] as $registro)
1981                {
1982                    $c1 = new certificadoB();
1983                    $c1->certificado($registro['chave_publica']);
1984                    if ($c1->apresentado)
1985                    {
1986                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
1987                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
1988                        {
1989                            $aux_mails[] = $registro['chave_publica'];
1990                            $mail_list[] = strtolower($item);
1991                        }
1992                        else
1993                        {
1994                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
1995                            {
1996                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
1997                                    $c1->dados['EXPIRADO'],$c2->revogado);
1998                            }
1999
2000                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2001                            foreach($c2->erros_ssl as $linha)
2002                            {
2003                                $erros_acumulados .=  $linha . chr(0x0A);
2004                            }
2005                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2006                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2007                        }
2008                    }
2009                    else
2010                    {
2011                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2012                    }
2013                }
2014                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2015                                {
2016                                        return $erros_acumulados;
2017                        }
2018            }
2019
2020            $mail->Certs_crypt = $aux_mails;
2021        }
[3018]2022                // Build CID images
2023                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
[1035]2024
[2]2025                //      Build Uploading Attachments!!!
[689]2026                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
[2]2027                {
2028                        $total_uploaded_size = 0;
[1264]2029                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
[2]2030                        foreach ($attachments as $attach)
2031                        {
2032                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2033                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2034                        }
[1247]2035                        if( $total_uploaded_size > $upload_max_filesize)
[1472]2036                                return $this->parse_error("message file too big");
[828]2037                }
[689]2038                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
[828]2039
[689]2040                        $total_uploaded_size = 0;
[1472]2041                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
[689]2042                        foreach($local_attachments as $local_attachment) {
2043                                $file_description = unserialize(rawurldecode($local_attachment));
2044                                $tmp = array_values($file_description);
[1472]2045                                foreach($file_description as $i => $descriptor){
[689]2046                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2047                                }
2048                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2049                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2050                        }
2051                        if( $total_uploaded_size > $upload_max_filesize)
[828]2052                                return 'false';
[689]2053                }
[2]2054////////////////////////////////////////////////////////////////////////////////////////////////////
[271]2055                //      Build Forwarding Attachments!!!
[2]2056                if (count($forwarding_attachments) > 0)
2057                {
2058                        // Bug fixed for array_search function
[3018]2059                        $name_cid_files = array();
[2]2060                        if(count($name_cid_files) > 0) {
2061                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2062                                $name_cid_files[0] = null;
[1472]2063                        }
2064
[2]2065                        foreach($forwarding_attachments as $forwarding_attachment)
2066                        {
[271]2067                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2068                                        $tmp = array_values($file_description);
[1472]2069                                        foreach($file_description as $i => $descriptor){
[271]2070                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2071                                        }
[1472]2072                                        $file_description = $tmp;
[271]2073                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2074                                        $fileName = $file_description[2];
2075                                        if(!array_search(trim($fileName),$name_cid_files)) {
2076                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
[63]2077                                }
[2]2078                        }
2079                }
[37]2080
[2]2081////////////////////////////////////////////////////////////////////////////////////////////////////
[614]2082                // Important message
2083                if($is_important)
2084                        $mail->isImportant();
2085
2086////////////////////////////////////////////////////////////////////////////////////////////////////
[2]2087                // Disposition-Notification-To
2088                if ($return_receipt)
2089                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2090////////////////////////////////////////////////////////////////////////////////////////////////////
[504]2091
[117]2092                $sent = $mail->Send();
[1472]2093
[117]2094                if(!$sent)
[2]2095                {
[504]2096                        return $this->parse_error($mail->ErrorInfo);
[2]2097                }
2098                else
2099                {
[1035]2100            if ($signed && !$params['smime'])
2101                        {
2102                                return $sent;
2103                        }
[1472]2104                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]2105                        {
2106                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2107                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2108                                $now = date("d/m/y H:i:s");
2109                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[1472]2110                                $sent = trim($sent);
[117]2111                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2112                        }
[1472]2113                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
[485]2114                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]2115                                $contacts = new dynamic_contacts();
[485]2116                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2117                                return array("success" => true, "new_contacts" => $new_contacts);
[413]2118                        }
[485]2119                        return array("success" => true);
[2]2120                }
2121        }
[3018]2122        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2123        {
2124                //      Build CID for embedded Images!!!
2125                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2126                $cid_imgs = '';
2127                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2128                $cid_array = array();
2129                foreach($cid_imgs[6] as $j => $val){
2130                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2131                        {
2132                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2133                        }
2134                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2135                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[2]2136
[3018]2137                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2138                        {
2139                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2140                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2141                                $fileName = "image_".($j).".jpg";
2142                                $fileCode = "base64";
2143                                $fileType = "image/jpg";
2144                                $file_attached[0] = $cid_imgs[2][$j];
2145                                $file_attached[1] = $cid_imgs[4][$j];
2146                                $file_attached[2] = $fileName;
2147                                $file_attached[3] = $cid_imgs[6][$j];
2148                                $file_attached[4] = 'base64';
2149                                $file_attached[5] = strlen($fileContent); //Size of file
2150                                $return_forward[] = $file_attached;
2151
2152                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2153                                if ($file_attached[3] == $attachment_[3])
2154                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2155                        }
2156                        else
2157                        {
2158                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2159                                $file_description = unserialize(rawurldecode($attach_img));
2160                                if (is_array($file_description))
2161                                        foreach($file_description as $i => $descriptor){                                 
2162                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2163                                        }
2164                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2165                                $fileName = $file_description[2];
2166                                $fileCode = $file_description[4];
2167                                $fileType = $this->get_file_type($file_description[2]);
2168                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2169                                if (!empty($file_description))
2170                                {
2171                                        $file_description[5] = strlen($fileContent); //Size of file
2172                                        $return_forward[] = $file_description;
2173                                }
2174                        }
2175                        $tempDir = ini_get("session.save_path");
2176                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2177                        $f = fopen($tempDir.'/'.$file,"w");
2178                        fputs($f,$fileContent);
2179                        fclose($f);
2180                        if ($fileContent)
2181                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2182                        //else
2183                        //      return "Error loading image attachment content";                                                 
2184
2185                }
2186                return $return_forward;
2187        }
2188        function add_recipients_cert($full_address)
[1035]2189        {
2190                $result = "";
2191                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2192                foreach ($parse_address as $val)
2193                {
2194                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2195                        if ($val->mailbox == "INVALID_ADDRESS")
2196                                continue;
2197                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2198                                continue;
2199                        if (empty($val->personal))
2200                                $result .= $val->mailbox."@".$val->host . ",";
2201                        else
2202                                $result .= $val->mailbox."@".$val->host . ",";
2203                }
2204
2205                return substr($result,0,-1);
2206        }
2207
[2]2208        function add_recipients($recipient_type, $full_address, $mail)
2209        {
[1472]2210                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2211                foreach ($parse_address as $val)
[2]2212                {
2213                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2214                        if ($val->mailbox == "INVALID_ADDRESS")
2215                                continue;
[1472]2216
[2]2217                        if (empty($val->personal))
2218                        {
2219                                switch($recipient_type)
2220                                {
2221                                        case "to":
2222                                                $mail->AddAddress($val->mailbox."@".$val->host);
2223                                                break;
2224                                        case "cc":
2225                                                $mail->AddCC($val->mailbox."@".$val->host);
2226                                                break;
2227                                        case "cco":
2228                                                $mail->AddBCC($val->mailbox."@".$val->host);
2229                                                break;
2230                                }
2231                        }
2232                        else
2233                        {
2234                                switch($recipient_type)
2235                                {
2236                                        case "to":
2237                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2238                                                break;
2239                                        case "cc":
2240                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2241                                                break;
2242                                        case "cco":
2243                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2244                                                break;
2245                                }
2246                        }
2247                }
2248                return true;
2249        }
[1472]2250
[2]2251        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2252        {
[828]2253                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
[1472]2254                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
[2]2255                if($encoding == 'base64')
[449]2256                        # The function imap_base64 adds a new line
2257                        # at ASCII text, with CRLF line terminators.
2258                        # So is being exchanged for base64_decode.
2259                        #
2260                        #$fileContent = imap_base64($fileContent);
2261                        $fileContent = base64_decode($fileContent);
[2]2262                else if($encoding == 'quoted-printable')
[1472]2263                        $fileContent = quoted_printable_decode($fileContent);
[2]2264                return $fileContent;
2265        }
[1472]2266
[2]2267        function del_last_caracter($string)
2268        {
2269                $string = substr($string,0,(strlen($string) - 1));
[1472]2270                return $string;
[2]2271        }
[1472]2272
[2]2273        function del_last_two_caracters($string)
2274        {
2275                $string = substr($string,0,(strlen($string) - 2));
[1472]2276                return $string;
[2]2277        }
[1472]2278
[828]2279        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
[659]2280        {
[1625]2281                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
[970]2282                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2283                        foreach($imapsort as $iuid)
2284                                $sort[$iuid] = "";
[1518]2285                       
2286                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2287                                $slice_array = false;
2288                        else
2289                                $slice_array = true;
[970]2290                }
2291                else
[659]2292                {
[970]2293                        $sort = array();
2294                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2295                        $num_msgs = imap_num_msg($this->mbox);
2296                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
[975]2297                        $slice_array = true;
2298
[983]2299                        for ($i=$num_msgs; $i>0; $i--)
[828]2300                        {
[983]2301                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2302                                        break;
[970]2303                                $iuid = @imap_uid($this->mbox,$i);
2304                                $header = $this->get_header($iuid);
2305                                // List UNSEEN messages.
2306                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2307                                        continue;
2308                                }
2309                                // List SEEN messages.
2310                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2311                                        continue;
2312                                }
2313                                // List ANSWERED messages.
2314                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2315                                        continue;
2316                                }
2317                                // List FLAGGED messages.
2318                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2319                                        continue;
2320                                }
2321
2322                                if($sort_box_type=='SORTFROM') {
2323                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2324                                                $from = $header->to;
2325                                        else
2326                                                $from = $header->from;
2327
2328                                        $tmp = imap_mime_header_decode($from[0]->personal);
2329
2330                                        if ($tmp[0]->text != "")
2331                                                $sort[$iuid] = $tmp[0]->text;
2332                                        else
2333                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2334                                }
2335                                else if($sort_box_type=='SORTSUBJECT') {
2336                                        $sort[$iuid] = $header->subject;
2337                                }
2338                                else if($sort_box_type=='SORTSIZE') {
2339                                        $sort[$iuid] = $header->Size;
2340                                }
2341                                else {
2342                                        $sort[$iuid] = $header->udate;
2343                                }
2344
[659]2345                        }
[970]2346                        natcasesort($sort);
[828]2347
[970]2348                        if ($sort_box_reverse)
2349                                $sort = array_reverse($sort,true);
[659]2350                }
[828]2351
[972]2352                if(!is_array($sort))
2353                        $sort = array();
[1472]2354
[1808]2355
[972]2356                if ($slice_array)
[828]2357                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
[970]2358
[1472]2359
[828]2360                return $sort;
2361
[659]2362        }
[970]2363
2364
[1472]2365        function move_search_messages($params){
2366                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]2367                $params['new_folder'] = urldecode($params['new_folder']);
2368                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2369                $sel_msgs = explode(",", $params['selected_messages']);
[1472]2370                @reset($sel_msgs);
[163]2371                $sorted_msgs = array();
2372                foreach($sel_msgs as $idx => $sel_msg) {
2373                        $sel_msg = explode(";", $sel_msg);
2374                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2375                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[1472]2376                         }
[163]2377                         else {
2378                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2379                         }
2380                }
2381                @ksort($sorted_msgs);
[1472]2382                $last_return = false;
2383                foreach($sorted_msgs as $folder => $msgs_number) {
[163]2384                        $params['msgs_number'] = $msgs_number;
[1472]2385                        $params['folder'] = $folder;
[163]2386                        if($params['new_folder'] && $folder != $params['new_folder']){
[1472]2387                                $last_return = $this -> move_messages($params);
[163]2388                        }
2389                        elseif(!$params['new_folder'] || $params['delete'] ){
2390                                $last_return = $this -> delete_msgs($params);
2391                                $last_return['deleted'] = true;
2392                        }
2393                }
2394                return $last_return;
2395        }
[1472]2396
[2]2397        function move_messages($params)
2398        {
[1472]2399                $folder = $params['folder'];
2400                $mbox_stream = $this->open_mbox($folder);
[51]2401                $newmailbox = ($params['new_folder']);
2402                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
[2]2403                $new_folder_name = $params['new_folder_name'];
2404                $msgs_number = $params['msgs_number'];
2405                $return = array('msgs_number' => $msgs_number,
2406                                                'folder' => $folder,
2407                                                'new_folder_name' => $new_folder_name,
[325]2408                                                'border_ID' => $params['border_ID'],
2409                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[1472]2410
[325]2411                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2412        if (substr($folder,0,4) == 'user'){
2413                $acl = $this->getacltouser($folder);
2414                /*
2415                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2416                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2417                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2418                 *   w - write (STORE flags other than SEEN and DELETED)
2419                 *   i - insert (perform APPEND, COPY into mailbox)
2420                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2421                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2422                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2423                 *   a - administer (perform SETACL)
2424                        */
2425                        if (strpos($acl, "d") === false){
2426                                $return['status'] = false;
2427                                return $return;
2428                        }
2429        }
[432]2430        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[1747]2431        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2432            if (substr($new_folder_name,0,4) == 'user'){
2433                $this->ldap = new ldap_functions();
2434                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2435                $return['new_folder_name'] = array_pop($tmp_folder_name);
2436                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2437                {
2438                    $return['new_folder_name'] = $cn;
2439                }
2440            }
[432]2441        }
[1472]2442
2443                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
[51]2444                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]2445                {
[2]2446                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]2447                        // Fix problem in unserialize function JS.
2448                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2449                }
[1472]2450
2451                $mbox_stream = $this->open_mbox($folder);
[2]2452                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2453                        imap_expunge($mbox_stream);
[51]2454                        if($mbox_stream)
2455                                imap_close($mbox_stream);
[2]2456                        return $return;
2457                }else {
[1472]2458                        if(strstr(imap_last_error(),'Over quota')) {
[2]2459                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[1472]2460                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2461                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
[2]2462                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]2463                                $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]2464                                if(!$mbox)
2465                                        return imap_last_error();
[1472]2466                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
[2]2467                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]2468                                        if($mbox_stream)
2469                                                imap_close($mbox_stream);
[1472]2470                                        if($mbox)
[51]2471                                                imap_close($mbox);
[1472]2472                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
[2]2473                                }
2474                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2475                                        imap_expunge($mbox_stream);
[51]2476                                        if($mbox_stream)
2477                                                imap_close($mbox_stream);
[2]2478                                        // return to original quota limit.
2479                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2480                                                if($mbox)
2481                                                        imap_close($mbox);
[1472]2482                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]2483                                        }
[1472]2484                                        return $return;
[2]2485                                }
2486                                else {
[51]2487                                        if($mbox_stream)
2488                                                imap_close($mbox_stream);
[2]2489                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]2490                                                if($mbox)
2491                                                        imap_close($mbox);
[1472]2492                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]2493                                        }
[1472]2494                                        return imap_last_error();
[2]2495                                }
[1472]2496
[2]2497                        }
2498                        else {
[51]2499                                if($mbox_stream)
2500                                        imap_close($mbox_stream);
2501                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]2502                        }
[1472]2503                }
[2]2504        }
[1472]2505
[2]2506        function save_msg($params)
2507        {
[1472]2508
[271]2509                include_once("class.phpmailer.php");
2510                $mail = new PHPMailer();
2511                include_once("class.db_functions.inc.php");
2512                $toaddress = $params['input_to'];
2513                $ccaddress = $params['input_cc'];
[1638]2514                $ccoaddress = $params['input_cco'];
[271]2515                $subject = $params['input_subject'];
[320]2516                $msg_uid = $params['msg_id'];
[2]2517                $body = $params['body'];
2518                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
[155]2519                $body = preg_replace("/\n/"," ",$body);
[51]2520                $body = preg_replace("/\r/","",$body);
[271]2521                $forwarding_attachments = $params['forwarding_attachments'];
2522                $attachments = $params['FILES'];
2523                $return_files = $params['FILES'];
[1472]2524
[271]2525                $folder = $params['folder'];
[1472]2526                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[271]2527                // Fix problem with cyrus delimiter changes.
[1472]2528                // Dots in names: enabled/disabled.
[271]2529                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2530                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2531                // End Fix.
[1638]2532                if(strtoupper($folder) == 'INBOX/DRAFTS')
2533                    {
2534                        $mail->SaveMessageAsDraft = $folder;
2535                    }
[271]2536                $mail->SaveMessageInFolder = $folder;
2537                $mail->SMTPDebug = false;
[1472]2538
[271]2539                $mail->IsSMTP();
2540                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2541                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2542                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2543                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
[1472]2544
[271]2545                $mail->Sender = $mail->From;
2546                $mail->SenderName = $mail->FromName;
2547                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2548                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
[1472]2549
[271]2550                $this->add_recipients("to", $toaddress, &$mail);
2551                $this->add_recipients("cc", $ccaddress, &$mail);
[1638]2552                $this->add_recipients("cco", $ccoaddress, &$mail);
[271]2553                $mail->Subject = $subject;
2554                $mail->IsHTML(true);
2555                $mail->Body = $body;
[1472]2556
[3018]2557                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
[1472]2558
2559        //      Build Forwarding Attachments!!!
[271]2560                if (count($forwarding_attachments) > 0)
2561                {
2562                        foreach($forwarding_attachments as $forwarding_attachment)
2563                        {
2564                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2565                                $tmp = array_values($file_description);
[1472]2566                                foreach($file_description as $i => $descriptor){
[271]2567                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2568                                }
2569                                $file_description = $tmp;
[1472]2570
[271]2571                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2572                                $fileName = $file_description[2];
[1472]2573
[271]2574                                $file_description[5] = strlen($fileContent); //Size of file
2575                                $return_forward[] = $file_description;
[1472]2576
[271]2577                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2578                        }
2579                }
[1472]2580
[271]2581                if ((count($return_forward) > 0) && (count($return_files) > 0))
2582                        $return_files = array_merge_recursive($return_forward,$return_files);
2583                else
2584                        if (count($return_files) < 1)
2585                                $return_files = $return_forward;
[1472]2586
[271]2587                //      Build Uploading Attachments!!!
[1005]2588                $sizeof_attachments = count($attachments);
2589                if ($sizeof_attachments)
2590                        foreach ($attachments as $numb => $attach){
2591                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2592                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2593                                        switch ($image_type)
2594                                        {
[1380]2595                                        // Do not corrupt animated gif
2596                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
[1005]2597                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2598                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2599                                        case 6:
[1247]2600                                                require_once("gd_functions.php");
[1005]2601                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2602                                        default:
2603                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2604                                                break;
2605                                        }
2606                                        header('Content-type: image/jpeg');
2607                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2608                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2609                                        if ($width < $max_resolution && $height < $max_resolution){
2610                                                $new_width = $width;
2611                                                $new_height = $height;
2612                                        }
2613                                        else if ($width > $max_resolution){
2614                                                $new_width = $max_resolution;
2615                                                $new_height = $height*($new_width/$width);
2616                                        }
2617                                        else {
2618                                                $new_height = $max_resolution;
2619                                                $new_width = $width*($new_height/$height);
2620                                        }
2621                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2622                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2623                                        $tmpDir = ini_get("session.save_path");
[1472]2624                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
[1005]2625                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2626                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2627                                }
2628                                else
2629                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2630                                // optional name
2631                                }
[1472]2632
2633
2634
2635
[271]2636                if(!empty($mail->AltBody))
2637            $mail->ContentType = "multipart/alternative";
2638
[828]2639                $mail->error_count = 0; // reset errors
2640                $mail->SetMessageType();
2641                $header = $mail->CreateHeader();
[1472]2642                $body = $mail->CreateBody();
[828]2643
[1472]2644                $mbox_stream = $this->open_mbox($folder);
[271]2645                $new_header = str_replace("\n", "\r\n", $header);
2646                $new_body = str_replace("\n", "\r\n", $body);
[830]2647                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
[271]2648                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2649                $return['msg_no'] = $status->uidnext - 1;
2650                $return['folder_id'] = $folder;
[828]2651
[51]2652                if($mbox_stream)
2653                        imap_close($mbox_stream);
[1472]2654                if (is_array($return_files))
[828]2655                        foreach ($return_files as $index => $_attachment) {
2656                                if (array_key_exists("name",$_attachment)){
[271]2657                                unset($return_files[$index]);
2658                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2659                        }
2660                        else
2661                        {
2662                                unset($return_files[$index]);
2663                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2664                        }
2665                }
[1472]2666
[271]2667                $return['files'] = serialize($return_files);
[673]2668                $return["subject"] = $subject;
[1472]2669
[2]2670                if (!$return['append'])
2671                        $return['append'] = imap_last_error();
[1472]2672
[2]2673                return $return;
2674        }
[1472]2675
[2]2676        function set_messages_flag($params)
2677        {
2678                $folder = $params['folder'];
2679                $msgs_to_set = $params['msgs_to_set'];
2680                $flag = $params['flag'];
2681                $return = array();
2682                $return["msgs_to_set"] = $msgs_to_set;
2683                $return["flag"] = $flag;
[1472]2684
[411]2685                if(!$this->mbox && !is_resource($this->mbox))
[51]2686                        $this->mbox = $this->open_mbox($folder);
[1472]2687
[2]2688                if ($flag == "unseen")
[51]2689                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]2690                elseif ($flag == "seen")
[51]2691                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]2692                elseif ($flag == "answered"){
[51]2693                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2694                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]2695                }
2696                elseif ($flag == "forwarded")
[51]2697                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]2698                elseif ($flag == "flagged")
[51]2699                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[614]2700                elseif ($flag == "unflagged") {
2701                        $flag_importance = false;
2702                        $msgs_number = explode(",",$msgs_to_set);
[659]2703                        $unflagged_msgs = "";
[614]2704                        foreach($msgs_number as $msg_number) {
2705                                preg_match('/importance *: *(.*)\r/i',
2706                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]2707                                        ,$importance);
[673]2708                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]2709                                        $flag_importance=true;
2710                                }
[659]2711                                else {
2712                                        $unflagged_msgs.=$msg_number.",";
[1472]2713                                }
[614]2714                        }
2715
[659]2716                        if($unflagged_msgs!="") {
2717                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2718                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2719                        }
2720                        else {
2721                                $return["msgs_unflageds"] = false;
2722                        }
2723
[673]2724                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]2725                                $return["status"] = false;
2726                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2727                        }
[659]2728                        else {
2729                                $return["status"] = true;
2730                        }
[614]2731                }
[1472]2732
[411]2733                if($this->mbox && is_resource($this->mbox))
[51]2734                        imap_close($this->mbox);
[2]2735                return $return;
2736        }
[1472]2737
[2]2738        function get_file_type($file_name)
2739        {
2740                $file_name = strtolower($file_name);
2741                $strFileType = strrev(substr(strrev($file_name),0,4));
[1472]2742                if ($strFileType == ".asf")
[2]2743                        return "video/x-ms-asf";
2744                if ($strFileType == ".avi")
2745                        return "video/avi";
2746                if ($strFileType == ".doc")
2747                        return "application/msword";
2748                if ($strFileType == ".zip")
2749                        return "application/zip";
2750                if ($strFileType == ".xls")
2751                        return "application/vnd.ms-excel";
2752                if ($strFileType == ".gif")
2753                        return "image/gif";
2754                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2755                        return "image/jpeg";
2756                if ($strFileType == ".png")
2757                        return "image/png";
2758                if ($strFileType == ".wav")
2759                        return "audio/wav";
2760                if ($strFileType == ".mp3")
2761                        return "audio/mpeg3";
2762                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2763                        return "video/mpeg";
2764                if ($strFileType == ".rtf")
2765                        return "application/rtf";
2766                if ($strFileType == ".htm" || $strFileType == "html")
2767                        return "text/html";
[1472]2768                if ($strFileType == ".xml")
[2]2769                        return "text/xml";
[1472]2770                if ($strFileType == ".xsl")
[2]2771                        return "text/xsl";
[1472]2772                if ($strFileType == ".css")
[2]2773                        return "text/css";
[1472]2774                if ($strFileType == ".php")
[2]2775                        return "text/php";
[1472]2776                if ($strFileType == ".asp")
[2]2777                        return "text/asp";
2778                if ($strFileType == ".pdf")
2779                        return "application/pdf";
2780                if ($strFileType == ".txt")
2781                        return "text/plain";
2782                if ($strFileType == ".wmv")
2783                        return "video/x-ms-wmv";
2784                if ($strFileType == ".sxc")
2785                        return "application/vnd.sun.xml.calc";
2786                if ($strFileType == ".stc")
2787                        return "application/vnd.sun.xml.calc.template";
2788                if ($strFileType == ".sxd")
2789                        return "application/vnd.sun.xml.draw";
2790                if ($strFileType == ".std")
2791                        return "application/vnd.sun.xml.draw.template";
2792                if ($strFileType == ".sxi")
2793                        return "application/vnd.sun.xml.impress";
2794                if ($strFileType == ".sti")
2795                        return "application/vnd.sun.xml.impress.template";
2796                if ($strFileType == ".sxm")
2797                        return "application/vnd.sun.xml.math";
2798                if ($strFileType == ".sxw")
2799                        return "application/vnd.sun.xml.writer";
2800                if ($strFileType == ".sxq")
2801                        return "application/vnd.sun.xml.writer.global";
2802                if ($strFileType == ".stw")
2803                        return "application/vnd.sun.xml.writer.template";
[1472]2804
2805
2806                return "application/octet-stream";
[2]2807        }
[1472]2808
[2]2809        function htmlspecialchars_encode($str)
2810        {
[449]2811                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]2812        }
2813        function htmlspecialchars_decode($str)
2814        {
[449]2815                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]2816        }
[1472]2817
[828]2818        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2819        {
2820                if(!$this->mbox || !is_resource($this->mbox))
[51]2821                        $this->mbox = $this->open_mbox($folder);
[432]2822
[828]2823                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2824        }
[1472]2825
[53]2826        function get_info_next_msg($params)
2827        {
2828                $msg_number = $params['msg_number'];
2829                $folder = $params['msg_folder'];
2830                $sort_box_type = $params['sort_box_type'];
2831                $sort_box_reverse = $params['sort_box_reverse'];
2832                $reuse_border = $params['reuse_border'];
2833                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[1472]2834                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2835
[320]2836                $success = false;
2837                if (is_array($sort_array_msg))
[2]2838                {
[320]2839                        foreach ($sort_array_msg as $i => $value){
2840                                if ($value == $msg_number)
2841                                {
2842                                        $success = true;
2843                                        break;
2844                                }
2845                        }
[2]2846                }
2847
[320]2848                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]2849                {
2850                        $params['status'] = 'false';
2851                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2852                        return $params;
2853                }
[1472]2854
[2]2855                $params = array();
2856                $params['msg_number'] = $sort_array_msg[($i+1)];
2857                $params['msg_folder'] = $folder;
[1472]2858
2859                $return = $this->get_info_msg($params);
[2]2860                $return["reuse_border"] = $reuse_border;
2861                return $return;
2862        }
2863
2864        function get_info_previous_msg($params)
2865        {
2866                $msg_number = $params['msgs_number'];
2867                $folder = $params['folder'];
2868                $sort_box_type = $params['sort_box_type'];
2869                $sort_box_reverse = $params['sort_box_reverse'];
2870                $reuse_border = $params['reuse_border'];
[53]2871                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2872                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[1472]2873
[320]2874                $success = false;
2875                if (is_array($sort_array_msg))
[2]2876                {
[320]2877                        foreach ($sort_array_msg as $i => $value){
2878                                if ($value == $msg_number)
2879                                {
2880                                        $success = true;
2881                                        break;
2882                                }
2883                        }
[2]2884                }
[320]2885                if (! $success || $i == 0)
2886                {
[2]2887                        $params['status'] = 'false';
2888                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2889                        return $params;
2890                }
[1472]2891
[2]2892                $params = array();
2893                $params['msg_number'] = $sort_array_msg[($i-1)];
2894                $params['msg_folder'] = $folder;
[1472]2895
[2]2896                $return = $this->get_info_msg($params);
2897                $return["reuse_border"] = $reuse_border;
2898                return $return;
2899        }
[1472]2900
[2]2901        // This function updates the values: quota, paging and new messages menu.
2902        function get_menu_values($params){
2903                $return_array = array();
2904                $return_array = $this->get_quota($params);
[1472]2905
[2]2906                $mbox_stream = $this->open_mbox($params['folder']);
[1472]2907                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
[51]2908                if($mbox_stream)
2909                        imap_close($mbox_stream);
[1472]2910
2911                return $return_array;
[2]2912        }
[1472]2913
[325]2914        function get_quota($params){
[449]2915                // folder_id = user/{uid} for shared folders
2916                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2917                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
[1472]2918                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
[449]2919                }
2920                // folder_id = INBOX for inbox folders
2921                else
2922                        $folder_id = "INBOX";
[1472]2923
[1035]2924                if(!$this->mbox || !is_resource($this->mbox))
[51]2925                        $this->mbox = $this->open_mbox();
[345]2926
[325]2927                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]2928                if($this->mbox && is_resource($this->mbox))
[51]2929                        imap_close($this->mbox);
[1472]2930
[2]2931                if (!$quota){
2932                        return array(
2933                                'quota_percent' => 0,
2934                                'quota_used' => 0,
2935                                'quota_limit' =>  0
2936                        );
2937                }
[1472]2938
[2]2939                if(count($quota) && $quota['limit']) {
[3064]2940                        $quota_limit = $quota['limit'];
2941                        $quota_used  = $quota['usage'];
[2]2942                        if($quota_used >= $quota_limit)
[650]2943                        {
2944                                $quotaPercent = 100;
2945                        }
2946                        else
2947                        {
[2]2948                        $quotaPercent = ($quota_used / $quota_limit)*100;
2949                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
[650]2950                        }
[2]2951                        return array(
2952                                'quota_percent' => floor($quotaPercent),
[3064]2953                                'quota_used' => $quota_used,
2954                                'quota_limit' =>  $quota_limit
[2]2955                        );
2956                }
[1472]2957                else
[2]2958                        return array();
2959        }
[1472]2960
[2]2961        function send_notification($params){
[3231]2962                include("../header.inc.php");
[2]2963                require_once("class.phpmailer.php");
2964                $mail = new PHPMailer();
[1472]2965
[2]2966                $toaddress = $params['notificationto'];
[1472]2967
[3231]2968                $subject = lang("Read receipt: %1",$params['subject']);
2969                $body = lang("Your message: %1",$params['subject']) . '<br>';
2970                $body .= lang("Received in: %1",$params['date']) . '<br>';
2971                $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]2972                $mail->SMTPDebug = false;
2973                $mail->IsSMTP();
2974                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2975                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2976                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2977                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2978                $mail->AddAddress($toaddress);
2979                $mail->Subject = $this->htmlspecialchars_decode($subject);
2980
2981                $mail->IsHTML(true);
2982                $mail->Body = $body;
[1472]2983
[2]2984                if(!$mail->Send()){
2985                        return $mail->ErrorInfo;
2986                }
2987                else
2988                        return true;
2989        }
[1472]2990
[1965]2991        function empty_folder($params)
[2]2992        {
[1965]2993                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
[2]2994                $mbox_stream = $this->open_mbox($folder);
2995                $return = imap_delete($mbox_stream,'1:*');
[51]2996                if($mbox_stream)
2997                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2998                return $return;
2999        }
[1472]3000
[2]3001        function search($params)
3002        {
[673]3003                include("class.imap_attachment.inc.php");
[1472]3004                $imap_attachment = new imap_attachment();
[2]3005                $criteria = $params['criteria'];
3006                $return = array();
3007                $folders = $this->get_folders_list();
[1472]3008
[2]3009                $j = 0;
3010                foreach($folders as $folder)
3011                {
3012                        $mbox_stream = $this->open_mbox($folder);
3013                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[1472]3014
[2]3015                        if ($messages == '')
3016                                continue;
[1472]3017
[2]3018                        $i = 0;
3019                        $return[$j] = array();
3020                        $return[$j]['folder_name'] = $folder['name'];
[1472]3021
[2]3022                        foreach($messages as $msg_number)
3023                        {
[535]3024                                $header = $this->get_header($msg_number);
[2]3025                                if (!is_object($header))
3026                                        return false;
[1472]3027
[2]3028                                $return[$j][$i]['msg_folder']   = $folder['name'];
3029                                $return[$j][$i]['msg_number']   = $msg_number;
3030                                $return[$j][$i]['Recent']               = $header->Recent;
3031                                $return[$j][$i]['Unseen']               = $header->Unseen;
3032                                $return[$j][$i]['Answered']     = $header->Answered;
3033                                $return[$j][$i]['Deleted']              = $header->Deleted;
3034                                $return[$j][$i]['Draft']                = $header->Draft;
3035                                $return[$j][$i]['Flagged']              = $header->Flagged;
[1472]3036
[535]3037                                $date_msg = gmdate("d/m/Y",$header->udate);
3038                                if (gmdate("d/m/Y") == $date_msg)
3039                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]3040                                else
3041                                        $return[$j][$i]['udate'] = $date_msg;
[1472]3042
[2]3043                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3044                                $return[$j][$i]['fromaddress'] = '';
3045                                foreach ($fromaddress as $tmp)
3046                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[1472]3047
[2]3048                                $from = $header->from;
3049                                $return[$j][$i]['from'] = array();
3050                                $tmp = imap_mime_header_decode($from[0]->personal);
3051                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3052                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]3053                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]3054
3055                                $to = $header->to;
3056                                $return[$j][$i]['to'] = array();
3057                                $tmp = imap_mime_header_decode($to[0]->personal);
3058                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3059                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[1472]3060                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]3061
3062                                $subject = imap_mime_header_decode($header->fetchsubject);
3063                                $return[$j][$i]['subject'] = '';
3064                                foreach ($subject as $tmp)
3065                                        $return[$j][$i]['subject'] .= $tmp->text;
3066
3067                                $return[$j][$i]['Size'] = $header->Size;
3068                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]3069
[2]3070                                $return[$j][$i]['attachment'] = array();
3071                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[1472]3072
[2]3073                                $i++;
3074                        }
3075                        $j++;
[51]3076                        if($mbox_stream)
3077                                imap_close($mbox_stream);
[2]3078                }
[1472]3079
[2]3080                return $return;
3081        }
[1709]3082       
3083       
3084        function mobile_search($params)
3085        {
3086                include("class.imap_attachment.inc.php");
3087                $imap_attachment = new imap_attachment();
3088                $criterias = array ("TO","SUBJECT","FROM","CC");
3089                $return = array();
3090                $folders = $this->get_folders_list();
3091                $num_msgs = 0;
3092                                         
3093                foreach($folders as $id =>$folder)
3094                {
3095                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3096                                foreach($criterias as $criteria_fixed)
3097                    {
3098                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3099                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3100       
3101                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3102                                       
3103                                        if ($messages == ''){
3104                                                if($mbox_stream)
3105                                                        imap_close($mbox_stream);
3106                                                continue;       
3107                                        }
3108                                                                       
3109                                        foreach($messages as $msg_number)
3110                                        {                                       
3111                                                $temp = $this->get_info_head_msg($msg_number);
3112                                                if(!$temp)
3113                                                        return false;
3114               
3115                                                $return[$num_msgs] = $temp;
3116                                                $num_msgs++;
3117                                        }
3118                                        $return['num_msgs'] = $num_msgs;
3119                                       
3120                                        if($mbox_stream)
3121                                                imap_close($mbox_stream);
3122                                }
3123                        }
3124                               
3125                }
3126                return $return;
3127        }
[1472]3128
[2]3129        function delete_and_show_previous_message($params)
3130        {
3131                $return = $this->get_info_previous_msg($params);
[1472]3132
[2]3133                $params_tmp1 = array();
3134                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3135                $params_tmp1['folder'] = $params['msg_folder'];
3136                $return_tmp1 = $this->delete_msg($params_tmp1);
[1472]3137
[2]3138                $return['msg_number_deleted'] = $return_tmp1;
[1472]3139
[2]3140                return $return;
3141        }
[1472]3142
3143
[2]3144        function automatic_trash_cleanness($params)
3145        {
3146                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3147                $criteria =  'BEFORE "'.$before_date.'"';
[325]3148                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[3018]3149                // Free others requests
3150                session_write_close();
[2]3151                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3152                if (is_array($messages)){
3153                        foreach ($messages as $msg_number){
3154                                imap_delete($mbox_stream, $msg_number, FT_UID);
3155                        }
3156                }
[51]3157                if($mbox_stream)
3158                        imap_close($mbox_stream, CL_EXPUNGE);
[2]3159                return $messages;
3160        }
3161//      Fix the search problem with special characters!!!!
3162        function remove_accents($string) {
[1472]3163                return strtr($string,
3164                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]3165                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3166        }
3167
[1622]3168        function make_search_date($date){
3169
3170            $months = array(
3171                1   => 'jan',
3172                2   => 'feb',
3173                3   => 'mar',
3174                4   => 'apr',
3175                5   => 'may',
3176                6   => 'jun',
3177                7   => 'jul',
3178                8   => 'aug',
3179                9   => 'sep',
3180                10  => 'oct',
3181                11  => 'nov',
3182                12  => 'dec'
3183            );
3184
3185            //TODO: Adaptar a data de acordo com o locale do sistema.
3186            list($day,$month,$year) = explode("/", $date);
3187            $search_date = $day."-".$months[intval($month)]."-".$year;
3188            return $search_date;
3189
3190        }
3191
[1472]3192        function search_msg($params = ''){
[1614]3193            $mbox_stream = "";
[3223]3194            if(strpos($params['condition'],"#")===false) { //local messages? It shouldn't be necessary, should it? FIXME
[1614]3195                    $search=false;
3196            }
3197            else {
3198                    $search = explode(",",$params['condition']);
[3223]3199            }
3200            $params['page'] = $params['page']*1;
[689]3201
[3138]3202            if(is_array($search)){
3203                $search = array_unique($search); // Remove duplicated folders
[1614]3204                $search_criteria = '';
3205                $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3206                foreach($search as $tmp)
3207                {
3208                    $tmp1 = explode("##",$tmp);
3209                    $sum = 0;
3210                    $name_box = $tmp1[0];
3211                    unset($filter);
3212                    foreach($tmp1 as $index => $criteria)
3213                    {
3214                        if ($index != 0 && strlen($criteria) != 0)
3215                        {
3216                            $filter_array = explode("<=>",rawurldecode($criteria));
3217                            $filter .= " ".$filter_array[0];
[1622]3218                            if (strlen($filter_array[1]) != 0){
3219                                if (trim($filter_array[0]) != 'BEFORE' &&
3220                                    trim($filter_array[0]) != 'SINCE' &&
3221                                    trim($filter_array[0]) != 'ON')
3222                                {
3223                                    $filter .= '"'.$filter_array[1].'"';
3224                                }
3225                                else
3226                                    {
3227                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3228                                    }
3229                            }
[1614]3230                        }
3231                    }
3232                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3233                    $filter = $this->remove_accents($filter);
3234                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
[1747]3235                    if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
[1614]3236                    {
[1747]3237                        $folder_name = explode($this->imap_delimiter,$name_box);
[1614]3238                        $this->ldap = new ldap_functions();
3239                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3240                        {
3241                            $folder_name[1] = $cn;
3242                        }
[1747]3243                        $folder_name = implode($this->imap_delimiter,$folder_name);
[1614]3244                    }
[1747]3245                    else
3246                    {
3247                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3248                    }
[1472]3249
[1614]3250                    if(!is_resource($mbox_stream))
3251                    {
3252                        $mbox_stream = $this->open_mbox($name_box);
3253                    }
3254                    else
3255                        {
3256                            imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3257                        }
[1472]3258
[1614]3259                    if (preg_match("/^.?\bALL\b/", $filter))
3260                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
[1472]3261
[1614]3262                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3263                        foreach($all_criterias as $criteria_fixed)
3264                        {
3265                            $_filter = $criteria_fixed . substr($filter,4);
[1472]3266
[1614]3267                            $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
[1472]3268
[3223]3269                            if(is_array($search_criteria))
[1614]3270                            {
3271                                foreach($search_criteria as $new_search)
3272                                {
[3018]3273                                    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3274                                    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3275                                    $elem['uid'] = $new_search;
3276                                    $retorno[] = $elem;
[3223]3277                                }
3278                            }
[1614]3279                        }
3280                    }
3281                    else {
3282                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3283                        if( is_array( $search_criteria) )
3284                        {
3285                            foreach($search_criteria as $new_search)
[3018]3286                            {
3287                                    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3288                                    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3289                                    $elem['uid'] = $new_search;
[3223]3290                                    $retorno[] = $elem;
[1614]3291                            }
3292                        }
[3223]3293                    }
[1614]3294                }
3295            }
3296            if($mbox_stream)
3297            {
3298                imap_close($mbox_stream);
[3223]3299            }
3300            $num_msgs = count($retorno);
[1472]3301
[3223]3302            /* Comparison functions, descendent is ascendent with parms inverted */
3303            function SORTDATE($a, $b) { return ($a['udate'] < $b['udate']); }
3304            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
3305
3306            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
3307            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
3308
3309            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
3310            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
3311
3312            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
3313            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
3314
3315            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
3316            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
3317
3318            usort($retorno, $params['sort_type']);
3319            $pageret = array_slice($retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
3320            $arrayRetorno['num_msgs'] =  $num_msgs;
3321            $arrayRetorno['data'] =  $pageret;
3322
3323            if ($pageret)
[1614]3324            {
[3223]3325                return $arrayRetorno;
[1614]3326            }
3327            else
3328            {
3329                return 'none';
3330            }
[2]3331        }
[1472]3332
[3018]3333        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
[271]3334        {
[828]3335                $header = $this->get_header($uid_msg);
[3018]3336                require_once("class.imap_attachment.inc.php");
[828]3337                $imap_attachment = new imap_attachment();
3338                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3339                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3340                $flag = $header->Unseen
3341                        .$header->Recent
3342                        .$header->Flagged
3343                        .$header->Draft
3344                        .$header->Answered
3345                        .$header->Deleted
3346                        .$attachments;
3347
3348
[163]3349                $subject = $this->decode_string($header->fetchsubject);
3350                $from = $header->from[0]->mailbox;
[2]3351                if($header->from[0]->personal != "")
3352                        $from = $header->from[0]->personal;
[3018]3353                $ret_msg['from'] = $this->decode_string($from);
3354                $ret_msg['subject'] = $subject;
3355                $ret_msg['udate'] = $header ->udate;
3356                $ret_msg['size'] = $header->Size;
3357                $ret_msg['flag'] = $flag;
[1472]3358                return $ret_msg;
3359        }
[2]3360        function ob_array($the_object)
3361        {
3362           $the_array=array();
3363           if(!is_scalar($the_object))
3364           {
3365               foreach($the_object as $id => $object)
3366               {
3367                   if(is_scalar($object))
3368                   {
3369                       $the_array[$id]=$object;
3370                   }
3371                   else
3372                   {
3373                       $the_array[$id]=$this->ob_array($object);
3374                   }
3375               }
3376               return $the_array;
3377           }
3378           else
3379           {
3380               return $the_object;
3381           }
3382        }
[1472]3383
[2]3384        function getacl()
3385        {
3386                $this->ldap = new ldap_functions();
[1472]3387
[2]3388                $return = array();
[1472]3389                $mbox_stream = $this->open_mbox();
[2]3390                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]3391
[2]3392                $i = 0;
3393                foreach ($mbox_acl as $user => $acl)
3394                {
3395                        if ($user != $this->username)
3396                        {
3397                                $return[$i]['uid'] = $user;
3398                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3399                        }
3400                        $i++;
3401                }
3402                return $return;
3403        }
[1472]3404
[2]3405        function setacl($params)
3406        {
3407                $old_users = $this->getacl();
3408                if (!count($old_users))
3409                        $old_users = array();
[1472]3410
[2]3411                $tmp_array = array();
3412                foreach ($old_users as $index => $user_info)
3413                {
3414                        $tmp_array[$index] = $user_info['uid'];
3415                }
3416                $old_users = $tmp_array;
[1472]3417
[2]3418                $users = unserialize($params['users']);
3419                if (!count($users))
3420                        $users = array();
[1472]3421
[2]3422                //$add_share = array_diff($users, $old_users);
3423                $remove_share = array_diff($old_users, $users);
3424
3425                $mbox_stream = $this->open_mbox();
3426
3427                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3428                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3429
3430                /*if (count($add_share))
3431                {
3432                        foreach ($add_share as $index=>$uid)
3433                        {
3434                        if (is_array($mailboxes_list))
3435                        {
3436                        foreach ($mailboxes_list as $key => $val)
3437                        {
3438                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3439                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3440                        }
3441                        }
3442                        }
3443                }*/
[1472]3444
[2]3445                if (count($remove_share))
3446                {
3447                        foreach ($remove_share as $index=>$uid)
3448                        {
3449                        if (is_array($mailboxes_list))
3450                        {
3451                        foreach ($mailboxes_list as $key => $val)
3452                        {
3453                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3454                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3455                        }
3456                        }
[1472]3457                        }
[2]3458                }
[1472]3459
[2]3460                return true;
3461        }
[1472]3462
[2]3463        function getaclfromuser($params)
3464        {
3465                $useracl = $params['user'];
[1472]3466
[2]3467                $return = array();
3468                $return[$useracl] = 'false';
[1472]3469                $mbox_stream = $this->open_mbox();
[2]3470                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]3471
[2]3472                foreach ($mbox_acl as $user => $acl)
3473                {
3474                        if (($user != $this->username) && ($user == $useracl))
3475                        {
3476                                $return[$user] = $acl;
3477                        }
3478                }
3479                return $return;
3480        }
3481
3482        function getacltouser($user)
3483        {
3484                $return = array();
3485                $mbox_stream = $this->open_mbox();
[325]3486                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3487                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3488                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3489                if(substr($user,0,4) != 'user')
[449]3490                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]3491                else
3492                  $mbox_acl = imap_getacl($mbox_stream, $user);
[2]3493                return $mbox_acl[$this->username];
3494        }
3495
[1472]3496
[2]3497        function setaclfromuser($params)
3498        {
3499                $user = $params['user'];
3500                $acl = $params['acl'];
[1472]3501
[2]3502                $mbox_stream = $this->open_mbox();
3503
3504                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3505                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3506
3507                if (is_array($mailboxes_list))
3508                {
3509                        foreach ($mailboxes_list as $key => $val)
3510                        {
[449]3511                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3512                                $folder = str_replace("&-", "&", $folder);
[2]3513                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3514                                {
[449]3515                                        $return = imap_last_error();
[2]3516                                }
3517                        }
3518                }
[449]3519                if (isset($return))
3520                        return $return;
3521                else
3522                        return true;
[2]3523        }
[1472]3524
[51]3525        function download_attachment($msg,$msgno)
3526        {
[1472]3527                $array_parts_attachments = array();
[3289]3528                //$array_parts_attachments['names'] = '';
[689]3529                include_once("class.imap_attachment.inc.php");
[1472]3530                $imap_attachment = new imap_attachment();
3531
[51]3532                if (count($msg->fname[$msgno]) > 0)
3533                {
3534                        $i = 0;
3535                        foreach ($msg->fname[$msgno] as $index=>$fname)
3536                        {
3537                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
[1397]3538                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
[51]3539                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3540                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
[3289]3541                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
[51]3542                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3543                                $i++;
3544                        }
3545                }
[3289]3546                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
[51]3547                return $array_parts_attachments;
[1472]3548        }
[69]3549
3550        function spam($params)
3551        {
3552                $is_spam = $params['spam'];
3553                $folder = $params['folder'];
3554                $mbox_stream = $this->open_mbox($folder);
3555                $msgs_number = explode(',',$params['msgs_number']);
3556
3557                foreach($msgs_number as $msg_number) {
[877]3558                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3559                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3560                        $body = imap_body($mbox_stream, $imap_msg_number);
[69]3561                        $msg = $header . $body;
3562                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]3563                        $username = $this->username;
[69]3564                        strtok($email, '@');
3565                        $domain = strtok('@');
3566
[449]3567                        //Encontrar a assinatura do dspam no cabecalho
3568                        $v = explode("\r\n", $header);
3569                        foreach ($v as $linha){
[877]3570                                if (eregi("^Message-ID", $linha)) {
3571                                        $args = explode(" ", $linha);
3572                                        $msg_id = "'$args[1]'";
3573                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
[449]3574                                        $args = explode(" ",$linha);
3575                                        $signature = $args[1];
3576                                }
3577                        }
3578
[877]3579                        // Seleciona qual comando a ser executado
[449]3580                        switch($is_spam){
3581                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3582                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3583                        }
[877]3584
3585                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3586                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
[78]3587                        system($cmd);
[69]3588                }
3589                imap_close($mbox_stream);
3590                return false;
3591        }
[535]3592        function get_header($msg_number){
3593                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3594                if (!is_object($header))
3595                        return false;
3596                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3597                $pdate = date_parse($header->MailDate);
3598                $header->udate +=  $pdate['zone']*(-60);
[1472]3599
[673]3600                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[659]3601                        $flag = preg_match('/importance *: *(.*)\r/i',
3602                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]3603                                                ,$importance);
[659]3604                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3605                }
[1472]3606
[535]3607                return $header;
3608        }
[1000]3609
3610//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
3611///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.
3612
3613    function insert_email($source,$folder,$timestamp){
3614        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3615        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3616        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3617        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3618        $imap_options = '/notls/novalidate-cert';
3619        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3620        if(imap_last_error())
3621        {
3622            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3623       }
3624        if($timestamp){
3625            $tempDir = ini_get("session.save_path");
[1247]3626            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
[1000]3627                $f = fopen($file,"w");
3628                fputs($f,base64_encode($source));
3629            fclose($f);
[1586]3630            $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]3631            $return['command']=exec(escapeshellcmd($command));
[1000]3632        }else{
3633            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3634        }
3635        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3636        $return['msg_no'] = $status->uidnext - 1;
3637                $return['error'] = imap_last_error();
3638        if($mbox_stream)
3639                        imap_close($mbox_stream);
3640        return $return;
3641
3642    }
3643
[1035]3644    function show_decript($params){
3645        $source = $params['source'];
3646        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3647        $source = str_replace(" ", "+", $source,$i);
[1472]3648
[1035]3649        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3650            if(!$source = base64_decode($source,true))
3651                return "error ".$source."Espaços ".$i;
3652
3653        }
3654        else {
3655            if(!$source = base64_decode($source))
3656                return "error ".$source."Espaços ".$i;
3657        }
3658
3659        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3660
3661                $get['msg_number'] = $insert['msg_no'];
3662                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3663                $return = $this->get_info_msg($get);
3664                $get['msg_number'] = $params['ID'];
3665                $get['msg_folder'] = $params['folder'];
3666                $tmp = $this->get_info_msg($get);
3667                if(!$tmp['status_get_msg_info'])
3668                {
3669                        $return['msg_day']=$tmp['msg_day'];
3670                        $return['msg_hour']=$tmp['msg_hour'];
3671                        $return['fulldate']=$tmp['fulldate'];
3672                        $return['smalldate']=$tmp['smalldate'];
3673                }
3674                else
3675                {
3676                        $return['msg_day']='';
3677                        $return['msg_hour']='';
3678                        $return['fulldate']='';
3679                        $return['smalldate']='';
3680                }
3681        $return['msg_no'] =$insert['msg_no'];
3682        $return['error'] = $insert['error'];
3683        $return['folder'] = $params['folder'];
3684        //$return['acls'] = $insert['acls'];
3685        $return['original_ID'] =  $params['ID'];
3686
3687        return $return;
3688
3689    }
[1472]3690
[1000]3691//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
3692//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3693
3694    function treat_base64_from_post($source){
3695            $offset = 0;
3696            do
3697            {
3698                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3699                    {
3700                            $inicio = strpos($source, "\n\r", $inicio);
3701                            $fim = strpos($source, '--', $inicio);
3702                            if(!$fim)
3703                                    $fim = strpos($source,"\n\r", $inicio);
3704                            $length = $fim-$inicio;
3705                            $parte = substr( $source,$inicio,$length-1);
3706                            $parte = str_replace(" ", "+", $parte);
3707                            $source = substr_replace($source, $parte, $inicio, $length-1);
3708                    }
3709                    if($offset > $inicio)
3710                    $offset=FALSE;
3711                    else
3712                    $offset = $inicio;
3713            }
3714            while($offset);
3715            return $source;
3716    }
3717
3718//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.
3719
3720    function unarchive_mail($params)
3721    {
3722        $dest_folder = $params['folder'];
3723        $sources = explode("#@#@#@",$params['source']);
3724        $timestamps = explode("#@#@#@",$params['timestamp']);
3725        foreach($sources as $index=>$src) {
3726                        if($src!=""){
3727                                $source = $this->treat_base64_from_post($src);
3728                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3729                        }
3730                }
3731        return $insert;
3732    }
3733
3734    function download_all_local_attachments($params)
3735    {
3736        $source = $params['source'];
3737        $source = $this->treat_base64_from_post($source);
3738        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3739        $exporteml = new ExportEml();
3740        $params['num_msg']=$insert['msg_no'];
3741        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3742        return $exporteml->download_all_attachments($params);
3743    }
[3157]3744    function get_quota_folders(){
3745
3746            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3747            include_once("class.imapfp.inc.php");           
3748            $imapfp = new imapfp();
3749
3750            if(!$imapfp->open($this->imap_server,$this->imap_port))
3751                    return $imapfp->get_error();             
3752            if (!$imapfp->login( $this->username,$this->password ))
3753                    return $imapfp->get_error();
3754
3755            $response_array = $imapfp->get_mailboxes_size();
3756            if ($imapfp->error)
3757                    return $imapfp->get_error();
3758
3759            $data = array();
3760            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3761            $data["quota_root"] = $quota_root;
3762
3763            foreach ($response_array as $idx=>$line) {
3764                    $line2 = str_replace('"', "", $line);
3765                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3766                    list($folder,$size) = explode(";",$line2);
3767                    $size = str_replace(")","",$size);
3768                    $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3769                    if ($size < 1048576 && $size > 1024)
3770                            $quota_used = round($size / 1024, 0).' Kb';
3771                    else if($size > 1024)
3772                            $quota_used = round($size / (1024*1024), 1).' Mb';
3773                    else
3774                            $quota_used = $size." b";
3775                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3776                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
3777                            $folder = $this->functions->getLang("Inbox");
3778                    }
3779                    else
3780                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
3781
3782                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3783            }
3784            $imapfp->close();
3785            return $data;
3786    } 
[2]3787}
[278]3788?>
Note: See TracBrowser for help on using the repository browser.