source: companies/celepar/expressoMail1_2/inc/class.ScriptS.inc.php @ 763

Revision 763, 16.1 KB checked in by niltonneto, 15 years ago (diff)

Importação inicial do Expresso da Celepar

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