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

Revision 51, 15.2 KB checked in by niltonneto, 17 years ago (diff)

Atualizações da versão nova.

  • 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;                                              // var tamanho;
16        var $so;                                                // para verificar 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       
25        function ScriptS(){
26
27                //Cria o objeto;
28                $this->SieveS     = new SieveS();
29               
30                //$this->scriptfile = $GLOBALS['HTTP_SESSION_VARS']['phpgw_info']['expressomail']['user']['account_lid'];
31                $this->scriptfile = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
32                $this->username   = $this->scriptfile;
33               
34                $this->reply      = "";
35                $this->rules      = "";
36                $this->errstr     = "";
37                $this->size               = "";
38               
39                $this->continuebit      = 1;
40        $this->sizebit          = 2;
41        $this->anyofbit         = 4;
42        $this->keepbit          = 8;
43        $this->regexbit         = 128;
44       
45        }
46       
47        function init_a(){
48               
49                //Abre a conexão
50                $this->SieveS->start();
51               
52                $this->reply = $this->SieveS->getscript();
53               
54                if(!$this->reply){
55       
56                        $aux = $this->SieveS->putscript($this->scriptfile, $this->createScript());
57                        if(!$aux){
58                                // Caso de erro, grava dentro da variável errstr;
59                                $this->errstr = "O arquivo não foi criado";
60                        }
61                        // Mata a variavel;
62                        unset($aux);
63                        // Ativa o script;
64                        $aux = $this->SieveS->activatescript($this->scriptfile);
65                       
66                        if(!$aux){
67                                // Caso de erro, grava dentro da variavel errstr;
68                                $this->errstr = "O arquivo não foi ativado";
69                        }
70                        else{
71                                $this->reply = $this->SieveS->getscript();
72                                $this->rules = $this->readScript($this->reply);
73                        }
74                }else{
75                        $this->rules = $this->readScript($this->reply);
76                }               
77
78                //Fecha a conexao
79                $this->SieveS->close();
80                       
81                if($this->rules){               
82                        return $this->rules;
83                }else{
84                        return $this->errstr;
85                }
86                       
87        }
88       
89        function rec_rules($params){
90               
91                $newr1  = array();
92                $newr2  = array();
93                $newr3  = array();
94       
95                $var_decode = rawurldecode($params['arfilter']);
96               
97                $narray  = explode("_end_",$var_decode);
98               
99                foreach($narray as $key=>$tmp){
100                        if($tmp != ""){
101                                $newr1[] = $tmp;
102                        }
103                }
104                unset($key);
105                unset($tmp);
106                foreach($newr1 as $key=>$tmp){
107                        $tmp2 = explode("_begin_##", $tmp);
108                        foreach($tmp2 as $tmp3){
109                                if($tmp3 != ""){
110                                        $newr2[] = trim($tmp3);         
111                                }       
112                        }       
113                }
114               
115                unset($tmp);
116                unset($tmp2);
117                unset($tmp3);
118
119                foreach($newr2 as $tmp){
120                        if(trim($tmp) != ""){   
121                                $tmp2 = explode("##",$tmp);
122                                foreach($tmp2 as $tmp3){
123                                        $tmp4 .= trim($tmp3) . "&&";   
124                                }
125                                $newr3[] = substr($tmp4,0,(strlen($tmp4)-4));                   
126                                unset($tmp2);
127                                unset($tmp3);
128                                unset($tmp4);
129                        }
130                }
131               
132                $tmp = $newr3[count($newr3)-1];
133               
134                if(substr($tmp,0,9) == "#vacation"){
135                        $this->newout = array_pop($newr3);
136                        foreach($newr3 as $key=>$tmp){
137                                $this->newrules[] = $tmp;
138                        }
139                }else{
140                        foreach($newr3 as $tmp){
141                                $this->newrules[] = $tmp;       
142                        }
143                }
144                               
145                unset($tmp);
146                $tmp  = explode("&&",$this->newout);
147                $tmp1 = explode(",",$tmp[2]);
148                foreach($tmp1 as $key=>$tmp2){
149                        $tmp3 .= stripslashes(trim($tmp2)).", ";
150                }
151                $tmp3 = substr($tmp3,0,(strlen($tmp3)-2));
152               
153                unset($tmp);
154                unset($tmp1);
155                unset($tmp2);
156                unset($key);
157                $tmp = explode("&&",$this->newout);
158                foreach($tmp as $key=>$tmp1){
159                        if($key == 2){
160                                $tmp2 .= trim($tmp3) . "&&";   
161                        }else{
162                                $tmp2 .= trim($tmp1) . "&&";   
163                        }       
164                }
165                unset($this->newout);
166                $this->newout = substr($tmp2,0,(strlen($tmp2)-2));
167               
168                //Abre a conexao
169                $this->SieveS->start();
170                $this->errstr = "";
171               
172                // Escreve a nova regra;
173                $this->reply = $this->SieveS->getscript();
174               
175                if($this->reply){
176                        $this->errstr = $this->SieveS->deletescript($this->scriptfile);         
177                }
178
179                //Escreve a(s) nova(s) regra(s);
180                $this->errstr = $this->SieveS->putscript($this->scriptfile,$this->write_rule());
181               
182                //Ativa o script;
183                $this->errstr = $this->SieveS->activatescript($this->scriptfile);
184               
185                //Fecha a conexao
186                $this->SieveS->close();
187               
188                if($this->errstr){
189                        return "Ok";
190                }else{
191                        return "Problemas na criação do arquivo!";
192                }
193        }
194
195        function convert_specialchar($input){
196                  $special_char = false;
197                  for ( $i = 0; $i < strlen($input); $i++ )
198                      if ( preg_match('/[áéíóúàèìòùçãõâêôç]/', $input[$i]) )
199                      {
200                          $special_char = true;
201                          $input = preg_replace('/'.$input[$i].'/', '=' . bin2hex($input[$i]), $input);
202                      }
203                   if ( $special_char )
204                   {
205                   /*  When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. See preg_replace in php.net/preg_replace */
206                   $patterns[0] = '/=c3/i';
207                   $patterns[1] = '/ /';
208                   $replacements[1] = '';
209                   $replacements[0] = '_';
210                   $input = preg_replace($patterns, $replacements, $input);
211                   }
212                   return($input);
213        }
214
215        // Grava a nova regra;
216        function write_rule(){
217
218                // Variaveis;
219                $rule = array();
220                $vacation = array();
221                $newruletext = "";
222                $activerules = 0;
223                $regexused = 0;
224                $rejectused = 0;
225                $newscriptbody = "";
226        $continue = 1;
227       
228                // Recebe os valores das regras;
229                foreach($this->newrules as $tmp){
230                  $tmp1 = explode("&&",$tmp);
231                  $rule['priority']      = $tmp1[1];
232                  $rule['status']        = $tmp1[2];
233          $rule['from']              = $this->convert_specialchar($tmp1[3]);
234          $rule['to']            = $this->convert_specialchar($tmp1[4]);
235          $rule['subject'] = $this->convert_specialchar($tmp1[5]);
236          $rule['action']            = $tmp1[6];
237          $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
238          $rule['flg']               = $tmp1[8];   
239          $rule['field']                 = $tmp1[9];
240          $rule['field_val']     = $tmp1[10];
241          $rule['size']                    = $tmp1[11];
242          $rule['continue']        = ($tmp1[8] & $this->continuebit);
243          $rule['gthan']                   = ($tmp1[8] & $this->sizebit);
244          $rule['anyof']                   = ($tmp1[8] & $this->anyofbit);
245          $rule['keep']                    = ($tmp1[8] & $this->keepbit);
246          $rule['regexp']              = ($tmp1[8] & $this->regexbit);
247          $rule['unconditional']   = 0;
248                 
249                  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && !$rule['size'] && $rule['action']){
250                         $rule['unconditional'] = 1;
251                  }
252                  unset($tmp1);
253             
254              // Monta as regras;
255              if ($rule['status'] != 'ENABLED') {
256              }
257              else {
258                $activerules = 1;
259         
260                // Condições para montagem das regras;
261                $anyall = "allof";
262                if ($rule['anyof']) $anyall = "anyof";
263                if ($rule['regexp']) {
264                    $regexused = 1;
265                }
266                $started = 0;
267         
268                if (!$rule['unconditional']) {
269                    if (!$continue) $newruletext .= "els";
270                    $newruletext .= "if " . $anyall . " (";
271                    if ($rule['from']) {
272                        if (preg_match("/^\s*!/", $rule['from'])){
273                            $newruletext .= 'not ';
274                            $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
275                        }
276                        $match = ':contains';
277                        if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
278                        if ($rule['regexp']) $match = ':regex';
279                        $newruletext .= "address " . $match . " [\"From\"]";
280                        $newruletext .= " \"" . $rule['from'] . "\"";
281                        $started = 1;
282                    }
283                    if ($rule['to']) {
284                        if ($started) $newruletext .= ", ";
285                        if (preg_match("/^\s*!/", $rule['to'])){
286                            $newruletext .= 'not ';
287                            $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
288                        }
289                        $match = ':contains';
290                        if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
291                        if ($rule['regexp']) $match = ':regex';
292                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
293                        $newruletext .= " \"" . $rule['to'] . "\"";
294                        $started = 1;
295                    }
296                    if ($rule['subject']) {
297                        if ($started) $newruletext .= ", ";
298                        if (preg_match("/^\s*!/", $rule['subject'])){
299                            $newruletext .= 'not ';
300                            $rule['subject'] = preg_replace("/^\s*!/","",$rule['subject']);
301                        }
302                        $match = ':contains';
303                        if (preg_match("/\*|\?/", $rule['subject'])) $match = ':matches';
304                        if ($rule['regexp']) $match = ':regex';
305                        $newruletext .= "header " . $match . " \"subject\"";
306                        $newruletext .= " \"" . $rule['subject'] . "\"";
307                        $started = 1;
308                    }
309                    if ($rule['field'] && $rule['field_val']) {
310                        if ($started) $newruletext .= ", ";
311                        if (preg_match("/^\s*!/", $rule['field_val'])){
312                            $newruletext .= 'not ';
313                            $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
314                        }
315                        $match = ':contains';
316                        if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
317                        if ($rule['regexp']) $match = ':regex';
318                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
319                        $newruletext .= " \"" . $rule['field_val'] . "\"";
320                        $started = 1;
321                    }
322                    if ($rule['size']) {
323                        $xthan = " :under ";
324                        if ($rule['gthan']) $xthan = " :over ";
325                        if ($started) $newruletext .= ", ";
326                        $newruletext .= "size " . $xthan . $rule['size'] . "K";
327                        $started = 1;
328                    }
329         
330                }
331         
332                // Ações
333                if (!$rule['unconditional']) $newruletext .= ") {\n\t";
334       
335                if (preg_match("/folder/i",$rule['action'])) {
336                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
337                }
338                if (preg_match("/reject/i",$rule['action'])) {
339                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
340                    $rejectused = 1;
341                }
342                if (preg_match("/address/i",$rule['action'])) {
343                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
344                }
345                if (preg_match("/discard/i",$rule['action'])) {
346                    $newruletext .= "discard;";
347                }
348                if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
349                //if ($rule['keep']) $newruletext .= "\n\tkeep;";               
350                if (!$rule['unconditional']) $newruletext .= "\n}";
351         
352                $continue = 0;
353                if ($rule['continue']) $continue = 1;
354                if ($rule['unconditional']) $continue = 1;
355         
356                $newscriptbody .= $newruletext . "\n\n";
357                unset($newruletext);
358              }
359                }// Fim do Foreach;
360               
361                // Para a regras fora do escritorio;
362        unset($tmp);
363        if($this->newout != ""){
364                $aux                                    = explode("&&",$this->newout);
365                $vacation['days']               = $aux[1];
366                $vacation['addresses']  = $aux[2];             
367                $vacation['text']               = preg_replace("/\\\\n/","\r\n",$aux[3]);
368                $vacation['status']     = $aux[4];
369            }
370               
371                // Monta a regra para fora do escritorio;
372            if ($vacation['status'] == 'on') {
373                        $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
374            $newscriptbody .= $vacation['addresses'];
375            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
376            }
377               
378                // Cria o cabeçalho do arquivo;
379                $newscripthead  = "";
380                $newscripthead .= "#Mail filter rules for " .$this->username . "\n";
381                $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
382                $newscripthead .= "\n";
383
384                // Continuação do cabeçalho do arquivo;                 
385            if ($activerules) {
386                $newscripthead .= "require [\"fileinto\"";
387                if($regexused){
388                        $newscripthead .= ",\"regex\"";
389                }
390                if($rejectused){
391                        $newscripthead .= ",\"reject\"";
392                }
393                if($this->newout && $vacation['status'] == 'on'){
394                    $newscripthead .= ",\"vacation\"";
395                }
396                $newscripthead .= "];\n\n";
397            }else{
398                        if($vacation && $vacation['status'] == 'on'){
399                            $newscripthead .= "require [\"vacation\"];\n\n";
400                        }
401            }
402               
403                //preg_replace("/[\\n\\r]/","", $p);           
404               
405 
406            // Cria o rodapé do arquivo;
407            $newscriptfoot  = "";
408            $newscriptfoot .= "##PSEUDO script start\n";
409            // Lê as regras;
410            foreach($this->newrules as $tmp){
411                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
412            }
413            // Lê as regras fora do escritório;
414            if($this->newout != ""){
415                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
416            }
417                $newscriptfoot .= "#mode&&basic\n";
418               
419                $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
420
421                // Destroi as variaveis;
422                unset($rule);
423                unset($vacation);
424                unset($activerules);
425                unset($regexused);
426                unset($rejectused);
427                unset($newscripthead);
428                unset($newscriptbody);
429        unset($newscriptfoot);
430        unset($continue);
431        unset($this->newrules);
432        unset($this->newout);
433               
434                // Retorna o script construido;
435                return $newscript;
436       
437        }// Fim da Função
438
439        // Cria o script sieve, caso nao possua;
440        function createScript(){
441               
442                // Cria o cabeçalho do arquivo;
443                $newScriptHead  = "";
444                $newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
445                $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail '; 
446                $newScriptHead .= "\n";
447
448                //Cria o rodapé do arquivo;
449                $newScriptFoot  = "";
450                $newScriptFoot .= "##PSEUDO Script Start\n";
451                $newScriptFoot .= "#mode&&basic\n";
452               
453                //Para passar para o arquivo;
454                $newScript = $newScriptHead . $newScriptFoot;
455
456                return $newScript;
457        }
458       
459        //Lê o conteúdo do script;
460        function readScript($scriptName){
461               
462                // Verifica se a conexão foi bem sucedida;
463                if(!$scriptName){       
464                        $this->errstr = "Não foi possível conectar com o Servidor";
465                        return "false 2";       
466                }
467               
468                // Recebe o conteúdo do array;
469                $lines = array();
470                $lines = preg_split("/\n/",$scriptName);
471               
472                // Pega o tamanho da regra na primeira do script;
473                $size_rule = array_shift($lines);
474               
475                // Recebe o tamanho do script, pela primeira linha;
476                $this->size = trim($size_rule);
477               
478                // Verifica a composição do script;
479                $line = array_shift($lines);
480                if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
481                        $this->errstr = "Formato nao reconhecido";
482                        return false;
483                }
484               
485                // Variaveis para a regra e o campo ferias;
486                $regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
487                $retorno['rule']         = array();
488                $retorno['vacation'] = array();
489                $retorno['mode']         = array();
490               
491                $line = array_shift($lines);
492                while (isset($line)){
493                        foreach($regexps as $regp){
494                                if(preg_match("/$regp/i",$line)){
495                                        // Recebe todas as regras criadas no servidor;
496                                        if(preg_match("/^ *#rule&&/i",$line)){
497                                                $retorno['rule'][] = $line . "\n";
498                                        }
499                                        if(preg_match("/^ *#vacation&&/i",$line)){
500                                                $retorno['vacation'][] = $line . "\n"; 
501                                        }
502                                        if(preg_match("/^ *#mode&&(.*)/i",$line)){
503                                                $retorno['mode'][]= $line . "\n";                                               
504                                        }                                       
505                                }
506                        }
507                        // Pega a proxima linha do sript;
508                        $line = array_shift($lines);
509                }
510                return $retorno;       
511        }
512               
513}//Fim da Classe
514?>
Note: See TracBrowser for help on using the repository browser.