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

Revision 5728, 18.2 KB checked in by airton, 12 years ago (diff)

Ticket #1782 - Especificar DFD0060 - Verificacoes para evitar Fatal Error no momento da chamada do interceptor

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                        /* Usado na opção Bloquear usuário do ExpressoMail */
87                        if($data['block']) {
88                                ($i >0) ? $script_match = 'elsif anyof' : $script_match = 'if anyof';
89                                $script_match = $script_match . "(address :is \"from\" [\"" .$data['name'] . "\"]) {\r\n"; 
90                                $script_match .= "fileinto \"INBOX/Spam\"; \r\n}\r\n";
91                                $script_rules .= $script_match;
92                                $script_match = "";
93                                $script_criteria = "";
94                                $require_fileinto = true;
95                                $i++;
96                                continue;
97                        }
98                       
99                        if( $data['enabled'] == 'false' )
100                                continue;
101
102                        $vacation = false;
103                        $criteria = $data['criteria'];
104                        $action   = $data['actions'];
105                       
106                        ($i >0) ? $script_match = 'els' : $script_match = '';
107                        $data['isExact'] == 'false' ?  $script_match .= 'if anyof (' : $script_match .= 'if allof (';
108
109
110                        if( is_array($criteria) )
111                        foreach ($criteria as $j => $value);
112                        {                                       
113                                 
114                                switch($criteria[$j]['field']) {
115                                        case 'To':   
116                                        case 'to':   
117                                        case 'CC':
118                                        case 'Cc':
119                                                $criteria[$j]['field'] = "[\"To\", \"TO\", \"Cc\", \"CC\"]";
120                                                $script_criteria .= "address :";
121                                                break;
122                                        case 'from':
123                                                $criteria[$j]['field'] = "\"" . $criteria[$j]['field'] . "\"";
124                                                $script_criteria .= "address :";
125                                                break;
126                                        case 'size':   
127                                                $criteria[$j]['field'] = '';
128                                                $script_criteria .= "size :";
129                                                break;
130                                        case 'subject':
131                                                $criteria[$j]['field'] = "\"" . $criteria[$j]['field'] . "\"";
132                                                $criteria[$j]['value'] = "" . imap_8bit($criteria[$j]['value']) . "\", \"" . base64_encode($criteria[$j]['value']) . "";
133                                                $script_criteria .= "header :";
134                                                break;
135                                        case 'body':
136                                                $criteria[$j]['field'] = '';
137                                                $script_criteria .= "body :";
138                                                $require_body = true;
139                                                break;
140                                        case 'vacation':
141                                                continue;
142                                        default:
143                                                $script_criteria .= "header :";
144                                                break;
145                                }
146                               
147                                switch ($criteria[$j]['operator']) {
148                                        case '>':
149                                                $criteria[$j]['operator'] = "over";
150                                                break;
151                                        case '<':
152                                                $criteria[$j]['operator'] = "under";
153                                                break;
154                                        case '=':
155                                                $criteria[$j]['operator'] = "is";
156                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "\"]";
157                                                break;
158                                        case '*':
159                                                $criteria[$j]['operator'] = "contains";
160                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "\"]";
161                                                break;                                         
162                                        case '^':
163                                                $criteria[$j]['operator'] = "matches";
164                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "*\"]";
165                                                $startswith = true;
166                                                break;
167                                        case '$':
168                                                $criteria[$j]['operator'] = "matches";
169                                                $criteria[$j]['value'] = "[\"*" . $criteria[$j]['value'] . "\"]";
170                                                $endswith = true;
171                                                break;
172                                        /*
173                                           TO-DO:
174                                           Arrrumar regra do "não contém".
175                                        */
176                                        case '!*':
177                                                $criteria[$j]['operator'] = "contains";
178                                                $criteria[$j]['value'] = "[\"" . $criteria[$j]['value'] . "\"]";
179                                                break;
180                                }
181                               
182                                if ($criteria[$j]['field'] == "" || $criteria[$j]['field'] == "\"subject\"" || $startswith || $endswith)
183                                {
184                                        $script_criteria .= $criteria[$j]['operator'] . " " . $criteria[$j]['field'] . " " . $criteria[$j]['value'] . ", ";
185                                        $startswith = $endswith = false;
186                                }
187                                else
188                                        $script_criteria .= $criteria[$j]['operator'] . " " . $criteria[$j]['field'] . " " . $criteria[$j]['value'] . ", ";
189                        }
190                        $script_criteria = substr($script_criteria,0,-2);
191                        /* if ($vacation == false) */
192                        $script_criteria .= ")";
193
194                        $script_action = " {\r\n ";
195                       
196                        if( is_array($actions) )
197                        foreach ($action as $k=> $value);
198                        {
199                                switch ($action[$k]['type']) {
200                                        case 'redirect':
201                                                break;
202                                        case 'reject':
203                                                $require_reject = true;
204                                                break;
205                                        case 'fileinto':
206                                                $require_fileinto = true;
207                                                break;
208                                        case 'vacation':
209                                                $require_vacation = true;
210                                                $action[$k]['parameter'] = "\"" . $action[$k]['parameter'] . "\"";
211                                                $vacation_action = " :subject \"Fora do Escritório\" " . $action[$k]['parameter'] . ";";
212                                                $vacation = true;
213                                                continue;
214                                        case 'setflag':
215                                                $require_flag = true;
216                                                $action[$k]['parameter'] = "\\\\" . $action[$k]['parameter'];
217                                                break;
218                                        case 'discard':
219                                                break;
220                                }
221                                if ($vacation == false) $script_action .= $action[$k]['type'] . " \"" . $action[$k]['parameter'] . "\";\r\n ";
222                        }
223
224                        $script_action .= "}";
225                       
226                        if($vacation != true)
227                                $script_rules .= $script_match . $script_criteria . $script_action . "\r\n";
228
229                        if($data['id'] != "vacation")
230                                $i++;
231                        $script_match = "";
232                        $script_criteria = "";
233                       
234                }
235
236                if($require_reject || $require_fileinto || $require_vacation || $require_body || $require_flag)
237                {
238                        $script_header .= "require [";
239                        $require_reject ? $script_header .= "\"reject\", " : "";
240                        $require_fileinto ? $script_header .= "\"fileinto\", " : "";
241                        $require_vacation? $script_header .= "\"vacation\", " : ""; 
242                        $require_flag ? $script_header .= "\"imapflags\", " : ""; 
243                        $require_body ? $script_header .= "\"body\", " : "";  /* tem que instalar as extensões no Cyrus */
244                        $script_header = substr($script_header,0,-2);
245                        $script_header .= "];\r\n";
246                }
247
248                if( $vacation_action )
249                {
250                  $script_rules .= "vacation" . $vacation_action . "\r\n";
251                }
252
253                $json_data = json_encode($rules);
254               
255                $script_begin = "#Filtro gerado por Expresso Livre versão 2.4\r\n\r\n";
256
257                $content = $script_begin . $script_header . $script_rules . "\r\n\r\n#PseudoScript#" . "\r\n#" . $json_data;
258                //$content = "";
259                return( $content );
260        }
261       
262        /**
263        * Método que lê e faz o parser dos filtros antigos
264        *
265        * @license    http://www.gnu.org/copyleft/gpl.html GPL
266        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
267        * @sponsor    Caixa EconÃŽmica Federal
268        * @author     Airton Bordin Junior
269        * @author         Gustavo Pereira dos Santos   
270        * @param      <$scriptName> <Regras do usuário>
271        * @return     <Regra do usuário parseada>
272        * @access     <public>
273        */
274        public function readOldScript($scriptName)
275        {
276        // Recebe o conteúdo do array;
277        $lines = array();
278        $lines = preg_split("/\n/", $scriptName);
279
280        // Pega o tamanho da regra na primeira do script;
281        $size_rule = array_shift($lines);
282
283        // Recebe o tamanho do script, pela primeira linha;
284        $this->size = trim($size_rule);
285
286        // Verifica a composição do script; */
287         $line = array_shift($lines);
288
289        // Variaveis para a regra e o campo ferias;
290        $regexps = array('^ *##PSEUDO', '^ *#rule', '^ *#vacation', '^ *#mode');
291        $retorno['rule'] = array();
292
293        $line = array_shift($lines);
294        while (isset($line)) {
295            foreach ($regexps as $regp) {
296                if (preg_match("/$regp/i", $line)) {
297                    // Recebe todas as regras criadas no servidor;
298                    if (preg_match("/^ *#rule&&/i", $line)) {
299                        $retorno['rule'][] = $line . "\n";
300                    }
301                }
302            }
303            // Pega a proxima linha do sript;
304            $line = array_shift($lines);
305        }
306        return $retorno;
307    }
308       
309       
310       
311       
312        /**
313        * Método que faz o parsing do Script Sieve, transformando em Array.
314        *
315        * @license    http://www.gnu.org/copyleft/gpl.html GPL
316        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
317        * @sponsor    Caixa EconÃŽmica Federal
318        * @author     Airton Bordin Junior
319        * @author         Gustavo Pereira dos Santos   
320        * @param      <String> <$script> <Script Sieve com as regras do usuário>
321        * @return     <Regras do usuário em Array>
322        * @access     <public>
323        */
324        public function parseSieveScript( $script )
325        {
326                /*
327                $old_rule = strripos($script, "##PSEUDO script start");
328               
329                if($old_rule) {
330                       
331                        $parsed_rule = $this->readOldScript($old_script);
332                        $array_rule = explode("&&", $parsed_rule['rule'][0]);
333
334                        $old_retorno = array();
335                        $old_retorno['isExact'] = false;
336                        $old_retorno['name'] = $array_rule[1];
337                        $old_retorno['criteria'] = array();
338                        $old_retorno['criteria'][0] = array();
339                        $old_retorno['criteria'][0]['value'] = $array_rule[5];
340                        $old_retorno['criteria'][0]['operator'] = '=';
341                        $old_retorno['criteria'][0]['field'] = 'subject';
342                        $old_retorno['actions'] = array();
343                        $old_retorno['actions'][0] = array();
344                        $old_retorno['actions'][0]['parameter'] = $array_rule[7];
345                        $old_retorno['actions'][0]['type'] = $array_rule[6];
346                        $old_retorno['enabled'] = true;
347                        $old_retorno['id'] = $array_rule[1];
348                        $old_retorno['applyMessages'] = '';
349
350                        return $old_retorno;
351                }
352                */
353                $pos = strripos($script, "#PseudoScript#");
354                $pseudo_script = substr( $script, $pos+17 );
355
356                $return = json_decode( $pseudo_script, true );
357
358                return $return;
359        }
360
361        var $rules = false;
362
363        /**
364        * Construtor da classe.
365        *
366        * @license    http://www.gnu.org/copyleft/gpl.html GPL
367        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
368        * @sponsor    Caixa EconÃŽmica Federal
369        * @author     Airton Bordin Junior
370        * @author         Gustavo Pereira dos Santos   
371        * @access     <public>
372        */
373        public function __construct()
374        {
375                $this->service = Controller::service("Sieve");
376        }
377
378       
379        /**
380        * Método que recupera as regras do usuário.
381        *
382        * @license    http://www.gnu.org/copyleft/gpl.html GPL
383        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
384        * @sponsor    Caixa EconÃŽmica Federal
385        * @author     Airton Bordin Junior
386        * @author         Gustavo Pereira dos Santos   
387        * @return     <Regras do usuário>
388        * @access     <public>
389        */
390        public function getRules()
391        {
392                $this->rules = Controller::find( array( 'concept' => 'filter' ) );
393
394                if( !$this->rules ) {
395                        $this->rules = array();
396                }
397                return( $this->rules );
398        }
399
400       
401        /**
402        * Método que aplica o filtro para as mensagens do usuário.
403        *
404        * @license    http://www.gnu.org/copyleft/gpl.html GPL
405        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
406        * @sponsor    Caixa EconÃŽmica Federal
407        * @author     Airton Bordin Junior
408        * @author         Gustavo Pereira dos Santos   
409        * @param      <$uri>
410        * @param      <$result>
411        * @param      <$criteria>
412        * @param      <$original>
413        * @access     <public>
414        */
415        public function applySieveFilter( &$uri , &$result , &$criteria , $original  )
416        {
417                $result['id'] = $uri['id'];
418                $rule_apply = array();
419               
420                $filter = Controller::read($uri);
421                $filter_ = $this->parseSieveScript($filter['content']);
422               
423                foreach ($filter_ as $f_) {
424                        if($f_['id'] == $uri['id']) {
425                                $rule_apply     = $f_;
426                        }
427                }
428               
429                $actions = array();
430                $actions['type']      = $rule_apply['actions'][0]['type'];
431                $actions['parameter'] = $rule_apply['actions'][0]['parameter'];
432               
433                $messages = $rule_apply['applyMessages'];
434                 
435                         
436                $proc = array();
437                $proc['keep'] = false;
438                     
439               
440                $imap = Controller::service( 'Imap' );
441                //$imap->apliSieveFilter($original['properties']['applyMessages'] , $proc );
442                $imap->apliSieveFilter($messages , $actions );
443                return $result;
444        }
445
446       
447        /**
448        * Método que lê o script do usuário.
449        *
450        * @license    http://www.gnu.org/copyleft/gpl.html GPL
451        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
452        * @sponsor    Caixa EconÃŽmica Federal
453        * @author     Airton Bordin Junior
454        * @author         Gustavo Pereira dos Santos   
455        * @param      <$uri>
456        * @param      <$result>
457        * @param      <$criteria>
458        * @param      <$original>
459        * @return     <Script do usuário>
460        * @access     <public>
461        */
462        public function readUserScript( &$uri , &$params , &$criteria , $original )
463        { 
464                $uri['id'] = $this->service->config['user'];
465        }
466 
467 
468        /**
469        * Método que seta o script do usuário.
470        *
471        * @license    http://www.gnu.org/copyleft/gpl.html GPL
472        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
473        * @sponsor    Caixa EconÃŽmica Federal
474        * @author     Airton Bordin Junior
475        * @author         Gustavo Pereira dos Santos   
476        * @param      <$uri>
477        * @param      <$result>
478        * @param      <$criteria>
479        * @param      <$original>
480        * @return     <Script do usuário>
481        * @access     <public>
482        */
483        public function setRule( &$uri , &$params , &$criteria , $original  )
484        {
485                if( !$this->rules )
486                $this->rules = $this->getRules();
487
488            $uri['id'] = $params['id'] = isset($params['id']) ? $params['id'] : urlencode($params['name']);
489
490            $i = 0;
491
492            for( ; isset($this->rules[$i]) && $this->rules[$i]['id'] !== $params['id']; $i++ );
493
494            $this->rules[$i] = array_merge( ( isset($this->rules[$i]) ? $this->rules[$i] : array() ), $params );
495
496            $params = array( 'name' => $this->service->config['user'],
497                             'content' => $this->formatSieveScript( $this->rules ),
498                             'active' => true );
499        }
500
501       
502        /**
503        * Método que deleta o script do usuário.
504        *
505        * @license    http://www.gnu.org/copyleft/gpl.html GPL
506        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
507        * @sponsor    Caixa EconÃŽmica Federal
508        * @author     Airton Bordin Junior
509        * @author         Gustavo Pereira dos Santos   
510        * @param      <$uri>
511        * @param      <$result>
512        * @param      <$criteria>
513        * @param      <$original>
514        * @access     <public>
515        */
516        public function deleteRule( &$uri, &$params, &$criteria, $original )
517        {
518                if( !$this->rules ) {   
519                        $this->rules = $this->getRules();
520                }         
521                $params['id'] = $uri['id'];
522
523                $update = false;
524               
525                $rules = array();
526
527                foreach( $this->rules as $i => $rule )
528                        if( $rule['id'] !== $uri['id'] )
529                                $rules[] = $this->rules[$i];
530
531                $this->rules = $rules;
532               
533                $uri['id'] = '';
534
535                $params = array( 'name' => $this->service->config['user'],
536                           'content' => $this->formatSieveScript( $this->rules ),
537                           'active' => true );
538
539                $URI = Controller::URI( $uri['concept'], $this->service->config['user'] );
540                $this->service->update( $URI, $params );
541       
542                return( false );
543        }
544
545       
546        /**
547        * Método que pega o script do usuário.
548        *
549        * @license    http://www.gnu.org/copyleft/gpl.html GPL
550        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
551        * @sponsor    Caixa EconÃŽmica Federal
552        * @author     Airton Bordin Junior
553        * @author         Gustavo Pereira dos Santos   
554        * @param      <$uri>
555        * @param      <$result>
556        * @param      <$criteria>
557        * @param      <$original>
558        * @return     <Script do usuário>
559        * @access     <public>
560        */
561        public function getSieveRule( &$uri , &$params , &$criteria , $original )
562        {         
563                $script = $this->parseSieveScript( $params['content'] );
564
565                foreach( $script as $i => $rule )
566                        if( $rule['name'] === $original['id'] )
567                                return( $params = $rule );
568        }
569
570       
571        /**
572        * Método que lista as regras do usuário.
573        *
574        * @license    http://www.gnu.org/copyleft/gpl.html GPL
575        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
576        * @sponsor    Caixa EconÃŽmica Federal
577        * @author     Airton Bordin Junior
578        * @author         Gustavo Pereira dos Santos   
579        * @param      <$uri>
580        * @param      <$result>
581        * @param      <$criteria>
582        * @param      <$original>
583        * @return     <Regras do usuário>
584        * @access     <public>
585        */
586        public function listSieveRules( &$uri , &$params , &$criteria , $original  )
587        {
588                $return = $params = $this->parseSieveScript( $params[0]['content'] );
589                return( $return );
590        }
591}
Note: See TracBrowser for help on using the repository browser.