]> BookStack Code Mirror - website/blob - app/Http/Controllers/DocsController.php
930caeb318a280834c8f9285bc527938122c6bd0
[website] / app / Http / Controllers / DocsController.php
1 <?php namespace App\Http\Controllers;
2
3 use \Parsedown;
4
5 class DocsController extends Controller
6 {
7
8         /**
9          * Show the index page for all documents.
10          * @return View
11          */
12     public function index()
13     {
14         return view('docs/index');
15     }
16
17     /**
18      * Show a page of documentation
19      * @param  string $type Documentation Category
20      * @param  string $page Documentation Page Name
21      * @return [type]
22      */
23     public function showPage($type, $page)
24     {
25         $type = strtolower($type);
26         if ($type !== 'admin' && $type !== 'user') abort(404);
27
28         $cacheKey = $type . '-' . $page;
29         if ($this->cache->has($cacheKey) && !app()->environment('local')) {
30                 $html = $this->cache->get($cacheKey);
31         } else {
32                 $html = $this->getDocumentFromMarkdown($type, $page);
33                 $this->cache->forever($cacheKey, $html);
34         }
35
36         if ($this->cache->has($cacheKey . '_title') && !app()->environment('local')) {
37                 $title = $this->cache->get($cacheKey . '_title');
38         } else {
39                 $title = $this->getTitleFromHtml($html);
40                 $this->cache->forever($cacheKey . '_title', $title);
41         }
42
43         return view('docs/' . $type, [
44                 'html' => $html,
45                 'title' => $title,
46                         'type' => $type,
47                         'page' => $page
48         ]);
49     }
50
51     /**
52      * Get a page title from the HTML content.
53      * @param  string $html Page HTML content
54      * @return string
55      */
56     protected function getTitleFromHtml($html)
57     {
58         $titleRegex = '/<h1>(.*?)<\/h1>/';
59         $matches = [];
60         preg_match_all($titleRegex, $html, $matches);
61
62         if (isset($matches[1]) && isset($matches[1][0])) {
63                 return $matches[1][0];
64         }
65
66         return false;
67     }
68
69     /**
70      * Get document HTML from markdown content.
71      * @param  string $type Documentation Category
72      * @param  string $page Documentation Page Name
73      * @return string       Page HTML
74      */
75     protected function getDocumentFromMarkdown($type, $page)
76     {
77         $filePath = app()->basePath('resources/docs/' . strtolower($type) . '/' . strtolower($page) . '.md');
78
79         if (!file_exists($filePath) || !is_readable($filePath)) {
80                 abort(404);
81         }
82
83         $markdown = file_get_contents($filePath);
84         $parseDown = new Parsedown();
85         $html = $parseDown->text($markdown);
86         return $html;
87     }
88
89 }