]> BookStack Code Mirror - bookstack/blob - tests/Entity/PageContentTest.php
Merge branch 'v23-10' into development
[bookstack] / tests / Entity / PageContentTest.php
1 <?php
2
3 namespace Tests\Entity;
4
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Tools\PageContent;
7 use Tests\TestCase;
8
9 class PageContentTest extends TestCase
10 {
11     protected string $base64Jpeg = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k=';
12
13     public function test_page_includes()
14     {
15         $page = $this->entities->page();
16         $secondPage = $this->entities->page();
17
18         $secondPage->html = "<p id='section1'>Hello, This is a test</p><p id='section2'>This is a second block of content</p>";
19         $secondPage->save();
20
21         $this->asEditor();
22
23         $pageContent = $this->get($page->getUrl());
24         $pageContent->assertDontSee('Hello, This is a test');
25
26         $originalHtml = $page->html;
27         $page->html .= "{{@{$secondPage->id}}}";
28         $page->save();
29
30         $pageContent = $this->get($page->getUrl());
31         $pageContent->assertSee('Hello, This is a test');
32         $pageContent->assertSee('This is a second block of content');
33
34         $page->html = $originalHtml . " Well {{@{$secondPage->id}#section2}}";
35         $page->save();
36
37         $pageContent = $this->get($page->getUrl());
38         $pageContent->assertDontSee('Hello, This is a test');
39         $pageContent->assertSee('Well This is a second block of content');
40     }
41
42     public function test_saving_page_with_includes()
43     {
44         $page = $this->entities->page();
45         $secondPage = $this->entities->page();
46
47         $this->asEditor();
48         $includeTag = '{{@' . $secondPage->id . '}}';
49         $page->html = '<p>' . $includeTag . '</p>';
50
51         $resp = $this->put($page->getUrl(), ['name' => $page->name, 'html' => $page->html, 'summary' => '']);
52
53         $resp->assertStatus(302);
54
55         $page = Page::find($page->id);
56         $this->assertStringContainsString($includeTag, $page->html);
57         $this->assertEquals('', $page->text);
58     }
59
60     public function test_page_includes_rendered_on_book_export()
61     {
62         $page = $this->entities->page();
63         $secondPage = Page::query()
64             ->where('book_id', '!=', $page->book_id)
65             ->first();
66
67         $content = '<p id="bkmrk-meow">my cat is awesome and scratchy</p>';
68         $secondPage->html = $content;
69         $secondPage->save();
70
71         $page->html = "{{@{$secondPage->id}#bkmrk-meow}}";
72         $page->save();
73
74         $this->asEditor();
75         $htmlContent = $this->get($page->book->getUrl('/export/html'));
76         $htmlContent->assertSee('my cat is awesome and scratchy');
77     }
78
79     public function test_page_includes_can_be_nested_up_to_three_times()
80     {
81         $page = $this->entities->page();
82         $tag = "{{@{$page->id}#bkmrk-test}}";
83         $page->html = '<p id="bkmrk-test">Hello Barry ' . $tag . '</p>';
84         $page->save();
85
86         $pageResp = $this->asEditor()->get($page->getUrl());
87         $this->withHtml($pageResp)->assertElementContains('#bkmrk-test', 'Hello Barry Hello Barry Hello Barry Hello Barry ' . $tag);
88         $this->withHtml($pageResp)->assertElementNotContains('#bkmrk-test', 'Hello Barry Hello Barry Hello Barry Hello Barry Hello Barry ' . $tag);
89     }
90
91     public function test_page_includes_to_nonexisting_pages_does_not_error()
92     {
93         $page = $this->entities->page();
94         $missingId = Page::query()->max('id') + 1;
95         $tag = "{{@{$missingId}}}";
96         $page->html = '<p id="bkmrk-test">Hello Barry ' . $tag . '</p>';
97         $page->save();
98
99         $pageResp = $this->asEditor()->get($page->getUrl());
100         $pageResp->assertOk();
101         $pageResp->assertSee('Hello Barry');
102     }
103
104     public function test_page_content_scripts_removed_by_default()
105     {
106         $this->asEditor();
107         $page = $this->entities->page();
108         $script = 'abc123<script>console.log("hello-test")</script>abc123';
109         $page->html = "escape {$script}";
110         $page->save();
111
112         $pageView = $this->get($page->getUrl());
113         $pageView->assertStatus(200);
114         $pageView->assertDontSee($script, false);
115         $pageView->assertSee('abc123abc123');
116     }
117
118     public function test_more_complex_content_script_escaping_scenarios()
119     {
120         $checks = [
121             "<p>Some script</p><script>alert('cat')</script>",
122             "<div><div><div><div><p>Some script</p><script>alert('cat')</script></div></div></div></div>",
123             "<p>Some script<script>alert('cat')</script></p>",
124             "<p>Some script <div><script>alert('cat')</script></div></p>",
125             "<p>Some script <script><div>alert('cat')</script></div></p>",
126             "<p>Some script <script><div>alert('cat')</script><script><div>alert('cat')</script></p><script><div>alert('cat')</script>",
127         ];
128
129         $this->asEditor();
130         $page = $this->entities->page();
131
132         foreach ($checks as $check) {
133             $page->html = $check;
134             $page->save();
135
136             $pageView = $this->get($page->getUrl());
137             $pageView->assertStatus(200);
138             $this->withHtml($pageView)->assertElementNotContains('.page-content', '<script>');
139             $this->withHtml($pageView)->assertElementNotContains('.page-content', '</script>');
140         }
141     }
142
143     public function test_js_and_base64_src_urls_are_removed()
144     {
145         $checks = [
146             '<iframe src="javascript:alert(document.cookie)"></iframe>',
147             '<iframe src="JavAScRipT:alert(document.cookie)"></iframe>',
148             '<iframe src="JavAScRipT:alert(document.cookie)"></iframe>',
149             '<iframe SRC=" javascript: alert(document.cookie)"></iframe>',
150             '<iframe src="data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg==" frameborder="0"></iframe>',
151             '<iframe src="DaTa:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg==" frameborder="0"></iframe>',
152             '<iframe src=" data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg==" frameborder="0"></iframe>',
153             '<img src="javascript:alert(document.cookie)"/>',
154             '<img src="JavAScRipT:alert(document.cookie)"/>',
155             '<img src="JavAScRipT:alert(document.cookie)"/>',
156             '<img SRC=" javascript: alert(document.cookie)"/>',
157             '<img src="data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg=="/>',
158             '<img src="DaTa:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg=="/>',
159             '<img src=" data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg=="/>',
160             '<iframe srcdoc="<script>window.alert(document.cookie)</script>"></iframe>',
161             '<iframe SRCdoc="<script>window.alert(document.cookie)</script>"></iframe>',
162             '<IMG SRC=`javascript:alert("RSnake says, \'XSS\'")`>',
163         ];
164
165         $this->asEditor();
166         $page = $this->entities->page();
167
168         foreach ($checks as $check) {
169             $page->html = $check;
170             $page->save();
171
172             $pageView = $this->get($page->getUrl());
173             $pageView->assertStatus(200);
174             $html = $this->withHtml($pageView);
175             $html->assertElementNotContains('.page-content', '<iframe>');
176             $html->assertElementNotContains('.page-content', '<img');
177             $html->assertElementNotContains('.page-content', '</iframe>');
178             $html->assertElementNotContains('.page-content', 'src=');
179             $html->assertElementNotContains('.page-content', 'javascript:');
180             $html->assertElementNotContains('.page-content', 'data:');
181             $html->assertElementNotContains('.page-content', 'base64');
182         }
183     }
184
185     public function test_javascript_uri_links_are_removed()
186     {
187         $checks = [
188             '<a id="xss" href="javascript:alert(document.cookie)>Click me</a>',
189             '<a id="xss" href="javascript: alert(document.cookie)>Click me</a>',
190             '<a id="xss" href="JaVaScRiPt: alert(document.cookie)>Click me</a>',
191             '<a id="xss" href=" JaVaScRiPt: alert(document.cookie)>Click me</a>',
192         ];
193
194         $this->asEditor();
195         $page = $this->entities->page();
196
197         foreach ($checks as $check) {
198             $page->html = $check;
199             $page->save();
200
201             $pageView = $this->get($page->getUrl());
202             $pageView->assertStatus(200);
203             $this->withHtml($pageView)->assertElementNotContains('.page-content', '<a id="xss"');
204             $this->withHtml($pageView)->assertElementNotContains('.page-content', 'href=javascript:');
205         }
206     }
207
208     public function test_form_actions_with_javascript_are_removed()
209     {
210         $checks = [
211             '<form><input id="xss" type=submit formaction=javascript:alert(document.domain) value=Submit><input></form>',
212             '<form ><button id="xss" formaction="JaVaScRiPt:alert(document.domain)">Click me</button></form>',
213             '<form ><button id="xss" formaction=javascript:alert(document.domain)>Click me</button></form>',
214             '<form id="xss" action=javascript:alert(document.domain)><input type=submit value=Submit></form>',
215             '<form id="xss" action="JaVaScRiPt:alert(document.domain)"><input type=submit value=Submit></form>',
216         ];
217
218         $this->asEditor();
219         $page = $this->entities->page();
220
221         foreach ($checks as $check) {
222             $page->html = $check;
223             $page->save();
224
225             $pageView = $this->get($page->getUrl());
226             $pageView->assertStatus(200);
227             $this->withHtml($pageView)->assertElementNotContains('.page-content', '<button id="xss"');
228             $this->withHtml($pageView)->assertElementNotContains('.page-content', '<input id="xss"');
229             $this->withHtml($pageView)->assertElementNotContains('.page-content', '<form id="xss"');
230             $this->withHtml($pageView)->assertElementNotContains('.page-content', 'action=javascript:');
231             $this->withHtml($pageView)->assertElementNotContains('.page-content', 'formaction=javascript:');
232         }
233     }
234
235     public function test_metadata_redirects_are_removed()
236     {
237         $checks = [
238             '<meta http-equiv="refresh" content="0; url=//external_url">',
239             '<meta http-equiv="refresh" ConTeNt="0; url=//external_url">',
240             '<meta http-equiv="refresh" content="0; UrL=//external_url">',
241         ];
242
243         $this->asEditor();
244         $page = $this->entities->page();
245
246         foreach ($checks as $check) {
247             $page->html = $check;
248             $page->save();
249
250             $pageView = $this->get($page->getUrl());
251             $pageView->assertStatus(200);
252             $this->withHtml($pageView)->assertElementNotContains('.page-content', '<meta>');
253             $this->withHtml($pageView)->assertElementNotContains('.page-content', '</meta>');
254             $this->withHtml($pageView)->assertElementNotContains('.page-content', 'content=');
255             $this->withHtml($pageView)->assertElementNotContains('.page-content', 'external_url');
256         }
257     }
258
259     public function test_page_inline_on_attributes_removed_by_default()
260     {
261         $this->asEditor();
262         $page = $this->entities->page();
263         $script = '<p onmouseenter="console.log(\'test\')">Hello</p>';
264         $page->html = "escape {$script}";
265         $page->save();
266
267         $pageView = $this->get($page->getUrl());
268         $pageView->assertStatus(200);
269         $pageView->assertDontSee($script, false);
270         $pageView->assertSee('<p>Hello</p>', false);
271     }
272
273     public function test_more_complex_inline_on_attributes_escaping_scenarios()
274     {
275         $checks = [
276             '<p onclick="console.log(\'test\')">Hello</p>',
277             '<p OnCliCk="console.log(\'test\')">Hello</p>',
278             '<div>Lorem ipsum dolor sit amet.</div><p onclick="console.log(\'test\')">Hello</p>',
279             '<div>Lorem ipsum dolor sit amet.<p onclick="console.log(\'test\')">Hello</p></div>',
280             '<div><div><div><div>Lorem ipsum dolor sit amet.<p onclick="console.log(\'test\')">Hello</p></div></div></div></div>',
281             '<div onclick="console.log(\'test\')">Lorem ipsum dolor sit amet.</div><p onclick="console.log(\'test\')">Hello</p><div></div>',
282             '<a a="<img src=1 onerror=\'alert(1)\'> ',
283             '\<a onclick="alert(document.cookie)"\>xss link\</a\>',
284         ];
285
286         $this->asEditor();
287         $page = $this->entities->page();
288
289         foreach ($checks as $check) {
290             $page->html = $check;
291             $page->save();
292
293             $pageView = $this->get($page->getUrl());
294             $pageView->assertStatus(200);
295             $this->withHtml($pageView)->assertElementNotContains('.page-content', 'onclick');
296         }
297     }
298
299     public function test_page_content_scripts_show_when_configured()
300     {
301         $this->asEditor();
302         $page = $this->entities->page();
303         config()->set('app.allow_content_scripts', 'true');
304
305         $script = 'abc123<script>console.log("hello-test")</script>abc123';
306         $page->html = "no escape {$script}";
307         $page->save();
308
309         $pageView = $this->get($page->getUrl());
310         $pageView->assertSee($script, false);
311         $pageView->assertDontSee('abc123abc123');
312     }
313
314     public function test_svg_script_usage_is_removed()
315     {
316         $checks = [
317             '<svg id="test" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100"><a xlink:href="javascript:alert(document.domain)"><rect x="0" y="0" width="100" height="100" /></a></svg>',
318             '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="data:application/xml;base64 ,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KPGRlZnM+CjxjaXJjbGUgaWQ9InRlc3QiIHI9IjAiIGN4PSIwIiBjeT0iMCIgc3R5bGU9ImZpbGw6ICNGMDAiPgo8c2V0IGF0dHJpYnV0ZU5hbWU9ImZpbGwiIGF0dHJpYnV0ZVR5cGU9IkNTUyIgb25iZWdpbj0nYWxlcnQoZG9jdW1lbnQuZG9tYWluKScKb25lbmQ9J2FsZXJ0KCJvbmVuZCIpJyB0bz0iIzAwRiIgYmVnaW49IjBzIiBkdXI9Ijk5OXMiIC8+CjwvY2lyY2xlPgo8L2RlZnM+Cjx1c2UgeGxpbms6aHJlZj0iI3Rlc3QiLz4KPC9zdmc+#test"/></svg>',
319             '<svg><animate href=#xss attributeName=href values=javascript:alert(1) /></svg>',
320             '<svg><animate href="#xss" attributeName="href" values="a;javascript:alert(1)" /></svg>',
321             '<svg><animate href="#xss" attributeName="href" values="a;data:alert(1)" /></svg>',
322             '<svg><animate href=#xss attributeName=href from=javascript:alert(1) to=1 /><a id=xss><text x=20 y=20>XSS</text></a>',
323             '<svg><set href=#xss attributeName=href from=? to=javascript:alert(1) /><a id=xss><text x=20 y=20>XSS</text></a>',
324             '<svg><g><g><g><animate href=#xss attributeName=href values=javascript:alert(1) /></g></g></g></svg>',
325         ];
326
327         $this->asEditor();
328         $page = $this->entities->page();
329
330         foreach ($checks as $check) {
331             $page->html = $check;
332             $page->save();
333
334             $pageView = $this->get($page->getUrl());
335             $pageView->assertStatus(200);
336             $html = $this->withHtml($pageView);
337             $html->assertElementNotContains('.page-content', 'alert');
338             $html->assertElementNotContains('.page-content', 'xlink:href');
339             $html->assertElementNotContains('.page-content', 'application/xml');
340             $html->assertElementNotContains('.page-content', 'javascript');
341         }
342     }
343
344     public function test_page_inline_on_attributes_show_if_configured()
345     {
346         $this->asEditor();
347         $page = $this->entities->page();
348         config()->set('app.allow_content_scripts', 'true');
349
350         $script = '<p onmouseenter="console.log(\'test\')">Hello</p>';
351         $page->html = "escape {$script}";
352         $page->save();
353
354         $pageView = $this->get($page->getUrl());
355         $pageView->assertSee($script, false);
356         $pageView->assertDontSee('<p>Hello</p>', false);
357     }
358
359     public function test_duplicate_ids_does_not_break_page_render()
360     {
361         $this->asEditor();
362         $pageA = Page::query()->first();
363         $pageB = Page::query()->where('id', '!=', $pageA->id)->first();
364
365         $content = '<ul id="bkmrk-xxx-%28"></ul> <ul id="bkmrk-xxx-%28"></ul>';
366         $pageA->html = $content;
367         $pageA->save();
368
369         $pageB->html = '<ul id="bkmrk-xxx-%28"></ul> <p>{{@' . $pageA->id . '#test}}</p>';
370         $pageB->save();
371
372         $pageView = $this->get($pageB->getUrl());
373         $pageView->assertSuccessful();
374     }
375
376     public function test_duplicate_ids_fixed_on_page_save()
377     {
378         $this->asEditor();
379         $page = $this->entities->page();
380
381         $content = '<ul id="bkmrk-test"><li>test a</li><li><ul id="bkmrk-test"><li>test b</li></ul></li></ul>';
382         $pageSave = $this->put($page->getUrl(), [
383             'name'    => $page->name,
384             'html'    => $content,
385             'summary' => '',
386         ]);
387         $pageSave->assertRedirect();
388
389         $updatedPage = Page::query()->where('id', '=', $page->id)->first();
390         $this->assertEquals(substr_count($updatedPage->html, 'bkmrk-test"'), 1);
391     }
392
393     public function test_anchors_referencing_non_bkmrk_ids_rewritten_after_save()
394     {
395         $this->asEditor();
396         $page = $this->entities->page();
397
398         $content = '<h1 id="non-standard-id">test</h1><p><a href="#non-standard-id">link</a></p>';
399         $this->put($page->getUrl(), [
400             'name'    => $page->name,
401             'html'    => $content,
402             'summary' => '',
403         ]);
404
405         $updatedPage = Page::query()->where('id', '=', $page->id)->first();
406         $this->assertStringContainsString('id="bkmrk-test"', $updatedPage->html);
407         $this->assertStringContainsString('href="#bkmrk-test"', $updatedPage->html);
408     }
409
410     public function test_get_page_nav_sets_correct_properties()
411     {
412         $content = '<h1 id="testa">Hello</h1><h2 id="testb">There</h2><h3 id="testc">Donkey</h3>';
413         $pageContent = new PageContent(new Page(['html' => $content]));
414         $navMap = $pageContent->getNavigation($content);
415
416         $this->assertCount(3, $navMap);
417         $this->assertArrayMapIncludes([
418             'nodeName' => 'h1',
419             'link'     => '#testa',
420             'text'     => 'Hello',
421             'level'    => 1,
422         ], $navMap[0]);
423         $this->assertArrayMapIncludes([
424             'nodeName' => 'h2',
425             'link'     => '#testb',
426             'text'     => 'There',
427             'level'    => 2,
428         ], $navMap[1]);
429         $this->assertArrayMapIncludes([
430             'nodeName' => 'h3',
431             'link'     => '#testc',
432             'text'     => 'Donkey',
433             'level'    => 3,
434         ], $navMap[2]);
435     }
436
437     public function test_get_page_nav_does_not_show_empty_titles()
438     {
439         $content = '<h1 id="testa">Hello</h1><h2 id="testb">&nbsp;</h2><h3 id="testc"></h3>';
440         $pageContent = new PageContent(new Page(['html' => $content]));
441         $navMap = $pageContent->getNavigation($content);
442
443         $this->assertCount(1, $navMap);
444         $this->assertArrayMapIncludes([
445             'nodeName' => 'h1',
446             'link'     => '#testa',
447             'text'     => 'Hello',
448         ], $navMap[0]);
449     }
450
451     public function test_get_page_nav_shifts_headers_if_only_smaller_ones_are_used()
452     {
453         $content = '<h4 id="testa">Hello</h4><h5 id="testb">There</h5><h6 id="testc">Donkey</h6>';
454         $pageContent = new PageContent(new Page(['html' => $content]));
455         $navMap = $pageContent->getNavigation($content);
456
457         $this->assertCount(3, $navMap);
458         $this->assertArrayMapIncludes([
459             'nodeName' => 'h4',
460             'level'    => 1,
461         ], $navMap[0]);
462         $this->assertArrayMapIncludes([
463             'nodeName' => 'h5',
464             'level'    => 2,
465         ], $navMap[1]);
466         $this->assertArrayMapIncludes([
467             'nodeName' => 'h6',
468             'level'    => 3,
469         ], $navMap[2]);
470     }
471
472     public function test_page_text_decodes_html_entities()
473     {
474         $page = $this->entities->page();
475
476         $this->actingAs($this->users->admin())
477             ->put($page->getUrl(''), [
478                 'name' => 'Testing',
479                 'html' => '<p>&quot;Hello &amp; welcome&quot;</p>',
480             ]);
481
482         $page->refresh();
483         $this->assertEquals('"Hello & welcome"', $page->text);
484     }
485
486     public function test_page_markdown_table_rendering()
487     {
488         $this->asEditor();
489         $page = $this->entities->page();
490
491         $content = '| Syntax      | Description |
492 | ----------- | ----------- |
493 | Header      | Title       |
494 | Paragraph   | Text        |';
495         $this->put($page->getUrl(), [
496             'name' => $page->name,  'markdown' => $content,
497             'html' => '', 'summary' => '',
498         ]);
499
500         $page->refresh();
501         $this->assertStringContainsString('</tbody>', $page->html);
502
503         $pageView = $this->get($page->getUrl());
504         $this->withHtml($pageView)->assertElementExists('.page-content table tbody td');
505     }
506
507     public function test_page_markdown_task_list_rendering()
508     {
509         $this->asEditor();
510         $page = $this->entities->page();
511
512         $content = '- [ ] Item a
513 - [x] Item b';
514         $this->put($page->getUrl(), [
515             'name' => $page->name,  'markdown' => $content,
516             'html' => '', 'summary' => '',
517         ]);
518
519         $page->refresh();
520         $this->assertStringContainsString('input', $page->html);
521         $this->assertStringContainsString('type="checkbox"', $page->html);
522
523         $pageView = $this->get($page->getUrl());
524         $this->withHtml($pageView)->assertElementExists('.page-content li.task-list-item input[type=checkbox]');
525         $this->withHtml($pageView)->assertElementExists('.page-content li.task-list-item input[type=checkbox][checked]');
526     }
527
528     public function test_page_markdown_strikethrough_rendering()
529     {
530         $this->asEditor();
531         $page = $this->entities->page();
532
533         $content = '~~some crossed out text~~';
534         $this->put($page->getUrl(), [
535             'name' => $page->name,  'markdown' => $content,
536             'html' => '', 'summary' => '',
537         ]);
538
539         $page->refresh();
540         $this->assertStringMatchesFormat('%A<s%A>some crossed out text</s>%A', $page->html);
541
542         $pageView = $this->get($page->getUrl());
543         $this->withHtml($pageView)->assertElementExists('.page-content p > s');
544     }
545
546     public function test_page_markdown_single_html_comment_saving()
547     {
548         $this->asEditor();
549         $page = $this->entities->page();
550
551         $content = '<!-- Test Comment -->';
552         $this->put($page->getUrl(), [
553             'name' => $page->name,  'markdown' => $content,
554             'html' => '', 'summary' => '',
555         ]);
556
557         $page->refresh();
558         $this->assertStringMatchesFormat($content, $page->html);
559
560         $pageView = $this->get($page->getUrl());
561         $pageView->assertStatus(200);
562         $pageView->assertSee($content, false);
563     }
564
565     public function test_base64_images_get_extracted_from_page_content()
566     {
567         $this->asEditor();
568         $page = $this->entities->page();
569
570         $this->put($page->getUrl(), [
571             'name' => $page->name, 'summary' => '',
572             'html' => '<p>test<img src="data:image/jpeg;base64,' . $this->base64Jpeg . '"/></p>',
573         ]);
574
575         $page->refresh();
576         $this->assertStringMatchesFormat('%A<p%A>test<img src="http://localhost/uploads/images/gallery/%A.jpeg">%A</p>%A', $page->html);
577
578         $matches = [];
579         preg_match('/src="https:\/\/p.rizon.top:443\/http\/localhost(.*?)"/', $page->html, $matches);
580         $imagePath = $matches[1];
581         $imageFile = public_path($imagePath);
582         $this->assertEquals(base64_decode($this->base64Jpeg), file_get_contents($imageFile));
583
584         $this->files->deleteAtRelativePath($imagePath);
585     }
586
587     public function test_base64_images_get_extracted_when_containing_whitespace()
588     {
589         $this->asEditor();
590         $page = $this->entities->page();
591
592         $base64PngWithWhitespace = "iVBORw0KGg\noAAAANSUhE\tUgAAAAEAAAA BCA   YAAAAfFcSJAAA\n\t ACklEQVR4nGMAAQAABQAB";
593         $base64PngWithoutWhitespace = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQAB';
594         $this->put($page->getUrl(), [
595             'name' => $page->name, 'summary' => '',
596             'html' => '<p>test<img src="data:image/png;base64,' . $base64PngWithWhitespace . '"/></p>',
597         ]);
598
599         $page->refresh();
600         $this->assertStringMatchesFormat('%A<p%A>test<img src="http://localhost/uploads/images/gallery/%A.png">%A</p>%A', $page->html);
601
602         $matches = [];
603         preg_match('/src="https:\/\/p.rizon.top:443\/http\/localhost(.*?)"/', $page->html, $matches);
604         $imagePath = $matches[1];
605         $imageFile = public_path($imagePath);
606         $this->assertEquals(base64_decode($base64PngWithoutWhitespace), file_get_contents($imageFile));
607
608         $this->files->deleteAtRelativePath($imagePath);
609     }
610
611     public function test_base64_images_within_html_blanked_if_not_supported_extension_for_extract()
612     {
613         // Relevant to https://github.com/BookStackApp/BookStack/issues/3010 and other cases
614         $extensions = [
615             'jiff', 'pngr', 'png ', ' png', '.png', 'png.', 'p.ng', ',png',
616             'data:image/png', ',data:image/png',
617         ];
618
619         foreach ($extensions as $extension) {
620             $this->asEditor();
621             $page = $this->entities->page();
622
623             $this->put($page->getUrl(), [
624                 'name' => $page->name, 'summary' => '',
625                 'html' => '<p>test<img src="data:image/' . $extension . ';base64,' . $this->base64Jpeg . '"/></p>',
626             ]);
627
628             $page->refresh();
629             $this->assertStringContainsString('<img src=""', $page->html);
630         }
631     }
632
633     public function test_base64_images_within_html_blanked_if_no_image_create_permission()
634     {
635         $editor = $this->users->editor();
636         $page = $this->entities->page();
637         $this->permissions->removeUserRolePermissions($editor, ['image-create-all']);
638
639         $this->actingAs($editor)->put($page->getUrl(), [
640             'name' => $page->name,
641             'html' => '<p>test<img src="data:image/jpeg;base64,' . $this->base64Jpeg . '"/></p>',
642         ]);
643
644         $page->refresh();
645         $this->assertStringMatchesFormat('%A<p%A>test<img src="">%A</p>%A', $page->html);
646     }
647
648     public function test_base64_images_within_html_blanked_if_content_does_not_appear_like_an_image()
649     {
650         $page = $this->entities->page();
651
652         $imgContent = base64_encode('file://test/a/b/c');
653         $this->asEditor()->put($page->getUrl(), [
654             'name' => $page->name,
655             'html' => '<p>test<img src="data:image/jpeg;base64,' . $imgContent . '"/></p>',
656         ]);
657
658         $page->refresh();
659         $this->assertStringMatchesFormat('%A<p%A>test<img src="">%A</p>%A', $page->html);
660     }
661
662     public function test_base64_images_get_extracted_from_markdown_page_content()
663     {
664         $this->asEditor();
665         $page = $this->entities->page();
666
667         $this->put($page->getUrl(), [
668             'name'     => $page->name, 'summary' => '',
669             'markdown' => 'test ![test](data:image/jpeg;base64,' . $this->base64Jpeg . ')',
670         ]);
671
672         $page->refresh();
673         $this->assertStringMatchesFormat('%A<p%A>test <img src="http://localhost/uploads/images/gallery/%A.jpeg" alt="test">%A</p>%A', $page->html);
674
675         $matches = [];
676         preg_match('/src="https:\/\/p.rizon.top:443\/http\/localhost(.*?)"/', $page->html, $matches);
677         $imagePath = $matches[1];
678         $imageFile = public_path($imagePath);
679         $this->assertEquals(base64_decode($this->base64Jpeg), file_get_contents($imageFile));
680
681         $this->files->deleteAtRelativePath($imagePath);
682     }
683
684     public function test_markdown_base64_extract_not_limited_by_pcre_limits()
685     {
686         $pcreBacktrackLimit = ini_get('pcre.backtrack_limit');
687         $pcreRecursionLimit = ini_get('pcre.recursion_limit');
688
689         $this->asEditor();
690         $page = $this->entities->page();
691
692         ini_set('pcre.backtrack_limit', '500');
693         ini_set('pcre.recursion_limit', '500');
694
695         $content = str_repeat(base64_decode($this->base64Jpeg), 50);
696         $base64Content = base64_encode($content);
697
698         $this->put($page->getUrl(), [
699             'name'     => $page->name, 'summary' => '',
700             'markdown' => 'test ![test](data:image/jpeg;base64,' . $base64Content . ') ![test](data:image/jpeg;base64,' . $base64Content . ')',
701         ]);
702
703         $page->refresh();
704         $this->assertStringMatchesFormat('<p%A>test <img src="http://localhost/uploads/images/gallery/%A.jpeg" alt="test"> <img src="http://localhost/uploads/images/gallery/%A.jpeg" alt="test">%A</p>%A', $page->html);
705
706         $matches = [];
707         preg_match('/src="https:\/\/p.rizon.top:443\/http\/localhost(.*?)"/', $page->html, $matches);
708         $imagePath = $matches[1];
709         $imageFile = public_path($imagePath);
710         $this->assertEquals($content, file_get_contents($imageFile));
711
712         $this->files->deleteAtRelativePath($imagePath);
713         ini_set('pcre.backtrack_limit', $pcreBacktrackLimit);
714         ini_set('pcre.recursion_limit', $pcreRecursionLimit);
715     }
716
717     public function test_base64_images_within_markdown_blanked_if_not_supported_extension_for_extract()
718     {
719         $page = $this->entities->page();
720
721         $this->asEditor()->put($page->getUrl(), [
722             'name'     => $page->name, 'summary' => '',
723             'markdown' => 'test ![test](data:image/jiff;base64,' . $this->base64Jpeg . ')',
724         ]);
725
726         $this->assertStringContainsString('<img src=""', $page->refresh()->html);
727     }
728
729     public function test_base64_images_within_markdown_blanked_if_no_image_create_permission()
730     {
731         $editor = $this->users->editor();
732         $page = $this->entities->page();
733         $this->permissions->removeUserRolePermissions($editor, ['image-create-all']);
734
735         $this->actingAs($editor)->put($page->getUrl(), [
736             'name' => $page->name,
737             'markdown' => 'test ![test](data:image/jpeg;base64,' . $this->base64Jpeg . ')',
738         ]);
739
740         $this->assertStringContainsString('<img src=""', $page->refresh()->html);
741     }
742
743     public function test_base64_images_within_markdown_blanked_if_content_does_not_appear_like_an_image()
744     {
745         $page = $this->entities->page();
746
747         $imgContent = base64_encode('file://test/a/b/c');
748         $this->asEditor()->put($page->getUrl(), [
749             'name' => $page->name,
750             'markdown' => 'test ![test](data:image/jpeg;base64,' . $imgContent . ')',
751         ]);
752
753         $page->refresh();
754         $this->assertStringContainsString('<img src=""', $page->refresh()->html);
755     }
756
757     public function test_nested_headers_gets_assigned_an_id()
758     {
759         $page = $this->entities->page();
760
761         $content = '<table><tbody><tr><td><h5>Simple Test</h5></td></tr></tbody></table>';
762         $this->asEditor()->put($page->getUrl(), [
763             'name'    => $page->name,
764             'html'    => $content,
765         ]);
766
767         // The top level <table> node will get assign the bkmrk-simple-test id because the system will
768         // take the node value of h5
769         // So the h5 should get the bkmrk-simple-test-1 id
770         $this->assertStringContainsString('<h5 id="bkmrk-simple-test-1">Simple Test</h5>', $page->refresh()->html);
771     }
772
773     public function test_non_breaking_spaces_are_preserved()
774     {
775         $page = $this->entities->page();
776
777         $content = '<p>&nbsp;</p>';
778         $this->asEditor()->put($page->getUrl(), [
779             'name'    => $page->name,
780             'html'    => $content,
781         ]);
782
783         $this->assertStringContainsString('<p id="bkmrk-%C2%A0">&nbsp;</p>', $page->refresh()->html);
784     }
785
786     public function test_page_save_with_many_headers_and_links_is_reasonable()
787     {
788         $page = $this->entities->page();
789
790         $content = '';
791         for ($i = 0; $i < 500; $i++) {
792             $content .= "<table><tbody><tr><td><h5 id='header-{$i}'>Simple Test</h5><a href='#header-{$i}'></a></td></tr></tbody></table>";
793         }
794
795         $time = time();
796         $this->asEditor()->put($page->getUrl(), [
797             'name'    => $page->name,
798             'html'    => $content,
799         ])->assertRedirect();
800
801         $timeElapsed = time() - $time;
802         $this->assertLessThan(3, $timeElapsed);
803     }
804 }