source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 5309

Revision 5309, 201.1 KB checked in by cristiano, 12 years ago (diff)

Ticket #2417 - Mensagem alterar o layout do Expresso - Alterado expressão regular que encontra a tag Style

  • 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,
[4830]16                'report_mail_error'             => True,
[1518]17                'msgs_to_archive'                               => True
[2]18        );
19
20        var $ldap;
21        var $mbox;
22        var $imap_port;
23        var $has_cid;
24        var $imap_options = '';
25        var $functions;
[3071]26        var $prefs;
[650]27        var $foldersLimit;
[1912]28        var $imap_sentfolder;
[5134]29        var $rawMessage;
[5302]30        var $folders;
[2]31
[5302]32       
[2]33        function imap_functions (){
[5134]34                $this->init();
[5302]35        }
[5134]36       
37        function init(){
[5302]38                $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
39                $this->username            = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
40                $this->password            = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
41                $this->imap_server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
42                $this->imap_port           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
43                $this->imap_delimiter  = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
44                $this->functions           = new functions();
[1912]45                $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   : str_replace("*","", $this->functions->getLang("Sent"));
[2]46                $this->has_cid = false;
[5302]47                $this->prefs               = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
48               
49                //armazena os caminhos das pastas ( sent, spam, drafts, trash )
[5306]50                $this->folders['sent']    =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']) ? 'Sent' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']; //Variavel folders armazena o caminho /sent
51                $this->folders['spam']    =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']) ? 'Spam' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
52                $this->folders['drafts']  =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']) ? 'Drafts' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
53                $this->folders['trash']   =  empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']) ? 'Trash' : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
54
[2]55                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
56                {
57                        $this->imap_options = '/tls/novalidate-cert';
58                }
59                else
60                {
61                        $this->imap_options = '/notls/novalidate-cert';
62                }
63        }
[5302]64       
65        function mount_url_folder($folders){
[5306]66                return implode($this->imap_delimiter,$folders);
[5302]67        }
68       
[2]69        // BEGIN of functions.
[3391]70        function open_mbox($folder = False,$force_die=true)
[2]71        {
[5223]72                $folder = mb_convert_encoding($folder, "UTF7-IMAP",'UTF-8, ISO-8859-1, UTF7-IMAP');
[828]73                if (is_resource($this->mbox))
[3394]74                {
75                     if ($force_die)
76                     {
77                        @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
78                     }
79                     else
80                        {
81                            @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder);
82                        }
83                }
84                else
85                    {
86                        if($force_die)
87                        {
88                            $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()))));
89                        }
90                        else
91                            {
92                                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password);
93                            }
94                       
95                    }
96                    return $this->mbox;
[2]97         }
98
[5134]99        function parse_error($error, $field = ''){
[504]100                // This error is returned from Imap.
101                if(strstr($error,'Connection refused')) {
102                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
103                }
[5134]104                else if(strstr($error,'virus')) {
[628]105                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
106                }
[5134]107                else if(strstr($error,'Failed to add recipient:')) {
108                        preg_match_all('/:\s([\s\.";@!a-z0-9]+)\s\[SMTP:/', $error, $res);
109                        return  str_replace("%1", $res['1']['0'], $this->functions->getLang("SMTP Error: The following recipient addresses failed: %1"));
110                }
111                else if(strstr($error,'Recipient address rejected')) {
112                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Invalid recipients in the message").'.');
113                }
114                else if(strstr($error,'Invalid Mail:')) {
115                        return  str_replace("%1", $field, $this->functions->getLang("The recipients addresses failed %1"));
116                }
117                else if(strstr($error,'Message file too big')) {
118                        return ($this->functions->getLang("Message file too big."));
119                }
[504]120                // This condition verifies if SESSION is expired.
[4795]121                elseif(!count($_SESSION))
[504]122                        return "nosession";
123
124                return $error;
125        }
[1472]126
[2]127        function get_range_msgs2($params)
[4025]128        {
[4044]129                // Free others requests
130                session_write_close();
[4162]131                $folder = $params['folder'];
132                $msg_range_begin = $params['msg_range_begin'];
133                $msg_range_end = $params['msg_range_end'];
[5134]134                $sort_box_type          = isset($params['sort_box_type']) ? $params['sort_box_type'] : '';
135                $sort_box_reverse       = isset($params['sort_box_reverse']) ? $params['sort_box_reverse'] : '';
136                $search_box_type        = (isset($params['search_box_type']) && $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" )? $params['search_box_type'] : false;
[1472]137
[4044]138                if( !$this->mbox || !is_resource( $this->mbox ) )
[3392]139                        $this->mbox = $this->open_mbox($folder);
140
[4044]141        $return = array();
[4050]142
[4169]143        $return['folder'] = $folder;
144
[4044]145        //Para enviar o offset entre o timezone definido pelo usuário e GMT
146        $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
[3392]147
[4162]148        if(!$search_box_type || $search_box_type=="UNSEEN" || $search_box_type=="SEEN") {
149                        $msgs_info = imap_status($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".mb_convert_encoding( $folder, "UTF7-IMAP", "ISO_8859-1" ) ,SA_ALL);
[3392]150
151
[4162]152                        $return['tot_unseen'] = $search_box_type == "SEEN" ? 0 : $msgs_info->unseen;
[828]153
[4162]154                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
[3392]155
[4162]156                        $num_msgs = ($search_box_type=="UNSEEN") ? $msgs_info->unseen : (($search_box_type=="SEEN") ? ($msgs_info->messages - $msgs_info->unseen) : $msgs_info->messages);
157
[4025]158                        $i = 0;
[4162]159                        if(is_array($sort_array_msg)){
160                                foreach($sort_array_msg as $msg_number => $value)
161                                {
162                                        $temp = $this->get_info_head_msg($msg_number);
[5134]163                                        $temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
[4162]164                                        if(!$temp)
165                                                return false;
[4025]166
[4162]167                                        $return[$i] = $temp;
168                                        $i++;
169                                }
170                        }
171                        $return['num_msgs'] =  $num_msgs;
172                }
173                else {
174                        $num_msgs = imap_num_msg($this->mbox);
175                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
[828]176
[4044]177
[4162]178                        $return['tot_unseen'] = 0;
179                        $i = 0;
[4044]180
[4162]181                        if(is_array($sort_array_msg)){
182
183                            foreach($sort_array_msg as $msg_number => $value)
184                            {
185                                $temp = $this->get_info_head_msg($msg_number);
186                                if(!$temp)
187                                    return false;
188
189                                if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
190                                                $return['tot_unseen']++;
191                                        }
192
193                                if($i <= ($msg_range_end-$msg_range_begin))
194                                    $return[$i] = $temp;
195                                $i++;
196                            }
197                        }
198                        $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
199                }
200                return $return;
[4044]201    }
202
203        function get_info_head_msg($msg_number)
204        {
[689]205                $head_array = array();
206                include_once("class.imap_attachment.inc.php");
[828]207
[3271]208                $imap_attachment = new imap_attachment();
209                //if ($this->prefs['use_important_flag'] )
210                //{
[3071]211                        /*Como eu preciso do atributo Importance para saber se o email é
212                         * importante ou não, uso abaixo a função imap_fetchheader e busco
213                         * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
214                         * duas vezes e de duas formas diferentes, mas em contrapartida, eu
215                         * não preciso reimplementar o método utilizando o fetchheader.
216                         * Como as mensagens são renderizadas em um número pequeno por vez,
217                         * não parece ter perda considerável de performance.
218                         */
[830]219
[3071]220                        $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
221                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[3271]222                //}
223                // Reimplementado código para identificação dos e-mails assinados e cifrados
224                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
225                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
226                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
[1174]227
[689]228                $header = $this->get_header($msg_number);
[828]229                if (!is_object($header))
230                        return false;
[689]231                $head_array['Recent'] = $header->Recent;
232                $head_array['Unseen'] = $header->Unseen;
233                if($header->Answered =='A' && $header->Draft == 'X'){
234                        $head_array['Forwarded'] = 'F';
[2]235                }
[689]236                else {
237                        $head_array['Answered'] = $header->Answered;
[828]238                        $head_array['Draft']    = $header->Draft;
[46]239                }
[689]240                $head_array['Deleted'] = $header->Deleted;
241                $head_array['Flagged'] = $header->Flagged;
242                $head_array['msg_number'] = $msg_number;
[3057]243                $head_array['udate'] = $header->udate;
[3923]244                $head_array['offsetToGMT'] = $this->functions->CalculateDateOffset();
[828]245
[3923]246                $msgTimestamp = $header->udate + $head_array['offsetToGMT'];
247                $head_array['timestamp'] = $msgTimestamp;
248               
[3499]249                $date_msg = gmdate("d/m/Y",$msgTimestamp);
250//              if (date("d/m/Y") == $date_msg)
251//                      $return['udate'] = $header->udate;
252//              else
253
254                if (date("d/m/Y") == $date_msg) //no dia
255                {
256                        $head_array['smalldate'] = gmdate("H:i",$msgTimestamp);
257                }
258                else
259                {
260                        $head_array['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
261                }
262
[5134]263                if(isset($header->from))
[689]264                $from = $header->from;
265                $head_array['from'] = array();
[1740]266                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
[5134]267                if(isset($from))
[689]268                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
[5134]269                else
270                        $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@";
271                if(!$head_array['from']['name'] || trim($head_array['from']['name']) === '' )
[689]272                        $head_array['from']['name'] = $head_array['from']['email'];
[5134]273                if(isset($header->to))
[689]274                $to = $header->to;
275                $head_array['to'] = array();
[5134]276                if(isset($to[1]) && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
[3831]277                        $head_array['to']['name'] = $head_array['to']['email'] = NULL;
278                }
279                else {
280                        $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
281                        $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
282                        $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
283                        if(!$head_array['to']['name'])
284                                $head_array['to']['name'] = $head_array['to']['email'];
285                }
[5134]286                $cc = null;
287                $cco = null;
288                if(isset($header->cc)){
[3777]289                $cc = $header->cc;
[5134]290                }
291                if(isset($header->bcc)){
[3831]292                $cco = $header->bcc;
[5134]293                }
[3777]294                if ( ($cc) && (!$head_array['to']['name']) ){
295                        $head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL;
296                        $head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host;
[5134]297                        if(!$head_array['to']['name']){
298                                $head_array['to']['name'] = $head_array['from']['name'];
299                                //$head_array['to']['email'] = $head_array['from']['email'];
300                        }
[3777]301                }
[3831]302                else if ( ($cco) && (!$head_array['to']['name']) ){
303                        $head_array['to']['name'] = ( isset( $cco[0]->personal ) ) ? $this->decode_string($cco[0]->personal) : NULL;
304                        $head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host;
305                        if(!$head_array['to']['name'])
[5134]306                                $head_array['to']['name'] = $head_array['from']['name'];
[3831]307                }
[1751]308                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
[5134]309                if($head_array['subject'] == "" || $head_array['subject'] == '' || $head_array['subject'] == null ){
310                        $head_array['subject'] = $this->functions->getLang("(no subject)   ");
311                }
312       
313                if($head_array['to']['name'] == 'undisclosed-recipients@' || $head_array['to']['name'] == '@'){
314                        $head_array['to']['name'] = $head_array['from']['name'];
315                        $head_array['to']['email'] = $head_array['from']['email'];
316                }
[828]317
[689]318                $head_array['Size'] = $header->Size;
[828]319
[689]320                $head_array['attachment'] = array();
321                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[828]322
[689]323                return $head_array;
[2]324        }
[828]325
[4416]326        /**
[5079]327        *
[4416]328        * @license    http://www.gnu.org/copyleft/gpl.html GPL
[5134]329        * @param      string $string String a ser decodificada
330        * @return     string
[4416]331        * @todo       Verificar a possibilidade de se utilizar a função iconv_mime_decode, que é capaz de identificar a codificação por si só, mas que pode ser interpretada de forma diversa dependendo da implementação do sistema
332        * @todo       Executar testes suficientes para validar a funçao iconv_mime_decode em substituição à este método decode_string
333        */
[2]334        function decode_string($string)
[4795]335        {
[5134]336        $return = '';
337        $decoded = '';
[4795]338                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
339                {
340                        $tmp = imap_mime_header_decode($string);
341                        foreach ($tmp as $tmp1)
[4416]342            {
[4795]343                                $return .= $this->htmlspecialchars_encode($tmp1->text);
[4416]344            }
[4795]345
[4416]346            return str_replace("\t", "", $return);
[4795]347                }
348                else if (strpos(strtolower($string), '=?utf-8') !== false)
349                {
350                        $elements = imap_mime_header_decode($string);
[1472]351
[4795]352                        for($i = 0;$i < count($elements);$i++)
353                        {
354                                $charset = strtolower($elements[$i]->charset);
355                                $text = $elements[$i]->text;
356                                if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
357                                $decoded .= $this->functions->utf8_to_ncr($text);
358                                else
359                                {
360                                        if( strcasecmp($charset,"default") )
361                                                $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
362                                        else
363                                                $decoded .= $this->htmlspecialchars_encode($text);
364                                }
365                        }
[1401]366
[4416]367              return str_replace("\t", "", $decoded);
[4795]368                }
[4773]369                else if(strpos(strtolower($string), '=?us-ascii') !== false)
370           {
371                        $retun = '';
372                        $tmp = imap_mime_header_decode($string);
373                        foreach ($tmp as $tmp1)
374                                $return .= $this->htmlspecialchars_encode(quoted_printable_decode($tmp1->text));
375               
376                        return str_replace("\t", "", $return);
377         
378            }
[5134]379        else if( strpos( $string , '=?' ) !== false )
380            return $this->htmlspecialchars_encode(iconv_mime_decode( $string ));
[4773]381       
[1401]382
[4795]383                        return $this->htmlspecialchars_encode($string);
384        }
[5079]385       
386       
[615]387        /**
388        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
389        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
390        */
[5265]391        function import_msgs($params) {         
[1000]392                if(!$this->mbox)
[660]393                        $this->mbox = $this->open_mbox();
[1472]394
[5264]395                if( preg_match('/local_/',$params["folder"]) ){
396                       
[1366]397                        // PLEASE, BE CAREFULL!!! YOU SHOULD USE EMAIL CONFIGURATION VALUES (EMAILADMIN MODULE)
[5302]398                        //$tmp_box = mb_convert_encoding('INBOX'.$this->folders['trash'].$this->imap_delimiter.'tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
399                        $tmp_box = mb_convert_encoding($this->mount_url_folder(array("INBOX",$this->folders['trash'],"tmpMoveToLocal")), "UTF7-IMAP", "UTF-8");
400                       
[5264]401                        if ( ! imap_createmailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" ) )
[1000]402                                return $this->functions->getLang( 'Import to Local : fail...' );
403                        imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
404                        $params["folder"] = $tmp_box;
405                }
[5264]406               
[615]407                $errors = array();
408                $invalid_format = false;
[1472]409                $filename = $params['FILES'][0]['name'];
[5264]410                $params["folder"] = mb_convert_encoding($params["folder"], "UTF7-IMAP","ISO-8859-1, UTF-8");
[660]411                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
[5264]412               
[660]413                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
414                        return array( 'error' => $this->functions->getLang("fail in import:").
[1000]415                                                        " ".$this->functions->getLang("Over quota"));
[660]416                }
[5264]417               
[615]418                if(substr($filename,strlen($filename)-4)==".zip") {
[660]419                        $zip = zip_open($params['FILES'][0]['tmp_name']);
[615]420                        if ($zip) {
421                                while ($zip_entry = zip_read($zip)) {
[1000]422
[615]423                                        if (zip_entry_open($zip, $zip_entry, "r")) {
424                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
425                                                $status = @imap_append($this->mbox,
[660]426                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
[615]427                                                                        $email
428                                                                        );
429                                                if(!$status)
430                                                        array_push($errors,zip_entry_name($zip_entry));
431                                                zip_entry_close($zip_entry);
432                                        }
433                                }
[660]434                                zip_close($zip);
[615]435                        }
[5264]436                        if (isset( $tmp_box ) && ! sizeof( $errors )){
[1000]437                                $mc = imap_check($this->mbox);
438                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
439                                $ids = array( );
440                                foreach ($result as $overview)
441                                        $ids[ ] = $overview -> uid;
442                                return implode( ',', $ids );
[830]443                        }
[5264]444               
445                }else if(substr($filename,strlen($filename)-4)==".eml") {
[660]446                        $email = implode("",file($params['FILES'][0]['tmp_name']));
[5264]447                        $status = imap_append($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],$email);
[5265]448                               
[5264]449                        if(!$status)
[5266]450                                return "Error importing";
[5264]451                       
[5134]452                        if ( isset( $tmp_box ) && ! sizeof( $errors ) ) {
453                                $mc = imap_check($this->mbox);
454
455                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
456
457                                $ids = array( );
458                                foreach ($result as $overview)
459                                        $ids[ ] = $overview -> uid;
460
461                                return implode( ',', $ids );
462                        }
[615]463                }
[5264]464                else{
[1000]465                        if ( isset( $tmp_box ) )
466                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
467
[660]468                        return array("error" => $this->functions->getLang("wrong file format"));
[615]469                        $invalid_format = true;
470                }
[1000]471
[615]472                if(!$invalid_format) {
473                        if(count($errors)>0) {
[660]474                                $message = $this->functions->getLang("fail in import:")."\n";
[615]475                                foreach($errors as $arquivo) {
476                                        $message.=$arquivo."\n";
477                                }
[660]478                                return array("error" => $message);
[615]479                        }
480                        else
[3843]481                                return $this->functions->getLang("The import was executed successfully.");
[615]482                }
[1000]483        }
484        /*
[613]485                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
486                a primeira parte do e-mail, que é o texto, sem anexos.
487                O método considera que o email é multpart.
488        */
489        function remove_attachments($params) {
490                include_once("class.message_components.inc.php");
491                if(!$this->mbox || !is_resource($this->mbox))
492                        $this->mbox = $this->open_mbox($params["folder"]);
493                $return["status"] = true;
494                $header = "";
[1472]495
[613]496                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
497                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
498                        $head1 = explode(":",$head);
[1472]499                        if ( (strtoupper($head1[0]) == "TO") ||
[3566]500                                        (strtoupper($head1[0]) == "FROM") ||
501                                        (strtoupper($head1[0]) == "SUBJECT") ||
502                                        (strtoupper($head1[0]) == "DATE") )
503                                $header .= $head."\r\n";
[613]504                }
[1472]505
[5134]506                $msg = new message_components($this->mbox);
[1472]507                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
508                                                             Então uso essa classe para verificar a codificação e o charset,
[613]509                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
[1472]510
[3566]511                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][0]);
512                $all_body_encoding = $msg->encoding[$params["msg_num"]][0];
513                $all_body_charset = $msg->charset[$params["msg_num"]][0];
514               
515                if($all_body_type=='multipart/alternative') {
516                        if(strtolower($msg->file_type[$params["msg_num"]][2]=='text/html') &&
517                                        $msg->pid[$params["msg_num"]][2] == '1.2') {
518                                $body_part_to_show = '1.2';
519                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][2]);
520                                $all_body_encoding = $msg->encoding[$params["msg_num"]][2];
521                                $all_body_charset = $msg->charset[$params["msg_num"]][2];
522                        }
523                        else {
524                                $body_part_to_show = '1.1';
525                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][1]);
526                                $all_body_encoding = $msg->encoding[$params["msg_num"]][1];
527                                $all_body_charset = $msg->charset[$params["msg_num"]][1];
528                        }
529                }
530                else
531                        $body_part_to_show = '1';
532
[1319]533                $status = imap_append($this->mbox,
[613]534                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
535                                        $header.
[3566]536                                        "Content-Type: ".$all_body_type."; charset = \"".$all_body_charset."\"".
[613]537                                        "\r\n".
[3566]538                                        "Content-Transfer-Encoding: ".$all_body_encoding.
539                                        "\r\n".
540                                        "\r\n".
[5134]541                                        str_replace("\n","\r\n",preg_replace("/<img[^>]+\>/i", " ", $this->decodeBody(
[3566]542                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
543                                                        $all_body_encoding, $all_body_charset
[5134]544                                                        ))
545                                        ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos. //Remove imagens do corpo, pois estas estão na lista de anexo e serão removidas.
[1472]546
[1319]547                if(!$status)
548                {
[613]549                        $return["status"] = false;
550                        $return["msg"] = lang("error appending mail on delete attachments");
551                }
[1319]552                else
553                {
554                        $status = imap_status($this->mbox, "{".$this->imap_server.":".$this->imap_port."}".$params['folder'], SA_UIDNEXT);
[1472]555                        $return['msg_no'] = $status->uidnext - 1;
[1319]556                        imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"]));
557                        imap_expunge($this->mbox);
558                }
[1472]559
[613]560                return $return;
[1472]561
[613]562        }
[1518]563       
564        function msgs_to_archive($params) {
565               
566                $folder = $params['folder'];
[1931]567                $all_ids = $this-> get_msgs($folder, 'SORTARRIVAL', false, 0,-1,-1);
[613]568
[1518]569                $messages_not_to_copy = explode(",",$params['mails']);
570                $ids = array();
571               
[1931]572                $cont = 0;
573               
[1518]574                foreach($all_ids as $each_id=>$value) {
[1931]575                        if(!in_array($each_id,$messages_not_to_copy)) {
[1518]576                                array_push($ids,$each_id);
[1931]577                                $cont++;
578                        }
579                        if($cont>=100)
580                                break;
[1518]581                }
582
583                if (empty($ids))
584                        return array();
585
586                $params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
587               
588               
589                return $this->get_info_msgs($params);
590               
591               
592        }
593
[689]594/**
[1472]595         *
596         * @return
[689]597         * @param $params Object
598         */
599        function get_info_msgs($params) {
600                include_once("class.exporteml.inc.php");
[5172]601               
602                if(array_key_exists('messages', $params)){
603                        $sel_msgs = explode(",", $params['messages']);
604                        @reset($sel_msgs);
605                        $sorted_msgs = array();
606                        foreach($sel_msgs as $idx => $sel_msg) {
607                                $sel_msg = explode(";", $sel_msg);
608                                if(array_key_exists($sel_msg[0], $sorted_msgs)){
609                                        $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
610                                }
611                                else {
612                                        $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
613                                }
614                        }
615                        unset($sorted_msgs['']);       
616               
617                        $return = array();
618                        $array_names_keys = array_keys($sorted_msgs);
619                       
620                        for($i = 0; $i < count($sorted_msgs); $i++){
621                       
622                                $new_params = array();
623                                $attach_params = array();
624                       
625                                $new_params["msg_folder"]= $array_names_keys[$i];
626                                $attach_params["folder"] = $params["folder"];
627                                $msgs = explode(",",$sorted_msgs[$array_names_keys[$i]]);
628                                $exporteml = new ExportEml();
629                                $unseen_msgs = array();
630                                foreach($msgs as $msg_number) {
631                                        $new_params["msg_number"] = $msg_number;
632                                        //ini_set("display_errors","1");
633                                        $msg_info = $this->get_info_msg($new_params);
634
635                                        $this->mbox = $this->open_mbox($array_names_keys[$i]); //Não sei porque, mas se não abrir de novo a caixa dá erro.
636                                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
637
638                                        $attach_params["num_msg"] = $msg_number;
639                                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
640                                        imap_close($this->mbox);
641                                        $this->mbox=false;
642                                        array_push($return,serialize($msg_info));
643                               
644                                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
645                                                        array_push($unseen_msgs,$msg_number);
646                                        }
647                                }
648                        }
649                        if($unseen_msgs){
650                                $msgs_list = implode(",",$unseen_msgs);
651                                $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
652                                $this->set_messages_flag($array_msgs);
653                        }
654                        return $return;
655                }else{
[689]656                $return = array();
657                $new_params = array();
658                $attach_params = array();
659                $new_params["msg_folder"]=$params["folder"];
660                $attach_params["folder"] = $params["folder"];
661                $msgs = explode(",",$params["msgs_number"]);
662                $exporteml = new ExportEml();
[1382]663                $unseen_msgs = array();
[689]664                foreach($msgs as $msg_number) {
665                        $new_params["msg_number"] = $msg_number;
666                        //ini_set("display_errors","1");
667                        $msg_info = $this->get_info_msg($new_params);
668
669                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
670                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
671
672                        $attach_params["num_msg"] = $msg_number;
673                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
674                        imap_close($this->mbox);
675                        $this->mbox=false;
676                        array_push($return,serialize($msg_info));
[1472]677
[1388]678                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
[1472]679                                        array_push($unseen_msgs,$msg_number);
680                        }
681                }
[1382]682                if($unseen_msgs){
683                        $msgs_list = implode(",",$unseen_msgs);
684                        $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
[1472]685                        $this->set_messages_flag($array_msgs);
[689]686                }
687                return $return;
688        }
[5172]689        }
[4795]690
[4436]691        /**
[5079]692        * @license    http://www.gnu.org/copyleft/gpl.html GPL
693        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]694        * @param     $msg_number numero da mensagem
[4436]695        */
[4416]696        function getRawHeader($msg_number)
697    {
698                return imap_fetchheader($this->mbox, $msg_number, FT_UID);
699        }
700       
[4436]701        /**
[5079]702        * @license    http://www.gnu.org/copyleft/gpl.html GPL
703        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]704        * @param     $msg_number numero da mensagem
[4436]705        */
[4416]706        function getRawBody($msg_number)
707    {
708                return  imap_body($this->mbox, $msg_number, FT_UID);   
709        }
[689]710
[4436]711       
712        /**
[5079]713        * @license    http://www.gnu.org/copyleft/gpl.html GPL
714        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]715        * @param     $msg mensagem
[4436]716        */
[4416]717        function builderMsgHeader($msg)
718    {
719
720 
721            $fromMail =  str_replace('<','', str_replace('>','',$msg->headers['from']));
722            $tosMails =  str_replace('<','', str_replace('>','',$msg->headers['to']));
723
724            $tos = explode(',',$tosMails);
725            $to = '';
726            foreach ($tos as $value)
727            {
728                $to .= '<a href="mailto:'.str_replace(' ','',$value).'">'.$value.'</a>, ';
729            }
730
731            $header = '
732                <table style="margin: 2px; border: 1px solid black; background: none repeat scroll 0% 0% rgb(234, 234, 234);">
733                <tbody>
734                <tr><td><b>'.$this->functions->getLang('Subject').':</b></td><td>'.$msg->headers['subject'].'</td></tr>
735                <tr><td><b>'.$this->functions->getLang('From').':</b></td><td><a href="mailto:'.$fromMail.'">'.$fromMail.'</a></td></tr>
736                <tr><td><b>'.$this->functions->getLang('Date').':</b></td><td>'.$msg->headers['date'].'</td></tr>
737                <tr><td><b>'.$this->functions->getLang('To').':</b></td><td>'.$to.'</td></tr>
738                </tbody>
739                </table>
740                <br />'
741            ;
742
743          return $header;
744    }
745       
[5079]746        /**
[5134]747        * Constroe o corpo da msg direto na variavel de conteudo
748        * @param Mail_mimeDecode $structure
749        * @param <type> $content Ponteiro para Variavel de conteudo da msg
[5079]750        */
[4416]751        function builderMsgBody($structure , &$content , $printHeader = false)
752        {
753            if(strtolower($structure->ctype_primary) == 'multipart' && strtolower($structure->ctype_secondary) == 'alternative')
754            {
755                $numParts = count($structure->parts) - 1;
756
757                for($i = $numParts; $i >= 0; $i--)
758                {
759                    $part = $structure->parts[$i];
760
761                    switch (strtolower($part->ctype_primary))
762                    {
763                       case 'text':
[5134]764                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
[4416]765                           if($disposition != 'attachment')
766                           {
767                                if(strtolower($part->ctype_secondary) == 'html')
768                                {
769                                   if($printHeader)
770                                        $content .= $this->builderMsgHeader($part);
771
772                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
773                                }
774
775                                if(strtolower($part->ctype_secondary) == 'plain' )
776                                {
777                                  if($printHeader)
778                                      $content .= $this->builderMsgHeader($part);
779
[4781]780                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
[4416]781                                }
[5134]782                                if(strtolower($part->ctype_secondary) == 'calendar')
783                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
[4416]784
785                           }
786
787                            $i = -1;
788                            break;
789
790                       case 'multipart':
791
792                            if($printHeader)
793                               $content .= $this->builderMsgHeader($part);
794
795                            $this->builderMsgBody($part,$content);
796
797                            $i = -1;
798                            break;
799
800                       case 'message':
801
802                            if(!is_array($part->parts))
803                            {
804                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4781]805                                $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body, $structure->ctype_parameters['charset'],false)).'</pre>';
[4416]806                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
807                            }
808                            else
809                                $this->builderMsgBody($part,$content,true);
810
811                            $i = -1;
812                            break;
813                    }
814                }
815            }
816            else
817            {
818                foreach ($structure->parts  as $index => $part)
819                {
820                   switch (strtolower($part->ctype_primary))
821                   {
822                       case 'text':
[5134]823                           $disposition = '';
824                           if(isset($part->disposition))
825                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
[4416]826                           if($disposition != 'attachment')
827                           {
828                                if(strtolower($part->ctype_secondary) == 'html')
829                                {
830                                   if($printHeader)
831                                        $content .= $this->builderMsgHeader($part);
832
833                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
834                                }
835
836                                if(strtolower($part->ctype_secondary) == 'plain')
837                                {
838                                  if($printHeader)
839                                      $content .= $this->builderMsgHeader($part);
840
[4781]841                                   $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
[4416]842                                }
[5134]843                                if(strtolower($part->ctype_secondary) == 'calendar')
844                                    $content .= $this->builderMsgCalendar($part->body);
[4416]845                       
846                           }
847                            break;
848                       case 'multipart':
849
850                            if($printHeader)
851                               $content .= $this->builderMsgHeader($part);
852
853                            $this->builderMsgBody($part,$content);
854
855                            break;
856                       case 'message':
[5134]857                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != '1')
858                        {
[4416]859                            if(!is_array($part->parts))
860                            {
861                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4781]862                                $content .= '<pre>'.  htmlentities($this->decodeMailPart($part->body, $structure->ctype_parameters['charset'],false)).'</pre>';
[4416]863                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
864                            }
865                            else
866                                $this->builderMsgBody($part,$content,true);
867                        break;
868                 }
869               }
870            }
871        }
[5134]872        }
[4416]873       
874       
[4436]875        /**
[5079]876        * @license    http://www.gnu.org/copyleft/gpl.html GPL
877        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
[5134]878        * @param     $msg_number numero da mensagem
[4436]879        */
880        function get_msg_sample($msg_number)
[4416]881        {
[5134]882        $content = '';
[4416]883
884                $return = "";
885                if( (!isset($this->prefs['preview_msg_subject']) || ($this->prefs['preview_msg_subject'] != "1")) &&
886                        (!isset($this->prefs['preview_msg_tip']    ) || ($this->prefs['preview_msg_tip']     != "1")) )
887                {
888                        $return['body'] = "";
889                        return $return;
890                }
891
892                include_once("class.message_components.inc.php");
[5134]893                $msg = new message_components($this->mbox);
[4416]894                $msg->fetch_structure($msg_number); 
895
[5134]896                if(!isset($msg->structure[$msg_number]->parts))
[4416]897                {
898                        $content = '';
899                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
900                        {
901                                $content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
902                        }
903                }
904                else
905                {
906                        foreach($msg->pid[$msg_number] as $values => $msg_part)
907                        {
908
909                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
910                                if($file_type == "text/plain" || $file_type == "text/html") {
911                                        $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]);
912                                        break;
913                                }
914                        }
915                }
[5134]916     
[4416]917                $tags_replace = array("<br>","<br/>","<br />");
[5134]918                $content = str_replace($tags_replace," ", nl2br($content));
919                $content = $this->html2txt($content);   
[4416]920                $content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
[5134]921                $return['body'] = base64_encode(mb_convert_encoding(substr($return['body'], 0, 305),'ISO-8859-1'));
[4416]922                return $return;
923        }
[5134]924    function html2txt($document){
925        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
926                       '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
927                       '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
928                       '@<![\s\S]*?--[ \t\n\r]*>@si'         // Strip multi-line comments including CDATA                   
929        );
930        $text = preg_replace($search, '', $document);
931        return html_entity_decode($text);
932    }
933
934    function ope_msg_part($params)
935    {
936        $return = array();
937        require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
[4416]938       
[5134]939        $atObj = new attachment();
940        $atObj->setStructureFromMail($params['msg_folder'],$params['msg_number']);
941        $mbox_stream = $this->open_mbox($params['save_folder']);
942        $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], $atObj->getAttachment($params['msg_part']), "\\Seen \\Draft");
943        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], SA_UIDNEXT);
[4416]944       
[5134]945        $return['msg_folder']  = $params['save_folder'];
946        $return['msg_number'] = $status->uidnext - 1;       
947
948        return $return;
949
950    }
[5079]951       
[2]952        function get_info_msg($params)
953        {
[51]954                $return = array();
[2]955                $msg_number = $params['msg_number'];
[1724]956                $msg_folder = urldecode($params['msg_folder']);
[4416]957               
[5134]958                if(preg_match('/(.+)(_[a-zA-Z0-9]+)/',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.
[4795]959                        $msg_number = $matches[1];
960                        $plus_id = $matches[2];
961                }
962                else {
963                        $plus_id = '';
964                }
965
[411]966                if(!$this->mbox || !is_resource($this->mbox))
[4795]967                        $this->mbox = $this->open_mbox($msg_folder);
[4416]968               
[535]969                $header = $this->get_header($msg_number);
[205]970                if (!$header) {
[4795]971                        $return['status_get_msg_info'] = "false";
[205]972                        return $return;
973                }
[4795]974
975                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
[51]976                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
[4416]977                $body = $return_get_body['body'];
[1035]978                if($return_get_body['body']=='isCripted'){
979                        $exporteml = new ExportEml();
980                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
981                        $return['body']                 = "";
982                        $return['attachments']  =  "";
983                        $return['thumbs']               =  "";
984                        $return['signature']    =  "";
985                        //return $return;
986                }else{
[4795]987            $return['body']             = $body;
988            $return['attachments']      = $return_get_body['attachments'];
989            $return['thumbs']           = $return_get_body['thumbs'];
[5134]990            //$return['signature']      = $return_get_body['signature'];
[4795]991                }
[3018]992                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
[828]993                if (preg_match($pattern, $header_, $fields))
994                {
[4795]995                        if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
996                                $return['DispositionNotificationTo'] = "<".$matches[0].">";
997                        }
[2]998                }
[828]999
[2]1000                $return['Recent']       = $header->Recent;
1001                $return['Unseen']       = $header->Unseen;
[4795]1002                $return['Deleted']      = $header->Deleted;
[2]1003                $return['Flagged']      = $header->Flagged;
1004
1005                if($header->Answered =='A' && $header->Draft == 'X'){
1006                        $return['Forwarded'] = 'F';
1007                }
[4795]1008
[2]1009                else {
1010                        $return['Answered']     = $header->Answered;
[4795]1011                        $return['Draft']        = $header->Draft;
[2]1012                }
1013
[4795]1014                $return['msg_number'] = $msg_number.$plus_id;
[2]1015                $return['msg_folder'] = $msg_folder;
[4795]1016
[5134]1017               
1018               
1019                $msgTimesTamp = $header->udate + $this->functions->CalculateDateOffset(); //Aplica offset do usuario
1020                $date_msg = gmdate("d/m/Y",$msgTimesTamp);
[4795]1021
[5134]1022//      Removido codigo pois a o método send_nofication precisa da data completa.
1023//              if (date("d/m/Y") == $date_msg)
1024//                      $return['udate'] = gmdate("H:i",$header->udate);
1025//              else
1026
1027//      Passa o a data completa para mensagem.         
1028                $return['udate'] = $header->udate;
1029
[4795]1030                $return['msg_day'] = $date_msg;
[5134]1031                $return['msg_hour'] = gmdate("H:i",$msgTimesTamp);
[4795]1032
[2]1033                if (date("d/m/Y") == $date_msg) //no dia
1034                {
[5134]1035                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
1036                        $return['smalldate'] = gmdate("H:i",$msgTimesTamp);
1037                       
[605]1038
[5134]1039                                $timestamp_now = strtotime("now");
1040                        //      removido offset nao esta sendo parametrizado
1041                        //      $timestamp_now = strtotime("now") + $offset;
1042                       
1043                       
1044                        $timestamp_msg_time = $msgTimesTamp;
[4416]1045                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
[535]1046                        // The variable $timestamp_diff is calculated without MailDate TZ.
[4416]1047                        $pdate = date_parse($header->MailDate);
1048                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
[4795]1049
[2]1050                        if (gmdate("H",$timestamp_diff) > 0)
1051                        {
[197]1052                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
[2]1053                        }
1054                        else
1055                        {
1056                                if (gmdate("i",$timestamp_diff) == 0){
[197]1057                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
[2]1058                                }
1059                                elseif (gmdate("i",$timestamp_diff) == 1){
[197]1060                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
[2]1061                                }
1062                                else{
[197]1063                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
[2]1064                                }
1065                        }
1066                }
1067                else{
[5134]1068                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
1069                        $return['smalldate'] = gmdate("d/m/Y",$msgTimesTamp);
[2]1070                }
[4795]1071
[2]1072                $from = $header->from;
1073                $return['from'] = array();
[5134]1074                $return['from']['name'] = isset($sender[0]->personal) ? $this->decode_string($from[0]->personal) : '';
[2]1075                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
1076                if ($return['from']['name'])
1077                {
1078                        if (substr($return['from']['name'], 0, 1) == '"')
1079                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
1080                        else
1081                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
1082                }
1083                else
1084                        $return['from']['full'] = $return['from']['email'];
[4795]1085
[2]1086                // Sender attribute
1087                $sender = $header->sender;
[4795]1088                $return['sender'] = array();
[5134]1089                $return['sender']['name'] = isset($sender[0]->personal) ? $this->decode_string($sender[0]->personal): '';
[2]1090                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
[5134]1091               
[2]1092                if ($return['sender']['name'])
1093                {
1094                        if (substr($return['sender']['name'], 0, 1) == '"')
1095                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
1096                        else
1097                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
1098                }
1099                else
1100                        $return['sender']['full'] = $return['sender']['email'];
1101
1102                if($return['from']['full'] == $return['sender']['full'])
1103                        $return['sender'] = null;
1104                $to = $header->to;
1105                $return['toaddress2'] = "";
1106                if (!empty($to))
1107                {
1108                        foreach ($to as $tmp)
1109                        {
1110                                if (!empty($tmp->personal))
1111                                {
1112                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
1113                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
1114                                        $return['toaddress2'] .= " ";
1115                                        $return['toaddress2'] .= "&lt;";
[320]1116                                        if ($tmp->host != 'unspecified-domain')
1117                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
1118                                        else
1119                                                $return['toaddress2'] .= $tmp->mailbox;
[2]1120                                        $return['toaddress2'] .= "&gt;";
1121                                        $return['toaddress2'] .= ", ";
1122                                }
1123                                else
1124                                {
[320]1125                                        if ($tmp->host != 'unspecified-domain')
1126                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
1127                                        else
1128                                                $return['toaddress2'] .= $tmp->mailbox;
[2]1129                                        $return['toaddress2'] .= ", ";
1130                                }
1131                        }
1132                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
1133                }
[4416]1134                else
1135                {
[4730]1136                        $return['toaddress2'] = "";
[4416]1137                }       
[5134]1138                if(isset($header->cc))
[2]1139                $cc = $header->cc;
1140                $return['cc'] = "";
1141                if (!empty($cc))
1142                {
1143                        foreach ($cc as $tmp_cc)
1144                        {
1145                                if (!empty($tmp_cc->personal))
1146                                {
1147                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
1148                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
1149                                        $return['cc'] .= " ";
1150                                        $return['cc'] .= "&lt;";
[5134]1151                                        if ($tmp_cc->host != 'unspecified-domain')
[2]1152                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[5134]1153                                        else
1154                                                $return['cc'] .= $tmp_cc->mailbox;
1155                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[2]1156                                        $return['cc'] .= "&gt;";
1157                                        $return['cc'] .= ", ";
1158                                }
1159                                else
1160                                {
[5134]1161                                        if ($tmp_cc->host != 'unspecified-domain')
[2]1162                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[5134]1163                                        else
1164                                                $return['cc'] .= $tmp_cc->mailbox;
1165                                        //$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
[2]1166                                        $return['cc'] .= ", ";
1167                                }
1168                        }
1169                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
1170                }
1171                else
1172                {
1173                        $return['cc'] = "";
[4795]1174                }
[449]1175
1176                ##
1177                # @AUTHOR Rodrigo Souza dos Santos
1178                # @DATE 2008/09/12
1179                # @BRIEF Adding the BCC field.
1180                ##
[5134]1181        if(isset($header->bcc)){       
[4795]1182                $bcc = $header->bcc;
[5134]1183                }
[449]1184                $return['bcc'] = "";
1185                if (!empty($bcc))
1186                {
1187                        foreach ($bcc as $tmp_bcc)
1188                        {
1189                                if (!empty($tmp_bcc->personal))
1190                                {
1191                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
1192                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
1193                                        $return['bcc'] .= " ";
1194                                        $return['bcc'] .= "&lt;";
[5134]1195                                        if ($tmp_bcc->host != 'unspecified-domain')
[449]1196                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
[5134]1197                                        else
1198                                                $return['bcc'] .= $tmp_bcc->mailbox;
[449]1199                                        $return['bcc'] .= "&gt;";
1200                                        $return['bcc'] .= ", ";
1201                                }
1202                                else
1203                                {
[5134]1204                                        if ($tmp_bcc->host != 'unspecified-domain')
[449]1205                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
[5134]1206                                        else
1207                                                $return['bcc'] .= $tmp_bcc->mailbox;
1208                                        //$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
[449]1209                                        $return['bcc'] .= ", ";
1210                                }
1211                        }
1212                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
[426]1213                }
[449]1214                else
1215                {
1216                        $return['bcc'] = "";
[4795]1217                }
[426]1218
[2]1219                $reply_to = $header->reply_to;
1220                $return['reply_to'] = "";
1221                if (is_object($reply_to[0]))
1222                {
1223                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
1224                        {
1225                                if (!empty($reply_to[0]->personal))
1226                                {
1227                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
[41]1228                                        if(!empty($personal_reply_to[0]->text)) {
1229                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
1230                                                $return['reply_to'] .= " ";
1231                                                $return['reply_to'] .= "&lt;";
1232                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1233                                                $return['reply_to'] .= "&gt;";
1234                                        }
1235                                        else {
1236                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1237                                        }
[2]1238                                }
1239                                else
1240                                {
1241                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
1242                                }
1243                        }
1244                }
1245                $return['reply_to'] = $this->decode_string($return['reply_to']);
1246                $return['subject'] = $this->decode_string($header->fetchsubject);
[5134]1247
1248                if($return['subject'] == $this->functions->getLang("(no subject)   ")){
1249                        $return['subject'] = str_replace(" ","", $return['subject']);
1250                }
1251                if($return['subject'] == '' || $return['subject'] == null){
1252                        $return['subject'] = $this->functions->getLang("(no subject)   ");
1253                }
[4795]1254                $return['Size'] = $header->Size;
[828]1255                $return['reply_toaddress'] = $header->reply_toaddress;
[4795]1256
[689]1257                //All this is to help in local messages
[4795]1258                $return['timestamp'] = $header->udate;
[689]1259                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
1260                $return['reply_toaddress'] = $header->reply_toaddress;
[4795]1261               
[5134]1262                if(($return['from']['email'] ==  '@unspecified-domain' || $return['sender']['email'] == null) && $return['msg_folder'] == 'INBOX/Drafts'){
1263                        $return['from']['email'] = "Rascunho";
1264                }
1265                if($return['toaddress2'] == 'undisclosed-recipients@, @'){
1266                        $return['toaddress2'] = $this->functions->getLang('without destination');
1267                }
[2]1268                return $return;
1269        }
[1472]1270
[5079]1271       
[5134]1272        /*
[5079]1273        * Converte textos utf8 para o padrão html.
[5134]1274         * Modificado por Cristiano Corrêa Schmidt
1275         * @link http://php.net/manual/en/function.utf8-decode.php
[5079]1276        * @author     luka8088 <luka8088@gmail.com>
1277        */     
[4781]1278        function utf8_to_html ($data)
[4795]1279        {
[4781]1280            return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '$this->_utf8_to_html("\\1")', $data);
1281        }
[4795]1282
[4781]1283        function _utf8_to_html ($data)
[4795]1284                {
[4781]1285            $ret = 0;
1286                foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
1287                        $ret += (ord($v) % 128) * pow(64, $k);
[5134]1288                    return html_entity_decode("&#$ret;" , ENT_QUOTES);
[4795]1289                }
[4781]1290        //------------------------------------------------------------------------------//
[4795]1291
1292
[4416]1293                /**
[5134]1294         * Decodifica uma part da mensagem para iso-8859-1
1295         * @param <type> $part parte do email
1296         * @param <type> $encode codificação da parte
1297         * @return <type> string decodificada
[5079]1298                */
[4781]1299        function decodeMailPart($part, $encode, $html = true)
[4795]1300                {
[4416]1301            switch (strtolower($encode))
[4795]1302                        {
[4416]1303                case 'iso-8859-1':
1304                    return $part;
1305                    break;
[1752]1306
[4416]1307                case 'utf-8':
[5134]1308                    if ($html) return  $this->utf8_to_html($part);
1309                    else       return  utf8_decode ($part);
[4416]1310                    break;
[1752]1311
[4416]1312                default:
1313                    return mb_convert_encoding($part, 'iso-8859-1');
[4795]1314                                        break;
1315                                }
1316                        }
1317
[4416]1318       
[2]1319        function get_body_msg($msg_number, $msg_folder)
1320        {
[4429]1321            /*
[4416]1322             * Requires of librarys
1323             */
1324            require_once $_SESSION['rootPath'].'/library/mime/mimePart.php';
1325            require_once $_SESSION['rootPath'].'/library/mime/mimeDecode.php';
1326            require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
[5134]1327            //include_once("class.message_components.inc.php");
[4416]1328            //--------------------------------------------------------------------//
[1472]1329
[4416]1330            $return = array();
[1035]1331
[5134]1332//            $msg = new message_components($this->mbox);
1333//            $msg->fetch_structure($msg_number);
[1035]1334
[4416]1335            $content = '';
[1035]1336
[5134]1337            /*
1338            * Chamada original  $this->getRawHeader($msg_number)."\r\n".$this->getRawBody($msg_number);
1339            * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios
1340            */
1341            $rawMessageData = str_replace("\r\n\t", '', $this->getRawHeader($msg_number))."\r\n".$this->getRawBody($msg_number);
[3018]1342
[4416]1343            $decoder = new Mail_mimeDecode($rawMessageData);
[3018]1344
[4416]1345            $params['include_bodies'] = true;
1346            $params['decode_bodies']  = true;
1347            $params['decode_headers'] = true;
[5134]1348                        if(array_key_exists('nested_messages_are_shown', $_SESSION['phpgw_info']['user']['preferences']['expressoMail']) && ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] == '1'))
1349                                $params['rfc_822bodies']  = true;
[4416]1350            $structure = $decoder->decode($params);
[3018]1351
[4416]1352            /*
1353             * Inicia Gerenciador de Anexos
1354             */
1355            $attachmentManager = new attachment();
1356            $attachmentManager->setStructure($structure);
1357            //----------------------------------------------//
[1472]1358
[4416]1359            /*
[4429]1360             * Monta informações dos anexos para o cabecalhos
[4416]1361             */
1362            $attachments = $attachmentManager->getAttachmentsInfo();
1363            $return['attachments'] = $attachments;
1364            //----------------------------------------------//
[2]1365
[4416]1366            /*
[4429]1367             * Monta informações das imagens
1368             */
[4416]1369            $images = $attachmentManager->getEmbeddedImagesInfo();
1370            //----------------------------------------------//
[1472]1371
[4795]1372                if(!$this->has_cid)
1373                {
[4416]1374                    $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
[5134]1375               // $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
[4795]1376                }
[1472]1377
[4416]1378            switch (strtolower($structure->ctype_primary))
[4795]1379                {
[4908]1380                        case 'text':
1381                                        if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
1382                                        {
[4795]1383                                $return['body']='isCripted';
1384                                return $return;
1385                        }
[4416]1386                        $attachment = array();
[3414]1387
[4416]1388                        $msg_subtype = strtolower($structure->ctype_secondary);
[5134]1389                    if(isset($structure->disposition))
[4416]1390                        $disposition = strtolower($structure->disposition);
[5134]1391                    else
1392                        $disposition = '';
[1472]1393
[4908]1394                        if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
[4795]1395                        {
[4416]1396                                if(strtolower($msg_subtype) == 'plain')
[4795]1397                                        {
[5134]1398                        if(isset($structure->ctype_parameters['charset']))
[4781]1399                                        $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false);
[5134]1400                        else
1401                            $content = $this->decodeMailPart($structure->body, null,false);
[4795]1402                                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );
1403                                                $content = htmlentities( $content );
[4784]1404                                        $this->replace_links($content);
[4795]1405                                                $content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content );
1406                                                $content = '<pre>' . $content . '</pre>';
1407                                                $return[ 'body' ] = $content;
1408                                                return $return;
1409                                        }
[4781]1410                                                                $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']);
[4795]1411                                }
[5134]1412                    if(strtolower($structure->ctype_secondary) == 'calendar')
1413                           $content .= $this->builderMsgCalendar($structure->body);
[1897]1414
[4416]1415                    break;
[1897]1416
[4429]1417               case 'multipart':
[5134]1418                    $this->builderMsgBody($structure , $content);
[1897]1419
[4416]1420                    break;
[1897]1421
[4416]1422               case 'message':
[5134]1423                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != 1)
1424                    {
[4416]1425                    if(!is_array($structure->parts))
[4795]1426                                {
[4416]1427                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4781]1428                        $content .= '<pre>'.htmlentities($this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false)).'</pre>';
[4416]1429                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[4795]1430                                                }
1431                                            else
[4416]1432                        $this->builderMsgBody($structure , $content,true);
[5134]1433                    }
[4429]1434                    break;
[3018]1435
[5134]1436            case 'application':
1437                if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
1438                {   
1439                  //  $return['body']='isCripted';
1440                  // return $return;
1441                                 
1442                                  //TODO: Descartar código após atualização do módulo de segurança da SERPRO
1443                                        $rawMessageData2 = $this->extractSignedContents($rawMessageData);
1444                                        if($rawMessageData2 === false){
1445                                                $return['body']='isCripted';
1446                                                return $return;
1447                                        }
1448                                        $decoder2 = new Mail_mimeDecode($rawMessageData2);
1449                            $structure2 = $decoder2->decode($params);
1450                            $this-> builderMsgBody($structure2 , $content); 
1451                 
1452                            $attachmentManager->setStructure($structure2);
1453                            /*
1454                            * Monta informações dos anexos para o cabecarios
1455                            */
1456                            $attachments = $attachmentManager->getAttachmentsInfo();
1457                        $return['attachments'] = $attachments;
1458
1459                            //----------------------------------------------//
1460                 
1461                            /*
1462                        * Monta informações das imagens
1463                            */
1464                            $images = $attachmentManager->getEmbeddedImagesInfo();
1465                            //----------------------------------------------//
1466                 
1467                            if(!$this->has_cid){
1468                                $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
1469                                $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
1470                            }
1471                }
1472                        ///////////////////////////////////////////////////////////////////////////////////////////
[4429]1473               default:
1474                    if(count($attachments) > 0)
1475                       $content .= '';
1476                    break;
[4795]1477                                                                }
[3018]1478
[1472]1479                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
[2]1480                $this->set_messages_flag($params);
[4416]1481                $content = $this->process_embedded_images($images,$msg_number,$content, $msg_folder);
[4795]1482                $content = $this->replace_special_characters($content);
[4416]1483                $this->replace_links($content);
1484                $return['body'] = &$content;
1485               
[4795]1486                return $return;
[2]1487        }
[1472]1488
[5134]1489       
1490        //TODO: Descartar código após atualização do módulo de segurança da SERPRO
1491        function extractSignedContents( $data )
1492    {
1493                $pipes_desc = array(
1494                        0 => array('pipe', 'r'),
1495                        1 => array('pipe', 'w')
1496            );
1497         
1498            $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes);
1499            if (!is_resource($fp)) {
1500                        return false;
1501            }
1502         
1503            $output = '';
1504         
1505                /* $pipes[0] => writeable handle connected to child stdin
1506                $pipes[1] => readable handle connected to child stdout */
1507            fwrite($pipes[0], $data);
1508            fclose($pipes[0]);
1509         
1510            while (!feof($pipes[1])) {
1511                        $output .= fgets($pipes[1], 1024);
1512            }
1513            fclose($pipes[1]);
1514            proc_close($fp);
1515         
1516            return $output;
1517        }
1518    ///////////////////////////////////////////////////////////////////////////////////////
1519   
1520        function builderMsgCalendar($calendar)
1521        {
1522            $icalService = ServiceLocator::getService('ical');
1523
1524            $codificao =  mb_detect_encoding($calendar.'x', 'UTF-8, ISO-8859-1');
1525            if($codificao == 'UTF-8')
1526                $calendar = utf8_decode($calendar);
1527
1528            if($icalService->setIcal($calendar))
1529            {
1530                $content = '';
1531
1532                switch ($icalService->getMethod()) {
1533
1534                    case 'REPLY':
1535                          include_once($_SESSION['rootPath'].'/header.inc.php');
1536                          include_once($_SESSION['rootPath'].'/calendar/inc/class.boicalendar.inc.php');
1537                          $boicalendar = new boicalendar();
1538
1539                          $ical = $icalService->getComponent('vevent');
1540                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
1541                          $content.= '<span style="font-size: 12" >';
1542                          $notExist = false;
1543
1544                          foreach ($ical['attendee'] as $attendee)
1545                          {
1546                                if($attendee['params']['PARTSTAT'] == 'ACCEPTED')
1547                                {
1548                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'ACCEPTED',$attendee['params']['CN']))
1549                                    {
1550                                        $content.= $this->functions->getLang('User').' ';
1551                                        if($attendee['params']['CN'])
1552                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1553                                        else
1554                                            $content.= '<b>'.$attendee['value'].'</b> ';
1555
1556                                        $content.= $this->functions->getLang('accepted your event');
1557                                    }
1558                                    else
1559                                        $notExist = true;
1560                                }
1561
1562                                if($attendee['params']['PARTSTAT'] == 'TENTATIVE')
1563                                {
1564                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'TENTATIVE',$attendee['params']['CN']))
1565                                    {
1566                                        $content.= $this->functions->getLang('User').' ';
1567                                        if($attendee['params']['CN'])
1568                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1569                                        else
1570                                            $content.= '<b>'.$attendee['value'].'</b> ';
1571
1572                                        if($ical['description']['value'])
1573                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1574                                        else
1575                                            $content.= $this->functions->getLang('provisionally accepted you event');
1576                                    }
1577                                    else
1578                                         $notExist = true;
1579                                }
1580
1581                                if($attendee['params']['PARTSTAT'] == 'DECLINED')
1582                                {
1583                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'DECLINED',$attendee['params']['CN']))
1584                                    {
1585                                        $content.= $this->functions->getLang('User').' ';
1586                                        if($attendee['params']['CN'])
1587                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
1588                                        else
1589                                            $content.= '<b>'.$attendee['value'].'</b> ';
1590
1591                                        if($ical['description']['value'])
1592                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1593                                        else
1594                                            $content.= $this->functions->getLang('provisionally decline you event');
1595                                    }
1596                                    else
1597                                        $notExist = true;
1598                                }
1599                          }
1600                          if($notExist)
1601                            $content.= '<b><span style="color:red">'.$this->functions->getLang('This event does not exist on its agenda').'.</span></b>';
1602                          $content.= '</span><br /><br />';
1603
1604                        break;
1605
1606                      case 'CANCEL':
1607
1608                          $ical = $icalService->getComponent('vevent');
1609                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
1610                          $content.= '<span style="font-size: 12" >';
1611                          $content.= '<b><span style="color:red">'.$this->functions->getLang('Your event has been canceled').'</span></b>';
1612   
1613                          if($ical['description']['value'])
1614                              $content.= ' <br /> <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
1615
1616                          $content.= '<br /><b>* '.$this->functions->getLang('To remove the event from your calendar to import the iCal file attached').'.</b>';
1617                          $content.= '</span><br /><br />';
1618                        break;
1619
1620                    case 'REQUEST':
1621
1622                        $ical = $icalService->getComponent('vevent');
1623                        if($ical['dtstart']['value']['tz'] == 'Z')
1624                        {
1625                            $tz = $_SESSION['phpgw_info']['user']['preferences']['common']['tz_offset'];
1626                            $ical['dtstart']['value']['hour'] += $tz;
1627                            $ical['dtend']['value']['hour'] += $tz;
1628                        }
1629                       
1630                        $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br />'.
1631                                   ' <br /> <b>'.$this->functions->getLang('Title').': </b>'.$ical['summary']['value'].
1632                                   ' <br /> <b>'.$this->functions->getLang('Location').': </b>'.$ical['location']['value'].
1633                                   ' <br /> <b>'.$this->functions->getLang('Details').': </b>'. str_replace('\n','<br />',nl2br($ical['description']['value']));
1634                        $content.= ' <br /> <b>'.$this->functions->getLang('Start') . ':  </b>' . $ical['dtstart']['value']['day'] . "/" . $ical['dtstart']['value']['month']  . "/" . $ical['dtstart']['value']['year']  . " - " . $ical['dtstart']['value']['hour']  . ":" . $ical['dtstart']['value']['min'] ;
1635                        $content.= ' <br /> <b>'.$this->functions->getLang('End') . ': </b>' . $ical['dtend']['value']['day'] . "/" . $ical['dtend']['value']['month']  . "/" . $ical['dtend']['value']['year']  . " - " . $ical['dtend']['value']['hour']  . ":" . $ical['dtend']['value']['min'] ;
1636
1637                        if($ical['organizer']['params']['CN'])
1638                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b>'.$ical['organizer']['params']['CN'].' -  <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a></li>' ;
1639                        else
1640                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b> <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a>' ;
1641
1642                        if($ical['attendee'])
1643                        {
1644                            $att = ' <br /> <b>'.$this->functions->getLang('Participants').': </b>';
1645                            $att .= '<ul> ';
1646                            foreach ($ical['attendee'] as $attendee)
1647                            {
1648                                if($attendee['params']['CN'])
1649                                    $att .= '<li>'.$attendee['params']['CN'].' -  <a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
1650                                else
1651                                    $att .= '<li><a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
1652                            }
1653                            $att .= '</ul> <br />'  ;
1654                        }
1655                        $content.= $att;
1656
1657                        break;
1658                    default:
1659                        break;
1660                }
1661     
1662            }
1663            return $content;
1664        }
1665       
[2]1666        function htmlfilter($body)
1667        {
1668                require_once('htmlfilter.inc');
[1472]1669
[2]1670                $tag_list = Array(
1671                                false,
1672                                'blink',
1673                                'object',
1674                                'meta',
1675                                'html',
1676                                'link',
1677                                'frame',
1678                                'iframe',
1679                                'layer',
1680                                'ilayer',
1681                                'plaintext'
1682                );
1683
1684                /**
1685                * A very exclusive set:
1686                */
1687                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
1688                $rm_tags_with_content = Array(
1689                                'script',
1690                                'style',
1691                                'applet',
1692                                'embed',
1693                                'head',
1694                                'frameset',
1695                                'xml',
1696                                'xmp'
1697                );
1698
1699                $self_closing_tags =  Array(
1700                                'img',
1701                                'br',
1702                                'hr',
1703                                'input'
1704                );
1705
1706                $force_tag_closing = true;
1707
1708                $rm_attnames = Array(
1709                        '/.*/' =>
1710                                Array(
1711                                        '/target/i',
1712                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
1713                                        '/^dynsrc/i',
1714                                        '/^datasrc/i',
1715                                        '/^data.*/i',
1716                                        '/^lowsrc/i'
1717                                )
1718                );
1719
1720                /**
1721                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
1722                 * some idea of what's going on here. :)
1723                 */
1724
1725                $bad_attvals = Array(
1726                '/.*/' =>
1727                Array(
1728                      '/.*/' =>
1729                              Array(
1730                                Array(
1731                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1732                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1733                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1734                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1735                                      ),
1736                            Array(
1737                                              '\\1oddjob:\\2\\1',
1738                                          //'\\1uucp:\\2\\1', -> doclinks notes
1739                                      '\\1amaretto:\\2\\1',
1740                                          '\\1round:\\2\\1'
1741                                        )
[1472]1742                                    ),
1743
[2]1744                          '/^style/i' =>
1745                              Array(
1746                                        Array(
1747                                          '/expression/i',
1748                                              '/behaviou*r/i',
1749                                          '/binding/i',
1750                                              '/include-source/i',
1751                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1752                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1753                                         ),
1754                                        Array(
1755                                          'idiocy',
1756                                              'idiocy',
1757                                          'idiocy',
1758                                              'idiocy',
1759                                          'url(\\1http://securityfocus.com/\\1)',
1760                                          'url(\\1http://securityfocus.com/\\1)'
1761                                         )
1762                                )
1763                          )
1764                    );
1765
1766                $add_attr_to_tag = Array(
1767                                '/^a$/i' => Array('target' => '"_new"')
1768                );
[1472]1769
1770
[2]1771                $trusted_body = sanitize($body,
1772                                $tag_list,
1773                                $rm_tags_with_content,
1774                                $self_closing_tags,
1775                                $force_tag_closing,
1776                                $rm_attnames,
1777                                $bad_attvals,
1778                                $add_attr_to_tag
1779                );
[1472]1780
[2]1781            return $trusted_body;
1782        }
[1472]1783
[2]1784        function decodeBody($body, $encoding, $charset=null)
1785        {
[4416]1786
[2]1787                if ($encoding == 'quoted-printable')
[828]1788                {
[2]1789                        $body = quoted_printable_decode($body);
[1792]1790
[4795]1791                        }
1792        else if ($encoding == 'base64')
1793        {
1794                $body = base64_decode($body);
1795        }
1796                // All other encodings are returned raw.
1797                if (strtolower($charset) == "utf-8")
1798                        return utf8_decode($body);
1799        else
1800                        return $body;
1801        }
1802
[4436]1803                               
1804        /**
1805        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1806        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1807        * @param     $images
1808        * @param     $msgno
1809        * @param     $body
1810        * @param     $msg_folder
1811        */                     
[4416]1812        function process_embedded_images($images, $msgno, $body, $msg_folder)
[2]1813        {
[1472]1814
[4416]1815            foreach ($images as $image)
[4795]1816                {
[4416]1817                $image['cid'] = eregi_replace("<", "", $image['cid']);
1818                $image['cid'] = eregi_replace(">", "", $image['cid']);
[5134]1819                               
1820                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\" ", $body);
1821                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
1822                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
[4795]1823                        }
1824                return $body;
[2]1825        }
[1472]1826
[5309]1827        function replace_special_characters($body)
1828        {
1829            // Suspected TAGS!
1830            // $tag_list = Array('blink','object','meta','html','link','frame','iframe','layer','ilayer','plaintext','script','style','img','applet','embed','head','frameset','xml','xmp');
1831            // remove MS Office's proprietary tag
1832            //$body = mb_ereg_replace('<!\-\-\[if [^!]* mso .*\]>.*<!\[endif\]\-\->', '', $body);
1833            // Layout problem: Change html elements
1834            // with absolute position to relate position, CASE INSENSITIVE.
1835            $body = @mb_eregi_replace("POSITION: ABSOLUTE;", "", $body);
[4795]1836
[5309]1837            //Remove Comentario Expresso
1838            $findExpCom[] = '<!-- TAG <';
1839            $findExpCom[] = '> Removed by ExpressoMail -->';
1840            $body = str_replace($findExpCom, '', $body);
1841            ///--------------------------------//
1842            // tags to be removed doe to security reasons
1843            $tag_list = Array(
1844                'blink', 'object', 'frame', 'iframe',
1845                'layer', 'ilayer', 'plaintext', 'script',
1846                'applet', 'embed', 'frameset', 'xml', 'xmp'
1847            );
[2]1848
[5309]1849            foreach ($tag_list as $index => $tag)
1850                $body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body);
1851           
[5134]1852
[5309]1853            $body = @mb_eregi_replace("<meta[^>]*>", '', $body);
1854            $body = @mb_eregi_replace("<base[^>]*>", '', $body);
[4795]1855
[5309]1856            //try to wrap CSS code instead of remove STYLE tags
1857            require_once('../library/csstidy/class.csstidy.php');
1858            $css = new csstidy();
1859            $css->set_cfg('preserve_css', false);
[6]1860
[5309]1861            $regs_found = array();
1862            $tags_found = @mb_eregi("<style\b[^>]*>(.*?)</style[^>]*>", $body, $regs_found);
1863            $wrapper_class = 'ExpressoCssWrapper' . time();
[2]1864
[5309]1865            foreach ($regs_found as $block_found) {
1866                $n_start = strpos($block_found, '>') + 1;
1867                $n_length = strrpos($block_found, '<') - $n_start;
1868                $bf_innerHTML = substr($block_found, $n_start, $n_length);
[4416]1869
[5309]1870                $bf_innerHTML = mb_ereg_replace('<!--', '', $bf_innerHTML);
1871                $bf_innerHTML = mb_ereg_replace('-->', '', $bf_innerHTML);
[4416]1872
[5309]1873                $css->parse($bf_innerHTML);
[4795]1874
[5309]1875                $prefix = ".$wrapper_class ";
1876                if (isset($css->css[41]) && count($css->css[41] > 0))
1877                    foreach ($css->css[41] as $key => $value) {
1878                        //explode multiple selectors per block
1879                        $selectors = explode(',', $key);
[4795]1880
[5309]1881                        foreach ($selectors as $selector) {
1882                            if (ereg('\*', $key)) {
1883                                //skip selecto '*'
1884                                continue;
1885                            }
[4996]1886
[5309]1887                            $selector = eregi_replace('[^#\.]*body.*', '', $selector);
1888                            $css->css[41][$prefix . trim($selector)] = $value;
1889                        }
1890                        unset($css->css[41][$key]);
1891                    }
[5134]1892
[5309]1893                $body = str_replace($block_found, '<style>' . $css->print->plain() . '</style>', $body);
1894        }
1895
1896
1897        // Malicious Code Remove
1898        $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";
1899        preg_match_all($dirtyCodePattern, $body, $rest, PREG_PATTERN_ORDER);
1900        foreach ($rest[0] as $i => $val) {
1901            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
1902                $body = str_replace($rest[1][$i], "<" . $rest[2][$i] . $rest[3][$i] . $rest[7][$i] . ">", $body);
1903        }
1904
1905        /*
1906         * Remove deslocamento a esquerda colocado pelo Outlook.
1907         * Este delocamento faz com que algumas palavras fiquem escondidas atras da barra lateral do expresso.
1908         */
1909        $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1910        $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1911        $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)", "\\1\\3", $body);
1912        //--------------------------------------------------------------------------------------------//       
1913        //Remoção de tags <span></span> para correção de erro no firefox
1914        //Comentado pois estes replaces geram erros no html da msg, não se pode garantir que o os </span></span> sejam realmente os fechamentos dos <span><span>.
1915        //Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo.
1916        //              $body = mb_eregi_replace("<span><span>","",$body);
1917        //              $body = mb_eregi_replace("</span></span>","",$body);
1918        //Correção para compatibilização com Outlook, ao visualizar a mensagem
1919        $body = mb_ereg_replace('<!--\[', '<!-- [', $body);
1920        $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1921
1922        return "<div class=\"$wrapper_class\"><span>" . $body . '</span></div>';
1923    }
[5079]1924       
[4784]1925        function replace_links_callback($matches) 
[4800]1926        {
[5247]1927            if($matches[3])
1928                    $pref = $matches[3];
1929            else
1930                    $pref = $matches[3] = 'http';
[4795]1931
[5247]1932            return '<a href="'.$pref.'://'.$matches[4].$matches[5].'" target="_blank">'.$matches[0].'</a>';
[4784]1933        }
[4795]1934
1935
[4436]1936        /**
1937        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1938        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1939        * @param     $body corpo da mensagem
1940        */
1941        function replace_links(&$body)
[5247]1942        {
[4784]1943                // Trata urls do tipo aaaa.bbb.empresa 
1944                // Usadas na intranet. 
[5247]1945                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])(((http|https|ftp|ftps)?:\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';   
1946                $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body);
[1897]1947
[4795]1948        }
1949
[91]1950        function get_signature($msg, $msg_number, $msg_folder)
[1035]1951        {
[3352]1952            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1953            include_once("class.db_functions.inc.php");
1954            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1955            {
1956                $sign = array();
1957                $temp = $this->get_info_head_msg($msg_number);
1958                if($temp['ContentType'] =='normal') return $sign;
1959                $file_type = strtolower($file_type);
1960                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]1961                {
[3394]1962                    if ($temp['ContentType'] == 'signature')
[3352]1963                    {
[3394]1964                        if(!$this->mbox || !is_resource($this->mbox))
1965                        $this->mbox = $this->open_mbox($msg_folder);
[1035]1966
[3352]1967                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[1035]1968
[3352]1969                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1970                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
[1035]1971
[3352]1972                        $certificado = new certificadoB();
1973                        $validade = $certificado->verificar($imap_msg);
[3394]1974                                        $sign[] = $certificado->msg_sem_assinatura;
[3352]1975                        if ($certificado->apresentado)
1976                        {
1977                            $from = $header->from;
1978                            foreach ($from as $id => $object)
1979                            {
1980                                $fromname = $object->personal;
1981                                $fromaddress = $object->mailbox . "@" . $object->host;
1982                            }
1983                            foreach ($certificado->erros_ssl as $item)
1984                            {
1985                                $sign[] = $item . "#@#";
1986                            }
[1035]1987
[3352]1988                            if (count($certificado->erros_ssl) < 1)
1989                            {
1990                                $check_msg = 'Message untouched';
1991                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1992                                {
1993                                    $check_msg .= ' and authentic###';
1994                                }
1995                                else
1996                                {
1997                                    $check_msg .= ' with signer different from sender#@#';
1998                                }
1999                                $sign[] = $check_msg;
2000                            }
2001                                               
2002                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
2003                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
2004                            $sign[] = 'Mail from: ###' . $fromaddress;
2005                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
2006                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
2007                            $sign[] = 'Message date: ###' . $header->Date;
[1035]2008
[3352]2009                            $cert = openssl_x509_parse($certificado->cert_assinante);
[1035]2010
[3352]2011                            $sign_alert = array();
2012                            $sign_alert[] = 'Certificate Owner###:\n';
2013                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
2014                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
2015                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
2016                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
2017                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
2018                            $sign_alert[] = 'Personal Data###:' . '\n';
2019                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
2020                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
2021                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
2022                            $sign_alert[]= 'Certificate Issuer###:\n';
2023                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
2024                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
2025                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
2026                            $sign_alert[]= 'Validity###:\n';
2027                            $H = data_hora($cert[validFrom]);
2028                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2029                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
2030                            $H = data_hora($cert[validTo]);
2031                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
2032                            $sign_alert[]= 'Valid Until### ' . $X;
2033                            $sign[] = $sign_alert;
2034
2035                            $this->db = new db_functions();
2036                           
2037                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
2038                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
2039                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
[91]2040                        }
[3352]2041                        else
2042                        {
2043                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
2044                            foreach($certificado->erros_ssl as $item)
2045                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
2046                        }
2047                    }
[91]2048                }
[3352]2049            }
2050            return $sign;
[91]2051        }
2052
[4436]2053       
2054        /**
2055        * @license   http://www.gnu.org/copyleft/gpl.html GPL
2056        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2057        * @param     $images
2058        * @param     $msg_number
2059        * @param     $msg_folder
2060        */
[4416]2061        function get_thumbs($images, $msg_number, $msg_folder)
[2]2062        {
[4416]2063
[5134]2064                if (!count($images)) return '';
[4416]2065               
[5134]2066                foreach ($images as $key => $value) {
2067                        $images[$key]['width']  = 160;
2068                        $images[$key]['height'] = 120;
2069                        $images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$image['pid']."&image=true";
[4795]2070                }
[5134]2071
2072                return json_encode($images);
[2]2073        }
[1472]2074
[2]2075        /*function delete_msg($params)
2076        {
2077                $folder = $params['folder'];
2078                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[1472]2079
[2]2080                $mbox_stream = $this->open_mbox($folder);
[1472]2081
[2]2082                foreach ($msgs_to_delete as $msg_number){
2083                        imap_delete($mbox_stream, $msg_number, FT_UID);
2084                }
2085                imap_close($mbox_stream, CL_EXPUNGE);
2086                return $params['msgs_to_delete'];
2087        }*/
2088
2089        // Novo
2090        function delete_msgs($params)
2091        {
[4795]2092
[2]2093                $folder = $params['folder'];
[51]2094                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]2095                $msgs_number = explode(",",$params['msgs_number']);
[5134]2096                if(array_key_exists('border_ID' ,$params))
[2]2097                $border_ID = $params['border_ID'];
[5134]2098                else
2099                        $border_ID = '';
[2]2100                $return = array();
[4795]2101
[5134]2102                if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){
[2]2103                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]2104                        // Fix problem in unserialize function JS.
2105                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2106                }
[2]2107
[4795]2108                //$mbox_stream = $this->open_mbox($folder);
[504]2109                $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()))));
[4795]2110
[2]2111                foreach ($msgs_number as $msg_number)
2112                {
2113                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
2114                                $return['msgs_number'][] = $msg_number;
2115                }
[4795]2116
[2]2117                $return['folder'] = $folder;
2118                $return['border_ID'] = $border_ID;
[4795]2119
[51]2120                if($mbox_stream)
2121                        imap_close($mbox_stream, CL_EXPUNGE);
[5172]2122                       
2123                $return['status'] = true;
[2]2124                return $return;
2125        }
2126
[1472]2127
[2]2128        function refresh($params)
2129        {
[3265]2130
[5134]2131                $return = array();
2132                $return['new_msgs'] = 0;
[2]2133                $folder = $params['folder'];
2134                $msg_range_begin = $params['msg_range_begin'];
2135                $msg_range_end = $params['msg_range_end'];
2136                $msgs_existent = $params['msgs_existent'];
[1472]2137                $sort_box_type = $params['sort_box_type'];
[2]2138                $sort_box_reverse = $params['sort_box_reverse'];
2139                $msgs_in_the_server = array();
[53]2140                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[828]2141                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2142                $msgs_in_the_server = array_keys($msgs_in_the_server);
[1472]2143
[828]2144                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
[5134]2145
[5158]2146                $dif = ($params['msg_range_end'] - $params['msg_range_begin']) +1;
2147                if(!count($msgs_in_the_server)){
2148                        $msg_range_begin -= $dif;
2149                        $msg_range_end -= $dif;
2150                        $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
2151                        $msgs_in_the_server = array_keys($msgs_in_the_server); 
2152                        $num_msgs = NULL;
2153                        $return['msg_range_begin'] = $msg_range_begin;
2154                        $return['msg_range_end'] = $msg_range_end;
2155                }               
2156                $return['new_msgs'] = imap_num_recent($this->mbox);
2157               
[1472]2158                $msgs_in_the_client = explode(",", $msgs_existent);
[51]2159
[2]2160                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[5134]2161
2162                if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){
2163                        $aux = 0;
2164                        while(array_key_exists($aux, $msg_to_insert)){
2165                                if($msg_to_insert[$aux] > $msgs_in_the_client[0]){
2166                                        $return['new_msgs'] += 1;
2167                                }
2168                                $aux++;
2169                        }
2170                }else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){
2171                        $aux = 0;
2172                        while(array_key_exists($aux, $msg_to_insert)){
2173                                if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){
2174                                        $return['new_msgs'] += 1;
2175                                }
2176                                $aux++;
2177                        }
[5158]2178                }else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0 && $msg_range_end == $dif){
[5134]2179                        $return['tot_msgs'] = $num_msgs;
2180                }
2181               
[5158]2182                if(!count($msgs_in_the_server)){
2183                        return Array();
2184                }       
2185
[271]2186                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[2]2187                $msgs_to_exec = array();
[3265]2188                foreach($msg_to_insert as $msg_number)
2189                        $msgs_to_exec[] = $msg_number;
[4764]2190                //sort($msgs_to_exec);
[2]2191                $i = 0;
[3265]2192                foreach($msgs_to_exec as $msg_number)
[2]2193                {
[614]2194                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
[1472]2195                        * atributos do cabeçalho. Como eu preciso do atributo Importance
[614]2196                        * para saber se o email é importante ou não, uso abaixo a função
2197                        * imap_fetchheader e busco o atributo importance nela para passar
2198                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
2199                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
2200                        * não preciso reimplementar o método utilizando o fetchheader.
2201                        */
[3955]2202   
2203                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
[1035]2204                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
[689]2205                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
[1472]2206
[1752]2207                        $msg_sample = $this->get_msg_sample($msg_number);
2208                        $return[$i]['msg_sample'] = $msg_sample;
2209
[535]2210                        $header = $this->get_header($msg_number);
[2]2211                        if (!is_object($header))
[828]2212                                continue;
2213
[2]2214                        $return[$i]['msg_number']       = $msg_number;
[3955]2215                       
2216                        //get the next msg number to append this msg in the view in a correct place
2217                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
2218                       
[4764]2219                        $return[$i]['msg_key_position'] = $msg_key_position;
2220                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1,$msgs_in_the_server) !== false)
[3955]2221                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
[4764]2222                        else
2223                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position];
[1472]2224
[2]2225                        $return[$i]['msg_folder']       = $folder;
[3955]2226                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
[3265]2227                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
[2]2228                        $return[$i]['Recent']           = $header->Recent;
2229                        $return[$i]['Unseen']           = $header->Unseen;
2230                        $return[$i]['Answered']         = $header->Answered;
2231                        $return[$i]['Deleted']          = $header->Deleted;
2232                        $return[$i]['Draft']            = $header->Draft;
2233                        $return[$i]['Flagged']          = $header->Flagged;
2234
[3106]2235                        $return[$i]['udate'] = $header->udate;
2236               
[2]2237                        $from = $header->from;
2238                        $return[$i]['from'] = array();
2239                        $tmp = imap_mime_header_decode($from[0]->personal);
2240                        $return[$i]['from']['name'] = $tmp[0]->text;
2241                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]2242                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[5134]2243                        if(!$return[$i]['from']['name'] || trim($return[$i]['from']['name']) === '')
[2]2244                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[1472]2245
[2]2246                        /*$toaddress = imap_mime_header_decode($header->toaddress);
2247                        $return[$i]['toaddress'] = '';
2248                        foreach ($toaddress as $tmp)
2249                                $return[$i]['toaddress'] .= $tmp->text;*/
2250                        $to = $header->to;
2251                        $return[$i]['to'] = array();
[5134]2252                        if(isset($to[0]->personal))
[2]2253                        $tmp = imap_mime_header_decode($to[0]->personal);
[5134]2254                        if(trim($return[$i]['to']['name']) === '')
2255                                $return[$i]['to']['name'] = $to[0]->mailbox . "@" . $to[0]->host;
2256                        else
[2]2257                        $return[$i]['to']['name'] = $tmp[0]->text;
2258                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2259                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[5134]2260                        if(isset($header->cc))
[3777]2261                        $cc = $header->cc;
[5134]2262
2263                        if ( isset($cc) && (!$return[$i]['to']['name'] || $return[$i]['to']['name'] == '@') ){
[3777]2264                                $return[$i]['to']['name'] =  $cc[0]->personal;
2265                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
2266                        }
[5134]2267                        $return[$i]['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
2268                        if($return[$i]['subject'] == "" || $return[$i]['subject'] == '' || $return[$i]['subject'] == null ){
2269                                $return[$i]['subject'] = $this->functions->getLang("(no subject)   ");
2270                        }
[2]2271                        $return[$i]['Size'] = $header->Size;
2272                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]2273
[5134]2274                        if($return[$i]['to']['email'] == '@' || $return[$i]['to']['email'] =='undisclosed-recipients@' || $return[$i]['to']['name'] =='undisclosed-recipients@'
2275                                || $return[$i]['to']['name'] == null){
2276                                $return[$i]['to']['email'] = $return[$i]['from']['email'];
2277                                $return[$i]['to']['name'] = $return[$i]['from']['name'];
2278                                $return[$i]['to']['full'] = $return[$i]['reply_toaddress'];
2279                        }
2280                       
[2]2281                        $return[$i]['attachment'] = array();
[3265]2282                        if (!isset($imap_attachment))
2283                        {
2284                                include_once("class.imap_attachment.inc.php");
2285                                $imap_attachment = new imap_attachment();
2286                        }
[51]2287                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]2288                        $i++;
2289                }
[3265]2290                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
2291                $return['sort_box_type'] = $params['sort_box_type'];
[3427]2292                if(!$this->mbox || !is_resource($this->mbox))
2293                {
2294                    $this->open_mbox($folder);
2295                }
[4819]2296
[271]2297                $return['msgs_to_delete'] = $msg_to_delete;
[3493]2298                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
[411]2299                if($this->mbox && is_resource($this->mbox))
[51]2300                        imap_close($this->mbox);
[828]2301
[2]2302                return $return;
2303        }
2304
[1035]2305     /**
2306     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
2307     * assinado ou cifrado.
2308     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
2309     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
2310     * @param $msg_number O número da mesagem
2311     * @return Retorna o tipo da mensagem (normal, signature, cipher).
2312     */
2313    function getMessageType($msg_number, $headers = false){
[3394]2314            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2315            $contentType = "normal";
2316            if (!$headers){
2317                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
2318            }
[3394]2319           
2320            if (preg_match("/pkcs7-signature/i", $headers) == 1){
[1035]2321                $contentType = "signature";
[3394]2322            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
2323                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
[1035]2324            }
2325
2326            return $contentType;
2327    }
[5216]2328   
[5218]2329                /**
2330        * Retorna a posição que a pasta esta dentro do array de pastas
2331        *
2332        * @license    www.gnu.org/copyleft/gpl.html GPL
2333        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2334        * @sponsor    Caixa Econômica Federal
2335        * @author     Cristiano Corrêa Schmidt
2336        * @access     public
2337                */
2338               
[5216]2339        function getFolderPos(&$array , $find)
2340        {           
2341                foreach($array as $i => $v)
2342                        if($v['id'] === $find)
2343                                return $i;
2344                return false;
2345        }
2346       
2347        /**
2348        * Ordenas as pastas padrões do usuario na ordem INBOX > SENT > DRAFTS > SPAM > TRASH > OTHERS
2349        *
2350        * @license    http://www.gnu.org/copyleft/gpl.html GPL
2351        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2352        * @sponsor    Caixa Econômica Federal
2353        * @author     Cristiano Corrêa Schmidt
2354        * @access     public
2355        */
2356        function orderDefaultFolders( &$folders , $user)
[2]2357        {
[5216]2358                $principals = array();
2359                for($x = 0; $x < 5 ; $x++)
2360                {
2361                        switch ($x) {
2362                                case 0:                             
2363                                        if( ($p = $this->getFolderPos($folders , $user )) || $p === 0 )
2364                                                $principals[] = $folders[$p];
2365                                        break;
2366                                case 1:
[5306]2367                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['drafts'])) )) || $p === 0 )
[5216]2368                                                $principals[] = $folders[$p];
2369                                        break;
2370                                case 2:
[5306]2371                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['sent'])) )) || $p === 0 )
[5216]2372                                                $principals[] = $folders[$p];
2373                                        break;
2374                                case 3:
[5306]2375                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['spam'])) )) || $p === 0 )
[5216]2376                                                $principals[] = $folders[$p];
2377                                        break;
2378                                case 4:
[5306]2379                                        if( ($p = $this->getFolderPos($folders , $this->mount_url_folder(array($user , $this->folders['trash'])) )) || $p === 0  )
[5216]2380                                                $principals[] = $folders[$p];                                           
2381                                        break;
2382                        }
2383                        if($p !== false)
2384                                unset($folders[$p]);
[1953]2385                }
[5216]2386                $folders = array_merge($principals, $folders);
2387        }
2388       
2389        /**
2390        * Retorna lista de pastas do usuario no padrão que a lib javascript espera.
2391        *
2392        * @license    http://www.gnu.org/copyleft/gpl.html GPL
2393        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2394        * @sponsor    Caixa Econômica Federal
2395        * @author     Cristiano Corrêa Schmidt
2396        * @access     public
2397        */
2398        function get_folders_list($params = null)
2399        {
2400                ///Define Variaveis
2401                $prefixShared = 'user'; //Prefixo das pastas compartilhadas
2402                $uid2cn = (isset($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'])) ? $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] : false;
2403                $mboxStream = $this->open_mbox(); //abre conexão imap
2404                $currentFolder = isset($params['folder']) ? $params['folder'] : 'INBOX';
2405                $folders = array();
2406                $return = array();
2407                ///////////////////////////////////////////////////////////////
2408                   
2409                if( isset($params['onload']) && $_SESSION['phpgw_info']['expressomail']['server']['certificado'])
2410                        $this->delete_mailbox(array('del_past' => 'INBOX'.$this->imap_delimiter.'decifradas')); //Deleta Pasta decifradas
2411               
2412                session_write_close(); // Free others requests
[3018]2413                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[3790]2414               
[5216]2415                if ( isset($params['noSharedFolders']) )
2416                        $folders_list = array_merge(imap_getmailboxes($mboxStream, $serverString, 'INBOX' ), imap_getmailboxes($mboxStream, $serverString, 'INBOX/*' ) );
[3790]2417                else
[5216]2418                        $folders_list = imap_getmailboxes($mboxStream, $serverString, '*' );
[3761]2419
[3018]2420                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
2421
[5216]2422                if (!is_array($folders_list)) return false;
2423                        if($uid2cn)
2424                                $this->ldap = new ldap_functions();
2425               
2426                foreach ($folders_list as $i => $v ) //Separando Pastas e informações
[1816]2427                {
[5216]2428                        $folderId = substr($v->name,(strpos($v->name , '}') + 1));
2429                        $nameArray = explode($this->imap_delimiter, $folderId);
2430                        $nameCount = count($nameArray);
2431                        $decifrada = mb_convert_encoding('INBOX'.$this->imap_delimiter.'decifradas','UTF7-IMAP','ISO-8859-1'); //Ignorar esta pasta decifrada
2432                        $parent = ($nameCount > 1 && $nameArray[($nameCount - 2)] !== 'INBOX') ? implode($this->imap_delimiter, array_slice($nameArray, 0, ($nameCount - 1))): ''; //Pega folder pai
2433                        if($nameArray[0] === 'user')
2434                                $folders[$prefixShared.$this->imap_delimiter.$nameArray[1]][] = array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes , 'name' => $nameArray[($nameCount-1)] , 'user' => $nameArray[1] ,'parent' => $parent);
2435                        else if( $folderId !== $decifrada) //Escapa pasta decifrada
2436                                $folders['INBOX'][] =  array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes ,'name' => $nameArray[($nameCount-1)] , 'parent' => $parent);
[1816]2437                }
[5216]2438                unset($folders_list); //destroy array de objetos desnecessarios
2439                foreach($folders as $i => $v) //Ordenando e resgatando novas informações
2440                {
2441                        $this->orderDefaultFolders($folders[$i] , $i);  //Ordenando Pastas Padrões
2442                       
2443                        foreach ($folders[$i] as $ii => $vv)
[5134]2444                        {
[5216]2445                                $append = array();                             
2446                                $append['folder_id'] = mb_convert_encoding($vv['id'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA ID DAS PASTAS COM ACENTOS
2447                                $append['folder_name'] = (($uid2cn && isset($vv['user'])) && ($cn = $this->ldap->uid2cn($vv['user']))) ? $cn : $vv['name'];
2448                                $append['folder_name'] = mb_convert_encoding($append['folder_name'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA NOME DAS PASTAS COM ACENTOS
2449                                $status = imap_status($mboxStream, $vv['stream'], SA_UNSEEN); //Resgata Numero de mensagens não lidas
2450                                $append['folder_unseen'] = isset($status->unseen) ? $status->unseen : 0 ;
2451                                $append['folder_hasChildren'] = (($vv['attributes'] == 32) && ($vv['name'] != 'INBOX')) ? 1 : 0;
[5228]2452                                $append['folder_parent'] = mb_convert_encoding($vv['parent'],'ISO-8859-1','UTF7-IMAP');
[5216]2453                                $return[] = $append;
[5134]2454                        }
2455                }
[5216]2456               
2457                $quotaInfo =  (!isset($params['noQuotaInfo'])) ? $this->get_quota( array('folder_id' => $currentFolder)) : false; //VERIFICA SE O USUARIO TEM COTA
[5243]2458
[5216]2459                return ( ( is_array($quotaInfo) ) ?  array_merge($return, $quotaInfo) : $return );       
[2]2460        }
[5216]2461   
[1472]2462
[2]2463        function create_mailbox($arr)
2464        {
2465                $namebox        = $arr['newp'];
2466                $mbox_stream = $this->open_mbox();
2467                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]2468                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[1472]2469
[2]2470                $result = "Ok";
[51]2471                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]2472                {
2473                        $result = implode("<br />\n", imap_errors());
[1472]2474                }
2475
[51]2476                if($mbox_stream)
2477                        imap_close($mbox_stream);
[1472]2478
[2]2479                return $result;
[1472]2480
[2]2481        }
[1472]2482
[2]2483        function create_extra_mailbox($arr)
2484        {
2485                $nameboxs = explode(";",$arr['nw_folders']);
2486                $result = "";
2487                $mbox_stream = $this->open_mbox();
2488                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1472]2489                foreach($nameboxs as $key=>$tmp){
[2]2490                        if($tmp != ""){
2491                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
2492                                        $result = implode("<br />\n", imap_errors());
[51]2493                                        if($mbox_stream)
[1472]2494                                                imap_close($mbox_stream);
[2]2495                                        return $result;
2496                                }
2497                        }
2498                }
[51]2499                if($mbox_stream)
2500                        imap_close($mbox_stream);
[2]2501                return true;
2502        }
[1472]2503
[2]2504        function delete_mailbox($arr)
2505        {
2506                $namebox = $arr['del_past'];
2507                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[1953]2508                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
[2]2509                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[1472]2510
[2]2511                $result = "Ok";
2512                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2513                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2514                {
2515                        $result = implode("<br />\n", imap_errors());
2516                }
[1953]2517                /*
[51]2518                if($mbox_stream)
2519                        imap_close($mbox_stream);
[1953]2520                */
[2]2521                return $result;
2522        }
[1472]2523
[2]2524        function ren_mailbox($arr)
2525        {
2526                $namebox = $arr['current'];
2527                $new_box = $arr['rename'];
2528                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2529                $mbox_stream = $this->open_mbox();
2530                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[1472]2531
[2]2532                $result = "Ok";
2533                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]2534                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[1472]2535
[2]2536                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2537                {
[1472]2538                        $result = imap_errors();
[2]2539                }
[51]2540                if($mbox_stream)
2541                        imap_close($mbox_stream);
[2]2542                return $result;
[1472]2543
[2]2544        }
[1472]2545
[2]2546        function get_num_msgs($params)
2547        {
2548                $folder = $params['folder'];
[411]2549                if(!$this->mbox || !is_resource($this->mbox)) {
[2]2550                        $this->mbox = $this->open_mbox($folder);
[411]2551                        if(!$this->mbox || !is_resource($this->mbox))
[2]2552                        return imap_last_error();
[1472]2553                }
[2]2554                $num_msgs = imap_num_msg($this->mbox);
[432]2555                if($this->mbox && is_resource($this->mbox))
[51]2556                        imap_close($this->mbox);
[1472]2557
[2]2558                return $num_msgs;
2559        }
[1472]2560
[1912]2561        function folder_exists($folder){
2562                $mbox =  $this->open_mbox();
2563                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2564                $list = imap_getmailboxes($mbox,$serverString, $folder);
2565                $return = is_array($list);             
2566                imap_close($mbox);
2567                return $return;
2568        }
2569       
[2]2570        function send_mail($params)
2571        {
[5134]2572                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
2573                $mailService = ServiceLocator::getService('mail');
2574
[2]2575                include_once("class.db_functions.inc.php");
2576                $db = new db_functions();
2577                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[5134]2578                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
2579               
[449]2580                ##
2581                # @AUTHOR Rodrigo Souza dos Santos
[3369]2582                # @DATE 2008/09/17$fileName
[449]2583                # @BRIEF Checks if the user has permission to send an email with the email address used.
2584                ##
2585                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2586                {
2587                        $deny = true;
2588                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2589                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2590                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2591
2592                        if ( $deny )
2593                                return "The server denied your request to send a mail, you cannot use this mail address.";
2594                }
[2]2595                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
2596                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
2597                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
[5134]2598
2599                $toaddress  = preg_replace('/<\s+/', '<', $toaddress);                 
2600                $toaddress  = preg_replace('/\s+>/', '>', $toaddress);
2601                       
2602                $ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
2603                $ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
2604               
2605                $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
2606                $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
2607               
[3527]2608                $replytoaddress = $params['input_replyto'];
[2]2609                $subject = $params['input_subject'];
[271]2610                $msg_uid = $params['msg_id'];
[2]2611                $return_receipt = $params['input_return_receipt'];
[614]2612                $is_important = $params['input_important_message'];
[1035]2613        $encrypt = $params['input_return_cripto'];
2614                $signed = $params['input_return_digital'];
2615
[5134]2616                $message_attachments = $params['message_attachments'];
2617                 
2618                if(substr($params['input_to'],-1) == ',')
2619                    $params['input_to'] = substr($params['input_to'],0,-1);
2620
2621                if(substr($params['input_cc'],-1) == ',')
2622                    $params['input_cc'] = substr($params['input_cc'],0,-1);
2623
2624                if(substr($params['input_cco'],-1) == ',')
2625                    $params['input_cco'] = substr($params['input_cco'],0,-1);
2626
2627                // Valida numero Maximo de Destinatarios
2628                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0)
2629                {
2630                    $sendersNumber = count(explode(',',$params['input_to']));
2631
2632                    if($params['input_cc'])
2633                        $sendersNumber +=  count(explode(',',$params['input_cc']));
2634                    if($params['input_cco'])
2635                        $sendersNumber +=  count(explode(',',$params['input_cco']));
2636
2637                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username);
2638                    if($userMaxmimumSenders)
2639                    {
2640                        if($sendersNumber > $userMaxmimumSenders)
2641                            return $this->functions->getLang('Number of recipients greater than allowed');
2642                    }
2643                    else
2644                    {
2645                        $ldap = new ldap_functions();
2646                        $groupsToUser = $ldap->get_user_groups($this->username);
2647
2648                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser);
2649
2650                        if($groupMaxmimumSenders > 0)
2651                        {
2652                            if($sendersNumber > $groupMaxmimumSenders)
2653                                return $this->functions->getLang('Number of recipients greater than allowed');
2654                        }
2655                        else
2656                        {
2657                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'])
2658                             return $this->functions->getLang('Number of recipients greater than allowed');
2659                        }
2660                    }
2661
2662                }
2663                //Fim Valida numero maximo de destinatarios
2664               
2665               
2666                //Valida envio de email para shared accounts
2667                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
2668                {
2669                    $ldap = new ldap_functions();
2670                    $arrayF = explode(';', $params['input_from']);
2671
2672                    /*
2673                     * Verifica se o remetente n?o ? uma conta compartilhada
2674                     */
2675                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
2676                    {
2677                        $groupsToUser = $ldap->get_user_groups($this->username);
2678                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
2679
2680                        /*
2681                         * Pega o UID do remetente
2682                         */
2683                        $uidFrom = $ldap->mail2uid($arrayF[1]);
2684
2685                         /*
2686                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
2687                         */
2688                        foreach ($sharedAccounts as $key => $value)
2689                        {
2690                            if($value)
2691                                 $acl = $this->getaclfrombox($value);
2692
2693                             if (array_key_exists($uidFrom, $acl))
2694                                 unset($sharedAccounts[$key]);
2695
2696                        }
2697
2698                        /*
2699                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
2700                         */
2701                        if(count($sharedAccounts) > 0)
2702                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
2703
2704                        /*
2705                         * Retorna as contas compartilhadas bloqueadas
2706                         */
2707                        if(count($accountsBlockeds) > 0)
2708                        {
2709                            $return = '';
2710
2711                            foreach ($accountsBlockeds as $accountBlocked)
2712                                $return.= $accountBlocked.', ';
2713
2714                             $return = substr($return,0,-2);
2715
2716                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
2717                        }
2718                    }
2719                }
2720                // Fim Valida envio de email para shared accounts
2721               
2722               
2723//          TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
2724            if($params['smime'] AND false)
[1035]2725        {
2726            $body = $params['smime'];
2727            $mail->SMIME = true;
2728            // A MSG assinada deve ser testada neste ponto.
2729            // Testar o certificado e a integridade da msg....
[3271]2730            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2731            $erros_acumulados = '';
2732            $certificado = new certificadoB();
2733            $validade = $certificado->verificar($body);
2734            if(!$validade)
2735            {
2736                foreach($certificado->erros_ssl as $linha_erro)
2737                {
2738                    $erros_acumulados .= $linha_erro;
2739                }
2740            }
2741            else
2742            {
2743                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2744                if ($certificado->apresentado)
2745                {
2746                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
[4291]2747                    $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'])&&$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']!=''?$_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']]:$this->username;
2748                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
[1035]2749                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2750                }
2751                else
2752                {
2753                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2754                }
2755            }
2756            if(!$erros_acumulados =='')
2757            {
2758                return $erros_acumulados;
2759            }
2760        }
2761        else
2762        {
[3250]2763            //Compatibilização com Outlook, ao encaminhar a mensagem
[5134]2764                        $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
[1035]2765        }
[5134]2766
[3900]2767                $attachments = $_FILES;
[2]2768                $forwarding_attachments = $params['forwarding_attachments'];
[689]2769                $local_attachments = $params['local_attachments'];
[3369]2770
[1912]2771                //Test if must be saved in shared folder and change if necessary
2772                if( $fromaddress[2] == 'y' ){
2773                        //build shared folder path
2774                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
[5134]2775                        if($this->folder_exists($newfolder))
2776                                $folder = $newfolder;
2777                        else
2778                                $folder = $params['folder'];
2779                       
[1912]2780                } else  {
2781                        $folder = $params['folder'];                   
2782                }
2783               
[5134]2784                $folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
2785                $folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
[1472]2786                $folder_name = $params['folder_name'];
[1035]2787
[5134]2788//              TODO - tratar assinatura e remover o AND false
2789                if($signed && !$params['smime'] AND false)
[1035]2790                {
2791            $mail->Mailer = "smime";
2792                        $mail->SignedBody = true;
2793                }
[1472]2794
[5134]2795
2796                if($fromaddress)
2797                        $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
2798               else
2799                        $mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
2800                //$mailService->addTo($toaddress);
2801                //$mailService->addCc($ccaddress);
[5299]2802                $bol = $this->add_recipients('to', $toaddress, $mailService);
[5134]2803                if(!$bol){
2804                        return $this->parse_error("Invalid Mail:", $toaddress);
[2]2805                }
[5299]2806                $bol = $this->add_recipients('cc', $ccaddress, $mailService);
[5134]2807                if(!$bol){
2808                        return $this->parse_error("Invalid Mail:", $ccaddress);
2809                }
[4832]2810                $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy'];
2811                 
[5134]2812                if($allow)
[4832]2813                                {
[5134]2814                        //$mailService->addBcc($ccoaddress);
[5299]2815                        $bol = $this->add_recipients('cco', $ccoaddress, $mailService);
[5134]2816
2817                        if(!$bol){
2818                                return $this->parse_error("Invalid Mail:", $ccoaddress);
2819                        }
[4832]2820                                }
[271]2821
[5134]2822                $mailService->setSubject($subject);
2823                $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ?
2824                                                strtolower($params['type']) != 'plain' : true );
2825       
2826
2827//              TODO - tratar mensagem criptografada e remover o AND false abaixo
2828        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)      // a msg deve ser enviada cifrada...
[1035]2829                {
2830                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2831            $email = explode(",",$email);
2832            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2833            // Deve ser verificado um numero limite de destinatarios.
2834            // Deve ser verificado se os certificados sao validos.
2835            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2836            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2837            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2838            $erros_acumulados = "";
2839            $aux_mails = array();
2840            $mail_list = array();
2841            if(count($email) > $numero_maximo)
2842            {
2843                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2844                return $erros_acumulados;
2845            }
2846            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2847            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2848            foreach($email as $item)
2849            {
2850                $certificate = $db->get_certificate(strtolower($item));
2851                if(!$certificate)
2852                {
2853                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2854                    return $erros_acumulados;
2855                }
2856
2857                if (array_key_exists("dberr1", $certificate))
2858                {
2859
2860                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2861                    return $erros_acumulados;
2862                                }
2863                if (array_key_exists("dberr2", $certificate))
2864                {
2865                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2866                    //continue;
2867                }
2868                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2869                if (!array_key_exists("certs", $certificate))
2870                {
2871                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2872                    continue;
2873                }
2874            */
[3271]2875                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
[1035]2876
2877                foreach ($certificate['certs'] as $registro)
2878                {
2879                    $c1 = new certificadoB();
2880                    $c1->certificado($registro['chave_publica']);
2881                    if ($c1->apresentado)
2882                    {
2883                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2884                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2885                        {
2886                            $aux_mails[] = $registro['chave_publica'];
2887                            $mail_list[] = strtolower($item);
2888                        }
2889                        else
2890                        {
2891                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2892                            {
2893                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2894                                    $c1->dados['EXPIRADO'],$c2->revogado);
2895                            }
2896
2897                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2898                            foreach($c2->erros_ssl as $linha)
2899                            {
2900                                $erros_acumulados .=  $linha . chr(0x0A);
2901                            }
2902                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2903                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2904                        }
2905                    }
2906                    else
2907                    {
2908                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2909                    }
2910                }
2911                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2912                                {
2913                                        return $erros_acumulados;
2914                        }
2915            }
2916
2917            $mail->Certs_crypt = $aux_mails;
2918        }
[5134]2919                                               
2920                if( count($forwarding_attachments) > 0 )// Build CID images
2921                        $this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body);
[1035]2922
[2]2923                //      Build Uploading Attachments!!!
[3387]2924                if (count($attachments)>0) //Caso seja forward normal...
[2]2925                {
2926                        $total_uploaded_size = 0;
2927                        foreach ($attachments as $attach)
2928                        {
[3900]2929                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2930                                    return $this->parse_error("message file too big");
[3387]2931                                if($attach['name']=='Unknown')
2932                                        continue;
[5134]2933                                $mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
[2]2934                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2935                        }
[5134]2936                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
2937                        {
2938         
2939                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2940                            if( $total_uploaded_size > $upload_max_filesize)
[1472]2941                                return $this->parse_error("message file too big");
[3387]2942                        }
[828]2943                }
[3387]2944                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
[828]2945
[689]2946                        $total_uploaded_size = 0;
[5134]2947                       
[689]2948                        foreach($local_attachments as $local_attachment) {
2949                                $file_description = unserialize(rawurldecode($local_attachment));
2950                                $tmp = array_values($file_description);
[1472]2951                                foreach($file_description as $i => $descriptor){
[689]2952                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2953                                }
[5134]2954                                $mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
[689]2955                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2956                        }
[5134]2957                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
2958                        {
2959                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2960                            if( $total_uploaded_size > $upload_max_filesize)
2961                                   return $this->parse_error("message file too big");
2962                        }
[689]2963                }
[5134]2964
[271]2965                //      Build Forwarding Attachments!!!
[2]2966                if (count($forwarding_attachments) > 0)
2967                {
2968                        // Bug fixed for array_search function
[3018]2969                        $name_cid_files = array();
[2]2970                        if(count($name_cid_files) > 0) {
2971                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2972                                $name_cid_files[0] = null;
[1472]2973                        }
2974
[2]2975                        foreach($forwarding_attachments as $forwarding_attachment)
2976                        {
[5134]2977                                $file_description = unserialize(rawurldecode($forwarding_attachment));
[5177]2978                               
2979                                foreach($file_description as $i => $item)
2980                                        $file_description[$i] = urldecode($item);
2981                               
[5134]2982                                $tmp = array_values($file_description);
2983                                foreach($file_description as $i => $descriptor){
2984                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2985                                }
2986                                $file_description = $tmp;
2987                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2988                                $fileName = $file_description[2];
2989                                if(!array_search(trim($fileName),$name_cid_files)) {
2990                                        $filename_dec = html_entity_decode(rawurldecode($fileName));
2991                                        $mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
2992
2993                                }
2994                        }
2995                }
2996               
2997                //Build Message Attachments!!!
2998                if(count($message_attachments) > 0 )
2999                {
3000                        foreach($message_attachments as $folder_name => $messages)
3001                        {
3002                                foreach ($messages as $message_number => $message_subject)
3003                                {
3004                                        if (!$message_subject)
3005                                                $message_subject  = 'no title.eml';
3006                                        else
3007                                                $message_subject .= '.eml';
3008                                       
3009                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3010                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3011                                        else{
3012                                                $mbox_stream = $this->open_mbox($folder_name);
3013                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
[271]3014                                        }
[5134]3015                                                       
3016                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3017                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
[63]3018                                }
[2]3019                        }
3020                }
[5134]3021               
3022                $message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
3023                $message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
3024               
3025                ////////////////////////////////////////////////////////////////////////////////////////////////////   
3026                /**
3027                * Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão.
3028                 */
3029                $default_max_size_rule = $db->get_default_max_size_rule();     
3030                if(!$default_max_size_rule)
3031                {
3032                        $default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */
3033                }
3034                else
3035                {
3036                        foreach($default_max_size_rule as $i=>$value)
3037                        {               
3038                                $default_max_size_rule = $value['config_value'];
3039                        }                               
3040                }
3041               
3042                $default_max_size_rule = $default_max_size_rule * 1024 * 1024;            /* Tamanho da regra padrão, em bytes */
3043                $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];   
3044               
3045               
3046                $ldap = new ldap_functions();
3047                $groups_user = $ldap->get_user_groups($id_user);
[37]3048
[5134]3049                $size_rule_by_group = array(); 
3050                foreach($groups_user as $k=>$value_)
3051                {       
3052                        $rule_in_group = $db->get_rule_by_user_in_groups($k);
3053                        if ($rule_in_group != "")
3054                                array_push($size_rule_by_group, $rule_in_group);
3055                }       
3056               
3057                $n_rule_groups = 0;
3058                $maior_valor_regra_grupo = 0;
3059                foreach($size_rule_by_group as $i=>$value)
3060                {
3061                        if(is_array($value[0]))
3062                        {
3063                                $n_rule_groups++;
3064                                if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
3065                                        $maior_valor_regra_grupo = $value[0]['email_max_recipient'];
3066                        }
3067                }
3068               
3069                if($default_max_size_rule)
3070                {
3071                        $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
3072
3073                        if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */
3074                        {
3075                                if($message_size_total > $default_max_size_rule)
3076                                        return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
3077                        }
3078
3079                        else
3080                        {
3081                                if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
3082                                {
3083                                        $regra_mais_permissiva = 0;
3084                                        foreach($size_rule as $i=>$value)
3085                                        {       
3086                                                if($regra_mais_permissiva < $value['email_max_recipient'])
3087                                                        $regra_mais_permissiva = $value['email_max_recipient'];
3088                                        }
3089                                        $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;                 
3090                                        if($message_size_total > $regra_mais_permissiva)
3091                                                return $this->functions->getLang("Message size greater than allowed (Rule By User)");
3092                                }
3093                                else /* Regra por grupo */
3094                                {               
3095                                        $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;                     
3096                                        if($message_size_total > $maior_valor_regra_grupo)
3097                                                return $this->functions->getLang("Message size greater than allowed (Rule By Group)"); 
3098                               
3099                               
3100                                }
3101                        }
3102                }
3103                /**
3104         * Fim da validação do tamanho da regra do tamanho de mensagem.
3105                 */
3106                 ////////////////////////////////////////////////////////////////////////////////////////////////////
3107               
3108               
3109               
3110               
3111               
3112                if($isHTML)
3113                        $mailService->setBodyHtml($body);
3114                else
3115                        $mailService->setBodyText($body);
3116
[614]3117                if($is_important)
[5134]3118                        $mailService->addHeaderField('Importance','High');
[614]3119
[5134]3120                if($return_receipt)
3121                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
[504]3122
[1472]3123
[5134]3124                if ($folder != 'null'){
3125                        $mbox_stream = $this->open_mbox($folder);
3126                        @imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
3127                }
3128
3129                $sent = $mailService->send();
3130
3131                if($sent !== true)
[2]3132                {
[5134]3133                        return $this->parse_error($sent);
[2]3134                }
3135                else
3136                {
[1035]3137            if ($signed && !$params['smime'])
3138                        {
3139                                return $sent;
3140                        }
[1472]3141                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]3142                        {
3143                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3144                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
3145                                $now = date("d/m/y H:i:s");
3146                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[1472]3147                                $sent = trim($sent);
[117]3148                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
3149                        }
[5134]3150                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]3151                                $contacts = new dynamic_contacts();
[485]3152                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
3153                                return array("success" => true, "new_contacts" => $new_contacts);
[413]3154                        }
[485]3155                        return array("success" => true);
[2]3156                }
3157        }
[4416]3158       
[4436]3159       
3160        /**
3161        * @license   http://www.gnu.org/copyleft/gpl.html GPL
3162        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
3163        * @param     $mail email
3164        * @param     $msg_uid uid da mensagem
3165        * @param     $forwarding_attachments anexos
3166        */
[5134]3167
3168        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
[4795]3169        {
[5134]3170                //Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
3171                $pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';
[4795]3172                $cid_imgs = '';
[5134]3173                preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
3174                //-------------------------------------------------------------------//
[2]3175
[5134]3176                $attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
[3018]3177
[5134]3178                foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
3179                        $desc = unserialize(rawurldecode($v));
3180                        $attPostions[$desc[3]] = $i;
3181                }
[3018]3182
[5134]3183                //Intera as imagens encontradas
3184                foreach($cid_imgs[6] as $j => $val)
3185        {               
3186                        $cid = base_convert(microtime().$j, 10, 36); //Gera um cid
[5158]3187                        $body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'"', $body ); //tira o src da imagem e coloca o cid.
[4416]3188                        $count    = strlen($cid_imgs[6][$j]);
3189                                       
[5134]3190                        $attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
[4416]3191                        $file_description = unserialize(rawurldecode($attach_img));
3192                       
3193                        if (is_array($file_description))
3194                                foreach($file_description as $i => $descriptor)                         
[5134]3195                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);
[4416]3196
3197                        // The image is not in the same mail?
3198                        if ($msg_uid != $cid_imgs[4][$j])
[4795]3199                        {
[5134]3200                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
3201                $fileContent = &$fa['binary'];
3202                                $fileName = $fa['name'];
3203                                $fileCode = $fa['encoding'];
3204                                $fileType =  $fa['type'];
[4795]3205                                $file_attached[0] = $cid_imgs[2][$j];
3206                                $file_attached[1] = $cid_imgs[4][$j];
3207                                $file_attached[2] = $fileName;
[5134]3208                                $file_attached[3] = '0.'.(string)($j+1);
[4795]3209                                $file_attached[4] = 'base64';
3210                                $file_attached[5] = strlen($fileContent); //Size of file
[4416]3211                                $file_attached[6] = $cid_imgs[6][$j];
[4795]3212                                $return_forward[] = $file_attached;
[4416]3213
3214                                if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
[5134]3215                                        unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
[4416]3216                               
[4795]3217                        }
3218                        else
3219                        {
3220                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
3221                                $fileName = $file_description[2];
3222                                $fileCode = $file_description[4];
[5134]3223                                $file_description[3] = '0.'.(string)($j+1);
[4416]3224                                $file_description[6] = $cid_imgs[6][$j];
[4795]3225                                $fileType = $this->get_file_type($file_description[2]);
[5134]3226                                unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
[4795]3227                                if (!empty($file_description))
3228                                {
3229                                        $file_description[5] = strlen($fileContent); //Size of file
3230                                        $return_forward[] = $file_description;
3231                                }
3232                        }
[4416]3233
[4795]3234                        if ($fileContent)
[5134]3235                                $mail->addStringImage($fileContent,$fileType,$fileName, $cid);                                 
[4416]3236                }
[4795]3237
3238                return $return_forward;
3239        }
[3018]3240        function add_recipients_cert($full_address)
[1035]3241        {
3242                $result = "";
3243                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
3244                foreach ($parse_address as $val)
3245                {
3246                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3247                        if ($val->mailbox == "INVALID_ADDRESS")
3248                                continue;
3249                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
3250                                continue;
3251                        if (empty($val->personal))
3252                                $result .= $val->mailbox."@".$val->host . ",";
3253                        else
3254                                $result .= $val->mailbox."@".$val->host . ",";
3255                }
3256
3257                return substr($result,0,-1);
3258        }
3259
[5243]3260        function add_recipients($recipient_type, $full_address, $mail, $mobile = false)
[2]3261        {
[3932]3262                //remove a comma if is given two unexpected commas
3263                $full_address = preg_replace("/, ?,/",",",$full_address);
[1472]3264                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
[5254]3265
[5255]3266                $bolean = true;         
3267                foreach ($parse_address as $val)
3268                {
3269                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
3270                        if ($val->mailbox == "INVALID_ADDRESS")
3271                                continue;
3272                        switch($recipient_type)
[5243]3273                        {
[5255]3274                                case "to":
3275                                        if($mobile){
3276                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
3277                                        }else{
3278                                                $mail->AddTo( ($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3279                                        }
3280                                        break;
3281                                case "cc":
3282                                        if($mobile){
3283                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
3284                                        }else{
3285                                                $mail->AddCC( ($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
[5243]3286                                        }
[5255]3287                                        break;
3288                                case "cco":
3289                                        $mail->AddBcc(($val->personal ? "\"$val->personal\" <$val->mailbox@$val->host>" : "$val->mailbox@$val->host"));
3290                                        break;
[2]3291                        }
[5255]3292                        if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){
3293                                $bolean = false;
[2]3294                        }
3295                }
[5134]3296                return $bolean;
[2]3297        }
[1472]3298
[2]3299        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
3300        {
[4416]3301            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
3302            $attachment = new attachment();
[5134]3303                        $attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo.
[4416]3304            $attachment->setStructureFromMail($msg_folder, $msg_number);
3305            return $attachment->getAttachment($msg_part);
[2]3306        }
[1472]3307
[5134]3308        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding)
3309        {
3310            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
3311            $attachment = new attachment();
3312            $attachment->setStructureFromMail($msg_folder, $msg_number);
3313            $return = $attachment->getAttachmentInfo($msg_part);
3314            $return['binary'] = $attachment->getAttachment($msg_part);
3315            return $return;
3316        }
3317
[2]3318        function del_last_caracter($string)
3319        {
3320                $string = substr($string,0,(strlen($string) - 1));
[1472]3321                return $string;
[2]3322        }
[1472]3323
[2]3324        function del_last_two_caracters($string)
3325        {
3326                $string = substr($string,0,(strlen($string) - 2));
[1472]3327                return $string;
[2]3328        }
[1472]3329
[828]3330        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
[659]3331        {
[1625]3332                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
[970]3333                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
3334                        foreach($imapsort as $iuid)
3335                                $sort[$iuid] = "";
[1518]3336                       
3337                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
3338                                $slice_array = false;
3339                        else
3340                                $slice_array = true;
[970]3341                }
3342                else
[659]3343                {
[970]3344                        $sort = array();
3345                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
3346                        $num_msgs = imap_num_msg($this->mbox);
3347                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
[975]3348                        $slice_array = true;
3349
[983]3350                        for ($i=$num_msgs; $i>0; $i--)
[828]3351                        {
[983]3352                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
3353                                        break;
[970]3354                                $iuid = @imap_uid($this->mbox,$i);
3355                                $header = $this->get_header($iuid);
3356                                // List UNSEEN messages.
3357                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
3358                                        continue;
3359                                }
3360                                // List SEEN messages.
3361                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
3362                                        continue;
3363                                }
3364                                // List ANSWERED messages.
3365                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
3366                                        continue;
3367                                }
3368                                // List FLAGGED messages.
3369                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
3370                                        continue;
3371                                }
3372
3373                                if($sort_box_type=='SORTFROM') {
3374                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
3375                                                $from = $header->to;
3376                                        else
3377                                                $from = $header->from;
[5134]3378                                        if(isset($from[0]->personal))
[970]3379                                        $tmp = imap_mime_header_decode($from[0]->personal);
[5134]3380                                        else
3381                                                $tmp = null;
3382                                        if (isset($tmp[0]->text))
[970]3383                                                $sort[$iuid] = $tmp[0]->text;
3384                                        else
3385                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
3386                                }
3387                                else if($sort_box_type=='SORTSUBJECT') {
3388                                        $sort[$iuid] = $header->subject;
3389                                }
3390                                else if($sort_box_type=='SORTSIZE') {
3391                                        $sort[$iuid] = $header->Size;
3392                                }
3393                                else {
3394                                        $sort[$iuid] = $header->udate;
3395                                }
3396
[659]3397                        }
[970]3398                        natcasesort($sort);
[828]3399
[970]3400                        if ($sort_box_reverse)
3401                                $sort = array_reverse($sort,true);
[659]3402                }
[5134]3403                if(empty($sort) or !is_array($sort)){
[972]3404                        $sort = array();
[5134]3405                }
3406               
3407                       
[1472]3408
[1808]3409
[972]3410                if ($slice_array)
[828]3411                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
[970]3412
[1472]3413
[828]3414                return $sort;
3415
[659]3416        }
[970]3417
[5172]3418        function move_delete_search_messages($params){
3419                $move = false;
3420                $msg_no_move = "";
3421       
3422                $params['selected_messages'] = urldecode($params['selected_messages_move']);
3423                $params['new_folder'] = urldecode($params['new_folder_move']);
3424                $params['new_folder_name'] = urldecode($params['new_folder_name_move']);
3425                $sel_msgs = explode(",", $params['selected_messages']);
3426                @reset($sel_msgs);
3427                $sorted_msgs = array();
3428                foreach($sel_msgs as $idx => $sel_msg) {
3429                        $sel_msg = explode(";", $sel_msg);
3430                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3431                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3432                         }
3433                         else {
3434                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3435                         }
3436                }               
3437                @ksort($sorted_msgs);
3438                $last_return = false;
3439                foreach($sorted_msgs as $folder => $msgs_number) {
3440                        $params['msgs_number'] = $msgs_number;
3441                        $params['folder'] = $folder;
3442                               
3443                        $last_return = $this->move_messages($params);
3444                       
3445                        if($last_return['status']){
3446                                $move = true;
3447                        }else{
3448                                $msg_no_move =  $params['msgs_number'];
3449                        }
3450                }
3451                $sel_msgs = null;               
3452                $params['selected_messages'] = urldecode($params['selected_messages_delete']);
3453                $params['new_folder'] = urldecode($params['new_folder_delete']);
3454                $params['new_folder_name'] = urldecode($params['new_folder_name_delete']);
3455                $sel_msgs = explode(",", $params['selected_messages']);
3456                @reset($sel_msgs);
3457                $sorted_msgs = array();
3458                foreach($sel_msgs as $idx => $sel_msg) {
3459                        $sel_msg = explode(";", $sel_msg);
3460                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3461                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3462                         }
3463                         else {
3464                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3465                         }
3466                }
3467                @ksort($sorted_msgs);
3468                $last_return = false;
3469                foreach($sorted_msgs as $folder => $msgs_number) {
3470                        $params['msgs_number'] = $msgs_number;
3471                        $params['folder'] = $folder;
3472               
3473                        $params['folder'] = $params['new_folder_delete'];
3474                        $last_return = $this->delete_msgs($params);
3475                        $last_return['deleted'] = true;
3476                        if($last_return['status']){
3477                                $move = true;
3478                        }else{
3479                                $msg_no_move =  $params['msgs_number'];
3480                        }
3481               
3482                }
3483       
3484                if($move)
3485                        $last_return['move'] = true;
3486                       
3487                if($msg_no_move != "")
3488                        $last_return['no_move'] = $msg_no_move;
3489               
3490                return $last_return;
3491        }
[970]3492
[1472]3493        function move_search_messages($params){
[5256]3494                $params['selected_messages'] = str_replace('/',$this->imap_delimiter,urldecode($params['selected_messages']));
3495                $params['new_folder'] = str_replace('/',$this->imap_delimiter,urldecode($params['new_folder']));
[163]3496                $params['new_folder_name'] = urldecode($params['new_folder_name']);
3497                $sel_msgs = explode(",", $params['selected_messages']);
[5172]3498                $move = false;
3499                $msg_no_move = "";
3500               
[1472]3501                @reset($sel_msgs);
[163]3502                $sorted_msgs = array();
3503                foreach($sel_msgs as $idx => $sel_msg) {
3504                        $sel_msg = explode(";", $sel_msg);
3505                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
3506                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[1472]3507                         }
[163]3508                         else {
3509                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3510                         }
3511                }
3512                @ksort($sorted_msgs);
[1472]3513                $last_return = false;
3514                foreach($sorted_msgs as $folder => $msgs_number) {
[163]3515                        $params['msgs_number'] = $msgs_number;
[1472]3516                        $params['folder'] = $folder;
[5172]3517                       
3518                if($params['delete'] === 'true'){
3519                        $params['folder'] = $params['new_folder'];
3520                        $last_return = $this->delete_msgs($params);
[163]3521                                $last_return['deleted'] = true;
[5172]3522                       
3523                        if($last_return['status']){
3524                                $move = true;
3525                        }else{
3526                                $msg_no_move =  $params['msgs_number'];
[163]3527                        }
[5172]3528                       
3529                }else{
3530                                $last_return = $this->move_messages($params);
3531                               
3532                                if($last_return['status']){
3533                                        $move = true;
3534                                }else{
3535                                        $msg_no_move =  $params['msgs_number'];
3536                        }
[163]3537                }
[5172]3538                }
3539               
3540                if($move)
3541                        $last_return['move'] = true;
3542                       
3543                if($msg_no_move != "")
3544                        $last_return['no_move'] = $msg_no_move;
3545                       
[163]3546                return $last_return;
3547        }
[1472]3548
[2]3549        function move_messages($params)
3550        {
[1472]3551                $folder = $params['folder'];
3552                $mbox_stream = $this->open_mbox($folder);
[5134]3553                $newmailbox = ($params['new_folder']);
[5212]3554                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO-8859-1, UTF-8, UTF7-IMAP");
[5134]3555                $new_folder_name = $params['new_folder_name'];
[4997]3556                $msgs_number = $params['msgs_number'];
[2]3557                $return = array('msgs_number' => $msgs_number,
3558                                                'folder' => $folder,
3559                                                'new_folder_name' => $new_folder_name,
[325]3560                                                'border_ID' => $params['border_ID'],
3561                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[1472]3562
[325]3563                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
3564        if (substr($folder,0,4) == 'user'){
3565                $acl = $this->getacltouser($folder);
3566                /*
3567                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
3568                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
3569                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
3570                 *   w - write (STORE flags other than SEEN and DELETED)
3571                 *   i - insert (perform APPEND, COPY into mailbox)
3572                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
3573                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
3574                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
3575                 *   a - administer (perform SETACL)
3576                        */
3577                        if (strpos($acl, "d") === false){
3578                                $return['status'] = false;
3579                                return $return;
3580                        }
3581        }
[432]3582        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[5134]3583        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){
[1747]3584        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
3585            if (substr($new_folder_name,0,4) == 'user'){
3586                $this->ldap = new ldap_functions();
3587                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
3588                $return['new_folder_name'] = array_pop($tmp_folder_name);
3589                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
3590                {
3591                    $return['new_folder_name'] = $cn;
3592                }
3593            }
[432]3594        }
[5134]3595                }
[1472]3596
3597                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
[51]3598                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]3599                {
[2]3600                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]3601                        // Fix problem in unserialize function JS.
[5134]3602                        if(array_key_exists('body', $return['previous_msg']))
[449]3603                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
3604                }
[1472]3605
3606                $mbox_stream = $this->open_mbox($folder);
[2]3607                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3608                        imap_expunge($mbox_stream);
[51]3609                        if($mbox_stream)
3610                                imap_close($mbox_stream);
[2]3611                        return $return;
3612                }else {
[1472]3613                        if(strstr(imap_last_error(),'Over quota')) {
[2]3614                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[1472]3615                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
3616                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
[2]3617                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]3618                                $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]3619                                if(!$mbox)
3620                                        return imap_last_error();
[1472]3621                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
[2]3622                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]3623                                        if($mbox_stream)
3624                                                imap_close($mbox_stream);
[1472]3625                                        if($mbox)
[51]3626                                                imap_close($mbox);
[1472]3627                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
[2]3628                                }
3629                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
3630                                        imap_expunge($mbox_stream);
[51]3631                                        if($mbox_stream)
3632                                                imap_close($mbox_stream);
[2]3633                                        // return to original quota limit.
3634                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]3635                                                if($mbox)
3636                                                        imap_close($mbox);
[1472]3637                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]3638                                        }
[1472]3639                                        return $return;
[2]3640                                }
3641                                else {
[51]3642                                        if($mbox_stream)
3643                                                imap_close($mbox_stream);
[2]3644                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]3645                                                if($mbox)
3646                                                        imap_close($mbox);
[1472]3647                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
[2]3648                                        }
[1472]3649                                        return imap_last_error();
[2]3650                                }
[1472]3651
[2]3652                        }
3653                        else {
[51]3654                                if($mbox_stream)
3655                                        imap_close($mbox_stream);
3656                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]3657                        }
[1472]3658                }
[2]3659        }
[1472]3660
[5134]3661
[2]3662        function save_msg($params)
3663        {
[5206]3664       
[5134]3665                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
3666                $mailService = ServiceLocator::getService('mail');
[1472]3667
[4795]3668                $return_receipt = $params['input_return_receipt'];
3669                $is_important = $params['input_important_message'];
[5134]3670               
[4795]3671                $msg_uid = $params['msg_id'];
3672                $body = $params['body'];
[4416]3673                $body = str_replace("%nbsp;","&nbsp;",$body);
[155]3674                $body = preg_replace("/\n/"," ",$body);
[5134]3675                $body = preg_replace("/\r/","" ,$body);
[5177]3676                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
[271]3677                $forwarding_attachments = $params['forwarding_attachments'];
[5134]3678                $message_attachments    = $params['message_attachments'];
[4795]3679                $attachments = $params['FILES'];
[271]3680                $return_files = $params['FILES'];
[5134]3681                $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
[1472]3682
[4800]3683                if(is_array($params['local_attachments'])){
3684                    foreach ($params['local_attachments'] as $key => $local_attach) {
3685                       $tmp = unserialize(urldecode($local_attach));
[5134]3686                           $attachments[$key]['name'] = urldecode($tmp[2]);
3687                           $return_files[$key]['name'] = urldecode($tmp[2]);
[4800]3688                    }
3689                }
3690
[5206]3691                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
[5134]3692                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
[4800]3693
[5134]3694                $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
3695                $mailService->addTo($params['input_to']);
3696                $mailService->addCc( $params['input_cc']);
3697                $mailService->addBcc($params['input_cco']);
3698                $mailService->setSubject($params['input_subject']);
[4795]3699
[5134]3700                if($is_important){
3701                        $mailService->addHeaderField('Importance','High');
3702                }
[4795]3703
[5134]3704                if($return_receipt)
3705                        $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
[4795]3706
[5134]3707                $isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
[4795]3708
3709               
[5134]3710                if( count($forwarding_attachments) > 0 )
3711                        $return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
3712                       
3713                //Build Message Attachments!!!
3714                if(count($message_attachments) > 0 )
3715                {
3716                        foreach($message_attachments as $folder_name => $messages)
3717                        {
3718                                foreach ($messages as $message_number => $message_subject)
3719                                {
3720                                        if (!$message_subject)
3721                                                $message_subject  = 'no title.eml';
3722                                        else
3723                                                $message_subject .= '.eml';
3724                                       
3725                                        if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
3726                                                $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
3727                                        else{
3728                                                $mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
3729                                                $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
3730                                        }
3731                                                                                       
3732                                        $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
3733                                        $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
3734                                }
3735                        }
3736                }
3737               
[4416]3738                $imagesParts = array();
[4795]3739
[5134]3740                if(count($return_forward) > 0 )
[4416]3741                foreach ($return_forward as $value)
3742                        $imagesParts[$value[6]] = $value[3];   
[1472]3743
[5134]3744                //Build Forwarding Attachments!!!
3745                if(count($forwarding_attachments) > 0 )
3746                {
[4795]3747                        foreach($forwarding_attachments as $forwarding_attachment)
3748                        {
[5177]3749
[4795]3750                                $file_description = unserialize(rawurldecode($forwarding_attachment));
[5177]3751                                foreach($file_description as $i => $item)
3752                                        $file_description[$i] = urldecode($item);                               
3753                       
3754                                $file_description = array_values($file_description);
[4457]3755                                       
[5134]3756                                foreach($file_description as $i => $descriptor)
[4457]3757                                                        $file_description[$i] = eregi_replace('\'*\'','',$descriptor);
[5134]3758                               
[4795]3759                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
[5134]3760                                $file_description[2] = html_entity_decode($file_description[2]);
[4795]3761
3762                                $file_description[5] = strlen($fileContent); //Size of file
3763                                $return_forward[] = $file_description;
[5134]3764                                $mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
[4795]3765                        }
[5134]3766                        }
[4795]3767
[271]3768                if ((count($return_forward) > 0) && (count($return_files) > 0))
3769                        $return_files = array_merge_recursive($return_forward,$return_files);
[4416]3770                else if (count($return_files) < 1)
[4795]3771                                $return_files = $return_forward;
[1472]3772
[5134]3773                //Build Uploading Attachments!!!
[5206]3774                $sizeof_attachments = count($attachments);     
[1005]3775                if ($sizeof_attachments)
[4416]3776                        foreach ($attachments as $numb => $attach)
[5134]3777                                $mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
[4416]3778
[4795]3779
[5134]3780                if (!$body)
3781                        $body = ' ';
3782               
3783                if($isHTML)
3784                        $mailService->setBodyHtml($body);
3785                else
3786                        $mailService->setBodyText($body);
[271]3787
[828]3788
[4795]3789                $mbox_stream = $this->open_mbox($folder);
[5134]3790                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
3791
[4795]3792                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
[271]3793                $return['msg_no'] = $status->uidnext - 1;
3794                $return['folder_id'] = $folder;
[4416]3795                $return['imagesParts'] = $imagesParts;
[828]3796
[51]3797                if($mbox_stream)
3798                        imap_close($mbox_stream);
[4416]3799                       
[5134]3800                $returnFiles = array();                 
3801                $ii = 0;
3802                               
3803                if(count($return_files) > 0)
[4416]3804                {
3805                        foreach ($return_files as $index => $_attachment)
[271]3806                        {
[4416]3807                                if (array_key_exists("name", $_attachment))
3808                                {
[5206]3809                                        $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment['name'], 'UTF-8', 'UTF-8, ISO-8859-1') );
[5134]3810                                        $returnFiles[$ii]['size'] = $_attachment['size'];
3811                                        $ii++;
[271]3812                        }
[5134]3813                                else if($_attachment[2])
[4795]3814                        {
[5206]3815                                        $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment[2], 'UTF-8', 'UTF-8, ISO-8859-1'));
[5134]3816                                        $returnFiles[$ii]['size'] = $_attachment[5];         
3817                                        $ii++;
[4795]3818                        }
[271]3819                }
[4795]3820                }
[5134]3821                $return['files'] = serialize($returnFiles);
3822                $return["subject"] = $params['input_subject'];
3823                if (!$return['append']) $return['append'] = imap_last_error();
[5207]3824                       
[2]3825                return $return;
3826        }
[1472]3827
[5264]3828       
3829        function set_messages_flag_from_search($params){               
3830                $error = False;
3831                $fileNames = "";
3832               
3833                $sel_msgs = explode(",", $params['msg_to_flag']);
3834                @reset($sel_msgs);
3835                $sorted_msgs = array();
3836                foreach($sel_msgs as $idx => $sel_msg) {
3837                        $sel_msg = explode(";", $sel_msg);
3838                        if(array_key_exists($sel_msg[0], $sorted_msgs)){
3839                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
3840                        }
3841                        else {
3842                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
3843                        }
3844                }
3845                unset($sorted_msgs['']);                       
3846                $array_names_keys = array_keys($sorted_msgs);   
3847                // Verifica se as n mensagens selecionadas
3848                // se encontram em um mesmo folder
3849                if (count($sorted_msgs)==1){
3850                        $param['folder'] = $array_names_keys[0];
3851                        $param['msgs_to_set'] = $sorted_msgs[$array_names_keys[0]];
3852                        $param['flag'] = $params['flag'];
3853                        $returns[0] = $this->set_messages_flag($param);
3854                        return $returns;
3855                }else{
3856                        for($i = 0; $i < count($array_names_keys); $i++){
3857                                $param['folder'] = $array_names_keys[$i];
3858                                $param['msgs_to_set'] = $sorted_msgs[$array_names_keys[$i]];
3859                                $param['flag'] = $params['flag'];
3860                                $returns[$i] = $this->set_messages_flag($param);
3861                }
3862        }
3863        return $returns;
3864}
[2]3865        function set_messages_flag($params)
[5264]3866        {               
3867                $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
[5134]3868                $msgs_to_set = $params['msgs_to_set'];
[2]3869                $flag = $params['flag'];
3870                $return = array();
[5134]3871                $return["msgs_to_set"] = $msgs_to_set;
[2]3872                $return["flag"] = $flag;
[5182]3873                $return["msgs_not_to_set"] = "";
3874                       
[5264]3875                $this->mbox = $this->open_mbox($folder);
[5223]3876                       
[5182]3877                if ($flag == "unseen"){
3878                        $return["msgs_to_set"] = "";
3879                        $msgs = explode(",",$msgs_to_set);
3880                        foreach($msgs as $men){
3881                                if (imap_clearflag_full($this->mbox, $men, "\\Seen", ST_UID))
3882                                        $return["msgs_to_set"] .= $men.",";
3883                                else
3884                                        $return["msgs_not_to_set"] .= $men.",";
3885                        }
3886                        $return["status"] = true;
3887                }elseif ($flag == "seen"){
3888                        $return["msgs_to_set"] = "";
3889                        $msgs = explode(",",$msgs_to_set);
3890                        foreach($msgs as $men){
3891                                if (imap_setflag_full($this->mbox, $men, "\\Seen", ST_UID))
3892                                        $return["msgs_to_set"] .= $men.",";
3893                                else
3894                                        $return["msgs_not_to_set"] .= $men.",";
3895                        }
3896                        $return["status"] = true;
3897                }elseif ($flag == "answered"){
[51]3898                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
3899                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]3900                }
3901                elseif ($flag == "forwarded")
[51]3902                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]3903                elseif ($flag == "flagged")
[51]3904                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[614]3905                elseif ($flag == "unflagged") {
3906                        $flag_importance = false;
3907                        $msgs_number = explode(",",$msgs_to_set);
[659]3908                        $unflagged_msgs = "";
[614]3909                        foreach($msgs_number as $msg_number) {
3910                                preg_match('/importance *: *(.*)\r/i',
3911                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]3912                                        ,$importance);
[673]3913                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]3914                                        $flag_importance=true;
3915                                }
[659]3916                                else {
3917                                        $unflagged_msgs.=$msg_number.",";
[1472]3918                                }
[614]3919                        }
3920
[659]3921                        if($unflagged_msgs!="") {
3922                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
3923                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
3924                        }
3925                        else {
3926                                $return["msgs_unflageds"] = false;
3927                        }
3928
[673]3929                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
[614]3930                                $return["status"] = false;
3931                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
3932                        }
[659]3933                        else {
3934                                $return["status"] = true;
3935                        }
[614]3936                }
[5182]3937               
3938                if(($flag == "seen") || ($flag == "unseen")){
3939                        if ($return["msgs_not_to_set"] != ""){
3940                                $return["msgs_not_to_set"] = substr($return["msgs_not_to_set"], 0, -1);
[5223]3941                                $return["status"] = false;
[5182]3942                        }
3943                        if($return["msgs_to_set"] != ""){
3944                                $return["msgs_to_set"] = substr($return["msgs_to_set"], 0, -1);
3945                        }
3946                }
[411]3947                if($this->mbox && is_resource($this->mbox))
[5223]3948                        imap_close($this->mbox);               
[2]3949                return $return;
3950        }
[1472]3951
[2]3952        function get_file_type($file_name)
3953        {
3954                $file_name = strtolower($file_name);
3955                $strFileType = strrev(substr(strrev($file_name),0,4));
[5134]3956                if ($strFileType == ".eml")
3957                        return "message/rfc822";
[1472]3958                if ($strFileType == ".asf")
[2]3959                        return "video/x-ms-asf";
3960                if ($strFileType == ".avi")
3961                        return "video/avi";
3962                if ($strFileType == ".doc")
3963                        return "application/msword";
3964                if ($strFileType == ".zip")
3965                        return "application/zip";
3966                if ($strFileType == ".xls")
3967                        return "application/vnd.ms-excel";
3968                if ($strFileType == ".gif")
3969                        return "image/gif";
3970                if ($strFileType == ".jpg" || $strFileType == "jpeg")
3971                        return "image/jpeg";
3972                if ($strFileType == ".png")
3973                        return "image/png";
3974                if ($strFileType == ".wav")
3975                        return "audio/wav";
3976                if ($strFileType == ".mp3")
3977                        return "audio/mpeg3";
3978                if ($strFileType == ".mpg" || $strFileType == "mpeg")
3979                        return "video/mpeg";
3980                if ($strFileType == ".rtf")
3981                        return "application/rtf";
3982                if ($strFileType == ".htm" || $strFileType == "html")
3983                        return "text/html";
[1472]3984                if ($strFileType == ".xml")
[2]3985                        return "text/xml";
[1472]3986                if ($strFileType == ".xsl")
[2]3987                        return "text/xsl";
[1472]3988                if ($strFileType == ".css")
[2]3989                        return "text/css";
[1472]3990                if ($strFileType == ".php")
[2]3991                        return "text/php";
[1472]3992                if ($strFileType == ".asp")
[2]3993                        return "text/asp";
3994                if ($strFileType == ".pdf")
3995                        return "application/pdf";
3996                if ($strFileType == ".txt")
3997                        return "text/plain";
3998                if ($strFileType == ".wmv")
3999                        return "video/x-ms-wmv";
4000                if ($strFileType == ".sxc")
4001                        return "application/vnd.sun.xml.calc";
4002                if ($strFileType == ".stc")
4003                        return "application/vnd.sun.xml.calc.template";
4004                if ($strFileType == ".sxd")
4005                        return "application/vnd.sun.xml.draw";
4006                if ($strFileType == ".std")
4007                        return "application/vnd.sun.xml.draw.template";
4008                if ($strFileType == ".sxi")
4009                        return "application/vnd.sun.xml.impress";
4010                if ($strFileType == ".sti")
4011                        return "application/vnd.sun.xml.impress.template";
4012                if ($strFileType == ".sxm")
4013                        return "application/vnd.sun.xml.math";
4014                if ($strFileType == ".sxw")
4015                        return "application/vnd.sun.xml.writer";
4016                if ($strFileType == ".sxq")
4017                        return "application/vnd.sun.xml.writer.global";
4018                if ($strFileType == ".stw")
4019                        return "application/vnd.sun.xml.writer.template";
[1472]4020
4021
4022                return "application/octet-stream";
[2]4023        }
[1472]4024
[2]4025        function htmlspecialchars_encode($str)
4026        {
[449]4027                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]4028        }
4029        function htmlspecialchars_decode($str)
4030        {
[449]4031                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]4032        }
[1472]4033
[828]4034        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
4035        {
4036                if(!$this->mbox || !is_resource($this->mbox))
[51]4037                        $this->mbox = $this->open_mbox($folder);
[432]4038
[828]4039                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
4040        }
[1472]4041
[53]4042        function get_info_next_msg($params)
4043        {
4044                $msg_number = $params['msg_number'];
4045                $folder = $params['msg_folder'];
4046                $sort_box_type = $params['sort_box_type'];
4047                $sort_box_reverse = $params['sort_box_reverse'];
4048                $reuse_border = $params['reuse_border'];
4049                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[1472]4050                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
4051
[320]4052                $success = false;
4053                if (is_array($sort_array_msg))
[2]4054                {
[320]4055                        foreach ($sort_array_msg as $i => $value){
4056                                if ($value == $msg_number)
4057                                {
4058                                        $success = true;
4059                                        break;
4060                                }
4061                        }
[2]4062                }
4063
[320]4064                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]4065                {
4066                        $params['status'] = 'false';
4067                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4068                        return $params;
4069                }
[1472]4070
[2]4071                $params = array();
4072                $params['msg_number'] = $sort_array_msg[($i+1)];
4073                $params['msg_folder'] = $folder;
[1472]4074
4075                $return = $this->get_info_msg($params);
[2]4076                $return["reuse_border"] = $reuse_border;
4077                return $return;
4078        }
4079
4080        function get_info_previous_msg($params)
4081        {
4082                $msg_number = $params['msgs_number'];
4083                $folder = $params['folder'];
4084                $sort_box_type = $params['sort_box_type'];
4085                $sort_box_reverse = $params['sort_box_reverse'];
4086                $reuse_border = $params['reuse_border'];
[53]4087                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
4088                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[1472]4089
[320]4090                $success = false;
4091                if (is_array($sort_array_msg))
[2]4092                {
[320]4093                        foreach ($sort_array_msg as $i => $value){
4094                                if ($value == $msg_number)
4095                                {
4096                                        $success = true;
4097                                        break;
4098                                }
4099                        }
[2]4100                }
[320]4101                if (! $success || $i == 0)
4102                {
[2]4103                        $params['status'] = 'false';
4104                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
4105                        return $params;
4106                }
[1472]4107
[2]4108                $params = array();
4109                $params['msg_number'] = $sort_array_msg[($i-1)];
4110                $params['msg_folder'] = $folder;
[1472]4111
[2]4112                $return = $this->get_info_msg($params);
4113                $return["reuse_border"] = $reuse_border;
4114                return $return;
4115        }
[1472]4116
[2]4117        // This function updates the values: quota, paging and new messages menu.
4118        function get_menu_values($params){
4119                $return_array = array();
4120                $return_array = $this->get_quota($params);
[1472]4121
[2]4122                $mbox_stream = $this->open_mbox($params['folder']);
[1472]4123                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
[51]4124                if($mbox_stream)
4125                        imap_close($mbox_stream);
[1472]4126
4127                return $return_array;
[2]4128        }
[1472]4129
[325]4130        function get_quota($params){
[449]4131                // folder_id = user/{uid} for shared folders
4132                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
4133                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
[1472]4134                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
[449]4135                }
4136                // folder_id = INBOX for inbox folders
4137                else
4138                        $folder_id = "INBOX";
[1472]4139
[1035]4140                if(!$this->mbox || !is_resource($this->mbox))
[51]4141                        $this->mbox = $this->open_mbox();
[345]4142
[325]4143                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]4144                if($this->mbox && is_resource($this->mbox))
[51]4145                        imap_close($this->mbox);
[1472]4146
[2]4147                if (!$quota){
4148                        return array(
4149                                'quota_percent' => 0,
4150                                'quota_used' => 0,
4151                                'quota_limit' =>  0
4152                        );
4153                }
[1472]4154
[2]4155                if(count($quota) && $quota['limit']) {
[3064]4156                        $quota_limit = $quota['limit'];
4157                        $quota_used  = $quota['usage'];
[2]4158                        if($quota_used >= $quota_limit)
[650]4159                        {
4160                                $quotaPercent = 100;
4161                        }
4162                        else
4163                        {
[2]4164                        $quotaPercent = ($quota_used / $quota_limit)*100;
4165                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
[650]4166                        }
[2]4167                        return array(
4168                                'quota_percent' => floor($quotaPercent),
[3064]4169                                'quota_used' => $quota_used,
4170                                'quota_limit' =>  $quota_limit
[2]4171                        );
4172                }
[1472]4173                else
[2]4174                        return array();
4175        }
[1472]4176
[2]4177        function send_notification($params){
[3231]4178                include("../header.inc.php");
[2]4179                require_once("class.phpmailer.php");
4180                $mail = new PHPMailer();
[1472]4181
[2]4182                $toaddress = $params['notificationto'];
[1472]4183
[3231]4184                $subject = lang("Read receipt: %1",$params['subject']);
4185                $body = lang("Your message: %1",$params['subject']) . '<br>';
[4739]4186                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
[3231]4187                $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]4188                $mail->SMTPDebug = false;
4189                $mail->IsSMTP();
4190                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
4191                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
4192                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4193                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
4194                $mail->AddAddress($toaddress);
4195                $mail->Subject = $this->htmlspecialchars_decode($subject);
4196
4197                $mail->IsHTML(true);
4198                $mail->Body = $body;
[1472]4199
[2]4200                if(!$mail->Send()){
4201                        return $mail->ErrorInfo;
4202                }
4203                else
4204                        return true;
4205        }
[1472]4206
[1965]4207        function empty_folder($params)
[2]4208        {
[1965]4209                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
[2]4210                $mbox_stream = $this->open_mbox($folder);
4211                $return = imap_delete($mbox_stream,'1:*');
[51]4212                if($mbox_stream)
4213                        imap_close($mbox_stream, CL_EXPUNGE);
[2]4214                return $return;
4215        }
[1472]4216
[2]4217        function search($params)
4218        {
[673]4219                include("class.imap_attachment.inc.php");
[1472]4220                $imap_attachment = new imap_attachment();
[2]4221                $criteria = $params['criteria'];
4222                $return = array();
4223                $folders = $this->get_folders_list();
[1472]4224
[2]4225                $j = 0;
4226                foreach($folders as $folder)
4227                {
4228                        $mbox_stream = $this->open_mbox($folder);
4229                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[1472]4230
[2]4231                        if ($messages == '')
4232                                continue;
[1472]4233
[2]4234                        $i = 0;
4235                        $return[$j] = array();
4236                        $return[$j]['folder_name'] = $folder['name'];
[1472]4237
[2]4238                        foreach($messages as $msg_number)
4239                        {
[535]4240                                $header = $this->get_header($msg_number);
[2]4241                                if (!is_object($header))
4242                                        return false;
[1472]4243
[2]4244                                $return[$j][$i]['msg_folder']   = $folder['name'];
4245                                $return[$j][$i]['msg_number']   = $msg_number;
4246                                $return[$j][$i]['Recent']               = $header->Recent;
4247                                $return[$j][$i]['Unseen']               = $header->Unseen;
4248                                $return[$j][$i]['Answered']     = $header->Answered;
4249                                $return[$j][$i]['Deleted']              = $header->Deleted;
4250                                $return[$j][$i]['Draft']                = $header->Draft;
4251                                $return[$j][$i]['Flagged']              = $header->Flagged;
[1472]4252
[535]4253                                $date_msg = gmdate("d/m/Y",$header->udate);
4254                                if (gmdate("d/m/Y") == $date_msg)
4255                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]4256                                else
4257                                        $return[$j][$i]['udate'] = $date_msg;
[1472]4258
[2]4259                                $fromaddress = imap_mime_header_decode($header->fromaddress);
4260                                $return[$j][$i]['fromaddress'] = '';
4261                                foreach ($fromaddress as $tmp)
4262                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[1472]4263
[2]4264                                $from = $header->from;
4265                                $return[$j][$i]['from'] = array();
4266                                $tmp = imap_mime_header_decode($from[0]->personal);
4267                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
4268                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[1472]4269                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]4270
4271                                $to = $header->to;
4272                                $return[$j][$i]['to'] = array();
4273                                $tmp = imap_mime_header_decode($to[0]->personal);
4274                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
4275                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[1472]4276                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]4277
4278                                $subject = imap_mime_header_decode($header->fetchsubject);
4279                                $return[$j][$i]['subject'] = '';
4280                                foreach ($subject as $tmp)
4281                                        $return[$j][$i]['subject'] .= $tmp->text;
4282
4283                                $return[$j][$i]['Size'] = $header->Size;
4284                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[1472]4285
[2]4286                                $return[$j][$i]['attachment'] = array();
4287                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[1472]4288
[2]4289                                $i++;
4290                        }
4291                        $j++;
[51]4292                        if($mbox_stream)
4293                                imap_close($mbox_stream);
[2]4294                }
[1472]4295
[2]4296                return $return;
4297        }
[3923]4298
4299
[1709]4300        function mobile_search($params)
4301        {
4302                include("class.imap_attachment.inc.php");
4303                $imap_attachment = new imap_attachment();
4304                $criterias = array ("TO","SUBJECT","FROM","CC");
4305                $return = array();
[3589]4306                if(!isset($params['folder'])) {
4307                        $folder_params = array("noSharedFolders"=>1);
4308                        if(isset($params['folderType']))
4309                                $folder_params['folderType'] = $params['folderType'];
4310                        $folders = $this->get_folders_list($folder_params);
4311                }
4312                else
4313                        $folders = array(0=>array('folder_id'=>$params['folder']));
[1709]4314                $num_msgs = 0;
[3923]4315                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
4316                $return["msgs"] = array();
4317               
4318                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
[1709]4319                foreach($folders as $id =>$folder)
4320                {
4321                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
4322                                foreach($criterias as $criteria_fixed)
[3923]4323                                {
4324                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
4325
[3573]4326                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
[3923]4327
4328                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
[1709]4329                                       
4330                                        if ($messages == ''){
4331                                                if($mbox_stream)
4332                                                        imap_close($mbox_stream);
4333                                                continue;       
4334                                        }
[3923]4335                                       
[1709]4336                                        foreach($messages as $msg_number)
[3923]4337                                        {
[1709]4338                                                $temp = $this->get_info_head_msg($msg_number);
4339                                                if(!$temp)
4340                                                        return false;
[3573]4341                                                $temp['msg_folder'] = $folder['folder_id'];
[3923]4342                                                $return["msgs"][$num_msgs] = $temp;
[1709]4343                                                $num_msgs++;
4344                                        }
[3923]4345
[1709]4346                                        if($mbox_stream)
4347                                                imap_close($mbox_stream);
4348                                }
[3923]4349                        }
[1709]4350                }
[3923]4351
4352                if(!function_exists("cmp_date")) {
4353                        function cmp_date($obj1, $obj2){
4354                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
4355                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
4356                        }
4357                }
4358                usort($return["msgs"], "cmp_date");
4359                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
4360                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
[4560]4361                $return["msgs"]['num_msgs'] = $num_msgs;
[3923]4362               
[1709]4363                return $return;
4364        }
[1472]4365
[2]4366        function delete_and_show_previous_message($params)
4367        {
4368                $return = $this->get_info_previous_msg($params);
[1472]4369
[2]4370                $params_tmp1 = array();
4371                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
4372                $params_tmp1['folder'] = $params['msg_folder'];
4373                $return_tmp1 = $this->delete_msg($params_tmp1);
[1472]4374
[2]4375                $return['msg_number_deleted'] = $return_tmp1;
[1472]4376
[2]4377                return $return;
4378        }
[1472]4379
4380
[2]4381        function automatic_trash_cleanness($params)
4382        {
4383                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
4384                $criteria =  'BEFORE "'.$before_date.'"';
[5302]4385                //$mbox_stream = $this->open_mbox('INBOX'.$this->folders['trash']);
4386                $mbox_stream = $this->open_mbox($this->mount_url_folder(array("INBOX",$this->folders['trash'])));
4387               
[3018]4388                // Free others requests
4389                session_write_close();
[2]4390                $messages = imap_search($mbox_stream, $criteria, SE_UID);
4391                if (is_array($messages)){
4392                        foreach ($messages as $msg_number){
4393                                imap_delete($mbox_stream, $msg_number, FT_UID);
4394                        }
4395                }
[51]4396                if($mbox_stream)
4397                        imap_close($mbox_stream, CL_EXPUNGE);
[2]4398                return $messages;
4399        }
4400//      Fix the search problem with special characters!!!!
4401        function remove_accents($string) {
[1472]4402                return strtr($string,
4403                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]4404                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
4405        }
4406
[4795]4407        function make_search_date($date,$before = false){
4408
[1622]4409            //TODO: Adaptar a data de acordo com o locale do sistema.
4410            list($day,$month,$year) = explode("/", $date);
[4795]4411            $before?$day=(int)$day+1:$day=(int)$day;
4412            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
4413            $search_date = date('d-M-Y',$timestamp);
[1622]4414            return $search_date;
4415
[4795]4416        }
[1622]4417
[3843]4418        function search_msg( $params = false )
4419        {
4420                $mbox_stream = "";
4421               
4422                if(strpos($params['condition'],"#")===false)
4423                { //local messages
4424                        $search=false;
4425                }
4426                else
4427                {
4428                        $search = explode(",",$params['condition']);
4429                }
4430               
4431                $params['page'] = $params['page'] * 1;
[689]4432
[3843]4433            if( is_array($search) )
4434            {
4435                        $search = array_unique($search); // Remove duplicated folders
4436                        $search_criteria = '';
4437                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
4438                        foreach($search as $tmp)
4439                        {
4440                                $tmp1 = explode("##",$tmp);
4441                                $sum = 0;
4442                                $name_box = $tmp1[0];
4443                                unset($filter);
4444                                foreach($tmp1 as $index => $criteria)
4445                                {
4446                                        if ($index != 0 && strlen($criteria) != 0)
4447                                        {
4448                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
4449                                                $filter .= " ".$filter_array[0];
4450                                                if (strlen($filter_array[1]) != 0)
4451                                                {
4452                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
4453                                                                 trim($filter_array[0]) != 'SINCE' &&
4454                                                                 trim($filter_array[0]) != 'ON')
4455                                                        {
4456                                                            $filter .= '"'.$filter_array[1].'"';
[5134]4457                                                        }else if(trim($filter_array[0]) == 'BEFORE' ){
[4795]4458                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
4459                                                        }else{
4460                                                            $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
4461                                                        }
[3843]4462                                                }
4463                                        }
4464                                }
4465                               
[5134]4466                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
[3843]4467                                $filter = $this->remove_accents($filter);
[1472]4468
[3843]4469                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
4470                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
4471                                {
4472                                        $folder_name = explode($this->imap_delimiter,$name_box);
4473                                        $this->ldap = new ldap_functions();
4474                                       
4475                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
4476                                        {
4477                                                $folder_name[1] = $cn;
4478                                        }
4479                                        $folder_name = implode($this->imap_delimiter,$folder_name);
[3391]4480                                }
[3843]4481                                else
[5134]4482                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
[3843]4483                               
4484                                if(!is_resource($mbox_stream))
4485                                        $mbox_stream = $this->open_mbox($name_box);
4486                                else
4487                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
4488                               
4489                                if (preg_match("/^.?\bALL\b/", $filter))
4490                                {
4491                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
4492                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
4493                                           
4494                                        foreach($all_criterias as $criteria_fixed)
4495                                        {
4496                                                $_filter = $criteria_fixed . substr($filter,4);
4497                                               
4498                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
4499                                               
4500                                                if(is_array($search_criteria))
4501                                                {
4502                                                        foreach($search_criteria as $new_search)
4503                                                        {
4504                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
[5134]4505                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
[4795]4506                                                                $elem['uid'] = $new_search;
4507                                                                /* compare dates in ordering */
4508                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
[3843]4509                                                                $retorno[] = $elem;
4510                                                        }
4511                                                }
4512                                        }
4513                                }
[4068]4514                                else{
[5134]4515                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
[4941]4516                                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
4517                                    {
4518                                        if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
4519                                        {
4520                                            $num_msgs = imap_num_msg($mbox_stream);
4521                                            $flagged_msgs = array();
4522                                            for ($i=$num_msgs; $i>0; $i--)
[4068]4523                                            {
[4941]4524                                                $iuid = @imap_uid($this->mbox,$i);
4525                                                $header = $this->get_header($iuid);
4526                                                if(trim($header->Flagged))
4527                                                {
4528                                                        $flagged_msgs[$i] = $iuid;
4529                                                }
[4068]4530                                            }
[5134]4531                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
[4941]4532                                            {
[5134]4533                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
4534                                                    foreach($arry_diff as $msg)
[4941]4535                                            {
[5134]4536                                                        $search_criteria[] = $msg;
[4941]4537                                            }
4538                                        }
[5134]4539                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
[4941]4540                                        {
[5134]4541                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
[4941]4542                                        }
4543                                    }
4544                                    }
4545
4546                                    if( is_array( $search_criteria) )
4547                                    {
4548                                        foreach($search_criteria as $new_search)
4549                                        {
4550                                            $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
[5134]4551                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
[4941]4552                                            $elem['uid'] = $new_search;
4553                                            /* compare dates in ordering */
4554                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
4555                                            $retorno[] = $elem;
4556                                        }
4557                                    }
[3843]4558                                }
4559                        }
4560                }
4561               
4562                if($mbox_stream)
4563                {
4564                        imap_close($mbox_stream);
[3803]4565            }
[3843]4566           
[3803]4567            $num_msgs = count($retorno);
[3223]4568
[3803]4569            /* Comparison functions, descendent is ascendent with parms inverted */
[4515]4570            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
[3803]4571            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
[3391]4572
[3803]4573            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
4574            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
4575
4576            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
4577            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
4578
4579            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
4580            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
4581
4582            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
4583            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
4584
[3843]4585            usort( $retorno, $params['sort_type']);
4586            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
4587           
4588            $arrayRetorno['num_msgs']   =  $num_msgs;
4589            $arrayRetorno['data']               =  $pageret;
[4158]4590            $arrayRetorno['currentTab'] =  $params['current_tab'];
[3803]4591
[3843]4592                if ($pageret)
4593                {
4594                        return $arrayRetorno;
4595                }
4596                else
4597                {
4598                        return 'none';
4599                }
[2]4600        }
[1472]4601
[3803]4602        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
[271]4603        {
[828]4604                $header = $this->get_header($uid_msg);
[3803]4605                require_once("class.imap_attachment.inc.php");
[828]4606                $imap_attachment = new imap_attachment();
4607                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
4608                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
4609                $flag = $header->Unseen
4610                        .$header->Recent
4611                        .$header->Flagged
4612                        .$header->Draft
4613                        .$header->Answered
4614                        .$header->Deleted
4615                        .$attachments;
4616
4617
[163]4618                $subject = $this->decode_string($header->fetchsubject);
4619                $from = $header->from[0]->mailbox;
[2]4620                if($header->from[0]->personal != "")
4621                        $from = $header->from[0]->personal;
[3843]4622                $ret_msg['from']        = $this->decode_string($from);
4623                $ret_msg['subject']     = $subject;
4624                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
4625                $ret_msg['size']        = $header->Size;
4626                $ret_msg['flag']        = $flag;
[1472]4627                return $ret_msg;
4628        }
[3391]4629
4630
4631        function size_msg($size){
4632                $var = floor($size/1024);
4633                if($var >= 1){
4634                        return $var." kb";
4635                }else{
4636                        return $size ." b";
4637                }
4638        }
4639       
[2]4640        function ob_array($the_object)
4641        {
4642           $the_array=array();
4643           if(!is_scalar($the_object))
4644           {
4645               foreach($the_object as $id => $object)
4646               {
4647                   if(is_scalar($object))
4648                   {
4649                       $the_array[$id]=$object;
4650                   }
4651                   else
4652                   {
4653                       $the_array[$id]=$this->ob_array($object);
4654                   }
4655               }
4656               return $the_array;
4657           }
4658           else
4659           {
4660               return $the_object;
4661           }
4662        }
[1472]4663
[2]4664        function getacl()
4665        {
4666                $this->ldap = new ldap_functions();
[1472]4667
[2]4668                $return = array();
[1472]4669                $mbox_stream = $this->open_mbox();
[2]4670                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]4671
[2]4672                $i = 0;
4673                foreach ($mbox_acl as $user => $acl)
4674                {
4675                        if ($user != $this->username)
4676                        {
4677                                $return[$i]['uid'] = $user;
4678                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
4679                        }
4680                        $i++;
4681                }
4682                return $return;
4683        }
[1472]4684
[2]4685        function setacl($params)
4686        {
4687                $old_users = $this->getacl();
4688                if (!count($old_users))
4689                        $old_users = array();
[1472]4690
[2]4691                $tmp_array = array();
4692                foreach ($old_users as $index => $user_info)
4693                {
4694                        $tmp_array[$index] = $user_info['uid'];
4695                }
4696                $old_users = $tmp_array;
[1472]4697
[2]4698                $users = unserialize($params['users']);
4699                if (!count($users))
4700                        $users = array();
[1472]4701
[2]4702                //$add_share = array_diff($users, $old_users);
4703                $remove_share = array_diff($old_users, $users);
4704
4705                $mbox_stream = $this->open_mbox();
4706
4707                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4708                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4709
4710                /*if (count($add_share))
4711                {
4712                        foreach ($add_share as $index=>$uid)
4713                        {
4714                        if (is_array($mailboxes_list))
4715                        {
4716                        foreach ($mailboxes_list as $key => $val)
4717                        {
4718                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4719                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
4720                        }
4721                        }
4722                        }
4723                }*/
[1472]4724
[2]4725                if (count($remove_share))
4726                {
4727                        foreach ($remove_share as $index=>$uid)
4728                        {
[4741]4729                            if (is_array($mailboxes_list))
4730                            {
4731                                foreach ($mailboxes_list as $key => $val)
4732                                {
4733                                    $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
4734                                    $folder = str_replace("&-", "&", $folder);
4735                                    imap_setacl ($mbox_stream, $folder, "$uid", "");
4736                                }
4737                            }
[1472]4738                        }
[2]4739                }
[1472]4740
[2]4741                return true;
4742        }
[1472]4743
[2]4744        function getaclfromuser($params)
4745        {
4746                $useracl = $params['user'];
[1472]4747
[2]4748                $return = array();
4749                $return[$useracl] = 'false';
[1472]4750                $mbox_stream = $this->open_mbox();
[2]4751                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[1472]4752
[2]4753                foreach ($mbox_acl as $user => $acl)
4754                {
4755                        if (($user != $this->username) && ($user == $useracl))
4756                        {
4757                                $return[$user] = $acl;
4758                        }
4759                }
4760                return $return;
4761        }
4762
4763        function getacltouser($user)
4764        {
4765                $return = array();
4766                $mbox_stream = $this->open_mbox();
[325]4767                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
4768                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
4769                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
4770                if(substr($user,0,4) != 'user')
[449]4771                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]4772                else
[5134]4773                  $mbox_acl = @imap_getacl($mbox_stream, $user);
4774                if(isset($mbox_acl[$this->username]))
[2]4775                return $mbox_acl[$this->username];
[5134]4776                else
4777                    return '';
[2]4778        }
4779
[1472]4780
[2]4781        function setaclfromuser($params)
4782        {
4783                $user = $params['user'];
4784                $acl = $params['acl'];
[1472]4785
[2]4786                $mbox_stream = $this->open_mbox();
4787
4788                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
4789                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
4790
4791                if (is_array($mailboxes_list))
4792                {
4793                        foreach ($mailboxes_list as $key => $val)
4794                        {
[449]4795                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
4796                                $folder = str_replace("&-", "&", $folder);
[2]4797                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
4798                                {
[449]4799                                        $return = imap_last_error();
[2]4800                                }
4801                        }
4802                }
[449]4803                if (isset($return))
4804                        return $return;
4805                else
4806                        return true;
[2]4807        }
[1472]4808
[51]4809        function download_attachment($msg,$msgno)
4810        {
[1472]4811                $array_parts_attachments = array();
[3289]4812                //$array_parts_attachments['names'] = '';
[689]4813                include_once("class.imap_attachment.inc.php");
[1472]4814                $imap_attachment = new imap_attachment();
4815
[51]4816                if (count($msg->fname[$msgno]) > 0)
4817                {
4818                        $i = 0;
4819                        foreach ($msg->fname[$msgno] as $index=>$fname)
4820                        {
4821                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
[1397]4822                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
[51]4823                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
4824                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
[3289]4825                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
[51]4826                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
4827                                $i++;
4828                        }
4829                }
[3289]4830                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
[51]4831                return $array_parts_attachments;
[1472]4832        }
[69]4833
[4436]4834       
4835        /**
4836        * @license   http://www.gnu.org/copyleft/gpl.html GPL
4837        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
4838        * @param     $params
4839        */
4840        function spam($params)
[69]4841        {
[4416]4842               
4843                $mbox_stream = $this->open_mbox($params['folder']);
[69]4844                $msgs_number = explode(',',$params['msgs_number']);
4845
[4416]4846                $user = Array();
4847
4848                if(substr($params['folder'], 0, 4) == 'user')
4849                {
4850                    $ldapObject = new ldap_functions();
4851
4852                    $folderArray = Array();
4853                    $folderArray = explode($this->imap_delimiter, $params['folder']);
4854
4855                    $user['name'] = $folderArray[1];
4856                    $user['email'] = $ldapObject->getMailByUid($user['name']);
4857               
4858                }
4859                else
4860                {
4861                    $user['name'] = $this->username;
4862                    $user['email'] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4863                }
4864
4865                foreach($msgs_number as $msg_number)
4866                {
[877]4867                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
4868                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
4869                        $body = imap_body($mbox_stream, $imap_msg_number);
[69]4870                        $msg = $header . $body;
[4416]4871                        strtok($user['email'], '@');
[69]4872                        $domain = strtok('@');
4873
[4416]4874           
4875
[449]4876                        //Encontrar a assinatura do dspam no cabecalho
4877                        $v = explode("\r\n", $header);
4878                        foreach ($v as $linha){
[877]4879                                if (eregi("^Message-ID", $linha)) {
4880                                        $args = explode(" ", $linha);
4881                                        $msg_id = "'$args[1]'";
4882                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
[449]4883                                        $args = explode(" ",$linha);
4884                                        $signature = $args[1];
4885                                }
4886                        }
4887
[877]4888                        // Seleciona qual comando a ser executado
[4416]4889                        switch($params['spam']){
[449]4890                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
4891                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
4892                        }
[877]4893
[4416]4894                     
[877]4895                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
[4416]4896                        $cmd = str_replace($tags, array($user['email'], $user['name'], $domain, $signature, $msg_id), $cmd);
4897                       
[78]4898                        system($cmd);
[69]4899                }
[4416]4900
[69]4901                imap_close($mbox_stream);
4902                return false;
4903        }
[4436]4904       
4905       
[5134]4906/**
4907* Descrição do método
4908*
4909* @license    http://www.gnu.org/copyleft/gpl.html GPL
4910* @author     
4911* @sponsor    Caixa Econômica Federal
4912* @author     
4913* @param      <tipo> <$msg_number> <Número da mensagem>
4914* @return     <cabeçalho da mensagem>
4915* @access     <public>
4916*/     
[4436]4917        function get_header($msg_number)
4918        {
[4795]4919                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[535]4920                if (!is_object($header))
4921                        return false;
[1472]4922
[5134]4923                if($header->Flagged != "F" ) {
[659]4924                        $flag = preg_match('/importance *: *(.*)\r/i',
4925                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
[1472]4926                                                ,$importance);
[659]4927                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
4928                }
[1472]4929
[535]4930                return $header;
4931        }
[1000]4932
4933//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
4934///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.
4935
[5191]4936
[3911]4937    function insert_email($source,$folder,$timestamp,$flags){
[5191]4938               
[1000]4939        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
4940        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
4941        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
4942        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
4943        $imap_options = '/notls/novalidate-cert';
[5134]4944
4945       
4946        $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
4947
[1000]4948        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
[5134]4949       
4950        if(imap_last_error() === 'Mailbox already exists')
[1000]4951            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
4952        if($timestamp){
[4436]4953                        $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local)
4954                        $timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local.
[4457]4955                        /* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */
4956                        $file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
4957               
[1000]4958                $f = fopen($file,"w");
4959                fputs($f,base64_encode($source));
[4795]4960            fclose($f);
[5134]4961            $command = "python ".$_SESSION['rootPath']."/expressoMail1_2/imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
4962            $return['command']= exec($command);
[1000]4963        }else{
4964            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
4965        }
4966        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
[3872]4967                       
[1000]4968        $return['msg_no'] = $status->uidnext - 1;
[3911]4969        $return['error'] = imap_last_error();
4970        if(!$return['error'] && $flags != '' ){
[3872]4971
[3911]4972                  $flags_array=explode(':',$flags);
4973                  //"Answered","Draft","Flagged","Unseen"
4974                  $flags_fixed = "";
4975                  if($flags_array[0] == 'A')
4976                        $flags_fixed.="\\Answered ";
4977                  if($flags_array[1] == 'X')
4978                        $flags_fixed.="\\Draft ";
4979                  if($flags_array[2] == 'F')
4980                        $flags_fixed.="\\Flagged ";
4981                  if($flags_array[3] != 'U')
4982                        $flags_fixed.="\\Seen ";
[5184]4983                  if($flags_array[4] == 'F')
4984                        $flags_fixed.="\\Answered \\Draft ";
[3911]4985                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
4986                }
[5134]4987       
4988        //Ignorando erro de AUTH=Plain
4989        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN')
4990            $return['error'] = false;
4991                               
[1000]4992        if($mbox_stream)
[3911]4993            imap_close($mbox_stream);
[1000]4994        return $return;
4995    }
4996
[5134]4997        function show_decript($params,$dec=0){
[1035]4998        $source = $params['source'];
[5083]4999                 
[5134]5000        //error_log("source: $source\nversao: " . PHP_VERSION);         
5001        if ($dec == 0)
5002        {
5003            $source = str_replace(" ", "+", $source,$i);
[5083]5004                        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
5005                            if(!$source = base64_decode($source,true))
[5134]5006                    return "error ".$source."Espaï¿?os ".$i;
[5083]5007                 
5008                        }
5009                        else {
5010                            if(!$source = base64_decode($source))
[5134]5011                    return "error ".$source."Espaï¿?os ".$i;
5012            }
[1035]5013        }
[3803]5014
[1035]5015        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5016
5017                $get['msg_number'] = $insert['msg_no'];
5018                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
5019                $return = $this->get_info_msg($get);
5020                $get['msg_number'] = $params['ID'];
5021                $get['msg_folder'] = $params['folder'];
5022                $tmp = $this->get_info_msg($get);
5023                if(!$tmp['status_get_msg_info'])
5024                {
5025                        $return['msg_day']=$tmp['msg_day'];
5026                        $return['msg_hour']=$tmp['msg_hour'];
5027                        $return['fulldate']=$tmp['fulldate'];
5028                        $return['smalldate']=$tmp['smalldate'];
5029                }
5030                else
5031                {
5032                        $return['msg_day']='';
5033                        $return['msg_hour']='';
5034                        $return['fulldate']='';
5035                        $return['smalldate']='';
5036                }
5037        $return['msg_no'] =$insert['msg_no'];
5038        $return['error'] = $insert['error'];
5039        $return['folder'] = $params['folder'];
5040        //$return['acls'] = $insert['acls'];
5041        $return['original_ID'] =  $params['ID'];
5042
5043        return $return;
5044
5045    }
[1472]5046
[1000]5047//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
5048//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
5049
5050    function treat_base64_from_post($source){
5051            $offset = 0;
5052            do
5053            {
5054                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
5055                    {
5056                            $inicio = strpos($source, "\n\r", $inicio);
5057                            $fim = strpos($source, '--', $inicio);
5058                            if(!$fim)
5059                                    $fim = strpos($source,"\n\r", $inicio);
5060                            $length = $fim-$inicio;
5061                            $parte = substr( $source,$inicio,$length-1);
5062                            $parte = str_replace(" ", "+", $parte);
5063                            $source = substr_replace($source, $parte, $inicio, $length-1);
5064                    }
5065                    if($offset > $inicio)
5066                    $offset=FALSE;
5067                    else
5068                    $offset = $inicio;
5069            }
5070            while($offset);
5071            return $source;
5072    }
5073
5074//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.
5075
5076    function unarchive_mail($params)
[5191]5077    {           
[1000]5078        $dest_folder = $params['folder'];
5079        $sources = explode("#@#@#@",$params['source']);
[5134]5080        //Add user timeszone
[5191]5081        $timestamps = explode("#@#@#@",$params['timestamp']);
5082
5083
[3911]5084        $flags = explode("#@#@#@",$params['flags']);
[5191]5085               
[5134]5086                foreach($sources as $index=>$src) {
5087                        if($src!=""){
[3911]5088                $source = $this->treat_base64_from_post($src);
[5191]5089                $timestampsactual = $timestamps[$index] + $this->functions->CalculateDateOffset();
5090                        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestampsactual,$flags[$index]);
[3911]5091            }
5092        }
[1000]5093        return $insert;
5094    }
5095
5096    function download_all_local_attachments($params)
5097    {
5098        $source = $params['source'];
5099        $source = $this->treat_base64_from_post($source);
5100        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
5101        $exporteml = new ExportEml();
5102        $params['num_msg']=$insert['msg_no'];
5103        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
5104        return $exporteml->download_all_attachments($params);
5105    }
[4830]5106       
5107        /**
5108         * Método que envia um email reportando um erro no email do usuário
5109         * @license http://www.gnu.org/copyleft/gpl.html GPL
5110         * @author Prognus Software Livre (http://www.prognus.com.br)
5111         */ 
5112        function report_mail_error($params)
5113        {       
5114                $params = $params['params'];
5115                $array_params = explode(";;", $params);
5116                $id_msg   = $array_params[0];
5117                $msg_user = $array_params[1];
5118               
5119                if($msg_user == '')
5120                        $msg_user = "Sem mensagem!";
5121                         
5122                $toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
5123                 
5124                $exporteml    = new ExportEml();
5125                $mail_content = $exporteml->export_msg_data($id_msg, $msg_folder);
5126                $this->open_mbox($msg_folder); 
5127                $title = "Erro de email reportado";
5128                $body  = "<body>O usuário <strong>$toname</strong> reportou um erro na tentativa de acesso ao conteúdo do email.<br><br>Segue em anexo o fonte da mensagem" .                           " reportada.<br><br><hr><strong><u>Mensagem do usuário:</strong></u><br><br><br>" .
5129                                "$msg_user</body><br><br><hr>";
5130                             
[5134]5131                require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
[4830]5132                $mailService = ServiceLocator::getService('mail');     
[5134]5133                $mailService->addStringAttachment($mail_content, 'report.eml', 'application/text');
5134                $mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body);
[4830]5135        }
5136       
[5134]5137        function array_msort($array, $cols)
5138        {
5139                $colarr = array();
5140                foreach ($cols as $col => $order) {
5141                        $colarr[$col] = array();
5142                        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
5143                }
5144                $params = array();
5145                foreach ($cols as $col => $order) {
5146                        $params[] =& $colarr[$col];
5147                        $params = array_merge($params, (array)$order);
5148                }
5149                call_user_func_array('array_multisort', $params);
5150                $ret = array();
5151                $keys = array();
5152                $first = true;
5153                foreach ($colarr as $col => $arr) {
5154                        foreach ($arr as $k => $v) {
5155                                if ($first) { $keys[$k] = substr($k,1); }
5156                                $k = $keys[$k];
5157                                if (!isset($ret[$k])) $ret[$k] = $array[$k];
5158                                $ret[$k][$col] = $array[$k][$col];
5159                        }
5160                        $first = false;
5161                }
5162               
5163                return $ret;
5164
5165        }
5166       
5167        function parseCriteriaSearchMail($search)
5168        {
5169            $criteria = '';
5170            $searchArray = explode(' ', $search);
5171
5172            foreach ($searchArray as $v)
5173                if(trim($v) !== '' )
5174                    $criteria .= 'TEXT "'.$v.'" ' ;
5175           
5176            return $criteria;
5177        }
5178       
5179        function quickSearchMail( $params )
5180        {
5181                $return = array();
5182                $return['folder'] = $params['folder'];
5183                if(!is_array($params['folder']))
5184                        $params['folder'] = array( $params['folder'] );
5185               
5186                if(!isset($params['sort']))
[5172]5187                        $params['sort'] = 'SORTDATE_REVERSE';
[5134]5188                               
5189                $params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
5190               
5191                $i = 0;         
5192                if(!isset($params['page'])) $params['page'] = 0;
5193                $end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));       
5194                $ini = $end - $this->prefs['max_email_per_page'] ;
5195                $count = 0;
5196               
5197                $search = $this->parseCriteriaSearchMail($params['search']);
5198                               
5199                foreach ($params['folder'] as $folder)
5200                {
5201                        $imap = $this->open_mbox( $folder ) ;
[5172]5202                        $msgIds = imap_sort( $imap , SORTDATE , 1 , SE_UID , $search ,'UTF-8');
[5134]5203                                               
5204                        $count += count($msgIds); 
5205                       
5206                        foreach ($msgIds as $ii => $v)
5207                        {                               
5208                                $msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) );
5209                                $return['msgs'][$i]['from'] = '';
5210                               
5211                                $from = $msg->from[0]->mailbox;
5212                                if($msg->from[0]->personal != "")
5213                                        $from = $msg->from[0]->personal;
5214                                $return['msgs'][$i]['from']     = mb_convert_encoding($this->decode_string($from), 'UTF-8');
5215                               
5216                                $return['msgs'][$i]['subject'] = ' ';
5217                               
5218                                $subject = imap_mime_header_decode($msg->subject);
5219                                foreach ($subject as $tmp)
[5189]5220                                        $return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
[5134]5221                               
[5189]5222                               
[5134]5223                                $return['msgs'][$i]['flag'] = ' ';
5224                                $return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
5225                                $return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';       
5226                                $return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';     
5227                                $return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : ''; 
5228                                $return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';   
5229                                $return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';     
5230                               
5231                                $return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset());
5232                                $return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2);
5233                            $return['msgs'][$i]['date'] =   $msg->udate;
5234                                $return['msgs'][$i]['size'] =  $msg->Size;
5235                                $return['msgs'][$i]['boxname'] = $folder;
5236                                $return['msgs'][$i]['uid'] = $v;
5237                                $i++;
5238                        }       
5239                }
5240               
5241                $return['num_msgs'] = $count;
5242               
5243                if(!isset($return['msgs']))
5244                        $return['msgs'] = array();
5245               
5246                define('SORTBOX', 69);
5247                define('SORTWHO', 2);
5248                define('SORTBOX_REVERSE', 69);
5249                define('SORTWHO_REVERSE', 2);
5250                define('SORTDATE_REVERSE', 0);
5251                define('SORTSUBJECT_REVERSE', 3);
5252                define('SORTSIZE_REVERSE', 6);
5253               
5254                switch (constant( $params['sort'] )){
5255                        case 0 : $sA = 'date'; break;
5256                        case 2 : $sA = 'from'; break;
5257                        case 69 : $sA = 'boxname'; break;
5258                        case 3 : $sA = 'subject'; break;
5259                        case 6 : $sA = 'size'; break;
5260        }
[4830]5261       
[5134]5262                       
[5172]5263                if($params['sort'] !== 'SORTDATE_REVERSE')
[5134]5264                if(strpos($params['sort'],'REVERSE') !== false)
[5172]5265                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_DESC));
5266                        else
5267                                $return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
[5134]5268               
5269                $k = -1;
5270                $nMsgs = array();
5271               
5272                foreach ($return['msgs'] as $v)
5273                {               
5274                        $k++;
5275                        if($k < $ini || $k >= $end ) continue;                 
5276                        $nMsgs[] = $v;
5277                }
5278                $return['msgs'] = $nMsgs;
[5189]5279               
[5134]5280                $return = json_encode($return);         
5281                $return = base64_encode($return);
[4830]5282       
[5134]5283                return $return;
5284        }
5285       
[3157]5286    function get_quota_folders(){
5287
5288            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
5289            include_once("class.imapfp.inc.php");           
5290            $imapfp = new imapfp();
5291
5292            if(!$imapfp->open($this->imap_server,$this->imap_port))
5293                    return $imapfp->get_error();             
5294            if (!$imapfp->login( $this->username,$this->password ))
5295                    return $imapfp->get_error();
5296
5297            $response_array = $imapfp->get_mailboxes_size();
5298            if ($imapfp->error)
5299                    return $imapfp->get_error();
5300
5301            $data = array();
5302            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
5303            $data["quota_root"] = $quota_root;
5304
5305            foreach ($response_array as $idx=>$line) {
5306                    $line2 = str_replace('"', "", $line);
5307                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
5308                    list($folder,$size) = explode(";",$line2);
[3854]5309                    $quota_used = str_replace(")","",$size);
5310                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
[3157]5311                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
5312                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
5313                            $folder = $this->functions->getLang("Inbox");
5314                    }
5315                    else
5316                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
5317
5318                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
5319            }
5320            $imapfp->close();
5321            return $data;
5322    } 
[5134]5323   
5324    function getaclfrombox($mail)
5325        {
5326                $mailArray = explode('@', $mail);
5327                $boxacl = $mailArray[0];
5328                $return = array();
5329
5330                if(!$this->mbox)
5331                     $this->open_mbox();
5332
5333                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl);
5334
5335                foreach ($mbox_acl as $user => $acl)
5336                {
5337                        if ($user != $boxacl )
5338                            $return[$user] = $acl;
5339                }
5340                return $return;
5341        }
[2]5342}
[278]5343?>
Note: See TracBrowser for help on using the repository browser.