You are here

function _locale_parse_js_file in Drupal 6

Same name and namespace in other branches
  1. 8 core/modules/locale/locale.module \_locale_parse_js_file()
  2. 7 includes/locale.inc \_locale_parse_js_file()
  3. 9 core/modules/locale/locale.module \_locale_parse_js_file()
  4. 10 core/modules/locale/locale.module \_locale_parse_js_file()

Parses a JavaScript file, extracts strings wrapped in Drupal.t() and Drupal.formatPlural() and inserts them into the database.

1 string reference to '_locale_parse_js_file'
locale_update_js_files in modules/locale/locale.module
Update JavaScript translation file, if required, and add it to the page.

File

includes/locale.inc, line 1706
Administration functions for locale.module.

Code

function _locale_parse_js_file($filepath) {
  global $language;

  // Load the JavaScript file.
  $file = file_get_contents($filepath);

  // Match all calls to Drupal.t() in an array.
  // Note: \s also matches newlines with the 's' modifier.
  preg_match_all('~[^\\w]Drupal\\s*\\.\\s*t\\s*\\(\\s*(' . LOCALE_JS_STRING . ')\\s*[,\\)]~s', $file, $t_matches);

  // Match all Drupal.formatPlural() calls in another array.
  preg_match_all('~[^\\w]Drupal\\s*\\.\\s*formatPlural\\s*\\(\\s*.+?\\s*,\\s*(' . LOCALE_JS_STRING . ')\\s*,\\s*((?:(?:\'(?:\\\\\'|[^\'])*@count(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*@count(?:\\\\"|[^"])*")(?:\\s*\\+\\s*)?)+)\\s*[,\\)]~s', $file, $plural_matches);

  // Loop through all matches and process them.
  $all_matches = array_merge($plural_matches[1], $t_matches[1]);
  foreach ($all_matches as $key => $string) {
    $strings = array(
      $string,
    );

    // If there is also a plural version of this string, add it to the strings array.
    if (isset($plural_matches[2][$key])) {
      $strings[] = $plural_matches[2][$key];
    }
    foreach ($strings as $key => $string) {

      // Remove the quotes and string concatenations from the string.
      $string = implode('', preg_split('~(?<!\\\\)[\'"]\\s*\\+\\s*[\'"]~s', substr($string, 1, -1)));
      $result = db_query("SELECT lid, location FROM {locales_source} WHERE source = '%s' AND textgroup = 'default'", $string);
      if ($source = db_fetch_object($result)) {

        // We already have this source string and now have to add the location
        // to the location column, if this file is not yet present in there.
        $locations = preg_split('~\\s*;\\s*~', $source->location);
        if (!in_array($filepath, $locations)) {
          $locations[] = $filepath;
          $locations = implode('; ', $locations);

          // Save the new locations string to the database.
          db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $locations, $source->lid);
        }
      }
      else {

        // We don't have the source string yet, thus we insert it into the database.
        db_query("INSERT INTO {locales_source} (location, source, textgroup) VALUES ('%s', '%s', 'default')", $filepath, $string);
      }
    }
  }
}