/** * Returns the translation table for a given language. * * // Get all defined Spanish messages * $messages = I18n::load('es'); * * @param string $lang language to load * @return array */ public static function load($lang) { if (isset(I18n::$_cache[$lang])) { return I18n::$_cache[$lang]; } // Кешировка данных $cache = new Cache(); $cache->setLocalPath($lang . '_I18n'); // $cache->load(); if ($cache->isValid()) { $items = json_decode($cache->getData(), true); } else { // Возврошает масив где ключи те ж что id таблици $entities = EntityModel::all()->keyBy('id')->toArray(); $translations = (new EntityTranslationModel())->whereLang_id(Lang::instance()->getLang($lang)['id'])->get()->toArray(); // Новая таблица для трансляций $items = []; // Заливает масив где ключом становится entities.text а значением entities_translations.text foreach ($translations as $trans) { $items[$entities[$trans['entity_id']]['text']] = $trans['text']; } //todo: Cacher@ miacnel // $cache->setData(json_encode($items)); // $cache->save(); } // Cache the translation table locally return I18n::$_cache[$lang] = $items; }
public function dispose() { if ($this->_page) { $this->_page->setLang(Lang::instance()->getCurrentLang()['iso']); \Theme::setPage($this->_page); } parent::dispose(); }
/** * Метод обрабатывающий событие обновления транслиаций */ public static function onEntitiesUpdate() { // Очишает кеш $cache = new Cache(); foreach (Lang::instance()->getLangs() as $lang) { $cache->setLocalPath($lang['iso'] . '_I18n'); $cache->clear(); } }
function __($string, array $values = NULL, $lang = null) { if (!$lang) { $lang = Lang::instance()->getCurrentLang()['iso']; } if ($lang !== Lang::DEFAULT_LANGUAGE) { // The message and target languages are different // Get the translation for this message $string = I18n::get($string, $lang); } return empty($values) ? $string : strtr($string, $values); }
public function __construct($json) { $this->_data = json_decode($json, true); if (isset($this->_data['contents'])) { $this->_data['content'] = null; foreach ($this->_data['contents'] as $content) { if ($content['lang_id'] == Lang::instance()->getCurrentLang()['id']) { $this->_data['content'] = $content; } } unset($this->_data['contents']); } }
public function __get($name) { if (parent::__get($name) !== null) { return parent::__get($name); } if ($this->content == null) { $this->content = (new \ContentModel())->getContent($this, Lang::instance()->getCurrentLang()['id']); } return $this->content[$name]; // return parent::__get($name); // return $this->content[$name]; // var_dump($this->id);die; // return (new ContentsModel)->getContent($this, Lang::instance()->getCurrentLang()['iso']); }
public static function makeUriFromId($uri) { // Если это внешний УРЛ if (strpos($uri, 'http:\\') !== false || strpos($uri, 'https:\\') !== false) { return $uri; } if (strpos($uri, 'http://') !== false || strpos($uri, 'https://') !== false) { return $uri; } // Если это Домашная страница if ($uri == '/') { if (!Lang::instance()->getCurrentLangExcept(Lang::instance()->getPrimaryLang()['iso'])['iso']) { return $uri; } return '/' . Lang::instance()->getCurrentLangExcept(Lang::instance()->getPrimaryLang()['iso'])['iso']; } // Приклепляет к УРЛ '/' . текуший язык . сам УРЛ . расширение сайта return '/' . ltrim(Lang::instance()->getCurrentLangExcept(Lang::instance()->getPrimaryLang()['iso'])['iso'] . '/' . ltrim($uri, '/'), '/') . App::URI_EXT; // return '/'.ltrim(implode('/', [Lang::instance()->getCurrentLangExcept(Lang::instance()->getPrimaryLang()['iso'])['iso'], ltrim($uri, '/')]),'/') . App::URI_EXT; }
<label for="title">Title</label> <input type="text" name="content[<?php echo $iso; ?> ][title]" class="form-control" id="title" placeholder="Title" <?php echo Lang::instance()->isPrimary($iso) ? ' required' : ''; ?> > </div> <div class="form-group col-sm-13"> <label for="crumb">Crumb</label> <input type="text" name="content[<?php echo $iso; ?> ][crumb]" class="form-control" id="crumb" placeholder="Crumb" <?php echo Lang::instance()->isPrimary($iso) ? ' required' : ''; ?> > </div> <div class="form-group col-sm-13"> <label for="desc">Description</label> <textarea name="content[<?php echo $iso; ?> ][desc]" class="tinymce"></textarea> </div> <legend>Meta Content</legend> <div class="form-group col-sm-13"> <label for="meta_title">Title</label> <input type="text" name="content[<?php echo $iso;
/** * Проверяет совпадает ли адрес роута с указанным * @param $uri * @return bool */ public function matchURI($uri) { if (class_exists('Lang\\Lang')) { $uri = Lang::instance()->initSiteLangFromUri($uri); // Инициадизут УРИ без префикса ИСО яхыка if (!$this->_whiteUri) { $this->_whiteUri = $uri; } } //проверяем верная ли оконцовка файла указанная в конфигах if (!preg_match('#' . str_replace('.', '\\.', App::URI_EXT) . '$#uD', $uri) && $uri != '/') { return empty($this->_rules) && $this->_uri . App::URI_EXT === $uri; } //удаляем оконцовку $uri = preg_replace('#(' . str_replace('.', '\\.', App::URI_EXT) . ')$#uD', '', $uri); $pattern = $this->_uri; //находим совпадения для правил валидации preg_match_all('#[{]([^}?]+)([?]?)[}]#uD', $pattern, $matches); //обрабатывает страку в соответствии с правилами валидации if (!empty($matches)) { $patterns = $replacments = []; for ($i = 0; $i < count($matches[1]); $i++) { $endOfPattern = ')'; if (isset($this->_rules[$matches[1][$i]])) { $endOfPattern = preg_replace('#\\.#uD', '[^/\\#.\\^$]', $this->_rules[$matches[1][$i]]) . $endOfPattern; } else { $endOfPattern = '[^/\\#.\\^$]+' . $endOfPattern; } if ($matches[2][$i] === '?') { $endOfPattern .= '?'; } $replacments[$matches[1][$i]] = '(?P<' . $matches[1][$i] . '>' . $endOfPattern; $patterns[] = '#[{]' . $matches[1][$i] . '[?]?[}]#uD'; } $pattern = preg_replace($patterns, $replacments, $pattern); if (preg_match('#[/]\\([^)]+\\)[?]#uD', $pattern)) { $pattern = preg_replace('#([/])(\\([^)]+\\))([?])#uD', '(?(?=/)(/$2))?', $pattern); } } $match = (bool) preg_match("#^{$pattern}\$#uD", $uri, $this->_actionVaribles); //отправляем переданные переманные в контроллер foreach ($this->_actionVaribles as $key => $val) { if (is_numeric($key)) { unset($this->_actionVaribles[$key]); } } return $match; }
/** * Редактирование материалов */ public function anyEdit() { $id = (int) $this->getRequestParam('id') ?: null; $article = ArticleModel::find($id); if (empty($article)) { throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Article'])); } if (Arr::get($this->getPostData(), 'submit') !== null) { $data = Arr::extract($this->getPostData(), ['slug', 'parentId', 'status', 'content']); $parent = ArticleModel::find($data['parentId']); // Транзакция для Записание данных в базу try { Event::fire('Admin.beforeArticleUpdate', $article); Capsule::connection()->transaction(function () use($data, $article, $parent) { if ($parent) { $article->makeChildOf($parent); } else { $article->makeRoot(); } // Заодно обновляет и пункты меню привязанные к slug-у (new \MenuItemModel())->whereSlug($article->slug)->update(['slug' => $data['slug']]); $article->update(['slug' => $data['slug'], 'status' => $data['status']]); foreach ($data['content'] as $iso => $item) { $lang_id = Lang::instance()->getLang($iso)['id']; if ((int) $item['id'] != 0) { $content = ContentModel::find($item['id']); $content->update(['title' => $item['title'], 'crumb' => $item['crumb'], 'desc' => $item['desc'], 'meta_title' => $item['metaTitle'], 'meta_desc' => $item['metaDesc'], 'meta_keys' => $item['metaKeys'], 'lang_id' => $lang_id]); } else { //todo: надо по тестить почему без ID каждий раз создаётся все записи а не обновляются $content = ContentModel::create(['article_id' => $data['content']['ru']['id'], 'title' => $item['title'], 'crumb' => $item['crumb'], 'desc' => $item['desc'], 'meta_title' => $item['metaTitle'], 'meta_desc' => $item['metaDesc'], 'meta_keys' => $item['metaKeys'], 'lang_id' => $lang_id]); $article->contents()->attach($content); } // $article->contents()->attach($content); } }); Event::fire('Admin.articleUpdate', $article); } catch (QueryException $e) { Message::instance()->warning('Article was don\'t edited'); } } // Загрузка контента для каждово языка $contents = []; foreach (Lang::instance()->getLangs() as $iso => $lang) { $contents[$iso] = $article->contents()->where('lang_id', '=', $lang['id'])->first(); } $this->layout->content = View::make('back/articles/edit')->with('node', $article::getNode())->with('article', $article)->with('contents', $contents); }
/** * Редактирование */ public function anyEdit() { $id = (int) $this->getRequestParam('id') ?: null; $model = PlayerModel::find($id); $firstNameModel = $model->firstNameModel()->first(); $lastNameModel = $model->lastNameModel()->first(); if (empty($model)) { throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Player'])); } if (Arr::get($this->getPostData(), 'submit') !== null) { $data = Arr::extract($this->getPostData(), ['slug', 'image', 'country', 'position', 'status', 'number', 'team', 'first_name', 'last_name', 'content']); // Транзакция для Записание данных в базу try { Capsule::connection()->transaction(function () use($data, $model, $firstNameModel, $lastNameModel) { // Загрузка картинки $file = new UploadFile('image', new FileSystem('uploads/images')); // Optionally you can rename the file on upload $file->setName(uniqid()); // // Validate file upload // $file->addValidations(array( // // Ensure file is of type image // new UploadMimeType(['image/png','image/jpg','image/gif']), // // // Ensure file is no larger than 5M (use "B", "K", M", or "G") // new UploadSize('50M') // )); // Try to upload file try { // Success! $file->upload(); $image = '/' . static::IMAGE_PATH . '/' . $file->getNameWithExtension(); } catch (UploadException $e) { // Fail! $image = null; Message::instance()->warning($file->getErrors()); } catch (Exception $e) { // Fail! $image = null; Message::instance()->warning($file->getErrors()); } $firstNameModel->updateOrCreate(['id' => $firstNameModel->id], ['text' => $data['first_name']]); $lastNameModel->updateOrCreate(['id' => $lastNameModel->id], ['text' => $data['last_name']]); foreach ($data['content'] as $iso => $d) { $lang_id = Lang::instance()->getLang($iso)['id']; EntityTranslationModel::updateOrCreate(['id' => $d['first_name_id']], ['text' => $d['first_name'], 'lang_id' => $lang_id, 'entity_id' => $firstNameModel->id]); EntityTranslationModel::updateOrCreate(['id' => $d['last_name_id']], ['text' => $d['last_name'], 'lang_id' => $lang_id, 'entity_id' => $lastNameModel->id]); } Event::fire('Admin.entitiesUpdate'); // если нету нового изображения оставить прежний if ($image) { $imageId = PhotoModel::create(['path' => $image, 'is_bound' => 1])->id; $model->update(['image_id' => $imageId]); } $model->update(['team_id' => $data['team'], 'slug' => $data['slug'], 'number' => $data['number'], 'status' => $data['status'], 'country_id' => $data['country'], 'position_id' => $data['position'], 'first_name_id' => $firstNameModel->id, 'last_name_id' => $lastNameModel->id]); }); Message::instance()->success('Player was successfully saved'); } catch (Exception $e) { Message::instance()->warning('Player was don\'t saved'); } } $model = PlayerModel::find($id); $firstNameModel = $model->firstNameModel()->first(); $lastNameModel = $model->lastNameModel()->first(); // Загрузка контента для каждово языка $contents = []; foreach (Lang::instance()->getLangsExcept(Lang::DEFAULT_LANGUAGE) as $iso => $lang) { $contents[$iso]['firstName'] = $firstNameModel->translations()->whereLang_id($lang['id'])->first(); $contents[$iso]['lastName'] = $lastNameModel->translations()->whereLang_id($lang['id'])->first(); } //echo "<pre>"; //print_r($contents); //die; $this->layout->content = View::make('back/players/edit')->with('item', $model)->with('contents', $contents); }
public function anyTestLangRoute() { var_dump(Lang::instance()->getCurrentLang()); $article = (new \ArticleModel())->find(1); echo $article->id; echo "<br>"; echo $article->title; echo "<br>"; echo $article->desc; echo "<br>"; echo \Helpers\Uri::makeUri('TestLangRoute.html'); echo "<br>"; }
/** * Редактирование пункта меню */ public function anyEdit() { $id = (int) $this->getRequestParam('id') ?: null; $model = MenuItemModel::find($id); $entityModel = $model->entities()->first(); if (empty($model)) { throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Article'])); } if (Arr::get($this->getPostData(), 'submit') !== null) { $data = Arr::extract($this->getPostData(), ['slug', 'icon', 'parentId', 'status', 'entity', 'content']); $parent = MenuItemModel::find($data['parentId']); // Транзакция для Записание данных в базу try { Capsule::connection()->transaction(function () use($data, $model, $parent, $entityModel) { // Загрузка картинки $file = new UploadFile('image', new FileSystem('uploads/images')); // Optionally you can rename the file on upload $file->setName(uniqid()); // Validate file upload $file->addValidations(array(new UploadMimeType(['image/png', 'image/jpg', 'image/gif']), new UploadSize('50M'))); // Try to upload file try { // Success! $file->upload(); $data['icon'] = $file->getNameWithExtension(); } catch (Exception $e) { // Fail! Message::instance()->warning($file->getErrors()); } $entityModel->update(['text' => $data['entity']]); foreach ($data['content'] as $iso => $d) { $langId = Lang::instance()->getLang($iso)['id']; EntityTranslationModel::updateOrCreate(['id' => $d['id']], ['text' => $d['text'], 'lang_id' => $langId, 'entity_id' => $entityModel->id]); } Event::fire('Admin.entitiesUpdate'); // если нету нового изображения оставить прежний $data['icon'] ?: $model->icon; $model->update(['slug' => $data['slug'], 'status' => $data['status'], 'icon' => $data['icon']]); if ($parent) { $model->makeChildOf($parent); } else { $model->makeRoot($parent); } }); Message::instance()->success('Menu Item was successfully edited'); } catch (Exception $e) { Message::instance()->warning('Menu Item was don\'t edited'); } } $model = MenuItemModel::find($id); $entityModel = $model->entities()->first(); // Загрузка контента для каждово языка $contents = []; foreach (Lang::instance()->getLangsExcept(Lang::DEFAULT_LANGUAGE) as $iso => $lang) { $contents[$iso] = $entityModel->translations()->where('lang_id', '=', $lang['id'])->first(); } $this->layout->content = View::make('back/menus/edit')->with('node', $model::getNode())->with('item', $model)->with('contents', $contents); }
<!-- <script src="external/jquery/jquery.js"></script>--> <script src="/media/libs/jquery-ui-1.11.4.sortable/jquery-ui.min.js"></script> <!-- Скрипти для загрузки файлов--> <script src='/media/back/plugins/bootstrap-fileinput-master/js/plugins/canvas-to-blob.min.js'></script> <script src='/media/back/plugins/bootstrap-fileinput-master/js/fileinput.min.js'></script> <script src='/media/back/plugins/bootstrap-fileinput-master/js/fileinput_locale_LANG.js'></script> <script src='/media/back/plugins/jquery.mjs.nestedSortable.js'></script> </head> <body> <div id="main" data-base-url="<?php echo App::baseUrl(); ?> " data-current-lang-iso="<?php echo Lang::instance()->getCurrentLang()['iso']; ?> " data-uri-ext="<?php echo App::URI_EXT; ?> " data-redirect=""> <nav class="navbar navbar-fixed-top navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php