MailController.php 15.5 KB
Newer Older
1
2
3
4
<?php

namespace App\Http\Controllers;

5
use App\Mail\Sprachdatei;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\Redis;
8
use Illuminate\Http\Response;
9
use LaravelLocalization;
10
use Mail;
Dominik Hebeler's avatar
Dominik Hebeler committed
11
use Log;
12
use Validator;
Dominik Hebeler's avatar
Dominik Hebeler committed
13
14
use \IBAN;
use \IBANCountry;
15
16
17
18
19
20
21
22
23

class MailController extends Controller
{
    /**
     * Load Startpage accordingly to the given URL-Parameter and Mobile
     *
     * @param  int  $id
     * @return Response
     */
Dominik Hebeler's avatar
Dominik Hebeler committed
24
25
    public function contactMail(Request $request)
    {
26
        # Nachricht, die wir an den Nutzer weiterleiten:
Dominik Hebeler's avatar
Dominik Hebeler committed
27
        $messageType = ""; # [success|error]
28
        $returnMessage = '';
29
30

        # Wir benötigen 3 Felder von dem Benutzer wenn diese nicht übermittelt wurden, oder nicht korrekt sind geben wir einen Error zurück
31
        $input_data = $request->all();
32
33

        $maxFileSize = 5 * 1024;
34
        $validator = Validator::make(
35
            $input_data,
36
            [
Dominik Hebeler's avatar
Dominik Hebeler committed
37
                'email' => 'required|email',
Dominik Hebeler's avatar
Dominik Hebeler committed
38
                'pcsrf' => ['required', 'string', new \App\Rules\PCSRF],
39
                'attachments' => ['max:5'],
40
                'attachments.*' => ['file', 'max:' . $maxFileSize],
41
42
43
            ]
        );

Dominik Hebeler's avatar
Dominik Hebeler committed
44
        if ($validator->fails()) {
45
46
47
48
49
            return view('kontakt.kontakt')->with('formerrors', $validator)->with('title', trans('titles.kontakt'))->with('navbarFocus', 'kontakt');
        }

        $name = $request->input('name', '');

Dominik Hebeler's avatar
Dominik Hebeler committed
50
        $replyTo = $request->input('email', 'noreply@metager.de');
Dominik Hebeler's avatar
Dominik Hebeler committed
51
        if ($replyTo === "") {
52
            $replyTo = "noreply@metager.de";
Dominik Hebeler's avatar
Dominik Hebeler committed
53
        } else {
54
55
56
            $replyTo = $request->input('email');
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
57
        if (!$request->filled('message') || !$request->filled('subject')) {
Dominik Hebeler's avatar
Dominik Hebeler committed
58
            $messageType = "error";
59
            $returnMessage = trans('kontakt.error.1');
Dominik Hebeler's avatar
Dominik Hebeler committed
60
        } else {
61
            $message = $request->input('message');
62
            $subject = $request->input('subject');
63

64
            # Wir versenden die Mail des Benutzers an uns:
65
66
67
68
69
70
71
72
73
            $postdata = [
                "alert" => true,
                "autorespond" => true,
                "source" => "API",
                "name" => $name,
                "email" => $replyTo,
                "subject" => $subject,
                "ip" => $request->ip(),
                "deptId" => 5,
74
75
                "message" => "data:text/plain;charset=utf-8, $message",
                "attachments" => []
76
77
            ];

Dominik Hebeler's avatar
Dominik Hebeler committed
78
            if($request->has("attachments") && is_array($request->file("attachments"))){
79
80
81
82
83
84
85
                foreach($request->file("attachments") as $attachment){
                    $postdata["attachments"][] = [
                        $attachment->getClientOriginalName() => "data:" . $attachment->getMimeType() . ";base64," . base64_encode(file_get_contents($attachment->getRealPath()))
                    ];
                }
            }  

Dominik Hebeler's avatar
Dominik Hebeler committed
86
            if (LaravelLocalization::getCurrentLocale() === "de") {
87
                $postdata["deptId"] = 1;
88
            }
89

90
91
92
            $postdata = json_encode($postdata);

            $resulthash = md5($subject . $message);
93

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
            $mission = [
                "resulthash" => $resulthash,
                "url" => env("TICKET_URL", "https://metager.de"),
                "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
                "username" => null,
                "password" => null,
                "headers" => [
                    "X-API-Key" => env("TICKET_APIKEY", ""),
                    "Content-Type" => "application/json",
                    "Content-Length" => strlen($postdata)
                ],
                "cacheDuration" => 0,
                "name" => "Ticket",
                "curlopts" => [
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => $postdata,
                    CURLOPT_LOW_SPEED_TIME => 20,
                    CURLOPT_CONNECTTIMEOUT => 10,
                    CURLOPT_TIMEOUT => 20
                ]
            ];
            $mission = json_encode($mission);
            Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);

            // Fetch the result
            $answer = Redis::blpop($resulthash, 20);
            
            // Fehlerfall
            if(empty($answer) || (is_array($answer) && sizeof($answer) === 2 && $answer[1] === "no-result")){
                $messageType = "error";
                $returnMessage = trans('kontakt.error.2', ["email" => env("MAIL_USERNAME", "support+46521@metager.de")]);
            }else{
                $returnMessage = trans('kontakt.success.1', ["email" => $replyTo]);
                $messageType = "success";
            }
129
130
131
        }

        return view('kontakt.kontakt')
Dominik Hebeler's avatar
Dominik Hebeler committed
132
            ->with('title', 'Kontakt')
133
            ->with('js', ['lib.js'])
Dominik Hebeler's avatar
Dominik Hebeler committed
134
            ->with($messageType, $returnMessage);
135
    
136
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
137
138
139

    public function donation(Request $request)
    {
140
141
142
143
144
        $firstname = "";
        $lastname = "";
        $company = "";
        $private = $request->input('person', '') === 'private' ? true : false;
        if($request->input('person', '') === 'private') {
Davide Aprea's avatar
Davide Aprea committed
145
146
            $firstname = $request->input('firstname');
            $lastname = $request->input('lastname');
147
        } elseif($request->input('person', '') === 'company') {
Davide Aprea's avatar
Davide Aprea committed
148
149
150
            $company = $request->input('companyname');
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
151
        $data = [
152
153
154
155
            'person' => $request->input('person', ''),
            'firstname' => $request->input('firstname', ''),
            'lastname' => $request->input('lastname', ''),
            'company' => $company,
Dominik Hebeler's avatar
Dominik Hebeler committed
156
157
158
            'iban' => $request->input('iban', ''),
            'bic' => $request->input('bic', ''),
            'email' => $request->input('email', ''),
159
            'betrag' => $request->input('amount', ''),
Phil Höfer's avatar
Phil Höfer committed
160
            'frequency' => $request->input('frequency', ''),
Dominik Hebeler's avatar
Dominik Hebeler committed
161
162
            'nachricht' => $request->input('Nachricht', ''),
        ];
Davide Aprea's avatar
Davide Aprea committed
163
    
Dominik Hebeler's avatar
Dominik Hebeler committed
164
165
166
        $iban = $request->input('iban', '');
        $bic = $request->input('bic', '');
        $email = $request->input('email', '');
167
        $frequency = $request->input('frequency', '');
Phil Höfer's avatar
Phil Höfer committed
168
        $betrag = $request->input('amount', '');
Dominik Hebeler's avatar
Dominik Hebeler committed
169
        $nachricht = $request->input('Nachricht', '');
170

Phil Höfer's avatar
Phil Höfer committed
171
        # Allow custom amounts
172
        if ($betrag == "custom" && $request->filled('custom-amount')) {
Phil Höfer's avatar
Phil Höfer committed
173
174
175
176
            $betrag = $request->input('custom-amount', '');
            $data['betrag'] = $betrag;
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
177
178
179
180
181
182
183
184
185
        # Check for valid frequency
        $validFrequencies = [
            "once",
            "monthly",
            "quarterly",
            "six-monthly",
            "annual",
        ];

Dominik Hebeler's avatar
Dominik Hebeler committed
186
187
        # Der enthaltene String wird dem Benutzer nach der Spende ausgegeben
        $messageToUser = "";
Dominik Hebeler's avatar
Dominik Hebeler committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
        $messageType = ""; # [success|error]

        # Check the IBAN
        $iban = new IBAN($iban);
        $country = new IBANCountry($iban->Country());
        $isSEPA = filter_var($country->IsSEPA(), FILTER_VALIDATE_BOOLEAN);

        # Check the amount
        $validBetrag = is_numeric($betrag) && $betrag > 0;

        # Validate Email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $email = "anonymous@suma-ev.de";
        }
202
        if(($private && (empty($firstname) || empty($lastname))) || (!$private && empty($company))){
Davide Aprea's avatar
Davide Aprea committed
203
204
205
            $messageToUser = trans('spende.error.name');
            $messageType = "error";
        } elseif (!$iban->Verify()) {
Dominik Hebeler's avatar
Dominik Hebeler committed
206
            $messageToUser = trans('spende.error.iban');
Dominik Hebeler's avatar
Dominik Hebeler committed
207
            $messageType = "error";
208
        } elseif (!$isSEPA && $bic === '') {
Dominik Hebeler's avatar
Dominik Hebeler committed
209
            $messageToUser = trans('spende.error.bic');
Dominik Hebeler's avatar
Dominik Hebeler committed
210
            $messageType = "error";
211
        } elseif (!$validBetrag) {
Dominik Hebeler's avatar
Dominik Hebeler committed
212
213
214
215
            $messageToUser = trans('spende.error.amount');
            $messageType = "error";
        } elseif (!in_array($frequency, $validFrequencies)) {
            $messageToUser = trans('spende.error.frequency');
Dominik Hebeler's avatar
Dominik Hebeler committed
216
            $messageType = "error";
Dominik Hebeler's avatar
Dominik Hebeler committed
217
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
218

Dominik Hebeler's avatar
Dominik Hebeler committed
219
220
221
            # The value has to have a maximum of 2 decimal digits
            $betrag = round($betrag, 2, PHP_ROUND_HALF_DOWN);

Davide Aprea's avatar
Davide Aprea committed
222
            # Generating personalised key for donor
223
            $key = app('App\Models\Key')->generateKey($betrag, null, null, 'Für ' . $betrag . '€ aufgeladen am '. date("d.m.Y"));
Davide Aprea's avatar
Davide Aprea committed
224

Dominik Hebeler's avatar
Dominik Hebeler committed
225
            try {
226
                $postdata = [
Davide Aprea's avatar
Davide Aprea committed
227
228
                    "entity" => "Contribution",
                    "action" => "mgcreate",
229
230
                    "api_key" => env("CIVICRM_API_KEY", ''),
                    "key" => env("CIVICRM_SITE_KEY", ''),
Davide Aprea's avatar
Davide Aprea committed
231
                    "json" => 1,
Davide Aprea's avatar
Davide Aprea committed
232
233
                    "iban" => $iban->MachineFormat(),
                    "bic" => $bic,
Davide Aprea's avatar
Davide Aprea committed
234
235
                    "amount" => $betrag,
                    "frequency" => $frequency,
236
                    "email" => $email,
Davide Aprea's avatar
Davide Aprea committed
237
                    "mgkey" => $key,
Davide Aprea's avatar
Davide Aprea committed
238
                    "message" => $nachricht
239
                ];
Dominik Hebeler's avatar
Dominik Hebeler committed
240

Davide Aprea's avatar
Davide Aprea committed
241
242
243
244
                if($request->input('person') === 'private') {
                    $postdata['first_name'] = $firstname;
                    $postdata['last_name'] = $lastname;
                } elseif($request->input('person') === 'company') {
Davide Aprea's avatar
Davide Aprea committed
245
                    $postdata['business_name'] = $company;
246
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
247

Davide Aprea's avatar
Davide Aprea committed
248
                $postdata = http_build_query($postdata);
249
    
250
                $resulthash = md5(json_encode($postdata));
251
252
253
    
                $mission = [
                    "resulthash" => $resulthash,
254
                    "url" => env("CIVICRM_URL", "https://metager.de"),
255
256
257
258
                    "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
                    "username" => null,
                    "password" => null,
                    "headers" => [
Davide Aprea's avatar
Davide Aprea committed
259
                        "Content-Type" => "application/x-www-form-urlencoded",
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
                    ],
                    "cacheDuration" => 0,
                    "name" => "Ticket",
                    "curlopts" => [
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => $postdata,
                        CURLOPT_LOW_SPEED_TIME => 20,
                        CURLOPT_CONNECTTIMEOUT => 10,
                        CURLOPT_TIMEOUT => 20
                    ]
                ];
                $mission = json_encode($mission);
                Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);
    
                // Fetch the result
                $answer = Redis::blpop($resulthash, 20);
                
                // Fehlerfall
                if(empty($answer) || (is_array($answer) && sizeof($answer) === 2 && $answer[1] === "no-result")){
                    $messageType = "error";
                    $messageToUser = "Beim Senden Ihrer Spendenbenachrichtigung ist ein Fehler auf unserer Seite aufgetreten. Bitte schicken Sie eine E-Mail an: dominik@suma-ev.de, damit wir uns darum kümmern können.";
                }else{
                    $messageToUser = "Herzlichen Dank!! Wir haben Ihre Spendenbenachrichtigung erhalten.";
                    $messageType = "success";
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
285
            } catch (\Swift_TransportException $e) {
Dominik Hebeler's avatar
Dominik Hebeler committed
286
                Log::error($e->getMessage());
Dominik Hebeler's avatar
Dominik Hebeler committed
287
                $messageType = "error";
288
                $messageToUser = 'Beim Senden Ihrer Spendenbenachrichtigung ist ein Fehler auf unserer Seite aufgetreten. Bitte schicken Sie eine E-Mail an: dominik@suma-ev.de, damit wir uns darum kümmern können.';
Dominik Hebeler's avatar
Dominik Hebeler committed
289
290
291
            }
        }

292
        if ($messageType === "error") {
293
            return view('spende.spende')
294
                ->with('title', 'Kontakt')
Dominik Hebeler's avatar
Dominik Hebeler committed
295
296
                ->with($messageType, $messageToUser)
                ->with('data', $data);
297
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
298
            $data['iban'] = $iban->HumanFormat();
Davide Aprea's avatar
Davide Aprea committed
299
            $data['key'] = $key;
300
            $data = base64_encode(serialize($data));
301
            return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), route("danke", ['data' => $data])));
302
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
303
    }
304

305
    #Ueberprueft ob ein bereits vorhandener Eintrag bearbeitet worden ist
306
    public static function isEdited($k, $v, $filename)
307
    {
308
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
309
            $temp = include resource_path() . "/" . $filename;
310
            foreach ($temp as $key => $value) {
Dominik Hebeler's avatar
Dominik Hebeler committed
311
                if ($k === $key && $v !== $value) {
312
313
                    return true;
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
314
            }
315
316
317
        } catch (\ErrorException $e) {
            #Datei existiert noch nicht
            return true;
318
319
320
321
        }
        return false;
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
322
    public function sendLanguageFile(Request $request, $from, $to, $exclude = "", $email = "")
323
324
325
326
    {
        $filename = $request->input('filename');
        # Wir erstellen nun zunächst den Inhalt der Datei:
        $data = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
327
        $new = 0;
328
        $emailAddress = "";
329
        $editedKeys = "";
330
331
332
333
        foreach ($request->all() as $key => $value) {
            if ($key === "filename" || $value === "") {
                continue;
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
334
            if ($key === "email") {
335
336
337
                $emailAddress = $value;
                continue;
            }
338
            $key = base64_decode($key);
339
340
341
            if (strpos($key, "_new_") === 0 && $value !== "") {
                $new++;
                $key = substr($key, strpos($key, "_new_") + 5);
Dominik Hebeler's avatar
Dominik Hebeler committed
342
                $editedKeys = $editedKeys . "\n" . $key;
343
            } elseif ($this->isEdited($key, $value, $filename)) {
344
                $new++;
Dominik Hebeler's avatar
Dominik Hebeler committed
345
                $editedKeys = $editedKeys . "\n" . $key;
346
            }
347

348
349
350
351
352
353
354
355
356
357
358
359
360
            $key = trim($key);
            if (!strpos($key, "#")) {
                $data[$key] = $value;
            } else {
                $ref = &$data;
                do {
                    $ref = &$ref[substr($key, 0, strpos($key, "#"))];
                    $key = substr($key, strpos($key, "#") + 1);
                } while (strpos($key, "#"));
                $ref = &$ref[$key];
                $ref = $value;
            }
        }
361

362
        $output = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
363
364
365
        $output = preg_replace("/\{/si", "[", $output);
        $output = preg_replace("/\}/si", "]", $output);
        $output = preg_replace("/\": ([\"\[])/si", "\"\t=>\t$1", $output);
Dominik Hebeler's avatar
Dominik Hebeler committed
366

367
368
        $output = "<?php\n\nreturn $output;\n";

369
370
        $message = "Moin moin,\n\nein Benutzer hat eine Sprachdatei aktualisiert.\nBearbeitet wurden die Einträge: $editedKeys\n\nSollten die Texte so in Ordnung sein, ersetzt, oder erstellt die Datei aus dem Anhang in folgendem Pfad:\n$filename\n\nFolgend zusätzlich der Inhalt der Datei:\n\n$output";

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
        # Wir haben nun eine Mail an uns geschickt, welche die entsprechende Datei beinhaltet.
        # Nun müssen wir den Nutzer eigentlich nur noch zurück leiten und die Letzte bearbeitete Datei ausschließen:
        $ex = [];
        if ($exclude !== "") {
            try {
                $ex = unserialize(base64_decode($exclude));
            } catch (\ErrorException $e) {
                $ex = [];
            }

            if (!isset($ex["files"])) {
                $ex["files"] = [];
            }
        }
        if (!isset($ex["new"])) {
            $ex["new"] = 0;
        }
        $ex['files'][] = basename($filename);
        $ex["new"] += $new;
390
391

        if ($new > 0) {
Dominik Hebeler's avatar
Dominik Hebeler committed
392
            if ($emailAddress !== "") {
Aria Givi's avatar
Aria Givi committed
393
                Mail::to("dev@suma-ev.de")
Dominik Hebeler's avatar
Dominik Hebeler committed
394
                    ->send(new Sprachdatei($message, $output, basename($filename), $emailAddress));
395
            } else {
Aria Givi's avatar
Aria Givi committed
396
                Mail::to("dev@suma-ev.de")
Dominik Hebeler's avatar
Dominik Hebeler committed
397
                    ->send(new Sprachdatei($message, $output, basename($filename)));
398
            }
399
        }
400
        $ex = base64_encode(serialize($ex));
401
402

        return redirect(url('languages/edit', ['from' => $from, 'to' => $to, 'exclude' => $ex, 'email' => $emailAddress]));
403
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
404
}