Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add better URL detection in ClickableHook #136

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 41 additions & 10 deletions src/Decoda/Hook/ClickableHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class ClickableHook extends AbstractHook {
* @param string $content
* @return string
*/

public function beforeParse($content) {
$parser = $this->getParser();

Expand Down Expand Up @@ -48,16 +49,46 @@ public function beforeParse($content) {
if ($parser->hasFilter('Url')) {
$protocols = $parser->getFilter('Url')->getConfig('protocols');
$chars = preg_quote('-_=+|\;:&?/[]%,.!@#$*(){}"\'', '/');
$split_char = "<>[] ";
$split_chars = [];
$result = [];

$length = strlen($content);
$split = [];
$current = "";
for ($i = 0; $i < $length; ++$i) {
if (strpos($split_char, $content[$i]) !== false) {
array_push($split_chars, $content[$i]);
array_push($split, $current);
$current = "";
} else {
$current .= $content[$i];
}
}

if (strlen($current) != 0) {
array_push($split, $current);
}

$pattern = implode('', array(
'((' . implode('|', $protocols) . ')s?:\/\/([\w\.\+]+:[\w\.\+]+@)?|www\.)', // protocol & login or www. (without http(s))
'([\w\-\.]{5,255}+)', // domain, tld
'(:[0-9]{0,6}+)?', // port
'(\/?\?[a-z0-9' . $chars . ']+)?', // query
'(#[a-z0-9' . $chars . ']+)?' // fragment
));
$length = count($split);
for ($i = 0; $i < $length; ++$i) {
if (filter_var($split[$i], FILTER_VALIDATE_URL)) {
$split[$i] = self::_urlCallback($split[$i]);
} else if (preg_match("/www\.[A-z,-]+\.[A-z,-]+/", $split[$i])) {
$split[$i] = self::_urlCallback($split[$i]);
}
}

$result = "";
$split_length = count($split_chars);
for ($i = 0; $i < $length; ++$i) {
$result .= $split[$i];
if ($i < $split_length) {
$result .= $split_chars[$i];
}
}

$content = preg_replace_callback('/(' . $pattern . ')/i', array($this, '_urlCallback'), $content);
$content = $result;
}

// Based on W3C HTML5 spec: https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
Expand Down Expand Up @@ -99,11 +130,11 @@ protected function _emailCallback($matches) {
* @param array $matches
* @return string
*/
protected function _urlCallback($matches) {
protected function _urlCallback($match) {
return $this->getParser()->getFilter('Url')->parse(array(
'tag' => 'url',
'attributes' => array()
), trim($matches[1]));
), trim($match));
}

}