Search by

clesson-de / silverstripe-qr-code

clesson-de

A public React QR code generator with SVG/PNG downloads, a page type and optional Elemental integration.

Package info

github.com/clesson-de/silverstripe-qr-code

Type:silverstripe-vendormodule

pkg:composer/clesson-de/silverstripe-qr-code

Statistics

Installs: 7

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.2.2 2026-11-28 15:34 UTC

This package is not auto-updated.

Last update: 2026-11-28 15:35:32 UTC


README

A QR code module with a public React generator, an optional Elemental element, page QR codes, and trackable QR destinations managed in the CMS.

Visitors can choose image size, foreground/background colors, a PNG/JPEG logo and error correction. Generation happens on this website's PHP backend using endroid/qr-code:^6. Public generator URLs, logos and generated images are not permanently stored. Destinations entered for tracked QR codes and their visit logs are stored as described below. Destination URLs are never fetched.

Installation

Requires Silverstripe CMS 6, PHP 8.3+, and GD, Fileinfo, Intl and SimpleXML. The consuming application must provide the usual Page and PageController classes. Supported SilverStripe versions: 6.x. Supported PHP versions: 8.3 and newer. The module registers its routes automatically; no additional route configuration is needed.

composer require clesson-de/silverstripe-qr-code
composer vendor-expose
vendor/bin/sake db:build --flush

Alternatively, run /dev/build?flush=all in an authorized development session.

For the optional content element:

composer require dnadesign/silverstripe-elemental:^6
composer vendor-expose
vendor/bin/sake db:build --flush

Configure an Elemental area on the desired page types as described in Elemental's documentation. No second QR package is needed. If your project restricts allowed element classes, include Clesson\QrCode\Element\QrCodeElement in its allowlist. Installing or removing Elemental requires a manifest flush. Removing Elemental from an existing site does not migrate already-saved element records.

For local development, register this directory as a Composer path repository and require clesson-de/silverstripe-qr-code:@dev in the consuming project. Keep the path repository inside that project when using symlinks: Silverstripe's vendor asset plugin expects exposed source paths to be within the project root.

Editorial and visitor usage

Create a QR code page, or add a QR code generator to an existing Elemental area, then publish the page. Both inherit the site's normal page/element permissions. There is no new module permission or CMS settings model.

Enter an absolute HTTP(S) URL, choose settings and click Create QR code. The preview and download refer to that exact generated result. Changing an input disables the download until another code is created. Multiple instances on one page work independently. JavaScript is required.

Regular pages also receive an Enable QR code checkbox. After it is enabled and saved, the CMS shows a PNG preview. The image is generated on demand, not stored. Visitors can retrieve the same PNG from /page-url/qr-code; the action is available only while enabled and follows the page's normal view permissions. Error and redirector pages are excluded.

Tracked QR destinations

The QR codes CMS section is a single-record administration page with a related list of tracked QR codes. Add a name and an absolute HTTP(S) destination URL, then enable the record to display its QR preview. Each record gets an immutable, cryptographically random 32-character ID. Its QR code encodes the site's absolute /qr/<id> URL, not the destination URL directly. Visiting that tracking URL records the visit and responds with a temporary redirect to the configured destination. Deleted, disabled, or unknown IDs return 404.

Each visit log stores its timestamp, client IP address, and User-Agent. These are visitor data; disclose the tracking and retention policy to site visitors and restrict CMS access appropriately. Logs for a deleted tracked QR code are removed immediately; all other logs older than 90 days are removed by the module's cleanup task. Schedule it to run daily, for example:

vendor/bin/sake tasks:CleanupQRCodeVisitsTask

The tracked destination URL is validated as HTTP(S) and is never fetched by the module. A QR code that points to a tracked URL stops working if its record is disabled or deleted.

The page uses the site's normal outer Page.ss template. Its module layout is templates/Clesson/QrCode/Page/Layout/QrCodePage.ss; override it in your theme if needed. The element respects the inherited ShowTitle setting.

Limits and readability

Setting Rule
URL HTTP(S), no embedded credentials; at most 2,048 UTF-8 bytes
Image 256-2,048 pixels per side, including the quiet zone
Colors Opaque #RRGGBB, lighter background, contrast at least 4.5:1
Quiet zone At least four QR modules on each side
Module size At least two pixels; dense codes require a larger image
Logo Actual PNG/JPEG, at most 2 MiB and 2,048 pixels on each axis
Logo placement Proportional fit within 20% of the inner symbol's side
Logo correction H required; enforced in both browser and backend
Request body At most 2 MiB plus 64 KiB multipart overhead

Defaults are PNG, 512 pixels, black on white and correction M. Adding a logo selects and locks correction H. Removing it unlocks the selection.

The URL is encoded as submitted, apart from trimming surrounding whitespace. Unicode hosts and paths are supported without rewriting the encoded destination. The URL byte limit is not a QR capacity guarantee: long URLs can exceed the selected correction level's capacity even at large image sizes.

Uploaded logos are decoded, resized and re-encoded without source metadata. Transparent logo pixels use the selected background. SVG downloads contain vector QR geometry and an embedded raster logo. Both formats use the same overlay; SVG logo punchout is intentionally not enabled.

Contrast and geometry checks are conservative safeguards, not a scanability guarantee. Always scan-test customized codes and printed output before use.

Developer documentation

The shared presentation helper Clesson\QrCode\Helper\QrApp::render() loads the assets and renders an independent mount without embedding a session token. The frontend fetches its translated labels and anonymous-session token separately. Concurrent instances share one bootstrap request to establish the same anonymous session; their form state, pending generation requests and results remain independent. English and German translations are included; Silverstripe selects the locale.

The public endpoints are:

Endpoint Response
GET /qr-code/config JSON labels, fixed defaults/limits, generation URL and CSRF token
POST /qr-code/generate Binary SVG/PNG or a localized JSON error

POST fields are url, format (svg/png), size, foreground, background, level (L/M/Q/H), the returned token field, and optional logo. The standard browser request is multipart/form-data. Responses use Cache-Control: no-store, private and X-Content-Type-Options: nosniff. Downloads have a fixed qr-code.svg or qr-code.png filename.

Errors have this shape:

{
  "error": {
    "code": "CONTRAST",
    "message": "The background must be lighter than the foreground with at least 4.5:1 contrast.",
    "field": "foreground"
  }
}

HTTP statuses: 403 for invalid/expired CSRF tokens, 405 for unsupported methods, 413 for oversized bodies, 422 for invalid settings/uploads or QR capacity/density errors, and 500 for generation infrastructure failures.

Validation and upload policies are fixed in QrFields, QrValidator and QrLogo, not configurable CMS options. Generator implementations can be replaced through Silverstripe Injector mapping for Clesson\QrCode\Service\QrGenerator. Replacement implementations must preserve validation, resource bounds and cleanup.

Frontend assets

The module ships compiled files in client/frontend/dist/; consumers need no Node.js installation. To modify the frontend, use Node.js 22 (.nvmrc):

nvm use
npm ci
npm run build
npm run watch

npm run build:js bundles React/TypeScript with Rollup into bundle.js. npm run build:css compiles Sass separately into bundle.css. npm run typecheck checks TypeScript. Output filenames are stable, exposed by Composer and referenced through Silverstripe Requirements. Commit both generated files together with source changes.

CodeGuard

SilverStripe CodeGuard is installed as a development dependency. Run its project checks with:

vendor/bin/silverstripe-codeguard check

Project-specific rules and the release gate are configured in .codeguard.yml.

Reusable QRCodeField

Clesson\QrCode\Form\QRCodeField can add the same opt-in PNG preview to another CMS form. Pass it the checkbox's persisted field name, its label, and the data string to encode; the QR code is generated only when that checkbox is enabled:

use Clesson\QrCode\Form\QRCodeField;

$fields->addFieldToTab(
    'Root.Main',
    QRCodeField::create(
        'ShowQRCode',
        'Show QR code',
        $this->owner->AbsoluteLink(),
        (bool) $this->owner->ShowQRCode,
    ),
);

The target URL is validated and never fetched by the module. Use an absolute HTTP(S) URL of at most 2,048 UTF-8 bytes.

Tests

npm test
npm run build

PHP tests run in a consuming Silverstripe project with a configured test database. Install phpunit/phpunit:^11 and the test-only khanamiryan/qrcode-detector-decoder:^2 in that project's development dependencies:

vendor/bin/phpunit -c vendor/clesson-de/silverstripe-qr-code/phpunit.xml.dist

Use an isolated test installation rather than a workspace containing several independent modules with duplicate test Page classes or nested vendor folders. The integration suite builds SapphireTest's temporary database. Run it once without Elemental and once with Elemental, flushing manifests between installations. The suite verifies actual dimensions, quiet-zone pixels, QR decoding, uploads, cleanup, permissions, localized endpoint responses and optional class discovery.

Browser smoke tests require a published generator page at /qr-generator and, when testing Elemental, a page at /qr-elements containing two generators:

npx playwright install chromium
QR_BASE_URL=http://127.0.0.1:8876 npm run test:browser
QR_BASE_URL=http://127.0.0.1:8876 QR_TEST_ELEMENTAL=1 npm run test:browser

Deployment and privacy

  • Configure reverse-proxy rate limiting for the generation endpoint. Public CSRF protection prevents cross-site requests, not bots or resource exhaustion.
  • Set PHP upload_max_filesize to at least 2M, post_max_size above the maximum multipart request (for example 4M), and a sufficient memory limit (for example 128M). Set corresponding web-server body limits. A proxy rejecting the body before PHP may return its own error page.
  • Ensure PHP's temporary directory is writable. PHP upload files exist for the request; module-created sanitized files are removed after rendering, including failures. Images are never written to Silverstripe Assets.
  • Bypass full-page/proxy caching for /qr-code/config and /qr-code/generate. The config token belongs to an anonymous session; normal pages contain only token-free mount markup.
  • Do not log request bodies or uploaded images in proxies/APM. Module failure logs contain only a generic message and exception class, not submitted URLs.
  • The public generator does not save generated results or uploaded logos. Tracked QR destinations are stored in the CMS; each tracked visit stores its timestamp, client IP address and User-Agent for up to 90 days, according to the scheduled cleanup task. Sessions, transient request processing, browser Blob URLs and standard access logs may also exist.

No visitor accounts, remote logo fetching, URL shortening, arbitrary text/vCard/Wi-Fi payloads, CAPTCHA or application-level rate limiter are included.

License

BSD-3-Clause.