AmosTranslation.php 34.6 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
2
3
4
5
<?php
/**
 * Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
 * OPEN 2.0
 *
6
7
8
 * @see https://www.open2.0.regione.lombardia.it Developers'community
 * @license GPLv3
 * @license https://opensource.org/licenses/gpl-3.0.html GNU General Public License version 3
Marcello Pivanti's avatar
Marcello Pivanti committed
9
 *
waltermazza's avatar
waltermazza committed
10
 * @package    arter\amos\translation
Marcello Pivanti's avatar
Marcello Pivanti committed
11
12
13
14
 * @category   CategoryName
 * @author     Elite Division S.r.l.
 */

waltermazza's avatar
waltermazza committed
15
namespace arter\amos\translation;
Marcello Pivanti's avatar
Marcello Pivanti committed
16

waltermazza's avatar
waltermazza committed
17
18
19
20
use arter\amos\core\module\Module;
use arter\amos\core\module\AmosModule;
use arter\amos\core\module\ModuleInterface;
use arter\amos\core\record\Record;
Marcello Pivanti's avatar
Marcello Pivanti committed
21
22
23
24
25
26
27
28
29
use yii\web\Application;
use yii\base\BootstrapInterface;
use Yii;
use yii\base\Event;
use yii\helpers\StringHelper;
use yii\helpers\FileHelper;

/**
 * Class AmosWorkflow
waltermazza's avatar
waltermazza committed
30
 * @package arter\amos\workflow
Marcello Pivanti's avatar
Marcello Pivanti committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 */
class AmosTranslation extends AmosModule implements BootstrapInterface
{
    public static $CONFIG_FOLDER = 'config';

    /**
     * @var string|boolean the layout that should be applied for views within this module. This refers to a view name
     * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
     * will be taken. If this is false, layout will be disabled within this module.
     */
    public $layout              = 'main';
    public $name                = 'Translation';
    public $newFileMode         = 0666;
    public $newDirMode          = 0777;
    public $languageField       = 'language';
waltermazza's avatar
waltermazza committed
46
    public $controllerNamespace = 'arter\amos\translation\controllers';
Marcello Pivanti's avatar
Marcello Pivanti committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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

    /**
     * It set the language source, if is set every saved record is copied in the translation language default
     * @var type $defaultLanguage
     */
    public $defaultLanguage;

    /**
     * If is set it sets the translation language when the translation request is not present
     * @var type $defaultTranslationLanguage
     */
    public $defaultTranslationLanguage;
    public $enableUserLanguage = true;

    /**
     * If the value is true it disable all the permission on the record translation
     * @var type $byPassPermissionInlineTranslation
     */
    public $byPassPermissionInlineTranslation = true;

    /**
     * If set to true it enables the display of the translatable fields in the forms
     * @var boolean $enableLabelTranslationField
     */
    public $enableLabelTranslationField = false;

    /**
     * Template of translation field in the form, near the label
     * @var string $templateTranslationField
     */
    public $templateTranslationField = '{translation}';

    /**
     * Template of translation alt field in the form, near the $templateTranslationField
     * @var string $templateTranslationAltField
     */
    public $templateTranslationAltField = '{altTranslation}';

    /**
     * This string will be parsed by the "eval()" function instead of $tempalteTransaltionField, by default {translation}
     * @var string $translationLabelField
     */
    public $translationLabelField = 'strtoupper(substr(\Yii::$app->language, 0, 2));';

    /**
     * This string will be parsed by the "eval()" function instead of $templateTranslationAltField, by default {altTranslation}
     * @var string $translationLabelAltField
     */
    public $translationLabelAltField = '\Yii::t("amostranslation", "Testo traducibile direttamente scrivendo in questo campo, tradurrai nella lingua selezionata, la visualizzazione attuale è in");';

    /**
     * This string is the html code that will be used in the labels to represent a translatable field
     * @var string $labelTranslationField
     */
    public $labelTranslationField = ' (<span class="label_translation am am-translate" title="{altTranslation} {translation}"> - {translation}</span>)';

    /**
     * It is the default user language
     * @var string $defaultUserLanguage
     */
    public $defaultUserLanguage         = 'en-GB';
    public $nameCreatedBy               = 'nome';
    public $surnameCreatedBy            = 'cognome';
    public $supportedLanguages          = [];
    public $secureCookie                = true;
    public $enableCookieFor2LevelDomain = false;

    /**
     * Add this module to /common/config/main.php
     * ```php
     * 'modules' => [
     * 'translation' => [
waltermazza's avatar
waltermazza committed
119
     *      'class' => 'arter\amos\translation\AmosTranslation',
Marcello Pivanti's avatar
Marcello Pivanti committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
     *      'translationBootstrap' => [
     *          'configuration' => [
     *              'translationLabels' => [
     *                  'classBehavior' => \lajax\translatemanager\behaviors\TranslateBehavior::className(),
     *                  'models' => [
     *                      [
     *                      'namespace' => 'cornernote\workflow\manager\models\Status',
     *                      //'connection' => 'db', //if not set it use 'db'
     *                      //'classBehavior' => null,//if not set it use default classBehavior 'lajax\translatemanager\behaviors\TranslateBehavior'
     *                      'attributes' => ['field'],
     *                      ],
     *                  ],
     *              ],
     *              'translationContents' => [
waltermazza's avatar
waltermazza committed
134
     *                  'classBehavior' => \arter\amos\translation\behaviors\TranslateableBehavior::className(),
Marcello Pivanti's avatar
Marcello Pivanti committed
135
136
137
138
     *                  'models' => [
     *                      [
     *                      'namespace' => 'backend\modules\id_plugin\models\NameModel',
     *                      //'connection' => 'db', //if not set it use 'db'
waltermazza's avatar
waltermazza committed
139
     *                      //'classBehavior' => null,//if not set it use default classBehavior 'arter\amos\translation\behaviors\TranslateableBehavior'
Marcello Pivanti's avatar
Marcello Pivanti committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
     *                      //'enableWorkflow' => false,//if not set it use default configuration of the plugin
     *                      //'workflow' => 'AmosTranslationWorkflow',
     *                      //'view' => '@backend/modules/module/controller/view,
     *                      //'forceTranslation' => true,
     *                      'rteAttributes' => ['field'], //only if $this->enableRTE is true it set the RTE for the specified attributes
     *                      'attributes' => ['field'],
     *                      'plugin' => 'id_plugin'
     *                      ]
     *                  ],
     *              ],
     *          ],
     *      ],
     *      'module_translation_labels' => 'translatemanager',
     *      //'module_translation_labels_options' => [];//all the options of the translatemanager
     *      'components' => [
     *          'translatemanager' => [
     *              'class' => 'lajax\translatemanager\Component'
     *          ],
     *      ],
     * ],
     * ],
     * ```
     *
     * Add to bootstrap array in the /backend/config/main.php and/or /frontend/config/main.php the follow class
     * ```php
     *  'bootstrap' => [
     *      'translation',
waltermazza's avatar
waltermazza committed
167
168
     *      'arter\amos\translation\bootstrap\EventActiveRecordBootstrap',//fot the translation of the records
     *      'arter\amos\translation\bootstrap\EventViewBootstrap',//for the widget in the view file
Marcello Pivanti's avatar
Marcello Pivanti committed
169
170
171
172
173
174
175
176
177
178
179
     * ],
     * ```
     */
    public $translationBootstrap;
    public $modules;
    public $forceTranslation         = true;
    public $pathsForceTranslation    = ['@frontend'];
    public $eventViewBlackListViews  = [];
    public $eventViewBlackListModels = [];
    public $eventViewWhiteListParts  = ['_form'];
    public $enableWidgetView         = true;
waltermazza's avatar
waltermazza committed
180
    public $widgetViewFile           = '@vendor/arter/amos-translation/src/views/default/language_status.php';
Marcello Pivanti's avatar
Marcello Pivanti committed
181
182
183
184
185
186
187
188
189
    public $actionLanguage           = '/translation/default/language';
    public $numberGridViewField      = 3;
    public $enableRTE                = true;
    public $clientOptionsRTE         = [];

    /**
     * Model base class will be generated
     * @var string
     */
waltermazza's avatar
waltermazza committed
190
    public $modelBaseClass        = 'arter\\amos\\core\\record\\Record';
Marcello Pivanti's avatar
Marcello Pivanti committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    public $modelNs               = "backend\\models\\translations";
    public $modelGenerateRelation = 'all';

    /**
     * Enable or disable the workflow on the Active Record
     * @var boolean
     */
    public $enableWorkflow = true;

    /**
     * Workflow behavior name, default is 'workflow'
     * @var string
     */
    public $workflowBehavior                 = 'workflow';
    public $statusWorkflowApproved           = 'AmosTranslationWorkflow/APPROVED';
    public $statusWorkflowInitial            = 'AmosTranslationWorkflow/DRAFT';
    public $module_translation_labels;
    public $module_translation_labels_options;
    public $components                       = [];
    public $dbTranslation                    = 'db';
    public $dbSource                         = 'db';
    public $defaultTypeAttributesToTranslate = ['string', 'text'];
    public $systemBlackListAttributes        = ['id', 'status', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by',
        'deleted_by'];

    /**
     * The cache object or the ID of the cache application component that is used for query caching
     * @var type
     */
    public $queryCache = 'cache';

    /**
     * If true, the cache of the Query or the ActiveQuery is active
     * @var boolean $cached
     */
    public $cached = true;

    /**
     * The time of the cache duration, after this time the cache will be invalidated
     * @var integer $cacheDuration
     */
    public $cacheDuration = 86400;

    /**
     * Name of the property the modules will use for the configuration of the fields of the db to be translated
     * @var string $propertyModule
     */
    public $propertyModule = 'db_fields_translation';

    /**
     * Name of the file that will be generated with the configurations of the fields of the db to be translated
     * @var string $fileNameDbConfFields
     */
    public $fileNameDbConfFields = '__db_fields_translation';

    /**
     * Blacklist of the modules for which it will not occur the existence of field configurations of the db to be translated
     * @var array $moduleBlackListForDbConfFields
     */
    public $moduleBlackListForDbConfFields = ['translation', 'audit', 'debug'];

    /**
     * @var string $modelOwnerPlatformTranslation
     */
    public $modelOwnerPlatformTranslation     = 'lajax\translatemanager\models\LanguageTranslate';
    public $modelOwnerPlatformTrIdField       = 'id';
    public $modelOwnerPlatformTrLanguageField = 'language';
    public $availableLanguages                = null;

    public static function getModuleName()
    {
        return "translation";
    }

    public function init()
    {
        parent::init();

waltermazza's avatar
waltermazza committed
269
        \Yii::setAlias('@arter/amos/'.static::getModuleName().'/controllers', __DIR__.'/controllers');
Marcello Pivanti's avatar
Marcello Pivanti committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// initialize the module with the configuration loaded from config.php
        Yii::configure($this, require(__DIR__.DIRECTORY_SEPARATOR.self::$CONFIG_FOLDER.DIRECTORY_SEPARATOR.'config.php'));
        $this->configTranslationLabelsByModules();
        $this->module_translation_labels_options = $this->getModuleTranslationLabelsOptions();


        \Yii::$app->setModule($this->module_translation_labels, $this->module_translation_labels_options);
        if (\Yii::$app instanceof Application) {
            \Yii::$app->setComponents($this->components);
        }
        $this->generateTranslationTables();
        $this->generateTranslationModels();
    }

    public function getWidgetIcons()
    {
        return [
            widgets\icons\WidgetIconTranslation::className(),
            widgets\icons\WidgetIconTrContents::className(),
            widgets\icons\WidgetIconTrPlatform::className(),
            //widgets\icons\WidgetIconTrLanguage::className(),//will to ability when the view of the translate of platform are completed
            widgets\icons\WidgetIconTrOptimize::className(),
            widgets\icons\WidgetIconTrScan::className(),
        ];
    }

    public function getWidgetGraphics()
    {
        return [];
    }

    public function getModuleTranslationLabelsOptions()
    {
        $configuration                            = [];
        $configuration['class']                   = (isset($this->module_translation_labels_options['class']) ? $this->module_translation_labels_options['class']
                : 'lajax\translatemanager\Module');
        $configuration['root']                    = (isset($this->module_translation_labels_options['root']) ? $this->module_translation_labels_options['root']
                : [
            '@app',
            '@backend',
            '@frontend',
waltermazza's avatar
waltermazza committed
311
            '@vendor/arter/',
Marcello Pivanti's avatar
Marcello Pivanti committed
312
313
314
315
        ]);
        $configuration['scanRootParentDirectory'] = (isset($this->module_translation_labels_options['scanRootParentDirectory'])
                ? $this->module_translation_labels_options['scanRootParentDirectory'] : true);
        $configuration['layout']                  = (isset($this->module_translation_labels_options['layout']) ? $this->module_translation_labels_options['layout']
waltermazza's avatar
waltermazza committed
316
                : '@vendor/arter/amos-layout/src/views/layouts/main');
Marcello Pivanti's avatar
Marcello Pivanti committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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
409
410
411
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
        $configuration['allowedIPs']              = (isset($this->module_translation_labels_options['allowedIPs']) ? $this->module_translation_labels_options['allowedIPs']
                : ['*']);
        $configuration['roles']                   = (isset($this->module_translation_labels_options['roles']) ? $this->module_translation_labels_options['roles']
                : ['ADMIN']);
        $configuration['tmpDir']                  = (isset($this->module_translation_labels_options['tmpDir']) ? $this->module_translation_labels_options['tmpDir']
                : '@runtime');
        $configuration['phpTranslators']          = (isset($this->module_translation_labels_options['phpTranslators']) ? $this->module_translation_labels_options['phpTranslators']
                : [
            '::t',
            '::tText',
            '::tHtml',
        ]);
        $configuration['jsTranslators']           = (isset($this->module_translation_labels_options['jsTranslators']) ? $this->module_translation_labels_options['jsTranslators']
                : ['lajax.t']);
        $configuration['patterns']                = (isset($this->module_translation_labels_options['patterns']) ? $this->module_translation_labels_options['patterns']
                : ['*.js', '*.php']);
        $configuration['ignoredCategories']       = (isset($this->module_translation_labels_options['ignoredCategories'])
                ? $this->module_translation_labels_options['ignoredCategories'] : ['yii']);
        $configuration['ignoredItems']            = (isset($this->module_translation_labels_options['ignoredItems']) ? $this->module_translation_labels_options['ignoredItems']
                : ['config']);
        $configuration['scanTimeLimit']           = (isset($this->module_translation_labels_options['scanTimeLimit']) ? $this->module_translation_labels_options['scanTimeLimit']
                : null);
        $configuration['searchEmptyCommand']      = (isset($this->module_translation_labels_options['searchEmptyCommand'])
                ? $this->module_translation_labels_options['searchEmptyCommand'] : '!');
        $configuration['defaultExportStatus']     = (isset($this->module_translation_labels_options['defaultExportStatus'])
                ? $this->module_translation_labels_options['defaultExportStatus'] : 1);
        $configuration['defaultExportFormat']     = (isset($this->module_translation_labels_options['defaultExportFormat'])
                ? $this->module_translation_labels_options['defaultExportFormat'] : 'json');
        $configuration['tables']                  = (isset($this->module_translation_labels_options['tables']) ? $this->module_translation_labels_options['tables']
                : $this->getArrayDbTranslation());
        $configuration['scanners']                = (isset($this->module_translation_labels_options['scanners']) ? $this->module_translation_labels_options['scanners']
                : [
// define this if you need to override default scanners (below)
            '\lajax\translatemanager\services\scanners\ScannerPhpFunction',
            '\lajax\translatemanager\services\scanners\ScannerPhpArray',
            '\lajax\translatemanager\services\scanners\ScannerJavaScriptFunction',
            '\lajax\translatemanager\services\scanners\ScannerDatabase',
        ]);

        return $configuration;
    }

    public function configTranslationLabelsByModules()
    {
        $config = $this->translationBootstrap;

        $dbConfFieldsPath = \Yii::getAlias('@'.str_replace('\\', '/', $this->modelNs)).'/'."{$this->fileNameDbConfFields}".'.php';
        if (file_exists($dbConfFieldsPath)) {
            $this->translationBootstrap['configuration']['translationLabels']['models'] = array_merge((!empty($config['configuration']['translationLabels']['models'])
                    ? $config['configuration']['translationLabels']['models'] : []), require($dbConfFieldsPath));
        }
    }

    public function bootstrap($app)
    {
        if ($app instanceof Application) {
            $preferredLanguage = !\Yii::$app->user->isGuest ? $this->getLanguageCookie() : null;
            if (empty($preferredLanguage)) {
                if ($this->enableUserLanguage == true && !\Yii::$app->getUser()->isGuest) {
                    $preferredLanguage = $this->getUserLanguage();
                } else if (\Yii::$app->getUser()->isGuest) {
                    $preferredLanguage = $this->getLanguageCookie();
                    if (empty($preferredLanguage)) {
                        $preferredLanguage = $this->getBrowserLanguage();
                    }
                } else {
                    $preferredLanguage = $app->request->getPreferredLanguage($this->supportedLanguages);
                }
            }
            $app->language = $preferredLanguage;

            if ($this->enableUserLanguage == true) {
                $this->setUserLanguage($app->language);
            }
        }
        if (empty($app->language)) {
            $app->language = $this->defaultUserLanguage;
        }
    }

    /**
     * @return null|string
     */
    public function getLanguageCookie()
    {
        if ($this->secureCookie) {
            $preferredLanguage = (isset(\Yii::$app->request->cookies['language'])) ? (string) \Yii::$app->request->cookies['language']
                    : null;
        } else {
            $preferredLanguage = !empty($_COOKIE['language']) ? $_COOKIE['language'] : null;
        }
        return $preferredLanguage;
    }

    /**
     * Set user language
     * @param string $language For example 'it-IT', 'en-GB', 'en-US'
     */
    public function setUserLanguage($language)
    {
        $available = $this->getAvailableLanguages();
        if (!empty($available) && array_key_exists($language, $available)) {
            if (\Yii::$app instanceof Application && !\Yii::$app->getUser()->isGuest) {
                $userId     = \Yii::$app->getUser()->getId();
                $preference = models\TranslationUserPreference::find()->andWhere(['user_id' => $userId]);
                if ($preference->count()) {
                    $model       = $preference->one();
                    $model->lang = $language;
                    $model->save(false);
                } else {
                    $newPreference          = new models\TranslationUserPreference();
                    $newPreference->user_id = $userId;
                    $newPreference->lang    = $language;
                    $newPreference->validate();
                    $newPreference->save(false);
                }
            }
            \Yii::$app->language = $language;
        }
        if (empty(\Yii::$app->language)) {
            \Yii::$app->language = $this->defaultUserLanguage;
        }
    }

    /**
     * Set guest language
     * @return string $language For example 'it-IT', 'en-GB', 'en-US'
     */
    public function getGuestLanguage()
    {
        $preferredLanguage = null;
        $language          = null;
        if (\Yii::$app instanceof Application) {
            $preferredLanguage = $this->getLanguageCookie();
            if (empty($preferredLanguage)) {
                $preferredLanguage = $this->getLanguageCookie();
                if (empty($preferredLanguage)) {
                    $preferredLanguage = $this->getBrowserLanguage();
                }
                if (empty($preferredLanguage)) {
                    $preferredLanguage = \Yii::$app->request->getPreferredLanguage($this->supportedLanguages);
                }
            }
            $language = $preferredLanguage;
        }
        if (empty($language)) {
            $language = $this->defaultUserLanguage;
        }

        return $language;
    }

    /**
     *
     * @param integer|null $userId
     * @return string
     */
    public function getUserLanguage($userId = null)
    {
        $language  = null;
        $available = $this->getAvailableLanguages();
        if ($userId != null) {
            $lang1 = $this->getUserLanguagePreference($userId);
            if (array_key_exists($lang1, $available)) {
                $language = $available[$lang1];
            }
        } else if (\Yii::$app instanceof Application && !\Yii::$app->getUser()->isGuest) {
            $userId = \Yii::$app->getUser()->getId();
            if ($userId != null) {
                $lang2 = $this->getUserLanguagePreference($userId);
                if (array_key_exists($lang2, $available)) {
                    $language = $available[$lang2];
                }
            }
        }

        if (\Yii::$app instanceof Application && $language == null) {
            $language = $this->getBrowserLanguage();
        }

        if ($language == null && !empty($this->defaultUserLanguage)) {
            $language = $this->defaultUserLanguage;
        } else if (!empty(\Yii::$app->language) && $language == null) {
            $language = \Yii::$app->language;
        }

        return $language;
    }

    /**
     * Get browser language
     * @return string Language
     */
    public function getBrowserLanguage()
    {
        $available = $this->getAvailableLanguages();
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            if (!empty($available)) {
                foreach ($langs as $lang) {
                    $lang = explode(';', $lang);
                    if (is_array($lang)) {
                        foreach ($lang as $lng) {
                            if (array_key_exists($lng, $available)) {
                                return $available[$lng];
                            }
                        }
                    } else {
                        if (array_key_exists($lang, $available)) {
                            return $available[$lang];
                        }
                    }
                }
            }
        }
        return $this->defaultUserLanguage;
    }

    /**
     *
     * @param boolean $beta_language Default false
     * @return array
     */
    public function getAvailableLanguages($beta_language = false)
    {
        if (is_null($this->availableLanguages)) {
            $languages                = models\TranslationConf::getStaticAllActiveLanguages(true, null, $beta_language)->asArray()->all();
            $this->availableLanguages = [];
            if (!empty($languages)) {
                foreach ($languages as $availableLang) {
                    $this->availableLanguages[$availableLang['language']]    = $availableLang['language_id'];
                    $this->availableLanguages[$availableLang['language_id']] = $availableLang['language_id'];
                }
            }
        }
        return $this->availableLanguages;
    }

    /**
     *
     * @param integer $userId
     * @return string|null
     */
    private function getUserLanguagePreference($userId)
    {
        $preference = models\TranslationUserPreference::find()->andWhere(['user_id' => $userId]);
        if ($preference->count() && !empty($preference->one()->lang)) {
            return $preference->one()->lang;
        }
        return null;
    }

    /**
     *
     * @param string $language
     */
    public function setAppLanguage($language)
    {
        \Yii::$app->language = $language;
    }

    /**
     *
     * @return array
     */
    public function getDefaultModels()
    {
        return [];
    }

    /**
     * 
     * @param boolean $force
     * @param boolean $forceModels
     */
    public function generateTranslationTables($force = false, $forceModels = false)
    {
        $models = [];
        if (!empty($this->translationBootstrap['configuration']['translationContents']['models'])) {
            foreach ($this->translationBootstrap['configuration']['translationContents']['models'] as $model) {
                $isCreated = $this->executeSql($model['namespace'], $force);
                if ($isCreated !== false || $forceModels === true) {
                    $models[] = ['namespace' => $model['namespace'], 'plugin' => (!empty($model['plugin']) ? $model['plugin']
                            : null)];
                }
            }
        }
        if (!empty($models)) {
            foreach ($models as $value) {
                $conf = models\TranslationConf::findOne(['namespace' => $value['namespace']]);
                if ($conf) {
                    $conf->plugin = $value['plugin'];
                    $conf->fields = serialize($this->getModelAttributes($value['namespace'], true));
                    $conf->save(false);
                } else {
                    $conf            = new models\TranslationConf();
                    $conf->namespace = $value['namespace'];
                    $conf->plugin    = $value['plugin'];
                    $conf->fields    = serialize($this->getModelAttributes($value['namespace'], true));
                    $conf->save(false);
                }
            }
        }
    }

    /**
     *
     * @param boolean $force
     */
    public function generateTranslationModels($force = false)
    {
        $models         = [];
        $files          = [];
        $workflow       = 'AmosTranslationWorkflow';
        $enableWorkflow = false;
        if (\Yii::$app->db->getTableSchema(models\TranslationConf::tableName(), false) !== null) {
            $verifyModels = models\TranslationConf::find();
            if ($force == false) {
                $verifyModels->andWhere(['model_generated' => 0]);
            }
            $configuration = (isset($this->translationBootstrap['configuration']['translationContents']['models']) ? $this->translationBootstrap['configuration']['translationContents']['models']
                    : '');
            foreach ((array) $configuration as $model) {
                if (isset($model['enableWorkflow'])) {
                    if ($model['enableWorkflow'] == true) {
                        $enableWorkflow = true;
                    }
                } else {
                    $enableWorkflow = $this->enableWorkflow;
                }
                if (!empty($model['workflow'])) {
                    $workflow = $model['workflow'];
                }
            }
            if ($verifyModels->count()) {
                foreach ($verifyModels->all() as $model) {
                    $namespace        = $model->namespace;
                    $modelClass       = StringHelper::basename($namespace)."Translation";
                    $table            = $namespace::tableName();
                    $tableTranslation = "{$table}__translation";
                    $tableSchema      = \Yii::$app->{$this->dbTranslation}->getTableSchema($tableTranslation);

                    if (!empty($tableSchema)) {
                        $generator                     = new components\Generator();
                        $generator->tableName          = $tableTranslation;
                        $generator->baseClass          = $this->modelBaseClass;
                        $generator->generatedClassName = $modelClass;
                        $generator->ns                 = $this->modelNs;
                        $generator->enableI18N         = true;
                        $generator->messageCategory    = 'amostranslation';
                        $generator->classnameTarget    = str_replace(StringHelper::basename($namespace), '', $namespace);
                        if ($enableWorkflow == true) {
                            $generator->workflow = $workflow;
                        }
                        $generator->db                         = $this->dbTranslation;
                        $generator->generateRelations          = $this->modelGenerateRelation;
                        $generator->generateLabelsFromComments = true;
                        $generator->queryNs                    = $this->modelNs;
                        $generator->modelClass                 = $this->modelNs.'\\'.$modelClass;
                        $files[]                               = $generator->generate();
                        $model->model_generated                = 1;
                        $model->save(false);
                    }
                }
            }
            if (!empty($files)) {
                foreach ($files as $file) {
                    foreach ($file as $File) {
                        $path = str_replace(StringHelper::basename($File->path), '', $File->path);
                        if (!is_dir($path)) {
                            FileHelper::createDirectory($path);
                        }
                        $handle = fopen($File->path, 'w');
                        fwrite($handle, $File->content);
                        fclose($handle);
                    }
                }
            }
        }
    }

    /**
     *
     * @param string $classname
     * @param boolean $force
     * @return boolean
     */
    protected function executeSql($classname, $force = false)
    {
        $sql    = "";
        $result = false;
        try {
            $connection = \Yii::$app->{$this->dbTranslation};
            //$connection->enableQueryCache  = false;
            //$connection->enableSchemaCache = false;
            $table      = $classname::tableName();

            if (\Yii::$app->{$this->dbTranslation}->getTableSchema("{$table}__translation") === NULL) {

                $sql .= "CREATE TABLE `{$table}__translation` (
                    `{$table}_id` int(11) NOT NULL,
                    `{$this->languageField}` VARCHAR(255) NOT NULL,";

                $tableSchema = \Yii::$app->{$this->dbSource}->getTableSchema($table);

                if (!empty($this->defaultTypeAttributesToTranslate) && !empty($tableSchema)) {
                    foreach ((array) $tableSchema->columns as $key => $value) {
                        if (in_array($value->type, $this->defaultTypeAttributesToTranslate) && !in_array($value->name,
                                $this->systemBlackListAttributes)) {
                            $sql .= "`{$value->name}` TEXT DEFAULT NULL,";
                        }
                    }
                }
                $sql .= "`status` VARCHAR(255) DEFAULT NULL,
                    `created_by` INTEGER DEFAULT NULL,
                    `updated_by` INTEGER DEFAULT NULL,
                    `deleted_by` INTEGER DEFAULT NULL,
                    `created_at` DATETIME DEFAULT NULL,
                    `updated_at` DATETIME DEFAULT NULL,
                    `deleted_at` DATETIME DEFAULT NULL) ".
                    (\Yii::$app->{$this->dbTranslation}->driverName === 'mysql' ? 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'
                        : null).
                    ";";
                $sql .= "ALTER TABLE `{$table}__translation`
                        ADD PRIMARY KEY (`{$table}_id`,`{$this->languageField}`);
                        ALTER TABLE `{$table}__translation`
                        ADD CONSTRAINT `fk_{$table}_id_trans` FOREIGN KEY (`{$table}_id`) REFERENCES `$table` (`{$tableSchema->primaryKey[0]}`);";

                $command = $connection->createCommand($sql);
                $result  = $command->execute();
            } else if ($force) {
                $columns = $this->getChangeAttributes($classname);
                if (!empty($columns) && count($columns)) {
                    $sql .= "ALTER TABLE `{$table}__translation` ADD COLUMN (";
                    $ind = 0;
                    foreach ($columns as $value) {
                        $sql .= ($ind == 0 ? "" : ",")."`$value` TEXT DEFAULT NULL";
                        $ind++;
                    }
                    $sql     .= ");";
                    $command = $connection->createCommand($sql);
                    $result  = $command->execute();
                }
            }
            return $result;
        } catch (\Exception $ex) {
            return false;
        }
    }

    /**
     *
     * @param string $classname
     * @return array
     */
    protected function getChangeAttributes($classname)
    {
        $table = $classname::tableName();

        $tableSchema            = \Yii::$app->{$this->dbSource}->getTableSchema($table);
        $tableSchemaTranslation = \Yii::$app->{$this->dbTranslation}->getTableSchema("{$table}__translation");
        $attributes             = $this->getModelAttributes($classname);
        $attributesTranslation  = $this->getModelAttributes("{$classname}Translation", true);

        return array_diff($attributes, $attributesTranslation);
    }

    public function getModelAttributes($classname, $translation = false)
    {
        $table       = $classname::tableName();
        $db          = ($translation ? $this->dbTranslation : $this->dbSource);
        $tableSchema = \Yii::$app->{$db}->getTableSchema($table);
        $attributes  = [];
        if (!empty($this->defaultTypeAttributesToTranslate) && !empty($tableSchema)) {
            foreach ((array) $tableSchema->columns as $key => $value) {
                if (in_array($value->type, $this->defaultTypeAttributesToTranslate) && !in_array($value->name,
                        $this->systemBlackListAttributes)) {
                    $attributes[] = $value->name;
                }
            }
        }
        return $attributes;
    }

    /**
     * @return array Array of the tables for the translatemanager plugin
     */
    public function getArrayDbTranslation()
    {
        try {
            $params             = $this->translationBootstrap;
            $arrayDbTranslation = [];
            if (!empty($params['configuration']['translationLabels']['models'])) {
                $models = $params['configuration']['translationLabels']['models'];
                foreach ($models as $model) {
                    $arrayDbTranslation[] = [
                        'connection' => (isset($model['connection']) ? $model['connection'] : 'db'),
                        'table' => $model['namespace']::tableName(),
                        'columns' => $model['attributes'],
                        'category' => (isset($model['category']) ? $model['category'] : 'database-table-name'),
                    ];
                }
            }

            return $arrayDbTranslation;
        } catch (\Exception $e) {
            return [];
        }
    }
}