mirror of
https://github.com/BookStackApp/BookStack.git
synced 2026-02-06 19:06:02 +03:00
Compare commits
12 Commits
v25.12.3
...
further_th
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d3d0a4a07 | ||
|
|
5038d124e1 | ||
|
|
f7890c2dd9 | ||
|
|
45ae03ceac | ||
|
|
aa0a8dda11 | ||
|
|
120ee38383 | ||
|
|
cd84074cdf | ||
|
|
4949520194 | ||
|
|
1b17bb3929 | ||
|
|
9fcfc762ec | ||
|
|
c32b1686a9 | ||
|
|
36649a6188 |
@@ -4,6 +4,8 @@ namespace BookStack\App\Providers;
|
||||
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Theming\ThemeService;
|
||||
use BookStack\Theming\ThemeViews;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class ThemeServiceProvider extends ServiceProvider
|
||||
@@ -24,7 +26,23 @@ class ThemeServiceProvider extends ServiceProvider
|
||||
{
|
||||
// Boot up the theme system
|
||||
$themeService = $this->app->make(ThemeService::class);
|
||||
$viewFactory = $this->app->make('view');
|
||||
if (!$themeService->getTheme()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$themeService->loadModules();
|
||||
$themeService->readThemeActions();
|
||||
$themeService->dispatch(ThemeEvents::APP_BOOT, $this->app);
|
||||
|
||||
$themeViews = new ThemeViews();
|
||||
$themeService->dispatch(ThemeEvents::THEME_REGISTER_VIEWS, $themeViews);
|
||||
$themeViews->registerViewPathsForTheme($viewFactory->getFinder(), $themeService->getModules());
|
||||
if ($themeViews->hasRegisteredViews()) {
|
||||
$viewFactory->share('__themeViews', $themeViews);
|
||||
Blade::directive('include', function ($expression) {
|
||||
return "<?php echo \$__themeViews->handleViewInclude({$expression}, array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1])); ?>";
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,8 +81,7 @@ function setting(?string $key = null, mixed $default = null): mixed
|
||||
|
||||
/**
|
||||
* Get a path to a theme resource.
|
||||
* Returns null if a theme is not configured and
|
||||
* therefore a full path is not available for use.
|
||||
* Returns null if a theme is not configured, and therefore a full path is not available for use.
|
||||
*/
|
||||
function theme_path(string $path = ''): ?string
|
||||
{
|
||||
|
||||
@@ -8,12 +8,6 @@
|
||||
* Do not edit this file unless you're happy to maintain any changes yourself.
|
||||
*/
|
||||
|
||||
// Join up possible view locations
|
||||
$viewPaths = [realpath(base_path('resources/views'))];
|
||||
if ($theme = env('APP_THEME', false)) {
|
||||
array_unshift($viewPaths, base_path('themes/' . $theme));
|
||||
}
|
||||
|
||||
return [
|
||||
|
||||
// App theme
|
||||
@@ -26,7 +20,7 @@ return [
|
||||
// Most templating systems load templates from disk. Here you may specify
|
||||
// an array of paths that should be checked for your views. Of course
|
||||
// the usual Laravel view path has already been registered for you.
|
||||
'paths' => $viewPaths,
|
||||
'paths' => [realpath(base_path('resources/views'))],
|
||||
|
||||
// Compiled View Path
|
||||
// This option determines where all the compiled Blade templates will be
|
||||
|
||||
305
app/Console/Commands/InstallModuleCommand.php
Normal file
305
app/Console/Commands/InstallModuleCommand.php
Normal file
@@ -0,0 +1,305 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Console\Commands;
|
||||
|
||||
use BookStack\Http\HttpRequestService;
|
||||
use BookStack\Theming\ThemeModule;
|
||||
use BookStack\Theming\ThemeModuleException;
|
||||
use BookStack\Theming\ThemeModuleManager;
|
||||
use BookStack\Theming\ThemeModuleZip;
|
||||
use GuzzleHttp\Psr7\Request;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class InstallModuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'bookstack:install-module
|
||||
{location : The URL or path of the module file}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Install a module to the currently configured theme';
|
||||
|
||||
protected array $cleanupActions = [];
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$location = $this->argument('location');
|
||||
|
||||
// Get the ZIP file containing the module files
|
||||
$zipPath = $this->getPathToZip($location);
|
||||
if (!$zipPath) {
|
||||
$this->cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Validate module zip file (metadata, size, etc...) and get module instance
|
||||
$zip = new ThemeModuleZip($zipPath);
|
||||
$themeModule = $this->validateAndGetModuleInfoFromZip($zip);
|
||||
if (!$themeModule) {
|
||||
$this->cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Get the theme folder in use, attempting to create one if no active theme in use
|
||||
$themeFolder = $this->getThemeFolder();
|
||||
if (!$themeFolder) {
|
||||
$this->cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Get the modules folder of the theme, attempting to create it if not existing,
|
||||
// and create a new module manager instance.
|
||||
$moduleFolder = $this->getModuleFolder($themeFolder);
|
||||
if (!$moduleFolder) {
|
||||
$this->cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
$manager = new ThemeModuleManager($moduleFolder);
|
||||
|
||||
// Handle existing modules with the same name
|
||||
$exitingModulesWithName = $manager->getByName($themeModule->name);
|
||||
$shouldContinue = $this->handleExistingModulesWithSameName($exitingModulesWithName, $manager);
|
||||
if (!$shouldContinue) {
|
||||
$this->cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Extract module ZIP into the theme modules folder
|
||||
try {
|
||||
$newModule = $manager->addFromZip($themeModule->name, $zip);
|
||||
} catch (ThemeModuleException $exception) {
|
||||
$this->error("ERROR: Failed to install module with error: {$exception->getMessage()}");
|
||||
$this->cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
$this->info("Module \"{$newModule->name}\" ({$newModule->getVersion()}) successfully installed!");
|
||||
$this->info("Install location: {$moduleFolder}/{$newModule->folderName}");
|
||||
$this->cleanup();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ThemeModule[] $existingModules
|
||||
*/
|
||||
protected function handleExistingModulesWithSameName(array $existingModules, ThemeModuleManager $manager): bool
|
||||
{
|
||||
if (count($existingModules) === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->warn("The following modules already exist with the same name:");
|
||||
foreach ($existingModules as $folder => $module) {
|
||||
$this->line("{$module->name} ({$folder}:{$module->getVersion()}) - {$module->description}");
|
||||
}
|
||||
$this->line('');
|
||||
|
||||
$choices = ['Cancel module install', 'Add alongside existing module'];
|
||||
if (count($existingModules) === 1) {
|
||||
$choices[] = 'Replace existing module';
|
||||
}
|
||||
$choice = $this->choice("What would you like to do?", $choices, 0, null, false);
|
||||
if ($choice === 'Cancel module install') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($choice === 'Replace existing module') {
|
||||
$existingModuleFolder = array_key_first($existingModules);
|
||||
$this->info("Replacing existing module in {$existingModuleFolder} folder");
|
||||
$manager->deleteModuleFolder($existingModuleFolder);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function getModuleFolder(string $themeFolder): string|null
|
||||
{
|
||||
$path = $themeFolder . DIRECTORY_SEPARATOR . 'modules';
|
||||
|
||||
if (file_exists($path) && !is_dir($path)) {
|
||||
$this->error("ERROR: Cannot create a modules folder, file already exists at {$path}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!file_exists($path)) {
|
||||
$created = mkdir($path, 0755, true);
|
||||
if (!$created) {
|
||||
$this->error("ERROR: Failed to create a modules folder at {$path}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
protected function getThemeFolder(): string|null
|
||||
{
|
||||
$path = theme_path('');
|
||||
if (!$path || !is_dir($path)) {
|
||||
$shouldCreate = $this->confirm('No active theme folder found, would you like to create one?');
|
||||
if (!$shouldCreate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$folder = 'custom';
|
||||
while (file_exists(base_path("themes" . DIRECTORY_SEPARATOR . $folder))) {
|
||||
$folder = 'custom-' . Str::random(4);
|
||||
}
|
||||
|
||||
$path = base_path("themes/{$folder}");
|
||||
$created = mkdir($path, 0755, true);
|
||||
if (!$created) {
|
||||
$this->error('Failed to create a theme folder to use. This may be a permissions issue. Try manually configuring an active theme');
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->info("Created theme folder at {$path}");
|
||||
$this->warn("You will need to set APP_THEME={$folder} in your BookStack env configuration to enable this theme!");
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
protected function validateAndGetModuleInfoFromZip(ThemeModuleZip $zip): ThemeModule|null
|
||||
{
|
||||
if (!$zip->exists()) {
|
||||
$this->error("ERROR: Cannot open ZIP file at {$zip->getPath()}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($zip->getContentsSize() > (50 * 1024 * 1024)) {
|
||||
$this->error("ERROR: Module ZIP file contents are too large. Maximum size is 50MB");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$themeModule = $zip->getModuleInstance();
|
||||
} catch (ThemeModuleException $exception) {
|
||||
$this->error("ERROR: Failed to read module metadata with error: {$exception->getMessage()}");
|
||||
return null;
|
||||
}
|
||||
|
||||
return $themeModule;
|
||||
}
|
||||
|
||||
protected function downloadModuleFile(string $location): string|null
|
||||
{
|
||||
$httpRequests = app()->make(HttpRequestService::class);
|
||||
$client = $httpRequests->buildClient(30, ['stream' => true]);
|
||||
$originalUrl = parse_url($location);
|
||||
$currentLocation = $location;
|
||||
$maxRedirects = 3;
|
||||
$redirectCount = 0;
|
||||
|
||||
// Follow redirects up to 3 times for the same hostname
|
||||
do {
|
||||
$resp = $client->sendRequest(new Request('GET', $currentLocation));
|
||||
$statusCode = $resp->getStatusCode();
|
||||
|
||||
if ($statusCode >= 300 && $statusCode < 400 && $redirectCount < $maxRedirects) {
|
||||
$redirectLocation = $resp->getHeaderLine('Location');
|
||||
if ($redirectLocation) {
|
||||
$redirectUrl = parse_url($redirectLocation);
|
||||
if (
|
||||
($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
|
||||
&& ($originalUrl['scheme'] ?? '') === ($redirectUrl['scheme'] ?? '')
|
||||
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '')
|
||||
) {
|
||||
$currentLocation = $redirectLocation;
|
||||
$redirectCount++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
if ($resp->getStatusCode() >= 300) {
|
||||
$this->error("ERROR: Failed to download module from {$location}");
|
||||
$this->error("Download failed with status code {$resp->getStatusCode()}");
|
||||
return null;
|
||||
}
|
||||
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'bookstack_module_');
|
||||
$fileHandle = fopen($tempFile, 'w');
|
||||
$respBody = $resp->getBody();
|
||||
$size = 0;
|
||||
$maxSize = 50 * 1024 * 1024;
|
||||
|
||||
while (!$respBody->eof()) {
|
||||
fwrite($fileHandle, $respBody->read(1024));
|
||||
$size += 1024;
|
||||
if ($size > $maxSize) {
|
||||
fclose($fileHandle);
|
||||
unlink($tempFile);
|
||||
$this->error("ERROR: Module ZIP file is too large. Maximum size is 50MB");
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
fclose($fileHandle);
|
||||
|
||||
$this->cleanupActions[] = function () use ($tempFile) {
|
||||
unlink($tempFile);
|
||||
};
|
||||
|
||||
return $tempFile;
|
||||
}
|
||||
|
||||
protected function getPathToZip(string $location): string|null
|
||||
{
|
||||
$lowerLocation = strtolower($location);
|
||||
$isRemote = str_starts_with($lowerLocation, 'http://') || str_starts_with($lowerLocation, 'https://');
|
||||
|
||||
if ($isRemote) {
|
||||
// Warning about fetching from source
|
||||
$host = parse_url($location, PHP_URL_HOST);
|
||||
$this->warn("This will download a module from {$host}. Modules can contain code which would have the ability to do anything on the BookStack host server.\nYou should only install modules from trusted sources.");
|
||||
$trustHost = $this->confirm('Are you sure you trust this source?');
|
||||
if (!$trustHost) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if the connection is http. If so, warn the user.
|
||||
if (str_starts_with($lowerLocation, 'http://')) {
|
||||
$this->warn("You are downloading a module from an insecure HTTP source.\nWe recommend only using HTTPS sources to avoid various security risks.");
|
||||
if (!$this->confirm('Are you sure you want to continue without HTTPS?')) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Download ZIP and get its location
|
||||
return $this->downloadModuleFile($location);
|
||||
}
|
||||
|
||||
// Validate file and get full location
|
||||
$zipPath = realpath($location);
|
||||
if (!$zipPath || !is_file($zipPath)) {
|
||||
$this->error("ERROR: Module file not found at {$location}");
|
||||
return null;
|
||||
}
|
||||
|
||||
return $zipPath;
|
||||
}
|
||||
|
||||
protected function cleanup(): void
|
||||
{
|
||||
foreach ($this->cleanupActions as $action) {
|
||||
$action();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,21 +5,22 @@ namespace BookStack\Theming;
|
||||
use BookStack\Facades\Theme;
|
||||
use BookStack\Http\Controller;
|
||||
use BookStack\Util\FilePathNormalizer;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class ThemeController extends Controller
|
||||
{
|
||||
/**
|
||||
* Serve a public file from the configured theme.
|
||||
*/
|
||||
public function publicFile(string $theme, string $path)
|
||||
public function publicFile(string $theme, string $path): StreamedResponse
|
||||
{
|
||||
$cleanPath = FilePathNormalizer::normalize($path);
|
||||
if ($theme !== Theme::getTheme() || !$cleanPath) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$filePath = theme_path("public/{$cleanPath}");
|
||||
if (!file_exists($filePath)) {
|
||||
$filePath = Theme::findFirstFile("public/{$cleanPath}");
|
||||
if (!$filePath) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
|
||||
@@ -134,6 +134,16 @@ class ThemeEvents
|
||||
*/
|
||||
const ROUTES_REGISTER_WEB_AUTH = 'routes_register_web_auth';
|
||||
|
||||
|
||||
/**
|
||||
* Theme register views event.
|
||||
* Called by the theme system when a theme is active, so that custom view templates can be registered
|
||||
* to be rendered in addition to existing app views.
|
||||
*
|
||||
* @param \BookStack\Theming\ThemeViews $themeViews
|
||||
*/
|
||||
const THEME_REGISTER_VIEWS = 'theme_register_views';
|
||||
|
||||
/**
|
||||
* Web before middleware action.
|
||||
* Runs before the request is handled but after all other middleware apart from those
|
||||
|
||||
59
app/Theming/ThemeModule.php
Normal file
59
app/Theming/ThemeModule.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
readonly class ThemeModule
|
||||
{
|
||||
public function __construct(
|
||||
public string $name,
|
||||
public string $description,
|
||||
public string $version,
|
||||
public string $folderName,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ThemeModule instance from JSON data.
|
||||
*
|
||||
* @throws ThemeModuleException
|
||||
*/
|
||||
public static function fromJson(array $data, string $folderName): self
|
||||
{
|
||||
if (empty($data['name']) || !is_string($data['name'])) {
|
||||
throw new ThemeModuleException("Module in folder \"{$folderName}\" is missing a valid 'name' property");
|
||||
}
|
||||
|
||||
if (!isset($data['description']) || !is_string($data['description'])) {
|
||||
throw new ThemeModuleException("Module in folder \"{$folderName}\" is missing a valid 'description' property");
|
||||
}
|
||||
|
||||
if (!isset($data['version']) || !is_string($data['version'])) {
|
||||
throw new ThemeModuleException("Module in folder \"{$folderName}\" is missing a valid 'version' property");
|
||||
}
|
||||
|
||||
if (!preg_match('/^v?\d+\.\d+\.\d+(-.*)?$/', $data['version'])) {
|
||||
throw new ThemeModuleException("Module in folder \"{$folderName}\" has an invalid 'version' format. Expected semantic version format like '1.0.0' or 'v1.0.0'");
|
||||
}
|
||||
|
||||
return new self(
|
||||
name: $data['name'],
|
||||
description: $data['description'],
|
||||
version: $data['version'],
|
||||
folderName: $folderName,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a path for a file within this module.
|
||||
*/
|
||||
public function path($path = ''): string
|
||||
{
|
||||
$component = trim($path, '/');
|
||||
return theme_path("modules/{$this->folderName}/{$component}");
|
||||
}
|
||||
|
||||
public function getVersion(): string
|
||||
{
|
||||
return str_starts_with($this->version, 'v') ? $this->version : 'v' . $this->version;
|
||||
}
|
||||
}
|
||||
7
app/Theming/ThemeModuleException.php
Normal file
7
app/Theming/ThemeModuleException.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
class ThemeModuleException extends \Exception
|
||||
{
|
||||
}
|
||||
133
app/Theming/ThemeModuleManager.php
Normal file
133
app/Theming/ThemeModuleManager.php
Normal file
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ThemeModuleManager
|
||||
{
|
||||
/** @var array<string, ThemeModule>|null */
|
||||
protected array|null $loadedModules = null;
|
||||
|
||||
public function __construct(
|
||||
protected string $modulesFolderPath
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ThemeModule>
|
||||
*/
|
||||
public function getByName(string $name): array
|
||||
{
|
||||
return array_filter($this->load(), fn(ThemeModule $module) => $module->name === $name);
|
||||
}
|
||||
|
||||
public function deleteModuleFolder(string $moduleFolderName): void
|
||||
{
|
||||
$modules = $this->load();
|
||||
$module = $modules[$moduleFolderName] ?? null;
|
||||
if (!$module) {
|
||||
return;
|
||||
}
|
||||
|
||||
$moduleFolderPath = $module->path('');
|
||||
if (!file_exists($moduleFolderPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->deleteDirectoryRecursively($moduleFolderPath);
|
||||
unset($this->loadedModules[$moduleFolderName]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ThemeModuleException
|
||||
*/
|
||||
public function addFromZip(string $name, ThemeModuleZip $zip): ThemeModule
|
||||
{
|
||||
$baseFolderName = Str::limit(Str::slug($name), 20);
|
||||
$folderName = $baseFolderName;
|
||||
while (!$baseFolderName || file_exists($this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName)) {
|
||||
$folderName = ($baseFolderName ?: 'mod') . '-' . Str::random(4);
|
||||
}
|
||||
|
||||
$folderPath = $this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName;
|
||||
$zip->extractTo($folderPath);
|
||||
|
||||
$module = $this->loadFromFolder($folderName);
|
||||
if (!$module) {
|
||||
throw new ThemeModuleException("Failed to load module from zip file after extraction");
|
||||
}
|
||||
|
||||
return $module;
|
||||
}
|
||||
|
||||
protected function deleteDirectoryRecursively(string $path): void
|
||||
{
|
||||
$items = array_diff(scandir($path), ['.', '..']);
|
||||
foreach ($items as $item) {
|
||||
$itemPath = $path . DIRECTORY_SEPARATOR . $item;
|
||||
if (is_dir($itemPath)) {
|
||||
$this->deleteDirectoryRecursively($itemPath);
|
||||
} else {
|
||||
$deleted = unlink($itemPath);
|
||||
if (!$deleted) {
|
||||
throw new ThemeModuleException("Failed to delete file at \"{$itemPath}\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
rmdir($path);
|
||||
}
|
||||
|
||||
public function load(): array
|
||||
{
|
||||
if ($this->loadedModules !== null) {
|
||||
return $this->loadedModules;
|
||||
}
|
||||
|
||||
if (!is_dir($this->modulesFolderPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$subFolders = array_filter(scandir($this->modulesFolderPath), function ($item) {
|
||||
return $item !== '.' && $item !== '..' && is_dir($this->modulesFolderPath . DIRECTORY_SEPARATOR . $item);
|
||||
});
|
||||
|
||||
$modules = [];
|
||||
|
||||
foreach ($subFolders as $folderName) {
|
||||
$module = $this->loadFromFolder($folderName);
|
||||
if ($module) {
|
||||
$modules[$folderName] = $module;
|
||||
}
|
||||
}
|
||||
|
||||
$this->loadedModules = $modules;
|
||||
|
||||
return $modules;
|
||||
}
|
||||
|
||||
protected function loadFromFolder(string $folderName): ThemeModule|null
|
||||
{
|
||||
$moduleJsonFile = $this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName . DIRECTORY_SEPARATOR . 'bookstack-module.json';
|
||||
if (!file_exists($moduleJsonFile)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$jsonContent = file_get_contents($moduleJsonFile);
|
||||
$jsonData = json_decode($jsonContent, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new ThemeModuleException("Invalid JSON in module file at \"{$moduleJsonFile}\": " . json_last_error_msg());
|
||||
}
|
||||
|
||||
$module = ThemeModule::fromJson($jsonData, $folderName);
|
||||
} catch (ThemeModuleException $exception) {
|
||||
throw $exception;
|
||||
} catch (\Exception $exception) {
|
||||
throw new ThemeModuleException("Failed loading module from \"{$moduleJsonFile}\" with error: {$exception->getMessage()}");
|
||||
}
|
||||
|
||||
return $module;
|
||||
}
|
||||
}
|
||||
98
app/Theming/ThemeModuleZip.php
Normal file
98
app/Theming/ThemeModuleZip.php
Normal file
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
use ZipArchive;
|
||||
|
||||
readonly class ThemeModuleZip
|
||||
{
|
||||
public function __construct(
|
||||
protected string $path
|
||||
) {
|
||||
}
|
||||
|
||||
public function extractTo(string $destinationPath): void
|
||||
{
|
||||
$zip = new ZipArchive();
|
||||
$zip->open($this->path);
|
||||
$zip->extractTo($destinationPath);
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the module's JSON metadata to read it into a ThemeModule instance.
|
||||
* @throws ThemeModuleException
|
||||
*/
|
||||
public function getModuleInstance(): ThemeModule
|
||||
{
|
||||
$zip = new ZipArchive();
|
||||
$open = $zip->open($this->path);
|
||||
if ($open !== true) {
|
||||
throw new ThemeModuleException("Unable to open zip file at {$this->path}");
|
||||
}
|
||||
|
||||
$moduleJsonText = $zip->getFromName('bookstack-module.json');
|
||||
$zip->close();
|
||||
|
||||
if ($moduleJsonText === false) {
|
||||
throw new ThemeModuleException("bookstack-module.json not found within module ZIP at {$this->path}");
|
||||
}
|
||||
|
||||
$moduleJson = json_decode($moduleJsonText, true);
|
||||
if ($moduleJson === null) {
|
||||
throw new ThemeModuleException("Could not read JSON from bookstack-module.json within module ZIP at {$this->path}");
|
||||
}
|
||||
|
||||
return ThemeModule::fromJson($moduleJson, '_temp');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the zip file.
|
||||
*/
|
||||
public function getPath(): string
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the zip file exists and that it appears to be a valid zip file.
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
if (!file_exists($this->path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$zip = new ZipArchive();
|
||||
$open = $zip->open($this->path, ZipArchive::RDONLY);
|
||||
if ($open === true) {
|
||||
$zip->close();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the total size of the zip file contents when uncompressed.
|
||||
*/
|
||||
public function getContentsSize(): int
|
||||
{
|
||||
$zip = new ZipArchive();
|
||||
|
||||
if ($zip->open($this->path) !== true) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$totalSize = 0;
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$stat = $zip->statIndex($i);
|
||||
if ($stat !== false) {
|
||||
$totalSize += $stat['size'];
|
||||
}
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
return $totalSize;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use BookStack\Access\SocialDriverManager;
|
||||
use BookStack\Exceptions\ThemeException;
|
||||
use Illuminate\Console\Application;
|
||||
use Illuminate\Console\Application as Artisan;
|
||||
use Illuminate\View\FileViewFinder;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
|
||||
class ThemeService
|
||||
@@ -15,6 +16,11 @@ class ThemeService
|
||||
*/
|
||||
protected array $listeners = [];
|
||||
|
||||
/**
|
||||
* @var array<string, ThemeModule>
|
||||
*/
|
||||
protected array $modules = [];
|
||||
|
||||
/**
|
||||
* Get the currently configured theme.
|
||||
* Returns an empty string if not configured.
|
||||
@@ -76,20 +82,71 @@ class ThemeService
|
||||
}
|
||||
|
||||
/**
|
||||
* Read any actions from the set theme path if the 'functions.php' file exists.
|
||||
* Read any actions from the 'functions.php' file of the active theme or its modules.
|
||||
*/
|
||||
public function readThemeActions(): void
|
||||
{
|
||||
$themeActionsFile = theme_path('functions.php');
|
||||
if ($themeActionsFile && file_exists($themeActionsFile)) {
|
||||
$moduleFunctionFiles = array_map(function (ThemeModule $module): string {
|
||||
return $module->path('functions.php');
|
||||
}, $this->modules);
|
||||
$allFunctionFiles = array_merge(array_values($moduleFunctionFiles), [theme_path('functions.php')]);
|
||||
$filteredFunctionFiles = array_filter($allFunctionFiles, function (string $file): bool {
|
||||
return $file && file_exists($file);
|
||||
});
|
||||
|
||||
foreach ($filteredFunctionFiles as $functionFile) {
|
||||
try {
|
||||
require $themeActionsFile;
|
||||
require $functionFile;
|
||||
} catch (\Error $exception) {
|
||||
throw new ThemeException("Failed loading theme functions file at \"{$themeActionsFile}\" with error: {$exception->getMessage()}");
|
||||
throw new ThemeException("Failed loading theme functions file at \"{$functionFile}\" with error: {$exception->getMessage()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the modules folder and load in any valid theme modules.
|
||||
* @throws ThemeModuleException
|
||||
*/
|
||||
public function loadModules(): void
|
||||
{
|
||||
$modulesFolder = theme_path('modules');
|
||||
if (!$modulesFolder) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->modules = (new ThemeModuleManager($modulesFolder))->load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all loaded theme modules.
|
||||
* @return array<string, ThemeModule>
|
||||
*/
|
||||
public function getModules(): array
|
||||
{
|
||||
return $this->modules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look for a specific file within the theme or its modules.
|
||||
* Returns the first file found or null if not found.
|
||||
*/
|
||||
public function findFirstFile(string $path): ?string
|
||||
{
|
||||
$themePath = theme_path($path);
|
||||
if (file_exists($themePath)) {
|
||||
return $themePath;
|
||||
}
|
||||
|
||||
foreach ($this->modules as $module) {
|
||||
$customizedFile = $module->path($path);
|
||||
if (file_exists($customizedFile)) {
|
||||
return $customizedFile;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see SocialDriverManager::addSocialDriver
|
||||
*/
|
||||
|
||||
104
app/Theming/ThemeViews.php
Normal file
104
app/Theming/ThemeViews.php
Normal file
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
use BookStack\Exceptions\ThemeException;
|
||||
use Illuminate\View\FileViewFinder;
|
||||
|
||||
class ThemeViews
|
||||
{
|
||||
/**
|
||||
* @var array<string, array<string, int>>
|
||||
*/
|
||||
protected array $beforeViews = [];
|
||||
|
||||
/**
|
||||
* @var array<string, array<string, int>>
|
||||
*/
|
||||
protected array $afterViews = [];
|
||||
|
||||
/**
|
||||
* Register any extra paths for where we may expect views to be located
|
||||
* with the provided FileViewFinder, to make custom views available for use.
|
||||
* @param ThemeModule[] $modules
|
||||
*/
|
||||
public function registerViewPathsForTheme(FileViewFinder $finder, array $modules): void
|
||||
{
|
||||
foreach ($modules as $module) {
|
||||
$moduleViewsPath = $module->path('views');
|
||||
if (file_exists($moduleViewsPath) && is_dir($moduleViewsPath)) {
|
||||
$finder->prependLocation($moduleViewsPath);
|
||||
}
|
||||
}
|
||||
|
||||
$finder->prependLocation(theme_path());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide the response for a blade template view include.
|
||||
*/
|
||||
public function handleViewInclude(string $viewPath, array $data = []): string
|
||||
{
|
||||
if (!$this->hasRegisteredViews()) {
|
||||
return view()->make($viewPath, $data)->render();
|
||||
}
|
||||
|
||||
$viewsContent = [
|
||||
...$this->renderViewSets($this->beforeViews[$viewPath] ?? [], $data),
|
||||
view()->make($viewPath, $data)->render(),
|
||||
...$this->renderViewSets($this->afterViews[$viewPath] ?? [], $data),
|
||||
];
|
||||
|
||||
return implode("\n", $viewsContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom view to be rendered before the given target view is included in the template system.
|
||||
*/
|
||||
public function renderBefore(string $targetView, string $localView, int $priority = 50): void
|
||||
{
|
||||
$this->registerAdjacentView($this->beforeViews, $targetView, $localView, $priority);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom view to be rendered after the given target view is included in the template system.
|
||||
*/
|
||||
public function renderAfter(string $targetView, string $localView, int $priority = 50): void
|
||||
{
|
||||
$this->registerAdjacentView($this->afterViews, $targetView, $localView, $priority);
|
||||
}
|
||||
|
||||
public function hasRegisteredViews(): bool
|
||||
{
|
||||
return !empty($this->beforeViews) && !empty($this->afterViews);
|
||||
}
|
||||
|
||||
protected function registerAdjacentView(array &$location, string $targetView, string $localView, int $priority = 50): void
|
||||
{
|
||||
$viewPath = theme_path($localView . '.blade.php');
|
||||
if (!file_exists($viewPath)) {
|
||||
throw new ThemeException("Expected registered view file at \"{$viewPath}\" does not exist");
|
||||
}
|
||||
|
||||
if (!isset($location[$targetView])) {
|
||||
$location[$targetView] = [];
|
||||
}
|
||||
$location[$targetView][$viewPath] = $priority;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, int> $viewSet
|
||||
* @return string[]
|
||||
*/
|
||||
protected function renderViewSets(array $viewSet, array $data): array
|
||||
{
|
||||
$paths = array_keys($viewSet);
|
||||
usort($paths, function (string $a, string $b) use ($viewSet) {
|
||||
return $viewSet[$a] <=> $viewSet[$b];
|
||||
});
|
||||
|
||||
return array_map(function (string $viewPath) use ($data) {
|
||||
return view()->file($viewPath, $data)->render();
|
||||
}, $paths);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace BookStack\Translation;
|
||||
|
||||
use BookStack\Facades\Theme;
|
||||
use Illuminate\Translation\FileLoader as BaseLoader;
|
||||
|
||||
class FileLoader extends BaseLoader
|
||||
@@ -12,11 +13,6 @@ class FileLoader extends BaseLoader
|
||||
* Extends Laravel's translation FileLoader to look in multiple directories
|
||||
* so that we can load in translation overrides from the theme file if wanted.
|
||||
*
|
||||
* Note: As of using Laravel 10, this may now be redundant since Laravel's
|
||||
* file loader supports multiple paths. This needs further testing though
|
||||
* to confirm if Laravel works how we expect, since we specifically need
|
||||
* the theme folder to be able to partially override core lang files.
|
||||
*
|
||||
* @param string $locale
|
||||
* @param string $group
|
||||
* @param string|null $namespace
|
||||
@@ -32,9 +28,18 @@ class FileLoader extends BaseLoader
|
||||
if (is_null($namespace) || $namespace === '*') {
|
||||
$themePath = theme_path('lang');
|
||||
$themeTranslations = $themePath ? $this->loadPaths([$themePath], $locale, $group) : [];
|
||||
$originalTranslations = $this->loadPaths($this->paths, $locale, $group);
|
||||
|
||||
return array_merge($originalTranslations, $themeTranslations);
|
||||
$modules = Theme::getModules();
|
||||
$moduleTranslations = [];
|
||||
foreach ($modules as $module) {
|
||||
$modulePath = $module->path('lang');
|
||||
if (file_exists($modulePath)) {
|
||||
$moduleTranslations = array_merge($moduleTranslations, $this->loadPaths([$modulePath], $locale, $group));
|
||||
}
|
||||
}
|
||||
|
||||
$originalTranslations = $this->loadPaths($this->paths, $locale, $group);
|
||||
return array_merge($originalTranslations, $moduleTranslations, $themeTranslations);
|
||||
}
|
||||
|
||||
return $this->loadNamespaced($locale, $group, $namespace);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace BookStack\Util;
|
||||
|
||||
use BookStack\Facades\Theme;
|
||||
|
||||
class SvgIcon
|
||||
{
|
||||
public function __construct(
|
||||
@@ -23,12 +25,9 @@ class SvgIcon
|
||||
$attrString .= $attrName . '="' . $attr . '" ';
|
||||
}
|
||||
|
||||
$iconPath = resource_path('icons/' . $this->name . '.svg');
|
||||
$themeIconPath = theme_path('icons/' . $this->name . '.svg');
|
||||
|
||||
if ($themeIconPath && file_exists($themeIconPath)) {
|
||||
$iconPath = $themeIconPath;
|
||||
} elseif (!file_exists($iconPath)) {
|
||||
$defaultIconPath = resource_path('icons/' . $this->name . '.svg');
|
||||
$iconPath = Theme::findFirstFile("icons/{$this->name}.svg") ?? $defaultIconPath;
|
||||
if (!file_exists($iconPath)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +99,41 @@ Theme::listen(ThemeEvents::APP_BOOT, function($app) {
|
||||
});
|
||||
```
|
||||
|
||||
## Custom View Registration Example
|
||||
|
||||
Using the logical theme system, you can register custom views to be rendered before/after other existing views, providing a flexible way to add content without needing to override and/or replicate existing content. This is done by listening to the `THEME_REGISTER_VIEWS`.
|
||||
|
||||
**Note:** You don't need to use this to override existing views, or register whole new main views to use, since that's done automatically based on their existence. This is just for advanced capabilities like inserting before/after existing views.
|
||||
|
||||
This event provides a `ThemeViews` instance which has the following methods made available:
|
||||
|
||||
- `renderBefore(string $targetView, string $localView, int $priority)`
|
||||
- `renderAfter(string $targetView, string $localView, int $priority)`
|
||||
|
||||
The target view is the name of that which we want to insert our custom view relative to.
|
||||
The local view is the name of the view we want to add and render.
|
||||
The priority provides a suggestion to the ordering of view display, with lower numbers being shown first. This defaults to 50 if not provided.
|
||||
|
||||
Here's an example of this in use:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use BookStack\Facades\Theme;
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Theming\ThemeViews;
|
||||
|
||||
Theme::listen(ThemeEvents::THEME_REGISTER_VIEWS, function (ThemeViews $themeViews) {
|
||||
$themeViews->renderBefore('layouts.parts.header', 'welcome-banner', 4);
|
||||
$themeViews->renderAfter('layouts.parts.header', 'information-alert');
|
||||
$themeViews->renderAfter('layouts.parts.header', 'additions.password-notice', 20);
|
||||
});
|
||||
```
|
||||
|
||||
In this example, we're inserting custom views before and after the main header bar.
|
||||
BookStack will look for a `welcome-banner.blade.php` file within our theme folder (or a theme module view folder) to render before the header. It'll look for the `information-alert.blade.php` and `additions/password-notice.blade.php` views to render afterwards.
|
||||
The password notice will be shown above the information alert view, since it has a specified priority of 20, whereas the information alert view would default to a priority of 50.
|
||||
|
||||
## Custom Command Registration Example
|
||||
|
||||
The logical theme system supports adding custom [artisan commands](https://laravel.com/docs/8.x/artisan) to BookStack.
|
||||
|
||||
68
dev/docs/theme-system-modules.md
Normal file
68
dev/docs/theme-system-modules.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Theme System Modules
|
||||
|
||||
A theme system module is a collection of customizations using the [visual](visual-theme-system.md) and [logical](logical-theme-system.md) theme systems, provided along with some metadata, that can be installed alongside other modules within a theme. They can effectively be thought of as "plugins" or "extensions" that can be applied in addition to any customizations in the active theme.
|
||||
|
||||
### Module Location
|
||||
|
||||
Modules are contained within a folder themselves, which should be located inside a `modules` folder within a [BookStack theme folder](visual-theme-system.md#getting-started).
|
||||
As an example, starting from the `themes/` top-level folder of a BookStack instance:
|
||||
|
||||
```txt
|
||||
themes
|
||||
└── my-theme
|
||||
└── modules
|
||||
├── module-a
|
||||
│ └── bookstack-module.json
|
||||
└── module-b
|
||||
└── bookstack-module.json
|
||||
```
|
||||
|
||||
### Module Format
|
||||
|
||||
A module exists as a folder in the location [as detailed above](#module-location).
|
||||
The content within the module folder should then follow this format:
|
||||
|
||||
- `bookstack-module.json` - REQUIRED - A JSON file containing [the metadata](#module-json-metadata) for the module.
|
||||
- `functions.php` - OPTIONAL - A PHP file containing code for the [logical theme system](logical-theme-system.md).
|
||||
- `icons/` - OPTIONAL - A folder containing any icons to use as per [the visual theme system](visual-theme-system.md#customizing-icons).
|
||||
- `lang/` - OPTIONAL - A folder containing any language files to use as per [the visual theme system](visual-theme-system.md#customizing-text-content).
|
||||
- `public/` - OPTIONAL - A folder containing any files to expose into public web-space as per [the visual theme system](visual-theme-system.md#publicly-accessible-files).
|
||||
- `views/` - OPTIONAL - A folder containing any view additions or overrides as per [the visual theme system](visual-theme-system.md#customizing-view-files).
|
||||
|
||||
You can create additional directories/files for your own needs within the module, but ideally name them something unique to prevent conflicts with the above structure.
|
||||
|
||||
### Module JSON Metadata
|
||||
|
||||
Modules are required to have a `bookstack-module.json` file in the top level directory of the module.
|
||||
This must be a JSON file with the following properties:
|
||||
|
||||
- `name` - string - An (ideally unique) name for the module.
|
||||
- `description` - string - A short description of the module.
|
||||
- `version` - string - A string version number generally following [semantic versioning](https://semver.org/).
|
||||
- Examples: `v0.4.0`, `4.3.12`, `v0.1.0-beta4`.
|
||||
|
||||
### Customization Order/Precedence
|
||||
|
||||
It's possible that multiple modules may override/customize the same content.
|
||||
Right now, there's no assurance in regard to the order in which modules may be loaded.
|
||||
Generally they will be used/searched in order of their module folder name, but this is not assured and should not be relied upon.
|
||||
|
||||
It's also possible that modules customize the same content as the configured theme.
|
||||
In this scenario, the theme takes precedence. Modules are designed to be more portable and instance abstract, whereas the theme folder would typically be specific to the instance.
|
||||
This allows the theme to be used to customize or override module content for the BookStack instance, without altering the module code itself.
|
||||
|
||||
### Module Best Practices
|
||||
|
||||
Here are some general best practices when it comes to creating modules:
|
||||
|
||||
- Use a unique name and clear description so the user can understand the purpose of the module.
|
||||
- Increment the metadata version on change, keeping to [semver](https://semver.org/) to indicate compatibility of new versions.
|
||||
- Where possible, prefer to [insert views before/after](logical-theme-system.md#custom-view-registration-example) instead of overriding existing views, to reduce likelihood of conflicts or update troubles.
|
||||
|
||||
### Distribution Format
|
||||
|
||||
Modules are expected to be distributed as a compressed ZIP file, where the ZIP contents follow that of a module folder.
|
||||
BookStack provides a `php artisan bookstack:install-module` command which allows modules to be installed from these ZIP files, either from a local path or from a web URL.
|
||||
Currently, there's a hardcoded total filesize limit of 50MB for module contents installed via this method.
|
||||
|
||||
There is not yet any direct update mechanism for modules, although this is something we may introduce in the future.
|
||||
@@ -4,7 +4,7 @@ BookStack allows visual customization via the theme system which enables you to
|
||||
|
||||
This is part of the theme system alongside the [logical theme system](./logical-theme-system.md).
|
||||
|
||||
**Note:** This theme system itself is maintained and supported but usages of this system, including the files you are able to override, are not considered stable and may change upon any update. You should test any customizations made after updates.
|
||||
**Note:** This theme system itself is maintained and supported, but usages of this system, including the files you are able to override, are not considered stable and may change upon any update. You should test any customizations made after updates.
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -18,6 +18,9 @@ You'll need to tell BookStack to use your theme via the `APP_THEME` option in yo
|
||||
Content placed in your `themes/<theme_name>/` folder will override the original view files found in the `resources/views` folder. These files are typically [Laravel Blade](https://laravel.com/docs/10.x/blade) files.
|
||||
As an example, I could override the `resources/views/books/parts/list-item.blade.php` file with my own template at the path `themes/<theme_name>/books/parts/list-item.blade.php`.
|
||||
|
||||
In addition to overriding original views, this could be used to add new views for use via the [logical theme system](logical-theme-system.md).
|
||||
By using the `THEME_REGISTER_VIEWS` logical event, you can also register your views to be rendered before/after existing views. An example of this can be found in our [logical theme guidance](logical-theme-system.md#custom-view-registration-example).
|
||||
|
||||
## Customizing Icons
|
||||
|
||||
SVG files placed in a `themes/<theme_name>/icons` folder will override any icons of the same name within `resources/icons`. You'd typically want to follow the format convention of the existing icons, where no XML deceleration is included and no width & height attributes are set, to ensure optimal compatibility.
|
||||
@@ -50,7 +53,7 @@ configured application theme.
|
||||
|
||||
There are some considerations to these publicly served files:
|
||||
|
||||
- Only a predetermined range "web safe" content-types are currently served.
|
||||
- Only a predetermined range of "web safe" content-types are currently served.
|
||||
- This limits running into potential insecure scenarios in serving problematic file types.
|
||||
- A static 1-day cache time it set on files served from this folder.
|
||||
- You can use alternative cache-breaking techniques (change of query string) upon changes if needed.
|
||||
|
||||
289
tests/Commands/InstallModuleCommandTest.php
Normal file
289
tests/Commands/InstallModuleCommandTest.php
Normal file
@@ -0,0 +1,289 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Commands;
|
||||
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
use ZipArchive;
|
||||
|
||||
class InstallModuleCommandTest extends TestCase
|
||||
{
|
||||
public function test_local_module_install_with_active_theme()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$zip = $this->getModuleZipPath();
|
||||
$expectedInstallPath = theme_path('modules/test-module');
|
||||
$this->artisan('bookstack:install-module', ['location' => $zip])
|
||||
->expectsOutput('Module "Test Module" (v1.0.0) successfully installed!')
|
||||
->expectsOutput("Install location: {$expectedInstallPath}")
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertDirectoryExists($expectedInstallPath);
|
||||
$this->assertFileExists($expectedInstallPath . '/bookstack-module.json');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_remote_module_install_with_active_theme()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$zip = $this->getModuleZipPath();
|
||||
|
||||
$http = $this->mockHttpClient([
|
||||
new Response(200, ['Content-Length' => filesize($zip)], file_get_contents($zip))
|
||||
]);
|
||||
$expectedInstallPath = theme_path('modules/test-module');
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
|
||||
->expectsOutput("This will download a module from example.com. Modules can contain code which would have the ability to do anything on the BookStack host server.\nYou should only install modules from trusted sources.")
|
||||
->expectsConfirmation('Are you sure you trust this source?', 'yes')
|
||||
->expectsOutput('Module "Test Module" (v1.0.0) successfully installed!')
|
||||
->expectsOutput("Install location: {$expectedInstallPath}")
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertEquals(1, $http->requestCount());
|
||||
$request = $http->requestAt(0);
|
||||
$this->assertEquals('/test-module.zip', $request->getUri()->getPath());
|
||||
|
||||
$this->assertDirectoryExists($expectedInstallPath);
|
||||
$this->assertFileExists($expectedInstallPath . '/bookstack-module.json');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_remote_http_module_warns_and_prompts_users()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$zip = $this->getModuleZipPath();
|
||||
|
||||
$http = $this->mockHttpClient([
|
||||
new Response(200, ['Content-Length' => filesize($zip)], file_get_contents($zip))
|
||||
]);
|
||||
$expectedInstallPath = theme_path('modules/test-module');
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => 'http://example.com/test-module.zip'])
|
||||
->expectsOutput("This will download a module from example.com. Modules can contain code which would have the ability to do anything on the BookStack host server.\nYou should only install modules from trusted sources.")
|
||||
->expectsConfirmation('Are you sure you trust this source?', 'yes')
|
||||
->expectsOutput("You are downloading a module from an insecure HTTP source.\nWe recommend only using HTTPS sources to avoid various security risks.")
|
||||
->expectsConfirmation('Are you sure you want to continue without HTTPS?', 'yes')
|
||||
->expectsOutput('Module "Test Module" (v1.0.0) successfully installed!')
|
||||
->expectsOutput("Install location: {$expectedInstallPath}")
|
||||
->assertExitCode(0);
|
||||
|
||||
$request = $http->requestAt(0);
|
||||
$this->assertEquals('/test-module.zip', $request->getUri()->getPath());
|
||||
});
|
||||
}
|
||||
|
||||
public function test_remote_module_install_follows_redirects()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$zip = $this->getModuleZipPath();
|
||||
|
||||
$http = $this->mockHttpClient([
|
||||
new Response(302, ['Location' => 'https://example.com/a-test-module.zip']),
|
||||
new Response(200, ['Content-Length' => filesize($zip)], file_get_contents($zip))
|
||||
]);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
|
||||
->expectsConfirmation('Are you sure you trust this source?', 'yes')
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertEquals(2, $http->requestCount());
|
||||
$this->assertEquals('/test-module.zip', $http->requestAt(0)->getUri()->getPath());
|
||||
$this->assertEquals('/a-test-module.zip', $http->requestAt(1)->getUri()->getPath());
|
||||
});
|
||||
}
|
||||
|
||||
public function test_remote_module_install_does_not_follow_redirects_to_different_origin()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$zip = $this->getModuleZipPath();
|
||||
|
||||
$http = $this->mockHttpClient([
|
||||
new Response(302, ['Location' => 'http://example.com/a-test-module.zip']),
|
||||
new Response(200, ['Content-Length' => filesize($zip)], file_get_contents($zip))
|
||||
]);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
|
||||
->expectsConfirmation('Are you sure you trust this source?', 'yes')
|
||||
->assertExitCode(1);
|
||||
|
||||
$this->assertEquals(1, $http->requestCount());
|
||||
$this->assertEquals('https', $http->requestAt(0)->getUri()->getScheme());
|
||||
});
|
||||
}
|
||||
|
||||
public function test_remote_module_install_download_failures_are_announced_to_user()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$http = $this->mockHttpClient([
|
||||
new Response(404),
|
||||
]);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
|
||||
->expectsConfirmation('Are you sure you trust this source?', 'yes')
|
||||
->expectsOutput('ERROR: Failed to download module from https://example.com/test-module.zip')
|
||||
->expectsOutput('Download failed with status code 404')
|
||||
->assertExitCode(1);
|
||||
$this->assertEquals(1, $http->requestCount());
|
||||
});
|
||||
}
|
||||
|
||||
public function test_run_with_invalid_path_exits_early()
|
||||
{
|
||||
$this->artisan('bookstack:install-module', ['location' => '/not-found.zip'])
|
||||
->expectsOutput('ERROR: Module file not found at /not-found.zip')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_run_with_invalid_zip_has_early_exit()
|
||||
{
|
||||
$zip = $this->getModuleZipPath();
|
||||
file_put_contents($zip, 'invalid zip');
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $zip])
|
||||
->expectsOutput("ERROR: Cannot open ZIP file at {$zip}")
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_run_with_large_zip_has_early_exit()
|
||||
{
|
||||
$zip = $this->getModuleZipPath(null, [
|
||||
'large-file.txt' => str_repeat('a', 1024 * 1024 * 51)
|
||||
]);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $zip])
|
||||
->expectsOutput("ERROR: Module ZIP file contents are too large. Maximum size is 50MB")
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_run_with_invalid_module_data_has_early_exit()
|
||||
{
|
||||
$zip = $this->getModuleZipPath([
|
||||
'name' => 'Invalid Module',
|
||||
'description' => 'A module with invalid data',
|
||||
'version' => 'dog',
|
||||
]);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $zip])
|
||||
->expectsOutput("ERROR: Failed to read module metadata with error: Module in folder \"_temp\" has an invalid 'version' format. Expected semantic version format like '1.0.0' or 'v1.0.0'")
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_local_module_install_without_active_theme_can_setup_theme_folder()
|
||||
{
|
||||
$zip = $this->getModuleZipPath();
|
||||
$expectedThemePath = base_path('themes/custom');
|
||||
File::deleteDirectory($expectedThemePath);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $zip])
|
||||
->expectsConfirmation('No active theme folder found, would you like to create one?', 'yes')
|
||||
->expectsOutput("Created theme folder at {$expectedThemePath}")
|
||||
->expectsOutput("You will need to set APP_THEME=custom in your BookStack env configuration to enable this theme!")
|
||||
->expectsOutput('Module "Test Module" (v1.0.0) successfully installed!')
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertDirectoryExists($expectedThemePath . '/modules/test-module');
|
||||
|
||||
File::deleteDirectory($expectedThemePath);
|
||||
}
|
||||
|
||||
public function test_local_module_install_with_active_theme_and_conflicting_modules_file_causes_early_exit()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$zip = $this->getModuleZipPath();
|
||||
File::put(theme_path('modules'), '{}');
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $zip])
|
||||
->expectsOutput("ERROR: Cannot create a modules folder, file already exists at " . theme_path('modules'))
|
||||
->assertExitCode(1);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_single_existing_module_with_same_name_replace()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$original = $this->createModuleFolderInCurrentTheme(['name' => 'Test Module', 'description' => 'cat', 'version' => '1.0.0']);
|
||||
$new = $this->getModuleZipPath(['name' => 'Test Module', 'description' => '', 'version' => '2.0.0']);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $new])
|
||||
->expectsOutput('The following modules already exist with the same name:')
|
||||
->expectsOutput('Test Module (test-module:v1.0.0) - cat')
|
||||
->expectsChoice('What would you like to do?', 'Replace existing module', ['Cancel module install', 'Add alongside existing module', 'Replace existing module'])
|
||||
->expectsOutput("Replacing existing module in test-module folder")
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertFileExists($original . '/bookstack-module.json');
|
||||
$metadata = json_decode(file_get_contents($original . '/bookstack-module.json'), true);
|
||||
$this->assertEquals('2.0.0', $metadata['version']);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_single_existing_module_with_same_name_cancel()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$original = $this->createModuleFolderInCurrentTheme(['name' => 'Test Module', 'description' => 'cat', 'version' => '1.0.0']);
|
||||
$new = $this->getModuleZipPath(['name' => 'Test Module', 'description' => '', 'version' => '2.0.0']);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $new])
|
||||
->expectsOutput('The following modules already exist with the same name:')
|
||||
->expectsOutput('Test Module (test-module:v1.0.0) - cat')
|
||||
->expectsChoice('What would you like to do?', 'Cancel module install', ['Cancel module install', 'Add alongside existing module', 'Replace existing module'])
|
||||
->assertExitCode(1);
|
||||
|
||||
$this->assertFileExists($original . '/bookstack-module.json');
|
||||
$metadata = json_decode(file_get_contents($original . '/bookstack-module.json'), true);
|
||||
$this->assertEquals('1.0.0', $metadata['version']);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_single_existing_module_with_same_name_add()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$original = $this->createModuleFolderInCurrentTheme(['name' => 'Test Module', 'description' => 'cat', 'version' => '1.0.0']);
|
||||
$new = $this->getModuleZipPath(['name' => 'Test Module', 'description' => '', 'version' => '2.0.0']);
|
||||
|
||||
$this->artisan('bookstack:install-module', ['location' => $new])
|
||||
->expectsOutput('The following modules already exist with the same name:')
|
||||
->expectsOutput('Test Module (test-module:v1.0.0) - cat')
|
||||
->expectsChoice('What would you like to do?', 'Add alongside existing module', ['Cancel module install', 'Add alongside existing module', 'Replace existing module'])
|
||||
->assertExitCode(0);
|
||||
|
||||
$dirs = File::directories(theme_path('modules/'));
|
||||
$this->assertCount(2, $dirs);
|
||||
});
|
||||
}
|
||||
|
||||
protected function createModuleFolderInCurrentTheme(array|null $metadata = null, array $extraFiles = []): string
|
||||
{
|
||||
$original = $this->getModuleZipPath($metadata, $extraFiles);
|
||||
$targetPath = theme_path('modules/test-module');
|
||||
mkdir($targetPath, 0777, true);
|
||||
$originalZip = new ZipArchive();
|
||||
$originalZip->open($original);
|
||||
$originalZip->extractTo($targetPath);
|
||||
$originalZip->close();
|
||||
|
||||
return $targetPath;
|
||||
}
|
||||
|
||||
protected function getModuleZipPath(array|null $metadata = null, array $extraFiles = []): string
|
||||
{
|
||||
$zip = new ZipArchive();
|
||||
$tmpFile = tempnam(sys_get_temp_dir(), 'bs-test-module');
|
||||
$zip->open($tmpFile, ZipArchive::CREATE);
|
||||
|
||||
$zip->addFromString('bookstack-module.json', json_encode($metadata ?? [
|
||||
'name' => 'Test Module',
|
||||
'description' => 'A test module for BookStack',
|
||||
'version' => '1.0.0',
|
||||
]));
|
||||
|
||||
foreach ($extraFiles as $path => $contents) {
|
||||
$zip->addFromString($path, $contents);
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
return $tmpFile;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Env;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Testing\Assert as PHPUnit;
|
||||
use Illuminate\Testing\Constraints\HasInDatabase;
|
||||
@@ -157,6 +158,23 @@ abstract class TestCase extends BaseTestCase
|
||||
}
|
||||
}
|
||||
|
||||
protected function usingThemeFolder(callable $callback): void
|
||||
{
|
||||
// Create a folder and configure a theme
|
||||
$themeFolderName = 'testing_theme_' . str_shuffle(rtrim(base64_encode(time()), '='));
|
||||
config()->set('view.theme', $themeFolderName);
|
||||
$themeFolderPath = theme_path('');
|
||||
|
||||
// Create a theme folder and clean it up on application tear-down
|
||||
File::makeDirectory($themeFolderPath);
|
||||
$this->beforeApplicationDestroyed(fn() => File::deleteDirectory($themeFolderPath));
|
||||
|
||||
// Run provided callback with the theme env option set
|
||||
$this->runWithEnv(['APP_THEME' => $themeFolderName], function () use ($callback, $themeFolderName) {
|
||||
call_user_func($callback, $themeFolderName);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the keys and properties in the given map to include
|
||||
* exist, albeit not exclusively, within the map to check.
|
||||
|
||||
321
tests/Theme/LogicalThemeEventsTest.php
Normal file
321
tests/Theme/LogicalThemeEventsTest.php
Normal file
@@ -0,0 +1,321 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Theme;
|
||||
|
||||
use BookStack\Activity\ActivityType;
|
||||
use BookStack\Activity\DispatchWebhookJob;
|
||||
use BookStack\Activity\Models\Webhook;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Facades\Theme;
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use League\CommonMark\Environment\Environment;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LogicalThemeEventsTest extends TestCase
|
||||
{
|
||||
public function test_commonmark_environment_configure()
|
||||
{
|
||||
$callbackCalled = false;
|
||||
$callback = function ($environment) use (&$callbackCalled) {
|
||||
$this->assertInstanceOf(Environment::class, $environment);
|
||||
$callbackCalled = true;
|
||||
|
||||
return $environment;
|
||||
};
|
||||
Theme::listen(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $callback);
|
||||
|
||||
$page = $this->entities->page();
|
||||
$content = new PageContent($page);
|
||||
$content->setNewMarkdown('# test', $this->users->editor());
|
||||
|
||||
$this->assertTrue($callbackCalled);
|
||||
}
|
||||
|
||||
public function test_web_middleware_before()
|
||||
{
|
||||
$callbackCalled = false;
|
||||
$requestParam = null;
|
||||
$callback = function ($request) use (&$callbackCalled, &$requestParam) {
|
||||
$requestParam = $request;
|
||||
$callbackCalled = true;
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
|
||||
$this->get('/login', ['Donkey' => 'cat']);
|
||||
|
||||
$this->assertTrue($callbackCalled);
|
||||
$this->assertInstanceOf(Request::class, $requestParam);
|
||||
$this->assertEquals('cat', $requestParam->header('donkey'));
|
||||
}
|
||||
|
||||
public function test_web_middleware_before_return_val_used_as_response()
|
||||
{
|
||||
$callback = function (Request $request) {
|
||||
return response('cat', 412);
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
|
||||
$resp = $this->get('/login', ['Donkey' => 'cat']);
|
||||
$resp->assertSee('cat');
|
||||
$resp->assertStatus(412);
|
||||
}
|
||||
|
||||
public function test_web_middleware_after()
|
||||
{
|
||||
$callbackCalled = false;
|
||||
$requestParam = null;
|
||||
$responseParam = null;
|
||||
$callback = function ($request, Response $response) use (&$callbackCalled, &$requestParam, &$responseParam) {
|
||||
$requestParam = $request;
|
||||
$responseParam = $response;
|
||||
$callbackCalled = true;
|
||||
$response->header('donkey', 'cat123');
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
|
||||
|
||||
$resp = $this->get('/login', ['Donkey' => 'cat']);
|
||||
$this->assertTrue($callbackCalled);
|
||||
$this->assertInstanceOf(Request::class, $requestParam);
|
||||
$this->assertInstanceOf(Response::class, $responseParam);
|
||||
$resp->assertHeader('donkey', 'cat123');
|
||||
}
|
||||
|
||||
public function test_web_middleware_after_return_val_used_as_response()
|
||||
{
|
||||
$callback = function () {
|
||||
return response('cat456', 443);
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
|
||||
|
||||
$resp = $this->get('/login', ['Donkey' => 'cat']);
|
||||
$resp->assertSee('cat456');
|
||||
$resp->assertStatus(443);
|
||||
}
|
||||
|
||||
public function test_auth_login_standard()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::AUTH_LOGIN, $callback);
|
||||
$this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals('standard', $args[0]);
|
||||
$this->assertInstanceOf(User::class, $args[1]);
|
||||
}
|
||||
|
||||
public function test_auth_register_standard()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
Theme::listen(ThemeEvents::AUTH_REGISTER, $callback);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$user = User::factory()->make();
|
||||
$this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals('standard', $args[0]);
|
||||
$this->assertInstanceOf(User::class, $args[1]);
|
||||
}
|
||||
|
||||
public function test_auth_pre_register()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
Theme::listen(ThemeEvents::AUTH_PRE_REGISTER, $callback);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$user = User::factory()->make();
|
||||
$this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals('standard', $args[0]);
|
||||
$this->assertEquals([
|
||||
'email' => $user->email,
|
||||
'name' => $user->name,
|
||||
'password' => 'password',
|
||||
], $args[1]);
|
||||
$this->assertDatabaseHas('users', ['email' => $user->email]);
|
||||
}
|
||||
|
||||
public function test_auth_pre_register_with_false_return_blocks_registration()
|
||||
{
|
||||
$callback = function () {
|
||||
return false;
|
||||
};
|
||||
Theme::listen(ThemeEvents::AUTH_PRE_REGISTER, $callback);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$user = User::factory()->make();
|
||||
$resp = $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
|
||||
$resp->assertRedirect('/login');
|
||||
$this->assertSessionError('User account could not be registered for the provided details');
|
||||
$this->assertDatabaseMissing('users', ['email' => $user->email]);
|
||||
}
|
||||
|
||||
public function test_webhook_call_before()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
|
||||
return ['test' => 'hello!'];
|
||||
};
|
||||
Theme::listen(ThemeEvents::WEBHOOK_CALL_BEFORE, $callback);
|
||||
|
||||
$responses = $this->mockHttpClient([new \GuzzleHttp\Psr7\Response(200, [], '')]);
|
||||
|
||||
$webhook = new Webhook(['name' => 'Test webhook', 'endpoint' => 'https://example.com']);
|
||||
$webhook->save();
|
||||
$event = ActivityType::PAGE_UPDATE;
|
||||
$detail = Page::query()->first();
|
||||
|
||||
dispatch((new DispatchWebhookJob($webhook, $event, $detail)));
|
||||
|
||||
$this->assertCount(5, $args);
|
||||
$this->assertEquals($event, $args[0]);
|
||||
$this->assertEquals($webhook->id, $args[1]->id);
|
||||
$this->assertEquals($detail->id, $args[2]->id);
|
||||
|
||||
$this->assertEquals(1, $responses->requestCount());
|
||||
$request = $responses->latestRequest();
|
||||
$reqData = json_decode($request->getBody(), true);
|
||||
$this->assertEquals('hello!', $reqData['test']);
|
||||
}
|
||||
|
||||
public function test_activity_logged()
|
||||
{
|
||||
$book = $this->entities->book();
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::ACTIVITY_LOGGED, $callback);
|
||||
$this->asEditor()->put($book->getUrl(), ['name' => 'My cool update book!']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals(ActivityType::BOOK_UPDATE, $args[0]);
|
||||
$this->assertTrue($args[1] instanceof Book);
|
||||
$this->assertEquals($book->id, $args[1]->id);
|
||||
}
|
||||
|
||||
public function test_page_include_parse()
|
||||
{
|
||||
/** @var Page $page */
|
||||
/** @var Page $otherPage */
|
||||
$page = $this->entities->page();
|
||||
$otherPage = Page::query()->where('id', '!=', $page->id)->first();
|
||||
$otherPage->html = '<p id="bkmrk-cool">This is a really cool section</p>';
|
||||
$page->html = "<p>{{@{$otherPage->id}#bkmrk-cool}}</p>";
|
||||
$page->save();
|
||||
$otherPage->save();
|
||||
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
|
||||
return '<strong>Big & content replace surprise!</strong>';
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::PAGE_INCLUDE_PARSE, $callback);
|
||||
$resp = $this->asEditor()->get($page->getUrl());
|
||||
$this->withHtml($resp)->assertElementContains('.page-content strong', 'Big & content replace surprise!');
|
||||
|
||||
$this->assertCount(4, $args);
|
||||
$this->assertEquals($otherPage->id . '#bkmrk-cool', $args[0]);
|
||||
$this->assertEquals('This is a really cool section', $args[1]);
|
||||
$this->assertTrue($args[2] instanceof Page);
|
||||
$this->assertTrue($args[3] instanceof Page);
|
||||
$this->assertEquals($page->id, $args[2]->id);
|
||||
$this->assertEquals($otherPage->id, $args[3]->id);
|
||||
}
|
||||
|
||||
public function test_routes_register_web_and_web_auth()
|
||||
{
|
||||
$functionsContent = <<<'END'
|
||||
<?php
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Facades\Theme;
|
||||
use Illuminate\Routing\Router;
|
||||
Theme::listen(ThemeEvents::ROUTES_REGISTER_WEB, function (Router $router) {
|
||||
$router->get('/cat', fn () => 'cat')->name('say.cat');
|
||||
});
|
||||
Theme::listen(ThemeEvents::ROUTES_REGISTER_WEB_AUTH, function (Router $router) {
|
||||
$router->get('/dog', fn () => 'dog')->name('say.dog');
|
||||
});
|
||||
END;
|
||||
|
||||
$this->usingThemeFolder(function () use ($functionsContent) {
|
||||
|
||||
$functionsFile = theme_path('functions.php');
|
||||
file_put_contents($functionsFile, $functionsContent);
|
||||
|
||||
$app = $this->createApplication();
|
||||
/** @var \Illuminate\Routing\Router $router */
|
||||
$router = $app->get('router');
|
||||
|
||||
/** @var \Illuminate\Routing\Route $catRoute */
|
||||
$catRoute = $router->getRoutes()->getRoutesByName()['say.cat'];
|
||||
$this->assertEquals(['web'], $catRoute->middleware());
|
||||
|
||||
/** @var \Illuminate\Routing\Route $dogRoute */
|
||||
$dogRoute = $router->getRoutes()->getRoutesByName()['say.dog'];
|
||||
$this->assertEquals(['web', 'auth'], $dogRoute->middleware());
|
||||
});
|
||||
}
|
||||
|
||||
public function test_register_views_to_insert_views_before_and_after()
|
||||
{
|
||||
$this->usingThemeFolder(function (string $folder) {
|
||||
$before = 'this-is-my-before-header-string';
|
||||
$afterA = 'this-is-my-after-header-string-a';
|
||||
$afterB = 'this-is-my-after-header-string-b';
|
||||
$afterC = 'this-is-my-after-header-string-{{ 1+51 }}';
|
||||
|
||||
$functionsContent = <<<'CONTENT'
|
||||
<?php use BookStack\Facades\Theme;
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Theming\ThemeViews;
|
||||
Theme::listen(ThemeEvents::THEME_REGISTER_VIEWS, function (ThemeViews $themeViews) {
|
||||
$themeViews->renderBefore('layouts.parts.header', 'before', 4);
|
||||
$themeViews->renderAfter('layouts.parts.header', 'after-a', 4);
|
||||
$themeViews->renderAfter('layouts.parts.header', 'after-b', 1);
|
||||
$themeViews->renderAfter('layouts.parts.header', 'after-c', 12);
|
||||
});
|
||||
CONTENT;
|
||||
|
||||
$viewDir = theme_path();
|
||||
file_put_contents($viewDir . '/functions.php', $functionsContent);
|
||||
file_put_contents($viewDir . '/before.blade.php', $before);
|
||||
file_put_contents($viewDir . '/after-a.blade.php', $afterA);
|
||||
file_put_contents($viewDir . '/after-b.blade.php', $afterB);
|
||||
file_put_contents($viewDir . '/after-c.blade.php', $afterC);
|
||||
|
||||
$this->refreshApplication();
|
||||
$this->artisan('view:clear');
|
||||
|
||||
$resp = $this->get('/login');
|
||||
$resp->assertSee($before);
|
||||
// Ensure ordering of the multiple after views
|
||||
$resp->assertSee($afterB . "\n" . $afterA . "\nthis-is-my-after-header-string-52");
|
||||
});
|
||||
|
||||
$this->artisan('view:clear');
|
||||
}
|
||||
}
|
||||
105
tests/Theme/LogicalThemeTest.php
Normal file
105
tests/Theme/LogicalThemeTest.php
Normal file
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Theme;
|
||||
|
||||
use BookStack\Exceptions\ThemeException;
|
||||
use BookStack\Facades\Theme;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LogicalThemeTest extends TestCase
|
||||
{
|
||||
public function test_theme_functions_file_used_and_app_boot_event_runs()
|
||||
{
|
||||
$this->usingThemeFolder(function ($themeFolder) {
|
||||
$functionsFile = theme_path('functions.php');
|
||||
app()->alias('cat', 'dog');
|
||||
file_put_contents($functionsFile, "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('cat', 'dog');});");
|
||||
$this->runWithEnv(['APP_THEME' => $themeFolder], function () {
|
||||
$this->assertEquals('cat', $this->app->getAlias('dog'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_functions_loads_errors_are_caught_and_logged()
|
||||
{
|
||||
$this->usingThemeFolder(function ($themeFolder) {
|
||||
$functionsFile = theme_path('functions.php');
|
||||
file_put_contents($functionsFile, "<?php\n\\BookStack\\Biscuits::eat();");
|
||||
|
||||
$this->expectException(ThemeException::class);
|
||||
$this->expectExceptionMessageMatches('/Failed loading theme functions file at ".*?" with error: Class "BookStack\\\\Biscuits" not found/');
|
||||
|
||||
$this->runWithEnv(['APP_THEME' => $themeFolder], fn() => null);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_add_social_driver()
|
||||
{
|
||||
Theme::addSocialDriver('catnet', [
|
||||
'client_id' => 'abc123',
|
||||
'client_secret' => 'def456',
|
||||
], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
|
||||
|
||||
$this->assertEquals('catnet', config('services.catnet.name'));
|
||||
$this->assertEquals('abc123', config('services.catnet.client_id'));
|
||||
$this->assertEquals(url('/login/service/catnet/callback'), config('services.catnet.redirect'));
|
||||
|
||||
$loginResp = $this->get('/login');
|
||||
$loginResp->assertSee('login/service/catnet');
|
||||
}
|
||||
|
||||
public function test_add_social_driver_uses_name_in_config_if_given()
|
||||
{
|
||||
Theme::addSocialDriver('catnet', [
|
||||
'client_id' => 'abc123',
|
||||
'client_secret' => 'def456',
|
||||
'name' => 'Super Cat Name',
|
||||
], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
|
||||
|
||||
$this->assertEquals('Super Cat Name', config('services.catnet.name'));
|
||||
$loginResp = $this->get('/login');
|
||||
$loginResp->assertSee('Super Cat Name');
|
||||
}
|
||||
|
||||
public function test_add_social_driver_allows_a_configure_for_redirect_callback_to_be_passed()
|
||||
{
|
||||
Theme::addSocialDriver(
|
||||
'discord',
|
||||
[
|
||||
'client_id' => 'abc123',
|
||||
'client_secret' => 'def456',
|
||||
'name' => 'Super Cat Name',
|
||||
],
|
||||
'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
|
||||
function ($driver) {
|
||||
$driver->with(['donkey' => 'donut']);
|
||||
}
|
||||
);
|
||||
|
||||
$loginResp = $this->get('/login/service/discord');
|
||||
$redirect = $loginResp->headers->get('location');
|
||||
$this->assertStringContainsString('donkey=donut', $redirect);
|
||||
}
|
||||
|
||||
public function test_register_command_allows_provided_command_to_be_usable_via_artisan()
|
||||
{
|
||||
Theme::registerCommand(new MyCustomCommand());
|
||||
|
||||
Artisan::call('bookstack:test-custom-command', []);
|
||||
$output = Artisan::output();
|
||||
|
||||
$this->assertStringContainsString('Command ran!', $output);
|
||||
}
|
||||
}
|
||||
|
||||
class MyCustomCommand extends Command
|
||||
{
|
||||
protected $signature = 'bookstack:test-custom-command';
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$this->line('Command ran!');
|
||||
}
|
||||
}
|
||||
223
tests/Theme/ThemeModuleTests.php
Normal file
223
tests/Theme/ThemeModuleTests.php
Normal file
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Theme;
|
||||
|
||||
use BookStack\Facades\Theme;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ThemeModuleTests extends TestCase
|
||||
{
|
||||
public function test_modules_loaded_on_theme_load()
|
||||
{
|
||||
$this->usingThemeFolder(function ($themeFolder) {
|
||||
$a = theme_path('modules/a');
|
||||
$b = theme_path('modules/b');
|
||||
mkdir($a, 0777, true);
|
||||
mkdir($b, 0777, true);
|
||||
|
||||
file_put_contents($a . '/bookstack-module.json', json_encode([
|
||||
'name' => 'Module A',
|
||||
'description' => 'This is module A',
|
||||
'version' => '1.0.0',
|
||||
]));
|
||||
file_put_contents($b . '/bookstack-module.json', json_encode([
|
||||
'name' => 'Module B',
|
||||
'description' => 'This is module B',
|
||||
'version' => 'v0.5.0',
|
||||
]));
|
||||
|
||||
$this->refreshApplication();
|
||||
|
||||
$modules = Theme::getModules();
|
||||
$this->assertCount(2, $modules);
|
||||
|
||||
$moduleA = $modules['a'];
|
||||
$this->assertEquals('Module A', $moduleA->name);
|
||||
$this->assertEquals('This is module A', $moduleA->description);
|
||||
$this->assertEquals('1.0.0', $moduleA->version);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_module_not_loaded_if_no_bookstack_module_json()
|
||||
{
|
||||
$this->usingThemeFolder(function ($themeFolder) {
|
||||
$moduleDir = theme_path('/modules/a');
|
||||
mkdir($moduleDir, 0777, true);
|
||||
file_put_contents($moduleDir . '/module.json', '{}');
|
||||
$this->refreshApplication();
|
||||
$modules = Theme::getModules();
|
||||
$this->assertCount(0, $modules);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_language_text_overridable_via_module()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$translationPath = $moduleFolderPath . '/lang/en';
|
||||
mkdir($translationPath, 0777, true);
|
||||
file_put_contents($translationPath . '/entities.php', '<?php return ["books" => "SuperBeans"];');
|
||||
$this->refreshApplication();
|
||||
|
||||
$this->asAdmin()->get('/books')->assertSee('SuperBeans');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_language_files_merge_with_theme_files_with_theme_taking_precedence()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$moduleTranslationPath = $moduleFolderPath . '/lang/en';
|
||||
mkdir($moduleTranslationPath, 0777, true);
|
||||
file_put_contents($moduleTranslationPath . '/entities.php', '<?php return ["books" => "SuperBeans", "recently_viewed" => "ViewedBiscuits"];');
|
||||
|
||||
$themeTranslationPath = theme_path('lang/en');
|
||||
mkdir($themeTranslationPath, 0777, true);
|
||||
file_put_contents($themeTranslationPath . '/entities.php', '<?php return ["books" => "WonderBeans"];');
|
||||
$this->refreshApplication();
|
||||
|
||||
$this->asAdmin()->get('/books')
|
||||
->assertSee('WonderBeans')
|
||||
->assertDontSee('SuperBeans')
|
||||
->assertSee('ViewedBiscuits');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_view_files_overridable_from_module()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$viewsFolder = $moduleFolderPath . '/views/layouts/parts';
|
||||
mkdir($viewsFolder, 0777, true);
|
||||
file_put_contents($viewsFolder . '/header.blade.php', 'My custom header that says badgerriffic');
|
||||
$this->refreshApplication();
|
||||
$this->asAdmin()->get('/')->assertSee('badgerriffic');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_view_files_take_precedence_over_module_view_files()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$viewsFolder = $moduleFolderPath . '/views/layouts/parts';
|
||||
mkdir($viewsFolder, 0777, true);
|
||||
file_put_contents($viewsFolder . '/header.blade.php', 'My custom header that says badgerriffic');
|
||||
|
||||
$themeViewsFolder = theme_path('layouts/parts');
|
||||
mkdir($themeViewsFolder, 0777, true);
|
||||
file_put_contents($themeViewsFolder . '/header.blade.php', 'My theme header that says awesomeferrets');
|
||||
|
||||
$this->refreshApplication();
|
||||
$this->asAdmin()->get('/')
|
||||
->assertDontSee('badgerriffic')
|
||||
->assertSee('awesomeferrets');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_and_modules_views_can_be_used_at_the_same_time()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$viewsFolder = $moduleFolderPath . '/views/layouts/parts';
|
||||
mkdir($viewsFolder, 0777, true);
|
||||
file_put_contents($viewsFolder . '/base-body-start.blade.php', 'My custom header that says badgerriffic');
|
||||
|
||||
$themeViewsFolder = theme_path('layouts/parts');
|
||||
mkdir($themeViewsFolder, 0777, true);
|
||||
file_put_contents($themeViewsFolder . '/base-body-end.blade.php', 'My theme header that says awesomeferrets');
|
||||
|
||||
$this->refreshApplication();
|
||||
$this->asAdmin()->get('/')
|
||||
->assertSee('badgerriffic')
|
||||
->assertSee('awesomeferrets');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_icons_can_be_overridden_from_module()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$iconsFolder = $moduleFolderPath . '/icons';
|
||||
mkdir($iconsFolder, 0777, true);
|
||||
file_put_contents($iconsFolder . '/books.svg', '<svg><path d="supericonpath"/></svg>');
|
||||
$this->refreshApplication();
|
||||
|
||||
$this->asAdmin()->get('/')->assertSee('supericonpath', false);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_icons_take_precedence_over_module_icons()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$iconsFolder = $moduleFolderPath . '/icons';
|
||||
mkdir($iconsFolder, 0777, true);
|
||||
file_put_contents($iconsFolder . '/books.svg', '<svg><path d="supericonpath"/></svg>');
|
||||
$this->refreshApplication();
|
||||
|
||||
$themeViewsFolder = theme_path('icons');
|
||||
mkdir($themeViewsFolder, 0777, true);
|
||||
file_put_contents($themeViewsFolder . '/books.svg', '<svg><path d="wackyiconpath"/></svg>');
|
||||
|
||||
|
||||
$this->asAdmin()->get('/')
|
||||
->assertSee('wackyiconpath', false)
|
||||
->assertDontSee('supericonpath', false);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_public_folder_can_be_provided_from_module()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$publicFolder = $moduleFolderPath . '/public';
|
||||
mkdir($publicFolder, 0777, true);
|
||||
$themeName = basename(dirname(dirname($moduleFolderPath)));
|
||||
file_put_contents($publicFolder . '/test.txt', 'hellofrominsidethisfileimaghostwoooo!');
|
||||
$this->refreshApplication();
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeName}/test.txt")->streamedContent();
|
||||
$this->assertEquals('hellofrominsidethisfileimaghostwoooo!', $resp);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_public_files_take_precedence_over_modules()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
$publicFolder = $moduleFolderPath . '/public';
|
||||
mkdir($publicFolder, 0777, true);
|
||||
$themeName = basename(theme_path());
|
||||
file_put_contents($publicFolder . '/test.txt', 'hellofrominsidethisfileimaghostwoooo!');
|
||||
|
||||
$themePublicFolder = theme_path('public');
|
||||
mkdir($themePublicFolder, 0777, true);
|
||||
file_put_contents($themePublicFolder . '/test.txt', 'imadifferentghostinsidethetheme,woooooo!');
|
||||
|
||||
$this->refreshApplication();
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeName}/test.txt")->streamedContent();
|
||||
$this->assertEquals('imadifferentghostinsidethetheme,woooooo!', $resp);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_logical_functions_file_loaded_from_module_and_it_runs_alongside_theme_functions()
|
||||
{
|
||||
$this->usingModuleFolder(function (string $moduleFolderPath) {
|
||||
file_put_contents($moduleFolderPath . '/functions.php', "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('cat', 'dog');});");
|
||||
|
||||
$themeFunctionsFile = theme_path('functions.php');
|
||||
file_put_contents($themeFunctionsFile, "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('beans', 'cheese');});");
|
||||
|
||||
$this->refreshApplication();
|
||||
|
||||
$this->assertEquals('cat', $this->app->getAlias('dog'));
|
||||
$this->assertEquals('beans', $this->app->getAlias('cheese'));
|
||||
});
|
||||
}
|
||||
|
||||
protected function usingModuleFolder(callable $callback): void
|
||||
{
|
||||
$this->usingThemeFolder(function (string $themeFolder) use ($callback) {
|
||||
$moduleFolderPath = theme_path('modules/test-module');
|
||||
mkdir($moduleFolderPath, 0777, true);
|
||||
file_put_contents($moduleFolderPath . '/bookstack-module.json', json_encode([
|
||||
'name' => 'Test Module',
|
||||
'description' => 'This is a test module',
|
||||
'version' => 'v1.0.0',
|
||||
]));
|
||||
$callback($moduleFolderPath);
|
||||
});
|
||||
}
|
||||
}
|
||||
132
tests/Theme/VisualThemeTest.php
Normal file
132
tests/Theme/VisualThemeTest.php
Normal file
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Theme;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
class VisualThemeTest extends TestCase
|
||||
{
|
||||
public function test_translation_text_can_be_overridden_via_theme()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$translationPath = theme_path('/lang/en');
|
||||
File::makeDirectory($translationPath, 0777, true);
|
||||
|
||||
$customTranslations = '<?php
|
||||
return [\'books\' => \'Sandwiches\'];
|
||||
';
|
||||
file_put_contents($translationPath . '/entities.php', $customTranslations);
|
||||
|
||||
$homeRequest = $this->actingAs($this->users->viewer())->get('/');
|
||||
$this->withHtml($homeRequest)->assertElementContains('header nav', 'Sandwiches');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_custom_settings_category_page_can_be_added_via_view_file()
|
||||
{
|
||||
$content = 'My SuperCustomSettings';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($content) {
|
||||
$viewDir = theme_path('settings/categories');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/beans.blade.php', $content);
|
||||
|
||||
$this->asAdmin()->get('/settings/beans')->assertSee($content);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_base_body_start_and_end_template_files_can_be_used()
|
||||
{
|
||||
$bodyStartStr = 'barry-fought-against-the-panther';
|
||||
$bodyEndStr = 'barry-lost-his-fight-with-grace';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr) {
|
||||
$viewDir = theme_path('layouts/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/base-body-start.blade.php', $bodyStartStr);
|
||||
file_put_contents($viewDir . '/base-body-end.blade.php', $bodyEndStr);
|
||||
|
||||
$resp = $this->asEditor()->get('/');
|
||||
$resp->assertSee($bodyStartStr);
|
||||
$resp->assertSee($bodyEndStr);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_export_body_start_and_end_template_files_can_be_used()
|
||||
{
|
||||
$bodyStartStr = 'garry-fought-against-the-panther';
|
||||
$bodyEndStr = 'garry-lost-his-fight-with-grace';
|
||||
$page = $this->entities->page();
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr, $page) {
|
||||
$viewDir = theme_path('layouts/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/export-body-start.blade.php', $bodyStartStr);
|
||||
file_put_contents($viewDir . '/export-body-end.blade.php', $bodyEndStr);
|
||||
|
||||
$resp = $this->asEditor()->get($page->getUrl('/export/html'));
|
||||
$resp->assertSee($bodyStartStr);
|
||||
$resp->assertSee($bodyEndStr);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_login_and_register_message_template_files_can_be_used()
|
||||
{
|
||||
$loginMessage = 'Welcome to this instance, login below you scallywag';
|
||||
$registerMessage = 'You want to register? Enter the deets below you numpty';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($loginMessage, $registerMessage) {
|
||||
$viewDir = theme_path('auth/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/login-message.blade.php', $loginMessage);
|
||||
file_put_contents($viewDir . '/register-message.blade.php', $registerMessage);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$this->get('/login')->assertSee($loginMessage);
|
||||
$this->get('/register')->assertSee($registerMessage);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_header_links_start_template_file_can_be_used()
|
||||
{
|
||||
$content = 'This is added text in the header bar';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($content) {
|
||||
$viewDir = theme_path('layouts/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/header-links-start.blade.php', $content);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$this->get('/login')->assertSee($content);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_public_folder_contents_accessible_via_route()
|
||||
{
|
||||
$this->usingThemeFolder(function (string $themeFolderName) {
|
||||
$publicDir = theme_path('public');
|
||||
mkdir($publicDir, 0777, true);
|
||||
|
||||
$text = 'some-text ' . md5(random_bytes(5));
|
||||
$css = "body { background-color: tomato !important; }";
|
||||
file_put_contents("{$publicDir}/file.txt", $text);
|
||||
file_put_contents("{$publicDir}/file.css", $css);
|
||||
copy($this->files->testFilePath('test-image.png'), "{$publicDir}/image.png");
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/file.txt");
|
||||
$resp->assertStreamedContent($text);
|
||||
$resp->assertHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/image.png");
|
||||
$resp->assertHeader('Content-Type', 'image/png');
|
||||
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/file.css");
|
||||
$resp->assertStreamedContent($css);
|
||||
$resp->assertHeader('Content-Type', 'text/css; charset=utf-8');
|
||||
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,521 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use BookStack\Activity\ActivityType;
|
||||
use BookStack\Activity\DispatchWebhookJob;
|
||||
use BookStack\Activity\Models\Webhook;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Exceptions\ThemeException;
|
||||
use BookStack\Facades\Theme;
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use League\CommonMark\Environment\Environment;
|
||||
|
||||
class ThemeTest extends TestCase
|
||||
{
|
||||
protected string $themeFolderName;
|
||||
protected string $themeFolderPath;
|
||||
|
||||
public function test_translation_text_can_be_overridden_via_theme()
|
||||
{
|
||||
$this->usingThemeFolder(function () {
|
||||
$translationPath = theme_path('/lang/en');
|
||||
File::makeDirectory($translationPath, 0777, true);
|
||||
|
||||
$customTranslations = '<?php
|
||||
return [\'books\' => \'Sandwiches\'];
|
||||
';
|
||||
file_put_contents($translationPath . '/entities.php', $customTranslations);
|
||||
|
||||
$homeRequest = $this->actingAs($this->users->viewer())->get('/');
|
||||
$this->withHtml($homeRequest)->assertElementContains('header nav', 'Sandwiches');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_functions_file_used_and_app_boot_event_runs()
|
||||
{
|
||||
$this->usingThemeFolder(function ($themeFolder) {
|
||||
$functionsFile = theme_path('functions.php');
|
||||
app()->alias('cat', 'dog');
|
||||
file_put_contents($functionsFile, "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('cat', 'dog');});");
|
||||
$this->runWithEnv(['APP_THEME' => $themeFolder], function () {
|
||||
$this->assertEquals('cat', $this->app->getAlias('dog'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function test_theme_functions_loads_errors_are_caught_and_logged()
|
||||
{
|
||||
$this->usingThemeFolder(function ($themeFolder) {
|
||||
$functionsFile = theme_path('functions.php');
|
||||
file_put_contents($functionsFile, "<?php\n\\BookStack\\Biscuits::eat();");
|
||||
|
||||
$this->expectException(ThemeException::class);
|
||||
$this->expectExceptionMessageMatches('/Failed loading theme functions file at ".*?" with error: Class "BookStack\\\\Biscuits" not found/');
|
||||
|
||||
$this->runWithEnv(['APP_THEME' => $themeFolder], fn() => null);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_event_commonmark_environment_configure()
|
||||
{
|
||||
$callbackCalled = false;
|
||||
$callback = function ($environment) use (&$callbackCalled) {
|
||||
$this->assertInstanceOf(Environment::class, $environment);
|
||||
$callbackCalled = true;
|
||||
|
||||
return $environment;
|
||||
};
|
||||
Theme::listen(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $callback);
|
||||
|
||||
$page = $this->entities->page();
|
||||
$content = new PageContent($page);
|
||||
$content->setNewMarkdown('# test', $this->users->editor());
|
||||
|
||||
$this->assertTrue($callbackCalled);
|
||||
}
|
||||
|
||||
public function test_event_web_middleware_before()
|
||||
{
|
||||
$callbackCalled = false;
|
||||
$requestParam = null;
|
||||
$callback = function ($request) use (&$callbackCalled, &$requestParam) {
|
||||
$requestParam = $request;
|
||||
$callbackCalled = true;
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
|
||||
$this->get('/login', ['Donkey' => 'cat']);
|
||||
|
||||
$this->assertTrue($callbackCalled);
|
||||
$this->assertInstanceOf(Request::class, $requestParam);
|
||||
$this->assertEquals('cat', $requestParam->header('donkey'));
|
||||
}
|
||||
|
||||
public function test_event_web_middleware_before_return_val_used_as_response()
|
||||
{
|
||||
$callback = function (Request $request) {
|
||||
return response('cat', 412);
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
|
||||
$resp = $this->get('/login', ['Donkey' => 'cat']);
|
||||
$resp->assertSee('cat');
|
||||
$resp->assertStatus(412);
|
||||
}
|
||||
|
||||
public function test_event_web_middleware_after()
|
||||
{
|
||||
$callbackCalled = false;
|
||||
$requestParam = null;
|
||||
$responseParam = null;
|
||||
$callback = function ($request, Response $response) use (&$callbackCalled, &$requestParam, &$responseParam) {
|
||||
$requestParam = $request;
|
||||
$responseParam = $response;
|
||||
$callbackCalled = true;
|
||||
$response->header('donkey', 'cat123');
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
|
||||
|
||||
$resp = $this->get('/login', ['Donkey' => 'cat']);
|
||||
$this->assertTrue($callbackCalled);
|
||||
$this->assertInstanceOf(Request::class, $requestParam);
|
||||
$this->assertInstanceOf(Response::class, $responseParam);
|
||||
$resp->assertHeader('donkey', 'cat123');
|
||||
}
|
||||
|
||||
public function test_event_web_middleware_after_return_val_used_as_response()
|
||||
{
|
||||
$callback = function () {
|
||||
return response('cat456', 443);
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
|
||||
|
||||
$resp = $this->get('/login', ['Donkey' => 'cat']);
|
||||
$resp->assertSee('cat456');
|
||||
$resp->assertStatus(443);
|
||||
}
|
||||
|
||||
public function test_event_auth_login_standard()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::AUTH_LOGIN, $callback);
|
||||
$this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals('standard', $args[0]);
|
||||
$this->assertInstanceOf(User::class, $args[1]);
|
||||
}
|
||||
|
||||
public function test_event_auth_register_standard()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
Theme::listen(ThemeEvents::AUTH_REGISTER, $callback);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$user = User::factory()->make();
|
||||
$this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals('standard', $args[0]);
|
||||
$this->assertInstanceOf(User::class, $args[1]);
|
||||
}
|
||||
|
||||
public function test_event_auth_pre_register()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
Theme::listen(ThemeEvents::AUTH_PRE_REGISTER, $callback);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$user = User::factory()->make();
|
||||
$this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals('standard', $args[0]);
|
||||
$this->assertEquals([
|
||||
'email' => $user->email,
|
||||
'name' => $user->name,
|
||||
'password' => 'password',
|
||||
], $args[1]);
|
||||
$this->assertDatabaseHas('users', ['email' => $user->email]);
|
||||
}
|
||||
|
||||
public function test_event_auth_pre_register_with_false_return_blocks_registration()
|
||||
{
|
||||
$callback = function () {
|
||||
return false;
|
||||
};
|
||||
Theme::listen(ThemeEvents::AUTH_PRE_REGISTER, $callback);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$user = User::factory()->make();
|
||||
$resp = $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
|
||||
$resp->assertRedirect('/login');
|
||||
$this->assertSessionError('User account could not be registered for the provided details');
|
||||
$this->assertDatabaseMissing('users', ['email' => $user->email]);
|
||||
}
|
||||
|
||||
public function test_event_webhook_call_before()
|
||||
{
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
|
||||
return ['test' => 'hello!'];
|
||||
};
|
||||
Theme::listen(ThemeEvents::WEBHOOK_CALL_BEFORE, $callback);
|
||||
|
||||
$responses = $this->mockHttpClient([new \GuzzleHttp\Psr7\Response(200, [], '')]);
|
||||
|
||||
$webhook = new Webhook(['name' => 'Test webhook', 'endpoint' => 'https://example.com']);
|
||||
$webhook->save();
|
||||
$event = ActivityType::PAGE_UPDATE;
|
||||
$detail = Page::query()->first();
|
||||
|
||||
dispatch((new DispatchWebhookJob($webhook, $event, $detail)));
|
||||
|
||||
$this->assertCount(5, $args);
|
||||
$this->assertEquals($event, $args[0]);
|
||||
$this->assertEquals($webhook->id, $args[1]->id);
|
||||
$this->assertEquals($detail->id, $args[2]->id);
|
||||
|
||||
$this->assertEquals(1, $responses->requestCount());
|
||||
$request = $responses->latestRequest();
|
||||
$reqData = json_decode($request->getBody(), true);
|
||||
$this->assertEquals('hello!', $reqData['test']);
|
||||
}
|
||||
|
||||
public function test_event_activity_logged()
|
||||
{
|
||||
$book = $this->entities->book();
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::ACTIVITY_LOGGED, $callback);
|
||||
$this->asEditor()->put($book->getUrl(), ['name' => 'My cool update book!']);
|
||||
|
||||
$this->assertCount(2, $args);
|
||||
$this->assertEquals(ActivityType::BOOK_UPDATE, $args[0]);
|
||||
$this->assertTrue($args[1] instanceof Book);
|
||||
$this->assertEquals($book->id, $args[1]->id);
|
||||
}
|
||||
|
||||
public function test_event_page_include_parse()
|
||||
{
|
||||
/** @var Page $page */
|
||||
/** @var Page $otherPage */
|
||||
$page = $this->entities->page();
|
||||
$otherPage = Page::query()->where('id', '!=', $page->id)->first();
|
||||
$otherPage->html = '<p id="bkmrk-cool">This is a really cool section</p>';
|
||||
$page->html = "<p>{{@{$otherPage->id}#bkmrk-cool}}</p>";
|
||||
$page->save();
|
||||
$otherPage->save();
|
||||
|
||||
$args = [];
|
||||
$callback = function (...$eventArgs) use (&$args) {
|
||||
$args = $eventArgs;
|
||||
|
||||
return '<strong>Big & content replace surprise!</strong>';
|
||||
};
|
||||
|
||||
Theme::listen(ThemeEvents::PAGE_INCLUDE_PARSE, $callback);
|
||||
$resp = $this->asEditor()->get($page->getUrl());
|
||||
$this->withHtml($resp)->assertElementContains('.page-content strong', 'Big & content replace surprise!');
|
||||
|
||||
$this->assertCount(4, $args);
|
||||
$this->assertEquals($otherPage->id . '#bkmrk-cool', $args[0]);
|
||||
$this->assertEquals('This is a really cool section', $args[1]);
|
||||
$this->assertTrue($args[2] instanceof Page);
|
||||
$this->assertTrue($args[3] instanceof Page);
|
||||
$this->assertEquals($page->id, $args[2]->id);
|
||||
$this->assertEquals($otherPage->id, $args[3]->id);
|
||||
}
|
||||
|
||||
public function test_event_routes_register_web_and_web_auth()
|
||||
{
|
||||
$functionsContent = <<<'END'
|
||||
<?php
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Facades\Theme;
|
||||
use Illuminate\Routing\Router;
|
||||
Theme::listen(ThemeEvents::ROUTES_REGISTER_WEB, function (Router $router) {
|
||||
$router->get('/cat', fn () => 'cat')->name('say.cat');
|
||||
});
|
||||
Theme::listen(ThemeEvents::ROUTES_REGISTER_WEB_AUTH, function (Router $router) {
|
||||
$router->get('/dog', fn () => 'dog')->name('say.dog');
|
||||
});
|
||||
END;
|
||||
|
||||
$this->usingThemeFolder(function () use ($functionsContent) {
|
||||
|
||||
$functionsFile = theme_path('functions.php');
|
||||
file_put_contents($functionsFile, $functionsContent);
|
||||
|
||||
$app = $this->createApplication();
|
||||
/** @var \Illuminate\Routing\Router $router */
|
||||
$router = $app->get('router');
|
||||
|
||||
/** @var \Illuminate\Routing\Route $catRoute */
|
||||
$catRoute = $router->getRoutes()->getRoutesByName()['say.cat'];
|
||||
$this->assertEquals(['web'], $catRoute->middleware());
|
||||
|
||||
/** @var \Illuminate\Routing\Route $dogRoute */
|
||||
$dogRoute = $router->getRoutes()->getRoutesByName()['say.dog'];
|
||||
$this->assertEquals(['web', 'auth'], $dogRoute->middleware());
|
||||
});
|
||||
}
|
||||
|
||||
public function test_add_social_driver()
|
||||
{
|
||||
Theme::addSocialDriver('catnet', [
|
||||
'client_id' => 'abc123',
|
||||
'client_secret' => 'def456',
|
||||
], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
|
||||
|
||||
$this->assertEquals('catnet', config('services.catnet.name'));
|
||||
$this->assertEquals('abc123', config('services.catnet.client_id'));
|
||||
$this->assertEquals(url('/login/service/catnet/callback'), config('services.catnet.redirect'));
|
||||
|
||||
$loginResp = $this->get('/login');
|
||||
$loginResp->assertSee('login/service/catnet');
|
||||
}
|
||||
|
||||
public function test_add_social_driver_uses_name_in_config_if_given()
|
||||
{
|
||||
Theme::addSocialDriver('catnet', [
|
||||
'client_id' => 'abc123',
|
||||
'client_secret' => 'def456',
|
||||
'name' => 'Super Cat Name',
|
||||
], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
|
||||
|
||||
$this->assertEquals('Super Cat Name', config('services.catnet.name'));
|
||||
$loginResp = $this->get('/login');
|
||||
$loginResp->assertSee('Super Cat Name');
|
||||
}
|
||||
|
||||
public function test_add_social_driver_allows_a_configure_for_redirect_callback_to_be_passed()
|
||||
{
|
||||
Theme::addSocialDriver(
|
||||
'discord',
|
||||
[
|
||||
'client_id' => 'abc123',
|
||||
'client_secret' => 'def456',
|
||||
'name' => 'Super Cat Name',
|
||||
],
|
||||
'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
|
||||
function ($driver) {
|
||||
$driver->with(['donkey' => 'donut']);
|
||||
}
|
||||
);
|
||||
|
||||
$loginResp = $this->get('/login/service/discord');
|
||||
$redirect = $loginResp->headers->get('location');
|
||||
$this->assertStringContainsString('donkey=donut', $redirect);
|
||||
}
|
||||
|
||||
public function test_register_command_allows_provided_command_to_be_usable_via_artisan()
|
||||
{
|
||||
Theme::registerCommand(new MyCustomCommand());
|
||||
|
||||
Artisan::call('bookstack:test-custom-command', []);
|
||||
$output = Artisan::output();
|
||||
|
||||
$this->assertStringContainsString('Command ran!', $output);
|
||||
}
|
||||
|
||||
public function test_base_body_start_and_end_template_files_can_be_used()
|
||||
{
|
||||
$bodyStartStr = 'barry-fought-against-the-panther';
|
||||
$bodyEndStr = 'barry-lost-his-fight-with-grace';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr) {
|
||||
$viewDir = theme_path('layouts/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/base-body-start.blade.php', $bodyStartStr);
|
||||
file_put_contents($viewDir . '/base-body-end.blade.php', $bodyEndStr);
|
||||
|
||||
$resp = $this->asEditor()->get('/');
|
||||
$resp->assertSee($bodyStartStr);
|
||||
$resp->assertSee($bodyEndStr);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_export_body_start_and_end_template_files_can_be_used()
|
||||
{
|
||||
$bodyStartStr = 'garry-fought-against-the-panther';
|
||||
$bodyEndStr = 'garry-lost-his-fight-with-grace';
|
||||
$page = $this->entities->page();
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr, $page) {
|
||||
$viewDir = theme_path('layouts/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/export-body-start.blade.php', $bodyStartStr);
|
||||
file_put_contents($viewDir . '/export-body-end.blade.php', $bodyEndStr);
|
||||
|
||||
$resp = $this->asEditor()->get($page->getUrl('/export/html'));
|
||||
$resp->assertSee($bodyStartStr);
|
||||
$resp->assertSee($bodyEndStr);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_login_and_register_message_template_files_can_be_used()
|
||||
{
|
||||
$loginMessage = 'Welcome to this instance, login below you scallywag';
|
||||
$registerMessage = 'You want to register? Enter the deets below you numpty';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($loginMessage, $registerMessage) {
|
||||
$viewDir = theme_path('auth/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/login-message.blade.php', $loginMessage);
|
||||
file_put_contents($viewDir . '/register-message.blade.php', $registerMessage);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$this->get('/login')->assertSee($loginMessage);
|
||||
$this->get('/register')->assertSee($registerMessage);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_header_links_start_template_file_can_be_used()
|
||||
{
|
||||
$content = 'This is added text in the header bar';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($content) {
|
||||
$viewDir = theme_path('layouts/parts');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/header-links-start.blade.php', $content);
|
||||
$this->setSettings(['registration-enabled' => 'true']);
|
||||
|
||||
$this->get('/login')->assertSee($content);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_custom_settings_category_page_can_be_added_via_view_file()
|
||||
{
|
||||
$content = 'My SuperCustomSettings';
|
||||
|
||||
$this->usingThemeFolder(function (string $folder) use ($content) {
|
||||
$viewDir = theme_path('settings/categories');
|
||||
mkdir($viewDir, 0777, true);
|
||||
file_put_contents($viewDir . '/beans.blade.php', $content);
|
||||
|
||||
$this->asAdmin()->get('/settings/beans')->assertSee($content);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_public_folder_contents_accessible_via_route()
|
||||
{
|
||||
$this->usingThemeFolder(function (string $themeFolderName) {
|
||||
$publicDir = theme_path('public');
|
||||
mkdir($publicDir, 0777, true);
|
||||
|
||||
$text = 'some-text ' . md5(random_bytes(5));
|
||||
$css = "body { background-color: tomato !important; }";
|
||||
file_put_contents("{$publicDir}/file.txt", $text);
|
||||
file_put_contents("{$publicDir}/file.css", $css);
|
||||
copy($this->files->testFilePath('test-image.png'), "{$publicDir}/image.png");
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/file.txt");
|
||||
$resp->assertStreamedContent($text);
|
||||
$resp->assertHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/image.png");
|
||||
$resp->assertHeader('Content-Type', 'image/png');
|
||||
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
|
||||
|
||||
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/file.css");
|
||||
$resp->assertStreamedContent($css);
|
||||
$resp->assertHeader('Content-Type', 'text/css; charset=utf-8');
|
||||
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
|
||||
});
|
||||
}
|
||||
|
||||
protected function usingThemeFolder(callable $callback)
|
||||
{
|
||||
// Create a folder and configure a theme
|
||||
$themeFolderName = 'testing_theme_' . str_shuffle(rtrim(base64_encode(time()), '='));
|
||||
config()->set('view.theme', $themeFolderName);
|
||||
$themeFolderPath = theme_path('');
|
||||
|
||||
// Create theme folder and clean it up on application tear-down
|
||||
File::makeDirectory($themeFolderPath);
|
||||
$this->beforeApplicationDestroyed(fn() => File::deleteDirectory($themeFolderPath));
|
||||
|
||||
// Run provided callback with theme env option set
|
||||
$this->runWithEnv(['APP_THEME' => $themeFolderName], function () use ($callback, $themeFolderName) {
|
||||
call_user_func($callback, $themeFolderName);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class MyCustomCommand extends Command
|
||||
{
|
||||
protected $signature = 'bookstack:test-custom-command';
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$this->line('Command ran!');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user