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

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