5 use BookStack\Activity\ActivityType;
6 use BookStack\Activity\DispatchWebhookJob;
7 use BookStack\Activity\Models\Webhook;
8 use BookStack\Entities\Models\Book;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Tools\PageContent;
11 use BookStack\Exceptions\ThemeException;
12 use BookStack\Facades\Theme;
13 use BookStack\Theming\ThemeEvents;
14 use BookStack\Users\Models\User;
15 use Illuminate\Console\Command;
16 use Illuminate\Http\Request;
17 use Illuminate\Http\Response;
18 use Illuminate\Support\Facades\Artisan;
19 use Illuminate\Support\Facades\File;
20 use League\CommonMark\Environment\Environment;
22 class ThemeTest extends TestCase
24 protected string $themeFolderName;
25 protected string $themeFolderPath;
27 public function test_translation_text_can_be_overridden_via_theme()
29 $this->usingThemeFolder(function () {
30 $translationPath = theme_path('/lang/en');
31 File::makeDirectory($translationPath, 0777, true);
33 $customTranslations = '<?php
34 return [\'books\' => \'Sandwiches\'];
36 file_put_contents($translationPath . '/entities.php', $customTranslations);
38 $homeRequest = $this->actingAs($this->users->viewer())->get('/');
39 $this->withHtml($homeRequest)->assertElementContains('header nav', 'Sandwiches');
43 public function test_theme_functions_file_used_and_app_boot_event_runs()
45 $this->usingThemeFolder(function ($themeFolder) {
46 $functionsFile = theme_path('functions.php');
47 app()->alias('cat', 'dog');
48 file_put_contents($functionsFile, "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('cat', 'dog');});");
49 $this->runWithEnv('APP_THEME', $themeFolder, function () {
50 $this->assertEquals('cat', $this->app->getAlias('dog'));
55 public function test_theme_functions_loads_errors_are_caught_and_logged()
57 $this->usingThemeFolder(function ($themeFolder) {
58 $functionsFile = theme_path('functions.php');
59 file_put_contents($functionsFile, "<?php\n\\BookStack\\Biscuits::eat();");
61 $this->expectException(ThemeException::class);
62 $this->expectExceptionMessageMatches('/Failed loading theme functions file at ".*?" with error: Class "BookStack\\\\Biscuits" not found/');
64 $this->runWithEnv('APP_THEME', $themeFolder, fn() => null);
68 public function test_event_commonmark_environment_configure()
70 $callbackCalled = false;
71 $callback = function ($environment) use (&$callbackCalled) {
72 $this->assertInstanceOf(Environment::class, $environment);
73 $callbackCalled = true;
77 Theme::listen(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $callback);
79 $page = $this->entities->page();
80 $content = new PageContent($page);
81 $content->setNewMarkdown('# test');
83 $this->assertTrue($callbackCalled);
86 public function test_event_web_middleware_before()
88 $callbackCalled = false;
90 $callback = function ($request) use (&$callbackCalled, &$requestParam) {
91 $requestParam = $request;
92 $callbackCalled = true;
95 Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
96 $this->get('/login', ['Donkey' => 'cat']);
98 $this->assertTrue($callbackCalled);
99 $this->assertInstanceOf(Request::class, $requestParam);
100 $this->assertEquals('cat', $requestParam->header('donkey'));
103 public function test_event_web_middleware_before_return_val_used_as_response()
105 $callback = function (Request $request) {
106 return response('cat', 412);
109 Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
110 $resp = $this->get('/login', ['Donkey' => 'cat']);
111 $resp->assertSee('cat');
112 $resp->assertStatus(412);
115 public function test_event_web_middleware_after()
117 $callbackCalled = false;
118 $requestParam = null;
119 $responseParam = null;
120 $callback = function ($request, Response $response) use (&$callbackCalled, &$requestParam, &$responseParam) {
121 $requestParam = $request;
122 $responseParam = $response;
123 $callbackCalled = true;
124 $response->header('donkey', 'cat123');
127 Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
129 $resp = $this->get('/login', ['Donkey' => 'cat']);
130 $this->assertTrue($callbackCalled);
131 $this->assertInstanceOf(Request::class, $requestParam);
132 $this->assertInstanceOf(Response::class, $responseParam);
133 $resp->assertHeader('donkey', 'cat123');
136 public function test_event_web_middleware_after_return_val_used_as_response()
138 $callback = function () {
139 return response('cat456', 443);
142 Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
144 $resp = $this->get('/login', ['Donkey' => 'cat']);
145 $resp->assertSee('cat456');
146 $resp->assertStatus(443);
149 public function test_event_auth_login_standard()
152 $callback = function (...$eventArgs) use (&$args) {
156 Theme::listen(ThemeEvents::AUTH_LOGIN, $callback);
159 $this->assertCount(2, $args);
160 $this->assertEquals('standard', $args[0]);
161 $this->assertInstanceOf(User::class, $args[1]);
164 public function test_event_auth_register_standard()
167 $callback = function (...$eventArgs) use (&$args) {
170 Theme::listen(ThemeEvents::AUTH_REGISTER, $callback);
171 $this->setSettings(['registration-enabled' => 'true']);
173 $user = User::factory()->make();
174 $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
176 $this->assertCount(2, $args);
177 $this->assertEquals('standard', $args[0]);
178 $this->assertInstanceOf(User::class, $args[1]);
181 public function test_event_webhook_call_before()
184 $callback = function (...$eventArgs) use (&$args) {
187 return ['test' => 'hello!'];
189 Theme::listen(ThemeEvents::WEBHOOK_CALL_BEFORE, $callback);
191 $responses = $this->mockHttpClient([new \GuzzleHttp\Psr7\Response(200, [], '')]);
193 $webhook = new Webhook(['name' => 'Test webhook', 'endpoint' => 'https://example.com']);
195 $event = ActivityType::PAGE_UPDATE;
196 $detail = Page::query()->first();
198 dispatch((new DispatchWebhookJob($webhook, $event, $detail)));
200 $this->assertCount(5, $args);
201 $this->assertEquals($event, $args[0]);
202 $this->assertEquals($webhook->id, $args[1]->id);
203 $this->assertEquals($detail->id, $args[2]->id);
205 $this->assertEquals(1, $responses->requestCount());
206 $request = $responses->latestRequest();
207 $reqData = json_decode($request->getBody(), true);
208 $this->assertEquals('hello!', $reqData['test']);
211 public function test_event_activity_logged()
213 $book = $this->entities->book();
215 $callback = function (...$eventArgs) use (&$args) {
219 Theme::listen(ThemeEvents::ACTIVITY_LOGGED, $callback);
220 $this->asEditor()->put($book->getUrl(), ['name' => 'My cool update book!']);
222 $this->assertCount(2, $args);
223 $this->assertEquals(ActivityType::BOOK_UPDATE, $args[0]);
224 $this->assertTrue($args[1] instanceof Book);
225 $this->assertEquals($book->id, $args[1]->id);
228 public function test_event_page_include_parse()
230 /** @var Page $page */
231 /** @var Page $otherPage */
232 $page = $this->entities->page();
233 $otherPage = Page::query()->where('id', '!=', $page->id)->first();
234 $otherPage->html = '<p id="bkmrk-cool">This is a really cool section</p>';
235 $page->html = "<p>{{@{$otherPage->id}#bkmrk-cool}}</p>";
240 $callback = function (...$eventArgs) use (&$args) {
243 return '<strong>Big & content replace surprise!</strong>';
246 Theme::listen(ThemeEvents::PAGE_INCLUDE_PARSE, $callback);
247 $resp = $this->asEditor()->get($page->getUrl());
248 $this->withHtml($resp)->assertElementContains('.page-content strong', 'Big & content replace surprise!');
250 $this->assertCount(4, $args);
251 $this->assertEquals($otherPage->id . '#bkmrk-cool', $args[0]);
252 $this->assertEquals('This is a really cool section', $args[1]);
253 $this->assertTrue($args[2] instanceof Page);
254 $this->assertTrue($args[3] instanceof Page);
255 $this->assertEquals($page->id, $args[2]->id);
256 $this->assertEquals($otherPage->id, $args[3]->id);
259 public function test_add_social_driver()
261 Theme::addSocialDriver('catnet', [
262 'client_id' => 'abc123',
263 'client_secret' => 'def456',
264 ], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
266 $this->assertEquals('catnet', config('services.catnet.name'));
267 $this->assertEquals('abc123', config('services.catnet.client_id'));
268 $this->assertEquals(url('/login/service/catnet/callback'), config('services.catnet.redirect'));
270 $loginResp = $this->get('/login');
271 $loginResp->assertSee('login/service/catnet');
274 public function test_add_social_driver_uses_name_in_config_if_given()
276 Theme::addSocialDriver('catnet', [
277 'client_id' => 'abc123',
278 'client_secret' => 'def456',
279 'name' => 'Super Cat Name',
280 ], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
282 $this->assertEquals('Super Cat Name', config('services.catnet.name'));
283 $loginResp = $this->get('/login');
284 $loginResp->assertSee('Super Cat Name');
287 public function test_add_social_driver_allows_a_configure_for_redirect_callback_to_be_passed()
289 Theme::addSocialDriver(
292 'client_id' => 'abc123',
293 'client_secret' => 'def456',
294 'name' => 'Super Cat Name',
296 'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
298 $driver->with(['donkey' => 'donut']);
302 $loginResp = $this->get('/login/service/discord');
303 $redirect = $loginResp->headers->get('location');
304 $this->assertStringContainsString('donkey=donut', $redirect);
307 public function test_register_command_allows_provided_command_to_be_usable_via_artisan()
309 Theme::registerCommand(new MyCustomCommand());
311 Artisan::call('bookstack:test-custom-command', []);
312 $output = Artisan::output();
314 $this->assertStringContainsString('Command ran!', $output);
317 public function test_base_body_start_and_end_template_files_can_be_used()
319 $bodyStartStr = 'barry-fought-against-the-panther';
320 $bodyEndStr = 'barry-lost-his-fight-with-grace';
322 $this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr) {
323 $viewDir = theme_path('layouts/parts');
324 mkdir($viewDir, 0777, true);
325 file_put_contents($viewDir . '/base-body-start.blade.php', $bodyStartStr);
326 file_put_contents($viewDir . '/base-body-end.blade.php', $bodyEndStr);
328 $resp = $this->asEditor()->get('/');
329 $resp->assertSee($bodyStartStr);
330 $resp->assertSee($bodyEndStr);
334 public function test_export_body_start_and_end_template_files_can_be_used()
336 $bodyStartStr = 'garry-fought-against-the-panther';
337 $bodyEndStr = 'garry-lost-his-fight-with-grace';
338 $page = $this->entities->page();
340 $this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr, $page) {
341 $viewDir = theme_path('layouts/parts');
342 mkdir($viewDir, 0777, true);
343 file_put_contents($viewDir . '/export-body-start.blade.php', $bodyStartStr);
344 file_put_contents($viewDir . '/export-body-end.blade.php', $bodyEndStr);
346 $resp = $this->asEditor()->get($page->getUrl('/export/html'));
347 $resp->assertSee($bodyStartStr);
348 $resp->assertSee($bodyEndStr);
352 public function test_login_and_register_message_template_files_can_be_used()
354 $loginMessage = 'Welcome to this instance, login below you scallywag';
355 $registerMessage = 'You want to register? Enter the deets below you numpty';
357 $this->usingThemeFolder(function (string $folder) use ($loginMessage, $registerMessage) {
358 $viewDir = theme_path('auth/parts');
359 mkdir($viewDir, 0777, true);
360 file_put_contents($viewDir . '/login-message.blade.php', $loginMessage);
361 file_put_contents($viewDir . '/register-message.blade.php', $registerMessage);
362 $this->setSettings(['registration-enabled' => 'true']);
364 $this->get('/login')->assertSee($loginMessage);
365 $this->get('/register')->assertSee($registerMessage);
369 public function test_header_links_start_template_file_can_be_used()
371 $content = 'This is added text in the header bar';
373 $this->usingThemeFolder(function (string $folder) use ($content) {
374 $viewDir = theme_path('layouts/parts');
375 mkdir($viewDir, 0777, true);
376 file_put_contents($viewDir . '/header-links-start.blade.php', $content);
377 $this->setSettings(['registration-enabled' => 'true']);
379 $this->get('/login')->assertSee($content);
383 protected function usingThemeFolder(callable $callback)
385 // Create a folder and configure a theme
386 $themeFolderName = 'testing_theme_' . str_shuffle(rtrim(base64_encode(time()), '='));
387 config()->set('view.theme', $themeFolderName);
388 $themeFolderPath = theme_path('');
390 // Create theme folder and clean it up on application tear-down
391 File::makeDirectory($themeFolderPath);
392 $this->beforeApplicationDestroyed(fn() => File::deleteDirectory($themeFolderPath));
394 // Run provided callback with theme env option set
395 $this->runWithEnv('APP_THEME', $themeFolderName, function () use ($callback, $themeFolderName) {
396 call_user_func($callback, $themeFolderName);
401 class MyCustomCommand extends Command
403 protected $signature = 'bookstack:test-custom-command';
405 public function handle()
407 $this->line('Command ran!');