-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhyde.module
91 lines (79 loc) · 2.33 KB
/
hyde.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
/**
* Implements hook_menu().
*/
function hyde_menu() {
_hyde_init();
$hyde_path = _hyde_path();
$files = file_scan_directory($hyde_path, '/\.md$/');
$items = array();
foreach ($files as $file) {
$rel_path = substr($file->uri, 1 + strlen($hyde_path));
$name = preg_replace(';\.md$;', '', $rel_path);
$items[$name] = array(
'page callback' => '_hyde_render',
'page arguments' => [$rel_path],
'access callback' => TRUE,
);
}
return $items;
}
/**
* @param string $rel_path
* The relative path to the Markdown document.
* @return string
* Rendered HTML document.
* @throws \Exception
*/
function _hyde_render($rel_path) {
_hyde_init();
if (strpos($rel_path, '..') !== FALSE) {
throw new Exception("I don't like your filename. Yes, this is too persnickity.");
}
$md_file = _hyde_path() . DIRECTORY_SEPARATOR . $rel_path;
if (!file_exists($md_file)) {
drupal_not_found();
}
$markdown = file_get_contents($md_file);
list($headers, $markdown) = _hyde_parse_headers($markdown);
if (isset($headers['title'])) {
drupal_set_title($headers['title']);
}
$parser = new Parsedown();
return
$parser->text($markdown);
}
/**
* Split apart the YAML headers and the main content of the Markdown document.
*
* @param string $markdown
* Ex: "---\ntitle: \"War and Peace\"\n---\nHello world"
* @return array
* Array(0 => $headers, 1 => $markdownText).
* Ex: [['title' => 'War and Peace'], 'Hello world']
*/
function _hyde_parse_headers($markdown) {
$headers = array();
if (preg_match(';^---\n(.*)\n---\n;m', $markdown, $matches)) {
$headers = Symfony\Component\Yaml\Yaml::parse($matches[1]);
$markdown = preg_replace(';^---\n(.*)\n---\n;m', '', $markdown, 1);
}
return array($headers, $markdown);
}
/**
* Ensure that all classes/resources are available.
*/
function _hyde_init() {
if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'vendor')) {
// It seems we installed with composer inside this repo. What dirty proof-of-concept hacking is this.
require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
}
}
/**
* Get the storage path for Markdown content.
*
* @return string
*/
function _hyde_path() {
return variable_get('hyde_path', variable_get('file_private_path') . DIRECTORY_SEPARATOR . 'hyde');
}