source: trunk/prototype/modules/filters/interceptors/FilterMapping.php @ 5747

Revision 5747, 18.3 KB checked in by airton, 12 years ago (diff)

Ticket #1782 - Especificar DFD0060 - Correcao da verificacao do array de regras

Line 
1<?php
2/**
3*
4* Copyright (C) 2011 Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
5*
6* This program is free software; you can redistribute it and/or modify it under
7* the terms of the GNU Affero General Public License version 3 as published by
8* the Free Software Foundation with the addition of the following permission
9* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
10* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
11* WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
12*
13* This program is distributed in the hope that it will be useful, but WITHOUT
14* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15* FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16* details.
17*
18* You should have received a copy of the GNU Affero General Public License
19* along with this program; if not, see www.gnu.org/licenses or write to
20* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21* MA 02110-1301 USA.
22*
23* This code is based on the OpenXchange Connector and on the Prognus pSync
24* Connector both developed by the community and licensed under the GPL
25* version 2 or above as published by the Free Software Foundation.
26*
27* You can contact Prognus Software Livre headquarters at Av. Tancredo Neves,
28* 6731, PTI, Bl. 05, Esp. 02, Sl. 10, Foz do Iguaçu - PR - Brasil or at
29* e-mail address prognus@prognus.com.br.
30*
31* Descrição rápida do arquivo
32*
33* Arquivo responsável pela manipulação dos filtros
34*
35* @package    filters
36* @license    http://www.gnu.org/copyleft/gpl.html GPL
37* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
38* @version    1.0
39* @sponsor    Caixa EconÃŽmica Federal
40* @since      Arquivo disponibilizado na versão 2.4
41*/
42
43
44
45/**
46* Classe responsável pela manipulação dos filtros.
47*
48*
49* @package    prototype
50* @license    http://www.gnu.org/copyleft/gpl.html GPL
51* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
52* @author     Airton Bordin Junior
53* @author     Gustavo Pereira dos Santos
54* @version    1.0
55* @since      Classe disponibilizada na versão 2.4
56*/
57class FilterMapping
58{
59       
60        var $service;
61       
62       
63        /**
64        * Método que formata o Script de acordo com a sintaxe do Sieve.
65        *
66        * @license    http://www.gnu.org/copyleft/gpl.html GPL
67        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
68        * @sponsor    Caixa EconÃŽmica Federal
69        * @author     Airton Bordin Junior
70        * @author         Gustavo Pereira dos Santos   
71        * @param      <Array> <$rules> <Array com as regras do usuário>
72        * @return     <Regra de acordo com a sintaxe do Sieve>
73        * @access     <public>
74        */
75        public function formatSieveScript( $rules )
76    {
77       
78                $require_fileinto = $require_flag = $require_reject = $require_vacation = $require_body = $require_imapflag = $vacation = $startswith = $endswith = false;
79
80                $script_rules = $script_header = $script_criteria = $vacation_action = "";
81
82                $i = 0;
83
84                foreach( $rules as $name => $data )
85                {
86                       
87                        if(array_key_exists("block", $data)) {
88                                /* Usado na opção Bloquear usuário do ExpressoMail */
89                                if($data['block']) {
90                                        ($i >0) ? $script_match = 'elsif anyof' : $script_match = 'if anyof';
91                                        $script_match = $script_match . "(address :is \"from\" [\"" .$data['name'] . "\"]) {\r\n"; 
92                                        $script_match .= "fileinto \"INBOX/Spam\"; \r\n}\r\n";
93                                        $script_rules .= $script_match;
94                                        $script_match = "";
95                                        $script_criteria = "";
96                                        $require_fileinto = true;
97                                        $i++;
98                                        continue;
99                                }
100                        }
101                        //if( $data['enabled'] == 'false' )
102                                //continue;
103
104                        $vacation = false;
105                        $criteria = $data['criteria'];
106                        $action   = $data['actions'];
107                       
108                        ($i >0) ? $script_match = 'els' : $script_match = '';
109                        $data['isExact'] == 'false' ?  $script_match .= 'if anyof (' : $script_match .= 'if allof (';
110
111
112                        if( is_array($criteria) )
113                        foreach ($criteria as $j => $value);
114                        {                                       
115                                 
116                                switch($criteria[$j]['field']) {
117                                        case 'To':   
118                                        case 'to':   
119                                        case 'CC':
120                                        case 'Cc':
121                                                $criteria[$j]['field'] = "[\"To\", \"TO\", \"Cc\", \"CC\"]";
122                                                $script_criteria .= "address :";
123                                                break;
124                                        case 'from':
125                                                $criteria[$j]['field'] = "\"" . $criteria[$j]['field'] . "\"";
126                                                $script_criteria .= "address :";
127                                                break;
128                                        case 'size':   
129                                                $criteria[$j]['field'] = '';
130                                                $script_criteria .= "size :";
131                                                break;
132                                        case 'subject':
133                                                $criteria[$j]['field'] = "\"" . $criteria[$j]['field'] . "\"";
134                                                $criteria[$j]['value'] = "" . imap_8bit($criteria[$j]['value']) . "\", \"" . base64_encode($criteria[$j]['value']) . "";
135                                                $script_criteria .= "header :";
136                                                break;
137                                        case 'body':
138                                                $criteria[$j]['field'] = '';
139                                                $script_criteria .= "body :";
140                                                $require_body = true;
141                                                break;
142                                        case 'vacation':
143                                                continue;
144                                        default:
145                                                $script_criteria .= "header :";
146                                                break;
147                                }
148                               
149                                switch ($criteria[$j]['operator']) {
150                                        case '>':
151                                                $criteria[$j]['operator'] = "over";
152                                                break;
153                                        case '<':
154                                                $criteria[$j]['operator'] = "under";
155                                                break;
156                                        case '=':
157                                                $criteria[$j]['operator'] = "is";
158                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "\"]";
159                                                break;
160                                        case '*':
161                                                $criteria[$j]['operator'] = "contains";
162                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "\"]";
163                                                break;                                         
164                                        case '^':
165                                                $criteria[$j]['operator'] = "matches";
166                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "*\"]";
167                                                $startswith = true;
168                                                break;
169                                        case '$':
170                                                $criteria[$j]['operator'] = "matches";
171                                                $criteria[$j]['value'] = "[\"*" . $criteria[$j]['value'] . "\"]";
172                                                $endswith = true;
173                                                break;
174                                        /*
175                                           TO-DO:
176                                           Arrrumar regra do "não contém".
177                                        */
178                                        case '!*':
179                                                $criteria[$j]['operator'] = "contains";
180                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "\"]";
181                                                break;
182                                }
183                               
184                                if ($criteria[$j]['field'] == "" || $criteria[$j]['field'] == "\"subject\"" || $startswith || $endswith)
185                                {
186                                        $script_criteria .= $criteria[$j]['operator'] . " " . $criteria[$j]['field'] . " " . $criteria[$j]['value'] . ", ";
187                                        $startswith = $endswith = false;
188                                }
189                                else
190                                        $script_criteria .= $criteria[$j]['operator'] . " " . $criteria[$j]['field'] . " " . $criteria[$j]['value'] . ", ";
191                        }
192                        $script_criteria = substr($script_criteria,0,-2);
193                        /* if ($vacation == false) */
194                        $script_criteria .= ")";
195
196                        $script_action = " {\r\n ";
197                       
198                        if( is_array($action) )
199                        foreach ($action as $k=> $value);
200                        {
201                                switch ($action[$k]['type']) {
202                                        case 'redirect':
203                                                break;
204                                        case 'reject':
205                                                $require_reject = true;
206                                                break;
207                                        case 'fileinto':
208                                                $require_fileinto = true;
209                                                break;
210                                        case 'vacation':
211                                                $require_vacation = true;
212                                                $action[$k]['parameter'] = "\"" . $action[$k]['parameter'] . "\"";
213                                                $vacation_action = " :subject \"Fora do Escritório\" " . $action[$k]['parameter'] . ";";
214                                                $vacation = true;
215                                                continue;
216                                        case 'setflag':
217                                                $require_flag = true;
218                                                $action[$k]['parameter'] = "\\\\" . $action[$k]['parameter'];
219                                                break;
220                                        case 'discard':
221                                                break;
222                                }
223                                if ($vacation == false) $script_action .= $action[$k]['type'] . " \"" . $action[$k]['parameter'] . "\";\r\n ";
224                        }
225
226                        $script_action .= "}";
227                       
228                        if($vacation != true)
229                                $script_rules .= $script_match . $script_criteria . $script_action . "\r\n";
230
231                        if($data['id'] != "vacation")
232                                $i++;
233                        $script_match = "";
234                        $script_criteria = "";
235                       
236                }
237
238                if($require_reject || $require_fileinto || $require_vacation || $require_body || $require_flag)
239                {
240                        $script_header .= "require [";
241                        $require_reject ? $script_header .= "\"reject\", " : "";
242                        $require_fileinto ? $script_header .= "\"fileinto\", " : "";
243                        $require_vacation? $script_header .= "\"vacation\", " : ""; 
244                        $require_flag ? $script_header .= "\"imapflags\", " : ""; 
245                        $require_body ? $script_header .= "\"body\", " : "";  /* tem que instalar as extensões no Cyrus */
246                        $script_header = substr($script_header,0,-2);
247                        $script_header .= "];\r\n";
248                }
249
250                if( $vacation_action )
251                {
252                  $script_rules .= "vacation" . $vacation_action . "\r\n";
253                }
254
255                $json_data = json_encode($rules);
256               
257                $script_begin = "#Filtro gerado por Expresso Livre versão 2.4\r\n\r\n";
258
259                $content = $script_begin . $script_header . $script_rules . "\r\n\r\n#PseudoScript#" . "\r\n#" . $json_data;
260                //$content = "";
261
262                return( $content );
263        }
264       
265        /**
266        * Método que lê e faz o parser dos filtros antigos
267        *
268        * @license    http://www.gnu.org/copyleft/gpl.html GPL
269        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
270        * @sponsor    Caixa EconÃŽmica Federal
271        * @author     Airton Bordin Junior
272        * @author         Gustavo Pereira dos Santos   
273        * @param      <$scriptName> <Regras do usuário>
274        * @return     <Regra do usuário parseada>
275        * @access     <public>
276        */
277        public function readOldScript($scriptName)
278        {
279        // Recebe o conteúdo do array;
280        $lines = array();
281        $lines = preg_split("/\n/", $scriptName);
282
283        // Pega o tamanho da regra na primeira do script;
284        $size_rule = array_shift($lines);
285
286        // Recebe o tamanho do script, pela primeira linha;
287        $this->size = trim($size_rule);
288
289        // Verifica a composição do script; */
290         $line = array_shift($lines);
291
292        // Variaveis para a regra e o campo ferias;
293        $regexps = array('^ *##PSEUDO', '^ *#rule', '^ *#vacation', '^ *#mode');
294        $retorno['rule'] = array();
295
296        $line = array_shift($lines);
297        while (isset($line)) {
298            foreach ($regexps as $regp) {
299                if (preg_match("/$regp/i", $line)) {
300                    // Recebe todas as regras criadas no servidor;
301                    if (preg_match("/^ *#rule&&/i", $line)) {
302                        $retorno['rule'][] = $line . "\n";
303                    }
304                }
305            }
306            // Pega a proxima linha do sript;
307            $line = array_shift($lines);
308        }
309        return $retorno;
310    }
311       
312       
313       
314       
315        /**
316        * Método que faz o parsing do Script Sieve, transformando em Array.
317        *
318        * @license    http://www.gnu.org/copyleft/gpl.html GPL
319        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
320        * @sponsor    Caixa EconÃŽmica Federal
321        * @author     Airton Bordin Junior
322        * @author         Gustavo Pereira dos Santos   
323        * @param      <String> <$script> <Script Sieve com as regras do usuário>
324        * @return     <Regras do usuário em Array>
325        * @access     <public>
326        */
327        public function parseSieveScript( $script )
328        {
329                /*
330                $old_rule = strripos($script, "##PSEUDO script start");
331               
332                if($old_rule) {
333                       
334                        $parsed_rule = $this->readOldScript($old_script);
335                        $array_rule = explode("&&", $parsed_rule['rule'][0]);
336
337                        $old_retorno = array();
338                        $old_retorno['isExact'] = false;
339                        $old_retorno['name'] = $array_rule[1];
340                        $old_retorno['criteria'] = array();
341                        $old_retorno['criteria'][0] = array();
342                        $old_retorno['criteria'][0]['value'] = $array_rule[5];
343                        $old_retorno['criteria'][0]['operator'] = '=';
344                        $old_retorno['criteria'][0]['field'] = 'subject';
345                        $old_retorno['actions'] = array();
346                        $old_retorno['actions'][0] = array();
347                        $old_retorno['actions'][0]['parameter'] = $array_rule[7];
348                        $old_retorno['actions'][0]['type'] = $array_rule[6];
349                        $old_retorno['enabled'] = true;
350                        $old_retorno['id'] = $array_rule[1];
351                        $old_retorno['applyMessages'] = '';
352
353                        return $old_retorno;
354                }
355                */
356                $pos = strripos($script, "#PseudoScript#");
357                $pseudo_script = substr( $script, $pos+17 );
358
359                $return = json_decode( $pseudo_script, true );
360
361                return $return;
362        }
363
364        var $rules = false;
365
366        /**
367        * Construtor da classe.
368        *
369        * @license    http://www.gnu.org/copyleft/gpl.html GPL
370        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
371        * @sponsor    Caixa EconÃŽmica Federal
372        * @author     Airton Bordin Junior
373        * @author         Gustavo Pereira dos Santos   
374        * @access     <public>
375        */
376        public function __construct()
377        {
378                $this->service = Controller::service("Sieve");
379        }
380
381       
382        /**
383        * Método que recupera as regras do usuário.
384        *
385        * @license    http://www.gnu.org/copyleft/gpl.html GPL
386        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
387        * @sponsor    Caixa EconÃŽmica Federal
388        * @author     Airton Bordin Junior
389        * @author         Gustavo Pereira dos Santos   
390        * @return     <Regras do usuário>
391        * @access     <public>
392        */
393        public function getRules()
394        {
395                $this->rules = Controller::find( array( 'concept' => 'filter' ) );
396
397                if( !$this->rules ) {
398                        $this->rules = array();
399                }
400                return( $this->rules );
401        }
402
403       
404        /**
405        * Método que aplica o filtro para as mensagens do usuário.
406        *
407        * @license    http://www.gnu.org/copyleft/gpl.html GPL
408        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
409        * @sponsor    Caixa EconÃŽmica Federal
410        * @author     Airton Bordin Junior
411        * @author         Gustavo Pereira dos Santos   
412        * @param      <$uri>
413        * @param      <$result>
414        * @param      <$criteria>
415        * @param      <$original>
416        * @access     <public>
417        */
418        public function applySieveFilter( &$uri , &$result , &$criteria , $original  )
419        {
420                /*
421                $result['id'] = $uri['id'];
422                $rule_apply = array();
423               
424                $filter = Controller::read($uri);
425                $filter_ = $this->parseSieveScript($filter['content']);
426               
427                foreach ($filter_ as $f_) {
428                        if($f_['id'] == $uri['id']) {
429                                $rule_apply     = $f_;
430                        }
431                }
432               
433                $actions = array();
434                $actions['type']      = $rule_apply['actions'][0]['type'];
435                $actions['parameter'] = $rule_apply['actions'][0]['parameter'];
436               
437                $messages = $rule_apply['applyMessages'];
438                 
439                         
440                $proc = array();
441                $proc['keep'] = false;
442                */     
443               
444                //$imap = Controller::service( 'Imap' );
445                //$imap->apliSieveFilter($original['properties']['applyMessages'] , $proc );
446                //$imap->apliSieveFilter($messages , $actions );
447                //return $result;
448        }
449
450       
451        /**
452        * Método que lê o script do usuário.
453        *
454        * @license    http://www.gnu.org/copyleft/gpl.html GPL
455        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
456        * @sponsor    Caixa EconÃŽmica Federal
457        * @author     Airton Bordin Junior
458        * @author         Gustavo Pereira dos Santos   
459        * @param      <$uri>
460        * @param      <$result>
461        * @param      <$criteria>
462        * @param      <$original>
463        * @return     <Script do usuário>
464        * @access     <public>
465        */
466        public function readUserScript( &$uri , &$params , &$criteria , $original )
467        { 
468                $uri['id'] = $this->service->config['user'];
469        }
470 
471 
472        /**
473        * Método que seta o script do usuário.
474        *
475        * @license    http://www.gnu.org/copyleft/gpl.html GPL
476        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
477        * @sponsor    Caixa EconÃŽmica Federal
478        * @author     Airton Bordin Junior
479        * @author         Gustavo Pereira dos Santos   
480        * @param      <$uri>
481        * @param      <$result>
482        * @param      <$criteria>
483        * @param      <$original>
484        * @return     <Script do usuário>
485        * @access     <public>
486        */
487        public function setRule( &$uri , &$params , &$criteria , $original  )
488        {
489                if( !$this->rules )
490                $this->rules = $this->getRules();
491
492            $uri['id'] = $params['id'] = isset($params['id']) ? $params['id'] : urlencode($params['name']);
493
494            $i = 0;
495
496            for( ; isset($this->rules[$i]) && $this->rules[$i]['id'] !== $params['id']; $i++ );
497
498            $this->rules[$i] = array_merge( ( isset($this->rules[$i]) ? $this->rules[$i] : array() ), $params );
499
500            $params = array( 'name' => $this->service->config['user'],
501                             'content' => $this->formatSieveScript( $this->rules ),
502                             'active' => true );
503        }
504
505       
506        /**
507        * Método que deleta o script do usuário.
508        *
509        * @license    http://www.gnu.org/copyleft/gpl.html GPL
510        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
511        * @sponsor    Caixa EconÃŽmica Federal
512        * @author     Airton Bordin Junior
513        * @author         Gustavo Pereira dos Santos   
514        * @param      <$uri>
515        * @param      <$result>
516        * @param      <$criteria>
517        * @param      <$original>
518        * @access     <public>
519        */
520        public function deleteRule( &$uri, &$params, &$criteria, $original )
521        {
522                if( !$this->rules ) {   
523                        $this->rules = $this->getRules();
524                }         
525                $params['id'] = $uri['id'];
526
527                $update = false;
528               
529                $rules = array();
530
531                foreach( $this->rules as $i => $rule )
532                        if( $rule['id'] !== $uri['id'] )
533                                $rules[] = $this->rules[$i];
534
535                $this->rules = $rules;
536               
537                $uri['id'] = '';
538
539                $params = array( 'name' => $this->service->config['user'],
540                           'content' => $this->formatSieveScript( $this->rules ),
541                           'active' => true );
542
543                $URI = Controller::URI( $uri['concept'], $this->service->config['user'] );
544                $this->service->update( $URI, $params );
545       
546                return( false );
547        }
548
549       
550        /**
551        * Método que pega o script do usuário.
552        *
553        * @license    http://www.gnu.org/copyleft/gpl.html GPL
554        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
555        * @sponsor    Caixa EconÃŽmica Federal
556        * @author     Airton Bordin Junior
557        * @author         Gustavo Pereira dos Santos   
558        * @param      <$uri>
559        * @param      <$result>
560        * @param      <$criteria>
561        * @param      <$original>
562        * @return     <Script do usuário>
563        * @access     <public>
564        */
565        public function getSieveRule( &$uri , &$params , &$criteria , $original )
566        {         
567                $script = $this->parseSieveScript( $params['content'] );
568
569                foreach( $script as $i => $rule )
570                        if(is_array ($rule['name']) && is_array($original['id']))
571                        if( $rule['name'] === $original['id'] )
572                                return( $params = $rule );
573        }
574
575       
576        /**
577        * Método que lista as regras do usuário.
578        *
579        * @license    http://www.gnu.org/copyleft/gpl.html GPL
580        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
581        * @sponsor    Caixa EconÃŽmica Federal
582        * @author     Airton Bordin Junior
583        * @author         Gustavo Pereira dos Santos   
584        * @param      <$uri>
585        * @param      <$result>
586        * @param      <$criteria>
587        * @param      <$original>
588        * @return     <Regras do usuário>
589        * @access     <public>
590        */
591        public function listSieveRules( &$uri , &$params , &$criteria , $original  )
592        {
593                $return = $params = $this->parseSieveScript( $params[0]['content'] );
594                return( $return );
595        }
596}
Note: See TracBrowser for help on using the repository browser.