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

Revision 5509, 22.4 KB checked in by gustavo, 12 years ago (diff)

Ticket #2488 - Adicionar cabecalho de licenca em arquivos que nao o possuem

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