Introducing widgets (#2853)

* Add "widgets" to the list of core modules

* Patch 44 for widget support

* +Widgets module

* Basic widget discovery

* +Render logic

* +render_widget_slot Twig function

* +get_list

* +Basic settings page to list active widgets

* +Add an `enabled` column to toggle the widget

* +disconnectUnavailable

* Catch exceptions while rendering templates and display an error block

* Types, checks and stuff

* +Add widgets/batch_connect to the crons

Also removed the 11+ year old "finish fixing, time to sleep" docblock

* Demonstration: Replace hardcoded branding text with a widget

* Changed the directory structure

* +Add an error block for the admin panel

* +Added the `widgets` table

* Actually this is pretty unnecessary.

* "render_widget_slot" -> "render_widgets"

* Updated the dates

* Also inject admin/client API if accessible

* +Add an options column

* Implemented optional "add_br" toggle

* Log the exception

* Redid the widgets module

* Added a few new slots

* If even the error template fails, there are bigger problems. Just display the error instead of catching it.

* Created and implemented WidgetProviderInterface

---------

Co-authored-by: Adam Daley <admdly@users.noreply.github.com>
This commit is contained in:
Yağızhan Burak YakarandAdam Daley authored and GitHub committed 2026-02-05 04:16:33 +00:00
1 parent 5d2e8be867
commit 19120d5a19
16 files changed
+617 -14

No files matched your search

+40
View File
@@ -133,6 +133,7 @@ class Box_TwigExtensions extends AbstractExtension implements InjectionAwareInte
public function getFunctions()
{
return [
new TwigFunction('render_widgets', $this->twig_render_widgets(...), ['needs_environment' => true, 'is_safe' => ['html']]),
new TwigFunction('svg_sprite', $this->twig_svg_sprite(...), ['needs_environment' => true, 'is_safe' => ['html']]),
// FOSSBilling API functions
@@ -152,6 +153,45 @@ class Box_TwigExtensions extends AbstractExtension implements InjectionAwareInte
return 'bb';
}
/**
* Part of the Widgets module. Renders the widgets of a specified slot.
*
* @param \Twig\Environment $env the Twig environment (injected automatically)
* @param string $slot name of the slot
* @param array $context optional slot context, such as order or client details
*
* @return string slot content
*/
public function twig_render_widgets(\Twig\Environment $env, string $slot, array $context = []): string
{
$widgets = $this->di['mod_service']('Widgets')->getSlotWidgets($slot);
if (empty($widgets)) {
return '';
}
$output = '';
foreach ($widgets as $widget) {
try {
$templateName = 'widgets/' . $widget['template'] . '.html.twig';
$output .= $env->render($templateName, $context);
} catch (\Throwable $e) {
// Render error widget on failure
$output .= $env->render('widgets/mod_widgets_error.html.twig', array_merge($context, [
'widget' => [
'slot' => $slot,
'mod_name' => $widget['module'],
'template' => $widget['template'],
],
'error' => \FOSSBilling\Environment::isDevelopment() ? $e->getMessage() : null,
]));
}
}
return $output;
}
public function twig_ipcountryname_filter($value)
{
if (empty($value)) {
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2025 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace FOSSBilling\Interfaces;
/**
* Interface for modules that provide widgets.
*
* Modules implementing this interface can register widgets that will be
* rendered in slots within templates via the Widgets module.
*/
interface WidgetProviderInterface
{
/**
* Get the widget definitions provided by this module.
*
* Each widget definition should contain:
* - 'slot': The target slot name (e.g., 'client.theme.footer.end')
* - 'template': The template name (without path/extension)
* - 'priority': (optional) Render order, lower numbers render first (default: 10)
*
* @return array<int, array{slot: string, template: string, priority?: int}>
*/
public function getWidgets(): array;
}
+2 -1
View File
@@ -32,7 +32,8 @@ class Module implements InjectionAwareInterface
'page', 'product', 'profile', 'security',
'servicecustom', 'servicedomain', 'servicedownloadable',
'servicehosting', 'servicelicense', 'staff', 'stats',
'support', 'system', 'theme', 'orderbutton', 'formbuilder'];
'support', 'system', 'theme', 'orderbutton', 'formbuilder',
'widgets'];
public function setDi(?\Pimple\Container $di): void
{
+14 -1
View File
@@ -11,7 +11,10 @@
namespace Box\Mod\Branding;
class Service implements \FOSSBilling\InjectionAwareInterface
use \FOSSBilling\InjectionAwareInterface;
use \FOSSBilling\Interfaces\WidgetProviderInterface;
class Service implements InjectionAwareInterface, WidgetProviderInterface
{
protected ?\Pimple\Container $di = null;
@@ -32,6 +35,16 @@ class Service implements \FOSSBilling\InjectionAwareInterface
];
}
public function getWidgets(): array
{
return [
[
'slot' => 'client.theme.footer.end',
'template' => 'mod_branding_footer',
],
];
}
public function uninstall(): bool
{
return true;
@@ -0,0 +1,6 @@
<div class="d-flex justify-content-center">
<span>{{ 'Powered by'|trans }}&nbsp;</span>
<a class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover"
href="https://fossbilling.org" title="Billing Software"
target="_blank">{{ 'FOSSBilling'|trans }}</a>
</div>
+1 -4
View File
@@ -39,9 +39,6 @@ class Service
];
}
/**
* @todo finish fixing, time to sleep (note: idk what exactly this is referring to. It predates FOSSBilling and is from BoxBilling well before we touched this code)
*/
public function runCrons(): bool
{
$api = $this->di['api_system'];
@@ -80,7 +77,7 @@ class Service
/**
* @param string $method
*/
protected function _exec($api, $method, $params = null)
protected function _exec($api, $method, $params = null): void
{
try {
$api->{$method}($params);
+37
View File
@@ -0,0 +1,37 @@
<?php
/**
* Copyright 2022-2025 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Widgets\Api;
class Admin extends \Api_Abstract
{
/**
* Get all registered widgets grouped by slots.
*
* @return array list of slots with their widgets
*/
public function list(): array
{
return $this->getService()->getWidgetList();
}
/**
* Force rebuild of the widget registry cache.
* Useful for debugging or after manual changes.
*/
public function rebuild(): bool
{
$service = $this->getService();
$service->invalidateCache();
$service->getRegistry(); // Trigger rebuild
return true;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
/**
* Copyright 2022-2025 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Widgets\Controller;
class Admin implements \FOSSBilling\InjectionAwareInterface
{
protected ?\Pimple\Container $di = null;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
public function fetchNavigation(): array
{
return [
'subpages' => [
[
'location' => 'extensions',
'label' => __trans('Widgets'),
'index' => 500,
'uri' => $this->di['url']->adminLink('widgets'),
'class' => '',
],
],
];
}
public function register(\Box_App &$app): void
{
$app->get('/widgets', 'get_index', [], static::class);
}
public function get_index(\Box_App $app): string
{
$this->di['is_admin_logged'];
return $app->render('mod_widgets_index');
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
/**
* Copyright 2022-2025 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Widgets;
use FOSSBilling\InjectionAwareInterface;
use FOSSBilling\Interfaces\WidgetProviderInterface;
use Symfony\Contracts\Cache\ItemInterface;
class Service implements InjectionAwareInterface
{
public const DEFAULT_PRIORITY = 10;
public const CACHE_KEY = 'widgets_registry';
protected ?\Pimple\Container $di = null;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
/**
* Get the widget registry from cache, rebuild if necessary.
*
* @return array<string, array<int, array{module: string, template: string, priority: int}>>
*/
public function getRegistry(): array
{
return $this->di['cache']->get(self::CACHE_KEY, function (ItemInterface $item) {
$item->expiresAfter(null); // No need to expire. We will manually invalidate on module activation/deactivation
return $this->buildRegistry();
});
}
/**
* Build the widget registry by scanning all active modules.
*
* @return array<string, array<int, array{module: string, template: string, priority: int}>>
*/
public function buildRegistry(): array
{
$registry = [];
$modules = $this->di['mod_service']('Extension')->getCoreAndActiveModules();
foreach ($modules as $modName) {
try {
$widgets = $this->getModuleWidgets($modName);
foreach ($widgets as $widget) {
if (!isset($widget['slot']) || !isset($widget['template'])) {
continue; // Skip invalid widget definitions
}
$slot = $widget['slot'];
$priority = $widget['priority'] ?? self::DEFAULT_PRIORITY;
if (!is_int($priority) || $priority <= 0) {
$priority = self::DEFAULT_PRIORITY;
}
$registry[$slot][] = [
'module' => $modName,
'template' => $widget['template'],
'priority' => $priority,
];
}
} catch (\Throwable $e) {
// Log the error but continue with other modules
$this->di['logger']->err("Error loading widgets from module '{$modName}': " . $e->getMessage());
}
}
// Sort each slot's widgets by priority (ascending)
foreach ($registry as $slot => &$widgets) {
usort($widgets, fn ($a, $b) => $a['priority'] <=> $b['priority']);
}
return $registry;
}
/**
* Invalidate the widget cache, forcing a rebuild on next access.
*/
public function invalidateCache(): void
{
$this->di['cache']->delete(self::CACHE_KEY);
}
/**
* Get widgets for a specific slot.
*
* Slot naming convention: {area}.{namespace}.{location}[.{position}]
* - area: 'admin' or 'client'
* - namespace: 'theme' for layout slots, or module name for module-specific slots
* - location: where the slot appears (e.g., 'footer', 'sidebar', 'details')
* - position: optional refinement (e.g., 'start', 'end', 'before', 'after')
*
* Examples:
* - 'client.theme.footer.end' - End of footer in client theme layout
* - 'admin.theme.sidebar.top' - Top of sidebar in admin theme layout
* - 'client.invoice.details.after' - After invoice details in Invoice module
*
* @param string $slot name of the slot (e.g., 'client.theme.footer.end')
*
* @return array<int, array{module: string, template: string, priority: int}> widgets for the slot
*/
public function getSlotWidgets(string $slot): array
{
$registry = $this->getRegistry();
return $registry[$slot] ?? [];
}
/**
* Get a module's widget definitions.
*
* @param string $modName the module name
*
* @return array list of widget definitions
*/
public function getModuleWidgets(string $modName): array
{
$mod = $this->di['mod']($modName);
if ($mod->hasService()) {
$service = $mod->getService();
if ($this->serviceProvidesWidgets($service)) {
return $service->getWidgets();
}
}
return [];
}
/**
* Check if a service class provides widgets.
*
* @param object $service the service class instance
*
* @return bool true if the service implements WidgetProviderInterface
*/
private function serviceProvidesWidgets(object $service): bool
{
return $service instanceof WidgetProviderInterface;
}
/**
* Get all widgets grouped by slot (for admin listing).
*
* @return array list of slots with their widgets
*/
public function getWidgetList(): array
{
$registry = $this->getRegistry();
$result = [];
foreach ($registry as $slot => $widgets) {
$result[] = [
'slot' => $slot,
'widgets' => $widgets,
'count' => count($widgets),
];
}
// Sort by slot name for consistent display
usort($result, fn ($a, $b) => strcmp($a['slot'], $b['slot']));
return $result;
}
/**
* Event handler: Invalidate cache when a module is activated.
*/
public static function onAfterAdminActivateExtension(\Box_Event $event): void
{
$params = $event->getParameters();
if (isset($params['id'])) {
$di = $event->getDi();
$ext = $di['db']->load('extension', $params['id']);
if (is_object($ext) && $ext->type === 'mod') {
$di['mod_service']('Widgets')->invalidateCache();
}
}
$event->setReturnValue(true);
}
/**
* Event handler: Invalidate cache when a module is deactivated.
*/
public static function onAfterAdminDeactivateExtension(\Box_Event $event): void
{
$params = $event->getParameters();
if (($params['type'] ?? null) === 'mod') {
$di = $event->getDi();
$di['mod_service']('Widgets')->invalidateCache();
}
$event->setReturnValue(true);
}
}
@@ -0,0 +1,156 @@
{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %}
{% import 'macro_functions.html.twig' as mf %}
{% block meta_title %}{{ 'Widgets'|trans }}{% endblock %}
{% set active_menu = 'extensions' %}
{% block breadcrumbs %}
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{{ '/'|alink }}">
<svg class="icon">
<use xlink:href="#home" />
</svg>
</a>
</li>
<li class="breadcrumb-item">
<a href="{{ 'extension'|alink }}">{{ 'Extensions'|trans }}</a>
</li>
<li class="breadcrumb-item active" aria-current="page">{{ 'Widgets'|trans }}</li>
</ol>
{% endblock %}
{% set slots = admin.widgets_list() %}
{% block content %}
<div class="card">
<div class="card-header">
<div>
<h3 class="card-title">{{ 'Widget Registry'|trans }}</h3>
<p class="card-subtitle">{{ 'Modules can register widgets to dynamically display content in theme slots'|trans }}</p>
</div>
<div class="card-actions">
<a href="{{ 'api/admin/widgets/rebuild'|link }}" class="btn btn-primary"
{{ fb_api_link({ reload: true, message: 'Widget cache rebuilt successfully'|trans}) }}>
<svg class="icon">
<use xlink:href="#refresh" />
</svg>
{{ 'Rediscover Widgets'|trans }}
</a>
</div>
</div>
{% if slots is empty %}
<div class="card-body">
<div class="empty">
<div class="empty-icon">
<svg class="icon icon-lg">
<use xlink:href="#info" />
</svg>
</div>
<p class="empty-title">{{ 'No widgets registered'|trans }}</p>
<p class="empty-subtitle text-secondary">
{{ 'Widgets will appear here when modules that provide them are activated.'|trans }}<br>
{{ 'Modules register widgets by implementing a <code>getWidgets()</code> method in their Service class.'|trans|raw }}
</p>
<div class="empty-action">
<a href="{{ 'extension'|alink }}" class="btn btn-primary">
<svg class="icon">
<use xlink:href="#iPlugin" />
</svg>
{{ 'Manage Extensions'|trans }}
</a>
</div>
</div>
</div>
{% else %}
<div class="card-body border-bottom py-3">
<div class="d-flex">
<div class="text-secondary">
{{ 'Showing'|trans }}
<span class="text-body fw-semibold">{{ slots|length }}</span>
{{ slots|length == 1 ? 'slot'|trans : 'slots'|trans }}
{{ 'with'|trans }}
<span class="text-body fw-semibold">{% set total_widgets = 0 %}{% for slot in slots %}{% set total_widgets = total_widgets + slot.count %}{% endfor %}{{ total_widgets }}</span>
{{ total_widgets == 1 ? 'widget'|trans : 'widgets'|trans }}
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-vcenter card-table">
<thead>
<tr>
<th>{{ 'Slot'|trans }}</th>
<th>{{ 'Widgets'|trans }}</th>
<th class="w-1"></th>
</tr>
</thead>
<tbody>
{% for slot in slots %}
<tr>
<td>
<div class="d-flex align-items-center">
<span class="avatar avatar-sm bg-primary-lt text-secondary me-2">
<svg class="icon">
<use xlink:href="#cog" />
</svg>
</span>
<div>
<code class="text-reset">{{ slot.slot }}</code>
<div class="text-secondary small">
{% set slot_parts = slot.slot|split('.') %}
{% if slot_parts[0] == 'admin' %}
<span class="badge bg-blue-lt">{{ 'Admin'|trans }}</span>
{% elseif slot_parts[0] == 'client' %}
<span class="badge bg-green-lt">{{ 'Client'|trans }}</span>
{% endif %}
{% if slot_parts[1] == 'theme' %}
{{ 'Theme layout slot'|trans }}
{% else %}
{{ 'Module slot'|trans }}
{% endif %}
</div>
</div>
</div>
</td>
<td>
<div class="d-flex flex-column gap-1">
{% for widget in slot.widgets %}
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary text-white" data-bs-toggle="tooltip" data-bs-title="{{ 'Priority'|trans }}">{{ widget.priority }}</span>
<span class="fw-medium">{{ widget.module|capitalize }}</span>
<span class="text-secondary">&rarr;</span>
<code class="text-secondary small">widgets/{{ widget.template }}.html.twig</code>
</div>
{% endfor %}
</div>
</td>
<td>
<span class="badge bg-blue-lt">{{ slot.count }}</span>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer">
<div class="row align-items-center">
<div class="col-auto">
<svg class="icon">
<use xlink:href="#info" />
</svg>
</div>
<div class="col">
<div class="text-secondary">
{{ 'Widgets are registered automatically when modules are activated. Lower priority numbers are rendered first.'|trans }}
</div>
</div>
</div>
</div>
{% endif %}
</div>
{% endblock %}
@@ -0,0 +1,27 @@
<div class="alert alert-danger" role="alert">
<div class="alert-icon">
<svg class="icon">
<use xlink:href="#alert-triangle" />
</svg>
</div>
<div>
<h4 class="alert-heading">An error occurred while rendering this widget.</h4>
<div class="alert-description">
<ul class="mb-1">
<li>
<strong>Slot:</strong>
{{ widget.slot|e }}</li>
<li>
<strong>Module:</strong>
{{ widget.mod_name|e }}</li>
<li>
<strong>Template:</strong>
{{ widget.template|e }}.html.twig</li>
</ul>
{% if error %}
<pre class="mt-3 mb-0 bg-light p-2 border rounded text-danger small">{{ error|e }}</pre>
{% endif %}
</div>
</div>
</div>
@@ -0,0 +1,13 @@
<div class="alert alert-danger" role="alert">
<h5 class="alert-heading">An error occurred while rendering this widget.</h5>
<ul class="mb-1">
<li><strong>Slot:</strong> {{ widget.slot|e }}</li>
<li><strong>Module:</strong> {{ widget.mod_name|e }}</li>
<li><strong>Template:</strong> {{ widget.template|e }}.html.twig</li>
</ul>
{% if error %}
<pre class="mt-3 mb-0 bg-light p-2 border rounded text-danger small">{{ error|e }}</pre>
{% endif %}
</div>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 4m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z" /><path d="M4 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z" /><path d="M14 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z" /><path d="M14 7l6 0" /><path d="M17 4l0 6" /></svg>

After

Width:  |  Height:  |  Size: 552 B

+8
View File
@@ -0,0 +1,8 @@
{
"id": "widgets",
"type": "mod",
"name": "Widgets",
"description": "Widget system for FOSSBilling. Allows modules to register widgets that can be rendered in designated slots.",
"icon_url": "icon.svg",
"version": "1.0.0"
}
@@ -209,16 +209,20 @@
</ol>
{% endblock %}
</nav>
{{ render_widgets('admin.theme.content.before') }}
{% block top_content %}{% endblock %}
{% block content %}{% endblock %}
{{ render_widgets('admin.theme.content.after') }}
</div>
</main>
<footer class="footer footer-transparent d-print-none">
<div class="container-xl">
{{ render_widgets('admin.theme.footer.start') }}
<p>&copy; {{ now|format_date(pattern='yyyy') }} <a href="https://github.com/FOSSBilling">FOSSBilling contributors</a>.
Licensed under <a href="https://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
Running version <code>{{ FOSSBillingVersion }}</code>.</p>
{{ render_widgets('admin.theme.footer.end') }}
</div>
</footer>
</div>
@@ -167,7 +167,9 @@
{% endblock %}
{% endif %}
{{ render_widgets('client.theme.content.before') }}
{% block content %}{% endblock %}
{{ render_widgets('client.theme.content.after') }}
{{ include('partial_message.html.twig') }}
@@ -180,6 +182,7 @@
{% if settings.footer_enabled %}
<footer id="footer" class="small text-muted mt-2 mb-3">
<div class="d-flex flex-column">
{{ render_widgets('client.theme.footer.start') }}
<div class="d-flex justify-content-center">
<span>&copy; {{ now|format_date(pattern='yyyy') }} {{ settings.footer_signature | default(company.signature) }}
{% if company.bank_info_pagebottom == 1 %}
@@ -229,14 +232,7 @@
{% endif %}
{% endif %}
</div>
{% if guest.extension_is_on({"mod":'branding'}) %}
<div class="d-flex justify-content-center">
<span>{{ 'Powered by'|trans }}&nbsp;</span>
<a class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover"
href="https://fossbilling.org" title="Billing Software"
target="_blank">{{ 'FOSSBilling'|trans }}</a>
</div>
{% endif %}
{{ render_widgets('client.theme.footer.end') }}
</div>
</footer>
{% endif %}