vanilla_respondage/translations/sync_labels.php

194 lines
7.1 KiB
PHP
Raw Normal View History

<?php
/**
* Extract every translatable label of this theme from config.xml into a
* spreadsheet-friendly CSV (translations/labels.csv) and keep that CSV up to
* date during development.
*
* What is extracted (all of it is shown to the admin through gT() on the
* custom options page, so the English source string is the translation key):
* - every <options>/<key> title="..." (context "option <key>")
* - every distinct category="..." name (context "category")
* - every optionlabels="A|B|..." entry (context "option <key> optionlabel")
* - every dropdown <optgroup label="..."> (context "option <key> optgroup")
* - every dropdown <option> label text (context "option <key> dropdown option")
*
* Usage:
* php translations/sync_labels.php update labels.csv (merge, preserve translations)
* php translations/sync_labels.php --check exit 1 when labels.csv is stale (for dev/CI checks)
*
* CSV layout: context,key,source,<language columns...>
* The language columns are whatever the header row has after "source"
* (default: "nl"). Add a language by adding a column in a spreadsheet editor;
* existing translations are never overwritten, new strings are appended with
* empty translation cells, strings that disappeared from config.xml are removed
* (and reported). Rows are keyed by the source string, because gT() translates
* by message text.
*
* After editing translations in the CSV, generate the SQL for the LimeSurvey
* message tables with:
* php translations/csv_to_sql.php translations/labels.csv nl > nl.sql
* and run that SQL in the installation's database (see README "Multiple
* languages in the theme options (i18n)").
*/
if (PHP_SAPI !== 'cli') {
fwrite(STDERR, "This script must be run from the command line.\n");
exit(1);
}
$here = __DIR__;
$themeDir = dirname($here);
$configFile = $themeDir . DIRECTORY_SEPARATOR . 'config.xml';
$csvFile = $here . DIRECTORY_SEPARATOR . 'labels.csv';
$check = in_array('--check', $argv, true);
if (!is_file($configFile)) {
fwrite(STDERR, "config.xml not found: $configFile\n");
exit(1);
}
$doc = new DOMDocument();
if (!$doc->load($configFile)) {
fwrite(STDERR, "Could not parse $configFile\n");
exit(1);
}
$xpath = new DOMXPath($doc);
$strings = []; // source => [context, key] (first occurrence wins)
$add = function (string $context, string $key, string $source) use (&$strings) {
$source = trim($source);
if ($source === '' || isset($strings[$source])) {
return;
}
$strings[$source] = [$context, $key];
};
// categories
foreach ($xpath->query('//options/*[@category]') as $opt) {
$add('category', '(category name)', (string) $opt->getAttribute('category'));
}
// option titles + optionlabels + dropdown labels
foreach ($xpath->query('//options/*') as $opt) {
$key = $opt->nodeName;
$cat = $opt->getAttribute('category');
$ctx = $cat !== '' ? "option $key ($cat)" : "option $key";
if ($opt->hasAttribute('title')) {
$add($ctx, $key, (string) $opt->getAttribute('title'));
}
if ($opt->hasAttribute('optionlabels') && $opt->hasAttribute('options')) {
$labels = explode('|', (string) $opt->getAttribute('optionlabels'));
foreach ($labels as $label) {
$add("option $key optionlabel", $key, $label);
}
}
foreach ($xpath->query('./dropdownoptions/optgroup', $opt) as $og) {
if ($og->hasAttribute('label')) {
$add("option $key optgroup", $key, (string) $og->getAttribute('label'));
}
foreach ($xpath->query('./option', $og) as $o) {
$add("option $key dropdown option", $key, (string) $o->textContent);
}
}
}
// --- read existing CSV (if any) ---
$langs = ['nl']; // default language column
$rows = []; // source => [context, key, [lang => translation]]
if (is_file($csvFile)) {
$fh = fopen($csvFile, 'r');
$header = fgetcsv($fh);
if ($header === false || count($header) < 3 || $header[0] !== 'context' || $header[1] !== 'key' || $header[2] !== 'source') {
fwrite(STDERR, "Existing $csvFile has an unexpected header (expected context,key,source,...). Fix or remove it.\n");
exit(1);
}
$langs = array_slice($header, 3);
if (empty($langs)) {
$langs = ['nl'];
}
while (($r = fgetcsv($fh)) !== false) {
if (count($r) < 3 || $r[2] === '') {
continue;
}
$trans = [];
foreach ($langs as $i => $lang) {
$trans[$lang] = $r[3 + $i] ?? '';
}
$rows[$r[2]] = [$r[0], $r[1], $trans];
}
fclose($fh);
}
// --- merge: keep translations, append new strings, drop stale ones ---
$order = array_keys($rows); // preserve existing order
$new = 0;
foreach ($strings as $source => [$context, $key]) {
if (!isset($rows[$source])) {
$trans = array_fill_keys($langs, '');
$rows[$source] = [$context, $key, $trans];
$order[] = $source;
$new++;
} else {
// keep context/key up to date with config.xml
$rows[$source][0] = $context;
$rows[$source][1] = $key;
// a language column added later gets an empty cell
foreach ($langs as $lang) {
if (!array_key_exists($lang, $rows[$source][2])) {
$rows[$source][2][$lang] = '';
}
}
}
}
$removed = 0;
foreach (array_keys($rows) as $source) {
if (!isset($strings[$source])) {
unset($rows[$source]);
$order = array_values(array_diff($order, [$source]));
$removed++;
}
}
// --- serialize ---
$out = fopen('php://temp', 'r+');
fputcsv($out, array_merge(['context', 'key', 'source'], $langs));
foreach ($order as $source) {
[$context, $key, $trans] = $rows[$source];
fputcsv($out, array_merge([$context, $key, $source], array_map(fn($l) => $trans[$l] ?? '', $langs)));
}
rewind($out);
$csv = stream_get_contents($out);
fclose($out);
// normalize to LF line endings
$csv = str_replace("\r\n", "\n", $csv);
if ($check) {
$current = is_file($csvFile) ? str_replace("\r\n", "\n", file_get_contents($csvFile)) : '';
if ($current !== $csv) {
fwrite(STDERR, "STALE: $csvFile is not in sync with config.xml — run: php translations/sync_labels.php\n");
fwrite(STDERR, " ($new new string(s), $removed removed string(s), " . count($strings) . " strings total)\n");
exit(1);
}
echo "labels.csv in sync with config.xml (" . count($strings) . " strings, languages: " . implode(', ', $langs) . ")\n";
exit(0);
}
file_put_contents($csvFile, $csv);
$filled = [];
foreach ($langs as $lang) {
$n = 0;
foreach ($rows as $r) {
if (($r[2][$lang] ?? '') !== '') {
$n++;
}
}
$filled[$lang] = $n;
}
echo "Wrote $csvFile: " . count($strings) . " strings, languages: " . implode(', ', $langs) . "\n";
echo " new strings appended (empty translations): $new\n";
echo " strings removed from config.xml: $removed\n";
foreach ($filled as $lang => $n) {
echo " translated [$lang]: $n / " . count($strings) . "\n";
}
echo "Next: edit the translations in a spreadsheet editor (CSV), then generate SQL with:\n";
echo " php translations/csv_to_sql.php " . basename($csvFile) . " nl > nl.sql\n";