Allow uninstalling modules through the admin panel (#2979)

* Allow uninstalling modules through the admin panel

* Extracted extension path logic to a method

* Fixed PHPDoc

* Tests

* Tests

* Typos

* Fİxed tests

* Fixed tests

* Remove accidental submodule

* Throw an InformationException instead

* Throw an InformationException instead

* Throw an InformationException instead
This commit is contained in:
Yağızhan Burak Yakar authored and GitHub committed 2025-10-31 14:42:54 +03:00
1 parent e9aae4ad9f
commit 8656d06d84
6 files changed
+143 -132

No files matched your search

+14 -6
View File
@@ -191,17 +191,25 @@ class Admin extends \Api_Abstract
}
/**
* Completely remove extension from FOSSBilling.
* Uninstall a deactivated extension, remove its files from the disk and call $extension->uninstall() to trigger database cleanup.
*
* @return bool
*
* @throws \FOSSBilling\Exception
*/
public function uninstall($data): bool
{
$ext = $this->_getExtension($data);
$this->di['events_manager']->fire(['event' => 'onBeforeAdminUninstallExtension', 'params' => ['id' => $ext->id]]);
$required = [
'id' => 'Extension ID was not passed',
'type' => 'Extension type was not passed',
];
$this->di['validator']->checkRequiredParamsForArray($required, $data);
$this->di['events_manager']->fire(['event' => 'onBeforeAdminUninstallExtension', 'params' => ['type' => $data['type'], 'id' => $data['id']]]);
$service = $this->getService();
$service->uninstall($ext);
$this->getService()->uninstall($data['type'], $data['id']);
$this->di['events_manager']->fire(['event' => 'onAfterAdminUninstallExtension', 'params' => ['id' => $ext->id]]);
$this->di['events_manager']->fire(['event' => 'onAfterAdminUninstallExtension', 'params' => ['type' => $data['type'], 'id' => $data['id']]]);
return true;
}
+95 -58
View File
@@ -45,19 +45,24 @@ class Service implements InjectionAwareInterface
'manage_extensions' => [
'type' => 'bool',
'display_name' => __trans('Manage extensions'),
'description' => __trans('Allows the staff member to install, update, or remove extensions.'),
'description' => __trans('Allows the staff member to install, update, or deactivate extensions.'),
],
'uninstall_extensions' => [
'type' => 'bool',
'display_name' => __trans('Uninstall extensions'),
'description' => __trans('Allow the staff member to uninstall extensions, including their associated database records and files.'),
],
];
}
public function isCoreModule($mod): bool
public function isCoreModule(string $mod): bool
{
$core = $this->di['mod']('extension')->getCoreModules();
return in_array($mod, $core);
}
public function isExtensionActive($type, $id)
public function isExtensionActive(string $type, string $id): bool
{
if ($type == 'mod' && $this->isCoreModule($id)) {
return true;
@@ -90,7 +95,7 @@ class Service implements InjectionAwareInterface
return true;
}
public function removeNotExistingModules()
public function removeNotExistingModules(): bool|int
{
$list = $this->di['db']->find('Extension', "type = 'mod'");
$removedItems = 0;
@@ -352,6 +357,11 @@ class Service implements InjectionAwareInterface
throw new \FOSSBilling\InformationException('Visit the extension directory for more information on updating this extension.', null, 252);
}
/**
* Activate an extension
* @param \Model_Extension $ext
* @return array|array{has_settings: bool, id: string, redirect: bool, type: string}
*/
public function activate(\Model_Extension $ext): array
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
@@ -384,6 +394,12 @@ class Service implements InjectionAwareInterface
return $result;
}
/**
* Deactivate an extension
* @param \Model_Extension $ext
* @throws \FOSSBilling\InformationException
* @return bool
*/
public function deactivate(\Model_Extension $ext): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
@@ -401,16 +417,7 @@ class Service implements InjectionAwareInterface
case \FOSSBilling\ExtensionManager::TYPE_MOD:
$mod = $ext->name;
if ($this->isCoreModule($mod)) {
throw new \FOSSBilling\InformationException('FOSSBilling core modules cannot be managed');
}
try {
$mm = $this->di['mod']($mod);
$mm->uninstall();
} catch (\FOSSBilling\Exception $e) {
if ($e->getCode() != 408) {
throw $e;
}
throw new \FOSSBilling\InformationException('Core modules are an integral part of the FOSSBilling system and cannot be deactivated.');
}
break;
@@ -424,37 +431,66 @@ class Service implements InjectionAwareInterface
return true;
}
public function uninstall(\Model_Extension $ext): bool
/**
* Uninstall a deactivated extension, remove its files from the disk and call $extension->uninstall() to trigger database cleanup.
* @param string $type Type of the extension (mod, theme, ...)
* @param string $id ID of the extension
* @throws \FOSSBilling\Exception
* @return bool
*/
public function uninstall(string $type, string $id): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'uninstall_extensions');
$this->deactivate($ext);
switch ($ext->type) {
case \FOSSBilling\ExtensionManager::TYPE_MOD:
break;
default:
break;
if ($this->isCoreModule($id)) {
throw new \FOSSBilling\InformationException('Core modules are an integral part of the FOSSBilling system and cannot be uninstalled.');
}
$this->di['db']->trash($ext);
if ($this->isExtensionActive($type, $id)) {
throw new \FOSSBilling\InformationException('Cannot uninstall an active module. Please deactivate it first.');
}
// Determine the path based on extension type
$path = $this->getExtensionPath($type, $id);
// Try calling $module->uninstall() for modules to trigger database cleanup
if ($type === \FOSSBilling\ExtensionManager::TYPE_MOD) {
$mod = $this->di['mod']($id);
try {
$mod->uninstall();
} catch (\Exception $e) {
throw new \FOSSBilling\Exception('An exception was thrown by the :name module: :err', [':name' => $id, ':err' => $e->getMessage()]);
}
}
// Finally remove the extension files from disk if they exist
if ($this->filesystem->exists($path)) {
try {
$this->filesystem->remove($path);
$this->di['logger']->info('Removed extension files for "%s" from %s', $id, $path);
} catch (IOException $e) {
$this->di['logger']->warn('Failed to remove extension files for "%s": %s', $id, $e->getMessage());
throw new \FOSSBilling\Exception('Failed to remove extension files. Please check file permissions and try again or manually remove the files from :path', [':path' => $path]);
}
} else {
throw new \FOSSBilling\Exception('Could not find the extension files in the supposed path. Please remove them from the disk manually.');
}
return true;
}
public function downloadAndExtract($type, $id): bool
public function downloadAndExtract(string $type, string $id): bool
{
$this->di['mod_service']('Staff')->checkPermissionsAndThrowException('extension', 'manage_extensions');
$latest = $this->di['extension_manager']->getLatestExtensionRelease($id);
if (!isset($latest['download_url'])) {
throw new \Exception('Coudn\'t find a valid download URL for the extension.');
throw new \FOSSBilling\Exception('Couldn\'t find a valid download URL for the extension.');
}
if (!$this->di['extension_manager']->isExtensionCompatible($id)) {
throw new \Exception('This extension is not compatible with your version of FOSSBilling. Please update FOSSBilling to the latest version and try again.');
throw new \FOSSBilling\InformationException('This extension is not compatible with your version of FOSSBilling. Please update FOSSBilling to the latest version and try again.');
}
$extractedPath = Path::join(PATH_CACHE, md5(uniqid()));
@@ -490,37 +526,17 @@ class Service implements InjectionAwareInterface
throw new \FOSSBilling\Exception('Failed to extract file, please check file and folder permissions. Further details are available in the error log.');
}
switch ($type) {
case \FOSSBilling\ExtensionManager::TYPE_MOD:
$destination = Path::join(PATH_MODS, ucfirst((string) $id));
// Get the destination path for the extension (includes LC_MESSAGES for translations)
$destination = $this->getExtensionPath($type, $id, true);
break;
case \FOSSBilling\ExtensionManager::TYPE_THEME:
$destination = Path::join(PATH_THEMES, $id);
break;
case \FOSSBilling\ExtensionManager::TYPE_TRANSLATION:
$destination = Path::join(PATH_LANGS, $id, 'LC_MESSAGES');
break;
case \FOSSBilling\ExtensionManager::TYPE_PG:
$destination = Path::join(PATH_LIBRARY, 'Payment', 'Adapter', ucfirst((string) $id));
break;
if ($this->filesystem->exists($destination)) {
throw new \FOSSBilling\InformationException('Extension :id seems to be already installed.', [':id' => $id], 436);
}
if (isset($destination)) {
if ($this->filesystem->exists($destination)) {
throw new \FOSSBilling\InformationException('Extension :id seems to be already installed.', [':id' => $id], 436);
}
try {
$this->filesystem->rename($extractedPath, $destination);
} catch (IOException) {
throw new \FOSSBilling\Exception("Failed to move extension to it's final destination. Please check permissions for the destination folder. (:destination)", [':destination' => $destination], 437);
}
} else {
throw new \FOSSBilling\InformationException('Extension type (:type) cannot be automatically installed.', [':type' => $type]);
try {
$this->filesystem->rename($extractedPath, $destination);
} catch (IOException) {
throw new \FOSSBilling\Exception("Failed to move extension to it's final destination. Please check permissions for the destination folder. (:destination)", [':destination' => $destination], 437);
}
if ($this->filesystem->exists($zipPath)) {
@@ -578,7 +594,7 @@ class Service implements InjectionAwareInterface
return true;
}
public function activateExistingExtension($data)
public function activateExistingExtension(array $data): array
{
$ext = $this->findExtension($data['type'], $data['id']);
if (!$ext instanceof \Model_Extension) {
@@ -661,7 +677,28 @@ class Service implements InjectionAwareInterface
return true;
}
private function _getSalt()
/**
* Get the filesystem path for an extension based on its type and ID
* @param string $type Extension type
* @param string $id Extension ID
* @param bool $includeMessagesSubdir Whether to include LC_MESSAGES subdirectory for translations (used during installation)
* @return string The filesystem path for the extension
* @throws \FOSSBilling\Exception If the extension type is not supported
*/
public function getExtensionPath(string $type, string $id, bool $includeMessagesSubdir = false): string
{
return match ($type) {
\FOSSBilling\ExtensionManager::TYPE_MOD => Path::join(PATH_MODS, ucfirst($id)),
\FOSSBilling\ExtensionManager::TYPE_THEME => Path::join(PATH_THEMES, $id),
\FOSSBilling\ExtensionManager::TYPE_TRANSLATION => $includeMessagesSubdir
? Path::join(PATH_LANGS, $id, 'LC_MESSAGES')
: Path::join(PATH_LANGS, $id),
\FOSSBilling\ExtensionManager::TYPE_PG => Path::join(PATH_LIBRARY, 'Payment', 'Adapter', ucfirst($id)),
default => throw new \FOSSBilling\InformationException('Extension type (:type) is not supported for automatic path determination.', [':type' => $type]),
};
}
private function _getSalt(): ?string
{
return Config::getProperty('info.salt');
}
@@ -69,7 +69,7 @@
{% if ext.type == 'mod' %}
{% if ext.status == 'installed' %}
<a class="btn btn-icon api-link"
href="{{ 'api/admin/extension/deactivate'|link({ 'type': ext.type, 'id': ext.id, 'CSRFToken': CSRFToken }) }}"
href="{{ 'api/admin/extension/deactivate'|link({ 'type': ext.type, 'id': ext.id }) }}"
data-api-type="danger"
data-api-confirm-btn="Deactivate"
data-api-confirm="{{ 'Are you sure?'|trans }}"
@@ -81,34 +81,47 @@
</a>
{% else %}
<a class="btn btn-icon api-link"
href="{{ 'api/admin/extension/activate'|link({ 'type': ext.type, 'id': ext.id, 'CSRFToken': CSRFToken }) }}"
data-api-confirm="{{ 'Are you sure?'|trans }}"
data-api-confirm-btn="Activate"
href="{{ 'api/admin/extension/uninstall'|link({ 'type': ext.type, 'id': ext.id }) }}"
data-api-confirm="{{ 'Are you sure?<br /><br />Uninstalling this module will permanently delete all its database tables and remove its files from the disk. This action cannot be undone.'|trans }}"
data-api-confirm-btn="Uninstall"
data-api-type="danger"
data-api-jsonp="onAfterModuleActivated"
data-bs-toggle="tooltip" data-bs-title="{{ 'Activate'|trans }}">
data-bs-toggle="tooltip" data-bs-title="{{ 'Uninstall'|trans }}">
<svg class="icon">
<use xlink:href="#play" />
<use xlink:href="#delete" />
</svg>
</a>
{% endif %}
{% else %}
&nbsp;
{% endif %}
</td>
{% if ext.type == 'mod' and ext.status != 'installed' %}
<td>
{% if ext.has_settings %}
<a class="btn btn-icon" href="{{ 'extension/settings'|alink }}/{{ ext.id }}"
data-bs-toggle="tooltip" data-bs-title="{{ 'Settings'|trans }}">
<svg class="icon">
<use xlink:href="#cog" />
</svg>
</a>
{% endif %}
<a class="btn btn-icon api-link"
href="{{ 'api/admin/extension/activate'|link({ 'type': ext.type, 'id': ext.id }) }}"
data-api-confirm="{{ 'Are you sure?'|trans }}"
data-api-confirm-btn="Activate"
data-api-jsonp="onAfterModuleActivated"
data-bs-toggle="tooltip" data-bs-title="{{ 'Activate'|trans }}">
<svg class="icon">
<use xlink:href="#play" />
</svg>
</a>
</td>
{% endif %}
{% if ext.has_settings %}
<td>
<a class="btn btn-icon" href="{{ 'extension/settings'|alink }}/{{ ext.id }}"
data-bs-toggle="tooltip" data-bs-title="{{ 'Settings'|trans }}">
<svg class="icon">
<use xlink:href="#cog" />
</svg>
</a>
</td>
{% endif %}
</tr>
{% else %}
<tr>
<td class="text-muted" colspan="4">{{ 'The list is empty'|trans }}</td>
<td class="text-muted" colspan="5">{{ 'The list is empty'|trans }}</td>
</tr>
{% endfor %}
</tbody>
Submodule src/modules/Fastnetmon deleted from 115c903b71.
@@ -204,9 +204,6 @@ class AdminTest extends \BBTestCase
$model->loadBean(new \DummyBean());
$serviceMock = $this->getMockBuilder('\\' . \Box\Mod\Extension\Service::class)->getMock();
$serviceMock->expects($this->atLeastOnce())
->method('findExtension')
->willReturn($model);
$serviceMock->expects($this->atLeastOnce())
->method('uninstall')
->willReturn(true);
+4 -47
View File
@@ -375,10 +375,6 @@ class ServiceTest extends \BBTestCase
->method('getCoreModules')
->willReturn([]);
$modMock->expects($this->atLeastOnce())
->method('uninstall')
->willReturn(true);
$staffService = $this->getMockBuilder(\Box\Mod\Staff\Service::class)->getMock();
$staffService->expects($this->atLeastOnce())->method('checkPermissionsAndThrowException');
@@ -417,40 +413,7 @@ class ServiceTest extends \BBTestCase
$this->service->setDi($di);
$this->expectException(\FOSSBilling\Exception::class);
$this->expectExceptionMessage('FOSSBilling core modules cannot be managed');
$this->service->deactivate($ext);
}
public function testdeactivateUninstallException(): void
{
$ext = new \Model_Extension();
$ext->loadBean(new \DummyBean());
$ext->type = 'mod';
$ext->name = 'extensionTest';
$exceptionMessage = 'testException';
$modMock = $this->getMockBuilder('\Box_Mod')->disableOriginalConstructor()->getMock();
$modMock->expects($this->atLeastOnce())
->method('getCoreModules')
->willReturn([]);
$modMock->expects($this->atLeastOnce())
->method('uninstall')
->willThrowException(new \FOSSBilling\Exception($exceptionMessage));
$staffService = $this->getMockBuilder(\Box\Mod\Staff\Service::class)->getMock();
$staffService->expects($this->atLeastOnce())->method('checkPermissionsAndThrowException');
$di = new \Pimple\Container();
$di['mod'] = $di->protect(fn ($name): \PHPUnit\Framework\MockObject\MockObject => $modMock);
$di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $staffService);
$this->service->setDi($di);
$this->expectException(\FOSSBilling\Exception::class);
$this->expectExceptionMessage($exceptionMessage);
$this->expectExceptionMessage('Core modules are an integral part of the FOSSBilling system and cannot be deactivated.');
$this->service->deactivate($ext);
}
@@ -479,14 +442,7 @@ class ServiceTest extends \BBTestCase
public function testuninstall(): void
{
$ext = new \Model_Extension();
$ext->loadBean(new \DummyBean());
$ext->type = 'mod';
$ext->name = 'extensionTest';
$dbMock = $this->getMockBuilder('\Box_Database')->getMock();
$dbMock->expects($this->atLeastOnce())
->method('trash');
$modMock = $this->getMockBuilder('\Box_Mod')->disableOriginalConstructor()->getMock();
$modMock->expects($this->atLeastOnce())
@@ -502,13 +458,14 @@ class ServiceTest extends \BBTestCase
$di = new \Pimple\Container();
$di['db'] = $dbMock;
$di['logger'] = new \Box_Log();
$di['mod'] = $di->protect(fn ($name): \PHPUnit\Framework\MockObject\MockObject => $modMock);
$di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $staffService);
$this->service->setDi($di);
$result = $this->service->deactivate($ext);
$result = $this->service->uninstall('mod', 'Branding');
$this->assertTrue($result);
}
@@ -529,7 +486,7 @@ class ServiceTest extends \BBTestCase
$this->service->setDi($di);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Coudn\'t find a valid download URL for the extension.');
$this->expectExceptionMessage('Couldn\'t find a valid download URL for the extension.');
$this->service->downloadAndExtract('mod', 'extensionId');
}