Files
FOSSBilling/AGENTS.md
T
Adam Daley 53eb4f2fca Refactor Twig environments and extensions (#2752)
* Replace Custom Twig components

Replace custom Twig components with native Twig components, remove unused custom Twig components, and move functionality to macros where appropriate.

m

Update partial_extensions.html.twig

* Update Twig components and migrate to FOSSBilling namespace

* Update Currency module...

* Refactor Twig environment config and loading

* Switch CSRF to cookie-based double-submit

* Add Api Twig extension and restore widget/svg helpers

* Cast language flags; improve JSON parsing

* Add markdown DI service and use in Admin API

* Refactor Twig extensions and markdown, simplify APIs

* Add sandboxed email Twig env, update render APIs

* Fix pagination URL usage and menu class

* Fix HTML markup in email templates

* Use macro for avatars and status badges

* Fix Twig spacing and pagination URL filter order

* Replace Custom Twig components

Replace custom Twig components with native Twig components, remove unused custom Twig components, and move functionality to macros where appropriate.

m

Update partial_extensions.html.twig

* Update Twig components and migrate to FOSSBilling namespace

* Refactor Twig environment config and loading

* Add Api Twig extension and restore widget/svg helpers

* Cast language flags; improve JSON parsing

* Add markdown DI service and use in Admin API

* Refactor Twig extensions and markdown, simplify APIs

* Fix pagination URL usage and menu class

* Fix Twig spacing and pagination URL filter order

* Use `current_theme` global and refactor `period_title`

* Allow markdown and date in email Twig sandbox

* Update email template examples

* Fix Twig URLs, quoting, and logo alt text

* Fix Twig templates: URLs, i18n, search params

* Use `templates/*` directories for module templates

* Tighten Twig sandbox and add tests

* Add Twig environment and template docs to `AGENTS.md`

* Use Symfony Filesystem/Finder and assorted fixes

* Fix ticket reply link fragment concatenation

* Close missing divs in dashboard template

* Use detailed `toApiArray` for client

* Fix module name resolution for email templates

* Regenerate `composer.lock`

* Use `markdown_to_html` filter in admin macro

* Handle null price/quantity and rename test method

* Use `Tools::isHTTPS()` for HTTPS checks

* Add 'area' param to `url` filter and update templates

* Use client area URLs in admin templates

* Use client area and guest API URLs in templates

* Remove client-side invoice delete feature

* Create Twig env via `TwigFactory` for PDF rendering

* Add embedded orderbutton JS and update render

* Add 'srclink' to cspell allowlist

* Use `renderEmailTplString` for email rendering

* Bump twig/markdown-extra to v3.24

* Use `markdown_to_html` for privacy policy

* Escape API JSON, handle null IP, client URLs

* Remove initial admin creation flow

* Handle HTTP failures and make tests robust

* Use `api_url` helper in admin templates

* Use `url` filter for footer link 5

* Add patch53 to remove legacy html templates

* Bump setting last_patch to 53

* Add patch54 to restore legacy email templates

* Use renderEmailTplString for email templating

* Remove redundant else/endif in order template

* Add file-hash cache buster for asset URLs

* Remove raw Twig filter and handle missing modules dir

* Return '-' for future timestamps

* Register and reuse TwigFactory and add CSRF cookie

* Adjust API URL helper and add Twig error handling

* Update composer.lock and package-lock.json

* Add twig_factory to ServiceTest DI

* Use url filter for link_page in template

* Composer - update deps and add markdown-extra

* Remove docblocks and inline comments in `TwigFactory`

* Add patches 53-55 and update `last_patch`

* Add `has_permission` Twig function; exclude `href`

* Remove duplicate network interface form

* Guard removal of legacy dirs; add network input

* Handle null category descriptions in template

* Add Twig adapter env and sandbox policy

* Add 'striptags' to cspell word list

* Update composer.lock (deps updated/removed)

* Sanitize custom payment adapter templates

* Remove redundant legacy API tests

* Bump `last_patch` setting to 56

* Coalesce null before `markdown_to_html`

* Move update patcher to system CLI command

* Remove stray `endif` from recaptcha macro

* Update composer.lock

* Fix extra closing brace in Api ServiceTest

* Fix test errors from main merge

- Remove testGetRequestCount tests (method moved to RateLimiter)
- Remove testGetDi from Staff and System GuestTest (protected method)
- Fix IP error message in testLoginCheckIpException
- Add rate_limiter mock to Staff GuestTest tests that need it

* Fix remaining Staff GuestTest issues

- Add extension service mock for captcha check
- Fix error message from 'User not found' to 'Admin not found'

* Fix Staff GuestTest: update query and add logger mock

* Fix Staff GuestTest: set admin status to active for password reset flow

* Fix stale API calls and inverted required condition

- Notification: replace removed system_string_render with direct output
- Antispam settings: replace |alink/|link with |url/|api_url filters
- build_form macro: fix inverted required condition for non-textarea inputs

* Sanitize JS/data URIs and disable buttons by permission

* Use client login/profile links in support emails

* Encode fb-api JSON and tighten URL sanitization

* Prefer session auth for API key methods

* Remove stray endif and fix template formatting

* Add CSRF token to CSV exports; fix template

* Remove stray endif in currency template

* Make invoice PDF generation return Response

* Fix Twig filters, templates, and form handling

* Remove readonly from anonymous class in test

* Inline DebugBar CSS/JS in renderHead

* Add Bootstrap Tab to global bootstrap

* Capitalize template UI strings

* Use CKEditor API for reply quotes

* Remove WYSIWYG module and move CKEditor to themes

* Bump `last_patch` in install SQL to 59

* Remove Spamchecker module

* Run domain management script only for active orders

* Standardize UI text capitalization & minor fixes

* Remove Spamchecker legacy tests; fix period test

* Rename Spamchecker tests to Antispam

* Restore antispam config in tests; remove fixture

* Refactor Antispam Guest tests for config checks

* Update theme build docs; remove Wysiwyg module

* Remove spamchecker from cspell and tweak comment

* Add spamchecker to cspell word list

* Capitalize 'Update Graphs' button label
2026-05-06 21:02:16 +01:00

12 KiB

FOSSBilling Project

Project Overview

FOSSBilling is a free and open-source billing and client management solution designed for hosting businesses and other online service providers. It automates invoicing, payment processing, and client management while being extensible and easily integrable with server management software and payment gateways. The project is primarily written in PHP with modern frontend technologies.

Key Technologies

  • Backend: PHP 8.3+ with dependencies managed by Composer. Key libraries include:
    • Symfony Components: Console, cache, filesystem, HTTP client, and other core functionalities. See composer.json for a list of imported components.
      • Prefer Symfony components wherever you can.
      • Use Filesystem, Path, and Finder for filesystem operations instead of native PHP functions (e.g., $filesystem->exists() instead of file_exists(), Finder instead of glob()).
    • Twig: Template engine for rendering views
      • API endpoints are injected as parameters to Twig. See the "Interacting with the FOSSBilling API" section.
      • Twig environments are created via TwigFactory at src/library/FOSSBilling/Twig/TwigFactory.php.
      • Three environment types: admin, client, and email (sandboxed for security).
      • Email templates use a sandboxed environment (EmailPolicy.php) that restricts allowed tags/filters/functions.
    • RedBeanPHP: ORM for database interactions in legacy modules.
    • Doctrine DBAL/ORM: ORM and DBAL for modern modules.
      • FOSSBilling is in the process of migrating modules and core parts from RedBeanPHP to Doctrine one by one.
      • The entity manager is available as $di['em']. It comes from the EntityManagerFactory in /src/library/FOSSBilling/Doctrine/EntityManagerFactory.php.
      • Entities and repositories reside under /src/modules/*/Entity/{Entity}.php and /src/modules/*/Repository/{EntityRepository}.php.
      • The FOSSBilling project is in the process of gradually phasing out RedBeanPHP in favor of Doctrine ORM.
      • When writing new pieces of code, avoid RedBeanPHP.
      • If you are assisting with the migration from RedBeanPHP to Doctrine, do your best to keep compatibility with the existing table structure.
      • When refactoring API endpoints, check how the $di['pager'] works in src/library/FOSSBilling/Pagination.php. paginateDoctrineQuery() is the replacement for getPaginatedResultSet().
    • Monolog: Logging framework. Used via $di['logger'] (/src/library/FOSSBilling/Monolog.php).
    • dompdf: PDF generation for invoices and documents
    • Pimple: Dependency injection container, see src/di.php.
  • Frontend: Modern JavaScript and CSS with npm package management. Key dependencies include:
    • Tabler.io: CSS framework for responsive design, based on Bootstrap 5
    • Tom Select: Enhanced select boxes with search and tagging
    • Autosize: Automatic textarea resizing
    • Flag Icons: Country flag icon library
    • Use vanilla JavaScript for all JS code.
  • Build Tools:
    • esbuild: Fast JavaScript/CSS bundler and minifier
    • Sass: CSS preprocessing
    • PostCSS with Autoprefixer: CSS post-processing
    • svg-sprite: SVG sprite generation for icons
  • Testing:
    • PHPUnit: Unit and integration testing framework
  • Code Quality & Analysis:
    • PHP-CS-Fixer: PSR-12 coding standards enforcement
    • Rector: Automated PHP code refactoring and modernization
    • PHPStan: Static analysis for PHP code

Architecture

FOSSBilling follows a modular architecture with clear separation of concerns:

  • Core Application: Located in src/ directory containing the main application logic
  • Modules: Located in src/modules/ - Two types of modules exist:
    • Service Modules: Represent products that can be sold (e.g., hosting packages, downloadable products). These modules' names must start with "Service", such as "Servicehosting".
    • Extension Modules: Extend FOSSBilling with additional functionality
    • Module templates are organized in templates/admin/, templates/client/, and templates/email/ subdirectories.
  • Themes: Located in src/themes/ for customizing the user interface
  • Libraries: Core libraries and third-party integrations in src/library/
  • Configuration: Environment-specific configurations and dependency injection setup

The application uses a modern PHP architecture with dependency injection, event-driven components, and a clean separation between business logic and presentation layers.

Building and Running

Prerequisites

  • PHP 8.3 or higher with required extensions:
    • curl, intl, mbstring, pdo, zlib
  • Composer for PHP dependency management
  • Node.js and npm for frontend asset management
  • MySQL/MariaDB database server

Important: If PHP is not installed or configured on the system, try using ddev to manage the development environment and run PHP/Composer commands.

Dependencies

Install PHP dependencies with Composer:

composer install

Install Node.js dependencies with npm:

npm install

Building Frontend Assets

FOSSBilling uses esbuild for fast asset compilation. Build frontend assets for themes and modules:

npm run build

This command builds assets for:

  • admin_default theme
  • huraga theme

Build scripts are defined in each theme's package.json and use esbuild.mjs for configuration:

# Build only themes
npm run build-themes

# Build specific theme (uses workspace scripts)
npm run build-admin_default
npm run build-huraga

Theme Structure:

  • admin_default: Uses esbuild.mjs with SVG sprite generation, SCSS compilation, and multiple asset types
  • huraga: Uses simplified esbuild.mjs for basic JS/CSS bundling
  • Theme-owned editor assets: Rich text editor bundles are built within the relevant theme instead of a shared module

Development Mode:

# Watch mode for active development (rebuilds on file changes)
cd src/themes/admin_default && npm run dev
cd src/themes/huraga && npm run dev

Testing

PHPUnit Tests: Run the PHP test suite using PHPUnit:

./src/vendor/bin/phpunit

The project has two test suites:

  • Library Tests: Located in tests-legacy/library/ for testing core library functionality
  • Module Tests: Located in tests-legacy/modules/ for testing individual modules

Code Quality Tools

PHP-CS-Fixer: Format PHP code according to PSR-12 standards:

./src/vendor/bin/php-cs-fixer fix

Rector: Modernize and refactor PHP code automatically:

./src/vendor/bin/rector

PHPStan: Run static analysis to catch potential issues:

./src/vendor/bin/phpstan analyse

Development Conventions

Coding Standards

  • PHP: Follows PSR-12 coding standard
    • Use PHP-CS-Fixer to automatically format code: ./vendor/bin/php-cs-fixer fix
    • Static analysis with PHPStan helps catch potential issues
  • Frontend: Modern JavaScript (ES6+) and Sass for styling. Avoid jQuery.
  • Commit Messages: Follow the project's commit message conventions detailed in CONTRIBUTING.md

Project Structure

src/
├── config-sample.php          # Sample configuration file
├── di.php                     # Dependency injection configuration
├── index.php                  # Main entry point
├── console.php                # CLI application entry point
├── cron.php                   # Scheduled tasks entry point
├── library/                   # Core libraries and third-party integrations
├── modules/                   # Application modules (50+ modules)
├── themes/                    # UI themes (admin_default, huraga)
├── data/                      # Runtime data (cache, logs, uploads)
├── install/                   # Installation scripts and assets
└── vendor/                    # Composer dependencies

tests/                         # Modern test structure
tests-legacy/                  # Legacy PHPUnit tests

Front-end Guidelines

  • admin_default theme icons are compiled from the src/themes/admin_default/assets/icons directory and can be referenced from within the Twig template like so:

    <svg class="icon">
      <use xlink:href="#icon-name" />
    </svg>
    
  • Check the available Twig filters and functions in src/library/FOSSBilling/Twig/Extension/FOSSBillingExtension.php and src/library/FOSSBilling/Twig/Extension/LegacyExtension.php. Use these where applicable.

    • ApiExtension.php provides fb_api, fb_api_form, fb_api_link helpers and |api_url filter.
    • Twig extensions use PHP 8 attributes (#[AsTwigFunction], #[AsTwigFilter]).
  • Global Twig variables include: app_area ('admin' or 'client'), current_theme, guest, CSRFToken, request, FOSSBillingVersion.

  • Email templates are rendered in a sandboxed Twig environment. Use |markdown_to_html filter for markdown content. The sandbox restricts available tags/filters - see EmailPolicy.php for allowed operations.

Interacting with the FOSSBilling API

  • API is injected directly into the Twig templates. You do not need to use fetch/AJAX to read from the API.
    • When applicable, APIs are injected as Twig parameters admin, client, and guest.
    • Guest API is always available. Admin and client APIs are injected if an admin or a client is logged in.
    • To access data, use this format: {{ role.module_endpoint(optional_parameters) }}. A few examples:
      • {{ admin.support_ticket_get_list({ 'status': 'active' }) }} => Reads into /api/admin/support/ticket_get_list?status=active
      • {{ client.order_get({ 'id': 1 }) }} => Reads into /api/client/order/get?id=1
      • {{ guest.system_version }} => Reads into /api/guest/system/version
  • If you need to interact with the API for means other than reading data, use the FOSSBilling API Wrapper in src/library/Api/API.js. It provides API.admin, API.client, and API.guest namespaces with get, post, put, delete, patch methods. CSRFToken is automatically appended.
  • For HTML forms that submit to the API, use the fb_api_form() Twig function. Example: <form {{ fb_api_form({message: 'Saved'|trans}) }}>
  • For links that trigger API calls, use the fb_api_link() Twig function. Example: <a href="..." {{ fb_api_link({modal: {type: 'confirm'}}) }}>
  • Use the |api_url filter to generate API URLs. Example: {{ 'client/delete'|api_url({id: 1}) }}

Contributing Workflow

  1. Read Documentation: Start with CONTRIBUTING.md for detailed guidelines
  2. Development Setup: Install dependencies and build assets
  3. Code Quality: Run tests and code quality tools before submitting
  4. Module Development: Understand the distinction between Service modules and Extension modules
  5. Testing: Write tests for new functionality using PHPUnit

Key Files and Directories

  • README.md: Project overview, installation instructions, and general information
  • CONTRIBUTING.md: Comprehensive contribution guidelines and development workflow
  • composer.json: PHP dependencies, scripts, and project metadata
  • package.json: Node.js dependencies, build scripts, and workspace configuration
  • phpunit.xml.dist: PHPUnit testing configuration
  • phpstan.neon: PHPStan static analysis configuration
  • .php-cs-fixer.dist.php: PHP-CS-Fixer coding standards configuration
  • rector.php: Rector refactoring rules configuration
  • src/config-sample.php: Sample application configuration file
  • src/di.php: Dependency injection container setup

Additional Resources

Important Notes

  • PHP Version: Requires PHP 8.3 or higher
  • Database: Requires MySQL/MariaDB database server
  • License: Apache License 2.0