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

Revision 1059, 16.1 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Removendo inclusão de header.inc.php nas classes e colocando no controler

  • 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          = 2;
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 = "O arquivo não foi criado";
65                        }
66                        // Mata a variavel;
67                        unset($aux);
68                        // Ativa o script;
69                        $aux = $this->SieveS->activatescript($this->scriptfile);
70                       
71                        if(!$aux){
72                                // Caso de erro, grava dentro da variavel errstr;
73                                $this->errstr = "O arquivo não foi ativado";
74                        }
75                        else{
76                                $this->reply = $this->SieveS->getscript();
77                                $this->rules = $this->readScript($this->reply);
78                        }
79                }else{
80                        $this->rules = $this->readScript($this->reply);
81                }               
82
83                //Fecha a conexao
84                $this->SieveS->close();
85                       
86                if($this->rules){               
87                        return $this->rules;
88                }else{
89                        return $this->errstr;
90                }
91                       
92        }
93       
94        function rec_rules($params){
95               
96                $newr1  = array();
97                $newr2  = array();
98                $newr3  = array();
99       
100                $var_decode = rawurldecode($params['arfilter']);
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                //Escreve a(s) nova(s) regra(s);
185                $this->errstr = $this->SieveS->putscript($this->scriptfile,$this->write_rule());
186               
187                //Ativa o script;
188                $this->errstr = $this->SieveS->activatescript($this->scriptfile);
189               
190                //Fecha a conexao
191                $this->SieveS->close();
192               
193                if($this->errstr){
194                        return "Ok";
195                }else{
196                        return "Problemas na criação do arquivo!\n" . $this->teste;
197                }
198        }
199
200    function convert_specialchar($input)
201    {
202      $special_char = false;
203          for ( $i = 0; $i < strlen($input); $i++ )
204          {
205              if ( preg_match('/[ÁáÉéÍíÓóÚúÀàÈèÌìÒòÙùüÇçÃãÕõÂâÊêÔô®©§ªºÐ¹²³°¢¿Æ£µøæß«»Ø÷±¬]/', $input[$i]) )
206              {
207                  $special_char = true;
208                  $input = preg_replace('/'.$input[$i].'/', '=' . bin2hex($input[$i]), $input);
209              }
210          }   
211     
212      if ( $special_char )
213          {
214                   /* *
215                    * When using arrays with pattern and replacement,
216                    * the keys are processed in the order they appear in the array.
217                    * See preg_replace in php.net/preg_replace
218                    * */
219                   $patterns[0] = '/=c3/i';
220                   $patterns[1] = '/ /';
221                   $replacements[1] = '';
222                   $replacements[0] = '_';
223                   $input = preg_replace($patterns, $replacements, $input);
224           }
225       
226       return($input);
227    }
228
229        // Grava a nova regra;
230        function write_rule(){
231
232                // Variaveis;
233                $rule = array();
234                $vacation = array();
235                $newruletext = "";
236                $activerules = 0;
237                $regexused = 0;
238                $rejectused = 0;
239                $notify = 0;
240                $newscriptbody = "";
241        $continue = 1;
242        $tmpSubject = "";
243       
244                // Recebe os valores das regras;
245                foreach($this->newrules as $tmp){
246                  $tmp1 = explode("&&",$tmp);
247                  $rule['priority']      = $tmp1[1];
248                  $rule['status']        = $tmp1[2];
249          $rule['from']              = $this->convert_specialchar($tmp1[3]);
250          $rule['to']            = $this->convert_specialchar($tmp1[4]);
251                  $tmpSubject                    = $tmp1[5];
252                  $rule['subject']               = $this->convert_specialchar($tmp1[5]);
253          $rule['action']            = $tmp1[6];
254                  $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
255          $rule['flg']               = $tmp1[8];   
256          $rule['field']                 = $tmp1[9];
257          $rule['field_val']     = $tmp1[10];
258          $rule['size']                    = $tmp1[11];
259          $rule['continue']        = ($tmp1[8] & $this->continuebit);
260          $rule['gthan']                   = ($tmp1[8] & $this->sizebit);
261          $rule['anyof']                   = ($tmp1[8] & $this->anyofbit);
262          $rule['keep']                    = ($tmp1[8] & $this->keepbit);
263          $rule['regexp']              = ($tmp1[8] & $this->regexbit);
264          $rule['unconditional']   = 0;
265                 
266                  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && !$rule['size'] && $rule['action']){
267                         $rule['unconditional'] = 1;
268                  }
269                  unset($tmp1);
270             
271              // Monta as regras;
272              if ($rule['status'] != 'ENABLED') {
273              }
274              else {
275                $activerules = 1;
276         
277                // Condições para montagem das regras;
278                $anyall = "allof";
279                if ($rule['anyof']) $anyall = "anyof";
280                if ($rule['regexp']) {
281                    $regexused = 1;
282                }
283                $started = 0;
284         
285                if (!$rule['unconditional']) {
286                    if (!$continue) $newruletext .= "els";
287                    $newruletext .= "if " . $anyall . " (";
288                    if ($rule['from']) {
289                        if (preg_match("/^\s*!/", $rule['from'])){
290                            $newruletext .= 'not ';
291                            $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
292                        }
293                        $match = ':contains';
294                        if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
295                        if ($rule['regexp']) $match = ':regex';
296                        $newruletext .= "header " . $match . " [\"From\"]";
297                        $newruletext .= " \"" . $rule['from'] . "\"";
298                        $started = 1;
299                    }
300                    if ($rule['to']) {
301                        if ($started) $newruletext .= ", ";
302                        if (preg_match("/^\s*!/", $rule['to'])){
303                            $newruletext .= 'not ';
304                            $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
305                        }
306                        $match = ':contains';
307                        if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
308                        if ($rule['regexp']) $match = ':regex';
309                        $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
310                        $newruletext .= " \"" . $rule['to'] . "\"";
311                        $started = 1;
312                    }
313                    if ($rule['subject']) {
314                        if ($started) $newruletext .= ", ";
315                        if (preg_match("/^\s*!/", $rule['subject'])){
316                            $newruletext .= 'not ';
317                            $rule['subject'] = preg_replace("/^\s*!/","",$rule['subject']);
318                        }
319                        $match = ':contains';
320                        if (preg_match("/\*|\?/", $rule['subject'])) $match = ':matches';
321                        if ($rule['regexp']) $match = ':regex';
322                        $newruletext .= "header " . $match . " \"subject\"";
323                        $newruletext .= " \"" . $rule['subject'] . "\"";
324                        $started = 1;
325                    }
326                    if ($rule['field'] && $rule['field_val']) {
327                        if ($started) $newruletext .= ", ";
328                        if (preg_match("/^\s*!/", $rule['field_val'])){
329                            $newruletext .= 'not ';
330                            $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
331                        }
332                        $match = ':contains';
333                        if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
334                        if ($rule['regexp']) $match = ':regex';
335                        $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
336                        $newruletext .= " \"" . $rule['field_val'] . "\"";
337                        $started = 1;
338                    }
339                    if ($rule['size']) {
340                        $xthan = " :under ";
341                        if ($rule['gthan']) $xthan = " :over ";
342                        if ($started) $newruletext .= ", ";
343                        $newruletext .= "size " . $xthan . $rule['size'] . "K";
344                        $started = 1;
345                    }
346         
347                }
348         
349                // Ações
350                if (!$rule['unconditional']) $newruletext .= ") {\n\t";
351       
352                if (preg_match("/folder/i",$rule['action']))
353                {
354                    $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
355                }
356               
357                if (preg_match("/reject/i",$rule['action']))
358                {
359                    $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
360                    $rejectused = 1;
361                }
362               
363                if (preg_match("/address/i",$rule['action']))
364                {
365                    $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
366                }
367               
368                if (preg_match("/notify/i",$rule['action']))
369                {
370                                $newruletext .= "notify :method \"mailto\" :options [\"".$this->EmailVoip ."\"]:" .
371                                                                "message \"<expressovoip><from>". $this->EmailExpresso."</from>".
372                                                                "<br/><Subject>".utf8_encode($tmpSubject)."</Subject></expressovoip>\";";
373                                $notify = 1;                                                   
374                }
375               
376                if (preg_match("/discard/i",$rule['action'])) {
377                    $newruletext .= "discard;";
378                }
379                if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
380                //if ($rule['keep']) $newruletext .= "\n\tkeep;";               
381                if (!$rule['unconditional']) $newruletext .= "\n}";
382         
383                $continue = 0;
384                if ($rule['continue']) $continue = 1;
385                if ($rule['unconditional']) $continue = 1;
386         
387                $newscriptbody .= $newruletext . "\n\n";
388                unset($newruletext);
389              }
390                }// Fim do Foreach;
391                $this->teste = $newscriptbody;         
392                // Para a regras fora do escritorio;
393        unset($tmp);
394        if($this->newout != ""){
395                $aux                                    = explode("&&",$this->newout);
396                $vacation['days']               = $aux[1];
397                $vacation['addresses']  = $aux[2];             
398                $vacation['text']               = preg_replace("/\\\\n/","\r\n",$aux[3]);
399                $vacation['status']     = $aux[4];
400            }
401               
402                // Monta a regra para fora do escritorio;
403            if ($vacation['status'] == 'on') {
404                        $newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
405            $newscriptbody .= $vacation['addresses'];
406            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
407            }
408               
409                // Cria o cabeçalho do arquivo;
410                $newscripthead  = "";
411                $newscripthead .= "#Mail filter rules for " .$this->username . "\n";
412                $newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
413                $newscripthead .= "\n";
414
415                // Continuação do cabeçalho do arquivo;                 
416            if ($activerules) {
417                $newscripthead .= "require [\"fileinto\"";
418               
419                if($notify){
420                        $newscripthead .= ",\"notify\"";                       
421                }
422                if($regexused){
423                        $newscripthead .= ",\"regex\"";
424                }
425                if($rejectused){
426                        $newscripthead .= ",\"reject\"";
427                }
428                if($this->newout && $vacation['status'] == 'on'){
429                    $newscripthead .= ",\"vacation\"";
430                }
431                $newscripthead .= "];\n\n";
432            }else{
433                        if($vacation && $vacation['status'] == 'on'){
434                            $newscripthead .= "require [\"vacation\"];\n\n";
435                        }
436            }
437               
438            // Cria o rodapé do arquivo;
439            $newscriptfoot  = "";
440            $newscriptfoot .= "##PSEUDO script start\n";
441            // Lê as regras;
442            foreach($this->newrules as $tmp){
443                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
444            }
445            // Lê as regras fora do escritório;
446            if($this->newout != ""){
447                        $newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
448            }
449                $newscriptfoot .= "#mode&&basic\n";
450               
451                $newscript = $newscripthead . $newscriptbody . $newscriptfoot;
452
453                // Destroi as variaveis;
454                unset($rule);
455                unset($vacation);
456                unset($activerules);
457                unset($regexused);
458                unset($rejectused);
459                unset($newscripthead);
460                unset($newscriptbody);
461        unset($newscriptfoot);
462        unset($continue);
463        unset($this->newrules);
464        unset($this->newout);
465               
466                // Retorna o script construido;
467                return $newscript;
468       
469        }// Fim da Função
470
471        // Cria o script sieve, caso nao possua;
472        function createScript(){
473               
474                // Cria o cabeçalho do arquivo;
475                $newScriptHead  = "";
476                $newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
477                $newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail '; 
478                $newScriptHead .= "\n";
479
480                //Cria o rodapé do arquivo;
481                $newScriptFoot  = "";
482                $newScriptFoot .= "##PSEUDO Script Start\n";
483                $newScriptFoot .= "#mode&&basic\n";
484               
485                //Para passar para o arquivo;
486                $newScript = $newScriptHead . $newScriptFoot;
487
488                return $newScript;
489        }
490       
491        //Lê o conteúdo do script;
492        function readScript($scriptName){
493               
494                // Verifica se a conexão foi bem sucedida;
495                if(!$scriptName){       
496                        $this->errstr = "Não foi possível conectar com o Servidor";
497                        return "false 2";       
498                }
499               
500                // Recebe o conteúdo do array;
501                $lines = array();
502                $lines = preg_split("/\n/",$scriptName);
503               
504                // Pega o tamanho da regra na primeira do script;
505                $size_rule = array_shift($lines);
506               
507                // Recebe o tamanho do script, pela primeira linha;
508                $this->size = trim($size_rule);
509               
510                // Verifica a composição do script;
511                $line = array_shift($lines);
512                if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
513                        $this->errstr = "Formato nao reconhecido";
514                        return false;
515                }
516               
517                // Variaveis para a regra e o campo ferias;
518                $regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
519                $retorno['rule']         = array();
520                $retorno['vacation'] = array();
521                $retorno['mode']         = array();
522               
523                $line = array_shift($lines);
524                while (isset($line)){
525                        foreach($regexps as $regp){
526                                if(preg_match("/$regp/i",$line)){
527                                        // Recebe todas as regras criadas no servidor;
528                                        if(preg_match("/^ *#rule&&/i",$line)){
529                                                $retorno['rule'][] = $line . "\n";
530                                        }
531                                        if(preg_match("/^ *#vacation&&/i",$line)){
532                                                $retorno['vacation'][] = $line . "\n"; 
533                                        }
534                                        if(preg_match("/^ *#mode&&(.*)/i",$line)){
535                                                $retorno['mode'][]= $line . "\n";                                               
536                                        }                                       
537                                }
538                        }
539                        // Pega a proxima linha do sript;
540                        $line = array_shift($lines);
541                }
542                return $retorno;       
543        }
544               
545}//Fim da Classe
546?>
Note: See TracBrowser for help on using the repository browser.