source: trunk/expressoMail1_2/inc/class.ScriptS.inc.php @ 2360

Revision 2360, 17.7 KB checked in by amuller, 14 years ago (diff)

Ticket #1008 - Adicionando informações sobre licenças

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