source: branches/2.2/expressoMail1_2/inc/class.ScriptS.inc.php @ 3441

Revision 3441, 17.4 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1290 - Marcação de importante para mensagens na edição de filtros

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2//Inclui o arquivo contendo a classe SieveS;
3include('class.SieveS.inc.php');
4
5class ScriptS {
6       
7        //Declaração de Variáveis;
8        var $SieveS;                                    // Var para criação do objeto;
9        var $reply;                                             // Var para resposta;
10        var $scriptfile;                                // Nome do script;
11        var $username;                                  // Nome do usuario;
12        var $rules;                                             // Regras do sieve;
13        var $errstr;                                    // Erros retornados;
14        var $size;                                              // Tamanho;
15        var $so;                                                // Verifica se a regra foi criada por outro tipo serviço de filtros;
16        var $continuebit;
17        var $sizebit;
18        var $anyofbit;
19        var $keepbit;
20        var $regexbit;
21        var $newrules = array();
22        var $newout;
23        var $teste;
24        var $EmailVoip;
25        var $EmailExpresso;
26       
27        function ScriptS(){
28
29                //Cria o objeto;
30                $this->SieveS     = new SieveS();
31               
32                //$this->scriptfile = $GLOBALS['HTTP_SESSION_VARS']['phpgw_info']['expressomail']['user']['account_lid'];
33                $this->scriptfile = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
34                $this->username   = $this->scriptfile;
35               
36                $this->reply      = "";
37                $this->rules      = "";
38                $this->errstr     = "";
39                $this->size               = "";
40               
41                $this->continuebit      = 1;
42        $this->sizebit          = 1;
43        $this->anyofbit         = 4;
44        $this->keepbit          = 8;
45        $this->regexbit         = 128;
46       
47        $this->EmailVoip = trim($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_email_redirect']);
48        $this->EmailExpresso = trim($_SESSION['phpgw_info']['expressomail']['user']['email']);
49       
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                        }
77                        else{
78                                $this->reply = $this->SieveS->getscript();
79                                $this->rules = $this->readScript($this->reply);
80                        }
81                }else{
82                        $this->rules = $this->readScript($this->reply);
83                }               
84
85                //Fecha a conexao
86                $this->SieveS->close();
87                       
88                if($this->rules)
89                        return $this->rules;
90                       
91        }
92       
93        function rec_rules($params){
94               
95                $newr1  = array();
96                $newr2  = array();
97                $newr3  = array();
98       
99                $var_decode = rawurldecode($params['arfilter']);
100                $var_decode = preg_replace('/\n\./', '.', $var_decode);
101               
102                $narray  = explode("_end_",$var_decode);
103
104                foreach($narray as $key=>$tmp){
105                        if($tmp != ""){
106                                $newr1[] = $tmp;
107                        }
108                }
109                unset($key);
110                unset($tmp);
111                foreach($newr1 as $key=>$tmp){
112                        $tmp2 = explode("_begin_##", $tmp);
113                        foreach($tmp2 as $tmp3){
114                                if($tmp3 != ""){
115                                        $newr2[] = trim($tmp3);         
116                                }       
117                        }       
118                }
119               
120                unset($tmp);
121                unset($tmp2);
122                unset($tmp3);
123
124                foreach($newr2 as $tmp){
125                        if(trim($tmp) != ""){   
126                                $tmp2 = explode("##",$tmp);
127                                foreach($tmp2 as $tmp3){
128                                        $tmp4 .= trim($tmp3) . "&&";   
129                                }
130                                $newr3[] = substr($tmp4,0,(strlen($tmp4)-4));                   
131                                unset($tmp2);
132                                unset($tmp3);
133                                unset($tmp4);
134                        }
135                }
136               
137                $tmp = $newr3[count($newr3)-1];
138               
139                if(substr($tmp,0,9) == "#vacation"){
140                        $this->newout = array_pop($newr3);
141                        foreach($newr3 as $key=>$tmp){
142                                $this->newrules[] = $tmp;
143                        }
144                }else{
145                        foreach($newr3 as $tmp){
146                                $this->newrules[] = $tmp;       
147                        }
148                }
149                               
150                unset($tmp);
151                $tmp  = explode("&&",$this->newout);
152                $tmp1 = explode(",",$tmp[2]);
153                foreach($tmp1 as $key=>$tmp2){
154                        $tmp3 .= stripslashes(trim($tmp2)).", ";
155                }
156                $tmp3 = substr($tmp3,0,(strlen($tmp3)-2));
157               
158                unset($tmp);
159                unset($tmp1);
160                unset($tmp2);
161                unset($key);
162                $tmp = explode("&&",$this->newout);
163                foreach($tmp as $key=>$tmp1){
164                        if($key == 2){
165                                $tmp2 .= trim($tmp3) . "&&";   
166                        }else{
167                                $tmp2 .= trim($tmp1) . "&&";   
168                        }       
169                }
170                unset($this->newout);
171                $this->newout = substr($tmp2,0,(strlen($tmp2)-2));
172               
173                //Abre a conexao
174                $this->SieveS->start();
175                $this->errstr = "";
176               
177                // Escreve a nova regra;
178                $this->reply = $this->SieveS->getscript();
179                /*
180                if($this->reply){
181                        $this->errstr = $this->SieveS->deletescript($this->scriptfile);         
182                }
183                */
184
185                $error_log_file="/home/expressolivre/sieve_error.log";
186                //Escreve a(s) nova(s) regra(s);
187                $newrule = $this->write_rule();
188                if (strlen($newrule) > 0)
189                        $this->errstr = $this->SieveS->putscript($this->scriptfile,$newrule);
190                else
191                {
192                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
193                                error_log(date("D M j G:i:s T Y").": SieveError, Invalid rule for "
194                                        .$_SESSION['phpgw_info']['expressomail']['user']['userid']."=>"
195                                        .$this->teste."\nRule:"
196                                        .$var_decode."\n", 3, $error_log_file);
197                        return "Invalid rule\n" . $this->teste;
198                }
199               
200                //Ativa o script;
201                $this->errstr = $this->SieveS->activatescript($this->scriptfile);
202               
203                //Fecha a conexao
204                $this->SieveS->close();
205               
206                if($this->errstr)
207                {
208                        return "Ok";
209                }
210                else
211                {
212                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
213                        error_log(date("D M j G:i:s T Y")
214                        .": SieveError, Problem for "
215                        .$_SESSION['phpgw_info']['expressomail']['user']['userid']."=>"
216                        ." "
217                        .$this->SieveS->errstr."\n", 3, $error_log_file);
218                        return "Problemas na criação do arquivo!\n" . $this->teste;
219                }
220        }
221
222    function convert_specialchar($input)
223    {
224      $special_char = false;
225          for ( $i = 0; $i < strlen($input); $i++ )
226          {
227                if ( preg_match('/[^a-z0-9.@~_+=&\'*^\ \-\[\]]/i', $input[$i]) )
228              {
229                  $special_char = true;
230                  $input = preg_replace('/\\'.$input[$i].'/', '=' . bin2hex($input[$i]), $input);
231              }
232          }   
233     
234      if ( $special_char )
235          {
236                   /* *
237                    * When using arrays with pattern and replacement,
238                    * the keys are processed in the order they appear in the array.
239                    * See preg_replace in php.net/preg_replace
240                    * */
241                   $patterns[0] = '/=c3/i';
242                   $patterns[1] = '/ /';
243                   $replacements[1] = '';
244                   $replacements[0] = '_';
245                   $input = preg_replace($patterns, $replacements, $input);
246           }
247       
248       return($input);
249    }
250
251        // build the rule
252        function write_rule(){
253
254                // Variaveis;
255                $rule = array();
256                $vacation = array();
257                $newruletext = "";
258                $activerules = 0;
259                $regexused = 0;
260                $rejectused = 0;
261                $notify = 0;
262                $flaggedused = 0;
263                $newscriptbody = "";
264        $continue = 1;
265        $tmpSubject = "";
266       
267                // Recebe os valores das regras;
268                foreach($this->newrules as $tmp){
269                  $tmp1 = explode("&&",$tmp);
270                  $rule['priority']      = $tmp1[1];
271                  $rule['status']        = $tmp1[2];
272          $rule['from']              = $this->convert_specialchar($tmp1[3]);
273          $rule['to']            = $this->convert_specialchar($tmp1[4]);
274                  $tmpSubject                    = $tmp1[5];
275                  $rule['subject']               = $this->convert_specialchar($tmp1[5]);
276          $rule['action']            = $tmp1[6];
277                  $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
278          $rule['flg']               = $tmp1[8];   
279          $rule['field']                 = $tmp1[9];
280          $rule['field_val']     = $tmp1[10];
281          $rule['size']                    = $tmp1[11];
282          $rule['continue']        = ($tmp1[8] & $this->continuebit);
283          $rule['gthan']                   = ($tmp1[8] & $this->sizebit);
284          $rule['anyof']                   = ($tmp1[8] & $this->anyofbit);
285          $rule['keep']                    = ($tmp1[8] & $this->keepbit);
286          $rule['regexp']              = ($tmp1[8] & $this->regexbit);
287          $rule['unconditional']   = 0;
288                 
289                  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && !($rule['size'] >= 0) && $rule['action']){
290                         $rule['unconditional'] = 1;
291                  }
292                  unset($tmp1);
293             
294              // Monta as regras;
295              if ($rule['status'] != 'ENABLED') {
296              }
297              else {
298                $activerules = 1;
299         
300                // Condições para montagem das regras;
301                $anyall = "allof";
302                if ($rule['anyof']) $anyall = "anyof";
303                if ($rule['regexp']) {
304                    $regexused = 1;
305                }
306                $started = 0;
307         
308                if (!$rule['unconditional']) {
309                    if (!$continue) $newruletext .= "els";
310                    $newruletext .= "if " . $anyall . " (";
311                    if ($rule['from']) {
312                        if (preg_match("/^\s*!/", $rule['from'])){
313                            $newruletext .= 'not ';
314                            $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
315                        }
316                        $match = ':contains';
317                        if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
318                        if ($rule['regexp']) $match = ':regex';
319                        $newruletext .= "header " . $match . " [\"From\"]";
320                        $newruletext .= " \"" . $rule['from'] . "\"";
321                        $started = 1;
322                    }
323                    if ($rule['to']) {
324                        if ($started) $newruletext .= ", ";
325                        if (preg_match("/^\s*!/", $rule['to'])){
326                            $newruletext .= 'not ';
327                            $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
328                        }
329                        $match = ':contains';
330                        if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
331                        if ($rule['regexp']) $match = ':regex';
332                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
333                        $newruletext .= " \"" . $rule['to'] . "\"";
334                        $started = 1;
335                    }
336                    if ($rule['subject']) {
337                        if ($started) $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'])) $match = ':matches';
344                        if ($rule['regexp']) $match = ':regex';
345                        $newruletext .= "header " . $match . " \"subject\"";
346                        $newruletext .= " \"" . $rule['subject'] . "\"";
347                        $started = 1;
348                    }
349                    if ($rule['field'] && $rule['field_val']) {
350                        if ($started) $newruletext .= ", ";
351                        if (preg_match("/^\s*!/", $rule['field_val'])){
352                            $newruletext .= 'not ';
353                            $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
354                        }
355                        $match = ':contains';
356                        if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
357                        if ($rule['regexp']) $match = ':regex';
358                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
359                        $newruletext .= " \"" . $rule['field_val'] . "\"";
360                        $started = 1;
361                    }
362                    if ($rule['size'] >= 0) {
363                        $xthan = " :under ";
364                        if ($rule['gthan']) $xthan = " :over ";
365                        if ($started) $newruletext .= ", ";
366                        $newruletext .= "size " . $xthan . $rule['size'] . "K";
367                        $started = 1;
368                    }
369         
370                }
371                // Don't write half rule!
372                if (strlen($newruletext) == 0)
373                        return false;
374                // Actions
375                if (!$rule['unconditional']) $newruletext .= ") {\n\t";
376       
377                if (preg_match("/folder/i",$rule['action']))
378                {
379                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
380                }
381               
382                if (preg_match("/reject/i",$rule['action']))
383                {
384                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
385                    $rejectused = 1;
386                }
387                if (preg_match("/flagged/i",$rule['action']))
388                {
389                    $newruletext .= "addflag \"\\\\Flagged\";";
390                    $flaggedused = 1;
391                }
392                if (preg_match("/address/i",$rule['action']))
393                {
394                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
395                }
396               
397                if (preg_match("/notify/i",$rule['action']))
398                {
399                                $newruletext .= "notify :method \"mailto\" :options [\"".$this->EmailVoip ."\"]:" .
400                                                                "message \"<expressovoip><from>". $this->EmailExpresso."</from>".
401                                                                "<br/><Subject>".utf8_encode($tmpSubject)."</Subject></expressovoip>\";";
402                                $notify = 1;                                                   
403                }
404               
405                if (preg_match("/discard/i",$rule['action'])) {
406                    $newruletext .= "discard;";
407                }
408                if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
409                //if ($rule['keep']) $newruletext .= "\n\tkeep;";               
410                if (!$rule['unconditional']) $newruletext .= "\n}";
411         
412                $continue = 0;
413                if ($rule['continue']) $continue = 1;
414                if ($rule['unconditional']) $continue = 1;
415         
416                $newscriptbody .= $newruletext . "\n\n";
417                unset($newruletext);
418              }
419                }// Fim do Foreach;
420                $this->teste = $newscriptbody;         
421                // Para a regras fora do escritorio;
422        unset($tmp);
423        if($this->newout != ""){
424                $aux                                    = explode("&&",$this->newout);
425                $vacation['days']               = $aux[1];
426                $vacation['addresses']  = $aux[2];             
427                $vacation['text']               = preg_replace("/\\\\n/","\r\n",$aux[3]);
428                $vacation['status']     = $aux[4];
429            }
430               
431                // Monta a regra para fora do escritorio;
432            if ($vacation['status'] == 'on') {
433                        $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
434            $newscriptbody .= $vacation['addresses'];
435            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
436            }
437               
438                // Cria o cabeçalho do arquivo;
439                $newscripthead  = "";
440                $newscripthead .= "#Mail filter rules for " .$this->username . "\n";
441                $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
442                $newscripthead .= "\n";
443
444                // Continuação do cabeçalho do arquivo;                 
445            if ($activerules) {
446                $newscripthead .= "require [\"fileinto\"";
447               
448                if($notify){
449                        $newscripthead .= ",\"notify\"";                       
450                }
451                if($regexused){
452                        $newscripthead .= ",\"regex\"";
453                }
454                if($rejectused){
455                        $newscripthead .= ",\"reject\"";
456                }
457                if($flaggedused){
458                        $newscripthead .= ",\"imapflags\"";
459                }
460                if($this->newout && $vacation['status'] == 'on'){
461                    $newscripthead .= ",\"vacation\"";
462                }
463                $newscripthead .= "];\n\n";
464            }else{
465                        if($vacation && $vacation['status'] == 'on'){
466                            $newscripthead .= "require [\"vacation\"];\n\n";
467                        }
468            }
469               
470            // Cria o rodapé do arquivo;
471            $newscriptfoot  = "";
472            $newscriptfoot .= "##PSEUDO script start\n";
473            // Lê as regras;
474            foreach($this->newrules as $tmp){
475                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
476            }
477            // Lê as regras fora do escritório;
478            if($this->newout != ""){
479                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
480            }
481                $newscriptfoot .= "#mode&&basic\n";
482               
483                $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
484
485                // Destroi as variaveis;
486                unset($rule);
487                unset($vacation);
488                unset($activerules);
489                unset($regexused);
490                unset($rejectused);
491                unset($flaggedused);
492                unset($newscripthead);
493                unset($newscriptbody);
494        unset($newscriptfoot);
495        unset($continue);
496        unset($this->newrules);
497        unset($this->newout);
498               
499                // Retorna o script construido;
500                return $newscript;
501       
502        }// Fim da Função
503
504        // Cria o script sieve, caso nao possua;
505        function createScript(){
506               
507                // Cria o cabeçalho do arquivo;
508                $newScriptHead  = "";
509                $newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
510                $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail '; 
511                $newScriptHead .= "\n";
512
513                //Cria o rodapé do arquivo;
514                $newScriptFoot  = "";
515                $newScriptFoot .= "##PSEUDO Script Start\n";
516                $newScriptFoot .= "#mode&&basic\n";
517               
518                //Para passar para o arquivo;
519                $newScript = $newScriptHead . $newScriptFoot;
520
521                return $newScript;
522        }
523       
524        //Lê o conteúdo do script;
525        function readScript($scriptName){
526               
527                // Verifica se a conexão foi bem sucedida;
528                if(!$scriptName){       
529                        $this->errstr = "Não foi possível conectar com o Servidor";
530                        return "false 2";       
531                }
532               
533                // Recebe o conteúdo do array;
534                $lines = array();
535                $lines = preg_split("/\n/",$scriptName);
536               
537                // Pega o tamanho da regra na primeira do script;
538                $size_rule = array_shift($lines);
539               
540                // Recebe o tamanho do script, pela primeira linha;
541                $this->size = trim($size_rule);
542               
543                // Verifica a composição do script;
544                $line = array_shift($lines);
545                if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
546                        $this->errstr = "Formato nao reconhecido";
547                        return false;
548                }
549               
550                // Variaveis para a regra e o campo ferias;
551                $regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
552                $retorno['rule']         = array();
553                $retorno['vacation'] = array();
554                $retorno['mode']         = array();
555               
556                $line = array_shift($lines);
557                while (isset($line)){
558                        foreach($regexps as $regp){
559                                if(preg_match("/$regp/i",$line)){
560                                        // Recebe todas as regras criadas no servidor;
561                                        if(preg_match("/^ *#rule&&/i",$line)){
562                                                $retorno['rule'][] = $line . "\n";
563                                        }
564                                        if(preg_match("/^ *#vacation&&/i",$line)){
565                                                $retorno['vacation'][] = $line . "\n"; 
566                                        }
567                                        if(preg_match("/^ *#mode&&(.*)/i",$line)){
568                                                $retorno['mode'][]= $line . "\n";                                               
569                                        }                                       
570                                }
571                        }
572                        // Pega a proxima linha do sript;
573                        $line = array_shift($lines);
574                }
575                return $retorno;       
576        }
577               
578}//Fim da Classe
579?>
Note: See TracBrowser for help on using the repository browser.