LanguageController.php 19.7 KB
Newer Older
1
2
3
4
5
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
6
use App\Models\LanguageObject;
7
8
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
9
use ZipArchive;
10
11
12

class LanguageController extends Controller
{
Aria Givi's avatar
Aria Givi committed
13
14
15
16

    public function __construct() 
    {
       $this->languageFilePath = resource_path()."/lang/";
17
       $this->languages = array('de','en','fr','es','nd');
Aria Givi's avatar
Aria Givi committed
18
19
    }

20
21
    public function createOverview(Request $request)
    {
22
        $languageFolders  = scandir($this->languageFilePath);
23
        $dirs             = [];
24

Aria Givi's avatar
Aria Givi committed
25
26
27
        foreach ($languageFolders as $folder) {
            if (is_dir($this->languageFilePath . $folder) && $folder !== "." && $folder !== "..") {
                $dirs[] = $folder;
28
29
30
31
32
33
34
35
            }
        }
        # Im Array "$dirs" haben wir nun alle Verzeichnisse mit dem entsprechenden Sprachkürzel
        # Alle von uns bislang unterstützen Sprachen sind hier eingetragen.
        $langTexts = [];
        $sum       = [];
        foreach ($dirs as $dir) {
            # Wir überprüfen nun für jede Datei die Anzahl der vorhandenen Übersetzungen
Aria Givi's avatar
Aria Givi committed
36
            $di                           = new RecursiveDirectoryIterator($this->languageFilePath . $dir);
37
38
39
40
41
42
43
            $langTexts[$dir]["textCount"] = 0;
            $langTexts[$dir]["fileCount"] = 0;
            foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
                if (!$this->endsWith($filename, ".")) {
                    $langTexts[$dir]["fileCount"] += 1;
                    $tmp = include $filename;
                    foreach ($tmp as $key => $value) {
44
                        $sum = array_merge($sum, $this->getValues([$key => $value], basename($filename)));
45
                        $langTexts[$dir]["textCount"] += count($this->getValues([$key => $value]));
46
47
48
49
50
51
52
53
54
55
56
57
                    }
                }
            }
        }
        $deComplete = $langTexts["de"]["textCount"] === count($sum) ? true : false;
        return view('languages.overview')
            ->with('title', trans('titles.languages'))
            ->with('langTexts', $langTexts)
            ->with('sum', $sum)
            ->with('deComplete', $deComplete);
    }

58
    public function createEditPage($from, $to, $exclude = "", $email = "")
59
    {
Aria Givi's avatar
Aria Givi committed
60
        $languageFolders  = scandir($this->languageFilePath);
61
        $dirs             = [];
62

Aria Givi's avatar
Aria Givi committed
63
64
65
        foreach ($languageFolders as $folder) {
            if (is_dir($this->languageFilePath . $folder) && $folder !== "." && $folder !== "..") {
                $dirs[$folder] = $folder;
66
67
            }
        }
Aria Givi's avatar
Aria Givi committed
68

69
        # Abbruchbedingungen:
70
        if (!in_array($to, $this->languages) || $from === "" || $to === "" || ($from !== "de" && $from !== "all") || ($from === "all" && $to !== "de") && !array_has($dirs, $to)) {
71
72
73
74
75
            return redirect(url('languages'));
        }

        $texts = [];

76
77
78
        $langTexts = [];
        $sum       = [];
        $filePath  = [];
79
80
81
82
83
84
        foreach ($dirs as $dir) {
            if ($from !== "all" && $dir !== $to && $dir !== $from) {
                continue;
            }

            # Wir überprüfen nun für jede Datei die Anzahl der vorhandenen Übersetzungen
Aria Givi's avatar
Aria Givi committed
85
            $di              = new RecursiveDirectoryIterator($this->languageFilePath . $dir);
86
            $langTexts[$dir] = 0;
87
88
89
90
            foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
                if (!$this->endsWith($filename, ".")) {
                    $tmp = include $filename;
                    foreach ($tmp as $key => $value) {
91
                        $sum                                    = array_merge($sum, $this->getValues([$key => $value], basename($filename)));
92
                        $texts[basename($filename)][$key][$dir] = $value;
93
                        $langTexts[$dir] += count($this->getValues([$key => $value]));
94
                    }
95
                    $filePath[basename($filename)] = preg_replace("/lang\/.*?\//si", "lang/$to/", substr($filename, strpos($filename, "lang")));
96
97
98
                }
            }
        }
99

100
101
        $langs = [];
        $fn    = "";
102
        $t     = [];
Aria Givi's avatar
Aria Givi committed
103
        $ex = $this->decodeExcludedFiles($exclude);
104

105
106
107
        foreach ($texts as $filename => $text) {
            foreach ($ex['files'] as $file) {
                if ($file === $filename) {
Aria Givi's avatar
Aria Givi committed
108
                    continue 2;
109
110
                }
            }
111
112
113
            while ($this->hasToMuchDimensions($text)) {
                $text = $this->deMultidimensionalizeArray($text);
            }
114
            # Hier können wir später die bereits bearbeiteten Dateien ausschließen.
115
            foreach ($text as $textname => $languages) {
116
117
118
119
                if ($languages === "") {
                    continue;
                }

120
121
122
123
124
125
                foreach ($languages as $lang => $value) {
                    if ($lang !== $to) {
                        $langs = array_add($langs, $lang, $lang);
                    }
                }
                if (!isset($languages[$to])) {
126
127
                    $fn = $filePath[$filename];
                    $t  = $text;
128
                    break 2;
129
130
131
                }
            }
        }
132
        $t = $this->htmlEscape($t, $to);
133
        $t = $this->createHints($t, $to);
134
        return view('languages.edit')
135
136
137
138
139
140
141
142
143
            ->with('texts', $t)             //Array mit vorhandenen Übersetzungen der Datei $fn in beiden Sprachen
            ->with('filename', $fn)         //Pfad zur angezeigten Datei
            ->with('title', trans('titles.languages.edit')) 
            ->with('langs', $langs)         //Ausgangssprache (1 Element)
            ->with('to', $to)               //zu bearbeitende Sprache
            ->with('langTexts', $langTexts) //Anzahl der vorhandenen Übersetzungen
            ->with('sum', $sum)             //Alle vorhandenen Texte (in allen Dateien) in beiden Sprachen in einem Array
            ->with('new', $ex["new"])       //
            ->with('email', $email);        //Email-Adresse des Benutzers
144
145
    }

146
    public function createSynopticEditPage(Request $request, $exclude = '', $chosenFile = '') 
147
    {
Aria Givi's avatar
Aria Givi committed
148
        $languageFolders  = scandir($this->languageFilePath); 
149

150
        # Enthält zu jeder Sprache ein Objekt mit allen Daten
151
        $languageObjects  = [];
152
153
154

        # Alle vorhandenen Sprachen
        $to = [];
155

156
        # Dekodieren ausgeschlossener Dateien anhand des URL-Parameters
Aria Givi's avatar
Aria Givi committed
157
        $ex = $this->decodeExcludedFiles($exclude);
158

159
        # Instanziiere LanguageObject
160
        foreach ($languageFolders as $folder) {
Aria Givi's avatar
Aria Givi committed
161
162
            if (is_dir($this->languageFilePath . $folder) && $folder !== "." && $folder !== "..") {
                $languageObjects[$folder] = new LanguageObject($folder, $this->languageFilePath.$folder);
163
            }
164
        }
165
        $fileNames = [];
166
        # Speichere Daten in LanguageObject, überspringe ausgeschlossene Dateien
167
168
169
        foreach ($languageObjects as $folder => $languageObject) {
            $to[] = $folder;
            $di = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($languageObject->filePath));
170
            foreach($di as $filename => $file) {
171
172
173
                if(!$this->endsWith($filename, ".") && !in_array(basename($filename), $fileNames)) {
                    $fileNames[] = basename($filename);
                }
174
                if(!$this->endsWith($filename, ".")) {
175
176
                    $tmp = include $filename;
                    foreach ($tmp as $key => $value) {
177
                        $languageObject->saveData(basename($filename), $key, $value);
178
                    }
179
                }
180
181
            }
        }
182

183
        $fn = "";
184

185
        # Wähle die erste, unbearbeitete Datei aus, überspringe bereits bearbeitete Dateien
186
187
188
189
190
        if($chosenFile !== "") {
            $fn = $chosenFile;
        } else {
            foreach($languageObjects as $folder => $languageObject) {
                foreach($languageObject->stringMap as $languageFileName => $languageFile) {
191
192
193
194
195
                    foreach($ex['files'] as $file) {
                        if($file === basename($languageFileName)) {
                            continue 2;
                        }
                    }   
196
197
198
                    $fn = $languageFileName;
                    break 2;            
                }
199
200
            }
        }
Aria Givi's avatar
Aria Givi committed
201
        $snippets = [];
202
203
        $changeTime = 0;
        $recentlyChangedFiles = [];
Aria Givi's avatar
Aria Givi committed
204

205
        # Speichere den Inhalt der ausgewählten Datei in allen Sprachen in $snippets ab
206
207
208
        foreach($languageObjects as $folder => $languageObject) {
            foreach($languageObject->stringMap as $languageFileName => $languageFile) {
                if($languageFileName === $fn) {
209
210
                    if($changeTime < filemtime($languageObject->filePath."/".$languageFileName)) {
                        unset($recentlyChangedFiles);
211
212
                        $changeTime = filemtime($languageObject->filePath."/".$languageFileName);
                        $recentlyChangedFiles[] = $languageObject->language; 
213
214
                    } else if($changeTime === filemtime($languageObject->filePath."/".$languageFileName)) {
                        $recentlyChangedFiles[] = $languageObject->language; 
215
                    }
Aria Givi's avatar
Aria Givi committed
216
217
218
                    foreach($languageFile as $key => $value) {
                        $snippets[$key][$languageObject->language] = $value;      
                    }
219
                    continue 2;
220
221
222
223
                }
            }
        }

224
        # Fülle $snippets auf mit leeren Einträgen für die restlichen Sprachen
Aria Givi's avatar
Aria Givi committed
225
226
227
228
229
230
        foreach($to as $t) {
            foreach($snippets as $key => $langArray) {
                if(!isset($langArray[$t])) {
                    $snippets[$key][$t] = "";
                }
            }
231
        }
232

233
        return view('languages.synoptic')
234
235
236
            ->with('to', $to)           # Alle vorhandenen Sprachen
            ->with('texts', $snippets)         # Array mit Sprachsnippets
            ->with('filename', $fn)     # Name der Datei
237
            ->with('recentlyChangedFiles', $recentlyChangedFiles)
238
            ->with('otherFiles', $fileNames) # Namen der restlichen Sprachdateien
239
            ->with('title', trans('titles.languages.edit'));
240
241
    }

242
243
244
245
246
247
248
249
250
251
252
253
254
255
    private function htmlEscape($t, $to)
    {
        foreach ($t as $key => $langTexts) {
            if ($langTexts !== "") {
                foreach ($langTexts as $lang => $text) {
                    if ($lang !== $to) {
                        $t[$key][$lang] = htmlspecialchars($text);
                    }
                }
            }
        }
        return $t;
    }

256
    public function processSynopticPageInput(Request $request, $exclude = '', $chosenFile = '') {
257
258
259

        $filename = $request->input('filename');

260
        # Identifizieren des gedrückten Buttons
261
262
        if(isset($request['download'])) {
        # Auslesen, zippen und herunterladen der veränderten Dateien 
Aria Givi's avatar
Aria Givi committed
263
264
265
266
         
            $data = [];
            $new  = 0;
            $editedFiles = [];
267

Aria Givi's avatar
Aria Givi committed
268
            foreach ($request->all() as $key => $value) {
269

Aria Givi's avatar
Aria Givi committed
270
271
272
                if ($key === "filename" || $value === "") {
                    continue;
                }
273

Aria Givi's avatar
Aria Givi committed
274
                $key = base64_decode($key);
275

276
                # Pfad zur Datei anhand des Schlüsselnamens rekonstruieren (Schlüssel enthält Sprachkürzel)
Aria Givi's avatar
Aria Givi committed
277
278
279
280
281
282
283
284
                $langdir = $this->extractLanguage($key);
                $filepath = "lang/".$langdir."/".$filename;
     
                if (strpos($key, "_new_") === 0 && $value !== "" || MailController::isEdited($this->processKey($key), $value, $filepath)) {
                    $new++;
                    $editedFiles[$langdir] = $filepath;
                } 
            }     
285

286
            # Erneute Iteration über Request, damit Dateien mitsamt vorherigen Einträgen abgespeichert werden 
Aria Givi's avatar
Aria Givi committed
287
            foreach($request->all() as $key => $value) {
288

Aria Givi's avatar
Aria Givi committed
289
290
291
                if ($key === "filename" || $value === "") {
                    continue;
                }
292

Aria Givi's avatar
Aria Givi committed
293
                $key = base64_decode($key);
294

295
                # Pfad zur Datei anhand des Schlüsselnamens rekonstruieren (Schlüssel enthält Sprachkürzel)
Aria Givi's avatar
Aria Givi committed
296
                $langdir = $this->extractLanguage($key);
297

298
                # Überspringe Datei, falls diese nicht bearbeitet worden ist
Aria Givi's avatar
Aria Givi committed
299
300
301
                if(!isset($editedFiles[$langdir])) {
                    continue;
                }
302

303
                # Key kuerzen, sodass er nur den eigentlichen Keynamen enthält
Aria Givi's avatar
Aria Givi committed
304
305
306
307
                $key = $this->processKey($key);
                
                if (!strpos($key, "#")) {
                    $data[$langdir][$key] = $value;
308
                # Aufdröseln von 2D-Arrays
Aria Givi's avatar
Aria Givi committed
309
310
311
312
313
314
315
316
317
                } else {
                    $ref = &$data;
                    do {
                        $ref = &$ref[$langdir][substr($key, 0, strpos($key, "#"))];
                        $key = substr($key, strpos($key, "#") + 1);
                    } while (strpos($key, "#"));
                    $ref = &$ref[$key];
                    $ref = $value;
                }
318
319
            }

320
321
            if(file_exists("/tmp/langfiles.zip"))
                unlink("/tmp/langfiles.zip");
322

Aria Givi's avatar
Aria Givi committed
323
            $zip = new ZipArchive();
324

325
            if (empty($data) || $zip->open("/tmp/langfiles.zip", ZipArchive::CREATE) !== TRUE) {
Aria Givi's avatar
Aria Givi committed
326
327
328
329
                return redirect(url('synoptic', ['exclude' => $exclude]));
            } 
                
            try{
330
            # Erstelle Ausgabedateien
Aria Givi's avatar
Aria Givi committed
331
332
333
334
335
336
337
338
339
                foreach($data as $lang => $entries) {
                    $output = json_encode($entries, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                    $output = preg_replace("/\{/si", "[", $output);
                    $output = preg_replace("/\}/si", "]", $output);
                    $output = preg_replace("/\": ([\"\[])/si", "\"\t=>\t$1", $output);
                    $output = "<?php\n\nreturn $output;\n";
                    $zip->addEmptyDir($lang);
                    $zip->addFromString($lang."/".$filename, $output);
                }
340

Aria Givi's avatar
Aria Givi committed
341
            $zip->close();
342

343
            return response()->download("/tmp/langfiles.zip", $filename.".zip");
Aria Givi's avatar
Aria Givi committed
344
345
346
                    } catch(ErrorException $e) {
                echo("Failed to write ".$filename);
                }
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
        # Andernfalls weiterleiten zur nächsten Seite
        } else {

            $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 = base64_encode(serialize($ex));

            if(isset($request['nextpage'])) {
                return redirect(url('synoptic', ['exclude' => $ex]));
            } elseif(isset($request['chosenFile'])) {
372
                return redirect(url('synoptic', ['exclude' => $ex, 'chosenFile' => $request['chosenFile']]));
373
            }
374
375
        }
    }
Aria Givi's avatar
Aria Givi committed
376

377
378
379
    private function createHints($t, $to)
    {
        foreach ($t as $key => $langTexts) {
380
381
382
            if ($langTexts !== "") {
                foreach ($langTexts as $lang => $text) {
                    if ($lang !== $to) {
383
384
                        if (preg_match("/:\w+/si", $text)) {
                            $t[$key][$lang] = preg_replace("/(:\w+)/si", "<a class=\"text-danger hint\" data-toggle=\"tooltip\" data-trigger=\"hover\" data-placement=\"auto\" title=\"Dies ist ein Variablenname. Er wird dort, wo der Text verwendet wird durch einen dynamischen Wert ersetzt. In der Übersetzung sollte dieser deshalb auch so wie er ist in den Satz integriert werden.\" data-container=\"body\" >$1</a>", $text);
385
                        }
386
387
388
                        if (preg_match("/&lt;.*?&gt;/si", $text)) {
                            $t[$key][$lang] = preg_replace("/(&lt;.*?&gt;)/si", "<a class=\"text-danger hint\" data-toggle=\"tooltip\" data-trigger=\"hover\" data-placement=\"auto\" title=\"Dies ist ein sogenanntes HTML-Tag. Wenn Sie sich das zutrauen, bauen Sie diese HTML Tags gerne so wie sie sind in Ihre Übersetzung ein. Achten Sie hierbei darauf, dass der Text zwischen den Tags auch bei der Übersetzung an der logisch gleichen Stelle von den Tags umfasst ist.\" data-container=\"body\" >$1</a>", $text);
                        }
389

390
                    }
391
392
393
394
395
396
                }
            }
        }
        return $t;
    }

Aria Givi's avatar
Aria Givi committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    private function decodeExcludedFiles($exclude)
    {
        $ex = ['files' => [], 'new' => 0];

        if ($exclude !== "") {
            try {
                $ex = unserialize(base64_decode($exclude));
            } catch (ErrorException $e) {
                $ex = ['files' => [], 'new' => 0];
            }
        }

        return $ex;
    }

412
413
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
469
470
471
472
473
474
475
476
477
478
    private function getValues($values, $prefix = "")
    {
        $return = [];
        if (!is_array($values)) {
            return $return;
        } else {
            foreach ($values as $key => $value) {
                if (is_array($value)) {
                    $return = array_merge($return, $this->getValues($value, $prefix . $key));
                } elseif (is_string($value)) {
                    $return[$prefix . $key] = $value;
                }
            }
        }

        return $return;
    }

    private function hasToMuchDimensions($t)
    {
        foreach ($t as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $lang => $val) {
                    if (is_array($val)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    private function deMultidimensionalizeArray($t)
    {
        # Es gibt noch Besonderheiten in den Texten
        # Es kann sein, dass statt einem String ein Array aus Strings als Werte existieren.
        # Diese müssen aufgelöst werden:
        $tmp = [];
        foreach ($t as $key => $value) {
            $isArray = false;
            if (is_array($value)) {
                foreach ($value as $lang => $val) {
                    if (is_array($val)) {
                        $isArray = true;
                    }
                }
            } else {
                $tmp[$key] = $value;
                continue;
            }
            if (!$isArray) {
                $tmp[$key] = $value;
            } else {
                $tmp[$key] = "";
                foreach ($value as $lang => $val) {
                    if (is_array($val)) {
                        foreach ($val as $key2 => $val) {
                            $tmp["\t" . $key . "#" . $key2][$lang] = $val;
                        }

                    }
                }
            }

        }
        return $tmp;
479
480
    }

481
    public function startsWith($haystack, $needle)
482
483
484
485
486
    {
        // search backwards starting from haystack length characters from the end
        return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
    }

487
    public function endsWith($haystack, $needle)
488
489
490
491
    {
        // search forward starting from end minus needle length characters
        return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
    }
492

Aria Givi's avatar
Aria Givi committed
493
    private function extractLanguage($key) 
494
    {   
495
        # Kürzt bspw. "_new_de_redirect bzw. "de_redirect" zu "de"
496
497
498
499
500
501
502
503
504
505
        preg_match("/^(?:_new_)?([^_]*)/", $key, $matches);
        foreach($matches as $dir) {
            if(strlen($dir) == 2)
                return $dir;
            }
    }

    private function processKey($key) 
    {   
        $key = trim($key);
506
        # Kürzt bspw. "_new_de_redirect bzw. "de_redirect" zu "redirect"
507
508
509
510
511
512
513
514
        preg_match("/^(?:_new_)?(?:[^_]*)_(\w*.?\w*#?.?\w*)/", $key, $matches);
        foreach($matches as $processedKey) {
            if(strpos($processedKey, "_") === FALSE) {
                return $processedKey;
            }
        }
        return $key;
    }
515
}