Commit ebed01bc authored by Stefan Golban's avatar Stefan Golban
Browse files

initial commit

parents
# phpstorm project files
.idea
# netbeans project files
nbproject
# zend studio for eclipse project files
.buildpath
.project
.settings
# windows thumbnail cache
Thumbs.db
# composer vendor dir
/vendor
# composer itself is not needed
composer.phar
# Mac DS_Store Files
.DS_Store
# phpunit itself is not needed
phpunit.phar
# local phpunit config
/phpunit.xml
composer.lock
# CS fixer cache
.php_cs.cache
\ No newline at end of file
<?php
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude([
'vendor',
])
;
return PhpCsFixer\Config::create()
->setRules([
'@Symfony' => true,
'array_syntax' => ['syntax' => 'short'],
'concat_space' => ['spacing' => 'one'],
'phpdoc_align' => false,
'phpdoc_annotation_without_dot' => false,
'phpdoc_summary' => false,
'phpdoc_inline_tag' => false,
'heredoc_to_nowdoc' => false,
'phpdoc_add_missing_param_annotation' => ['only_untyped' => false],
])
->setFinder($finder)
;
\ No newline at end of file
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/).
## [1.7.3] - 2018-04-04
### Fixed
- Fix invalid column name in findOne() condition #118
## [1.7.2] - 2018-02-23
### Minor
- Restrict version constraints for Yii dependencies in composer.json #116
## [1.7.1] - 2017-10-30
### Fixed
- Fix url creation in translate action #108
- Fix incorrect md5 hash for non-English characters in javascripts #114
## [1.7.0] - 2017-04-30
### Added
- Allow to override default scanners via module configuration #87
- Namespaced migration support #101
### Security
- Limit access to Import/Export actions #89
### Misc
- Module access enhancements #86
- Add PHP-CS-Fixer config and fix coding style #95
- Add usage hint for the search empty command #102
## [1.6.0] - 2016-07-12
### Added
- Add db connection to module settings #85
## [1.5.4] - 2016-04-10
### Added
- Add option to specify whether scan the parent directory of the root, or the root directory itself #73
- Add multiple root directory scan #77
## [1.5.3] - 2016-04-05
### Added
- Add TranslateBehavior
### Changed
- Move headers (h1) from views to layout #53
### Fixed
- Fix translation completeness percentage calculation #51
- Load the correct translation in DialogAction #57
- Fix PHP7 incompatibility in Database Scanner #58
- Fix multiple translators detection in scanners #59
- Run JavaScript generators for active languages after import #68
## [1.5.2] - 2016-02-12
### Added
- Add ability to define category of database translations #41
### Changed
- Display enabled languages firsts in language list #44
### Fixed
- Fix wrong translation returned #43
- Restore searchEmptyCommand functionality #50
## [1.5.1] - 2015-11-16
### Added
- Ability to change source language on translation page
### Changed
- Optimizations in language search model
### Fixed
- Error if extend Module #38
- Filter case sensitive in PostgreSQL #39
- Fixes in language search model
## [1.5.0] - 2015-09-01
### Added
- Import/export feature #31
### Changed
- Autocofus translation textarea in frontend translation dialog #33
### Fixed
- Round error in translation statistic
[1.7.3]: https://github.com/lajax/yii2-translate-manager/compare/1.7.2...1.7.3
[1.7.2]: https://github.com/lajax/yii2-translate-manager/compare/1.7.1...1.7.2
[1.7.1]: https://github.com/lajax/yii2-translate-manager/compare/1.7.0...1.7.1
[1.7.0]: https://github.com/lajax/yii2-translate-manager/compare/1.6.0...1.7.0
[1.6.0]: https://github.com/lajax/yii2-translate-manager/compare/1.5.4...1.6.0
[1.5.4]: https://github.com/lajax/yii2-translate-manager/compare/1.5.3...1.5.4
[1.5.3]: https://github.com/lajax/yii2-translate-manager/compare/1.5.2...1.5.3
[1.5.2]: https://github.com/lajax/yii2-translate-manager/compare/1.5.1...1.5.2
[1.5.1]: https://github.com/lajax/yii2-translate-manager/compare/1.5.0...1.5.1
[1.5.0]: https://github.com/lajax/yii2-translate-manager/compare/1.4.9...1.5.0
# Contributing
Contributions are welcome.
We accept contributions via Pull Requests on [Github](https://github.com/lajax/yii2-translate-manager).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - Check the code style with ``$ composer cs-fix-dry-run`` and fix it with ``$ composer cs-fix``.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is [meaningful](https://chris.beams.io/posts/git-commit/). If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
**Happy coding**!
\ No newline at end of file
<?php
namespace translatemanager;
use Yii;
/**
* Initialisation of the front end interactive translation tool.
* The interface will only appear for users who were given the necessary privileges in the configuration of the translatemanager module.
*
* Initialisation example:
*
* ~~~
* 'bootstrap' => ['translatemanager'],
* 'component' => [
* 'translatemanager' => [
* 'class' => 'translatemanager\Component'
* ]
* ]
* ~~~
*
* @author Lajos Molnar <lajax.m@gmail.com>
*
* @since 1.0
*/
class Component extends \yii\base\Component
{
/**
* @inheritdoc
*/
public function init()
{
$this->_initTranslation();
parent::init();
}
/**
* Initialising front end translator.
*/
private function _initTranslation()
{
$module = Yii::$app->getModule('translatemanager');
if ($module->checkAccess() && $this->_checkRoles($module->roles)) {
Yii::$app->session->set(Module::SESSION_KEY_ENABLE_TRANSLATE, true);
}
}
/**
* Determines if the current user has the necessary privileges for online translation.
*
* @param array $roles The necessary roles for accessing the module.
*
* @return bool
*/
private function _checkRoles($roles)
{
if (!$roles) {
return true;
}
foreach ($roles as $role) {
if (Yii::$app->user->can($role)) {
return true;
}
}
return false;
}
}
The MIT License (MIT)
====================
Copyright (c) 2014 Lajos Molnar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
<?php
namespace translatemanager;
use Yii;
use yii\web\ForbiddenHttpException;
use yii\web\Response;
/**
* This is the main module class for the TranslateManager module.
*
* Initialisation example:
*
* Simple example:
*
* ~~~
* 'modules' => [
* 'translatemanager' => [
* 'class' => 'translatemanager\Module',
* ],
* ],
* ~~~
*
* Complex example:
*
* ~~~
* 'modules' => [
* 'translatemanager' => [
* 'class' => 'translatemanager\Module',
* 'root' => '@app', // The root directory of the project scan.
* 'layout' => 'language', // Name of the used layout. If using own layout use 'null'.
* 'allowedIPs' => ['127.0.0.1'], // IP addresses from which the translation interface is accessible.
* 'roles' => ['@'], // For setting access levels to the translating interface.
* 'tmpDir' => '@runtime', // Writable directory for the client-side temporary language files.
* // IMPORTANT: must be identical for all applications (the AssetsManager serves the JavaScript files containing language elements from this directory).
* 'phpTranslators' => ['::t'], // list of the php function for translating messages.
* 'jsTranslators' => ['lajax.t'], // list of the js function for translating messages.
* 'patterns' => ['*.js', '*.php'],// list of file extensions that contain language elements.
* 'ignoredCategories' => ['yii'], // these categories won’t be included in the language database.
* 'ignoredItems' => ['config'], // these files will not be processed.
* 'languageTable' => 'language', // Name of the database table storing the languages.
* 'scanTimeLimit' => null, // increase to prevent "Maximum execution time" errors, if null the default max_execution_time will be used
* 'searchEmptyCommand' => '!', // the search string to enter in the 'Translation' search field to find not yet translated items, set to null to disable this feature
* 'defaultExportStatus' => 1, // the default selection of languages to export, set to 0 to select all languages by default
* 'defaultExportFormat' => 'json',// the default format for export, can be 'json' or 'xml'
* 'tables' => [ // Properties of individual tables
* [
* 'connection' => 'db', // connection identifier
* 'table' => '{{%language}}', // table name
* 'columns' => ['name', 'name_ascii'], //names of multilingual fields
* 'category' => 'database-table-name', // the category is the database table name
* ]
* ]
* ],
* ],
* ~~~
*
* IMPORTANT: If you want to modify the value of roles (in other words to start using user roles) you need to enable authManager in the common config.
*
* Using of authManager: http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
*
* examples:
*
* PhpManager:
*
* ~~~
* 'components' => [
* 'authManager' => [
* 'class' => 'yii\rbac\PhpManager',
* ],
* ],
* ~~~
*
* DbManager:
*
* ~~~
* 'components' => [
* 'authManager' => [
* 'class' => 'yii\rbac\DbManager',
* ],
* ],
* ~~~
*
*
* @author Lajos Molnár <lajax.m@gmail.com>
*
* @since 1.0
*/
class Module extends \yii\base\Module
{
/**
* Session key for storing front end translating privileges.
*/
const SESSION_KEY_ENABLE_TRANSLATE = 'frontendTranslation_EnableTranslate';
/**
* @inheritdoc
*/
public $controllerNamespace = 'translatemanager\controllers';
/**
* @inheritdoc
*/
public $defaultRoute = 'language/list';
/**
* @var string name of the used layout. If you want to use the site default layout set value null.
*/
/* public $layout = 'language';*/
/**
* @var array the list of IPs that are allowed to access this module.
*/
public $allowedIPs = ['127.0.0.1', '::1'];
/**
* @var array the list of rights that are allowed to access this module.
* If you modify, you also need to enable authManager.
* http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
*/
public $roles = [];
/**
* @var array list of the categories being ignored.
*/
public $ignoredCategories = [];
/**
* @var array directories/files being ignored.
*/
public $ignoredItems = [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/BaseYii.php',
'runtime',
'bower',
'nikic',
];
/**
* @var string|array The root directory or directories of the scanning. The path can be an alias or
* a full path.
*
* It is possible to define one root directory as string. In this case the `scanRootParentDirectory` will be used
* when determining the actual directory to scan.
*
* Multiple root directories can be declared in an array. In this case all items must point to the exact directory,
* as `scanRootParentDirectory` **will be omitted**.
*/
public $root = '@app';
/**
* @var bool Whether scan the defined `root` parent directory, or the folder itself. This option is used only,
* when the `root` option contains a single directory as string (e.g. `'root' => '@app'`).
*
* <b>IMPORTANT</b>: Changing this from `true` to `false` could cause loss of translated items, as
* optimize action removes the missing items.
*
* If the configured root is `@app`:
* - `true` means for advanced apps, that the scan runs on the parent directory, which is the root for the entire project.
* This is the desired behavior.
* - `true` means for basic apps, that the scan runs also on the parent directory, which is outside of the project folder
* (as `@app` is equals to the project root). This is not desired behavior, it is preferred to change this option
* to `false`.
*/
public $scanRootParentDirectory = true;
/**
* @var string writeable directory used for keeping the generated javascript files.
*/
public $tmpDir = '@runtime/';
/**
* @var array list of file extensions that contain language elements.
* Only files with these extensions will be processed.
*/
public $patterns = ['*.php', '*.js'];
/**
* @var string name of the subdirectory which contains the language elements.
*/
public $subDir = '/translate/';
/**
* @var string Regular expression to match PHP Yii::t functions.
*
* @deprecated since version 1.2.7
*/
public $patternPhp = '#::t\s*\(\s*(?P<category>\'[\w\d\s_-]+?(?<!\\\\)\'|"[\w\d\s_-]+?(?<!\\\\)"?)\s*,\s*(?P<text>\'.*?(?<!\\\\)\'|".*?(?<!\\\\)"?)\s*[,\)]#s';
/**
* @var string PHP Regular expression to match arrays containing language elements to translate.
*
* @deprecated since version 1.2.7
*/
public $patternArray = "#\@translate[^\$]+\$(?P<text>.+?)[\]\)];#smui";
/**
* @var string PHP Regular expression to detect langualge elements within arrays.
*
* @deprecated since version 1.2.7
*/
public $patternArrayRecursive = '#(?P<category>)(\[|\(|>|,|)\s*(?P<text>\'.*?(?<!\\\\)\'|".*?(?<!\\\\)"?)\s*(,|$)#s';
/**
* @var string Regular expression to detect JavaScript lajax.t functions.
*
* @deprecated since version 1.2.7
*/
public $patternJs = '#.t\s*\(\s*(?P<text>\'.*?(?<!\\\\)\'|".*?(?<!\\\\)"?)\s*[,\)]#s';
/**
* @var array List of the PHP function for translating messages.
*/
public $phpTranslators = ['::t'];
/**
* @var array List of the JavaScript function for translating messages.
*/
public $jsTranslators = ['lajax.t'];
/**
* @var string PHP Regular expression to match arrays containing language elements to translate.
*/
public $patternArrayTranslator = '#\@translate[^\$]+(?P<translator>[\w\d\s_]+[^\(\[]+)#s';
/**
* @var int The max_execution_time used when scanning, when set to null the default max_execution_time will not be modified.
*/
public $scanTimeLimit = null;
/**
* examples:
*
* ~~~
* $tables = [
* [
* 'connection' => 'db', // connection identifier.
* 'table' => '{{%language}}', // name of the database table to scan.
* 'columns' => ['name', 'name_ascii'] // fields to check.
* ],
* [
* 'connection' => 'db', // connection identifier.
* 'table' => '{{%post}}', // name of the database table to scan.
* 'columns' => ['title', 'description', 'content']// fields to check.
* ],
* ];
* ~~~
*
* @var array identifiers for the database tables containing language elements.
*/
public $tables;
/**
* @var string The database table storing the languages.
*/
public $languageTable = '{{%language}}';
/**
* @var string The search string to find empty translations.
*/
public $searchEmptyCommand = '!';
/**
* @var int The minimum status for a language to be selected by default in the export list.
*/
public $defaultExportStatus = 1;
/**
* @var string The default export format (yii\web\Response::FORMAT_JSON or yii\web\Response::FORMAT_XML).
*/
public $defaultExportFormat = Response::FORMAT_JSON;
/**
* @var string The default db connection
*/
public $connection = 'db';
/**
* @var array Scanners can be overriden here. If not set original set of scanners will be used from Scanner
*/
public $scanners = [];
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if ($this->checkAccess()) {
return parent::beforeAction($action);
} else {
throw new ForbiddenHttpException('You are not allowed to access this page.');
}
}
/**
* @return bool whether the module can be accessed by the current user
*/
public function checkAccess()
{
$ip = Yii::$app->request->getUserIP();
foreach ($this->allowedIPs as $filter) {
if ($filter === '*' || $filter === $ip || (($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos))) {
return true;
}
}
Yii::warning('Access to Translate is denied due to IP address restriction. The requested IP is ' . $ip, __METHOD__);
return false;
}
/**
* @return string The full path of the directory containing the generated JavaScript files.
*/
public function getLanguageItemsDirPath()
{
return Yii::getAlias($this->tmpDir) . $this->subDir;
}
}
# Yii2 - Translate Manager
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Total Downloads][ico-downloads]][link-downloads]
Translation management extension for Yii 2
## Introduction
This module provides a simple translating interface for the multilingual elements of your project. It can auto-detect new language elements (project scan).
Duplications are filtered out automatically during project scanning.
Unused language elements can be removed from the database with a single click (database optimisation) and translations can be imported and exported.
It is possible to translate client side messages too (those stored in JavaScript files) as the project scan collects language elements to be translated from JavaScript files as well.
It also allows you to translate text on the client side (on the live webpage) without having to log in to the translating interface. (frontendTranslation).
On the server side it can handle database or one-dimensional/multidimensional array elements and Yii::t functions.
You can exclude files, folders or categories to prevent them from being translated.
## Contributing
Please read and follow the instructions in the [Contributing guide](CONTRIBUTING.md).
## Installation
Via [Composer](http://getcomposer.org/download/)
```
composer require lajax/yii2-translate-manager
```
### Migration
Run the following command in Terminal for database migration:
```
yii migrate/up --migrationPath=@vendor/lajax/yii2-translate-manager/migrations
```
Or use the [namespaced migration](http://www.yiiframework.com/doc-2.0/guide-db-migrations.html#namespaced-migrations) (requires at least Yii 2.0.10):
```php
// Add namespace to console config:
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'translatemanager\migrations\namespaced',
],
],
],
```