]> BookStack Code Mirror - bookstack/blob - app/Theming/CustomHtmlHeadContentProvider.php
Finished off script CSP rules
[bookstack] / app / Theming / CustomHtmlHeadContentProvider.php
1 <?php
2
3 namespace BookStack\Theming;
4
5 use BookStack\Util\CspService;
6 use BookStack\Util\HtmlContentFilter;
7 use BookStack\Util\HtmlNonceApplicator;
8 use Illuminate\Contracts\Cache\Repository as Cache;
9
10 class CustomHtmlHeadContentProvider
11 {
12     /**
13      * @var CspService
14      */
15     protected $cspService;
16
17     /**
18      * @var Cache
19      */
20     protected $cache;
21
22     public function __construct(CspService $cspService, Cache $cache)
23     {
24         $this->cspService = $cspService;
25         $this->cache = $cache;
26     }
27
28     /**
29      * Fetch our custom HTML head content prepared for use on web pages.
30      * Content has a nonce applied for CSP.
31      */
32     public function forWeb(): string
33     {
34         $content = $this->getSourceContent();
35         $hash = md5($content);
36         $html = $this->cache->remember('custom-head-web:' . $hash, 86400, function() use ($content) {
37             return HtmlNonceApplicator::prepare($content);
38         });
39         return HtmlNonceApplicator::apply($html, $this->cspService->getNonce());
40     }
41
42     /**
43      * Fetch our custom HTML head content prepared for use in export formats.
44      * Scripts are stripped to avoid potential issues.
45      */
46     public function forExport(): string
47     {
48         $content = $this->getSourceContent();
49         $hash = md5($content);
50         return $this->cache->remember('custom-head-export:' . $hash, 86400, function() use ($content) {
51              return HtmlContentFilter::removeScripts($content);
52         });
53     }
54
55     /**
56      * Get the original custom head content to use.
57      */
58     protected function getSourceContent(): string
59     {
60         return setting('app-custom-head', '');
61     }
62
63 }