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

Revision 4789, 21.1 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1820 - Aplicada correção para cirar filtros com acentuação. r4641

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3//Inclui o arquivo contendo a classe SieveS;
4include('class.SieveS.inc.php');
5
6class ScriptS {
7
8    //Declaração de Variáveis;
9    var $SieveS;   // Var para criação do objeto;
10    var $reply;  // Var para resposta;
11    var $scriptfile;  // Nome do script;
12    var $username;   // Nome do usuario;
13    var $rules;  // Regras do sieve;
14    var $errstr;   // Erros retornados;
15    var $size;  // Tamanho;
16    var $so;  // Verifica se a regra foi criada por outro tipo serviço de filtros;
17    var $continuebit;
18    var $sizebit;
19    var $anyofbit;
20    var $keepbit;
21    var $regexbit;
22    var $newrules = array();
23    var $newout;
24    var $teste;
25    var $EmailVoip;
26    var $EmailExpresso;
27
28    function ScriptS() {
29
30        //Cria o objeto;
31        $this->SieveS = new SieveS();
32
33        //$this->scriptfile = $GLOBALS['HTTP_SESSION_VARS']['phpgw_info']['expressomail']['user']['account_lid'];
34        $this->scriptfile = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
35        $this->username = $this->scriptfile;
36
37        $this->reply    = "";
38        $this->rules    = "";
39        $this->errstr   = "";
40        $this->size     = "";
41
42        $this->continuebit  = 1;
43        $this->sizebit      = 2;
44        $this->anyofbit     = 4;
45        $this->keepbit      = 8;
46        $this->regexbit     = 128;
47
48        $this->EmailVoip = trim($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_email_redirect']);
49        $this->EmailExpresso = trim($_SESSION['phpgw_info']['expressomail']['user']['email']);
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            } else {
77                $this->reply = $this->SieveS->getscript();
78                $this->rules = $this->readScript($this->reply);
79            }
80        } else {
81            $this->rules = $this->readScript($this->reply);
82        }
83
84        //Fecha a conexao
85        $this->SieveS->close();
86
87        if ($this->rules)
88            return $this->rules;
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            if ($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
190                error_log(date("D M j G:i:s T Y") . ": SieveError, Invalid rule for "
191                        . $_SESSION['phpgw_info']['expressomail']['user']['userid'] . "=>"
192                        . $this->teste . "\nRule:"
193                        . $var_decode . "\n", 3, $error_log_file);
194            return "Invalid rule\n" . $this->teste;
195        }
196
197        //Ativa o script;
198        $this->errstr = $this->SieveS->activatescript($this->scriptfile);
199
200        //Fecha a conexao
201        $this->SieveS->close();
202
203        if ($this->errstr) {
204            return "Ok";
205        } else {
206            if ($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
207                error_log(date("D M j G:i:s T Y")
208                        . ": SieveError, Problem for "
209                        . $_SESSION['phpgw_info']['expressomail']['user']['userid'] . "=>"
210                        . " "
211                        . $this->SieveS->errstr . "\n", 3, $error_log_file);
212            return "Problemas na criação do arquivo!\n" . $this->teste;
213        }
214    }
215
216    function convert_specialchar($input) {
217        $temp_input = $input; 
218        $temp_input = imap_8bit($temp_input);
219                 
220        $patterns[0] = '/ /';
221        $replacements[0] = '_'; 
222        $temp_input = preg_replace($patterns, $replacements, $temp_input); 
223        return ($temp_input);
224    }
225
226    // build the rule
227    function write_rule() {
228
229        // Variaveis;
230        $rule = array();
231        $vacation = array();
232        $newruletext = "";
233        $activerules = 0;
234        $regexused = 0;
235        $rejectused = 0;
236        $notify = 0;
237        $flaggedused = 0;
238        $newscriptbody = "";
239        $continue = 1;
240        $tmpSubject = "";
241
242        $a = 0;
243
244
245        // Recebe os valores das regras;
246        foreach ($this->newrules as $tmp)
247        {
248            $tmp1 = explode("&&", $tmp);
249            $rule['priority']   = $tmp1[1];
250            $rule['status']     = $tmp1[2];
251            $rule['from']       = $this->convert_specialchar($tmp1[3]);
252            $rule['to']         = $this->convert_specialchar($tmp1[4]);
253            $tmpSubject         = $tmp1[5];
254            $rule['subject']    = $rule['subject'] = " [\"" . $this->convert_specialchar($tmp1[5]) . "\", \"" . base64_encode($tmp1[5]) . "\"]";
255            $rule['action']     = $tmp1[6];
256            $rule['action_arg'] = utf8_encode(preg_replace("/\\r\\n/", "\r\n", $tmp1[7]));
257            $rule['flg']        = $tmp1[8];
258            $rule['field']      = $tmp1[9];
259            $rule['field_val']  = $tmp1[10];
260            $rule['size']       = trim($tmp1[11]);
261            $rule['continue']   = ($tmp1[8] & $this->continuebit);
262            $rule['gthan']      = ($tmp1[8] & $this->sizebit);
263            $rule['anyof']      = ($tmp1[8] & $this->anyofbit);
264            $rule['keep']       = ($tmp1[8] & $this->keepbit);
265            $rule['regexp']     = ($tmp1[8] & $this->regexbit);
266            $rule['unconditional'] = 0;
267
268            if( $a < 2 )
269            {
270                error_log( print_r($tmp, true), 3, "/tmp/log" );
271
272                error_log( print_r($rule, true), 3, "/tmp/log" );
273
274                $a++;
275            }
276
277
278            if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && empty($rule['size']) && $rule['action']) {
279                $rule['unconditional'] = 1;
280
281                if ($rule['unconditional'] && ($rule['size'] == "0" || $rule['size'] == 0 ))
282                    $rule['unconditional'] = 0;
283            }
284           
285            unset($tmp1);
286
287            // Monta as regras;
288            if ($rule['status'] == 'ENABLED')
289            {
290                $activerules = 1;
291
292                // Condições para montagem das regras;
293                $anyall = "allof";
294                if ($rule['anyof'])
295                    $anyall = "anyof";
296                if ($rule['regexp']) {
297                    $regexused = 1;
298                }
299                $started = 0;
300
301                if (!$rule['unconditional']) {
302                    if (!$continue)
303                        $newruletext .= "els";
304                    $newruletext .= "if " . $anyall . " (";
305                    if ($rule['from']) {
306                        if (preg_match("/^\s*!/", $rule['from'])) {
307                            $newruletext .= 'not ';
308                            $rule['from'] = preg_replace("/^\s*!/", "", $rule['from']);
309                        }
310                        $match = ':contains';
311                        if (preg_match("/\*|\?/", $rule['from']))
312                            $match = ':matches';
313                        if ($rule['regexp'])
314                            $match = ':regex';
315                        $newruletext .= "header " . $match . " [\"From\"]";
316                        $newruletext .= " \"" . $rule['from'] . "\"";
317                        $started = 1;
318                    }
319                    if ($rule['to']) {
320                        if ($started)
321                            $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']))
328                            $match = ':matches';
329                        if ($rule['regexp'])
330                            $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)
337                            $newruletext .= ", ";
338                        if (preg_match("/^\s*!/", $rule['subject'])) {
339                            $newruletext .= 'not ';
340                            $rule['subject'] = preg_replace("/^\s*!/", "", $rule['subject']);
341                        }
342                        $match = ':contains';
343                        if (preg_match("/\*|\?/", $rule['subject']))
344                            $match = ':matches';
345                        if ($rule['regexp'])
346                            $match = ':regex';
347                        $newruletext .= "header " . $match . " \"subject\"";
348                        $newruletext .= "" . $rule['subject'] . "";
349                        $started = 1;
350                    }
351                    if ($rule['field'] && $rule['field_val']) {
352                        if ($started)
353                            $newruletext .= ", ";
354                        if (preg_match("/^\s*!/", $rule['field_val'])) {
355                            $newruletext .= 'not ';
356                            $rule['field_val'] = preg_replace("/^\s*!/", "", $rule['field_val']);
357                        }
358                        $match = ':contains';
359                        if (preg_match("/\*|\?/", $rule['field_val']))
360                            $match = ':matches';
361                        if ($rule['regexp'])
362                            $match = ':regex';
363                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
364                        $newruletext .= " \"" . $rule['field_val'] . "\"";
365                        $started = 1;
366                    }
367
368                    if ($rule['size'] != '')
369                    {
370                        if ( $rule['size'] == 0 && $rule['gthan'] )
371                        {
372                            $xthan = " :over ";
373                           
374                            if ($started)
375                                $newruletext .= ", ";
376
377                            $newruletext .= "size " . $xthan . "0K";
378                            $started = 1;
379                        }
380
381                        if ( $rule['size'] > 0 )
382                        {
383                            $xthan = " :under ";
384
385                            if ($rule['gthan'])
386                                $xthan = " :over ";
387                            if ($started)
388                                $newruletext .= ", ";
389
390                            $newruletext .= "size " . $xthan . $rule['size'] . "K";
391                            $started = 1;
392                        }
393                    }
394                }
395
396                // Don't write half rule!
397                if (strlen($newruletext) == 0)
398                    return false;
399                // Actions
400                if (!$rule['unconditional'])
401                    $newruletext .= ") {\n\t";
402
403                if (preg_match("/folder/i", $rule['action'])) {
404                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
405                }
406
407                if (preg_match("/reject/i", $rule['action'])) {
408                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
409                    $rejectused = 1;
410                }
411                if (preg_match("/flagged/i", $rule['action'])) {
412                    $newruletext .= "addflag \"\\\\Flagged\";";
413                    $flaggedused = 1;
414                }
415                if (preg_match("/address/i", $rule['action'])) {
416                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
417                }
418
419                if (preg_match("/notify/i", $rule['action'])) {
420                    $newruletext .= "notify :method \"mailto\" :options [\"" . $this->EmailVoip . "\"]:" .
421                            "message \"<expressovoip><from>" . $this->EmailExpresso . "</from>" .
422                            "<br/><Subject>" . utf8_encode($tmpSubject) . "</Subject></expressovoip>\";";
423                    $notify = 1;
424                }
425
426                if (preg_match("/discard/i", $rule['action'])) {
427                    $newruletext .= "discard;";
428                }
429
430                if ($rule['keep'] )
431                {
432                    $newruletext .= "\n\tfileinto \"INBOX\";";
433                }
434
435                if (!$rule['unconditional'])
436                {
437                    $newruletext .= "\n}";
438                }
439
440                $continue = 0;
441                if ($rule['continue'])
442                    $continue = 1;
443                if ($rule['unconditional'])
444                    $continue = 1;
445
446                $newscriptbody .= $newruletext . "\n\n";
447                unset($newruletext);
448            }
449        }// Fim do Foreach;
450        $this->teste = $newscriptbody;
451        // Para a regras fora do escritorio;
452        unset($tmp);
453        if ($this->newout != "") {
454            $aux = explode("&&", $this->newout);
455            $vacation['days'] = $aux[1];
456            $vacation['addresses'] = $aux[2];
457            $vacation['text'] = preg_replace("/\\\\n/", "\r\n", $aux[3]);
458            $vacation['status'] = $aux[4];
459        }
460
461        // Monta a regra para fora do escritorio;
462        if ($vacation['status'] == 'on') {
463            $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
464            $newscriptbody .= $vacation['addresses'];
465            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
466        }
467
468        // Cria o cabeçalho do arquivo;
469        $newscripthead = "";
470        $newscripthead .= "#Mail filter rules for " . $this->username . "\n";
471        $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
472        $newscripthead .= "\n";
473
474        // Continuação do cabeçalho do arquivo;                 
475        if ($activerules) {
476            $newscripthead .= "require [\"fileinto\"";
477
478            if ($notify) {
479                $newscripthead .= ",\"notify\"";
480            }
481            if ($regexused) {
482                $newscripthead .= ",\"regex\"";
483            }
484            if ($rejectused) {
485                $newscripthead .= ",\"reject\"";
486            }
487            if ($flaggedused) {
488                $newscripthead .= ",\"imapflags\"";
489            }
490            if ($this->newout && $vacation['status'] == 'on') {
491                $newscripthead .= ",\"vacation\"";
492            }
493            $newscripthead .= "];\n\n";
494        } else {
495            if ($vacation && $vacation['status'] == 'on') {
496                $newscripthead .= "require [\"vacation\"];\n\n";
497            }
498        }
499
500        // Cria o rodapé do arquivo;
501        $newscriptfoot = "";
502        $newscriptfoot .= "##PSEUDO script start\n";
503        // Lê as regras;
504        foreach ($this->newrules as $tmp) {
505            $newscriptfoot .= preg_replace("/[\\n\\r]/", " ", $tmp) . "\n";
506        }
507        // Lê as regras fora do escritório;
508        if ($this->newout != "") {
509            $newscriptfoot .= preg_replace("/[\\n\\r]/", " ", $this->newout) . "\n";
510        }
511        $newscriptfoot .= "#mode&&basic\n";
512
513        $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
514
515        // Destroi as variaveis;
516        unset($rule);
517        unset($vacation);
518        unset($activerules);
519        unset($regexused);
520        unset($rejectused);
521        unset($flaggedused);
522        unset($newscripthead);
523        unset($newscriptbody);
524        unset($newscriptfoot);
525        unset($continue);
526        unset($this->newrules);
527        unset($this->newout);
528
529        // Retorna o script construido;
530        return $newscript;
531    }
532
533// Fim da Função
534    // Cria o script sieve, caso nao possua;
535    function createScript() {
536
537        // Cria o cabeçalho do arquivo;
538        $newScriptHead = "";
539        $newScriptHead .= "#Mail filter rules for " . $this->username . "\n";
540        $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail ';
541        $newScriptHead .= "\n";
542
543        //Cria o rodapé do arquivo;
544        $newScriptFoot = "";
545        $newScriptFoot .= "##PSEUDO Script Start\n";
546        $newScriptFoot .= "#mode&&basic\n";
547
548        //Para passar para o arquivo;
549        $newScript = $newScriptHead . $newScriptFoot;
550
551        return $newScript;
552    }
553
554    //Lê o conteúdo do script;
555    function readScript($scriptName) {
556
557        // Verifica se a conexão foi bem sucedida;
558        if (!$scriptName) {
559            $this->errstr = "Não foi possível conectar com o Servidor";
560            return "false 2";
561        }
562
563        // Recebe o conteúdo do array;
564        $lines = array();
565        $lines = preg_split("/\n/", $scriptName);
566
567        // Pega o tamanho da regra na primeira do script;
568        $size_rule = array_shift($lines);
569
570        // Recebe o tamanho do script, pela primeira linha;
571        $this->size = trim($size_rule);
572
573        // Verifica a composição do script;
574        $line = array_shift($lines);
575        if (!preg_match("/^# ?Mail(.*)rules for/", $line)) {
576            $this->errstr = "Formato nao reconhecido";
577            return false;
578        }
579
580        // Variaveis para a regra e o campo ferias;
581        $regexps = array('^ *##PSEUDO', '^ *#rule', '^ *#vacation', '^ *#mode');
582        $retorno['rule'] = array();
583        $retorno['vacation'] = array();
584        $retorno['mode'] = array();
585
586        $line = array_shift($lines);
587        while (isset($line)) {
588            foreach ($regexps as $regp) {
589                if (preg_match("/$regp/i", $line)) {
590                    // Recebe todas as regras criadas no servidor;
591                    if (preg_match("/^ *#rule&&/i", $line)) {
592                        $retorno['rule'][] = $line . "\n";
593                    }
594                    if (preg_match("/^ *#vacation&&/i", $line)) {
595                        $retorno['vacation'][] = $line . "\n";
596                    }
597                    if (preg_match("/^ *#mode&&(.*)/i", $line)) {
598                        $retorno['mode'][] = $line . "\n";
599                    }
600                }
601            }
602            // Pega a proxima linha do sript;
603            $line = array_shift($lines);
604        }
605        return $retorno;
606    }
607
608}
609
610//Fim da Classe
611?>
Note: See TracBrowser for help on using the repository browser.