From 1bfbb5c243b5039e6accff72f9a57f6eda35bb02 Mon Sep 17 00:00:00 2001 From: Dmitriy Simushev Date: Tue, 8 Jul 2014 11:01:30 +0000 Subject: [PATCH] Add canned messages import --- src/mibew/libs/canned.php | 45 ++++++++++++++++++++++++++++++-- src/mibew/libs/common/locale.php | 10 +++++-- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/src/mibew/libs/canned.php b/src/mibew/libs/canned.php index 3fa0aae1..73a90225 100644 --- a/src/mibew/libs/canned.php +++ b/src/mibew/libs/canned.php @@ -15,7 +15,7 @@ * limitations under the License. */ -// Import namespaces and classes of the core +use Symfony\Component\Yaml\Parser as YamlParser; use Mibew\Database; /** @@ -97,9 +97,50 @@ function add_canned_message($locale, $group_id, $title, $message) . "VALUES (?, ?, ?, ?)"), array( $locale, - ($group_id ? $group_id : "null"), + ($group_id ? $group_id : null), $title, $message, ) ); } + +/** + * Import canned messages from a YAML file. + * + * @param string $locale Locale code. + * @param string $file Full path to the file that should be imported. + */ +function import_canned_messages($locale, $file) +{ + // Get new canned messages that should be imported. + $parser = new YamlParser(); + $new_messages = $parser->parse(file_get_contents($file)); + if (empty($new_messages)) { + // Nothing to import. + return; + } + + // Get list of existing canned messages for specified locale an key it by + // message value. + $loaded_messages = load_canned_messages($locale, false); + $existing_messages = array(); + if (!empty($loaded_messages)) { + foreach ($loaded_messages as $message) { + $existing_messages[$message['vcvalue']] = $message; + } + } + + // Save only new messages to avoid duplication + foreach ($new_messages as $message) { + if (array_key_exists($message, $existing_messages)) { + continue; + } + + add_canned_message( + $locale, + null, + cut_string($message, 97, '...'), + $message + ); + } +} diff --git a/src/mibew/libs/common/locale.php b/src/mibew/libs/common/locale.php index 1927008d..a5aa2ce8 100644 --- a/src/mibew/libs/common/locale.php +++ b/src/mibew/libs/common/locale.php @@ -730,7 +730,6 @@ function import_messages($locale, $file, $override = false) } } - /** * Read and parse locale file. * @@ -894,12 +893,19 @@ function enable_locale($locale) ) ); - // Import localized messages to just created locale + // 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); + } } else { // The locale exists in the database. Update it. $db->query(