Merge branch 'editable_locales'

This allows to edit locales meta info using UI
This commit is contained in:
Dmitriy Simushev 2015-05-22 12:22:27 +00:00
commit 8326eb3ebf
10 changed files with 544 additions and 63 deletions

View File

@ -129,12 +129,23 @@ translation:
# Contains locales info # Contains locales info
locale: locale:
fields: fields:
# Artificial primary key # Artificial primary key.
localeid: "int NOT NULL auto_increment PRIMARY KEY" localeid: "int NOT NULL auto_increment PRIMARY KEY"
# Locale code # Locale code
code: "varchar(5) NOT NULL" code: "varchar(5) NOT NULL"
# Indicates if a locale is enabled or not. # Human readable name of the locale.
name: "varchar(128) NOT NULL DEFAULT ''"
# Indicates if the locale is enabled or not.
enabled: "tinyint NOT NULL DEFAULT 0" enabled: "tinyint NOT NULL DEFAULT 0"
# Indicates if the locale uses RTL writing.
rtl: "tinyint NOT NULL DEFAULT 0"
# Name of the locale which is used with PHP's setlocale to format dates.
time_locale: "varchar(128) NOT NULL DEFAULT 'en_US'"
# Serialized array of various date formats.
date_format: "text"
unique_keys:
# Make sure locale code can be duplicated
code: [code]
# Contains localized mail templates # Contains localized mail templates
mailtemplate: mailtemplate:

View File

@ -351,6 +351,26 @@ locale_disable:
requirements: requirements:
locale: "[a-z\-]{2,5}" locale: "[a-z\-]{2,5}"
locale_edit:
path: /operator/locale/{locale}/edit
defaults:
_controller: Mibew\Controller\Localization\LocaleController::showEditFormAction
_access_check: Mibew\AccessControl\Check\PermissionsCheck
_access_permissions: [CAN_ADMINISTRATE]
requirements:
locale: "[a-z\-]{2,5}"
methods: [GET]
locale_edit_save:
path: /operator/locale/{locale}/edit
defaults:
_controller: Mibew\Controller\Localization\LocaleController::submitEditFormAction
_access_check: Mibew\AccessControl\Check\PermissionsCheck
_access_permissions: [CAN_ADMINISTRATE]
requirements:
locale: "[a-z\-]{2,5}"
methods: [POST]
locale_enable: locale_enable:
path: /operator/locale/{locale}/enable path: /operator/locale/{locale}/enable
defaults: defaults:

View File

@ -55,7 +55,10 @@ abstract class AbstractController extends BaseAbstractController
? $this->generateUrl('translation_export') ? $this->generateUrl('translation_export')
: ''; : '';
$tabs[getlocal('Locales')] = ($route != 'locales') $locales = ($route == 'locales'
|| $route == 'locale_edit'
|| $route == 'locale_edit_save');
$tabs[getlocal('Locales')] = !$locales
? $this->generateUrl('locales') ? $this->generateUrl('locales')
: ''; : '';

View File

@ -130,4 +130,127 @@ class LocaleController extends AbstractController
return $this->redirect($this->generateUrl('locales')); return $this->redirect($this->generateUrl('locales'));
} }
/**
* Builds locale edit page.
*
* @param Request $request Incoming request.
* @return string Rendered page content.
* @throws NotFoundException If the locale with specified code is not found
* in the system.
*/
public function showEditFormAction(Request $request)
{
$page = array(
// Use errors list stored in the request. We need to do so to have
// an ability to pass the request from the "submitEditForm" action.
'errors' => $request->attributes->get('errors', array()),
);
$locale = $request->attributes->get('locale');
// Check if locale exists and enabled.
if (!in_array($locale, get_available_locales())) {
throw new NotFoundException();
}
$info = get_locale_info($locale);
$page['formtimelocale'] = $info['time_locale'];
$page['formdateformatfull'] = $info['date_format']['full'];
$page['formdateformatdate'] = $info['date_format']['date'];
$page['formdateformattime'] = $info['date_format']['time'];
// Override fields from the request if it's needed. This case will take
// place when a save handler fails and passes the request to this
// action.
if ($request->isMethod('POST')) {
$page['formtimelocale'] = $request->request->get('timelocale');
$page['formdateformatfull'] = $request->request->get('dateformatfull');
$page['formdateformatdate'] = $request->request->get('dateformatdate');
$page['formdateformattime'] = $request->request->get('dateformattime');
}
$page['stored'] = $request->query->has('stored');
$page['title'] = getlocal('Locale details');
$page['menuid'] = 'translation';
$page['formaction'] = $request->getBaseUrl() . $request->getPathInfo();
$page = array_merge($page, prepare_menu($this->getOperator()));
$page['tabs'] = $this->buildTabs($request);
return $this->render('locale_edit', $page);
}
/**
* Processes submitting of the form which is generated in
* {@link \Mibew\Controller\Localization\LocaleController::showEditFormAction()}
* method.
*
* @param Request $request Incoming request.
* @return string Rendered page content.
* @throws NotFoundException If the locale with specified code is not found
* in the system.
*/
public function submitEditFormAction(Request $request)
{
csrf_check_token($request);
$errors = array();
$locale = $request->attributes->get('locale');
$time_locale = $request->request->get('timelocale');
$date_format_full = $request->request->get('dateformatfull');
$date_format_date = $request->request->get('dateformatdate');
$date_format_time = $request->request->get('dateformattime');
if (!$locale) {
throw new NotFoundException();
}
if (!$time_locale) {
$errors[] = no_field('Time locale');
}
if (!$date_format_full) {
$errors[] = no_field('Date format (full)');
}
if (!$date_format_date) {
$errors[] = no_field('Date format (date)');
}
if (!$date_format_time) {
$errors[] = no_field('Date format (time)');
}
if (count($errors) != 0) {
$request->attributes->set('errors', $errors);
// The form should be rebuild. Invoke appropriate action.
return $this->showEditFormAction($request);
}
$locale_info = get_locale_info($locale);
$locale_info['time_locale'] = $time_locale;
$locale_info['date_format'] = array(
'full' => $date_format_full,
'date' => $date_format_date,
'time' => $date_format_time,
);
// Save the locale
set_locale_info($locale, $locale_info);
// Redirect the user to edit page again to use GET method instead of
// POST.
$redirect_to = $this->generateUrl(
'locale_edit',
array(
'locale' => $locale,
'stored' => true,
)
);
return $this->redirect($redirect_to);
}
} }

View File

@ -714,26 +714,8 @@ class Installer
foreach ($locales as $locale_info) { foreach ($locales as $locale_info) {
$locale = $locale_info['code']; $locale = $locale_info['code'];
// Import localized messages // Import translations, formats, mail templates, ...
import_messages( import_locale_content($locale);
$locale,
MIBEW_FS_ROOT . '/locales/' . $locale . '/translation.po',
true
);
// Import canned messages
$canned_messages_file = MIBEW_FS_ROOT . '/locales/' . $locale
. '/canned_messages.yml';
if (is_readable($canned_messages_file)) {
import_canned_messages($locale, $canned_messages_file);
}
// Import mail templates
$mail_templates_file = MIBEW_FS_ROOT . '/locales/' . $locale
. '/mail_templates.yml';
if (is_readable($mail_templates_file)) {
MailUtils::importTemplates($locale, $mail_templates_file);
}
// Mark the locale as "enabled" to indicate that all its content // Mark the locale as "enabled" to indicate that all its content
// is imported. // is imported.

View File

@ -317,4 +317,80 @@ class Updater
return true; return true;
} }
/**
* Performs all database updates needed for 2.1.0.
*
* @return boolean True if the updates have been applied successfully and
* false otherwise.
*/
protected function update20100()
{
$db = $this->getDatabase();
if (!$db) {
return false;
}
// Alter locale table.
try {
$db->query('ALTER TABLE {locale} ADD COLUMN name varchar(128) NOT NULL DEFAULT "" AFTER code');
$db->query('ALTER TABLE {locale} ADD COLUMN rtl tinyint NOT NULL DEFAULT 0');
$db->query('ALTER TABLE {locale} ADD COLUMN time_locale varchar(128) NOT NULL DEFAULT "en_US"');
$db->query('ALTER TABLE {locale} ADD COLUMN date_format text');
$db->query('ALTER TABLE {locale} ADD UNIQUE KEY code (code)');
} catch (\Exception $e) {
$this->errors[] = getlocal('Cannot update tables: {0}', $e->getMessage());
return false;
}
try {
// Store configs for available locales in the database.
$locales = $db->query(
'SELECT localeid as id, code from {locale}',
null,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$locales_info = get_locales();
foreach ($locales as $row) {
$id = $row['id'];
$code = $row['code'];
$info = (isset($locales_info[$code]) ? $locales_info[$code] : array())
// Default info
+ array(
'name' => $code,
'rtl' => false,
'time_locale' => 'en_US',
'date_format' => array(
'full' => '%d %B %Y, %H:%M',
'date' => '%d %B %Y',
'time' => '%H:%M',
),
);
$db->query(
('UPDATE {locale} SET '
. 'name = :name, rtl = :rtl, time_locale = :time_locale, '
. 'date_format = :date_format '
. 'WHERE localeid = :id'),
array(
':id' => $id,
':name' => $info['name'],
':rtl' => $info['rtl'] ? 1 : 0,
':time_locale' => $info['time_locale'],
':date_format' => serialize($info['date_format']),
)
);
}
} catch (\Exception $e) {
$this->errors[] = getlocal('Cannot update content: {0}', $e->getMessage());
return false;
}
return true;
}
} }

View File

@ -20,6 +20,7 @@
use Mibew\Database; use Mibew\Database;
use Mibew\Mail\Utils as MailUtils; use Mibew\Mail\Utils as MailUtils;
use Symfony\Component\Translation\Loader\PoFileLoader; use Symfony\Component\Translation\Loader\PoFileLoader;
use Symfony\Component\Yaml\Parser as YamlParser;
/** /**
* Name for the cookie to store locale code in use * Name for the cookie to store locale code in use
@ -245,17 +246,11 @@ function get_locale_links()
/** /**
* Returns meta data for all known locales. * Returns meta data for all known locales.
* *
* This function is deprecated. Use {get_locale_info()} instead.
*
* @deprecated since 2.1.0
* @return array Associative arrays which keys are locale codes and the values * @return array Associative arrays which keys are locale codes and the values
* are locales info. Locale info itself is an associative array with the * are locales info.
* following keys:
* - name: string, human readable locale name.
* - rtl: boolean, indicates with the locale uses right-to-left
* writing mode.
* - time_locale: string, locale code which is used in {@link setlocale()}
* function to set the correct date/time formatting.
* - date_format: array, list of available date formats. Each key of the
* array is format name and each value is a format string for
* {@link strftime()} function.
*/ */
function get_locales() function get_locales()
{ {
@ -696,19 +691,132 @@ function get_locales()
/** /**
* Returns locale info by its code. * Returns locale info by its code.
* *
* It is a wrapper for {@link get_locales()} function and can be used to improve
* readability of the code.
*
* @param string $locale * @param string $locale
* @return array|false Associative array of locale info or boolean false if the * @return array|false Associative array of locale info or boolean false if the
* locale is unknown. See {@link get_locales()} description for details of the * locale is unknown. Locale info array contains the following keys:
* info array keys. * - name: string, human readable locale name.
* - rtl: boolean, indicates with the locale uses right-to-left
* writing mode.
* - time_locale: string, locale code which is used in {@link setlocale()}
* function to set the correct date/time formatting.
* - date_format: array, list of available date formats. Each key of the
* array is format name and each value is a format string for
* {@link strftime()} function.
*/ */
function get_locale_info($locale) function get_locale_info($locale)
{ {
$locales = get_locales(); $cache = get_locale_info_cache();
return isset($locales[$locale]) ? $locales[$locale] : false; if (!isset($cache[$locale])) {
if (get_maintenance_mode() === false) {
// Load local info from the database
$info = Database::getInstance()->query(
'SELECT * FROM {locale} WHERE code = :code',
array(':code' => $locale),
array('return_rows' => Database::RETURN_ONE_ROW)
);
$cache[$locale] = $info
? array(
'name' => $info['name'],
'rtl' => (bool)$info['rtl'],
'time_locale' => $info['time_locale'],
'date_format' => unserialize($info['date_format'])
)
: false;
} else {
// Either installation or update is performed. Try to get locale
// info from its config file.
$config_path = MIBEW_FS_ROOT . '/locales/' . $locale . '/config.yml';
$info = read_locale_config($config_path);
$cache[$locale] = $info
? $info + array(
'name' => $locale,
'rtl' => false,
'time_locale' => 'en_US',
'date_format' => array(
'full' => '%B %d, %Y %I:%M %p',
'date' => '%B %d, %Y',
'time' => '%I:%M %p',
),
)
: false;
}
}
return $cache[$locale];
}
/**
* Updates locale meta info.
*
* @param string $locale Code of the locale to update.
* @param array $info Associative array of locale's info. This array should
* contain the follwing keys:
* - "name"
* - "rtl"
* - "time_locale"
* - "date_format"
* See description of {@link get_locale_info()} function for keys meaning.
* @return boolean True if the info is updated and false otherwise.
* @throws \InvalidArgumentException If the $info array is invalid.
*/
function set_locale_info($locale, $info)
{
// Make sure $info array is correct
$missed_keys = array_diff(
array(
'name',
'rtl',
'time_locale',
'date_format'
),
array_keys($info)
);
if (count($missed_keys) > 0) {
throw new \InvalidArgumentException(sprintf(
'These fields are missed: "%s".',
implode('", "', $missed_keys)
));
}
$success = Database::getInstance()->query(
('UPDATE {locale} SET name = :name, rtl = :rtl, '
. 'time_locale = :time_locale, date_format = :date_format '
. 'WHERE code = :code'),
array(
':code' => $locale,
':name' => $info['name'],
':rtl' => $info['rtl'] ? 1 : 0,
':time_locale' => $info['time_locale'],
':date_format' => serialize($info['date_format'])
)
);
if (!$success) {
return false;
}
// Update the cache.
$cache = get_locale_info_cache();
$cache[$locale] = $info;
return true;
}
/**
* Retrieves locales info cache.
*
* @return array Locales info cached. It's stored as static variable inside the
* function.
*/
function &get_locale_info_cache()
{
static $cache = array();
return $cache;
} }
/** /**
@ -926,7 +1034,6 @@ function save_message($locale, $key, $value)
* Enables specified locale. * Enables specified locale.
* *
* @param string $locale Locale code according to RFC 5646. * @param string $locale Locale code according to RFC 5646.
* @todo Rewrite the function and move somewhere locale creation and its import.
*/ */
function enable_locale($locale) function enable_locale($locale)
{ {
@ -944,34 +1051,17 @@ function enable_locale($locale)
if ($count == 0) { if ($count == 0) {
// The locale does not exist in the database. Create it. // The locale does not exist in the database. Create it.
$db->query( Database::getInstance()->query(
"INSERT INTO {locale} (code, enabled) VALUES (:code, :enabled)", ('INSERT INTO {locale} (code, enabled) VALUES(:code, :enabled)'),
array( array(
':code' => $locale, ':code' => $locale,
':enabled' => 1, ':enabled' => 1,
) )
); );
// Import localized messages to the just created locale // Import all locale-related info (translations, mail, templates,
import_messages( // formats...) to databse.
$locale, import_locale_content($locale);
MIBEW_FS_ROOT . '/locales/' . $locale . '/translation.po',
true
);
// Import canned messages for the locale if they exist in the locale's
// files.
$canned_messages_file = MIBEW_FS_ROOT . '/locales/' . $locale . '/canned_messages.yml';
if (is_readable($canned_messages_file)) {
import_canned_messages($locale, $canned_messages_file);
}
// Import mail templates for the locale if they exist in the locale's
// files.
$mail_templates_file = MIBEW_FS_ROOT . '/locales/' . $locale . '/mail_templates.yml';
if (is_readable($mail_templates_file)) {
MailUtils::importTemplates($locale, $mail_templates_file);
}
} else { } else {
// The locale exists in the database. Update it. // The locale exists in the database. Update it.
$db->query( $db->query(
@ -999,3 +1089,80 @@ function disable_locale($locale)
) )
); );
} }
/**
* Imports all locale's content (messages, mail templates, configs) to database.
*
* This function does not create the locale in database so you have to create it
* by yourself.
*
* @param string $locale Code of the locale to import.
*/
function import_locale_content($locale)
{
$config = (read_locale_config(MIBEW_FS_ROOT . '/locales/' . $locale . '/config.yml') ?: array())
+ array(
'name' => $locale,
'rtl' => false,
'time_locale' => 'en_US',
'date_format' => array(
'full' => '%B %d, %Y %I:%M %p',
'date' => '%B %d, %Y',
'time' => '%I:%M %p',
),
);
Database::getInstance()->query(
('UPDATE {locale} SET '
. 'name = :name, rtl = :rtl, time_locale = :time_locale,'
. 'date_format = :date_format '
. 'WHERE code = :code'),
array(
':code' => $locale,
':name' => $config['name'],
':rtl' => $config['rtl'] ? 1 : 0,
':time_locale' => $config['time_locale'],
':date_format' => serialize($config['date_format'])
)
);
// Import localized messages to the just created locale
import_messages(
$locale,
MIBEW_FS_ROOT . '/locales/' . $locale . '/translation.po',
true
);
// Import canned messages for the locale if they exist in the locale's
// files.
$canned_messages_file = MIBEW_FS_ROOT . '/locales/' . $locale . '/canned_messages.yml';
if (is_readable($canned_messages_file)) {
import_canned_messages($locale, $canned_messages_file);
}
// Import mail templates for the locale if they exist in the locale's
// files.
$mail_templates_file = MIBEW_FS_ROOT . '/locales/' . $locale . '/mail_templates.yml';
if (is_readable($mail_templates_file)) {
MailUtils::importTemplates($locale, $mail_templates_file);
}
}
/**
* Reads locale's config files.
*
* @param string $path Path of the file to read.
* @return boolean|array Boolean false if the file is not found and associative
* configs array otherwise.
*/
function read_locale_config($path)
{
if (!is_readable($path)) {
return false;
}
$parser = new YamlParser();
$config = $parser->parse(file_get_contents($path));
return $config;
}

View File

@ -0,0 +1,11 @@
# This is human-readable name which will be used everywhere in UI.
name: English
# Indicates if the locale uses Right-to-Left writing.
rtl: false
# Locale name which will be passed into PHP's setlocale function.
time_locale: en_US
# Various formats which will be used with PHP's strftime function.
date_format:
full: "%B %d, %Y %I:%M %p"
date: "%B %d, %Y"
time: "%I:%M %p"

View File

@ -0,0 +1,84 @@
{{#extends "_layout"}}
{{#override "menu"}}{{> _menu}}{{/override}}
{{#override "content"}}
{{l10n "Edit locale settings."}}
<br />
<br />
{{> _errors}}
{{#if stored}}
<div id="form-message">{{l10n "Changes saved"}}</div>
{{/if}}
<form name="localeForm" method="post" action="{{formaction}}">
{{csrfTokenInput}}
<div>
{{> _tabs}}
<div class="form-wrapper">
<div class="form-header">
<div class="form-header-inwards"></div>
</div>
<div class="form-inwards">
<div class="form-fields">
<div class="field">
<label for="time-locale" class="field-label">{{l10n "Time locale"}}<span class="required">*</span></label>
<div class="field-value">
<input id="time-locale" type="text" name="timelocale" size="40" value="{{formtimelocale}}" class="field-input" />
</div>
<label for="time-locale" class="field-description"> &mdash; {{l10n "This value will be passed to PHP's setlocale function to localize words in date/time string"}}</label>
<br clear="all"/>
</div>
<div class="field">
<label for="date-format-full" class="field-label">{{l10n "Date format (full)"}}<span class="required">*</span></label>
<div class="field-value">
<input id="date-format-full" type="text" name="dateformatfull" size="40" value="{{formdateformatfull}}" class="field-input" />
</div>
<label for="date-format-full" class="field-description"> &mdash; {{l10n "This value will be used with PHP's strftime to format date with time."}}</label>
<br clear="all"/>
</div>
<div class="field">
<label for="date-format-date" class="field-label">{{l10n "Date format (date)"}}<span class="required">*</span></label>
<div class="field-value">
<input id="date-format-date" type="text" name="dateformatdate" size="40" value="{{formdateformatdate}}" class="field-input" />
</div>
<label for="date-format-date" class="field-description"> &mdash; {{l10n "This value will be used with PHP's strftime to format date only."}}</label>
<br clear="all"/>
</div>
<div class="field">
<label for="date-format-time" class="field-label">{{l10n "Date format (time)"}}<span class="required">*</span></label>
<div class="field-value">
<input id="date-format-time" type="text" name="dateformattime" size="40" value="{{formdateformattime}}" class="field-input" />
</div>
<label for="date-format-time" class="field-description"> &mdash; {{l10n "This value will be used with PHP's strftime to format time only."}}</label>
<br clear="all"/>
</div>
<div class="form-button">
<input type="submit" name="save" class="submit-button-background save-button" value="{{l10n "Save"}}"/>
</div>
</div>
</div>
<div class="form-footer">
<div class="form-footer-inwards"></div>
</div>
</div>
</div>
<div class="asterisk">
<span class="required">*</span> - {{l10n "mandatory fields"}}
</div>
</form>
{{/override}}
{{/extends}}

View File

@ -55,6 +55,10 @@
{{else}} {{else}}
<a href="{{csrfProtectedRoute "locale_disable" locale=code}}">{{l10n "disable"}}</a> <a href="{{csrfProtectedRoute "locale_disable" locale=code}}">{{l10n "disable"}}</a>
{{/if}} {{/if}}
{{#unless isDisabled}}
<a href="{{route "locale_edit" locale=code}}">{{l10n "edit"}}</a>
{{/unless}}
</td> </td>
</tr> </tr>
{{/each}} {{/each}}