source: branches/2.2/expressoMail1_2/inc/class.ScriptS.inc.php @ 3849

Revision 3849, 17.6 KB checked in by alexandrecorreia, 13 years ago (diff)

Ticket #1650 - Filtros de tamanho de mensagem maior que zero nao sao criados.

  • 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          = 1;
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 = "Error: file not created";
65                                return $this->errstr;
66                        }
67                        // Mata a variavel;
68                        unset($aux);
69                        // Ativa o script;
70                        $aux = $this->SieveS->activatescript($this->scriptfile);
71                       
72                        if(!$aux){
73                                // Caso de erro, grava dentro da variavel errstr;
74                                $this->errstr = "Error: error to activate file";
75                                return $this->errstr;
76                        }
77                        else{
78                                $this->reply = $this->SieveS->getscript();
79                                $this->rules = $this->readScript($this->reply);
80                        }
81                }else{
82                        $this->rules = $this->readScript($this->reply);
83                }               
84
85                //Fecha a conexao
86                $this->SieveS->close();
87                       
88                if($this->rules)
89                        return $this->rules;
90                       
91        }
92       
93        function rec_rules($params){
94               
95                $newr1  = array();
96                $newr2  = array();
97                $newr3  = array();
98       
99                $var_decode = rawurldecode($params['arfilter']);
100                $var_decode = preg_replace('/\n\./', '.', $var_decode);
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                $flaggedused = 0;
263                $newscriptbody = "";
264        $continue = 1;
265        $tmpSubject = "";
266       
267                // Recebe os valores das regras;
268                foreach($this->newrules as $tmp){
269                  $tmp1 = explode("&&",$tmp);
270                  $rule['priority']      = $tmp1[1];
271                  $rule['status']        = $tmp1[2];
272          $rule['from']              = $this->convert_specialchar($tmp1[3]);
273          $rule['to']            = $this->convert_specialchar($tmp1[4]);
274                  $tmpSubject                    = $tmp1[5];
275                  $rule['subject']               = $this->convert_specialchar($tmp1[5]);
276          $rule['action']            = $tmp1[6];
277                  $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
278          $rule['flg']               = $tmp1[8];   
279          $rule['field']                 = $tmp1[9];
280          $rule['field_val']     = $tmp1[10];
281          $rule['size']                    = $tmp1[11];
282          $rule['continue']        = ($tmp1[8] & $this->continuebit);
283          $rule['gthan']                   = ($tmp1[8] & $this->sizebit);
284          $rule['anyof']                   = ($tmp1[8] & $this->anyofbit);
285          $rule['keep']                    = ($tmp1[8] & $this->keepbit);
286          $rule['regexp']              = ($tmp1[8] & $this->regexbit);
287          $rule['unconditional']   = 0;
288                 
289                  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && empty($rule['size']) && $rule['action'])
290                  {
291                        $rule['unconditional'] = 1;
292                       
293                        if( $rule['unconditional'] && ($rule['size'] == "0" || $rule['size'] == 0 ) )
294                                $rule['unconditional'] = 0;
295                  }
296                  unset($tmp1);
297             
298              // Monta as regras;
299              if ($rule['status'] != 'ENABLED') {
300              }
301              else {
302                $activerules = 1;
303         
304                // Condições para montagem das regras;
305                $anyall = "allof";
306                if ($rule['anyof']) $anyall = "anyof";
307                if ($rule['regexp']) {
308                    $regexused = 1;
309                }
310                $started = 0;
311         
312                if (!$rule['unconditional']) {
313                    if (!$continue) $newruletext .= "els";
314                    $newruletext .= "if " . $anyall . " (";
315                    if ($rule['from']) {
316                        if (preg_match("/^\s*!/", $rule['from'])){
317                            $newruletext .= 'not ';
318                            $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
319                        }
320                        $match = ':contains';
321                        if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
322                        if ($rule['regexp']) $match = ':regex';
323                        $newruletext .= "header " . $match . " [\"From\"]";
324                        $newruletext .= " \"" . $rule['from'] . "\"";
325                        $started = 1;
326                    }
327                    if ($rule['to']) {
328                        if ($started) $newruletext .= ", ";
329                        if (preg_match("/^\s*!/", $rule['to'])){
330                            $newruletext .= 'not ';
331                            $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
332                        }
333                        $match = ':contains';
334                        if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
335                        if ($rule['regexp']) $match = ':regex';
336                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
337                        $newruletext .= " \"" . $rule['to'] . "\"";
338                        $started = 1;
339                    }
340                    if ($rule['subject']) {
341                        if ($started) $newruletext .= ", ";
342                        if (preg_match("/^\s*!/", $rule['subject'])){
343                            $newruletext .= 'not ';
344                            $rule['subject'] = preg_replace("/^\s*!/","",$rule['subject']);
345                        }
346                        $match = ':contains';
347                        if (preg_match("/\*|\?/", $rule['subject'])) $match = ':matches';
348                        if ($rule['regexp']) $match = ':regex';
349                        $newruletext .= "header " . $match . " \"subject\"";
350                        $newruletext .= " \"" . $rule['subject'] . "\"";
351                        $started = 1;
352                    }
353                    if ($rule['field'] && $rule['field_val']) {
354                        if ($started) $newruletext .= ", ";
355                        if (preg_match("/^\s*!/", $rule['field_val'])){
356                            $newruletext .= 'not ';
357                            $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
358                        }
359                        $match = ':contains';
360                        if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
361                        if ($rule['regexp']) $match = ':regex';
362                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
363                        $newruletext .= " \"" . $rule['field_val'] . "\"";
364                        $started = 1;
365                    }
366                   
367                    if ( $rule['size'] >= 0 ) {
368                        $xthan = " :under ";
369                        if ($rule['gthan']) $xthan = " :over ";
370                        if ($started) $newruletext .= ", ";
371                                       
372                                        if($rule['size'] != 0 && $rule['size'] != "0")
373                                                $newruletext .= "size " . $xthan . $rule['size'] ."K";
374                                        else
375                                                $newruletext .= "size " . $xthan . "0K";
376                                               
377                        $started = 1;
378                    }
379         
380                }
381                // Don't write half rule!
382                if (strlen($newruletext) == 0)
383                        return false;
384                // Actions
385                if (!$rule['unconditional']) $newruletext .= ") {\n\t";
386       
387                if (preg_match("/folder/i",$rule['action']))
388                {
389                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
390                }
391               
392                if (preg_match("/reject/i",$rule['action']))
393                {
394                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
395                    $rejectused = 1;
396                }
397                if (preg_match("/flagged/i",$rule['action']))
398                {
399                    $newruletext .= "addflag \"\\\\Flagged\";";
400                    $flaggedused = 1;
401                }
402                if (preg_match("/address/i",$rule['action']))
403                {
404                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
405                }
406               
407                if (preg_match("/notify/i",$rule['action']))
408                {
409                                $newruletext .= "notify :method \"mailto\" :options [\"".$this->EmailVoip ."\"]:" .
410                                                                "message \"<expressovoip><from>". $this->EmailExpresso."</from>".
411                                                                "<br/><Subject>".utf8_encode($tmpSubject)."</Subject></expressovoip>\";";
412                                $notify = 1;                                                   
413                }
414               
415                if (preg_match("/discard/i",$rule['action'])) {
416                    $newruletext .= "discard;";
417                }
418                if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
419                //if ($rule['keep']) $newruletext .= "\n\tkeep;";               
420                if (!$rule['unconditional']) $newruletext .= "\n}";
421         
422                $continue = 0;
423                if ($rule['continue']) $continue = 1;
424                if ($rule['unconditional']) $continue = 1;
425         
426                $newscriptbody .= $newruletext . "\n\n";
427                unset($newruletext);
428              }
429                }// Fim do Foreach;
430                $this->teste = $newscriptbody;         
431                // Para a regras fora do escritorio;
432        unset($tmp);
433        if($this->newout != ""){
434                $aux                                    = explode("&&",$this->newout);
435                $vacation['days']               = $aux[1];
436                $vacation['addresses']  = $aux[2];             
437                $vacation['text']               = preg_replace("/\\\\n/","\r\n",$aux[3]);
438                $vacation['status']     = $aux[4];
439            }
440               
441                // Monta a regra para fora do escritorio;
442            if ($vacation['status'] == 'on') {
443                        $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
444            $newscriptbody .= $vacation['addresses'];
445            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
446            }
447               
448                // Cria o cabeçalho do arquivo;
449                $newscripthead  = "";
450                $newscripthead .= "#Mail filter rules for " .$this->username . "\n";
451                $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
452                $newscripthead .= "\n";
453
454                // Continuação do cabeçalho do arquivo;                 
455            if ($activerules) {
456                $newscripthead .= "require [\"fileinto\"";
457               
458                if($notify){
459                        $newscripthead .= ",\"notify\"";                       
460                }
461                if($regexused){
462                        $newscripthead .= ",\"regex\"";
463                }
464                if($rejectused){
465                        $newscripthead .= ",\"reject\"";
466                }
467                if($flaggedused){
468                        $newscripthead .= ",\"imapflags\"";
469                }
470                if($this->newout && $vacation['status'] == 'on'){
471                    $newscripthead .= ",\"vacation\"";
472                }
473                $newscripthead .= "];\n\n";
474            }else{
475                        if($vacation && $vacation['status'] == 'on'){
476                            $newscripthead .= "require [\"vacation\"];\n\n";
477                        }
478            }
479               
480            // Cria o rodapé do arquivo;
481            $newscriptfoot  = "";
482            $newscriptfoot .= "##PSEUDO script start\n";
483            // Lê as regras;
484            foreach($this->newrules as $tmp){
485                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
486            }
487            // Lê as regras fora do escritório;
488            if($this->newout != ""){
489                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
490            }
491                $newscriptfoot .= "#mode&&basic\n";
492               
493                $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
494
495                // Destroi as variaveis;
496                unset($rule);
497                unset($vacation);
498                unset($activerules);
499                unset($regexused);
500                unset($rejectused);
501                unset($flaggedused);
502                unset($newscripthead);
503                unset($newscriptbody);
504        unset($newscriptfoot);
505        unset($continue);
506        unset($this->newrules);
507        unset($this->newout);
508               
509                // Retorna o script construido;
510                return $newscript;
511       
512        }// Fim da Função
513
514        // Cria o script sieve, caso nao possua;
515        function createScript(){
516               
517                // Cria o cabeçalho do arquivo;
518                $newScriptHead  = "";
519                $newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
520                $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail '; 
521                $newScriptHead .= "\n";
522
523                //Cria o rodapé do arquivo;
524                $newScriptFoot  = "";
525                $newScriptFoot .= "##PSEUDO Script Start\n";
526                $newScriptFoot .= "#mode&&basic\n";
527               
528                //Para passar para o arquivo;
529                $newScript = $newScriptHead . $newScriptFoot;
530
531                return $newScript;
532        }
533       
534        //Lê o conteúdo do script;
535        function readScript($scriptName){
536               
537                // Verifica se a conexão foi bem sucedida;
538                if(!$scriptName){       
539                        $this->errstr = "Não foi possível conectar com o Servidor";
540                        return "false 2";       
541                }
542               
543                // Recebe o conteúdo do array;
544                $lines = array();
545                $lines = preg_split("/\n/",$scriptName);
546               
547                // Pega o tamanho da regra na primeira do script;
548                $size_rule = array_shift($lines);
549               
550                // Recebe o tamanho do script, pela primeira linha;
551                $this->size = trim($size_rule);
552               
553                // Verifica a composição do script;
554                $line = array_shift($lines);
555                if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
556                        $this->errstr = "Formato nao reconhecido";
557                        return false;
558                }
559               
560                // Variaveis para a regra e o campo ferias;
561                $regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
562                $retorno['rule']         = array();
563                $retorno['vacation'] = array();
564                $retorno['mode']         = array();
565               
566                $line = array_shift($lines);
567                while (isset($line)){
568                        foreach($regexps as $regp){
569                                if(preg_match("/$regp/i",$line)){
570                                        // Recebe todas as regras criadas no servidor;
571                                        if(preg_match("/^ *#rule&&/i",$line)){
572                                                $retorno['rule'][] = $line . "\n";
573                                        }
574                                        if(preg_match("/^ *#vacation&&/i",$line)){
575                                                $retorno['vacation'][] = $line . "\n"; 
576                                        }
577                                        if(preg_match("/^ *#mode&&(.*)/i",$line)){
578                                                $retorno['mode'][]= $line . "\n";                                               
579                                        }                                       
580                                }
581                        }
582                        // Pega a proxima linha do sript;
583                        $line = array_shift($lines);
584                }
585                return $retorno;       
586        }
587               
588}//Fim da Classe
589?>
Note: See TracBrowser for help on using the repository browser.