-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.php
More file actions
72 lines (57 loc) · 2.39 KB
/
Copy pathplugin.php
File metadata and controls
72 lines (57 loc) · 2.39 KB
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
<?php
class TOCPlugin extends Plugin
{
public function init()
{
$this->dbFields = array();
}
public function siteBodyBegin()
{
global $WHERE_AM_I, $page;
if ($WHERE_AM_I == 'page') {
// Retrieve the original content of the page
$content = $page->content();
// Check if the TOC is already present in the content.
if (strpos($content, '<div id="toc">') === false) {
// Generate TOC based on content
$toc = $this->generateTOC($content);
// If the TOC is successfully created, add the TOC at the beginning of the content.
if (!empty($toc)) {
// Save only new content (TOC + article with link ID)
$modifiedContent = $toc;
$page->setField('content', $modifiedContent);
}
} else {
// If the TOC already exists, use the content as is without modification.
$page->setField('content', $content);
}
}
}
// Function to generate TOC
public function generateTOC($content)
{
$toc = '<div id="toc"><h5 class="mb-3 pb-3 border-bottom">Daftar Isi</h5><ul>';
// Regex to find headings from h2 to h6
$pattern = '/<h([2-3])([^>]*)>(.*?)<\/h\1>/i';
// Matching headings in the content
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
// If there is no heading, return empty.
if (empty($matches)) {
return ''; // No heading, TOC will not be displayed.
}
// Process each heading found and add an anchor ID.
foreach ($matches as $match) {
// Creating anchor IDs based on heading text
$headingText = strip_tags($match[3]);
$anchorID = strtolower(trim(preg_replace('/[^a-z0-9]+/', '-', $headingText), '-'));
// Adding anchor ID to heading
$content = str_replace($match[0], '<h' . $match[1] . ' id="' . $anchorID . '">' . $match[3] . '</h' . $match[1] . '>', $content);
// Adding items to TOC
$toc .= '<li class="toc-level-' . $match[1] . '"><a href="#' . $anchorID . '">' . $headingText . '</a></li>';
}
// Closing the tags <ul> and <div>
$toc .= '</ul></div>';
// Return the TOC and article content
return $toc . $content;
}
}