如何在HTMLPurifier中允许Google Fonts链接?
问题解决步骤
1. 修复Cannot retrieve undefined attribute type link错误
该错误源于你添加iframe的allowfullscreen属性时参数错误,HTMLPurifier的addAttribute方法第三个参数是属性类型,不存在link这个类型。将代码中的:
$def->addAttribute('iframe','allowfullscreen','link', 'Bool');
修改为:
$def->addAttribute('iframe', 'allowfullscreen', 'Bool');
2. 正确配置以允许Google Fonts的link标签
要让HTMLPurifier放行Google Fonts的link标签,需补充以下配置并调整现有错误项:
2.1 允许rel="stylesheet"的链接
添加配置允许link标签的rel属性值为stylesheet:
$config->set('HTML.AllowedRel', 'stylesheet');
2.2 允许fonts.googleapis.com域名的URL
配置URI白名单,纳入Google Fonts的域名:
$config->set('URI.AllowedHosts', array( 'fonts.googleapis.com', 'www.youtube.com', 'youtube-nocookie.com', 'player.vimeo.com' ));
2.3 移除无效的CSS属性配置
stylesheet是link标签的rel属性值,不属于CSS属性,从CSS.AllowedProperties中删除:
$config->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,margin-left,margin-right,float,color,background-color,text-align,width,max-width,padding-left,border');
完整修改后的代码
function strTrim($dirty_html, $config = FALSE){ require_once('ThirdParty/HTMLPurifier/library/HTMLPurifier.auto.php'); if (is_array($dirty_html)) { foreach ($dirty_html as $key => $val) { $clean_html[$key] = strTrim($val, $config); } } else { $config = HTMLPurifier_Config::createDefault(); $config->set('Core.Encoding', 'utf-8'); $config->set("AutoFormat.AutoParagraph", false); $config->set("Core.NormalizeNewlines", true); $config->set('HTML.Allowed', 'link[href|rel],iframe[src|title|frameborder|allowfullscreen|class|width|height],p,b,strong,a[href|title],abbr[title],blockquote[cite],code,pre[class],em,i,strike,u,s,sub,sup,ol,ul,li,hr,img[title|alt|src|class|style],h1,h2,h3,h4,h5,h6,object[width|height|data],param[name|value],embed[src|type|allowscriptaccess|width|height],br,*[style]'); // 移除无效的stylesheet属性,保留合法CSS属性 $config->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,margin-left,margin-right,float,color,background-color,text-align,width,max-width,padding-left,border'); $config->set('HTML.MaxImgLength', NULL); $config->set('CSS.MaxImgLength', NULL); $config->set('HTML.SafeObject', true); $config->set('HTML.SafeEmbed', true); $config->set('Output.FlashCompat', true); $config->set('AutoFormat.RemoveEmpty', true); $config->set('AutoFormat.RemoveEmpty.RemoveNbsp', true); $config->set('HTML.SafeIframe', true); $config->set('URI.SafeIframeRegexp', '%^//(www.youtube(?:-nocookie)?.com/embed/|player.vimeo.com/video/)%'); // 允许rel="stylesheet"的link标签 $config->set('HTML.AllowedRel', 'stylesheet'); // 允许Google Fonts等合法域名的URL $config->set('URI.AllowedHosts', array( 'fonts.googleapis.com', 'www.youtube.com', 'youtube-nocookie.com', 'player.vimeo.com' )); $def = $config->getHTMLDefinition(true); // 修复iframe allowfullscreen属性的添加方式 $def->addAttribute('iframe', 'allowfullscreen', 'Bool'); $purifier = new HTMLPurifier($config); $clean_html = $purifier->purify($dirty_html); } return $clean_html; }
内容的提问来源于stack exchange,提问作者DLK
相关产品推荐
相关产品推荐

