Commit feb179fe authored by Marcello Pivanti's avatar Marcello Pivanti
Browse files

Initial Commit

parents
# Amos Translation
Translation management.
### Button clean translatemanager cache
Insert in config/component-amos
```php
'view' => [
'class' => 'elitedivision\amos\core\components\AmosView',
'theme' => [
'pathMap' => [
'@vendor/lajax/yii2-translate-manager/views/language/' => '@vendor/elitedivision/amos-translation/src/views/translatemanager/'
],
],
],
```
{
"name": "arter/amos-translation",
"description": "AMOS Translation",
"keywords": [
"amos",
"yii2",
"translation"
],
"homepage": "http://www.elitedivision.it/",
"type": "component",
"license": "BSD-3-Clause",
"support": {
"issues": "http://www.example.com/",
"forum": "http://www.example.com/forum/",
"wiki": "http://www.example.com/wiki/",
"source": "https://github.com/elitedivision/amos-workflow"
},
"minimum-stability": "dev",
"require": {
"php": ">=5.5.0",
"arter/amos-core": ">=1.9.50",
"arter/amos-dashboard": ">=1.8.15",
"arter/amos-workflow": "*",
"lajax/yii2-translate-manager": "1.*"
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
},
"autoload": {
"psr-4": {
"elitedivision\\amos\\translation\\": "src"
}
}
}
\ No newline at end of file
This diff is collapsed.
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Automatic configuration of the fields of the db reading from an attribute of the AmosModule valued in the plugins installed on the platform
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\chat
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\translation\assets;
use yii\web\AssetBundle;
/**
* Class AmosChatAsset
* @package elitedivision\amos\chat\assets
*/
class AmosTranslationAsset extends AssetBundle
{
/**
* @var string
*/
public $sourcePath = '@vendor/elitedivision/amos-translation/src/assets/web';
/**
* @var array
*/
public $css = [
'css/style.css',
];
/**
* @var array
*/
public $js = [];
/**
* @var array
*/
public $depends = [
'elitedivision\amos\core\views\assets\AmosCoreAsset',
];
}
\ No newline at end of file
.color-source-content {
background-color: #d6dfea;
}
\ No newline at end of file
This diff is collapsed.
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\translation
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\translation\bootstrap;
use elitedivision\amos\translation\AmosTranslation;
use elitedivision\amos\translation\models\LanguageTranslateUserFields;
use Yii;
use yii\base\Event;
use yii\db\ActiveRecord;
/**
* Class EventActiveRecordBootstrap
* @package elitedivision\amos\translation\bootstrap
*/
class EventActiveRecordBootstrap extends \yii\db\ActiveRecord
{
private $configuration;
/**
* Application-specific roles initialization
* @uses onApplicationAction
*/
public function init()
{
$this->configuration = \Yii::$app->getModule('translation')->translationBootstrap;
\yii\base\Event::on(\yii\db\ActiveRecord::className(), self::EVENT_INIT, [$this, 'onEventInit']);
/** @var AmosTranslation $translationModule */
$translationModule = Yii::$app->getModule(AmosTranslation::getModuleName());
Event::on($translationModule->modelOwnerPlatformTranslation, ActiveRecord::EVENT_BEFORE_UPDATE,
[$this, 'setTranslationOwner']);
parent::init();
}
/**
*
* @param yii\base\Event $event
*/
public function onEventInit($event)
{
$this->initConfigurationLabels();
$this->enableTranslationContents($event);
$this->enableTranslationLabels($event);
}
/**
* @param yii\base\Event $event
*/
public function setTranslationOwner($event)
{
if (Yii::$app instanceof \yii\web\Application && !Yii::$app->user->isGuest && !empty($event->sender->dirtyAttributes)) {
/** @var AmosTranslation $translationModule */
$translationModule = Yii::$app->getModule(AmosTranslation::getModuleName());
$now = date('Y-m-d H:i:s');
$loggedUserId = Yii::$app->user->id;
$ltUserFields = LanguageTranslateUserFields::findOne([
'language_translate_id' => $event->sender->{$translationModule->modelOwnerPlatformTrIdField},
'language_translate_language' => $event->sender->{$translationModule->modelOwnerPlatformTrLanguageField}
]);
if (is_null($ltUserFields)) {
$ltUserFields = new LanguageTranslateUserFields();
$ltUserFields->language_translate_id = $event->sender->{$translationModule->modelOwnerPlatformTrIdField};
$ltUserFields->language_translate_language = $event->sender->{$translationModule->modelOwnerPlatformTrLanguageField};
$ltUserFields->created_at = $now;
$ltUserFields->created_by = $loggedUserId;
}
$ltUserFields->updated_at = $now;
$ltUserFields->updated_by = $loggedUserId;
$ltUserFields->save(YII_DEBUG);
}
}
public function initConfigurationLabels()
{
$processed = [];
$translationModule = \Yii::$app->getModule('translation');
$path = \Yii::getAlias('@'.str_replace('\\', '/', $translationModule->modelNs)).'/'."{$translationModule->fileNameDbConfFields}".'.php';
try {
if (!file_exists($path)) {
$handle = fopen($path, 'ab');
$placeholder = "/**************placeholder**************/";
fwrite($handle, "<?php return [\n$placeholder\n];\n");
fclose($handle);
$propertyName = $translationModule->propertyModule;
$conf = "";
foreach (\Yii::$app->getModules() as $k => $v) {
$module = \Yii::$app->getModule($k);
if (!empty($module) && !in_array($k, $translationModule->moduleBlackListForDbConfFields) && property_exists(get_class($module),
$propertyName)) {
if (!empty($module->{$propertyName}) && is_array($module->{$propertyName})) {
if (!in_array($k, $processed)) {
$processed[] = $k;
foreach ($module->db_fields_translation as $key => $value) {
$conf .= "\t[\n";
foreach ($value as $k1 => $v1) {
if (is_array($v1)) {
$v2 = implode("','", $v1);
$conf .= "\t\t'".$k1."' => ['".$v2."'],\n";
} else {
$conf .= "\t\t'".$k1."' => '".$v1."',\n";
}
}
$conf .= "\t],\n";
}
}
}
}
}
$fileContent = file_get_contents($path);
$configuration = str_replace($placeholder, $conf, $fileContent);
$handle2 = fopen($path, 'wb');
fwrite($handle2, $configuration);
fclose($handle2);
}
} catch (\Exception $e) {
\Yii::trace("Error in the configuration of the db fields translation", __METHOD__);
}
}
/**
*
* @param yii\base\Event $event
*/
public function enableTranslationLabels($event)
{
if (!empty($this->configuration['configuration']['translationLabels'])) {
$translationLabels = $this->configuration['configuration']['translationLabels'];
if (!empty($translationLabels['classBehavior']) && !empty($translationLabels['models']) && !empty(\Yii::$app->getModule('translatemanager'))) {
foreach ($translationLabels['models'] as $model) {
if (!empty($model['namespace']) && !empty($model['attributes'])) {
$classSender = get_class($event->sender);
if ($classSender == $model['namespace']) {
$event->sender->attachBehavior('translationLabels',
[
'class' => (isset($model['classBehavior']) ? $model['classBehavior'] : $translationLabels['classBehavior']),
'translateAttributes' => $model['attributes'],
'category' => (!empty($model['category']) ? $model['category'] : (null != ($event->sender->tableName())
? $event->sender->tableName() : 'database')),
]);
}
}
}
}
}
}
/**
*
* @param yii\base\Event $event
*/
private function enableTranslationContents($event)
{
if (!empty($this->configuration['configuration']['translationContents'])) {
$translationContents = $this->configuration['configuration']['translationContents'];
if (!empty($translationContents['classBehavior']) && !empty($translationContents['models']) && !empty(\Yii::$app->getModule('translation'))) {
foreach ($translationContents['models'] as $model) {
if (!empty($model['namespace']) && !empty($model['attributes'])) {
$classSender = get_class($event->sender);
if ($classSender == $model['namespace']) {
$configuration = $this->setTranslationContentsConfiguration($model, $event->sender);
$event->sender->attachBehavior('translationContents', $configuration);
}
}
}
}
}
}
/**
*
* @param array $model
* @return array
*/
private function setTranslationContentsConfiguration($model, $sender)
{
$configuration = [];
try {
$module = \Yii::$app->getModule('translation');
$configuration['class'] = (isset($model['classBehavior']) ? $model['classBehavior'] : $this->configuration['configuration']['translationContents']['classBehavior']);
$configuration['translationAttributes'] = (!empty($model['attributes']) ? $model['attributes'] : $this->getAllAttributes($sender));
$configuration['defaultLanguage'] = (!empty($model['defaultLanguage']) ? $model['defaultLanguage'] : $module->defaultLanguage);
$configuration['forceTranslation'] = (!empty($model['forceTranslation']) ? $model['forceTranslation'] : $module->forceTranslation);
$configuration['pathsTranslation'] = (!empty($model['pathsTranslation']) ? $model['pathsTranslation'] : $module->pathsForceTranslation);
$enableWorkflow = $module->enableWorkflow;
if (isset($model['enableWorkflow'])) {
$enableWorkflow = boolval($model['enableWorkflow']);
}
$workflowBehavior = (isset($model['workflowBehavior']) ? $model['workflowBehavior'] : $module->workflowBehavior);
$workflowStatusApproved = (isset($model['statusWorkflowApproved']) ? $model['statusWorkflowApproved'] : $module->statusWorkflowApproved);
$statusWorkflowInitial = (isset($model['statusWorkflowInitial']) ? $model['statusWorkflowInitial'] : $module->statusWorkflowInitial);
if ($enableWorkflow && !empty($workflowBehavior)) {
$configuration['enableWorkflow'] = $enableWorkflow;
$configuration['workflowBehavior'] = $workflowBehavior;
$configuration['statusWorkflowApproved'] = $workflowStatusApproved;
$configuration['statusWorkflowInitial'] = $statusWorkflowInitial;
$configuration['workflow'] = (!empty($model['workflow']) ? $model['workflow'] : 'AmosTranslationWorkflow');
}
return $configuration;
} catch (\Exception $ex) {
\Yii::$app->getSession()->addFlash('danger',
Yii::t('amostranslation', 'Configuration of the plugin Translation is not set correctly.'));
if (YII_ENV_DEV) {
pr($ex->getMessage());
die;
}
return $configuration;
}
}
protected function getAllAttributes($sender)
{
$attributes = [];
$classname = get_class($sender);
$table = $classname::tableName();
$dbSource = \Yii::$app->getModule('translation')->dbSource;
$defaultTypeAttributesToTranslate = \Yii::$app->getModule('translation')->defaultTypeAttributesToTranslate;
$tableSchema = \Yii::$app->$dbSource->getTableSchema($table);
if (!empty($defaultTypeAttributesToTranslate)) {
foreach ((array) $tableSchema->columns as $key => $value) {
if (in_array($value->type, $defaultTypeAttributesToTranslate)) {
$attributes[] = $value->name;
}
}
}
return $attributes;
}
}
\ No newline at end of file
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\translation
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\translation\bootstrap;
use Yii;
use yii\base\Application;
use yii\helpers\FileHelper;
use elitedivision\amos\translation\models\TranslationConf;
use elitedivision\amos\translation\AmosTranslation;
/**
* Class TranslationBootstrap: <br />
* Add behaviours for the translation of the model <br />
* ELIGIBLE FOR DEPRECATION (DEPRECATED)
* @package backend\bootstrap
*/
class EventViewBootstrap extends \yii\web\View
{
/**
* Application-specific roles initialization
* @uses onApplicationAction
*/
public function init()
{
\yii\base\Event::on(\yii\web\View::className(), self::EVENT_AFTER_RENDER, [$this, 'onEventAfterRender']);
//\yii\base\Event::on(\yii\web\View::className(), self::EVENT_END_BODY, [$this, 'onEventAfterRender']);
parent::init();
}
/**
*
* @param yii\base\Event $event
*/
public function onEventAfterRender($event)
{
$moduleTranslation = \Yii::$app->getModule('translation');
if (!empty($moduleTranslation)) {
if ($moduleTranslation->enableWidgetView && \Yii::$app instanceof Application) {
$viewSender = FileHelper::normalizePath(str_replace(['.php', '.PHP'], '', $event->sender->viewFile));
$modelSource = null;
$modelsEnabled = [];
$blackListModels = array_merge([
'elitedivision\amos\translation\bootstrap\EventViewBootstrap',
], $moduleTranslation->eventViewBlackListModels);
$blackListViews = array_merge([
'views/layouts/',
'yii2-debug\views',
], $moduleTranslation->eventViewBlackListViews);
$checkView = false;
$checkPart = false;
foreach ($blackListViews as $val) {
if (strpos($event->sender->viewFile, $val) === false) {
$checkView = true;
}
}
foreach ($moduleTranslation->eventViewWhiteListParts as $part) {
if (in_array($part, explode(DIRECTORY_SEPARATOR, str_replace('.php', '', $event->sender->viewFile)))) {
$checkPart = true;
}
}
$arrayModels = [];
if ($checkView && $checkPart) {
if (isset($moduleTranslation->translationBootstrap['configuration']['translationContents']['models'])) {
foreach ($moduleTranslation->translationBootstrap['configuration']['translationContents']['models'] as $value) {
if (!empty($value['namespace'])) {
$arrayModels[$value['namespace']] = (isset($value['workflow']) ? $value['workflow'] : 'AmosTranslationWorkflow');
}
if (!empty($value['view']) && !empty($value['namespace']) && FileHelper::normalizePath(str_replace([
'.php', '.PHP'], '', \Yii::getAlias($value['view']))) == $viewSender) {
$modelSource = $value['namespace'];
}
}
}
if (empty($modelSource)) {
if (!empty($event->sender->context->model) && !in_array(get_class($event->sender->context->model),
$blackListModels) && array_key_exists(get_class($event->sender->context->model),
$arrayModels)) {
$modelSource = $event->sender->context->model;
}
}
if (!empty($modelSource)) {
$conf = new TranslationConf();
$statuses = [];
$languages = TranslationConf::getStaticAllActiveLanguages(true);
$namespace = get_class($modelSource);
$workflow = $arrayModels[$namespace];
if ($languages->count() > 1) {
foreach ($languages->all() as $lang) {
$statusLang = $conf->getStatus($namespace, $lang, $modelSource->id);
$label = AmosTranslation::t('amostranslation', 'Not translated');
if (!empty($statusLang->status)) {
$label = (!empty($statusLang->status) ? $conf->getLabelStatus($statusLang->status,
$workflow) : AmosTranslation::t('amostranslation', 'Not translated'));
}
$statuses[$lang->language_id] = $label;
}
echo $event->sender->renderFile($moduleTranslation->widgetViewFile,
['statusLangs' => $statuses, 'namespace' => $namespace, 'getParams' => \Yii::$app->request->get()]);
}
}
}
}
}
}
}
\ No newline at end of file
<?php
/**
* Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
* OPEN 2.0
*
*
* @package elitedivision\amos\translation
* @category CategoryName
* @author Elite Division S.r.l.
*/
namespace elitedivision\amos\translation\components;
use Yii;
use yii\gii\CodeFile;
use yii\helpers\Inflector;
use yii\db\Schema;
class Generator extends \yii\gii\generators\model\Generator
{
/**
* @var bool whether to overwrite (extended) model classes, will be always created, if file does not exist
*/
public $generateModelClass = false;
/**
* @var null string for the table prefix, which is ignored in generated class name
*/
public $tablePrefix = null;
/**
* @var array key-value pairs for mapping a table-name to class-name, eg. 'prefix_FOObar' => 'FooBar'
*/
public $tableNameMap = [];
protected $classNames2;
public $classnameTarget;
/**
* @var array for new rules
*/
public $newRules = [];
/**
* @var array per relazioni aggiuntive
*/
public $otherRelations = [];
public $workflow;
/**
*
* @var array per le colonne rappresentative
*/
public $representingColumn;
/**
*
*/
public $pluginName;
/**
*
* @var string $generatedClassName
*/
public $generatedClassName;
/**
* @inheritdoc
*/
public function getName()
{
return 'Amos Model';
}
/**
* @inheritdoc
*/
public function getDescription()
{
return 'This generator generates an ActiveRecord class and base class for the specified database table.';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(
parent::rules(),
[
[['generateModelClass'], 'boolean'],
[['tablePrefix'], 'safe'],
]
);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_merge(
parent::attributeLabels(), [
'generateModelClass' => 'Generate Model Class',
]
);
}
/**
* @inheritdoc
*/
public function hints()
{
return array_merge(
parent::hints(),
[
'generateModelClass' => 'This indicates whether the generator should generate the model class, this should usually be done only once. The model-base class is always generated.',
'tablePrefix' => 'Custom table prefix, eg <code>app_</code>.<br/><b>Note!</b> overrides <code>yii\db\Connection</code> prefix!',
]