This repository has been archived by the owner on Jun 16, 2018. It is now read-only.
/
filesource.php
83 lines (79 loc) · 2.47 KB
/
filesource.php
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
<?php
/**
* Filesource
*
* Embed a file as text from the same directory
*
* Based on "PageInject"
* Original work licensed under MIT.
*/
namespace Grav\Plugin;
use Grav\Common\Grav;
use Grav\Common\Plugin;
use Grav\Common\Page\Page;
use RocketTheme\Toolbox\Event\Event;
class FilesourcePlugin extends Plugin
{
/**
* Return a list of subscribed events.
*
* @return array The list of events of the plugin of the form
* 'name' => ['method_name', priority].
*/
public static function getSubscribedEvents()
{
return [
'onBuildPagesInitialized' => ['onBuildPagesInitialized', 0],
];
}
/**
* Initialize configuration.
*/
public function onBuildPagesInitialized()
{
if ($this->isAdmin()) {
$this->active = false;
return;
}
$this->enable([
'onPageContentRaw' => ['onPageContentRaw', 0],
]);
}
/**
* Add content after page content was read into the system.
*
* @param Event $event An event object, when `onPageContentRaw` is fired.
*/
public function onPageContentRaw(Event $event)
{
/** @var Page $page */
$page = $event['page'];
$twig = $this->grav['twig'];
$config = $this->mergeConfig($page);
if ($config->get('enabled')) {
// Get raw content and substitute all formulas by a unique token
$raw = $page->getRawContent();
// build an anonymous function to pass to `parseLinks()`
$function = function ($matches) use (&$page, &$twig, &$config) {
$search = $matches[0];
$type = $matches[1];
$filename = $matches[3] ?: $matches[2];
// $template = $matches[4];
$req_file = $page->path() . "/" . $filename;
$replace_header = "<pre><code>";
$replace_footer = "</code></pre>";
$replace_content = file_get_contents($req_file);
$replace = "$replace_header" . "$replace_content" . "$replace_footer";
// do the replacement
return $replace;
};
// set the parsed content back into as raw content
$page->setRawContent($this->parseInjectLinks($raw, $function));
}
}
protected function parseInjectLinks($content, $function)
{
$regex = '/\[plugin:(filesource)\]\(((.*)\?template=(.*)|(.*))\)/i';
return preg_replace_callback($regex, $function, $content);
}
}