source: branches/2.2.0.1/expressoMail1_2/inc/class.ScriptS.inc.php @ 4576

Revision 4576, 21.7 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1726 - Criacao de filtros para utilizar o tamanho da mensagem. r4552

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