MailController.php 22 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 \PHP_IBAN\IBAN;
use \PHP_IBAN\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
            ];

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

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
            $mission = [
                "resulthash" => $resulthash,
96
                "url" => config("metager.metager.ticketsystem.url"),
97
98
99
100
                "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
                "username" => null,
                "password" => null,
                "headers" => [
101
                    "X-API-Key" => config("metager.metager.ticketsystem.apikey"),
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                    "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);
120

121
            // Fehlerfall
122
            if (empty($answer) || (is_array($answer) && sizeof($answer) === 2 && $answer[1] === "no-result")) {
123
                $messageType = "error";
124
                $returnMessage = trans('kontakt.error.2', ["email" => config("mail.mailers.smtp.username")]);
125
            } else {
126
127
128
                $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
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
136
137
138

    public function donation(Request $request)
    {
139
140
141
142
143
144
145
146
147
148
        # Wir benötigen 3 Felder von dem Benutzer wenn diese nicht übermittelt wurden, oder nicht korrekt sind geben wir einen Error zurück
        $input_data = $request->all();

        $validator = Validator::make(
            $input_data,
            [
                'pcsrf' => ['required', 'string', new \App\Rules\PCSRF],
            ]
        );

149
150
151
152
        $firstname = "";
        $lastname = "";
        $company = "";
        $private = $request->input('person', '') === 'private' ? true : false;
153
        if ($request->input('person', '') === 'private') {
Davide Aprea's avatar
Davide Aprea committed
154
155
            $firstname = $request->input('firstname');
            $lastname = $request->input('lastname');
156
        } elseif ($request->input('person', '') === 'company') {
Davide Aprea's avatar
Davide Aprea committed
157
158
159
            $company = $request->input('companyname');
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
160
        $data = [
161
162
163
164
            'person' => $request->input('person', ''),
            'firstname' => $request->input('firstname', ''),
            'lastname' => $request->input('lastname', ''),
            'company' => $company,
Dominik Hebeler's avatar
Dominik Hebeler committed
165
166
167
            'iban' => $request->input('iban', ''),
            'bic' => $request->input('bic', ''),
            'email' => $request->input('email', ''),
168
            'betrag' => $request->input('amount', ''),
Phil Höfer's avatar
Phil Höfer committed
169
            'frequency' => $request->input('frequency', ''),
Dominik Hebeler's avatar
Dominik Hebeler committed
170
171
            'nachricht' => $request->input('Nachricht', ''),
        ];
172

Dominik Hebeler's avatar
Dominik Hebeler committed
173
174
175
        $iban = $request->input('iban', '');
        $bic = $request->input('bic', '');
        $email = $request->input('email', '');
176
        $frequency = $request->input('frequency', '');
Phil Höfer's avatar
Phil Höfer committed
177
        $betrag = $request->input('amount', '');
Dominik Hebeler's avatar
Dominik Hebeler committed
178
        $nachricht = $request->input('Nachricht', '');
179

Phil Höfer's avatar
Phil Höfer committed
180
        # Allow custom amounts
181
        if ($betrag == "custom" && $request->filled('custom-amount')) {
Phil Höfer's avatar
Phil Höfer committed
182
183
184
185
            $betrag = $request->input('custom-amount', '');
            $data['betrag'] = $betrag;
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
186
187
188
189
190
191
192
193
194
        # Check for valid frequency
        $validFrequencies = [
            "once",
            "monthly",
            "quarterly",
            "six-monthly",
            "annual",
        ];

Dominik Hebeler's avatar
Dominik Hebeler committed
195
196
        # Der enthaltene String wird dem Benutzer nach der Spende ausgegeben
        $messageToUser = "";
Dominik Hebeler's avatar
Dominik Hebeler committed
197
198
199
200
201
202
203
204
205
206
207
208
        $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)) {
209
            $email = "";
Dominik Hebeler's avatar
Dominik Hebeler committed
210
        }
211
212
213
214

        if ($validator->fails()) {
            $messageToUser = trans('spende.error.robot');
            $messageType = "error";
215
        } elseif (($private && (empty($firstname) || empty($lastname))) || (!$private && empty($company))) {
Davide Aprea's avatar
Davide Aprea committed
216
217
218
            $messageToUser = trans('spende.error.name');
            $messageType = "error";
        } elseif (!$iban->Verify()) {
Dominik Hebeler's avatar
Dominik Hebeler committed
219
            $messageToUser = trans('spende.error.iban');
Dominik Hebeler's avatar
Dominik Hebeler committed
220
            $messageType = "error";
221
        } elseif (!$isSEPA && $bic === '') {
Dominik Hebeler's avatar
Dominik Hebeler committed
222
            $messageToUser = trans('spende.error.bic');
Dominik Hebeler's avatar
Dominik Hebeler committed
223
            $messageType = "error";
224
        } elseif (!$validBetrag) {
Dominik Hebeler's avatar
Dominik Hebeler committed
225
226
227
228
            $messageToUser = trans('spende.error.amount');
            $messageType = "error";
        } elseif (!in_array($frequency, $validFrequencies)) {
            $messageToUser = trans('spende.error.frequency');
Dominik Hebeler's avatar
Dominik Hebeler committed
229
            $messageType = "error";
Dominik Hebeler's avatar
Dominik Hebeler committed
230
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
231

Dominik Hebeler's avatar
Dominik Hebeler committed
232
233
234
            # The value has to have a maximum of 2 decimal digits
            $betrag = round($betrag, 2, PHP_ROUND_HALF_DOWN);
            try {
235
                $postdata = [
Davide Aprea's avatar
Davide Aprea committed
236
237
                    "entity" => "Contribution",
                    "action" => "mgcreate",
238
239
                    "api_key" => config("metager.metager.civicrm.apikey"),
                    "key" => config("metager.metager.civicrm.sitekey"),
Davide Aprea's avatar
Davide Aprea committed
240
                    "json" => 1,
Davide Aprea's avatar
Davide Aprea committed
241
242
                    "iban" => $iban->MachineFormat(),
                    "bic" => $bic,
Davide Aprea's avatar
Davide Aprea committed
243
244
                    "amount" => $betrag,
                    "frequency" => $frequency,
245
                    "email" => $email,
Davide Aprea's avatar
Davide Aprea committed
246
                    "message" => $nachricht
247
                ];
Dominik Hebeler's avatar
Dominik Hebeler committed
248

249
                if ($request->input('person') === 'private') {
Davide Aprea's avatar
Davide Aprea committed
250
251
                    $postdata['first_name'] = $firstname;
                    $postdata['last_name'] = $lastname;
252
                } elseif ($request->input('person') === 'company') {
Davide Aprea's avatar
Davide Aprea committed
253
                    $postdata['business_name'] = $company;
254
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
255

Davide Aprea's avatar
Davide Aprea committed
256
                $postdata = http_build_query($postdata);
257

258
                $resulthash = md5(json_encode($postdata));
259
260
                $mission = [
                    "resulthash" => $resulthash,
261
                    "url" => config("metager.metager.civicrm.url"),
262
263
264
265
                    "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
266
                        "Content-Type" => "application/x-www-form-urlencoded",
267
268
269
270
271
272
273
274
275
276
277
278
279
                    ],
                    "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);
280

281
282
                // Fetch the result
                $answer = Redis::blpop($resulthash, 20);
283
284
                $key = "";

285
                // Fehlerfall
286
                if (empty($answer) || (is_array($answer) && sizeof($answer) === 2 && $answer[1] === "no-result")) {
287
288
                    $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.";
289
290
291
292
293
294
295
                }
                $answer = json_decode($answer[1], true);
                if ($answer["is_error"] !== 0 || $answer["count"] !== 1) {
                    $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 {
                    $key = $answer["values"][0]["MGKey.MGKey"];
296
297
298
                    $messageToUser = "Herzlichen Dank!! Wir haben Ihre Spendenbenachrichtigung erhalten.";
                    $messageType = "success";
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
299
            } catch (\Swift_TransportException $e) {
Dominik Hebeler's avatar
Dominik Hebeler committed
300
                Log::error($e->getMessage());
Dominik Hebeler's avatar
Dominik Hebeler committed
301
                $messageType = "error";
302
                $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
303
304
305
            }
        }

306
        if ($messageType === "error") {
307
            return view('spende.spende')
308
                ->with('title', 'Kontakt')
Dominik Hebeler's avatar
Dominik Hebeler committed
309
310
                ->with($messageType, $messageToUser)
                ->with('data', $data);
311
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
312
            $data['iban'] = $iban->HumanFormat();
Davide Aprea's avatar
Davide Aprea committed
313
            $data['key'] = $key;
314
            $data = base64_encode(serialize($data));
315
            return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), route("danke", ['data' => $data])));
316
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
317
    }
318

319
320
    public function donationPayPalCallback(Request $request)
    {
321
        $url = "https://www.paypal.com/cgi-bin/webscr";
Dominik Hebeler's avatar
Dominik Hebeler committed
322
323
324
325
326
327
328
329
330
331
332
333
        # PayPal Transaction ID
        $tx = $request->input("tx", "");

        $postdata = [
            "cmd" => "_notify-synch",
            "tx" => $tx,
            "at" => config("metager.metager.paypal.pdt_token"),
            "submit" => "PDT",
        ];
        $postdata = http_build_query($postdata);

        $resulthash = md5($tx);
334

Dominik Hebeler's avatar
Dominik Hebeler committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
        $mission = [
            "resulthash" => $resulthash,
            "url" => $url,
            "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
            "username" => null,
            "password" => null,
            "headers" => [
                "Content-Type" => "application/x-www-form-urlencoded",
            ],
            "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
        // Verify at PayPal that the transaction was indeed SUCCESSFULL
        $answer = Redis::blpop($resulthash, 20);

362
        if (sizeof($answer) !== 2) {
Dominik Hebeler's avatar
Dominik Hebeler committed
363
            return ''; # TODO Redirect on failure
364
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
365
366
367
368
            $answer = $answer[1];
            $answer = explode("\n", $answer);
        }

369
        if ($answer[0] !== "SUCCESS") {
Dominik Hebeler's avatar
Dominik Hebeler committed
370
371
372
373
374
375
376
            return ''; #TODO Redirect on failure
        }

        # Transaction was successfull. Let's parse the details
        array_splice($answer, 0, 1);
        $answertmp = $answer;
        $answer = [];
377
378
        foreach ($answertmp as $index => $element) {
            if (preg_match("/^([^=]+)=(.*)$/", $element, $matches) === 1) {
Dominik Hebeler's avatar
Dominik Hebeler committed
379
380
381
                $key = $matches[1];
                $value = urldecode($matches[2]);
                $answer[$key] = $value;
382
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
383
384
        }

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
        $data = [
            "person" => "private",
            "firstname" => !empty($answer["first_name"]) ? $answer["first_name"] : "",
            "lastname" => !empty($answer["last_name"]) ? $answer["last_name"] : "",
            "company" => "",
            "iban" => "",
            "bic" => "",
            "email" => !empty($answer["payer_email"]) ? $answer["payer_email"] : "",
            "betrag" => !empty($answer["mc_gross"]) && !empty($answer["mc_fee"]) ? floatval($answer["mc_gross"]) - floatval($answer["mc_fee"]) : 0,
            "nachricht" => !empty($answer["memo"]) ? $answer["memo"] : "",
        ];

        // Generate a key
        $postdata = [
            "entity" => "Contribution",
            "action" => "mgcreate",
            "api_key" => config("metager.metager.civicrm.apikey"),
            "key" => config("metager.metager.civicrm.sitekey"),
            "json" => 1,
            "amount" => $data["betrag"],
            "frequency" => "once",
            "email" => $data["email"],
            "message" => $data["nachricht"],
            'first_name' => $data["firstname"],
409
410
            'last_name' => $data["lastname"],
            'transaction_id' => $answer["txn_id"]
411
412
413
        ];

        $postdata = http_build_query($postdata);
Dominik Hebeler's avatar
Dominik Hebeler committed
414

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        $resulthash = md5(json_encode($postdata));
        $mission = [
            "resulthash" => $resulthash,
            "url" => config("metager.metager.civicrm.url"),
            "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
            "username" => null,
            "password" => null,
            "headers" => [
                "Content-Type" => "application/x-www-form-urlencoded",
            ],
            "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);
        $key = "";

        $messageToUser = "";
        $messageType = ""; # [success|error]

        // 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.";
        }
        $answer = json_decode($answer[1], true);
        if ($answer["is_error"] !== 0 || $answer["count"] !== 1) {
            $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 {
            $key = $answer["values"][0]["MGKey.MGKey"];
            $messageToUser = "Herzlichen Dank!! Wir haben Ihre Spende erhalten.";
            $messageType = "success";
        }

        if ($messageType === "error") {
            return view('spende.spende')
                ->with('title', 'Kontakt')
                ->with($messageType, $messageToUser);
        } else {
            $data['key'] = $key;
            $data = base64_encode(serialize($data));
            return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), route("danke", ['data' => $data])));
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
469
470
    }

471
    #Ueberprueft ob ein bereits vorhandener Eintrag bearbeitet worden ist
472
    public static function isEdited($k, $v, $filename)
473
    {
474
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
475
            $temp = include resource_path() . "/" . $filename;
476
            foreach ($temp as $key => $value) {
Dominik Hebeler's avatar
Dominik Hebeler committed
477
                if ($k === $key && $v !== $value) {
478
479
                    return true;
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
480
            }
481
482
483
        } catch (\ErrorException $e) {
            #Datei existiert noch nicht
            return true;
484
485
486
487
        }
        return false;
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
488
    public function sendLanguageFile(Request $request, $from, $to, $exclude = "", $email = "")
489
490
491
492
    {
        $filename = $request->input('filename');
        # Wir erstellen nun zunächst den Inhalt der Datei:
        $data = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
493
        $new = 0;
494
        $emailAddress = "";
495
        $editedKeys = "";
496
497
498
499
        foreach ($request->all() as $key => $value) {
            if ($key === "filename" || $value === "") {
                continue;
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
500
            if ($key === "email") {
501
502
503
                $emailAddress = $value;
                continue;
            }
504
            $key = base64_decode($key);
505
506
507
            if (strpos($key, "_new_") === 0 && $value !== "") {
                $new++;
                $key = substr($key, strpos($key, "_new_") + 5);
Dominik Hebeler's avatar
Dominik Hebeler committed
508
                $editedKeys = $editedKeys . "\n" . $key;
509
            } elseif ($this->isEdited($key, $value, $filename)) {
510
                $new++;
Dominik Hebeler's avatar
Dominik Hebeler committed
511
                $editedKeys = $editedKeys . "\n" . $key;
512
            }
513

514
515
516
517
518
519
520
521
522
523
524
525
526
            $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;
            }
        }
527

528
        $output = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
529
530
531
        $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
532

533
534
        $output = "<?php\n\nreturn $output;\n";

535
536
        $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";

537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
        # 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;
556
557

        if ($new > 0) {
Dominik Hebeler's avatar
Dominik Hebeler committed
558
            if ($emailAddress !== "") {
Aria Givi's avatar
Aria Givi committed
559
                Mail::to("dev@suma-ev.de")
Dominik Hebeler's avatar
Dominik Hebeler committed
560
                    ->send(new Sprachdatei($message, $output, basename($filename), $emailAddress));
561
            } else {
Aria Givi's avatar
Aria Givi committed
562
                Mail::to("dev@suma-ev.de")
Dominik Hebeler's avatar
Dominik Hebeler committed
563
                    ->send(new Sprachdatei($message, $output, basename($filename)));
564
            }
565
        }
566
        $ex = base64_encode(serialize($ex));
567
568

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