source: branches/2.3/expressoMail1_2/inc/class.ScriptS.inc.php @ 5186

Revision 5186, 21.8 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2316 - Filtro por tamanho não funciona.

  • 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
[4551]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;
[5120]19    var $allofbit;
[4551]20    var $keepbit;
21    var $regexbit;
22    var $newrules = array();
23    var $newout;
24    var $teste;
25    var $EmailVoip;
26    var $EmailExpresso;
[2]27
[4551]28    function ScriptS() {
[3859]29
[4551]30        //Cria o objeto;
31        $this->SieveS = new SieveS();
[3859]32
[4551]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
[4576]37        $this->reply    = "";
38        $this->rules    = "";
39        $this->errstr   = "";
40        $this->size     = "";
[3859]41
[4551]42        $this->continuebit  = 1;
[4576]43        $this->sizebit      = 2;
[5120]44        $this->allofbit     = 4;
[4551]45        $this->keepbit      = 8;
46        $this->regexbit     = 128;
[3859]47
[4551]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
[4551]52    function init_a() {
[3859]53
[4551]54        //Abre a conexão
55        $this->SieveS->start();
[3859]56
[4551]57        $this->reply = $this->SieveS->getscript();
[3859]58
[4551]59        if (!$this->reply) {
[3859]60
[4551]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
[4551]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
[4551]84        //Fecha a conexao
85        $this->SieveS->close();
[3859]86
[4551]87        if ($this->rules)
88            return $this->rules;
89    }
[3859]90
[4551]91    function rec_rules($params) {
[3859]92
[4551]93        $newr1 = array();
94        $newr2 = array();
95        $newr3 = array();
[3859]96
[4551]97        $var_decode = rawurldecode($params['arfilter']);
98        $var_decode = preg_replace('/\n\./', '.', $var_decode);
[320]99
[4551]100        $narray = explode("_end_", $var_decode);
[3859]101
[4551]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
[4551]118        unset($tmp);
119        unset($tmp2);
120        unset($tmp3);
[2]121
[4551]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
[4551]135        $tmp = $newr3[count($newr3) - 1];
[3859]136
[4551]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
[4551]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
[4551]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
[4551]171        //Abre a conexao
172        $this->SieveS->start();
173        $this->errstr = "";
[3859]174
[4551]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
[4551]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
[4551]197        //Ativa o script;
198        $this->errstr = $this->SieveS->activatescript($this->scriptfile);
[3859]199
[4551]200        //Fecha a conexao
201        $this->SieveS->close();
[3859]202
[4551]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
[4551]216    function convert_specialchar($input) {
[4932]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);
[4551]239    }
[3859]240
[4551]241    // build the rule
242    function write_rule() {
[2]243
[4551]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 = "";
[3859]256
[4576]257        $a = 0;
258
259
[4551]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];
[5186]269            $rule['subject'] = $tmp1[5];
[4551]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);
[5120]278            $rule['allof']      = ($tmp1[8] & $this->allofbit);
[4551]279            $rule['keep']       = ($tmp1[8] & $this->keepbit);
280            $rule['regexp']     = ($tmp1[8] & $this->regexbit);
281            $rule['unconditional'] = 0;
[3859]282
[4576]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
[4551]293            if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && empty($rule['size']) && $rule['action']) {
294                $rule['unconditional'] = 1;
[3859]295
[4551]296                if ($rule['unconditional'] && ($rule['size'] == "0" || $rule['size'] == 0 ))
297                    $rule['unconditional'] = 0;
298            }
299           
300            unset($tmp1);
[3859]301
[4551]302            // Monta as regras;
303            if ($rule['status'] == 'ENABLED')
304            {
305                $activerules = 1;
[3859]306
[4551]307                // Condições para montagem das regras;
[5120]308                $anyall = "anyof";
309                if ($rule['allof'])
310                {
311                    $anyall = "allof";
312                }
313               
[4551]314                if ($rule['regexp']) {
315                    $regexused = 1;
316                }
317                $started = 0;
[3859]318
[4551]319                if (!$rule['unconditional']) {
320                    if (!$continue)
321                        $newruletext .= "els";
322                    $newruletext .= "if " . $anyall . " (";
323                    if ($rule['from']) {
324                        if (preg_match("/^\s*!/", $rule['from'])) {
325                            $newruletext .= 'not ';
326                            $rule['from'] = preg_replace("/^\s*!/", "", $rule['from']);
327                        }
328                        $match = ':contains';
329                        if (preg_match("/\*|\?/", $rule['from']))
330                            $match = ':matches';
331                        if ($rule['regexp'])
332                            $match = ':regex';
333                        $newruletext .= "header " . $match . " [\"From\"]";
334                        $newruletext .= " \"" . $rule['from'] . "\"";
335                        $started = 1;
336                    }
337                    if ($rule['to']) {
338                        if ($started)
339                            $newruletext .= ", ";
340                        if (preg_match("/^\s*!/", $rule['to'])) {
341                            $newruletext .= 'not ';
342                            $rule['to'] = preg_replace("/^\s*!/", "", $rule['to']);
343                        }
344                        $match = ':contains';
345                        if (preg_match("/\*|\?/", $rule['to']))
346                            $match = ':matches';
347                        if ($rule['regexp'])
348                            $match = ':regex';
349                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
350                        $newruletext .= " \"" . $rule['to'] . "\"";
351                        $started = 1;
352                    }
353                    if ($rule['subject']) {
[5186]354                        $rule['subject'] = " [\"" . $this->convert_specialchar($rule['subject']) . "\", \"" . base64_encode($rule['subject']) . "\"]";
[4551]355                        if ($started)
356                            $newruletext .= ", ";
357                        if (preg_match("/^\s*!/", $rule['subject'])) {
358                            $newruletext .= 'not ';
359                            $rule['subject'] = preg_replace("/^\s*!/", "", $rule['subject']);
360                        }
361                        $match = ':contains';
362                        if (preg_match("/\*|\?/", $rule['subject']))
363                            $match = ':matches';
364                        if ($rule['regexp'])
365                            $match = ':regex';
366                        $newruletext .= "header " . $match . " \"subject\"";
[4641]367                        $newruletext .= "" . $rule['subject'] . "";
[4551]368                        $started = 1;
369                    }
370                    if ($rule['field'] && $rule['field_val']) {
371                        if ($started)
372                            $newruletext .= ", ";
373                        if (preg_match("/^\s*!/", $rule['field_val'])) {
374                            $newruletext .= 'not ';
375                            $rule['field_val'] = preg_replace("/^\s*!/", "", $rule['field_val']);
376                        }
377                        $match = ':contains';
378                        if (preg_match("/\*|\?/", $rule['field_val']))
379                            $match = ':matches';
380                        if ($rule['regexp'])
381                            $match = ':regex';
382                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
383                        $newruletext .= " \"" . $rule['field_val'] . "\"";
384                        $started = 1;
385                    }
[3859]386
[4551]387                    if ($rule['size'] != '')
388                    {
[4576]389                        if ( $rule['size'] == 0 && $rule['gthan'] )
[4551]390                        {
391                            $xthan = " :over ";
392                           
393                            if ($started)
394                                $newruletext .= ", ";
[3859]395
[4551]396                            $newruletext .= "size " . $xthan . "0K";
397                            $started = 1;
398                        }
[3859]399
[4576]400                        if ( $rule['size'] > 0 )
401                        {
[4551]402                            $xthan = " :under ";
[4576]403
[4551]404                            if ($rule['gthan'])
405                                $xthan = " :over ";
406                            if ($started)
407                                $newruletext .= ", ";
[3859]408
[4551]409                            $newruletext .= "size " . $xthan . $rule['size'] . "K";
410                            $started = 1;
411                        }
412                    }
413                }
[3859]414
[4551]415                // Don't write half rule!
416                if (strlen($newruletext) == 0)
417                    return false;
418                // Actions
419                if (!$rule['unconditional'])
420                    $newruletext .= ") {\n\t";
[3859]421
[4551]422                if (preg_match("/folder/i", $rule['action'])) {
423                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
424                }
[3859]425
[4551]426                if (preg_match("/reject/i", $rule['action'])) {
427                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
428                    $rejectused = 1;
429                }
430                if (preg_match("/flagged/i", $rule['action'])) {
431                    $newruletext .= "addflag \"\\\\Flagged\";";
432                    $flaggedused = 1;
433                }
434                if (preg_match("/address/i", $rule['action'])) {
435                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
436                }
[3859]437
[4551]438                if (preg_match("/notify/i", $rule['action'])) {
439                    $newruletext .= "notify :method \"mailto\" :options [\"" . $this->EmailVoip . "\"]:" .
440                            "message \"<expressovoip><from>" . $this->EmailExpresso . "</from>" .
441                            "<br/><Subject>" . utf8_encode($tmpSubject) . "</Subject></expressovoip>\";";
442                    $notify = 1;
443                }
[3859]444
[4551]445                if (preg_match("/discard/i", $rule['action'])) {
446                    $newruletext .= "discard;";
447                }
[4576]448
449                if ($rule['keep'] )
450                {
[4551]451                    $newruletext .= "\n\tfileinto \"INBOX\";";
[4576]452                }
453
[4551]454                if (!$rule['unconditional'])
[4576]455                {
[4551]456                    $newruletext .= "\n}";
[4576]457                }
[3859]458
[4551]459                $continue = 0;
460                if ($rule['continue'])
461                    $continue = 1;
462                if ($rule['unconditional'])
463                    $continue = 1;
[3859]464
[4551]465                $newscriptbody .= $newruletext . "\n\n";
466                unset($newruletext);
467            }
468        }// Fim do Foreach;
469        $this->teste = $newscriptbody;
470        // Para a regras fora do escritorio;
471        unset($tmp);
472        if ($this->newout != "") {
473            $aux = explode("&&", $this->newout);
474            $vacation['days'] = $aux[1];
475            $vacation['addresses'] = $aux[2];
476            $vacation['text'] = preg_replace("/\\\\n/", "\r\n", $aux[3]);
477            $vacation['status'] = $aux[4];
478        }
[3859]479
[4551]480        // Monta a regra para fora do escritorio;
481        if ($vacation['status'] == 'on') {
482            $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
483            $newscriptbody .= $vacation['addresses'];
484            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
485        }
[3859]486
[4551]487        // Cria o cabeçalho do arquivo;
488        $newscripthead = "";
489        $newscripthead .= "#Mail filter rules for " . $this->username . "\n";
490        $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
491        $newscripthead .= "\n";
[2]492
[4551]493        // Continuação do cabeçalho do arquivo;                 
494        if ($activerules) {
495            $newscripthead .= "require [\"fileinto\"";
[3859]496
[4551]497            if ($notify) {
498                $newscripthead .= ",\"notify\"";
499            }
500            if ($regexused) {
501                $newscripthead .= ",\"regex\"";
502            }
503            if ($rejectused) {
504                $newscripthead .= ",\"reject\"";
505            }
506            if ($flaggedused) {
507                $newscripthead .= ",\"imapflags\"";
508            }
509            if ($this->newout && $vacation['status'] == 'on') {
510                $newscripthead .= ",\"vacation\"";
511            }
512            $newscripthead .= "];\n\n";
513        } else {
514            if ($vacation && $vacation['status'] == 'on') {
515                $newscripthead .= "require [\"vacation\"];\n\n";
516            }
517        }
[3859]518
[4551]519        // Cria o rodapé do arquivo;
520        $newscriptfoot = "";
521        $newscriptfoot .= "##PSEUDO script start\n";
522        // Lê as regras;
523        foreach ($this->newrules as $tmp) {
524            $newscriptfoot .= preg_replace("/[\\n\\r]/", " ", $tmp) . "\n";
525        }
526        // Lê as regras fora do escritório;
527        if ($this->newout != "") {
[4851]528            $newscriptfoot .= preg_replace("/[\\n\\r]/", "%0A", $this->newout) . "\n";
[4551]529        }
530        $newscriptfoot .= "#mode&&basic\n";
[2]531
[4551]532        $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
533        // Destroi as variaveis;
534        unset($rule);
535        unset($vacation);
536        unset($activerules);
537        unset($regexused);
538        unset($rejectused);
539        unset($flaggedused);
540        unset($newscripthead);
541        unset($newscriptbody);
542        unset($newscriptfoot);
543        unset($continue);
544        unset($this->newrules);
545        unset($this->newout);
[3859]546
[4551]547        // Retorna o script construido;
548        return $newscript;
549    }
[2]550
[3859]551// Fim da Função
[4551]552    // Cria o script sieve, caso nao possua;
553    function createScript() {
[3859]554
[4551]555        // Cria o cabeçalho do arquivo;
556        $newScriptHead = "";
557        $newScriptHead .= "#Mail filter rules for " . $this->username . "\n";
558        $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail ';
559        $newScriptHead .= "\n";
[2]560
[4551]561        //Cria o rodapé do arquivo;
562        $newScriptFoot = "";
563        $newScriptFoot .= "##PSEUDO Script Start\n";
564        $newScriptFoot .= "#mode&&basic\n";
[3859]565
[4551]566        //Para passar para o arquivo;
567        $newScript = $newScriptHead . $newScriptFoot;
[2]568
[4551]569        return $newScript;
570    }
[3859]571
[4551]572    //Lê o conteúdo do script;
573    function readScript($scriptName) {
[3859]574
[4551]575        // Verifica se a conexão foi bem sucedida;
576        if (!$scriptName) {
577            $this->errstr = "Não foi possível conectar com o Servidor";
578            return "false 2";
579        }
[3859]580
[4551]581        // Recebe o conteúdo do array;
582        $lines = array();
583        $lines = preg_split("/\n/", $scriptName);
[3859]584
[4551]585        // Pega o tamanho da regra na primeira do script;
586        $size_rule = array_shift($lines);
[3859]587
[4551]588        // Recebe o tamanho do script, pela primeira linha;
589        $this->size = trim($size_rule);
[3859]590
[4551]591        // Verifica a composição do script;
592        $line = array_shift($lines);
593        if (!preg_match("/^# ?Mail(.*)rules for/", $line)) {
594            $this->errstr = "Formato nao reconhecido";
595            return false;
596        }
[3859]597
[4551]598        // Variaveis para a regra e o campo ferias;
599        $regexps = array('^ *##PSEUDO', '^ *#rule', '^ *#vacation', '^ *#mode');
600        $retorno['rule'] = array();
601        $retorno['vacation'] = array();
602        $retorno['mode'] = array();
[3859]603
[4551]604        $line = array_shift($lines);
605        while (isset($line)) {
606            foreach ($regexps as $regp) {
607                if (preg_match("/$regp/i", $line)) {
608                    // Recebe todas as regras criadas no servidor;
609                    if (preg_match("/^ *#rule&&/i", $line)) {
610                        $retorno['rule'][] = $line . "\n";
611                    }
612                    if (preg_match("/^ *#vacation&&/i", $line)) {
613                        $retorno['vacation'][] = $line . "\n";
614                    }
615                    if (preg_match("/^ *#mode&&(.*)/i", $line)) {
616                        $retorno['mode'][] = $line . "\n";
617                    }
618                }
619            }
620            // Pega a proxima linha do sript;
621            $line = array_shift($lines);
622        }
623        return $retorno;
624    }
[3859]625
626}
627
628//Fim da Classe
[51]629?>
Note: See TracBrowser for help on using the repository browser.