diff --git a/.gitignore b/.gitignore index 5b8d09b..f3f0212 100644 --- a/.gitignore +++ b/.gitignore @@ -5,13 +5,16 @@ # internal notes and is deliberately NOT tracked, so it never reaches Forgejo. # --------------------------------------------------------------------------- -# variants/ — build & export tooling (build.php, export_public.sh) AND the -# confidential client definitions (*.json, leak-patterns.txt, README.internal.md). -# Local/private only. The canonical copies of the client variant definitions -# live in the private variants repository (vanilla_respondage_variants); point -# variants/build.php at that folder via its 2nd CLI argument or -# RESPONDAGE_VARIANTS_DIR. -/variants/ +# variants/ — only the confidential parts stay local: the client definitions +# (*.json), the leak patterns (client names/colors) and the dev tests. The +# generic tooling (build.php, export_public.sh — verified to contain no client +# data) IS tracked, so variants can be built from the public repo alone. The +# canonical client definitions live in the private variants repository +# (vanilla_respondage_variants); point variants/build.php at that folder via +# its 2nd CLI argument or RESPONDAGE_VARIANTS_DIR. +/variants/*.json +/variants/leak-patterns.txt +/variants/tests/ # sass/ sources are developer-only: they are compiled locally to css/plain.css # (which IS committed). LimeSurvey serves the committed css and never compiles diff --git a/variants/build.php b/variants/build.php new file mode 100644 index 0000000..aefda72 --- /dev/null +++ b/variants/build.php @@ -0,0 +1,277 @@ + in its config.xml). LimeSurvey then inherits ALL files + * (views, css, js, images, options page) from the mother theme, so any + * change made here in a file automatically applies to every variant. + * + * Only config.xml is generated per variant: it is a copy of this mother + * config.xml in which ONLY the house-style option values (colors, fonts, + * font sizes/colors/weights, logo files) listed in variants/.json + * are replaced, plus the metadata (name/title/description/extends). + * The section is emptied except , so engine settings + * (css framework, packages, view/files directories, template editor) are + * inherited from the mother. The section is kept as-is: LimeSurvey + * resolves each listed file in the variant first and then in the mother, + * so the mother's css/js keep loading until the variant ships its own file + * with the same name (which then replaces the mother's file). This mirrors + * what LimeSurvey itself does when you "extend" a theme in the theme editor. + * + * Usage: + * php variants/build.php [definitions-dir] + * + * The definitions (variants/.json) contain confidential client + * house-style values and are NOT kept in this (public) repository - see + * .gitignore. Store them in the private variants repository or locally, and + * point this script at that folder via the optional second argument or the + * RESPONDAGE_VARIANTS_DIR environment variable. + * + * Standard layout in that definitions dir per client: + * .json house-style option values + fontOptions + files_add + * /files/... client assets (logos, fonts in files/fonts/) + * /css/... client css (e.g. css/variant.css with @font-face) + * The / folder is copied into the generated theme automatically. + * + * Example: + * php variants/build.php /path/to/private-variants + * + * Optional keys in the variant json: + * "files_add": {"css": ["css/variant.css"], "js": []} extra files shipped by the + * variant, appended to the list of the generated config.xml + * "fontOptions": [{"value": "my_custom_font", "label": "My Custom Font"}] custom fonts, + * appended to the "Custom (this theme)" optgroup of the font dropdown + * + * Output: + * ..//config.xml (next to this theme, in upload/themes/survey) + * + * After running this script, upload the variant folder to + * upload/themes/survey/ and (re)install or reset the theme in LimeSurvey + * (Theme options -> reset), so the new config.xml is imported into the DB. + * + * If an option key in the json no longer exists in the mother config.xml, + * the script fails loudly, so drift between mother and variant is caught + * at build time instead of silently rendering wrong values. + */ + +if (PHP_SAPI !== 'cli') { + fwrite(STDERR, "This script must be run from the command line.\n"); + exit(1); +} + +$variantName = isset($argv[1]) ? trim($argv[1]) : ''; +if ($variantName === '' || !preg_match('/^[a-z0-9_]+$/i', $variantName)) { + fwrite(STDERR, "Usage: php variants/build.php [definitions-dir]\n"); + fwrite(STDERR, " must match an existing /.json file.\n"); + fwrite(STDERR, " Default definitions-dir: the variants/ folder next to this script, or RESPONDAGE_VARIANTS_DIR.\n"); + exit(1); +} + +$motherDir = dirname(__DIR__); // .../themes/survey/vanilla_respondage +$themesDir = dirname($motherDir); // .../themes/survey +$motherConfig = $motherDir . DIRECTORY_SEPARATOR . 'config.xml'; +$definitionsDir = $argv[2] ?? (getenv('RESPONDAGE_VARIANTS_DIR') ?: __DIR__); +$definitionFile = rtrim($definitionsDir, '/\\') . DIRECTORY_SEPARATOR . $variantName . '.json'; + +foreach ([$motherConfig, $definitionFile] as $f) { + if (!is_file($f)) { + fwrite(STDERR, "Required file not found: $f\n"); + exit(1); + } +} + +$definition = json_decode(file_get_contents($definitionFile), true); +if (!is_array($definition)) { + fwrite(STDERR, "Invalid JSON in $definitionFile\n"); + exit(1); +} + +$doc = new DOMDocument(); +$doc->preserveWhiteSpace = false; +$doc->formatOutput = true; +if (!$doc->load($motherConfig)) { + fwrite(STDERR, "Could not parse mother config: $motherConfig\n"); + exit(1); +} +$xpath = new DOMXPath($doc); + +$motherName = (string) $xpath->query('//metadata/name')->item(0)->textContent; + +// --- metadata: identify the variant, point extends to the mother theme --- +function setMetadata(DOMXPath $xpath, DOMDocument $doc, string $tag, string $value): void +{ + $node = $xpath->query("//metadata/$tag")->item(0); + if ($node === null) { + $node = $doc->createElement($tag); + $xpath->query('//metadata')->item(0)->appendChild($node); + } + $node->textContent = $value; +} + +/** Recursively copy a directory (used for the variant's own assets). */ +function copyDirRecursive(string $src, string $dst): void +{ + if (!is_dir($dst)) { + mkdir($dst, 0775, true); + } + $dir = opendir($src); + while (($entry = readdir($dir)) !== false) { + if ($entry === '.' || $entry === '..') { + continue; + } + $s = $src . DIRECTORY_SEPARATOR . $entry; + $d = $dst . DIRECTORY_SEPARATOR . $entry; + if (is_dir($s)) { + copyDirRecursive($s, $d); + } else { + copy($s, $d); + } + } + closedir($dir); +} + +setMetadata($xpath, $doc, 'name', $definition['name'] ?? $variantName); +setMetadata($xpath, $doc, 'title', $definition['title'] ?? ucfirst($variantName)); +if (isset($definition['description'])) { + setMetadata($xpath, $doc, 'description', $definition['description']); +} +setMetadata($xpath, $doc, 'extends', $motherName); +setMetadata($xpath, $doc, 'lastUpdate', date('Y-m-d H:i:s')); + +// --- empty the section except : inherited from the mother --- +// (same as TemplateManifest::deleteEngineInDom() does when extending a theme in LimeSurvey) +$engineNode = $xpath->query('//engine')->item(0); +if ($engineNode !== null) { + foreach (iterator_to_array($engineNode->childNodes) as $child) { + if ($child instanceof DOMElement && $child->nodeName !== 'optionspage') { + $engineNode->removeChild($child); + } elseif ($child instanceof DOMComment) { + $engineNode->removeChild($child); + } + } +} + +// --- extra files shipped by the variant itself --- +// In the variant json: "files_add": {"css": ["css/variant.css"], "js": []} +// They are appended to the list. The mother's files keep loading until the +// variant ships a file with the same name; from that moment it replaces the mother's +// file (LimeSurvey "add" also means "replace" for identical paths). +if (!empty($definition['files_add'])) { + $filesNode = $xpath->query('//files')->item(0); + if ($filesNode === null) { + fwrite(STDERR, "No section found in mother config\n"); + exit(1); + } + foreach (['css', 'js', 'print_css'] as $type) { + $values = $definition['files_add'][$type] ?? []; + if (empty($values)) { + continue; + } + $typeNode = $xpath->query('//files/' . $type)->item(0); + if ($typeNode === null) { + $typeNode = $doc->createElement($type); + $filesNode->appendChild($typeNode); + } + foreach ((array) $values as $file) { + $add = $doc->createElement('add'); + $add->appendChild($doc->createTextNode((string) $file)); + $typeNode->appendChild($add); + } + } +} + +// --- custom fonts of the variant, added to the font dropdown --- +// In the variant json: "fontOptions": [{"value": "my_custom_font", "label": "My Custom Font"}] +// The font files themselves live in the variant's files/fonts/ and the @font-face + +// GENERIC .font- rule (not body-scoped, so the per-element font overrides +// work too) in a css file shipped by the variant (see files_add, e.g. +// css/variant.css with src: url('../files/fonts/my-custom-font.woff2')). +// data-font-package stays "websafe": LimeSurvey only knows the core font packages +// (application/config/fonts.php), and "websafe" is the neutral one, so no missing +// package is requested. The real font is loaded by the variant's own css. +if (!empty($definition['fontOptions'])) { + $optgroup = $xpath->query('//options/font/dropdownoptions/optgroup[@label="Custom (this theme)"]')->item(0); + if ($optgroup === null) { + fwrite(STDERR, "No found in the font dropdown of the mother config.xml\n"); + exit(1); + } + foreach ((array) $definition['fontOptions'] as $font) { + if (empty($font['value']) || empty($font['label'])) { + fwrite(STDERR, "Each entry in 'fontOptions' needs 'value' and 'label'\n"); + exit(1); + } + $value = preg_replace('/[^a-z0-9_]/i', '_', (string) $font['value']); + $option = $doc->createElement('option'); + $option->setAttribute('class', 'font-' . $value); + $option->setAttribute('value', $value); + $option->setAttribute('data-font-package', 'websafe'); + $option->appendChild($doc->createTextNode((string) $font['label'])); + $optgroup->appendChild($option); + } +} + +// --- options: replace only the house-style values listed in the json --- +if (!empty($definition['options']) && !is_array($definition['options'])) { + fwrite(STDERR, "'options' in $definitionFile must be an object of optionName => value\n"); + exit(1); +} +// A variant that ships its own font(s) via fontOptions gets the first custom font as +// the DEFAULT value of the "font" option (so it is pre-selected in the options page +// dropdown), unless the json sets options.font explicitly. +if (!empty($definition['fontOptions']) + && (empty($definition['options']) || !isset($definition['options']['font']))) { + $definition['options']['font'] = preg_replace('/[^a-z0-9_]/i', '_', (string) $definition['fontOptions'][0]['value']); +} +$optionsNode = $xpath->query('//options')->item(0); +if ($optionsNode === null) { + fwrite(STDERR, "No section found in mother config\n"); + exit(1); +} +foreach (($definition['options'] ?? []) as $key => $value) { + $matches = $xpath->query('//options/' . $key); + if ($matches->length === 0) { + fwrite(STDERR, "Option '$key' from $definitionFile does not exist in the mother config.xml.\n"); + fwrite(STDERR, "Remove it from the json or rename it there; the mother theme changed.\n"); + exit(1); + } + $option = $matches->item(0); + // Replace only the text value, keep child elements (e.g. of the font option) + foreach (iterator_to_array($option->childNodes) as $child) { + if ($child instanceof DOMText) { + $option->removeChild($child); + } + } + $option->insertBefore($doc->createTextNode((string) $value), $option->firstChild); +} + +// --- write the variant config --- +$variantDir = $themesDir . DIRECTORY_SEPARATOR . $variantName; +if (!is_dir($variantDir) && !mkdir($variantDir, 0775, true)) { + fwrite(STDERR, "Could not create directory: $variantDir\n"); + exit(1); +} +if (!is_dir($variantDir . DIRECTORY_SEPARATOR . 'files')) { + mkdir($variantDir . DIRECTORY_SEPARATOR . 'files', 0775, true); +} +$out = $variantDir . DIRECTORY_SEPARATOR . 'config.xml'; +$doc->save($out); + +// --- copy the variant's own assets (fonts, css, images) from the definitions dir --- +// Standard layout in the private variants repo: // +// with e.g. files/fonts/*.woff2, files/*.png, css/variant.css. Everything in that +// folder is copied into the generated theme, so a client-specific font or css is +// part of the variant by default (no manual copying needed). +$variantAssets = rtrim($definitionsDir, '/\\') . DIRECTORY_SEPARATOR . $variantName; +if (is_dir($variantAssets)) { + copyDirRecursive($variantAssets, $variantDir); + echo "Copied variant assets: $variantAssets -> $variantDir\n"; +} + +echo "Variant '$variantName' built: $out\n"; +echo 'Options overridden: ' . (empty($definition['options']) ? '(none)' : implode(', ', array_keys($definition['options']))) . "\n"; +echo "Note: existing files in $variantDir were OVERWRITTEN from the definitions dir.\n"; +echo "REBUILD RULE: re-run this build after EVERY change to $variantName.json or to the\n"; +echo " /$variantName/ assets — a variant folder that is not rebuilt after\n"; +echo " a definitions change is stale (fonts/logo/css then don't match the definitions).\n"; +echo "Remember: upload the folder to upload/themes/survey/ and reset the theme in LimeSurvey.\n"; diff --git a/variants/export_public.sh b/variants/export_public.sh new file mode 100644 index 0000000..d3b789f --- /dev/null +++ b/variants/export_public.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# +# Build a PUBLIC release of the mother theme (vanilla_respondage) only. +# +# Client data (variant definitions variants/*.json, generated client theme +# folders, git branches containing a client theme) must NEVER be published. +# This script therefore: +# 1. copies ONLY the runtime files of the theme plus the generic variant +# tooling (variants/build.php, variants/export_public.sh) — the same set +# that the public repo tracks (see .gitignore): everything except .git, +# the confidential variants/ parts (*.json, leak-patterns.txt, tests/), +# sass/, css/*.map, dist/, AGENTS.md, prompts.md, FEATURE_REQUEST*.md, +# BUG_REPORT*.md, .vibe/, node_modules/ and package files; +# 2. scans the staged copy for client-identifying strings and ABORTS if any +# are found; +# 3. creates a zip next to the folder. +# +# NOTE: this script itself is tracked (variants/build.php and this file are the +# only tracked files under variants/ — see .gitignore); the public repo +# (Forgejo) contains runtime files + this tooling, so pushing that repo is +# already a valid public release. +# +# Usage: +# bash variants/export_public.sh [output-dir] +# +# Default output dir: /dist (deliberately NOT inside +# upload/themes/survey/, because every folder there is scanned as a theme). +# +set -euo pipefail + +THEME_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MOTHER_NAME="$(basename "$THEME_DIR")" +SITE_ROOT="$(cd "$THEME_DIR/../../../.." && pwd)" +OUT_DIR="${1:-$SITE_ROOT/dist}" +STAGE="$OUT_DIR/$MOTHER_NAME" +VERSION="$(sed -n 's:.*\([^<]*\).*:\1:p' "$THEME_DIR/config.xml" | head -1)" +ZIP_NAME="${MOTHER_NAME}-${VERSION}-public.zip" + +# 0. optional guard: css/plain.css must be in sync with sass/plain.sass. +# LimeSurvey serves the committed css/plain.css and NEVER compiles sass +# itself, so a stale compiled file would be shipped/served. If a sass +# compiler is on PATH AND the developer-local sass/ sources are present +# (sass/ is gitignored and NOT part of this repo), recompile to a temp +# file and compare; abort on drift. +if command -v sass >/dev/null 2>&1 && [ -f "$THEME_DIR/sass/plain.sass" ]; then + TMP_CSS="$(mktemp --suffix=.css)" + if sass --no-source-map "$THEME_DIR/sass/plain.sass" "$TMP_CSS" 2>/dev/null; then + # -B ignores blank-line-only changes (dart-sass adds one before the + # sourceMappingURL comment); strip that comment line: it contains the + # output file name and differs between the real and the temp output + if ! diff -qB <(sed '/sourceMappingURL/d' "$THEME_DIR/css/plain.css") <(sed '/sourceMappingURL/d' "$TMP_CSS") >/dev/null 2>&1; then + echo "ERROR: css/plain.css is stale relative to sass/plain.sass - aborting." >&2 + echo " Recompile in the theme dir, e.g.: sass sass/plain.sass css/plain.css" >&2 + echo " (a watcher like 'sass --watch sass/plain.sass css/plain.css' prevents this)" >&2 + echo " Commit the recompiled css/plain.css (the .map stays local, gitignored); sass/ is developer-local and not committed." >&2 + rm -f "$TMP_CSS" + exit 1 + fi + fi + rm -f "$TMP_CSS" +else + echo "NOTE: 'sass' binary or local sass/ sources not present - skipped the css/plain.css sync check (sass/ is developer-local, gitignored)." >&2 +fi + +rm -rf "$STAGE" +mkdir -p "$STAGE" "$OUT_DIR" + +# 1. copy the theme, excluding exactly the local-only/confidential files listed +# in .gitignore (the public repo tracks the remaining files; the generic +# variants/ tooling build.php + export_public.sh IS included, the client +# definitions *.json, leak-patterns.txt and tests/ are NOT) +(cd "$THEME_DIR" && tar --exclude='./.git' --exclude='./dist' --exclude='./variants/*.json' --exclude='./variants/leak-patterns.txt' --exclude='./variants/tests' --exclude='./sass' --exclude='./css/*.map' --exclude='./FEATURE_REQUEST*.md' --exclude='./BUG_REPORT*.md' --exclude='./AGENTS.md' --exclude='./prompts.md' --exclude='./.vibe' --exclude='./node_modules' --exclude='./package.json' --exclude='./package-lock.json' --exclude='./tmp' -cf - .) | (cd "$STAGE" && tar -xf -) + +# 2. leak check: no client-identifying strings may remain (text files only). +# Client names are NOT hardcoded in this public file. Patterns are derived: +# - the names of sibling variant theme folders (../respondage_ next to +# this theme, excluding this theme itself); +# - extra patterns (names, terms, hex colors) from variants/leak-patterns.txt, +# one regex per line. That file is gitignored here and lives in the PRIVATE +# variants repository (vanilla_respondage_variants). +PATTERNS="" +for d in "$THEME_DIR"/../respondage_*; do + [ -d "$d" ] || continue + name="$(basename "$d")" + [ "$name" = "$MOTHER_NAME" ] && continue + PATTERNS="$PATTERNS|$name" +done +if [ -f "$THEME_DIR/variants/leak-patterns.txt" ]; then + while IFS= read -r line; do + case "$line" in ''|\#*) continue ;; esac + PATTERNS="$PATTERNS|$line" + done < "$THEME_DIR/variants/leak-patterns.txt" +fi +PATTERNS="${PATTERNS#|}" +if [ -n "$PATTERNS" ] && grep -rIlE "$PATTERNS" "$STAGE"; then + echo "ERROR: client-identifying strings found in the public export - aborting, staging removed." >&2 + echo "(patterns came from sibling respondage_* folders and variants/leak-patterns.txt)" >&2 + rm -rf "$STAGE" + exit 1 +fi + +# 2b. PRIVACY check: during survey-taking this theme must NEVER make external +# requests (no calls to Google or any other external host). Scan all staged +# text files for http(s) URLs and abort if the host is not on the allowlist +# below. The allowlist contains only hosts that appear in comments/links +# (license texts, docs, the respondage.nl footer link) and that are never +# requested as resources. This automatically blocks googleapis.com, +# gstatic.com, fonts.google.com, cdnfonts.com, jsdelivr.net, unpkg.com, etc. +ALLOWED_HOSTS='www\.respondage\.nl|respondage\.nl|github\.com|raw\.githubusercontent\.com|scripts\.sil\.org|openfontlicense\.org|open-foundry\.com|getbootstrap\.com|bootswatch\.com|twig\.sensiolabs\.org|www\.yiiframework\.com|learn\.jquery\.com|limesurvey\.org|www\.limesurvey\.org|bugs\.limesurvey\.org|www\.w3\.org' +EXTERNAL="$(grep -rIhoE 'https?://[a-zA-Z0-9.-]+' "$STAGE" --include='*.css' --include='*.twig' --include='*.js' --include='*.xml' --include='*.json' --include='*.md' --include='*.php' --include='*.sh' --include='*.txt' --include='*.html' 2>/dev/null \ + | sed -E 's|https?://([a-zA-Z0-9.-]+).*|\1|; s|\.+$||' | sort -u \ + | grep -vE "^(${ALLOWED_HOSTS})$" || true)" +if [ -n "$EXTERNAL" ]; then + echo "ERROR: external host(s) referenced in the theme - aborting, staging removed." >&2 + echo "During survey-taking no external calls are allowed (privacy). Found:" >&2 + echo "$EXTERNAL" | sed 's/^/ - /' >&2 + rm -rf "$STAGE" + exit 1 +fi + +# 3. zip it +(cd "$OUT_DIR" && rm -f "$ZIP_NAME" && zip -qr "$ZIP_NAME" "$MOTHER_NAME") + +echo "Public release created:" +echo " folder: $STAGE" +echo " zip: $OUT_DIR/$ZIP_NAME" +echo +echo "Publish ONLY this artifact (or the main branch of this repo)." +echo "NEVER publish variants/*.json, generated client theme folders, or a git" +echo "branch that contains a client theme - client names, colors and logos are confidential."