]> BookStack Code Mirror - bookstack/blob - tests/ThemeTest.php
53361e35194dad7b8fdec639373cc1a673bdfdd4
[bookstack] / tests / ThemeTest.php
1 <?php
2
3 namespace Tests;
4
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;
21
22 class ThemeTest extends TestCase
23 {
24     protected string $themeFolderName;
25     protected string $themeFolderPath;
26
27     public function test_translation_text_can_be_overridden_via_theme()
28     {
29         $this->usingThemeFolder(function () {
30             $translationPath = theme_path('/lang/en');
31             File::makeDirectory($translationPath, 0777, true);
32
33             $customTranslations = '<?php
34             return [\'books\' => \'Sandwiches\'];
35         ';
36             file_put_contents($translationPath . '/entities.php', $customTranslations);
37
38             $homeRequest = $this->actingAs($this->users->viewer())->get('/');
39             $this->withHtml($homeRequest)->assertElementContains('header nav', 'Sandwiches');
40         });
41     }
42
43     public function test_theme_functions_file_used_and_app_boot_event_runs()
44     {
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'));
51             });
52         });
53     }
54
55     public function test_theme_functions_loads_errors_are_caught_and_logged()
56     {
57         $this->usingThemeFolder(function ($themeFolder) {
58             $functionsFile = theme_path('functions.php');
59             file_put_contents($functionsFile, "<?php\n\\BookStack\\Biscuits::eat();");
60
61             $this->expectException(ThemeException::class);
62             $this->expectExceptionMessageMatches('/Failed loading theme functions file at ".*?" with error: Class "BookStack\\\\Biscuits" not found/');
63
64             $this->runWithEnv('APP_THEME', $themeFolder, fn() => null);
65         });
66     }
67
68     public function test_event_commonmark_environment_configure()
69     {
70         $callbackCalled = false;
71         $callback = function ($environment) use (&$callbackCalled) {
72             $this->assertInstanceOf(Environment::class, $environment);
73             $callbackCalled = true;
74
75             return $environment;
76         };
77         Theme::listen(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $callback);
78
79         $page = $this->entities->page();
80         $content = new PageContent($page);
81         $content->setNewMarkdown('# test');
82
83         $this->assertTrue($callbackCalled);
84     }
85
86     public function test_event_web_middleware_before()
87     {
88         $callbackCalled = false;
89         $requestParam = null;
90         $callback = function ($request) use (&$callbackCalled, &$requestParam) {
91             $requestParam = $request;
92             $callbackCalled = true;
93         };
94
95         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
96         $this->get('/login', ['Donkey' => 'cat']);
97
98         $this->assertTrue($callbackCalled);
99         $this->assertInstanceOf(Request::class, $requestParam);
100         $this->assertEquals('cat', $requestParam->header('donkey'));
101     }
102
103     public function test_event_web_middleware_before_return_val_used_as_response()
104     {
105         $callback = function (Request $request) {
106             return response('cat', 412);
107         };
108
109         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
110         $resp = $this->get('/login', ['Donkey' => 'cat']);
111         $resp->assertSee('cat');
112         $resp->assertStatus(412);
113     }
114
115     public function test_event_web_middleware_after()
116     {
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');
125         };
126
127         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
128
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');
134     }
135
136     public function test_event_web_middleware_after_return_val_used_as_response()
137     {
138         $callback = function () {
139             return response('cat456', 443);
140         };
141
142         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
143
144         $resp = $this->get('/login', ['Donkey' => 'cat']);
145         $resp->assertSee('cat456');
146         $resp->assertStatus(443);
147     }
148
149     public function test_event_auth_login_standard()
150     {
151         $args = [];
152         $callback = function (...$eventArgs) use (&$args) {
153             $args = $eventArgs;
154         };
155
156         Theme::listen(ThemeEvents::AUTH_LOGIN, $callback);
157         $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
158
159         $this->assertCount(2, $args);
160         $this->assertEquals('standard', $args[0]);
161         $this->assertInstanceOf(User::class, $args[1]);
162     }
163
164     public function test_event_auth_register_standard()
165     {
166         $args = [];
167         $callback = function (...$eventArgs) use (&$args) {
168             $args = $eventArgs;
169         };
170         Theme::listen(ThemeEvents::AUTH_REGISTER, $callback);
171         $this->setSettings(['registration-enabled' => 'true']);
172
173         $user = User::factory()->make();
174         $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
175
176         $this->assertCount(2, $args);
177         $this->assertEquals('standard', $args[0]);
178         $this->assertInstanceOf(User::class, $args[1]);
179     }
180
181     public function test_event_webhook_call_before()
182     {
183         $args = [];
184         $callback = function (...$eventArgs) use (&$args) {
185             $args = $eventArgs;
186
187             return ['test' => 'hello!'];
188         };
189         Theme::listen(ThemeEvents::WEBHOOK_CALL_BEFORE, $callback);
190
191         $responses = $this->mockHttpClient([new \GuzzleHttp\Psr7\Response(200, [], '')]);
192
193         $webhook = new Webhook(['name' => 'Test webhook', 'endpoint' => 'https://example.com']);
194         $webhook->save();
195         $event = ActivityType::PAGE_UPDATE;
196         $detail = Page::query()->first();
197
198         dispatch((new DispatchWebhookJob($webhook, $event, $detail)));
199
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);
204
205         $this->assertEquals(1, $responses->requestCount());
206         $request = $responses->latestRequest();
207         $reqData = json_decode($request->getBody(), true);
208         $this->assertEquals('hello!', $reqData['test']);
209     }
210
211     public function test_event_activity_logged()
212     {
213         $book = $this->entities->book();
214         $args = [];
215         $callback = function (...$eventArgs) use (&$args) {
216             $args = $eventArgs;
217         };
218
219         Theme::listen(ThemeEvents::ACTIVITY_LOGGED, $callback);
220         $this->asEditor()->put($book->getUrl(), ['name' => 'My cool update book!']);
221
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);
226     }
227
228     public function test_event_page_include_parse()
229     {
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>";
236         $page->save();
237         $otherPage->save();
238
239         $args = [];
240         $callback = function (...$eventArgs) use (&$args) {
241             $args = $eventArgs;
242
243             return '<strong>Big &amp; content replace surprise!</strong>';
244         };
245
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!');
249
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);
257     }
258
259     public function test_add_social_driver()
260     {
261         Theme::addSocialDriver('catnet', [
262             'client_id'     => 'abc123',
263             'client_secret' => 'def456',
264         ], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
265
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'));
269
270         $loginResp = $this->get('/login');
271         $loginResp->assertSee('login/service/catnet');
272     }
273
274     public function test_add_social_driver_uses_name_in_config_if_given()
275     {
276         Theme::addSocialDriver('catnet', [
277             'client_id'     => 'abc123',
278             'client_secret' => 'def456',
279             'name'          => 'Super Cat Name',
280         ], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
281
282         $this->assertEquals('Super Cat Name', config('services.catnet.name'));
283         $loginResp = $this->get('/login');
284         $loginResp->assertSee('Super Cat Name');
285     }
286
287     public function test_add_social_driver_allows_a_configure_for_redirect_callback_to_be_passed()
288     {
289         Theme::addSocialDriver(
290             'discord',
291             [
292                 'client_id'     => 'abc123',
293                 'client_secret' => 'def456',
294                 'name'          => 'Super Cat Name',
295             ],
296             'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
297             function ($driver) {
298                 $driver->with(['donkey' => 'donut']);
299             }
300         );
301
302         $loginResp = $this->get('/login/service/discord');
303         $redirect = $loginResp->headers->get('location');
304         $this->assertStringContainsString('donkey=donut', $redirect);
305     }
306
307     public function test_register_command_allows_provided_command_to_be_usable_via_artisan()
308     {
309         Theme::registerCommand(new MyCustomCommand());
310
311         Artisan::call('bookstack:test-custom-command', []);
312         $output = Artisan::output();
313
314         $this->assertStringContainsString('Command ran!', $output);
315     }
316
317     public function test_base_body_start_and_end_template_files_can_be_used()
318     {
319         $bodyStartStr = 'barry-fought-against-the-panther';
320         $bodyEndStr = 'barry-lost-his-fight-with-grace';
321
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);
327
328             $resp = $this->asEditor()->get('/');
329             $resp->assertSee($bodyStartStr);
330             $resp->assertSee($bodyEndStr);
331         });
332     }
333
334     public function test_export_body_start_and_end_template_files_can_be_used()
335     {
336         $bodyStartStr = 'garry-fought-against-the-panther';
337         $bodyEndStr = 'garry-lost-his-fight-with-grace';
338         $page = $this->entities->page();
339
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);
345
346             $resp = $this->asEditor()->get($page->getUrl('/export/html'));
347             $resp->assertSee($bodyStartStr);
348             $resp->assertSee($bodyEndStr);
349         });
350     }
351
352     public function test_login_and_register_message_template_files_can_be_used()
353     {
354         $loginMessage = 'Welcome to this instance, login below you scallywag';
355         $registerMessage = 'You want to register? Enter the deets below you numpty';
356
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']);
363
364             $this->get('/login')->assertSee($loginMessage);
365             $this->get('/register')->assertSee($registerMessage);
366         });
367     }
368
369     public function test_header_links_start_template_file_can_be_used()
370     {
371         $content = 'This is added text in the header bar';
372
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']);
378
379             $this->get('/login')->assertSee($content);
380         });
381     }
382
383     protected function usingThemeFolder(callable $callback)
384     {
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('');
389
390         // Create theme folder and clean it up on application tear-down
391         File::makeDirectory($themeFolderPath);
392         $this->beforeApplicationDestroyed(fn() => File::deleteDirectory($themeFolderPath));
393
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);
397         });
398     }
399 }
400
401 class MyCustomCommand extends Command
402 {
403     protected $signature = 'bookstack:test-custom-command';
404
405     public function handle()
406     {
407         $this->line('Command ran!');
408     }
409 }