source: companies/serpro/expressoMail1_2/inc/class.ScriptS.inc.php @ 903

Revision 903, 15.3 KB checked in by niltonneto, 15 years ago (diff)

Importacao inicial do Expresso do Serpro

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                     
204           if ( $special_char )
205                   {
206                   /*  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 */
207                   $patterns[0] = '/=c3/i';
208                   $patterns[1] = '/ /';
209                   $replacements[1] = '';
210                   $replacements[0] = '_';
211                   $input = preg_replace($patterns, $replacements, $input);
212                   }
213                //   if (($input{0}) && (!eregi('^[a-zA-Z0-9=\-@&\.#\$!?%:\+_<>\(\)\"\ ]+$',$input)))
214                //              return false;   
215                //      else
216                        return($input);
217        }
218
219        // Grava a nova regra;
220        function write_rule(){
221
222                // Variaveis;
223                $rule = array();
224                $vacation = array();
225                $newruletext = "";
226                $activerules = 0;
227                $regexused = 0;
228                $rejectused = 0;
229                $newscriptbody = "";
230        $continue = 1;
231       
232                // Recebe os valores das regras;
233                foreach($this->newrules as $tmp){
234                  $tmp1 = explode("&&",$tmp);
235                  $rule['priority']      = $tmp1[1];
236                  $rule['status']        = $tmp1[2];
237          $rule['from']              = $this->convert_specialchar($tmp1[3]);
238          $rule['to']            = $this->convert_specialchar($tmp1[4]);
239                  $rule['subject'] = $this->convert_specialchar($tmp1[5]);
240          $rule['action']            = $tmp1[6];
241                  $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
242          $rule['flg']               = $tmp1[8];   
243          $rule['field']                 = $tmp1[9];
244          $rule['field_val']     = $tmp1[10];
245          $rule['size']                    = $tmp1[11];
246          $rule['continue']        = ($tmp1[8] & $this->continuebit);
247          $rule['gthan']                   = ($tmp1[8] & $this->sizebit);
248          $rule['anyof']                   = ($tmp1[8] & $this->anyofbit);
249          $rule['keep']                    = ($tmp1[8] & $this->keepbit);
250          $rule['regexp']              = ($tmp1[8] & $this->regexbit);
251          $rule['unconditional']   = 0;
252                 
253                  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && !$rule['size'] && $rule['action']){
254                         $rule['unconditional'] = 1;
255                  }
256                  unset($tmp1);
257             
258              // Monta as regras;
259              if ($rule['status'] != 'ENABLED') {
260              }
261              else {
262                $activerules = 1;
263         
264                // Condições para montagem das regras;
265                $anyall = "allof";
266                if ($rule['anyof']) $anyall = "anyof";
267                if ($rule['regexp']) {
268                    $regexused = 1;
269                }
270                $started = 0;
271         
272                if (!$rule['unconditional']) {
273                    if (!$continue) $newruletext .= "els";
274                    $newruletext .= "if " . $anyall . " (";
275                    if ($rule['from']) {
276                        if (preg_match("/^\s*!/", $rule['from'])){
277                            $newruletext .= 'not ';
278                            $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
279                        }
280                        $match = ':contains';
281                        if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
282                        if ($rule['regexp']) $match = ':regex';
283                        $newruletext .= "header " . $match . " [\"From\"]";
284                        $newruletext .= " \"" . $rule['from'] . "\"";
285                        $started = 1;
286                    }
287                    if ($rule['to']) {
288                        if ($started) $newruletext .= ", ";
289                        if (preg_match("/^\s*!/", $rule['to'])){
290                            $newruletext .= 'not ';
291                            $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
292                        }
293                        $match = ':contains';
294                        if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
295                        if ($rule['regexp']) $match = ':regex';
296                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
297                        $newruletext .= " \"" . $rule['to'] . "\"";
298                        $started = 1;
299                    }
300                    if ($rule['subject']) {
301                        if ($started) $newruletext .= ", ";
302                        if (preg_match("/^\s*!/", $rule['subject'])){
303                            $newruletext .= 'not ';
304                            $rule['subject'] = preg_replace("/^\s*!/","",$rule['subject']);
305                        }
306                        $match = ':contains';
307                        if (preg_match("/\*|\?/", $rule['subject'])) $match = ':matches';
308                        if ($rule['regexp']) $match = ':regex';
309                        $newruletext .= "header " . $match . " \"subject\"";
310                        $newruletext .= " \"" . $rule['subject'] . "\"";
311                        $started = 1;
312                    }
313                    if ($rule['field'] && $rule['field_val']) {
314                        if ($started) $newruletext .= ", ";
315                        if (preg_match("/^\s*!/", $rule['field_val'])){
316                            $newruletext .= 'not ';
317                            $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
318                        }
319                        $match = ':contains';
320                        if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
321                        if ($rule['regexp']) $match = ':regex';
322                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
323                        $newruletext .= " \"" . $rule['field_val'] . "\"";
324                        $started = 1;
325                    }
326                    if ($rule['size']) {
327                        $xthan = " :under ";
328                        if ($rule['gthan']) $xthan = " :over ";
329                        if ($started) $newruletext .= ", ";
330                        $newruletext .= "size " . $xthan . $rule['size'] . "K";
331                        $started = 1;
332                    }
333         
334                }
335         
336                // Ações
337                if (!$rule['unconditional']) $newruletext .= ") {\n\t";
338       
339                if (preg_match("/folder/i",$rule['action'])) {
340                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
341                }
342                if (preg_match("/reject/i",$rule['action'])) {
343                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
344                    $rejectused = 1;
345                }
346                if (preg_match("/address/i",$rule['action'])) {
347                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
348                }
349                if (preg_match("/discard/i",$rule['action'])) {
350                    $newruletext .= "discard;";
351                }
352                if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
353                //if ($rule['keep']) $newruletext .= "\n\tkeep;";               
354                if (!$rule['unconditional']) $newruletext .= "\n}";
355         
356                $continue = 0;
357                if ($rule['continue']) $continue = 1;
358                if ($rule['unconditional']) $continue = 1;
359         
360                $newscriptbody .= $newruletext . "\n\n";
361                unset($newruletext);
362              }
363                }// Fim do Foreach;
364               
365                // Para a regras fora do escritorio;
366        unset($tmp);
367        if($this->newout != ""){
368                $aux                                    = explode("&&",$this->newout);
369                $vacation['days']               = $aux[1];
370                $vacation['addresses']  = $aux[2];             
371                $vacation['text']               = preg_replace("/\\\\n/","\r\n",$aux[3]);
372                $vacation['status']     = $aux[4];
373            }
374               
375                // Monta a regra para fora do escritorio;
376            if ($vacation['status'] == 'on') {
377                        $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
378            $newscriptbody .= $vacation['addresses'];
379            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
380            }
381               
382                // Cria o cabeçalho do arquivo;
383                $newscripthead  = "";
384                $newscripthead .= "#Mail filter rules for " .$this->username . "\n";
385                $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
386                $newscripthead .= "\n";
387
388                // Continuação do cabeçalho do arquivo;                 
389            if ($activerules) {
390                $newscripthead .= "require [\"fileinto\"";
391                if($regexused){
392                        $newscripthead .= ",\"regex\"";
393                }
394                if($rejectused){
395                        $newscripthead .= ",\"reject\"";
396                }
397                if($this->newout && $vacation['status'] == 'on'){
398                    $newscripthead .= ",\"vacation\"";
399                }
400                $newscripthead .= "];\n\n";
401            }else{
402                        if($vacation && $vacation['status'] == 'on'){
403                            $newscripthead .= "require [\"vacation\"];\n\n";
404                        }
405            }
406               
407                //preg_replace("/[\\n\\r]/","", $p);           
408               
409 
410            // Cria o rodapé do arquivo;
411            $newscriptfoot  = "";
412            $newscriptfoot .= "##PSEUDO script start\n";
413            // Lê as regras;
414            foreach($this->newrules as $tmp){
415                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
416            }
417            // Lê as regras fora do escritório;
418            if($this->newout != ""){
419                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
420            }
421                $newscriptfoot .= "#mode&&basic\n";
422               
423                $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
424
425                // Destroi as variaveis;
426                unset($rule);
427                unset($vacation);
428                unset($activerules);
429                unset($regexused);
430                unset($rejectused);
431                unset($newscripthead);
432                unset($newscriptbody);
433        unset($newscriptfoot);
434        unset($continue);
435        unset($this->newrules);
436        unset($this->newout);
437               
438                // Retorna o script construido;
439                return $newscript;
440       
441        }// Fim da Função
442
443        // Cria o script sieve, caso nao possua;
444        function createScript(){
445               
446                // Cria o cabeçalho do arquivo;
447                $newScriptHead  = "";
448                $newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
449                $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail '; 
450                $newScriptHead .= "\n";
451
452                //Cria o rodapé do arquivo;
453                $newScriptFoot  = "";
454                $newScriptFoot .= "##PSEUDO Script Start\n";
455                $newScriptFoot .= "#mode&&basic\n";
456               
457                //Para passar para o arquivo;
458                $newScript = $newScriptHead . $newScriptFoot;
459
460                return $newScript;
461        }
462       
463        //Lê o conteúdo do script;
464        function readScript($scriptName){
465               
466                // Verifica se a conexão foi bem sucedida;
467                if(!$scriptName){       
468                        $this->errstr = "Não foi possível conectar com o Servidor";
469                        return "false 2";       
470                }
471               
472                // Recebe o conteúdo do array;
473                $lines = array();
474                $lines = preg_split("/\n/",$scriptName);
475               
476                // Pega o tamanho da regra na primeira do script;
477                $size_rule = array_shift($lines);
478               
479                // Recebe o tamanho do script, pela primeira linha;
480                $this->size = trim($size_rule);
481               
482                // Verifica a composição do script;
483                $line = array_shift($lines);
484                if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
485                        $this->errstr = "Formato nao reconhecido";
486                        return false;
487                }
488               
489                // Variaveis para a regra e o campo ferias;
490                $regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
491                $retorno['rule']         = array();
492                $retorno['vacation'] = array();
493                $retorno['mode']         = array();
494               
495                $line = array_shift($lines);
496                while (isset($line)){
497                        foreach($regexps as $regp){
498                                if(preg_match("/$regp/i",$line)){
499                                        // Recebe todas as regras criadas no servidor;
500                                        if(preg_match("/^ *#rule&&/i",$line)){
501                                                $retorno['rule'][] = $line . "\n";
502                                        }
503                                        if(preg_match("/^ *#vacation&&/i",$line)){
504                                                $retorno['vacation'][] = $line . "\n"; 
505                                        }
506                                        if(preg_match("/^ *#mode&&(.*)/i",$line)){
507                                                $retorno['mode'][]= $line . "\n";                                               
508                                        }                                       
509                                }
510                        }
511                        // Pega a proxima linha do sript;
512                        $line = array_shift($lines);
513                }
514                return $retorno;       
515        }
516               
517}//Fim da Classe
518?>
Note: See TracBrowser for help on using the repository browser.