message_bundle.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "extensions/common/message_bundle.h"
  5. #include <memory>
  6. #include <string>
  7. #include <vector>
  8. #include "base/containers/adapters.h"
  9. #include "base/containers/contains.h"
  10. #include "base/i18n/rtl.h"
  11. #include "base/lazy_instance.h"
  12. #include "base/strings/string_util.h"
  13. #include "base/strings/stringprintf.h"
  14. #include "base/strings/utf_string_conversions.h"
  15. #include "base/values.h"
  16. #include "extensions/common/error_utils.h"
  17. #include "extensions/common/extension_l10n_util.h"
  18. #include "extensions/common/manifest_constants.h"
  19. namespace extensions {
  20. namespace errors = manifest_errors;
  21. const char MessageBundle::kContentKey[] = "content";
  22. const char MessageBundle::kMessageKey[] = "message";
  23. const char MessageBundle::kPlaceholdersKey[] = "placeholders";
  24. const char MessageBundle::kPlaceholderBegin[] = "$";
  25. const char MessageBundle::kPlaceholderEnd[] = "$";
  26. const char MessageBundle::kMessageBegin[] = "__MSG_";
  27. const char MessageBundle::kMessageEnd[] = "__";
  28. // Reserved messages names.
  29. const char MessageBundle::kUILocaleKey[] = "@@ui_locale";
  30. const char MessageBundle::kBidiDirectionKey[] = "@@bidi_dir";
  31. const char MessageBundle::kBidiReversedDirectionKey[] = "@@bidi_reversed_dir";
  32. const char MessageBundle::kBidiStartEdgeKey[] = "@@bidi_start_edge";
  33. const char MessageBundle::kBidiEndEdgeKey[] = "@@bidi_end_edge";
  34. const char MessageBundle::kExtensionIdKey[] = "@@extension_id";
  35. // Reserved messages values.
  36. const char MessageBundle::kBidiLeftEdgeValue[] = "left";
  37. const char MessageBundle::kBidiRightEdgeValue[] = "right";
  38. // Formats message in case we encounter a bad formed key in the JSON object.
  39. // Returns false and sets |error| to actual error message.
  40. static bool BadKeyMessage(const std::string& name, std::string* error) {
  41. *error = base::StringPrintf(
  42. "Name of a key \"%s\" is invalid. Only ASCII [a-z], "
  43. "[A-Z], [0-9] and \"_\" are allowed.",
  44. name.c_str());
  45. return false;
  46. }
  47. // static
  48. MessageBundle* MessageBundle::Create(const CatalogVector& locale_catalogs,
  49. std::string* error) {
  50. std::unique_ptr<MessageBundle> message_bundle(new MessageBundle);
  51. if (!message_bundle->Init(locale_catalogs, error))
  52. return NULL;
  53. return message_bundle.release();
  54. }
  55. bool MessageBundle::Init(const CatalogVector& locale_catalogs,
  56. std::string* error) {
  57. dictionary_.clear();
  58. for (const auto& catalog : base::Reversed(locale_catalogs)) {
  59. for (base::DictionaryValue::Iterator message_it(*catalog);
  60. !message_it.IsAtEnd(); message_it.Advance()) {
  61. std::string key(base::ToLowerASCII(message_it.key()));
  62. if (!IsValidName(message_it.key()))
  63. return BadKeyMessage(key, error);
  64. std::string value;
  65. if (!GetMessageValue(message_it.key(), message_it.value(), &value, error))
  66. return false;
  67. // Keys are not case-sensitive.
  68. dictionary_[key] = value;
  69. }
  70. }
  71. if (!AppendReservedMessagesForLocale(
  72. extension_l10n_util::CurrentLocaleOrDefault(), error))
  73. return false;
  74. return true;
  75. }
  76. bool MessageBundle::AppendReservedMessagesForLocale(
  77. const std::string& app_locale, std::string* error) {
  78. SubstitutionMap append_messages;
  79. append_messages[kUILocaleKey] = app_locale;
  80. // Calling base::i18n::GetTextDirection on non-UI threads doesn't seems safe,
  81. // so we use GetTextDirectionForLocale instead.
  82. if (base::i18n::GetTextDirectionForLocale(app_locale.c_str()) ==
  83. base::i18n::RIGHT_TO_LEFT) {
  84. append_messages[kBidiDirectionKey] = "rtl";
  85. append_messages[kBidiReversedDirectionKey] = "ltr";
  86. append_messages[kBidiStartEdgeKey] = kBidiRightEdgeValue;
  87. append_messages[kBidiEndEdgeKey] = kBidiLeftEdgeValue;
  88. } else {
  89. append_messages[kBidiDirectionKey] = "ltr";
  90. append_messages[kBidiReversedDirectionKey] = "rtl";
  91. append_messages[kBidiStartEdgeKey] = kBidiLeftEdgeValue;
  92. append_messages[kBidiEndEdgeKey] = kBidiRightEdgeValue;
  93. }
  94. // Add all reserved messages to the dictionary, but check for collisions.
  95. auto it = append_messages.begin();
  96. for (; it != append_messages.end(); ++it) {
  97. if (base::Contains(dictionary_, it->first)) {
  98. *error = ErrorUtils::FormatErrorMessage(
  99. errors::kReservedMessageFound, it->first);
  100. return false;
  101. } else {
  102. dictionary_[it->first] = it->second;
  103. }
  104. }
  105. return true;
  106. }
  107. bool MessageBundle::GetMessageValue(const std::string& key,
  108. const base::Value& name_value,
  109. std::string* value,
  110. std::string* error) const {
  111. // Get the top level tree for given key (name part).
  112. const base::DictionaryValue* name_tree;
  113. if (!name_value.GetAsDictionary(&name_tree)) {
  114. *error = base::StringPrintf("Not a valid tree for key %s.", key.c_str());
  115. return false;
  116. }
  117. // Extract message from it.
  118. if (!name_tree->GetString(kMessageKey, value)) {
  119. *error = base::StringPrintf(
  120. "There is no \"%s\" element for key %s.", kMessageKey, key.c_str());
  121. return false;
  122. }
  123. SubstitutionMap placeholders;
  124. if (!GetPlaceholders(*name_tree, key, &placeholders, error))
  125. return false;
  126. if (!ReplacePlaceholders(placeholders, value, error))
  127. return false;
  128. return true;
  129. }
  130. MessageBundle::MessageBundle() {
  131. }
  132. bool MessageBundle::GetPlaceholders(const base::DictionaryValue& name_tree,
  133. const std::string& name_key,
  134. SubstitutionMap* placeholders,
  135. std::string* error) const {
  136. if (!name_tree.FindKey(kPlaceholdersKey))
  137. return true;
  138. const base::DictionaryValue* placeholders_tree;
  139. if (!name_tree.GetDictionary(kPlaceholdersKey, &placeholders_tree)) {
  140. *error = base::StringPrintf("Not a valid \"%s\" element for key %s.",
  141. kPlaceholdersKey, name_key.c_str());
  142. return false;
  143. }
  144. for (base::DictionaryValue::Iterator it(*placeholders_tree); !it.IsAtEnd();
  145. it.Advance()) {
  146. const base::DictionaryValue* placeholder;
  147. const std::string& content_key(it.key());
  148. if (!IsValidName(content_key))
  149. return BadKeyMessage(content_key, error);
  150. if (!it.value().GetAsDictionary(&placeholder)) {
  151. *error = base::StringPrintf("Invalid placeholder %s for key %s",
  152. content_key.c_str(),
  153. name_key.c_str());
  154. return false;
  155. }
  156. std::string content;
  157. if (!placeholder->GetString(kContentKey, &content)) {
  158. *error = base::StringPrintf("Invalid \"%s\" element for key %s.",
  159. kContentKey, name_key.c_str());
  160. return false;
  161. }
  162. (*placeholders)[base::ToLowerASCII(content_key)] = content;
  163. }
  164. return true;
  165. }
  166. bool MessageBundle::ReplacePlaceholders(const SubstitutionMap& placeholders,
  167. std::string* message,
  168. std::string* error) const {
  169. return ReplaceVariables(placeholders,
  170. kPlaceholderBegin,
  171. kPlaceholderEnd,
  172. message,
  173. error);
  174. }
  175. bool MessageBundle::ReplaceMessages(std::string* text,
  176. std::string* error) const {
  177. return ReplaceMessagesWithExternalDictionary(dictionary_, text, error);
  178. }
  179. MessageBundle::~MessageBundle() {
  180. }
  181. // static
  182. bool MessageBundle::ReplaceMessagesWithExternalDictionary(
  183. const SubstitutionMap& dictionary, std::string* text, std::string* error) {
  184. return ReplaceVariables(dictionary, kMessageBegin, kMessageEnd, text, error);
  185. }
  186. // static
  187. bool MessageBundle::ReplaceVariables(const SubstitutionMap& variables,
  188. const std::string& var_begin_delimiter,
  189. const std::string& var_end_delimiter,
  190. std::string* message,
  191. std::string* error) {
  192. std::string::size_type beg_index = 0;
  193. const std::string::size_type var_begin_delimiter_size =
  194. var_begin_delimiter.size();
  195. while (true) {
  196. beg_index = message->find(var_begin_delimiter, beg_index);
  197. if (beg_index == message->npos)
  198. return true;
  199. // Advance it immediately to the begining of possible variable name.
  200. beg_index += var_begin_delimiter_size;
  201. if (beg_index >= message->size())
  202. return true;
  203. std::string::size_type end_index =
  204. message->find(var_end_delimiter, beg_index);
  205. if (end_index == message->npos)
  206. return true;
  207. // Looking for 1 in substring of ...$1$....
  208. const std::string& var_name =
  209. message->substr(beg_index, end_index - beg_index);
  210. if (!IsValidName(var_name))
  211. continue;
  212. auto it = variables.find(base::ToLowerASCII(var_name));
  213. if (it == variables.end()) {
  214. *error = base::StringPrintf("Variable %s%s%s used but not defined.",
  215. var_begin_delimiter.c_str(),
  216. var_name.c_str(),
  217. var_end_delimiter.c_str());
  218. return false;
  219. }
  220. // Replace variable with its value.
  221. std::string value = it->second;
  222. message->replace(beg_index - var_begin_delimiter_size,
  223. end_index - beg_index + var_begin_delimiter_size +
  224. var_end_delimiter.size(),
  225. value);
  226. // And position pointer to after the replacement.
  227. beg_index += value.size() - var_begin_delimiter_size;
  228. }
  229. }
  230. // static
  231. bool MessageBundle::IsValidName(const std::string& name) {
  232. if (name.empty())
  233. return false;
  234. std::string::const_iterator it = name.begin();
  235. for (; it != name.end(); ++it) {
  236. // Allow only ascii 0-9, a-z, A-Z, and _ in the name.
  237. if (!base::IsAsciiAlpha(*it) && !base::IsAsciiDigit(*it) && *it != '_' &&
  238. *it != '@')
  239. return false;
  240. }
  241. return true;
  242. }
  243. // Dictionary interface.
  244. std::string MessageBundle::GetL10nMessage(const std::string& name) const {
  245. return GetL10nMessage(name, dictionary_);
  246. }
  247. // static
  248. std::string MessageBundle::GetL10nMessage(const std::string& name,
  249. const SubstitutionMap& dictionary) {
  250. auto it = dictionary.find(base::ToLowerASCII(name));
  251. if (it != dictionary.end()) {
  252. return it->second;
  253. }
  254. return std::string();
  255. }
  256. } // namespace extensions