HTML-фильтр, совместимый с HTML5

Есть ли простой подход для добавления набора правил HTML5 для HTMLPurifier?

HP можно настроить для распознавания новых тегов с помощью:

// setup configurable HP instance $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.DefinitionID', 'html5 draft'); $config->set('HTML.DefinitionRev', 1); $config->set('Cache.DefinitionImpl', null); // no caching $def = $config->getHTMLDefinition(true); // add a new tag $form = $def->addElement( 'article', // name 'Block', // content set 'Flow', // allowed children 'Common', // attribute collection array( // attributes ) ); // add a new attribute $def->addAttribute('a', 'contextmenu', "ID"); 

Однако это явно немного работы. Поскольку существует множество новых тегов и атрибутов HTML5, которые необходимо было зарегистрировать. Новые глобальные атрибуты должны сочетаться даже с существующими тегами HTML 4. (Трудно судить по документам, как увеличить основные правила). Итак, существует ли более удобная структура config / array для подачи нового и обновленного атрибута tag + атрибута + контекстная конфигурация (inline / block / empty / flow / ..) в HTMLPurifier?

 # mostly confused about how to extend existing tags: $def->addAttribute('input', 'type', "...|...|..."); # or how to allow data-* attributes (if I actually wanted that): $def->addAttribute("data-*", ... 

И, конечно, не все новые теги HTML5 подходят для неограниченного допуска. HTMLPurifier – это все, что касается фильтрации содержимого. Определение ограничений значений – это где. – <canvas> например, может быть не такой большой, если он появляется в пользовательском контенте. Потому что это бесполезно в лучшем случае без Javascript (который HP уже отфильтровывает). Но другие теги и атрибуты могут быть нежелательными; поэтому гибкая структура конфигурации является обязательной для включения / отключения тегов и связанных с ними атрибутов.

( Предположим, я должен обновить некоторые исследования … ). Но до сих пор нет практического компендиума / спецификации (нет, XML DTD – нет), который соответствует конфигурации HP.

  • http://simon.html5.org/html-elements
  • http://www.w3.org/TR/html5-diff/#new-elements
  • http://www.w3.org/TR/html5-diff/#new-attributes

(Uh, а HTML5 больше не черновик).

Расширение php tidy можно настроить для распознавания тэгов html5. http://tidy.sourceforge.net/docs/quickref.html#new-blocklevel-tags

Эта настройка для HTMLpurify позволяет использовать более новые теги HTML5.

Источник: https://github.com/kennberg/php-htmlpurfier-html5

,

 <?php /** * Load HTMLPurifier with HTML5, TinyMCE, YouTube, Video support. * * Copyright 2014 Alex Kennberg (https://github.com/kennberg/php-htmlpurifier-html5) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require_once(LIB_DIR . 'third-party/htmlpurifier/HTMLPurifier.safe-includes.php'); function load_htmlpurifier($allowed) { $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.Doctype', 'HTML 4.01 Transitional'); $config->set('CSS.AllowTricky', true); $config->set('Cache.SerializerPath', '/tmp'); // Allow iframes from: // o YouTube.com // o Vimeo.com $config->set('HTML.SafeIframe', true); $config->set('URI.SafeIframeRegexp', '%^(http:|https:)?//(www.youtube(?:-nocookie)?.com/embed/|player.vimeo.com/video/)%'); $config->set('HTML.Allowed', implode(',', $allowed)); // Set some HTML5 properties $config->set('HTML.DefinitionID', 'html5-definitions'); // unqiue id $config->set('HTML.DefinitionRev', 1); if ($def = $config->maybeGetRawHTMLDefinition()) { // http://developers.whatwg.org/sections.html $def->addElement('section', 'Block', 'Flow', 'Common'); $def->addElement('nav', 'Block', 'Flow', 'Common'); $def->addElement('article', 'Block', 'Flow', 'Common'); $def->addElement('aside', 'Block', 'Flow', 'Common'); $def->addElement('header', 'Block', 'Flow', 'Common'); $def->addElement('footer', 'Block', 'Flow', 'Common'); // Content model actually excludes several tags, not modelled here $def->addElement('address', 'Block', 'Flow', 'Common'); $def->addElement('hgroup', 'Block', 'Required: h1 | h2 | h3 | h4 | h5 | h6', 'Common'); // http://developers.whatwg.org/grouping-content.html $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common'); $def->addElement('figcaption', 'Inline', 'Flow', 'Common'); // http://developers.whatwg.org/the-video-element.html#the-video-element $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array( 'src' => 'URI', 'type' => 'Text', 'width' => 'Length', 'height' => 'Length', 'poster' => 'URI', 'preload' => 'Enum#auto,metadata,none', 'controls' => 'Bool', )); $def->addElement('source', 'Block', 'Flow', 'Common', array( 'src' => 'URI', 'type' => 'Text', )); // http://developers.whatwg.org/text-level-semantics.html $def->addElement('s', 'Inline', 'Inline', 'Common'); $def->addElement('var', 'Inline', 'Inline', 'Common'); $def->addElement('sub', 'Inline', 'Inline', 'Common'); $def->addElement('sup', 'Inline', 'Inline', 'Common'); $def->addElement('mark', 'Inline', 'Inline', 'Common'); $def->addElement('wbr', 'Inline', 'Empty', 'Core'); // http://developers.whatwg.org/edits.html $def->addElement('ins', 'Block', 'Flow', 'Common', array('cite' => 'URI', 'datetime' => 'CDATA')); $def->addElement('del', 'Block', 'Flow', 'Common', array('cite' => 'URI', 'datetime' => 'CDATA')); // TinyMCE $def->addAttribute('img', 'data-mce-src', 'Text'); $def->addAttribute('img', 'data-mce-json', 'Text'); // Others $def->addAttribute('iframe', 'allowfullscreen', 'Bool'); $def->addAttribute('table', 'height', 'Text'); $def->addAttribute('td', 'border', 'Text'); $def->addAttribute('th', 'border', 'Text'); $def->addAttribute('tr', 'width', 'Text'); $def->addAttribute('tr', 'height', 'Text'); $def->addAttribute('tr', 'border', 'Text'); } return new HTMLPurifier($config); } 

im используя исправление для wordpress, но, возможно, это может помочь вам (по крайней мере, для части массива)

http://nicolasgallagher.com/using-html5-elements-in-wordpress-post-content/

http://hybridgarden.com/blog/misc/adding-html5-capability-to-wordpress/

также:

http://code.google.com/p/html5lib/ Реализации Python и PHP парсера HTML на основе спецификации WHATWG HTML5 для максимальной совместимости с основными веб-браузерами на рабочем столе.

В роли Gallery есть экспериментальный парсер HTML5, основанный на HTMLPurifier:

https://github.com/gallery/gallery3-vendor/blob/master/htmlpurifier/modified/HTMLPurifier/Lexer/PH5P.php