source: sandbox/expressoMail1_2/corretor_ortografico/inc/class.ScriptS.inc.php @ 1352

Revision 1352, 16.9 KB checked in by amuller, 15 years ago (diff)

Ticket #615 - Correção de informação na montagem da regra no sieve

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