Projeto

Geral

Perfil

Estatísticas
| Branch: | Revisão:

expressolivretools / app / Console / Commands / Sogo / SieveSetListFile.php @ master

Histórico | Ver | Anotar | Baixar (6,9 KB)

1 ab2f5151 Alexandre Correia
<?php
2
3
namespace App\Console\Commands\Sogo;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Facades\DB;
7
use Illuminate\Support\Facades\File;
8
use Illuminate\Support\Facades\Storage;
9
10
class SieveSetListFile extends Command
11
{
12
    /**
13
     * The name and signature of the console command.
14
     *
15
     * @var string
16
     */
17
    protected $signature = 'sogo:set-user-sieve-script {--f|file=} {cmd?}';
18
19
    /**
20
     * The console command description.
21
     *
22
     * @var string
23
     */
24
    protected $description = 'cria script(s) sieve para usuario(s) sogo';
25
26
    /**
27
     * Create a new command instance.
28
     *
29
     * @return void
30
     */
31
    public function __construct()
32
    {
33
        parent::__construct();
34
    }
35
36
    /**
37
     * Execute the console command.
38
     *
39
     * @return mixed
40
     */
41
    public function handle()
42
    {
43
        $arguments = $this->arguments();
44
45
        $fileName = $this->option('file') ?? null;
46
47
        if( !file_exists('credential') ){
48
            $this->error(' Crie o arquivo de CREDENCIAIS  do cyrus.');
49
            die();
50
        }
51
52
        if( !is_null($fileName) ){
53
54
            $handle = fopen( $fileName, "r");
55
            
56
            if ($handle) {
57
                
58
                while ( ($line = fgets($handle)) !== false) {
59
60
                    // user | rule | is_active
61
                    $user     = "";
62
                    $rule     = "";
63
                    $isActive = "";
64
65
                    list( $user, $rule, $isActive ) = explode("|", $line );
66
67
                    // error offset
68
                    $ruleText = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {      
69
                        return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
70
                    }, $rule );
71
72
                    $this->writeFile( $user, $ruleText, $isActive );
73
                }
74
                
75
                fclose($handle);
76
                
77
                $sieveFiles = Storage::files( 'sieve' );
78
79
                foreach( $sieveFiles as $file )
80
                {
81
                    $user = preg_replace('/sieve\/sieve_/', '', $file );
82
83
                    $content = Storage::get( $file ) ;
84
                    $content = preg_replace('/\n/',',', $content );
85
                    $content = '{"SOGOSieveFilters":['.$content.']}';
86
87
                    File::put('fileSogoSieveFilter.json', $content );
88
                    
89
                    $commandSogoTool = "sogo-tool user-preferences set defaults {$user} -p credential SOGoSieveFilters -f fileSogoSieveFilter.json";
90
91
                    exec( $commandSogoTool );
92
                }
93
94
                if( file_exists('fileSogoSieveFilter.json') ){
95
                    File::delete('fileSogoSieveFilter.json');
96
                }
97
98
                if( file_exists('credential') ){
99
                    File::delete('credential');
100
                }
101
        
102
            } else {
103
                $this->error("Arquivo não encontrado");
104
            }                 
105
        }
106
        
107
    }
108
109
    private function writeFile( $user, $content, $isActive )
110
    {
111
        $rule = unserialize($content);
112
113
        $isActiveRule = ( intval($isActive) === 1 ? "1" : "0" );
114
115
        $newRule = '{"actions": [%actions%], "name": %name%, "rules": [%rules%], "match": %match%, "active": '.$isActiveRule.'}';
116
117
        // actions, name
118
        if( isset($rule['action']) ){
119
120
            $actions        = "";
121
            $name           = "";
122
123
            if( preg_match('/fileinto/', $rule['action']) ){
124
                $folderName = preg_replace('/fileinto:/','',$rule['action']);
125
                $actions = '{"argument": "'.$this->_toISO88591($folderName).'", "method": "fileinto"}';
126
                $name   .= 'ARQUIVAR em ' . $this->_toISO88591($folderName);
127
            }
128
129
            if( preg_match('/rejectText/', $rule['action']) ){
130
                $message = preg_replace('/rejectText:/','',$rule['action']);
131
                $message = $this->_toISO88591($message);
132
                $actions = '{"argument": "'. $message .'", "method": "reject"}';
133
                $name   .= 'REJEITAR com a mensagem : ' . $message;
134
            }
135
136
            if( preg_match('/flagged/', $rule['action']) ){
137
                $actions = '{"argument": "$label1", "method": "addflag"}';
138
                $name   .= 'MARCAR COMO IMPORTANTE ';
139
            }
140
141
            if( preg_match('/redirect/', $rule['action']) ){
142
                $emails = explode(';', preg_replace('/redirect:/','', $this->_toISO88591($rule['action'])));
143
                foreach( $emails as $email ){
144
                    $actions .= '{"argument": "'.$email.'", "method": "redirect"},';
145
                }
146
                $actions = rtrim($actions, ",");
147
                $name   .= 'REDIRECIONAR para ' . implode(', ', $emails );
148
            }
149
150
            if( preg_match('/discard/', $rule['action']) ){
151
                $actions = '{"argument": "", "method": "discard"}';
152
                $name   .= 'APAGAR mensagem ';
153
            }
154
155
            $newRule = preg_replace('/%actions%/', $actions, $newRule );
156
            $newRule = preg_replace('/%name%/', '"'.$name.'"', $newRule );
157
        }
158
159
        // match
160
        if( isset($rule['condition']) ){
161
            if($rule['condition'] === "anyof"){
162
                $newRule = preg_replace('/%match%/', '"any"', $newRule );
163
            }
164
            if($rule['condition'] === "allof"){
165
                $newRule = preg_replace('/%match%/', '"all"', $newRule );
166
            }
167
        }
168
169
        // fields from, to, subject
170
        $fieldFrom     = "";
171
        $fieldTo       = "";
172
        $fieldSubject  = "";
173
        
174
        if( isset($rule['from']) ){ $fieldFrom = '{"field": "from", "operator": "contains", "value": "'.$this->_toISO88591($rule['from']).'"}'; }
175
        if( isset($rule['to']) ){ $fieldTo = '{"field": "to", "operator": "contains", "value": "'.$this->_toISO88591($rule['to']).'"}'; }
176
        if( isset($rule['subject']) ){ $fieldSubject = '{"field": "subject", "operator": "contains", "value": "'.$this->_toISO88591($rule['subject']).'"}'; }
177
178
        $fields  = $fieldFrom;
179
        $fields .= ",".$fieldTo;
180
        $fields .= ",".$fieldSubject;
181
182
        if( trim($fields) !== "" ){ 
183
            $fields = preg_replace("/^\,{1,2}/","",$fields);
184
            $fields = preg_replace("/\,{1,2}$/","",$fields);
185
            $newRule = preg_replace('/%rules%/', $fields, $newRule );
186
        }
187
188
        Storage::append( 'sieve/sieve_'.$user, $newRule );
189
    }
190
191
        private function _toMailBox( $folder )
192
        {
193
                return $this->_toUTF8( $folder, false, 'UTF7-IMAP' );
194
        }
195
196
        private function _toUTF8( $str, $charset = false, $to = 'UTF-8' )
197
        {
198
                return mb_convert_encoding( $str, 'UTF-8', ( $charset === false? mb_detect_encoding( $str, 'UTF-8, ISO-8859-1', true ) : $charset ) );
199
    }
200
201
    private function _toISO88591( $str, $charset = false )
202
        {
203
                return mb_convert_encoding( $str, 'ISO-8859-1', ( $charset === false? mb_detect_encoding( $str, 'UTF-8, ISO-8859-1', true ) : $charset ) );
204
    }
205
206
}