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 *
RevLine 
[2]1<?php
[3859]2
[2]3//Inclui o arquivo contendo a classe SieveS;
4include('class.SieveS.inc.php');
5
6class ScriptS {
[3859]7
[4706]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;
[2]27
[4706]28    function ScriptS() {
[3859]29
[4706]30        //Cria o objeto;
31        $this->SieveS = new SieveS();
[3859]32
[4706]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;
[3859]36
[4735]37        $this->reply    = "";
38        $this->rules    = "";
39        $this->errstr   = "";
40        $this->size     = "";
[3859]41
[4706]42        $this->continuebit  = 1;
[4735]43        $this->sizebit      = 2;
[4706]44        $this->anyofbit     = 4;
45        $this->keepbit      = 8;
46        $this->regexbit     = 128;
[3859]47
[4706]48        $this->EmailVoip = trim($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_email_redirect']);
49        $this->EmailExpresso = trim($_SESSION['phpgw_info']['expressomail']['user']['email']);
50    }
[3859]51
[4706]52    function init_a() {
[3859]53
[4706]54        //Abre a conexão
55        $this->SieveS->start();
[3859]56
[4706]57        $this->reply = $this->SieveS->getscript();
[3859]58
[4706]59        if (!$this->reply) {
[3859]60
[4706]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);
[3859]71
[4706]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        }
[2]83
[4706]84        //Fecha a conexao
85        $this->SieveS->close();
[3859]86
[4706]87        if ($this->rules)
88            return $this->rules;
89    }
[3859]90
[4706]91    function rec_rules($params) {
[3859]92
[4706]93        $newr1 = array();
94        $newr2 = array();
95        $newr3 = array();
[3859]96
[4706]97        $var_decode = rawurldecode($params['arfilter']);
98        $var_decode = preg_replace('/\n\./', '.', $var_decode);
[320]99
[4706]100        $narray = explode("_end_", $var_decode);
[3859]101
[4706]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        }
[3859]117
[4706]118        unset($tmp);
119        unset($tmp2);
120        unset($tmp3);
[2]121
[4706]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        }
[3859]134
[4706]135        $tmp = $newr3[count($newr3) - 1];
[3859]136
[4706]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        }
[3859]147
[4706]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));
[3859]155
[4706]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));
[3859]170
[4706]171        //Abre a conexao
172        $this->SieveS->start();
173        $this->errstr = "";
[3859]174
[4706]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         */
[2]182
[4706]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        }
[3859]196
[4706]197        //Ativa o script;
198        $this->errstr = $this->SieveS->activatescript($this->scriptfile);
[3859]199
[4706]200        //Fecha a conexao
201        $this->SieveS->close();
[3859]202
[4706]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    }
[2]215
[4706]216    function convert_specialchar($input) {
[4789]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);
[4706]224    }
[2]225
[4706]226    // build the rule
227    function write_rule() {
[3859]228
[4706]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 = "";
[3859]241
[4735]242        $a = 0;
243
244
[4706]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];
[4789]254            $rule['subject']    = $rule['subject'] = " [\"" . $this->convert_specialchar($tmp1[5]) . "\", \"" . base64_encode($tmp1[5]) . "\"]";
[4706]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;
[3859]267
[4735]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
[4706]278            if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && empty($rule['size']) && $rule['action']) {
279                $rule['unconditional'] = 1;
[3859]280
[4706]281                if ($rule['unconditional'] && ($rule['size'] == "0" || $rule['size'] == 0 ))
282                    $rule['unconditional'] = 0;
283            }
284           
285            unset($tmp1);
[3859]286
[4706]287            // Monta as regras;
288            if ($rule['status'] == 'ENABLED')
289            {
290                $activerules = 1;
[3859]291
[4706]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;
[3859]300
[4706]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\"";
[4789]348                        $newruletext .= "" . $rule['subject'] . "";
[4706]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                    }
[3859]367
[4706]368                    if ($rule['size'] != '')
369                    {
[4735]370                        if ( $rule['size'] == 0 && $rule['gthan'] )
[4706]371                        {
372                            $xthan = " :over ";
373                           
374                            if ($started)
375                                $newruletext .= ", ";
[3859]376
[4706]377                            $newruletext .= "size " . $xthan . "0K";
378                            $started = 1;
379                        }
[3859]380
[4735]381                        if ( $rule['size'] > 0 )
382                        {
[4706]383                            $xthan = " :under ";
[4735]384
[4706]385                            if ($rule['gthan'])
386                                $xthan = " :over ";
387                            if ($started)
388                                $newruletext .= ", ";
[3859]389
[4706]390                            $newruletext .= "size " . $xthan . $rule['size'] . "K";
391                            $started = 1;
392                        }
393                    }
394                }
[3859]395
[4706]396                // Don't write half rule!
397                if (strlen($newruletext) == 0)
398                    return false;
399                // Actions
400                if (!$rule['unconditional'])
401                    $newruletext .= ") {\n\t";
[3859]402
[4706]403                if (preg_match("/folder/i", $rule['action'])) {
404                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
405                }
[3859]406
[4706]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                }
[3859]418
[4706]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                }
[3859]425
[4706]426                if (preg_match("/discard/i", $rule['action'])) {
427                    $newruletext .= "discard;";
428                }
[4735]429
430                if ($rule['keep'] )
431                {
[4706]432                    $newruletext .= "\n\tfileinto \"INBOX\";";
[4735]433                }
434
[4706]435                if (!$rule['unconditional'])
[4735]436                {
[4706]437                    $newruletext .= "\n}";
[4735]438                }
[3859]439
[4706]440                $continue = 0;
441                if ($rule['continue'])
442                    $continue = 1;
443                if ($rule['unconditional'])
444                    $continue = 1;
[3859]445
[4706]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        }
[3859]460
[4706]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        }
[2]467
[4706]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";
[3859]473
[4706]474        // Continuação do cabeçalho do arquivo;                 
475        if ($activerules) {
476            $newscripthead .= "require [\"fileinto\"";
[3859]477
[4706]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        }
[2]499
[4706]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";
[3859]512
[4706]513        $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
[3859]514
[4706]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);
[2]528
[4706]529        // Retorna o script construido;
530        return $newscript;
531    }
532
[3859]533// Fim da Função
[4706]534    // Cria o script sieve, caso nao possua;
535    function createScript() {
[3859]536
[4706]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";
[2]542
[4706]543        //Cria o rodapé do arquivo;
544        $newScriptFoot = "";
545        $newScriptFoot .= "##PSEUDO Script Start\n";
546        $newScriptFoot .= "#mode&&basic\n";
[3859]547
[4706]548        //Para passar para o arquivo;
549        $newScript = $newScriptHead . $newScriptFoot;
[2]550
[4706]551        return $newScript;
552    }
[3859]553
[4706]554    //Lê o conteúdo do script;
555    function readScript($scriptName) {
[3859]556
[4706]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        }
[3859]562
[4706]563        // Recebe o conteúdo do array;
564        $lines = array();
565        $lines = preg_split("/\n/", $scriptName);
[3859]566
[4706]567        // Pega o tamanho da regra na primeira do script;
568        $size_rule = array_shift($lines);
[3859]569
[4706]570        // Recebe o tamanho do script, pela primeira linha;
571        $this->size = trim($size_rule);
[3859]572
[4706]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        }
[3859]579
[4706]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();
[3859]585
[4706]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    }
[3859]607
608}
609
610//Fim da Classe
[51]611?>
Note: See TracBrowser for help on using the repository browser.