source: branches/2.0/expressoMail1_2/inc/class.ScriptS.inc.php @ 2658

Revision 2658, 16.8 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1056 - Corrigido problema que remove todas as regras ao criar um nova.

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