We now support CodePen embeds! While our page editor strips out most HTML tags, including <script>
tags, we've made a special provision to support tags specifically from CodePen. All you need to do is paste the embed code directly from CodePen into the page editor.
We use ParseDown and HTMLPurifier to encode Markdown and sanitize the resulting HTML. In order to support CodePen we needed to extract the entire embed before passing the HTML through the sanitizer then re-insert the pens upon completion. We used PHP's obscure preg_replace_callback
function to replace each CodePen with a variable, {codepen_1}
, {codepen_2}
, etc. then after the input is sanitized the variables are replaced with the original embeds.
I'm happy with how it turned out, so I thought I'd share the code.
/********************************************************************************/
// Convert the raw markdown into parsed HTML.
$parsedown = new Parsedown();
$content = $parsedown->parse($content);
/********************************************************************************/
// Sanitize the HTML to include only the Markdown elements and Codepens.
global $codepens;
$content = preg_replace_callback("/(\<p data-height.*?\<script async src\=\"\/\/[a-z]*\.{0,1}codepen.io.*?script\>)/s",
create_function('$m', '
static $id = 0;
global $codepens;
$id++;
$codepens[$id] = $m[1];
return "{codepen_$id}";
'),
$content
);
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'pre,code[class],img[src],img[alt],br,p,h1,h2,h3,h4,h5,blockquote,ol,li,ul,table[class],th,thead,tbody,tr,td,a[href],hr,strong,b,em,del,i,u,strike');
$purifier = new HTMLPurifier($config);
$content = $purifier->purify($content);
$content = preg_replace_callback("/\{codepen_(.*?)\}/s",
create_function('$m', '
global $codepens;
$id = $m[1];
return $codepens[$id];
'),
$content
);
See the Pen Canvas Fireworks by Jack Rugile (@jackrugile) on CodePen.