Free DNS provides easy shared DNS hosting & URL forwarding

Sunday, February 14, 2010

Automatic translation for Moodle UI strings with Google Translation API

Today I installed a fresh copy of Moodle 1.9. I'm reviewing it in order to upgrade our university's site (from Moodle 1.8) and another site (using Moodle 1.6). As always, I started going through all it's settings, looking for new features or things that changed. When I reached the Language section, I installed the Romanian language, just to make sure installation is working. However, I noticed that the Romanian language pack is missing 26.7% of strings (2672 to be more precise). Some translated string are also a bit weird.
I remembered that about two years ago, I patched Drupal in order to get automatic translation using Google Translate. At that time, Google translate did not provide any web services API, nor AJAX, and the translation of text containing HTML tags was very poor. The patch was doing simple HTTP requests, parsing of the HTTP response, some simple cleanup and in the end, it stored the translation into the Drupal locale messages.
Google Translate nowadays has much more languages than it used to backthen is AJAX based and offers web services, too. I was wondering how does it handle HTML tags and how hard would be to get it into the Moodle language editor. After 2 hours of coding and reading its API, I came up with this (sorry for JQuery, I know Moodle likes YUI):
$translang = preg_replace('/_.*/', '', $currentlang);
echo '
<script type="text/javascript" src=""></script>
<script type="text/javascript">
  google.load("language", "1")
  google.load("jquery", "1.4.1")
<script type="text/javascript">
  $(document).ready(function() {
    $("form .translator .stren").click(function() {
      var src = $(this);
      var dst = $("[name=\'stringXXX" + + "\']")
      var tokens = [];
      var text = src.text().replace(/\$a(->\w*)?/g, function(match) {
        return "TK" + (tokens.push(match)-1);
      google.language.translate(text, "en", "' . $translang .'", function(result) {
        if (!result.error) {
          dst.text(result.translation.replace(/TK\d+/g, function(match) {
            return tokens[match.substring(2)];
          })).css("background-color", "yellow")
This will allow a translator to click on any string in the Language editing section and get a Google translation for that string. The translation is saved in the corresponding textarea (which is marked with yellow). You can then check, edit, undo, or save these changes.