]> BookStack Code Mirror - bookstack/blob - tests/ThemeTest.php
Fixed local_secure_restricted preventing attachment uploads
[bookstack] / tests / ThemeTest.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Actions\DispatchWebhookJob;
7 use BookStack\Actions\Webhook;
8 use BookStack\Auth\User;
9 use BookStack\Entities\Models\Book;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Entities\Tools\PageContent;
12 use BookStack\Facades\Theme;
13 use BookStack\Theming\ThemeEvents;
14 use Illuminate\Console\Command;
15 use Illuminate\Http\Client\Request as HttpClientRequest;
16 use Illuminate\Http\Request;
17 use Illuminate\Http\Response;
18 use Illuminate\Support\Facades\Artisan;
19 use Illuminate\Support\Facades\File;
20 use Illuminate\Support\Facades\Http;
21 use League\CommonMark\ConfigurableEnvironmentInterface;
22
23 class ThemeTest extends TestCase
24 {
25     protected $themeFolderName;
26     protected $themeFolderPath;
27
28     public function test_translation_text_can_be_overridden_via_theme()
29     {
30         $this->usingThemeFolder(function () {
31             $translationPath = theme_path('/lang/en');
32             File::makeDirectory($translationPath, 0777, true);
33
34             $customTranslations = '<?php
35             return [\'books\' => \'Sandwiches\'];
36         ';
37             file_put_contents($translationPath . '/entities.php', $customTranslations);
38
39             $homeRequest = $this->actingAs($this->getViewer())->get('/');
40             $this->withHtml($homeRequest)->assertElementContains('header nav', 'Sandwiches');
41         });
42     }
43
44     public function test_theme_functions_file_used_and_app_boot_event_runs()
45     {
46         $this->usingThemeFolder(function ($themeFolder) {
47             $functionsFile = theme_path('functions.php');
48             app()->alias('cat', 'dog');
49             file_put_contents($functionsFile, "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('cat', 'dog');});");
50             $this->runWithEnv('APP_THEME', $themeFolder, function () {
51                 $this->assertEquals('cat', $this->app->getAlias('dog'));
52             });
53         });
54     }
55
56     public function test_event_commonmark_environment_configure()
57     {
58         $callbackCalled = false;
59         $callback = function ($environment) use (&$callbackCalled) {
60             $this->assertInstanceOf(ConfigurableEnvironmentInterface::class, $environment);
61             $callbackCalled = true;
62
63             return $environment;
64         };
65         Theme::listen(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $callback);
66
67         $page = Page::query()->first();
68         $content = new PageContent($page);
69         $content->setNewMarkdown('# test');
70
71         $this->assertTrue($callbackCalled);
72     }
73
74     public function test_event_web_middleware_before()
75     {
76         $callbackCalled = false;
77         $requestParam = null;
78         $callback = function ($request) use (&$callbackCalled, &$requestParam) {
79             $requestParam = $request;
80             $callbackCalled = true;
81         };
82
83         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
84         $this->get('/login', ['Donkey' => 'cat']);
85
86         $this->assertTrue($callbackCalled);
87         $this->assertInstanceOf(Request::class, $requestParam);
88         $this->assertEquals('cat', $requestParam->header('donkey'));
89     }
90
91     public function test_event_web_middleware_before_return_val_used_as_response()
92     {
93         $callback = function (Request $request) {
94             return response('cat', 412);
95         };
96
97         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
98         $resp = $this->get('/login', ['Donkey' => 'cat']);
99         $resp->assertSee('cat');
100         $resp->assertStatus(412);
101     }
102
103     public function test_event_web_middleware_after()
104     {
105         $callbackCalled = false;
106         $requestParam = null;
107         $responseParam = null;
108         $callback = function ($request, Response $response) use (&$callbackCalled, &$requestParam, &$responseParam) {
109             $requestParam = $request;
110             $responseParam = $response;
111             $callbackCalled = true;
112             $response->header('donkey', 'cat123');
113         };
114
115         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
116
117         $resp = $this->get('/login', ['Donkey' => 'cat']);
118         $this->assertTrue($callbackCalled);
119         $this->assertInstanceOf(Request::class, $requestParam);
120         $this->assertInstanceOf(Response::class, $responseParam);
121         $resp->assertHeader('donkey', 'cat123');
122     }
123
124     public function test_event_web_middleware_after_return_val_used_as_response()
125     {
126         $callback = function () {
127             return response('cat456', 443);
128         };
129
130         Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
131
132         $resp = $this->get('/login', ['Donkey' => 'cat']);
133         $resp->assertSee('cat456');
134         $resp->assertStatus(443);
135     }
136
137     public function test_event_auth_login_standard()
138     {
139         $args = [];
140         $callback = function (...$eventArgs) use (&$args) {
141             $args = $eventArgs;
142         };
143
144         Theme::listen(ThemeEvents::AUTH_LOGIN, $callback);
145         $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
146
147         $this->assertCount(2, $args);
148         $this->assertEquals('standard', $args[0]);
149         $this->assertInstanceOf(User::class, $args[1]);
150     }
151
152     public function test_event_auth_register_standard()
153     {
154         $args = [];
155         $callback = function (...$eventArgs) use (&$args) {
156             $args = $eventArgs;
157         };
158         Theme::listen(ThemeEvents::AUTH_REGISTER, $callback);
159         $this->setSettings(['registration-enabled' => 'true']);
160
161         $user = User::factory()->make();
162         $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
163
164         $this->assertCount(2, $args);
165         $this->assertEquals('standard', $args[0]);
166         $this->assertInstanceOf(User::class, $args[1]);
167     }
168
169     public function test_event_webhook_call_before()
170     {
171         $args = [];
172         $callback = function (...$eventArgs) use (&$args) {
173             $args = $eventArgs;
174
175             return ['test' => 'hello!'];
176         };
177         Theme::listen(ThemeEvents::WEBHOOK_CALL_BEFORE, $callback);
178
179         Http::fake([
180             '*' => Http::response('', 200),
181         ]);
182
183         $webhook = new Webhook(['name' => 'Test webhook', 'endpoint' => 'https://example.com']);
184         $webhook->save();
185         $event = ActivityType::PAGE_UPDATE;
186         $detail = Page::query()->first();
187
188         dispatch((new DispatchWebhookJob($webhook, $event, $detail)));
189
190         $this->assertCount(5, $args);
191         $this->assertEquals($event, $args[0]);
192         $this->assertEquals($webhook->id, $args[1]->id);
193         $this->assertEquals($detail->id, $args[2]->id);
194
195         Http::assertSent(function (HttpClientRequest $request) {
196             return $request->isJson() && $request->data()['test'] === 'hello!';
197         });
198     }
199
200     public function test_event_activity_logged()
201     {
202         $book = Book::query()->first();
203         $args = [];
204         $callback = function (...$eventArgs) use (&$args) {
205             $args = $eventArgs;
206         };
207
208         Theme::listen(ThemeEvents::ACTIVITY_LOGGED, $callback);
209         $this->asEditor()->put($book->getUrl(), ['name' => 'My cool update book!']);
210
211         $this->assertCount(2, $args);
212         $this->assertEquals(ActivityType::BOOK_UPDATE, $args[0]);
213         $this->assertTrue($args[1] instanceof Book);
214         $this->assertEquals($book->id, $args[1]->id);
215     }
216
217     public function test_add_social_driver()
218     {
219         Theme::addSocialDriver('catnet', [
220             'client_id'     => 'abc123',
221             'client_secret' => 'def456',
222         ], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
223
224         $this->assertEquals('catnet', config('services.catnet.name'));
225         $this->assertEquals('abc123', config('services.catnet.client_id'));
226         $this->assertEquals(url('/login/service/catnet/callback'), config('services.catnet.redirect'));
227
228         $loginResp = $this->get('/login');
229         $loginResp->assertSee('login/service/catnet');
230     }
231
232     public function test_add_social_driver_uses_name_in_config_if_given()
233     {
234         Theme::addSocialDriver('catnet', [
235             'client_id'     => 'abc123',
236             'client_secret' => 'def456',
237             'name'          => 'Super Cat Name',
238         ], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
239
240         $this->assertEquals('Super Cat Name', config('services.catnet.name'));
241         $loginResp = $this->get('/login');
242         $loginResp->assertSee('Super Cat Name');
243     }
244
245     public function test_add_social_driver_allows_a_configure_for_redirect_callback_to_be_passed()
246     {
247         Theme::addSocialDriver(
248             'discord',
249             [
250                 'client_id'     => 'abc123',
251                 'client_secret' => 'def456',
252                 'name'          => 'Super Cat Name',
253             ],
254             'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
255             function ($driver) {
256                 $driver->with(['donkey' => 'donut']);
257             }
258         );
259
260         $loginResp = $this->get('/login/service/discord');
261         $redirect = $loginResp->headers->get('location');
262         $this->assertStringContainsString('donkey=donut', $redirect);
263     }
264
265     public function test_register_command_allows_provided_command_to_be_usable_via_artisan()
266     {
267         Theme::registerCommand(new MyCustomCommand());
268
269         Artisan::call('bookstack:test-custom-command', []);
270         $output = Artisan::output();
271
272         $this->assertStringContainsString('Command ran!', $output);
273     }
274
275     public function test_base_body_start_and_end_template_files_can_be_used()
276     {
277         $bodyStartStr = 'barry-fought-against-the-panther';
278         $bodyEndStr = 'barry-lost-his-fight-with-grace';
279
280         $this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr) {
281             $viewDir = theme_path('layouts/parts');
282             mkdir($viewDir, 0777, true);
283             file_put_contents($viewDir . '/base-body-start.blade.php', $bodyStartStr);
284             file_put_contents($viewDir . '/base-body-end.blade.php', $bodyEndStr);
285
286             $resp = $this->asEditor()->get('/');
287             $resp->assertSee($bodyStartStr);
288             $resp->assertSee($bodyEndStr);
289         });
290     }
291
292     public function test_export_body_start_and_end_template_files_can_be_used()
293     {
294         $bodyStartStr = 'barry-fought-against-the-panther';
295         $bodyEndStr = 'barry-lost-his-fight-with-grace';
296         /** @var Page $page */
297         $page = Page::query()->first();
298
299         $this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr, $page) {
300             $viewDir = theme_path('layouts/parts');
301             mkdir($viewDir, 0777, true);
302             file_put_contents($viewDir . '/export-body-start.blade.php', $bodyStartStr);
303             file_put_contents($viewDir . '/export-body-end.blade.php', $bodyEndStr);
304
305             $resp = $this->asEditor()->get($page->getUrl('/export/html'));
306             $resp->assertSee($bodyStartStr);
307             $resp->assertSee($bodyEndStr);
308         });
309     }
310
311     protected function usingThemeFolder(callable $callback)
312     {
313         // Create a folder and configure a theme
314         $themeFolderName = 'testing_theme_' . rtrim(base64_encode(time()), '=');
315         config()->set('view.theme', $themeFolderName);
316         $themeFolderPath = theme_path('');
317         File::makeDirectory($themeFolderPath);
318
319         // Run provided callback with theme env option set
320         $this->runWithEnv('APP_THEME', $themeFolderName, function () use ($callback, $themeFolderName) {
321             call_user_func($callback, $themeFolderName);
322         });
323
324         // Cleanup the custom theme folder we created
325         File::deleteDirectory($themeFolderPath);
326     }
327 }
328
329 class MyCustomCommand extends Command
330 {
331     protected $signature = 'bookstack:test-custom-command';
332
333     public function handle()
334     {
335         $this->line('Command ran!');
336     }
337 }