Add new language to database. Scans all tables and adds new
multi-language fields
339647
public function addNewLangToDb()
    {
        //reset max count
        $this->_iCurrentMaxLangId = null;

        $table = $this->getAllTables();

        foreach ($table as $tableName) {
            $this->addNewMultilangField($tableName);
        }

        //updating views
        $this->updateViews();
    }
1056604
protected function addgroup_database(){
		$this->registerGroup(BLang::_('ADMIN_CONFIG_GENERAL_MYSQL'),'database',array(
			new BConfigFieldString(
				'MYSQL_DB_HOST',
				BLang::_('ADMIN_CONFIG_GENERAL_MYSQL_DBHOST'),
				'127.0.0.1'),
			new BConfigFieldString(
				'MYSQL_DB_USERNAME',
				BLang::_('ADMIN_CONFIG_GENERAL_MYSQL_DBUSERNAME'),
				'root'),
			new BConfigFieldPassword(
				'MYSQL_DB_PASSWORD',
				BLang::_('ADMIN_CONFIG_GENERAL_MYSQL_DBPASSWORD'),
				''),
			new BConfigFieldString(
				'MYSQL_DB_NAME',
				BLang::_('ADMIN_CONFIG_GENERAL_MYSQL_DBNAME'),
				'vidido')
			));
		}
697419
private function seedLangs()
    {
        Language::firstOrCreate(
            [
                'code'       => 'en',
                'i18n'       => 'en_US',
                'is_enabled' => true
            ]
        );

        Language::firstOrCreate(
            [
                'code'       => 'pl',
                'i18n'       => 'pl_PL',
                'is_enabled' => true
            ]
        );

        Language::firstOrCreate(
            [
                'code'       => 'de',
                'i18n'       => 'de_DE',
                'is_enabled' => false
            ]
        );

        Language::firstOrCreate(
            [
                'code'       => 'fr',
                'i18n'       => 'fr_FR',
                'is_enabled' => false
            ]
        );

        Language::where('code', config('app.locale'))->update(['is_default' => true]);
    }
188780
public function addLanguageValues($values)
    {
        $this->_languageValues = array_unique(array_merge($this->getLanguageValues(true), $this->filterLanguageValues($values)));
    }
905848
protected function wizardAddLanguage()
    {
        $this->validatePrompt('code', $this->text('Code'), 'language');
        $this->validatePrompt('name', $this->text('Name'), 'language', '');
        $this->validatePrompt('native_name', $this->text('Native name'), 'language', '');
        $this->validatePrompt('status', $this->text('Status'), 'language', 0);
        $this->validatePrompt('default', $this->text('Default') . '?', 'language', 0);
        $this->validatePrompt('weight', $this->text('Weight'), 'language', 0);
        $this->validatePrompt('rtl', $this->text('Right-to-left') . '?', 'language', 0);

        $this->validateComponent('language');
        $this->addLanguage();
    }
795149
protected function ensureMultiLanguageFields($table, $languageId)
    {
        $fields = $this->getMultilangFields($table);
        $sql = [];

        $tableSet = getLangTableName($table, $languageId);
        if (!$this->tableExists($tableSet)) {
            $sql[] = $this->_getCreateTableSetSql($table, $languageId);
        }

        if (is_array($fields) && count($fields) > 0) {
            foreach ($fields as $field) {
                $newFieldName = $field . "_" . $languageId;
                if ($languageId > 1) {
                    $previousLanguage = $languageId - 1;
                    $previousField = $field . '_' . $previousLanguage;
                } else {
                    $previousField = $field;
                }

                if (!$this->tableExists($tableSet) || !$this->fieldExists($newFieldName, $tableSet)) {
                    //getting add field sql
                    $sql[] = $this->getAddFieldSql($table, $field, $newFieldName, $previousField, $tableSet);

                    //getting add index sql on added field
                    $sql = array_merge($sql, (array) $this->getAddFieldIndexSql($table, $field, $newFieldName, $tableSet));
                }
            }
        }

        $this->executeSql($sql);
    }
1014434
def add_translation_fields(model, opts):
    
    model_empty_values = getattr(opts, 'empty_values', NONE)
    for field_name in opts.local_fields.keys():
        field_empty_value = parse_field(model_empty_values, field_name, NONE)
        for l in mt_settings.AVAILABLE_LANGUAGES:
            # Create a dynamic translation field
            translation_field = create_translation_field(
                model=model, field_name=field_name, lang=l, empty_value=field_empty_value)
            # Construct the name for the localized field
            localized_field_name = build_localized_fieldname(field_name, l)
            # Check if the model already has a field by that name

            if hasattr(model, localized_field_name):
                # Check if are not dealing with abstract field inherited.
                for cls in model.__mro__:
                    if hasattr(cls, '_meta') and cls.__dict__.get(localized_field_name, None):
                        cls_opts = translator._get_options_for_model(cls)
                        if not cls._meta.abstract or field_name not in cls_opts.local_fields:
                            raise ValueError("Error adding translation field. Model '%s' already"
                                             " contains a field named '%s'." %
                                             (model._meta.object_name, localized_field_name))
            # This approach implements the translation fields as full valid
            # django model fields and therefore adds them via add_to_class
            model.add_to_class(localized_field_name, translation_field)
            opts.add_translation_field(field_name, translation_field)

    # Rebuild information about parents fields. If there are opts.local_fields, field cache would be
    # invalidated (by model._meta.add_field() function). Otherwise, we need to do it manually.
    if len(opts.local_fields) == 0:
        model._meta._expire_cache()
        model._meta.get_fields()
724541
public function requireDefaultRecords() {
        parent::requireDefaultRecords();
        
        $defaultLangs=array_keys($this->defaultLanguages);
        $dbLangCount=SnippetLanguage::get()
                                        ->filter('Name', $defaultLangs)
                                        ->filter('UserLanguage', 0)
                                        ->Count();
        if($dbLangCount<count($defaultLangs)) {
            foreach($this->defaultLanguages as $name=>$data) {
                if(!SnippetLanguage::get()->find('Name', $name)) {
                    $lang=new SnippetLanguage();
                    $lang->Name=$name;
                    $lang->FileExtension=$data['Extension'];
                    $lang->HighlightCode=$data['HighlightCode'];
                    $lang->UserLanguage=false;
                    $lang->write();
                    
                    DB::alteration_message('Created snippet language "'.$name.'"', 'created');
                }
            }
        }
        
        
        //Look for config languages
        $configLanguages=CodeBank::config()->extra_languages;
        if(!empty($configLanguages)) {
            foreach($configLanguages as $language) {
                //Validate languages
                if(empty($language['Name']) || empty($language['FileName']) || empty($language['HighlightCode']) || empty($language['Brush'])) {
                    user_error('Invalid snippet user language found in config, user languages defined in config must contain a Name, FileName, HighlightCode and Brush file path', E_USER_WARNING);
                    continue;
                }
                
                
                $lang=SnippetLanguage::get()
                                            ->filter('Name', Convert::raw2sql($language['Name']))
                                            ->filter('HighlightCode', Convert::raw2sql($language['HighlightCode']))
                                            ->filter('UserLanguage', true)
                                            ->first();
                
                if(empty($lang) || $lang===false || $lang->ID<=0) {
                    if(Director::is_absolute($language['Brush']) || Director::is_absolute_url($language['Brush'])) {
                        user_error('Invalid snippet user language found in config, user languages defined in config must contain a path to the brush relative to the SilverStripe base ('.Director::baseFolder().')', E_USER_WARNING);
                        continue;
                    }
                    
                    if(preg_match('/\.js$/', $language['Brush'])==0) {
                        user_error('Invalid snippet user language found in config, user languages defined in config must be javascript files', E_USER_WARNING);
                        continue;
                    }
                    
                    
                    //Add language
                    $lang=new SnippetLanguage();
                    $lang->Name=$language['Name'];
                    $lang->FileExtension=$language['FileName'];
                    $lang->HighlightCode=$language['HighlightCode'];
                    $lang->BrushFile=$language['Brush'];
                    $lang->UserLanguage=true;
                    $lang->write();
                    
                    DB::alteration_message('Created snippet user language "'.$language['Name'].'"', 'created');
                }
            }
        }
    }
994623
public function updateAllAction() {
        QC::executeSQL('SET FOREIGN_KEY_CHECKS = 0');
        ModelOperator::getInstance(DC::getEnvironment()->getUserClassesRoot().'db/')->updateDBForAllModels();
        ModelOperator::getInstance()->generateAllModelClasses();
        $this->writeln('DB updated');
    }
994231
def create(self, **kwargs):
        
        with auto_populate(self._populate_mode):
            return super(MultilingualQuerySet, self).create(**kwargs)
850115
protected function safeGuardAdditionalMultiLanguageTables()
    {
        $maxLang = $this->getCurrentMaxLangId();
        $multiLanguageTables = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('aMultiLangTables');

        if (!is_array($multiLanguageTables) || empty($multiLanguageTables)) {
            return; //nothing to do
        }

        foreach ($multiLanguageTables as $table) {
            if ($this->tableExists($table)) {
                //We start with language id 1 and rely on that all fields for language 0 exists.
                //For language id 0 we have e.g. OXTITLE and logic here would expect it to
                //be OXTITLE_0, add that as new field, leading to incorrect data in views later on.
                for ($i=1; $i<=$maxLang; $i++) {
                    $this->ensureMultiLanguageFields($table, $i);
                }
            }
        }
    }
1267685
def add_translation_field(self, field, translation_field):
        
        self.local_fields[field].add(translation_field)
        self.fields[field].add(translation_field)
204465
def __initialize_languages_model(self):
        

        languages = [PYTHON_LANGUAGE, LOGGING_LANGUAGE, TEXT_LANGUAGE]
        existingGrammarFiles = [os.path.normpath(language.file) for language in languages]

        for directory in RuntimeGlobals.resources_directories:
            for file in foundations.walkers.files_walker(directory, ("\.{0}$".format(self.__extension),), ("\._",)):
                if os.path.normpath(file) in existingGrammarFiles:
                    continue

                languageDescription = get_language_description(file)
                if not languageDescription:
                    continue

                LOGGER.debug("> Adding '{0}' language to model.".format(languageDescription))
                languages.append(languageDescription)

        self.__languages_model = LanguagesModel(self, sorted(languages, key=lambda x: (x.name)))
        self.__get_supported_file_types_string()
592221
def add_table(self, name, columns, type_map=None, if_not_exists=False):
        """"""
        # Check types mapping #
        if type_map is None and isinstance(columns, dict): types = columns
        if type_map is None:                               types = {}
        # Safe or unsafe #
        if if_not_exists: query = 'CREATE TABLE IF NOT EXISTS "%s" (%s);'
        else:             query = 'CREATE table "%s" (%s);'
        # Do it #
        cols = ','.join(['"' + c + '"' + ' ' + types.get(c, 'text') for c in columns])
        self.own_cursor.execute(query % (self.main_table, cols))
1258690
public function insert($data)
    {
        DB::transaction(function() use($data) {
            $data['code'] = strtolower($data['code']);
            $model        = new Languages($data);
            $model->save();
            $inserts      = $this->prepareMultiInsert($data['code']);
            DB::table('tbl_translations')->insert($inserts);
        });
    }
1343591
def init_language_data(self, lang, lang_data_type):
        
        if lang not in self.loaded_langs:
            self.loaded_langs[lang] = {}

        if lang_data_type not in self.loaded_langs[lang]:
            result = self._query_lang(lang=lang, lang_data_type=lang_data_type)
            data = self._process_lang(result)
            self.loaded_langs[lang].update({lang_data_type: data})
596874
private function scanAndSaveTranslations()
    {
        // Scan translations
        $this->info('Scanning codebase and storing all translations');

        $this->strReplaceInFile(config_path('admin-translations.php'),
            '// here you can add your own directories',
            '// here you can add your own directories
        // base_path(\'routes\'), // uncomment if you have translations in your routes i.e. you have localized URLs
        base_path(\'vendor/brackets/admin-auth/src\'),
        base_path(\'vendor/brackets/admin-auth/resources\'),');

        $this->call('admin-translations:scan-and-save', [
            'paths' => array_merge(config('admin-translations.scanned_directories'),
                ['vendor/brackets/admin-auth/src', 'vendor/brackets/admin-auth/resources']),
        ]);
    }