source: trunk/expressoMail1_2/inc/class.ScriptS.inc.php @ 1036

Revision 1036, 16.2 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Atualização de segurança

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2        $GLOBALS['phpgw_info']['flags'] = array(
3                'currentapp' => 'expressoMail1_2',
4                'nonavbar'   => true,
5                'noheader'   => true
6        );
7
8        require_once $_SERVER[ 'DOCUMENT_ROOT' ] . '/header.inc.php';
9
10//Inclui o arquivo contendo a classe SieveS;
11include('class.SieveS.inc.php');
12
13class ScriptS {
14       
15        //Declaração de Variáveis;
16        var $SieveS;                                    // Var para criação do objeto;
17        var $reply;                                             // Var para resposta;
18        var $scriptfile;                                // Nome do script;
19        var $username;                                  // Nome do usuario;
20        var $rules;                                             // Regras do sieve;
21        var $errstr;                                    // Erros retornados;
22        var $size;                                              // Tamanho;
23        var $so;                                                // Verifica se a regra foi criada por outro tipo serviço de filtros;
24        var $continuebit;
25        var $sizebit;
26        var $anyofbit;
27        var $keepbit;
28        var $regexbit;
29        var $newrules = array();
30        var $newout;
31        var $teste;
32        var $EmailVoip;
33        var $EmailExpresso;
34       
35        function ScriptS(){
36
37                //Cria o objeto;
38                $this->SieveS     = new SieveS();
39               
40                //$this->scriptfile = $GLOBALS['HTTP_SESSION_VARS']['phpgw_info']['expressomail']['user']['account_lid'];
41                $this->scriptfile = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
42                $this->username   = $this->scriptfile;
43               
44                $this->reply      = "";
45                $this->rules      = "";
46                $this->errstr     = "";
47                $this->size               = "";
48               
49                $this->continuebit      = 1;
50        $this->sizebit          = 2;
51        $this->anyofbit         = 4;
52        $this->keepbit          = 8;
53        $this->regexbit         = 128;
54       
55        $this->EmailVoip = trim($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_email_redirect']);
56        $this->EmailExpresso = trim($_SESSION['phpgw_info']['expressomail']['user']['email']);
57       
58        }
59       
60        function init_a(){
61               
62                //Abre a conexão
63                $this->SieveS->start();
64               
65                $this->reply = $this->SieveS->getscript();
66               
67                if(!$this->reply){
68       
69                        $aux = $this->SieveS->putscript($this->scriptfile, $this->createScript());
70                        if(!$aux){
71                                // Caso de erro, grava dentro da variável errstr;
72                                $this->errstr = "O arquivo não foi criado";
73                        }
74                        // Mata a variavel;
75                        unset($aux);
76                        // Ativa o script;
77                        $aux = $this->SieveS->activatescript($this->scriptfile);
78                       
79                        if(!$aux){
80                                // Caso de erro, grava dentro da variavel errstr;
81                                $this->errstr = "O arquivo não foi ativado";
82                        }
83                        else{
84                                $this->reply = $this->SieveS->getscript();
85                                $this->rules = $this->readScript($this->reply);
86                        }
87                }else{
88                        $this->rules = $this->readScript($this->reply);
89                }               
90
91                //Fecha a conexao
92                $this->SieveS->close();
93                       
94                if($this->rules){               
95                        return $this->rules;
96                }else{
97                        return $this->errstr;
98                }
99                       
100        }
101       
102        function rec_rules($params){
103               
104                $newr1  = array();
105                $newr2  = array();
106                $newr3  = array();
107       
108                $var_decode = rawurldecode($params['arfilter']);
109               
110                $narray  = explode("_end_",$var_decode);
111
112                foreach($narray as $key=>$tmp){
113                        if($tmp != ""){
114                                $newr1[] = $tmp;
115                        }
116                }
117                unset($key);
118                unset($tmp);
119                foreach($newr1 as $key=>$tmp){
120                        $tmp2 = explode("_begin_##", $tmp);
121                        foreach($tmp2 as $tmp3){
122                                if($tmp3 != ""){
123                                        $newr2[] = trim($tmp3);         
124                                }       
125                        }       
126                }
127               
128                unset($tmp);
129                unset($tmp2);
130                unset($tmp3);
131
132                foreach($newr2 as $tmp){
133                        if(trim($tmp) != ""){   
134                                $tmp2 = explode("##",$tmp);
135                                foreach($tmp2 as $tmp3){
136                                        $tmp4 .= trim($tmp3) . "&&";   
137                                }
138                                $newr3[] = substr($tmp4,0,(strlen($tmp4)-4));                   
139                                unset($tmp2);
140                                unset($tmp3);
141                                unset($tmp4);
142                        }
143                }
144               
145                $tmp = $newr3[count($newr3)-1];
146               
147                if(substr($tmp,0,9) == "#vacation"){
148                        $this->newout = array_pop($newr3);
149                        foreach($newr3 as $key=>$tmp){
150                                $this->newrules[] = $tmp;
151                        }
152                }else{
153                        foreach($newr3 as $tmp){
154                                $this->newrules[] = $tmp;       
155                        }
156                }
157                               
158                unset($tmp);
159                $tmp  = explode("&&",$this->newout);
160                $tmp1 = explode(",",$tmp[2]);
161                foreach($tmp1 as $key=>$tmp2){
162                        $tmp3 .= stripslashes(trim($tmp2)).", ";
163                }
164                $tmp3 = substr($tmp3,0,(strlen($tmp3)-2));
165               
166                unset($tmp);
167                unset($tmp1);
168                unset($tmp2);
169                unset($key);
170                $tmp = explode("&&",$this->newout);
171                foreach($tmp as $key=>$tmp1){
172                        if($key == 2){
173                                $tmp2 .= trim($tmp3) . "&&";   
174                        }else{
175                                $tmp2 .= trim($tmp1) . "&&";   
176                        }       
177                }
178                unset($this->newout);
179                $this->newout = substr($tmp2,0,(strlen($tmp2)-2));
180               
181                //Abre a conexao
182                $this->SieveS->start();
183                $this->errstr = "";
184               
185                // Escreve a nova regra;
186                $this->reply = $this->SieveS->getscript();
187               
188                if($this->reply){
189                        $this->errstr = $this->SieveS->deletescript($this->scriptfile);         
190                }
191
192                //Escreve a(s) nova(s) regra(s);
193                $this->errstr = $this->SieveS->putscript($this->scriptfile,$this->write_rule());
194               
195                //Ativa o script;
196                $this->errstr = $this->SieveS->activatescript($this->scriptfile);
197               
198                //Fecha a conexao
199                $this->SieveS->close();
200               
201                if($this->errstr){
202                        return "Ok";
203                }else{
204                        return "Problemas na criação do arquivo!\n" . $this->teste;
205                }
206        }
207
208    function convert_specialchar($input)
209    {
210      $special_char = false;
211          for ( $i = 0; $i < strlen($input); $i++ )
212          {
213              if ( preg_match('/[ÁáÉéÍíÓóÚúÀàÈèÌìÒòÙùüÇçÃãÕõÂâÊêÔô®©§ªºÐ¹²³°¢¿Æ£µøæß«»Ø÷±¬]/', $input[$i]) )
214              {
215                  $special_char = true;
216                  $input = preg_replace('/'.$input[$i].'/', '=' . bin2hex($input[$i]), $input);
217              }
218          }   
219     
220      if ( $special_char )
221          {
222                   /* *
223                    * When using arrays with pattern and replacement,
224                    * the keys are processed in the order they appear in the array.
225                    * See preg_replace in php.net/preg_replace
226                    * */
227                   $patterns[0] = '/=c3/i';
228                   $patterns[1] = '/ /';
229                   $replacements[1] = '';
230                   $replacements[0] = '_';
231                   $input = preg_replace($patterns, $replacements, $input);
232           }
233       
234       return($input);
235    }
236
237        // Grava a nova regra;
238        function write_rule(){
239
240                // Variaveis;
241                $rule = array();
242                $vacation = array();
243                $newruletext = "";
244                $activerules = 0;
245                $regexused = 0;
246                $rejectused = 0;
247                $notify = 0;
248                $newscriptbody = "";
249        $continue = 1;
250        $tmpSubject = "";
251       
252                // Recebe os valores das regras;
253                foreach($this->newrules as $tmp){
254                  $tmp1 = explode("&&",$tmp);
255                  $rule['priority']      = $tmp1[1];
256                  $rule['status']        = $tmp1[2];
257          $rule['from']              = $this->convert_specialchar($tmp1[3]);
258          $rule['to']            = $this->convert_specialchar($tmp1[4]);
259                  $tmpSubject                    = $tmp1[5];
260                  $rule['subject']               = $this->convert_specialchar($tmp1[5]);
261          $rule['action']            = $tmp1[6];
262                  $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
263          $rule['flg']               = $tmp1[8];   
264          $rule['field']                 = $tmp1[9];
265          $rule['field_val']     = $tmp1[10];
266          $rule['size']                    = $tmp1[11];
267          $rule['continue']        = ($tmp1[8] & $this->continuebit);
268          $rule['gthan']                   = ($tmp1[8] & $this->sizebit);
269          $rule['anyof']                   = ($tmp1[8] & $this->anyofbit);
270          $rule['keep']                    = ($tmp1[8] & $this->keepbit);
271          $rule['regexp']              = ($tmp1[8] & $this->regexbit);
272          $rule['unconditional']   = 0;
273                 
274                  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && !$rule['size'] && $rule['action']){
275                         $rule['unconditional'] = 1;
276                  }
277                  unset($tmp1);
278             
279              // Monta as regras;
280              if ($rule['status'] != 'ENABLED') {
281              }
282              else {
283                $activerules = 1;
284         
285                // Condições para montagem das regras;
286                $anyall = "allof";
287                if ($rule['anyof']) $anyall = "anyof";
288                if ($rule['regexp']) {
289                    $regexused = 1;
290                }
291                $started = 0;
292         
293                if (!$rule['unconditional']) {
294                    if (!$continue) $newruletext .= "els";
295                    $newruletext .= "if " . $anyall . " (";
296                    if ($rule['from']) {
297                        if (preg_match("/^\s*!/", $rule['from'])){
298                            $newruletext .= 'not ';
299                            $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
300                        }
301                        $match = ':contains';
302                        if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
303                        if ($rule['regexp']) $match = ':regex';
304                        $newruletext .= "header " . $match . " [\"From\"]";
305                        $newruletext .= " \"" . $rule['from'] . "\"";
306                        $started = 1;
307                    }
308                    if ($rule['to']) {
309                        if ($started) $newruletext .= ", ";
310                        if (preg_match("/^\s*!/", $rule['to'])){
311                            $newruletext .= 'not ';
312                            $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
313                        }
314                        $match = ':contains';
315                        if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
316                        if ($rule['regexp']) $match = ':regex';
317                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
318                        $newruletext .= " \"" . $rule['to'] . "\"";
319                        $started = 1;
320                    }
321                    if ($rule['subject']) {
322                        if ($started) $newruletext .= ", ";
323                        if (preg_match("/^\s*!/", $rule['subject'])){
324                            $newruletext .= 'not ';
325                            $rule['subject'] = preg_replace("/^\s*!/","",$rule['subject']);
326                        }
327                        $match = ':contains';
328                        if (preg_match("/\*|\?/", $rule['subject'])) $match = ':matches';
329                        if ($rule['regexp']) $match = ':regex';
330                        $newruletext .= "header " . $match . " \"subject\"";
331                        $newruletext .= " \"" . $rule['subject'] . "\"";
332                        $started = 1;
333                    }
334                    if ($rule['field'] && $rule['field_val']) {
335                        if ($started) $newruletext .= ", ";
336                        if (preg_match("/^\s*!/", $rule['field_val'])){
337                            $newruletext .= 'not ';
338                            $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
339                        }
340                        $match = ':contains';
341                        if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
342                        if ($rule['regexp']) $match = ':regex';
343                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
344                        $newruletext .= " \"" . $rule['field_val'] . "\"";
345                        $started = 1;
346                    }
347                    if ($rule['size']) {
348                        $xthan = " :under ";
349                        if ($rule['gthan']) $xthan = " :over ";
350                        if ($started) $newruletext .= ", ";
351                        $newruletext .= "size " . $xthan . $rule['size'] . "K";
352                        $started = 1;
353                    }
354         
355                }
356         
357                // Ações
358                if (!$rule['unconditional']) $newruletext .= ") {\n\t";
359       
360                if (preg_match("/folder/i",$rule['action']))
361                {
362                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
363                }
364               
365                if (preg_match("/reject/i",$rule['action']))
366                {
367                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
368                    $rejectused = 1;
369                }
370               
371                if (preg_match("/address/i",$rule['action']))
372                {
373                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
374                }
375               
376                if (preg_match("/notify/i",$rule['action']))
377                {
378                                $newruletext .= "notify :method \"mailto\" :options [\"".$this->EmailVoip ."\"]:" .
379                                                                "message \"<expressovoip><from>". $this->EmailExpresso."</from>".
380                                                                "<br/><Subject>".utf8_encode($tmpSubject)."</Subject></expressovoip>\";";
381                                $notify = 1;                                                   
382                }
383               
384                if (preg_match("/discard/i",$rule['action'])) {
385                    $newruletext .= "discard;";
386                }
387                if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
388                //if ($rule['keep']) $newruletext .= "\n\tkeep;";               
389                if (!$rule['unconditional']) $newruletext .= "\n}";
390         
391                $continue = 0;
392                if ($rule['continue']) $continue = 1;
393                if ($rule['unconditional']) $continue = 1;
394         
395                $newscriptbody .= $newruletext . "\n\n";
396                unset($newruletext);
397              }
398                }// Fim do Foreach;
399                $this->teste = $newscriptbody;         
400                // Para a regras fora do escritorio;
401        unset($tmp);
402        if($this->newout != ""){
403                $aux                                    = explode("&&",$this->newout);
404                $vacation['days']               = $aux[1];
405                $vacation['addresses']  = $aux[2];             
406                $vacation['text']               = preg_replace("/\\\\n/","\r\n",$aux[3]);
407                $vacation['status']     = $aux[4];
408            }
409               
410                // Monta a regra para fora do escritorio;
411            if ($vacation['status'] == 'on') {
412                        $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
413            $newscriptbody .= $vacation['addresses'];
414            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
415            }
416               
417                // Cria o cabeçalho do arquivo;
418                $newscripthead  = "";
419                $newscripthead .= "#Mail filter rules for " .$this->username . "\n";
420                $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
421                $newscripthead .= "\n";
422
423                // Continuação do cabeçalho do arquivo;                 
424            if ($activerules) {
425                $newscripthead .= "require [\"fileinto\"";
426               
427                if($notify){
428                        $newscripthead .= ",\"notify\"";                       
429                }
430                if($regexused){
431                        $newscripthead .= ",\"regex\"";
432                }
433                if($rejectused){
434                        $newscripthead .= ",\"reject\"";
435                }
436                if($this->newout && $vacation['status'] == 'on'){
437                    $newscripthead .= ",\"vacation\"";
438                }
439                $newscripthead .= "];\n\n";
440            }else{
441                        if($vacation && $vacation['status'] == 'on'){
442                            $newscripthead .= "require [\"vacation\"];\n\n";
443                        }
444            }
445               
446            // Cria o rodapé do arquivo;
447            $newscriptfoot  = "";
448            $newscriptfoot .= "##PSEUDO script start\n";
449            // Lê as regras;
450            foreach($this->newrules as $tmp){
451                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
452            }
453            // Lê as regras fora do escritório;
454            if($this->newout != ""){
455                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
456            }
457                $newscriptfoot .= "#mode&&basic\n";
458               
459                $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
460
461                // Destroi as variaveis;
462                unset($rule);
463                unset($vacation);
464                unset($activerules);
465                unset($regexused);
466                unset($rejectused);
467                unset($newscripthead);
468                unset($newscriptbody);
469        unset($newscriptfoot);
470        unset($continue);
471        unset($this->newrules);
472        unset($this->newout);
473               
474                // Retorna o script construido;
475                return $newscript;
476       
477        }// Fim da Função
478
479        // Cria o script sieve, caso nao possua;
480        function createScript(){
481               
482                // Cria o cabeçalho do arquivo;
483                $newScriptHead  = "";
484                $newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
485                $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail '; 
486                $newScriptHead .= "\n";
487
488                //Cria o rodapé do arquivo;
489                $newScriptFoot  = "";
490                $newScriptFoot .= "##PSEUDO Script Start\n";
491                $newScriptFoot .= "#mode&&basic\n";
492               
493                //Para passar para o arquivo;
494                $newScript = $newScriptHead . $newScriptFoot;
495
496                return $newScript;
497        }
498       
499        //Lê o conteúdo do script;
500        function readScript($scriptName){
501               
502                // Verifica se a conexão foi bem sucedida;
503                if(!$scriptName){       
504                        $this->errstr = "Não foi possível conectar com o Servidor";
505                        return "false 2";       
506                }
507               
508                // Recebe o conteúdo do array;
509                $lines = array();
510                $lines = preg_split("/\n/",$scriptName);
511               
512                // Pega o tamanho da regra na primeira do script;
513                $size_rule = array_shift($lines);
514               
515                // Recebe o tamanho do script, pela primeira linha;
516                $this->size = trim($size_rule);
517               
518                // Verifica a composição do script;
519                $line = array_shift($lines);
520                if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
521                        $this->errstr = "Formato nao reconhecido";
522                        return false;
523                }
524               
525                // Variaveis para a regra e o campo ferias;
526                $regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
527                $retorno['rule']         = array();
528                $retorno['vacation'] = array();
529                $retorno['mode']         = array();
530               
531                $line = array_shift($lines);
532                while (isset($line)){
533                        foreach($regexps as $regp){
534                                if(preg_match("/$regp/i",$line)){
535                                        // Recebe todas as regras criadas no servidor;
536                                        if(preg_match("/^ *#rule&&/i",$line)){
537                                                $retorno['rule'][] = $line . "\n";
538                                        }
539                                        if(preg_match("/^ *#vacation&&/i",$line)){
540                                                $retorno['vacation'][] = $line . "\n"; 
541                                        }
542                                        if(preg_match("/^ *#mode&&(.*)/i",$line)){
543                                                $retorno['mode'][]= $line . "\n";                                               
544                                        }                                       
545                                }
546                        }
547                        // Pega a proxima linha do sript;
548                        $line = array_shift($lines);
549                }
550                return $retorno;       
551        }
552               
553}//Fim da Classe
554?>
Note: See TracBrowser for help on using the repository browser.