source: sandbox/2.2.0.2/expressoMail1_2/inc/class.ScriptS.inc.php @ 4242

Revision 4242, 15.9 KB checked in by airton, 13 years ago (diff)

Ticket #1848 - Problema de codificacao de caracteres acentuados no gerenciamento de filtros de mensagens

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