decarbone/site/plugins/process-links/index.php
2026-02-13 15:40:11 +01:00

69 lines
2.4 KiB
PHP

<?php
Kirby::plugin('adrienpayet/process-links', [
'fieldMethods' => [
'processLinks' => function ($field) {
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($field->value(), 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$anchorTags = $dom->getElementsByTagName('a');
$site = site();
for ($i = $anchorTags->length - 1; $i >= 0; $i--) {
$anchorTag = $anchorTags->item($i);
$href = $anchorTag->getAttribute('href');
$getIdPattern = '/@\/page\/(.*)/';
$regexResult = preg_match($getIdPattern, $href, $matches);
$isInternalPageLink = $regexResult && isset($matches[1]);
$isMailto = str_contains($href, 'mailto');
$isNote = !str_contains($href, 'http');
if (!$isMailto) {
if ($isInternalPageLink) {
processInternalLink($anchorTag, $site, $matches[1]);
} elseif ($isNote) {
processNote($dom, $anchorTag, $href);
} else {
$anchorTag->setAttribute('target', '_blank');
}
}
}
return $dom->saveHTML();
}
]
]);
function processInternalLink($anchorTag, $site, $targetId) {
try {
$targetPage = $site->find('page://' . $targetId);
if (!$targetPage) {
throw new Exception("No internal page found.");
}
$anchorTag->removeAttribute('target');
$attributes = [
'href' => $targetPage->url(),
'class' => 'internal-link',
'data-size' => formatSize($targetPage->size()->toInt())
];
foreach ($attributes as $key => $value) {
$anchorTag->setAttribute($key, $value);
}
} catch (Exception $e) {
error_log($e->getMessage());
}
}
function processNote($dom, $anchorTag, $href) {
$note = $dom->createElement('span');
$note->setAttribute('class', 'note');
$button = $dom->createElement('button');
$text = new DOMText($anchorTag->nodeValue);
$button->appendChild($text);
$note->appendChild($button);
$details = $dom->createElement('span');
$details->setAttribute('class', 'details hide');
$detailsText = new DOMText(' ' . urldecode($href));
$details->appendChild($detailsText);
$note->appendChild($details);
$anchorTag->parentNode->replaceChild($note, $anchorTag);
}