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

Revision 1040, 16.3 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Atualização de download de arquivos e sessão

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