Created
October 1, 2010 18:18
-
-
Save Majkl578/606623 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* namespace DJPW; */ | |
/** | |
* Perform transformation of BBCodes | |
* | |
* @copyright 2010 Diskuze.JakPsatWeb.cz | |
*/ | |
final class BBCode | |
{ | |
/** @var array replace patterns */ | |
public static $patterns = array( | |
'~\[([ibu])\](.*)\[/\\1\]~isU' => '<\\1>\\2</\\1>', //nahrazení [b]...[/b], [i]...[/i] a [u]...[/u] | |
'~\[img\](.*)\[/img\]~isU' => '<img src="\\1" alt="Obrázek" />', //nahrazení [img]...[/img] | |
'~\[url(?:=((?:ht|f)tps?://\S+)|)\](.*)\[/url\]~isU' => array(__CLASS__, 'replaceUrlCb'), //nahrazení [url=...]...[/url] a [url]...[/url] | |
); | |
/** @var bool sanitize against XSS */ | |
private $sanitizeHtml = TRUE; | |
/** | |
* Sanitize HTML implicitly or not? | |
* @param bool | |
* @return BBCode | |
*/ | |
public function sanitizeHtml($sanitize) | |
{ | |
$this->sanitizeHtml = (bool) $sanitize; | |
return $this; | |
} | |
/** | |
* Perform the transformation | |
* @param string The string with BB codes | |
* @return void | |
*/ | |
public function __invoke(& $string) | |
{ | |
if ($this->sanitizeHtml) { // sanitize against XSS | |
$string = htmlspecialchars($string); | |
} | |
foreach (self::$patterns as $pattern => $replacement) { | |
if (!is_string($replacement) && is_callable($replacement)) { | |
$string = preg_replace_callback($pattern, $replacement, $string); | |
} else { | |
$string = preg_replace($pattern, $replacement, $string); | |
} | |
} | |
} | |
/*************** pattern callbacks ***********/ | |
private static function replaceUrlCb($match) | |
{ | |
return '<a href="' . $match[2] . '" target="_blank">' . ($match[1] === '' ? $match[2] : $match[1]) . '</a>'; | |
} | |
} | |
$string = <<<EOS | |
<script>alert('XSS')</script> | |
[b]foo[/b] | |
[img]http://www.seznam.cz/st/img/logo-2.gif[/img] | |
[url=http://www.seznam.cz/]Seznam.cz[/url] | |
[url]http://www.seznam.cz/st/img/logo-2.gif[/url] | |
http://www.seznam.cz/st/img/logo-2.gif | |
foobar | |
EOS; | |
$bbcode = new /*\DJPW\*/BBCode; | |
$bbcode/*->__invoke*/($string); // proceed | |
echo htmlspecialchars($string); // just for debugging |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment