r77812 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r77811‎ | r77812 | r77813 >
Date:16:55, 5 December 2010
Author:jeroendedauw
Status:deferred
Tags:
Comment:
follow up to r77771 - added stuff I forgot to svn add
Modified paths:
  • /trunk/extensions/SemanticResultFormats/compat (added) (history)
  • /trunk/extensions/SemanticResultFormats/compat/Html.php (added) (history)

Diff [purge]

Index: trunk/extensions/SemanticResultFormats/compat/Html.php
@@ -0,0 +1,569 @@
 2+<?php
 3+/**
 4+ * This is a copy of the Html class in MW core at includes/Html.php,
 5+ * created to make SRF remain compatible with pre 1.16 while using this class.
 6+ */
 7+
 8+# Copyright © 2009 Aryeh Gregor
 9+# http://www.mediawiki.org/
 10+#
 11+# This program is free software; you can redistribute it and/or modify
 12+# it under the terms of the GNU General Public License as published by
 13+# the Free Software Foundation; either version 2 of the License, or
 14+# (at your option) any later version.
 15+#
 16+# This program is distributed in the hope that it will be useful,
 17+# but WITHOUT ANY WARRANTY; without even the implied warranty of
 18+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 19+# GNU General Public License for more details.
 20+#
 21+# You should have received a copy of the GNU General Public License along
 22+# with this program; if not, write to the Free Software Foundation, Inc.,
 23+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 24+# http://www.gnu.org/copyleft/gpl.html
 25+
 26+/**
 27+ * This class is a collection of static functions that serve two purposes:
 28+ *
 29+ * 1) Implement any algorithms specified by HTML5, or other HTML
 30+ * specifications, in a convenient and self-contained way.
 31+ *
 32+ * 2) Allow HTML elements to be conveniently and safely generated, like the
 33+ * current Xml class but a) less confused (Xml supports HTML-specific things,
 34+ * but only sometimes!) and b) not necessarily confined to XML-compatible
 35+ * output.
 36+ *
 37+ * There are two important configuration options this class uses:
 38+ *
 39+ * $wgHtml5: If this is set to false, then all output should be valid XHTML 1.0
 40+ * Transitional.
 41+ * $wgWellFormedXml: If this is set to true, then all output should be
 42+ * well-formed XML (quotes on attributes, self-closing tags, etc.).
 43+ *
 44+ * This class is meant to be confined to utility functions that are called from
 45+ * trusted code paths. It does not do enforcement of policy like not allowing
 46+ * <a> elements.
 47+ *
 48+ * @since 1.16
 49+ */
 50+class Html {
 51+ # List of void elements from HTML5, section 9.1.2 as of 2009-08-10
 52+ private static $voidElements = array(
 53+ 'area',
 54+ 'base',
 55+ 'br',
 56+ 'col',
 57+ 'command',
 58+ 'embed',
 59+ 'hr',
 60+ 'img',
 61+ 'input',
 62+ 'keygen',
 63+ 'link',
 64+ 'meta',
 65+ 'param',
 66+ 'source',
 67+ );
 68+
 69+ # Boolean attributes, which may have the value omitted entirely. Manually
 70+ # collected from the HTML5 spec as of 2009-08-10.
 71+ private static $boolAttribs = array(
 72+ 'async',
 73+ 'autobuffer',
 74+ 'autofocus',
 75+ 'autoplay',
 76+ 'checked',
 77+ 'controls',
 78+ 'defer',
 79+ 'disabled',
 80+ 'formnovalidate',
 81+ 'hidden',
 82+ 'ismap',
 83+ 'loop',
 84+ 'multiple',
 85+ 'novalidate',
 86+ 'open',
 87+ 'readonly',
 88+ 'required',
 89+ 'reversed',
 90+ 'scoped',
 91+ 'seamless',
 92+ );
 93+
 94+ /**
 95+ * Returns an HTML element in a string. The major advantage here over
 96+ * manually typing out the HTML is that it will escape all attribute
 97+ * values. If you're hardcoding all the attributes, or there are none, you
 98+ * should probably type out the string yourself.
 99+ *
 100+ * This is quite similar to Xml::tags(), but it implements some useful
 101+ * HTML-specific logic. For instance, there is no $allowShortTag
 102+ * parameter: the closing tag is magically omitted if $element has an empty
 103+ * content model. If $wgWellFormedXml is false, then a few bytes will be
 104+ * shaved off the HTML output as well. In the future, other HTML-specific
 105+ * features might be added, like allowing arrays for the values of
 106+ * attributes like class= and media=.
 107+ *
 108+ * @param $element string The element's name, e.g., 'a'
 109+ * @param $attribs array Associative array of attributes, e.g., array(
 110+ * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
 111+ * further documentation.
 112+ * @param $contents string The raw HTML contents of the element: *not*
 113+ * escaped!
 114+ * @return string Raw HTML
 115+ */
 116+ public static function rawElement( $element, $attribs = array(), $contents = '' ) {
 117+ global $wgWellFormedXml;
 118+ $start = self::openElement( $element, $attribs );
 119+ if ( in_array( $element, self::$voidElements ) ) {
 120+ if ( $wgWellFormedXml ) {
 121+ # Silly XML.
 122+ return substr( $start, 0, -1 ) . ' />';
 123+ }
 124+ return $start;
 125+ } else {
 126+ return "$start$contents" . self::closeElement( $element );
 127+ }
 128+ }
 129+
 130+ /**
 131+ * Identical to rawElement(), but HTML-escapes $contents (like
 132+ * Xml::element()).
 133+ */
 134+ public static function element( $element, $attribs = array(), $contents = '' ) {
 135+ return self::rawElement( $element, $attribs, strtr( $contents, array(
 136+ # There's no point in escaping quotes, >, etc. in the contents of
 137+ # elements.
 138+ '&' => '&amp;',
 139+ '<' => '&lt;'
 140+ ) ) );
 141+ }
 142+
 143+ /**
 144+ * Identical to rawElement(), but has no third parameter and omits the end
 145+ * tag (and the self-closing '/' in XML mode for empty elements).
 146+ */
 147+ public static function openElement( $element, $attribs = array() ) {
 148+ global $wgHtml5, $wgWellFormedXml;
 149+ $attribs = (array)$attribs;
 150+ # This is not required in HTML5, but let's do it anyway, for
 151+ # consistency and better compression.
 152+ $element = strtolower( $element );
 153+
 154+ # In text/html, initial <html> and <head> tags can be omitted under
 155+ # pretty much any sane circumstances, if they have no attributes. See:
 156+ # <http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags>
 157+ if ( !$wgWellFormedXml && !$attribs
 158+ && in_array( $element, array( 'html', 'head' ) ) ) {
 159+ return '';
 160+ }
 161+
 162+ # Remove HTML5-only attributes if we aren't doing HTML5
 163+ if ( !$wgHtml5 ) {
 164+ if ( $element == 'input' ) {
 165+ # Whitelist of valid XHTML1 types
 166+ $validTypes = array(
 167+ 'hidden',
 168+ 'text',
 169+ 'password',
 170+ 'checkbox',
 171+ 'radio',
 172+ 'file',
 173+ 'submit',
 174+ 'image',
 175+ 'reset',
 176+ 'button',
 177+ );
 178+ if ( isset( $attribs['type'] )
 179+ && !in_array( $attribs['type'], $validTypes ) ) {
 180+ # Fall back to type=text, the default
 181+ unset( $attribs['type'] );
 182+ }
 183+ }
 184+ if ( $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
 185+ unset( $attribs['maxlength'] );
 186+ }
 187+ # Here we're blacklisting some HTML5-only attributes...
 188+ $html5attribs = array(
 189+ 'autocomplete',
 190+ 'autofocus',
 191+ 'max',
 192+ 'min',
 193+ 'multiple',
 194+ 'pattern',
 195+ 'placeholder',
 196+ 'required',
 197+ 'step',
 198+ 'spellcheck',
 199+ );
 200+ foreach ( $html5attribs as $badAttr ) {
 201+ unset( $attribs[$badAttr] );
 202+ }
 203+ }
 204+
 205+ return "<$element" . self::expandAttributes(
 206+ self::dropDefaults( $element, $attribs ) ) . '>';
 207+ }
 208+
 209+ /**
 210+ * Returns "</$element>", except if $wgWellFormedXml is off, in which case
 211+ * it returns the empty string when that's guaranteed to be safe.
 212+ *
 213+ * @param $element string Name of the element, e.g., 'a'
 214+ * @return string A closing tag, if required
 215+ */
 216+ public static function closeElement( $element ) {
 217+ global $wgWellFormedXml;
 218+
 219+ $element = strtolower( $element );
 220+
 221+ # Reference:
 222+ # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
 223+ if ( !$wgWellFormedXml && in_array( $element, array(
 224+ 'html',
 225+ 'head',
 226+ 'body',
 227+ 'li',
 228+ 'dt',
 229+ 'dd',
 230+ 'tr',
 231+ 'td',
 232+ 'th',
 233+ ) ) ) {
 234+ return '';
 235+ }
 236+ return "</$element>";
 237+ }
 238+
 239+ /**
 240+ * Given an element name and an associative array of element attributes,
 241+ * return an array that is functionally identical to the input array, but
 242+ * possibly smaller. In particular, attributes might be stripped if they
 243+ * are given their default values.
 244+ *
 245+ * This method is not guaranteed to remove all redundant attributes, only
 246+ * some common ones and some others selected arbitrarily at random. It
 247+ * only guarantees that the output array should be functionally identical
 248+ * to the input array (currently per the HTML 5 draft as of 2009-09-06).
 249+ *
 250+ * @param $element string Name of the element, e.g., 'a'
 251+ * @param $attribs array Associative array of attributes, e.g., array(
 252+ * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
 253+ * further documentation.
 254+ * @return array An array of attributes functionally identical to $attribs
 255+ */
 256+ private static function dropDefaults( $element, $attribs ) {
 257+ # Don't bother doing anything if we aren't outputting HTML5; it's too
 258+ # much of a pain to maintain two sets of defaults.
 259+ global $wgHtml5;
 260+ if ( !$wgHtml5 ) {
 261+ return $attribs;
 262+ }
 263+
 264+ static $attribDefaults = array(
 265+ 'area' => array( 'shape' => 'rect' ),
 266+ 'button' => array(
 267+ 'formaction' => 'GET',
 268+ 'formenctype' => 'application/x-www-form-urlencoded',
 269+ 'type' => 'submit',
 270+ ),
 271+ 'canvas' => array(
 272+ 'height' => '150',
 273+ 'width' => '300',
 274+ ),
 275+ 'command' => array( 'type' => 'command' ),
 276+ 'form' => array(
 277+ 'action' => 'GET',
 278+ 'autocomplete' => 'on',
 279+ 'enctype' => 'application/x-www-form-urlencoded',
 280+ ),
 281+ 'input' => array(
 282+ 'formaction' => 'GET',
 283+ 'type' => 'text',
 284+ 'value' => '',
 285+ ),
 286+ 'keygen' => array( 'keytype' => 'rsa' ),
 287+ 'link' => array( 'media' => 'all' ),
 288+ 'menu' => array( 'type' => 'list' ),
 289+ # Note: the use of text/javascript here instead of other JavaScript
 290+ # MIME types follows the HTML5 spec.
 291+ 'script' => array( 'type' => 'text/javascript' ),
 292+ 'style' => array(
 293+ 'media' => 'all',
 294+ 'type' => 'text/css',
 295+ ),
 296+ 'textarea' => array( 'wrap' => 'soft' ),
 297+ );
 298+
 299+ $element = strtolower( $element );
 300+
 301+ foreach ( $attribs as $attrib => $value ) {
 302+ $lcattrib = strtolower( $attrib );
 303+ $value = strval( $value );
 304+
 305+ # Simple checks using $attribDefaults
 306+ if ( isset( $attribDefaults[$element][$lcattrib] ) &&
 307+ $attribDefaults[$element][$lcattrib] == $value ) {
 308+ unset( $attribs[$attrib] );
 309+ }
 310+
 311+ if ( $lcattrib == 'class' && $value == '' ) {
 312+ unset( $attribs[$attrib] );
 313+ }
 314+ }
 315+
 316+ # More subtle checks
 317+ if ( $element === 'link' && isset( $attribs['type'] )
 318+ && strval( $attribs['type'] ) == 'text/css' ) {
 319+ unset( $attribs['type'] );
 320+ }
 321+ if ( $element === 'select' && isset( $attribs['size'] ) ) {
 322+ if ( in_array( 'multiple', $attribs )
 323+ || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
 324+ ) {
 325+ # A multi-select
 326+ if ( strval( $attribs['size'] ) == '4' ) {
 327+ unset( $attribs['size'] );
 328+ }
 329+ } else {
 330+ # Single select
 331+ if ( strval( $attribs['size'] ) == '1' ) {
 332+ unset( $attribs['size'] );
 333+ }
 334+ }
 335+ }
 336+
 337+ return $attribs;
 338+ }
 339+
 340+ /**
 341+ * Given an associative array of element attributes, generate a string
 342+ * to stick after the element name in HTML output. Like array( 'href' =>
 343+ * 'http://www.mediawiki.org/' ) becomes something like
 344+ * ' href="http://www.mediawiki.org"'. Again, this is like
 345+ * Xml::expandAttributes(), but it implements some HTML-specific logic.
 346+ * For instance, it will omit quotation marks if $wgWellFormedXml is false,
 347+ * and will treat boolean attributes specially.
 348+ *
 349+ * @param $attribs array Associative array of attributes, e.g., array(
 350+ * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
 351+ * A value of false means to omit the attribute. For boolean attributes,
 352+ * you can omit the key, e.g., array( 'checked' ) instead of
 353+ * array( 'checked' => 'checked' ) or such.
 354+ * @return string HTML fragment that goes between element name and '>'
 355+ * (starting with a space if at least one attribute is output)
 356+ */
 357+ public static function expandAttributes( $attribs ) {
 358+ global $wgHtml5, $wgWellFormedXml;
 359+
 360+ $ret = '';
 361+ $attribs = (array)$attribs;
 362+ foreach ( $attribs as $key => $value ) {
 363+ if ( $value === false ) {
 364+ continue;
 365+ }
 366+
 367+ # For boolean attributes, support array( 'foo' ) instead of
 368+ # requiring array( 'foo' => 'meaningless' ).
 369+ if ( is_int( $key )
 370+ && in_array( strtolower( $value ), self::$boolAttribs ) ) {
 371+ $key = $value;
 372+ }
 373+
 374+ # Not technically required in HTML5, but required in XHTML 1.0,
 375+ # and we'd like consistency and better compression anyway.
 376+ $key = strtolower( $key );
 377+
 378+ # See the "Attributes" section in the HTML syntax part of HTML5,
 379+ # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
 380+ # marks omitted, but not all. (Although a literal " is not
 381+ # permitted, we don't check for that, since it will be escaped
 382+ # anyway.)
 383+ #
 384+ # See also research done on further characters that need to be
 385+ # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
 386+ $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
 387+ . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
 388+ . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
 389+ if ( $wgWellFormedXml || $value === ''
 390+ || preg_match( "![$badChars]!u", $value ) ) {
 391+ $quote = '"';
 392+ } else {
 393+ $quote = '';
 394+ }
 395+
 396+ if ( in_array( $key, self::$boolAttribs ) ) {
 397+ # In XHTML 1.0 Transitional, the value needs to be equal to the
 398+ # key. In HTML5, we can leave the value empty instead. If we
 399+ # don't need well-formed XML, we can omit the = entirely.
 400+ if ( !$wgWellFormedXml ) {
 401+ $ret .= " $key";
 402+ } elseif ( $wgHtml5 ) {
 403+ $ret .= " $key=\"\"";
 404+ } else {
 405+ $ret .= " $key=\"$key\"";
 406+ }
 407+ } else {
 408+ # Apparently we need to entity-encode \n, \r, \t, although the
 409+ # spec doesn't mention that. Since we're doing strtr() anyway,
 410+ # and we don't need <> escaped here, we may as well not call
 411+ # htmlspecialchars(). FIXME: verify that we actually need to
 412+ # escape \n\r\t here, and explain why, exactly.
 413+ #
 414+ # We could call Sanitizer::encodeAttribute() for this, but we
 415+ # don't because we're stubborn and like our marginal savings on
 416+ # byte size from not having to encode unnecessary quotes.
 417+ $map = array(
 418+ '&' => '&amp;',
 419+ '"' => '&quot;',
 420+ "\n" => '&#10;',
 421+ "\r" => '&#13;',
 422+ "\t" => '&#9;'
 423+ );
 424+ if ( $wgWellFormedXml ) {
 425+ # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
 426+ # But reportedly it breaks some XML tools? FIXME: is this
 427+ # really true?
 428+ $map['<'] = '&lt;';
 429+ }
 430+ $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
 431+ }
 432+ }
 433+ return $ret;
 434+ }
 435+
 436+ /**
 437+ * Output a <script> tag with the given contents. TODO: do some useful
 438+ * escaping as well, like if $contents contains literal '</script>' or (for
 439+ * XML) literal "]]>".
 440+ *
 441+ * @param $contents string JavaScript
 442+ * @return string Raw HTML
 443+ */
 444+ public static function inlineScript( $contents ) {
 445+ global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
 446+
 447+ $attrs = array();
 448+ if ( !$wgHtml5 ) {
 449+ $attrs['type'] = $wgJsMimeType;
 450+ }
 451+ if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
 452+ $contents = "/*<![CDATA[*/$contents/*]]>*/";
 453+ }
 454+ return self::rawElement( 'script', $attrs, $contents );
 455+ }
 456+
 457+ /**
 458+ * Output a <script> tag linking to the given URL, e.g.,
 459+ * <script src=foo.js></script>.
 460+ *
 461+ * @param $url string
 462+ * @return string Raw HTML
 463+ */
 464+ public static function linkedScript( $url ) {
 465+ global $wgHtml5, $wgJsMimeType;
 466+
 467+ $attrs = array( 'src' => $url );
 468+ if ( !$wgHtml5 ) {
 469+ $attrs['type'] = $wgJsMimeType;
 470+ }
 471+ return self::element( 'script', $attrs );
 472+ }
 473+
 474+ /**
 475+ * Output a <style> tag with the given contents for the given media type
 476+ * (if any). TODO: do some useful escaping as well, like if $contents
 477+ * contains literal '</style>' (admittedly unlikely).
 478+ *
 479+ * @param $contents string CSS
 480+ * @param $media mixed A media type string, like 'screen'
 481+ * @return string Raw HTML
 482+ */
 483+ public static function inlineStyle( $contents, $media = 'all' ) {
 484+ global $wgWellFormedXml;
 485+
 486+ if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
 487+ $contents = "/*<![CDATA[*/$contents/*]]>*/";
 488+ }
 489+ return self::rawElement( 'style', array(
 490+ 'type' => 'text/css',
 491+ 'media' => $media,
 492+ ), $contents );
 493+ }
 494+
 495+ /**
 496+ * Output a <link rel=stylesheet> linking to the given URL for the given
 497+ * media type (if any).
 498+ *
 499+ * @param $url string
 500+ * @param $media mixed A media type string, like 'screen'
 501+ * @return string Raw HTML
 502+ */
 503+ public static function linkedStyle( $url, $media = 'all' ) {
 504+ return self::element( 'link', array(
 505+ 'rel' => 'stylesheet',
 506+ 'href' => $url,
 507+ 'type' => 'text/css',
 508+ 'media' => $media,
 509+ ) );
 510+ }
 511+
 512+ /**
 513+ * Convenience function to produce an <input> element. This supports the
 514+ * new HTML5 input types and attributes, and will silently strip them if
 515+ * $wgHtml5 is false.
 516+ *
 517+ * @param $name string name attribute
 518+ * @param $value mixed value attribute
 519+ * @param $type string type attribute
 520+ * @param $attribs array Associative array of miscellaneous extra
 521+ * attributes, passed to Html::element()
 522+ * @return string Raw HTML
 523+ */
 524+ public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
 525+ $attribs['type'] = $type;
 526+ $attribs['value'] = $value;
 527+ $attribs['name'] = $name;
 528+
 529+ return self::element( 'input', $attribs );
 530+ }
 531+
 532+ /**
 533+ * Convenience function to produce an input element with type=hidden, like
 534+ * Xml::hidden.
 535+ *
 536+ * @param $name string name attribute
 537+ * @param $value string value attribute
 538+ * @param $attribs array Associative array of miscellaneous extra
 539+ * attributes, passed to Html::element()
 540+ * @return string Raw HTML
 541+ */
 542+ public static function hidden( $name, $value, $attribs = array() ) {
 543+ return self::input( $name, $value, 'hidden', $attribs );
 544+ }
 545+
 546+ /**
 547+ * Convenience function to produce an <input> element. This supports leaving
 548+ * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
 549+ * but not required by HTML5 and will silently set cols="" and rows="" if
 550+ * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
 551+ * but empty cols="" and rows="" as valid).
 552+ *
 553+ * @param $name string name attribute
 554+ * @param $value string value attribute
 555+ * @param $attribs array Associative array of miscellaneous extra
 556+ * attributes, passed to Html::element()
 557+ * @return string Raw HTML
 558+ */
 559+ public static function textarea( $name, $value = '', $attribs = array() ) {
 560+ global $wgHtml5;
 561+ $attribs['name'] = $name;
 562+ if ( !$wgHtml5 ) {
 563+ if ( !isset( $attribs['cols'] ) )
 564+ $attribs['cols'] = "";
 565+ if ( !isset( $attribs['rows'] ) )
 566+ $attribs['rows'] = "";
 567+ }
 568+ return self::element( 'textarea', $attribs, $value );
 569+ }
 570+}
Property changes on: trunk/extensions/SemanticResultFormats/compat/Html.php
___________________________________________________________________
Added: svn:eol-style
1571 + native

Past revisions this follows-up on

RevisionCommit summaryAuthorDate
r77771Added copy of Html class for bcjeroendedauw05:25, 5 December 2010

Status & tagging log