1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CWP\Core\Extension; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Core\Extension; |
6
|
|
|
use SilverStripe\ORM\DataObject; |
7
|
|
|
use SilverStripe\Assets\File; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Adds capability to augment links with extra attributes and meta information. |
11
|
|
|
* |
12
|
|
|
* Usage in the templates: |
13
|
|
|
* $Content.RichLinks |
14
|
|
|
* |
15
|
|
|
* Note: will only work with content produced by HtmlEditorField. |
16
|
|
|
*/ |
17
|
|
|
class RichLinksExtension extends Extension |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var array |
22
|
|
|
*/ |
23
|
|
|
private static $casting = [ |
|
|
|
|
24
|
|
|
'RichLinks' => 'HTMLText' |
25
|
|
|
]; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @return string |
29
|
|
|
*/ |
30
|
|
|
public function RichLinks() |
31
|
|
|
{ |
32
|
|
|
// Note: |
33
|
|
|
// Assume we can use Regexes because the link will always be formatted |
34
|
|
|
// in the same way coming from the CMS. |
35
|
|
|
|
36
|
|
|
$content = $this->owner->value; |
37
|
|
|
|
38
|
|
|
// Find all file links for processing. |
39
|
|
|
preg_match_all('/<a.*href="\[file_link,id=([0-9]+)\].*".*>.*<\/a>/U', $content, $matches); |
40
|
|
|
|
41
|
|
|
// Attach the file type and size to each of the links. |
42
|
|
|
for ($i = 0; $i < count($matches[0]); $i++) { |
|
|
|
|
43
|
|
|
$file = DataObject::get_by_id(File::class, $matches[1][$i]); |
44
|
|
|
if ($file) { |
45
|
|
|
$size = $file->getSize(); |
46
|
|
|
$ext = strtoupper($file->getExtension()); |
47
|
|
|
// Replace the closing </a> tag with the size span (and reattach the closing tag). |
48
|
|
|
$newLink = substr($matches[0][$i], 0, strlen($matches[0][$i]) - 4) |
49
|
|
|
. "<span class='fileExt'> [$ext, $size]</span></a>"; |
50
|
|
|
$content = str_replace($matches[0][$i], $newLink, $content); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// Inject extra attributes into the external links. |
55
|
|
|
$pattern = '/(<a.*)(href=\"https?:\/\/[^\"]*\"[^>]*>.*)(<\/a>)/iU'; |
56
|
|
|
$replacement = sprintf( |
57
|
|
|
'$1class="external" rel="external" title="%s" $2<span class="nonvisual-indicator">(%s)</span>$3', |
58
|
|
|
_t(__CLASS__ . '.OpenLinkTitle', 'Open external link'), |
59
|
|
|
_t(__CLASS__ . '.ExternalLink', 'external link') |
60
|
|
|
); |
61
|
|
|
$content = preg_replace($pattern, $replacement, $content, -1); |
62
|
|
|
|
63
|
|
|
return $content; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|