FilterElf.php in External Links Filter 8
File
src/Plugin/Filter/FilterElf.php
View source
<?php
namespace Drupal\elf\Plugin\Filter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Component\Utility\Html;
class FilterElf extends FilterBase {
protected $pattern = '';
public function settingsForm(array $form, FormStateInterface $form_state) {
$form['elf_nofollow'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Add rel="nofollow" to all external links'),
'#default_value' => $this->settings['elf_nofollow'],
];
return $form;
}
public function process($text, $langcode) {
$elf_settings = \Drupal::config('elf.settings');
$result = new FilterProcessResult($text);
$dom = Html::load($text);
$links = $dom
->getElementsByTagName('a');
foreach ($links as $a) {
$href = $a
->getAttribute('href');
if (!$href) {
continue;
}
if (strpos($href, 'mailto:') === 0) {
$a
->setAttribute('class', $a
->getAttribute('class') ? $a
->getAttribute('class') . ' elf-mailto elf-icon' : 'elf-mailto elf-icon');
continue;
}
if ($this
->elf_url_external($href)) {
$a
->setAttribute('class', $a
->getAttribute('class') ? $a
->getAttribute('class') . ' elf-external elf-icon' : 'elf-external elf-icon');
if ($a
->getElementsByTagName('img')->length > 0) {
$a
->setAttribute('class', $a
->getAttribute('class') ? $a
->getAttribute('class') . ' elf-img' : 'elf-img');
}
$no_follow = $this
->getConfiguration()['settings']['elf_nofollow'];
if ($no_follow) {
$rel = array_filter(explode(' ', $a
->getAttribute('rel')));
if (!in_array('nofollow', $rel)) {
$rel[] = 'nofollow';
$a
->setAttribute('rel', implode(' ', $rel));
}
}
if ($elf_settings
->get('elf_redirect')) {
$redirect_url = \Drupal::service('elf.manager')
->getRedirectUrl($a
->getAttribute('href'));
$a
->setAttribute('href', $redirect_url
->toString());
}
}
}
$result
->setProcessedText(Html::serialize($dom))
->addAttachments([
'library' => [
'elf/elf_css',
],
]);
return $result;
}
public function tips($long = FALSE) {
return $this
->t('External and mailto links in content links have an icon.');
}
public function elf_url_external($url) {
global $base_url;
if (empty($this->pattern)) {
$domains = [];
$elf_domains = \Drupal::config('elf.settings')
->get('elf_domains');
$elf_domains = is_array($elf_domains) ? $elf_domains : [];
foreach (array_merge($elf_domains, [
$base_url,
]) as $domain) {
$domains[] = preg_quote($domain, '#');
}
$this->pattern = '#^(' . str_replace('\\*', '.*', implode('|', $domains)) . ')#';
}
return preg_match($this->pattern, $url) ? FALSE : UrlHelper::isExternal($url);
}
}
Classes
Name |
Description |
FilterElf |
Adds a CSS class to all external and mailto links. |