<?php
function rewrite_relative_links($md, $page, $baselink = null) {
if(!$baselink) $baselink = $page->getEntity()->getRelativeLink();
$re = '/
([^\!]?) # exclude image format
\[
(.*?) # link title (non greedy)
\]
\(
(.*?) # link url (non greedy)
\)
/x';
preg_match_all($re, $md, $matches);
// relative path (relative to module base folder), without the filename.
// For "sapphire/en/current/topics/templates", this would be "templates"
$relativePath = dirname($page->getRelativePath());
if($relativePath == '.') $relativePath = '';
// file base link
$fileBaseLink = Director::makeRelative(dirname($page->getPath()));
if($matches) {
foreach($matches[0] as $i => $match) {
$title = $matches[2][$i];
$url = $matches[3][$i];
// Don't process API links
if(preg_match('/^api:/', $url)) continue;
// Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url);
if($urlParts && isset($urlParts['scheme'])) continue;
// for images we need to use the file base path
if(preg_match('/_images/', $url)) {
$relativeUrl = Controller::join_links(
Director::absoluteBaseURL(),
$fileBaseLink,
$url
);
}
else {
// Rewrite public URL
if(preg_match('/^\//', $url)) {
// Absolute: Only path to module base
$relativeUrl = Controller::join_links($baselink, $url);
} else {
// Relative: Include path to module base and any folders
$relativeUrl = Controller::join_links($baselink, $relativePath, $url);
}
}
// Resolve relative paths
while(strpos($relativeUrl, '..') !== FALSE) {
$relativeUrl = preg_replace('/\w+\/\.\.\//', '', $relativeUrl);
}
// Replace any double slashes (apart from protocol)
$relativeUrl = preg_replace('/([^:])\/{2,}/', '$1/', $relativeUrl);
// Replace in original content
$md = str_replace(
$match,
sprintf('%s[%s](%s)', $matches[1][$i], $title, $relativeUrl),
$md
);
}
}
return $md;
}
- Output for 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- Output for 4.4.2 - 4.4.9
- <br />
<b>Parse error</b>: syntax error, unexpected T_OBJECT_OPERATOR in <b>/in/luQ67</b> on line <b>4</b><br />
Process exited with code 255. - Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
- <br />
<b>Parse error</b>: parse error, unexpected T_OBJECT_OPERATOR in <b>/in/luQ67</b> on line <b>4</b><br />
Process exited with code 255. - Output for 4.3.2 - 4.3.4
- <br />
<b>Parse error</b>: parse error in <b>/in/luQ67</b> on line <b>4</b><br />
Process exited with code 255.
preferences:
348.4 ms | 401 KiB | 468 Q