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

Revision 5294, 21.7 KB checked in by alexandrecorreia, 12 years ago (diff)

Ticket #1909 - Sincronizando o repositorio trunk do expresso.

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