idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
44,000
protected static function getProperties ( DOMElement $ element ) { return ( isset ( self :: $ htmlElements [ $ element -> nodeName ] ) ) ? self :: $ htmlElements [ $ element -> nodeName ] : self :: $ htmlElements [ 'span' ] ; }
Return the properties associated with given element
44,001
protected static function hasProperty ( DOMElement $ element , $ propName ) { $ props = self :: getProperties ( $ element ) ; return ! empty ( $ props [ $ propName ] ) && ( ! isset ( $ props [ $ propName . '?' ] ) || self :: evaluate ( $ props [ $ propName . '?' ] , $ element ) ) ; }
Test whether given element has given property in context
44,002
protected static function toBin ( $ raw ) { $ bin = '' ; foreach ( str_split ( $ raw , 1 ) as $ char ) { $ bin .= strrev ( substr ( '0000000' . decbin ( ord ( $ char ) ) , - 8 ) ) ; } return $ bin ; }
Convert a raw string to a series of 0 and 1 in LSB order
44,003
public function add ( $ siteId , array $ siteConfig = null ) { $ siteId = $ this -> normalizeId ( $ siteId ) ; if ( isset ( $ siteConfig ) ) { $ siteConfig = $ this -> defaultSites -> normalizeValue ( $ siteConfig ) ; } else { $ siteConfig = $ this -> defaultSites -> get ( $ siteId ) ; } $ siteConfig [ 'extract' ] = $ this -> convertRegexps ( $ siteConfig [ 'extract' ] ) ; $ siteConfig [ 'scrape' ] = $ this -> convertScrapes ( $ siteConfig [ 'scrape' ] ) ; $ this -> checkAttributeFilters ( $ siteConfig [ 'attributes' ] ) ; $ tag = $ this -> addTag ( $ siteId , $ siteConfig ) ; $ this -> sites [ $ siteId ] = $ siteConfig ; foreach ( $ siteConfig [ 'host' ] as $ host ) { $ this -> configurator -> registeredVars [ 'MediaEmbed.hosts' ] [ $ host ] = $ siteId ; } $ this -> configurator -> registeredVars [ 'MediaEmbed.sites' ] [ $ siteId ] = [ $ siteConfig [ 'extract' ] , $ siteConfig [ 'scrape' ] ] ; return $ tag ; }
Add a media site
44,004
protected function addTag ( $ siteId , array $ siteConfig ) { $ tag = new Tag ( [ 'attributes' => $ this -> getAttributesConfig ( $ siteConfig ) , 'rules' => [ 'allowChild' => 'URL' , 'autoClose' => true , 'denyChild' => [ $ siteId , $ this -> tagName ] ] , 'template' => $ this -> templateBuilder -> build ( $ siteId , $ siteConfig ) ] ) ; $ this -> configurator -> templateNormalizer -> normalizeTag ( $ tag ) ; $ this -> configurator -> templateChecker -> checkTag ( $ tag ) ; $ this -> configurator -> tags -> add ( $ siteId , $ tag ) ; return $ tag ; }
Create and return a tag that handles given media site
44,005
protected function checkAttributeFilters ( array $ attributes ) { foreach ( $ attributes as $ attrConfig ) { if ( empty ( $ attrConfig [ 'filterChain' ] ) ) { continue ; } foreach ( $ attrConfig [ 'filterChain' ] as $ filter ) { if ( substr ( $ filter , 0 , 1 ) !== '#' && ! in_array ( $ filter , $ this -> allowedFilters , true ) ) { throw new RuntimeException ( "Filter '$filter' is not allowed in media sites" ) ; } } } }
Check the safety of given attributes
44,006
protected function convertScrapeConfig ( array $ config ) { $ config [ 'extract' ] = $ this -> convertRegexps ( $ config [ 'extract' ] ) ; $ config [ 'match' ] = $ this -> convertRegexps ( $ config [ 'match' ] ) ; return $ config ; }
Convert all regexps in a scraping config
44,007
protected function createMediaTag ( ) { $ tag = $ this -> configurator -> tags -> add ( $ this -> tagName ) ; $ tag -> rules -> autoClose ( ) ; $ tag -> rules -> denyChild ( $ this -> tagName ) ; $ tag -> filterChain -> clear ( ) ; $ tag -> filterChain -> append ( __NAMESPACE__ . '\\Parser::filterTag' ) -> resetParameters ( ) -> addParameterByName ( 'tag' ) -> addParameterByName ( 'parser' ) -> addParameterByName ( 'MediaEmbed.hosts' ) -> addParameterByName ( 'MediaEmbed.sites' ) -> addParameterByName ( 'cacheDir' ) -> setJS ( file_get_contents ( __DIR__ . '/Parser/tagFilter.js' ) ) ; }
Create the default MEDIA tag
44,008
protected function getAttributesConfig ( array $ siteConfig ) { $ attrNames = $ this -> getAttributeNamesFromRegexps ( $ siteConfig [ 'extract' ] ) ; foreach ( $ siteConfig [ 'scrape' ] as $ scrapeConfig ) { $ attrNames += $ this -> getAttributeNamesFromRegexps ( $ scrapeConfig [ 'extract' ] ) ; } $ attributes = $ siteConfig [ 'attributes' ] + array_fill_keys ( array_keys ( $ attrNames ) , [ ] ) ; foreach ( $ attributes as & $ attrConfig ) { $ attrConfig += [ 'required' => false ] ; } unset ( $ attrConfig ) ; return $ attributes ; }
Get the attributes config for given site config
44,009
protected function addTag ( $ tagPos , $ tagLen , $ hex ) { $ tag = $ this -> parser -> addSelfClosingTag ( $ this -> config [ 'tagName' ] , $ tagPos , $ tagLen , 10 ) ; $ seq = str_replace ( [ '-200d' , '-fe0f' ] , '' , $ hex ) ; $ tag -> setAttribute ( 'seq' , $ seq ) ; $ tseq = preg_replace ( '(-fe0f$)' , '' , ltrim ( $ hex , '0' ) ) ; $ tag -> setAttribute ( 'tseq' , $ tseq ) ; }
Add an emoji tag for given sequence
44,010
protected function getHexSequence ( $ str ) { $ seq = [ ] ; $ i = 0 ; do { $ cp = ord ( $ str [ $ i ] ) ; if ( $ cp >= 0xF0 ) { $ cp = ( $ cp << 18 ) + ( ord ( $ str [ ++ $ i ] ) << 12 ) + ( ord ( $ str [ ++ $ i ] ) << 6 ) + ord ( $ str [ ++ $ i ] ) - 0x3C82080 ; } elseif ( $ cp >= 0xE0 ) { $ cp = ( $ cp << 12 ) + ( ord ( $ str [ ++ $ i ] ) << 6 ) + ord ( $ str [ ++ $ i ] ) - 0xE2080 ; } elseif ( $ cp >= 0xC0 ) { $ cp = ( $ cp << 6 ) + ord ( $ str [ ++ $ i ] ) - 0x3080 ; } $ seq [ ] = sprintf ( '%04x' , $ cp ) ; } while ( ++ $ i < strlen ( $ str ) ) ; return implode ( '-' , $ seq ) ; }
Get the sequence of Unicode codepoints that corresponds to given emoji
44,011
protected function parseCustomAliases ( $ text ) { if ( empty ( $ this -> config [ 'customRegexp' ] ) ) { return ; } $ matchPos = 0 ; if ( isset ( $ this -> config [ 'customQuickMatch' ] ) ) { $ matchPos = strpos ( $ text , $ this -> config [ 'customQuickMatch' ] ) ; if ( $ matchPos === false ) { return ; } } preg_match_all ( $ this -> config [ 'customRegexp' ] , $ text , $ matches , PREG_OFFSET_CAPTURE , $ matchPos ) ; foreach ( $ matches [ 0 ] as list ( $ alias , $ tagPos ) ) { if ( isset ( $ this -> parser -> registeredVars [ 'Emoji.aliases' ] [ $ alias ] ) ) { $ hex = $ this -> getHexSequence ( $ this -> parser -> registeredVars [ 'Emoji.aliases' ] [ $ alias ] ) ; $ this -> addTag ( $ tagPos , strlen ( $ alias ) , $ hex ) ; } } }
Parse custom aliases in given text
44,012
protected function parseShortnames ( $ text ) { $ matchPos = strpos ( $ text , ':' ) ; if ( $ matchPos === false ) { return ; } preg_match_all ( $ this -> shortnameRegexp , $ text , $ matches , PREG_OFFSET_CAPTURE , $ matchPos ) ; foreach ( $ matches [ 0 ] as list ( $ alias , $ tagPos ) ) { $ alias .= ':' ; $ tagLen = strlen ( $ alias ) ; if ( isset ( $ this -> parser -> registeredVars [ 'Emoji.aliases' ] [ $ alias ] ) ) { $ hex = $ this -> getHexSequence ( $ this -> parser -> registeredVars [ 'Emoji.aliases' ] [ $ alias ] ) ; $ this -> addTag ( $ tagPos , $ tagLen , $ hex ) ; } elseif ( preg_match ( '/^:[0-3][0-9a-f]{3,4}(?:-[0-9a-f]{4,5})*:$/' , $ alias ) ) { $ this -> addTag ( $ tagPos , $ tagLen , substr ( $ alias , 1 , - 1 ) ) ; } } }
Parse shortnames in given text
44,013
protected function parseUnicode ( $ text ) { if ( strpos ( $ text , "\xE2" ) === false && strpos ( $ text , "\xEF" ) === false && strpos ( $ text , "\xF0" ) === false ) { return ; } preg_match_all ( $ this -> unicodeRegexp , $ text , $ matches , PREG_OFFSET_CAPTURE ) ; foreach ( $ matches [ 0 ] as list ( $ emoji , $ tagPos ) ) { $ this -> addTag ( $ tagPos , strlen ( $ emoji ) , $ this -> getHexSequence ( $ emoji ) ) ; } }
Parse Unicode emoji in given text
44,014
public static function executeAttributePreprocessors ( Tag $ tag , array $ tagConfig ) { if ( empty ( $ tagConfig [ 'attributePreprocessors' ] ) ) { return ; } foreach ( $ tagConfig [ 'attributePreprocessors' ] as list ( $ attrName , $ regexp , $ map ) ) { if ( $ tag -> hasAttribute ( $ attrName ) ) { self :: executeAttributePreprocessor ( $ tag , $ attrName , $ regexp , $ map ) ; } } }
Execute all the attribute preprocessors of given tag
44,015
public static function filterAttributes ( Tag $ tag , array $ tagConfig , array $ registeredVars , Logger $ logger ) { $ attributes = [ ] ; foreach ( $ tagConfig [ 'attributes' ] as $ attrName => $ attrConfig ) { $ attrValue = false ; if ( $ tag -> hasAttribute ( $ attrName ) ) { $ vars = [ 'attrName' => $ attrName , 'attrValue' => $ tag -> getAttribute ( $ attrName ) , 'logger' => $ logger , 'registeredVars' => $ registeredVars ] ; $ attrValue = self :: executeAttributeFilterChain ( $ attrConfig [ 'filterChain' ] , $ vars ) ; } if ( $ attrValue !== false ) { $ attributes [ $ attrName ] = $ attrValue ; } elseif ( isset ( $ attrConfig [ 'defaultValue' ] ) ) { $ attributes [ $ attrName ] = $ attrConfig [ 'defaultValue' ] ; } elseif ( ! empty ( $ attrConfig [ 'required' ] ) ) { $ tag -> invalidate ( ) ; } } $ tag -> setAttributes ( $ attributes ) ; }
Filter the attributes of given tag
44,016
public static function filterTag ( Tag $ tag , Parser $ parser , array $ tagsConfig , array $ openTags ) { $ tagName = $ tag -> getName ( ) ; $ tagConfig = $ tagsConfig [ $ tagName ] ; $ logger = $ parser -> getLogger ( ) ; $ logger -> setTag ( $ tag ) ; $ vars = [ 'logger' => $ logger , 'openTags' => $ openTags , 'parser' => $ parser , 'registeredVars' => $ parser -> registeredVars , 'tag' => $ tag , 'tagConfig' => $ tagConfig , 'text' => $ parser -> getText ( ) ] ; foreach ( $ tagConfig [ 'filterChain' ] as $ filter ) { if ( $ tag -> isInvalid ( ) ) { break ; } self :: executeFilter ( $ filter , $ vars ) ; } $ logger -> unsetTag ( ) ; }
Execute a tag s filterChain
44,017
protected static function executeAttributeFilterChain ( array $ filterChain , array $ vars ) { $ vars [ 'logger' ] -> setAttribute ( $ vars [ 'attrName' ] ) ; foreach ( $ filterChain as $ filter ) { $ vars [ 'attrValue' ] = self :: executeFilter ( $ filter , $ vars ) ; if ( $ vars [ 'attrValue' ] === false ) { break ; } } $ vars [ 'logger' ] -> unsetAttribute ( ) ; return $ vars [ 'attrValue' ] ; }
Execute an attribute s filterChain
44,018
protected static function executeAttributePreprocessor ( Tag $ tag , $ attrName , $ regexp , $ map ) { $ attrValue = $ tag -> getAttribute ( $ attrName ) ; $ captures = self :: getNamedCaptures ( $ attrValue , $ regexp , $ map ) ; foreach ( $ captures as $ k => $ v ) { if ( $ k === $ attrName || ! $ tag -> hasAttribute ( $ k ) ) { $ tag -> setAttribute ( $ k , $ v ) ; } } }
Execute an attribute preprocessor
44,019
protected static function executeFilter ( array $ filter , array $ vars ) { $ vars += [ 'registeredVars' => [ ] ] ; $ vars += $ vars [ 'registeredVars' ] ; $ args = [ ] ; if ( isset ( $ filter [ 'params' ] ) ) { foreach ( $ filter [ 'params' ] as $ k => $ v ) { $ args [ ] = ( isset ( $ vars [ $ k ] ) ) ? $ vars [ $ k ] : $ v ; } } return call_user_func_array ( $ filter [ 'callback' ] , $ args ) ; }
Execute a filter
44,020
protected static function getNamedCaptures ( $ str , $ regexp , $ map ) { if ( ! preg_match ( $ regexp , $ str , $ m ) ) { return [ ] ; } $ values = [ ] ; foreach ( $ map as $ i => $ k ) { if ( isset ( $ m [ $ i ] ) && $ m [ $ i ] !== '' ) { $ values [ $ k ] = $ m [ $ i ] ; } } return $ values ; }
Execute a regexp and return the values of the mapped captures
44,021
public function __isset ( $ propName ) { $ methodName = 'isset' . ucfirst ( $ propName ) ; if ( method_exists ( $ this , $ methodName ) ) { return $ this -> $ methodName ( ) ; } return isset ( $ this -> $ propName ) ; }
Test whether a property is set
44,022
protected function isControlStructure ( ) { return in_array ( $ this -> tokens [ $ this -> i ] [ 0 ] , [ T_ELSE , T_ELSEIF , T_FOR , T_FOREACH , T_IF , T_WHILE ] , true ) ; }
Test whether the token at current index is a control structure
44,023
protected function optimizeTokens ( ) { while ( ++ $ this -> i < $ this -> cnt ) { if ( $ this -> tokens [ $ this -> i ] === ';' ) { ++ $ this -> context [ 'statements' ] ; } elseif ( $ this -> tokens [ $ this -> i ] === '{' ) { ++ $ this -> braces ; } elseif ( $ this -> tokens [ $ this -> i ] === '}' ) { if ( $ this -> context [ 'braces' ] === $ this -> braces ) { $ this -> processEndOfBlock ( ) ; } -- $ this -> braces ; } elseif ( $ this -> isControlStructure ( ) ) { $ this -> processControlStructure ( ) ; } } }
Optimize control structures in stored tokens
44,024
protected function processControlStructure ( ) { $ savedIndex = $ this -> i ; if ( ! in_array ( $ this -> tokens [ $ this -> i ] [ 0 ] , [ T_ELSE , T_ELSEIF ] , true ) ) { ++ $ this -> context [ 'statements' ] ; } if ( $ this -> tokens [ $ this -> i ] [ 0 ] !== T_ELSE ) { $ this -> skipCondition ( ) ; } $ this -> skipWhitespace ( ) ; if ( $ this -> tokens [ $ this -> i ] !== '{' ) { $ this -> i = $ savedIndex ; return ; } ++ $ this -> braces ; $ replacement = [ T_WHITESPACE , '' ] ; if ( $ this -> tokens [ $ savedIndex ] [ 0 ] === T_ELSE && $ this -> tokens [ $ this -> i + 1 ] [ 0 ] !== T_VARIABLE && $ this -> tokens [ $ this -> i + 1 ] [ 0 ] !== T_WHITESPACE ) { $ replacement = [ T_WHITESPACE , ' ' ] ; } $ this -> context [ 'lastBlock' ] = $ this -> tokens [ $ savedIndex ] [ 0 ] ; $ this -> context = [ 'braces' => $ this -> braces , 'index' => $ this -> i , 'lastBlock' => null , 'parent' => $ this -> context , 'replacement' => $ replacement , 'savedIndex' => $ savedIndex , 'statements' => 0 ] ; }
Process the control structure starting at current index
44,025
protected function processEndOfBlock ( ) { if ( $ this -> context [ 'statements' ] < 2 && ! $ this -> mustPreserveBraces ( ) ) { $ this -> removeBracesInCurrentContext ( ) ; } $ this -> context = $ this -> context [ 'parent' ] ; $ this -> context [ 'parent' ] [ 'lastBlock' ] = $ this -> context [ 'lastBlock' ] ; }
Process the block ending at current index
44,026
protected function removeBracesInCurrentContext ( ) { $ this -> tokens [ $ this -> context [ 'index' ] ] = $ this -> context [ 'replacement' ] ; $ this -> tokens [ $ this -> i ] = ( $ this -> context [ 'statements' ] ) ? [ T_WHITESPACE , '' ] : ';' ; foreach ( [ $ this -> context [ 'index' ] - 1 , $ this -> i - 1 ] as $ tokenIndex ) { if ( $ this -> tokens [ $ tokenIndex ] [ 0 ] === T_WHITESPACE ) { $ this -> tokens [ $ tokenIndex ] [ 1 ] = '' ; } } if ( $ this -> tokens [ $ this -> context [ 'savedIndex' ] ] [ 0 ] === T_ELSE ) { $ j = 1 + $ this -> context [ 'savedIndex' ] ; while ( $ this -> tokens [ $ j ] [ 0 ] === T_WHITESPACE || $ this -> tokens [ $ j ] [ 0 ] === T_COMMENT || $ this -> tokens [ $ j ] [ 0 ] === T_DOC_COMMENT ) { ++ $ j ; } if ( $ this -> tokens [ $ j ] [ 0 ] === T_IF ) { $ this -> tokens [ $ j ] = [ T_ELSEIF , 'elseif' ] ; $ j = $ this -> context [ 'savedIndex' ] ; $ this -> tokens [ $ j ] = [ T_WHITESPACE , '' ] ; if ( $ this -> tokens [ $ j - 1 ] [ 0 ] === T_WHITESPACE ) { $ this -> tokens [ $ j - 1 ] [ 1 ] = '' ; } $ this -> unindentBlock ( $ j , $ this -> i - 1 ) ; $ this -> tokens [ $ this -> context [ 'index' ] ] = [ T_WHITESPACE , '' ] ; } } $ this -> changed = true ; }
Remove the braces surrounding current context
44,027
protected function skipCondition ( ) { $ this -> skipToString ( '(' ) ; $ parens = 0 ; while ( ++ $ this -> i < $ this -> cnt ) { if ( $ this -> tokens [ $ this -> i ] === ')' ) { if ( $ parens ) { -- $ parens ; } else { break ; } } elseif ( $ this -> tokens [ $ this -> i ] === '(' ) { ++ $ parens ; } } }
Skip the condition of a control structure
44,028
public function normalizeValue ( $ value ) { if ( $ value instanceof AbstractNormalization ) { return $ value ; } if ( is_callable ( $ value ) ) { return new Custom ( $ value ) ; } $ className = 's9e\\TextFormatter\\Configurator\\TemplateNormalizations\\' . $ value ; return new $ className ; }
Normalize the value to an instance of AbstractNormalization
44,029
protected function assessSafeness ( array $ map ) { $ values = implode ( '' , $ map ) ; $ isSafeInCSS = true ; foreach ( ContextSafeness :: getDisallowedCharactersInCSS ( ) as $ char ) { if ( strpos ( $ values , $ char ) !== false ) { $ isSafeInCSS = false ; break ; } } if ( $ isSafeInCSS ) { $ this -> markAsSafeInCSS ( ) ; } $ isSafeInJS = true ; foreach ( ContextSafeness :: getDisallowedCharactersInJS ( ) as $ char ) { if ( strpos ( $ values , $ char ) !== false ) { $ isSafeInJS = false ; break ; } } if ( $ isSafeInJS ) { $ this -> markAsSafeInJS ( ) ; } }
Assess the safeness of given map in contexts
44,030
public function aliasAttribute ( $ elName , $ attrName , $ alias ) { $ elName = $ this -> normalizeElementName ( $ elName ) ; $ attrName = $ this -> normalizeAttributeName ( $ attrName ) ; $ this -> aliases [ $ elName ] [ $ attrName ] = AttributeName :: normalize ( $ alias ) ; }
Alias the HTML attribute of given HTML element to a given attribute name
44,031
public function aliasElement ( $ elName , $ tagName ) { $ elName = $ this -> normalizeElementName ( $ elName ) ; $ this -> aliases [ $ elName ] [ '' ] = TagName :: normalize ( $ tagName ) ; }
Alias an HTML element to a given tag name
44,032
protected function rebuildTemplate ( Tag $ tag , $ elName , $ allowUnsafe ) { $ template = '<' . $ elName . '>' ; foreach ( $ tag -> attributes as $ attrName => $ attribute ) { $ template .= '<xsl:copy-of select="@' . $ attrName . '"/>' ; } $ template .= '<xsl:apply-templates/></' . $ elName . '>' ; if ( $ allowUnsafe ) { $ template = new UnsafeTemplate ( $ template ) ; } $ tag -> setTemplate ( $ template ) ; }
Rebuild a tag s template
44,033
public function asConfig ( ) { if ( empty ( $ this -> elements ) && empty ( $ this -> aliases ) ) { return ; } $ attrRegexp = '[a-z][-a-z0-9]*(?>\\s*=\\s*(?>"[^"]*"|\'[^\']*\'|[^\\s"\'=<>`]+))?' ; $ tagRegexp = RegexpBuilder :: fromList ( array_merge ( array_keys ( $ this -> aliases ) , array_keys ( $ this -> elements ) ) ) ; $ endTagRegexp = '/(' . $ tagRegexp . ')' ; $ startTagRegexp = '(' . $ tagRegexp . ')((?>\\s+' . $ attrRegexp . ')*+)\\s*/?' ; $ regexp = '#<(?>' . $ endTagRegexp . '|' . $ startTagRegexp . ')\\s*>#i' ; $ config = [ 'quickMatch' => $ this -> quickMatch , 'prefix' => $ this -> prefix , 'regexp' => $ regexp ] ; if ( ! empty ( $ this -> aliases ) ) { $ config [ 'aliases' ] = new Dictionary ; foreach ( $ this -> aliases as $ elName => $ aliases ) { $ config [ 'aliases' ] [ $ elName ] = new Dictionary ( $ aliases ) ; } } return $ config ; }
Generate this plugin s config
44,034
protected function inlineInferredValue ( DOMNode $ node , $ expr , $ value ) { $ query = './/xsl:value-of[@select="' . $ expr . '"]' ; foreach ( $ this -> xpath ( $ query , $ node ) as $ valueOf ) { $ this -> replaceValueOf ( $ valueOf , $ value ) ; } $ query = './/*[namespace-uri() != $XSL]/@*[contains(., "{' . $ expr . '}")]' ; foreach ( $ this -> xpath ( $ query , $ node ) as $ attribute ) { $ this -> replaceAttribute ( $ attribute , $ expr , $ value ) ; } }
Replace the inferred value in given node and its descendants
44,035
protected function replaceAttribute ( DOMAttr $ attribute , $ expr , $ value ) { AVTHelper :: replace ( $ attribute , function ( $ token ) use ( $ expr , $ value ) { if ( $ token [ 0 ] === 'expression' && $ token [ 1 ] === $ expr ) { $ token = [ 'literal' , $ value ] ; } return $ token ; } ) ; }
Replace an expression with a literal value in given attribute
44,036
protected function evaluate ( $ expr ) { $ useErrors = libxml_use_internal_errors ( true ) ; $ result = $ this -> xpath -> evaluate ( $ expr ) ; libxml_use_internal_errors ( $ useErrors ) ; return $ result ; }
Evaluate given expression without raising any warnings
44,037
protected function foldConstantXPathExpression ( array $ m ) { $ expr = $ m [ 0 ] ; if ( $ this -> isConstantExpression ( $ expr ) ) { $ result = $ this -> evaluate ( $ expr ) ; if ( $ this -> canBeSerialized ( $ result ) ) { $ foldedExpr = XPath :: export ( $ result ) ; if ( strlen ( $ foldedExpr ) < strlen ( $ expr ) ) { $ expr = $ foldedExpr ; } } } return $ expr ; }
Evaluate and replace a constant XPath expression
44,038
protected function isConstantExpression ( $ expr ) { $ expr = preg_replace ( '("[^"]*"|\'[^\']*\')' , '0' , $ expr ) ; preg_match_all ( '(\\w[-\\w]+(?=\\())' , $ expr , $ m ) ; if ( count ( array_diff ( $ m [ 0 ] , $ this -> supportedFunctions ) ) > 0 ) { return false ; } return ! preg_match ( '([^\\s\\-0-9a-z\\(-.]|\\.(?![0-9])|\\b[-a-z](?![-\\w]+\\()|\\(\\s*\\))i' , $ expr ) ; }
Test whether given expression seems to be constant
44,039
public function replaceCallbacks ( array $ config ) { foreach ( $ this -> callbacks as $ path => $ params ) { $ config = $ this -> mapArray ( $ config , explode ( '.' , $ path ) , $ params ) ; } return $ config ; }
Replace all callbacks in given config
44,040
protected function buildCallbackArguments ( array $ params , array $ localVars ) { unset ( $ params [ 'parser' ] ) ; $ localVars += [ 'logger' => 1 , 'openTags' => 1 , 'registeredVars' => 1 , 'text' => 1 ] ; $ args = [ ] ; foreach ( $ params as $ k => $ v ) { if ( isset ( $ v ) ) { $ args [ ] = $ this -> encoder -> encode ( $ v ) ; } elseif ( isset ( $ localVars [ $ k ] ) ) { $ args [ ] = $ k ; } else { $ args [ ] = 'registeredVars[' . json_encode ( $ k ) . ']' ; } } return implode ( ',' , $ args ) ; }
Build the list of arguments used in a callback invocation
44,041
protected function generateFunction ( array $ config , array $ params ) { if ( $ config [ 'js' ] == 'returnFalse' || $ config [ 'js' ] == 'returnTrue' ) { return new Code ( ( string ) $ config [ 'js' ] ) ; } $ config += [ 'params' => [ ] ] ; $ src = $ this -> getHeader ( $ params ) ; $ src .= 'function(' . implode ( ',' , array_keys ( $ params ) ) . '){' ; $ src .= 'return ' . $ this -> parenthesizeCallback ( $ config [ 'js' ] ) ; $ src .= '(' . $ this -> buildCallbackArguments ( $ config [ 'params' ] , $ params ) . ');}' ; return new Code ( $ src ) ; }
Generate a function from a callback config
44,042
protected function getHeader ( array $ params ) { $ header = "/**\n" ; foreach ( $ params as $ paramName => $ paramType ) { $ header .= '* @param {' . $ paramType . '} ' . $ paramName . "\n" ; } $ header .= "*/\n" ; return $ header ; }
Generate a function header for given signature
44,043
protected function mapArray ( array $ array , array $ path , array $ params ) { $ key = array_shift ( $ path ) ; $ keys = ( $ key === '*' ) ? array_keys ( $ array ) : [ $ key ] ; foreach ( $ keys as $ key ) { if ( ! isset ( $ array [ $ key ] ) ) { continue ; } $ array [ $ key ] = ( empty ( $ path ) ) ? $ this -> generateFunction ( $ array [ $ key ] , $ params ) : $ this -> mapArray ( $ array [ $ key ] , $ path , $ params ) ; } return $ array ; }
Replace callbacks in given config array
44,044
public function censorHtml ( $ html , $ censorAttributes = false ) { $ attributesExpr = '' ; if ( $ censorAttributes ) { $ attributesExpr = '|[^<">]*+(?="(?> [-\\w]+="[^"]*+")*+\\/?>)' ; } $ delim = $ this -> regexpHtml [ 0 ] ; $ pos = strrpos ( $ this -> regexpHtml , $ delim ) ; $ regexp = $ delim . '(?<!&|&#)' . substr ( $ this -> regexpHtml , 1 , $ pos - 1 ) . '(?=[^<>]*+(?=<|$)' . $ attributesExpr . ')' . substr ( $ this -> regexpHtml , $ pos ) ; return preg_replace_callback ( $ regexp , function ( $ m ) { return htmlspecialchars ( $ this -> getReplacement ( html_entity_decode ( $ m [ 0 ] , ENT_QUOTES , 'UTF-8' ) ) , ENT_QUOTES ) ; } , $ html ) ; }
Censor text nodes inside of HTML code
44,045
public function censorText ( $ text ) { return preg_replace_callback ( $ this -> regexp , function ( $ m ) { return $ this -> getReplacement ( $ m [ 0 ] ) ; } , $ text ) ; }
Censor given plain text
44,046
protected function getReplacement ( $ word ) { if ( $ this -> isAllowed ( $ word ) ) { return $ word ; } foreach ( $ this -> replacements as list ( $ regexp , $ replacement ) ) { if ( preg_match ( $ regexp , $ word ) ) { return $ replacement ; } } return $ this -> defaultReplacement ; }
Get the replacement for given word
44,047
public function getParser ( array $ config = null ) { $ this -> configOptimizer -> reset ( ) ; $ xslt = new XSLT ; $ xslt -> optimizer -> normalizer -> remove ( 'RemoveLivePreviewAttributes' ) ; $ this -> xsl = $ xslt -> getXSL ( $ this -> configurator -> rendering ) ; $ this -> config = ( isset ( $ config ) ) ? $ config : $ this -> configurator -> asConfig ( ) ; $ this -> config = ConfigHelper :: filterConfig ( $ this -> config , 'JS' ) ; $ this -> config = $ this -> callbackGenerator -> replaceCallbacks ( $ this -> config ) ; $ src = $ this -> getHints ( ) . $ this -> injectConfig ( $ this -> getSource ( ) ) ; $ src .= "if (!window['s9e']) window['s9e'] = {};\n" . $ this -> getExports ( ) ; $ src = $ this -> getMinifier ( ) -> get ( $ src ) ; $ src = '(function(){' . $ src . '})()' ; return $ src ; }
Get a JavaScript parser
44,048
public function setMinifier ( $ minifier ) { if ( is_string ( $ minifier ) ) { $ className = __NAMESPACE__ . '\\JavaScript\\Minifiers\\' . $ minifier ; $ args = array_slice ( func_get_args ( ) , 1 ) ; if ( ! empty ( $ args ) ) { $ reflection = new ReflectionClass ( $ className ) ; $ minifier = $ reflection -> newInstanceArgs ( $ args ) ; } else { $ minifier = new $ className ; } } $ this -> minifier = $ minifier ; return $ minifier ; }
Set the cached instance of Minifier
44,049
protected function getExports ( ) { if ( empty ( $ this -> exports ) ) { return '' ; } $ exports = [ ] ; foreach ( $ this -> exports as $ export ) { $ exports [ ] = "'" . $ export . "':" . $ export ; } sort ( $ exports ) ; return "window['s9e']['TextFormatter'] = {" . implode ( ',' , $ exports ) . '}' ; }
Generate and return the public API
44,050
protected function getPluginsConfig ( ) { $ plugins = new Dictionary ; foreach ( $ this -> config [ 'plugins' ] as $ pluginName => $ pluginConfig ) { if ( ! isset ( $ pluginConfig [ 'js' ] ) ) { continue ; } $ js = $ pluginConfig [ 'js' ] ; unset ( $ pluginConfig [ 'js' ] ) ; unset ( $ pluginConfig [ 'className' ] ) ; if ( isset ( $ pluginConfig [ 'quickMatch' ] ) ) { $ valid = [ '[[:ascii:]]' , '[\\xC0-\\xDF][\\x80-\\xBF]' , '[\\xE0-\\xEF][\\x80-\\xBF]{2}' , '[\\xF0-\\xF7][\\x80-\\xBF]{3}' ] ; $ regexp = '#(?>' . implode ( '|' , $ valid ) . ')+#' ; if ( preg_match ( $ regexp , $ pluginConfig [ 'quickMatch' ] , $ m ) ) { $ pluginConfig [ 'quickMatch' ] = $ m [ 0 ] ; } else { unset ( $ pluginConfig [ 'quickMatch' ] ) ; } } $ globalKeys = [ 'quickMatch' => 1 , 'regexp' => 1 , 'regexpLimit' => 1 ] ; $ globalConfig = array_intersect_key ( $ pluginConfig , $ globalKeys ) ; $ localConfig = array_diff_key ( $ pluginConfig , $ globalKeys ) ; if ( isset ( $ globalConfig [ 'regexp' ] ) && ! ( $ globalConfig [ 'regexp' ] instanceof Code ) ) { $ globalConfig [ 'regexp' ] = new Code ( RegexpConvertor :: toJS ( $ globalConfig [ 'regexp' ] , true ) ) ; } $ globalConfig [ 'parser' ] = new Code ( '/** * @param {!string} text * @param {!Array.<Array>} matches */ function(text, matches) { /** @const */ var config=' . $ this -> encode ( $ localConfig ) . '; ' . $ js . ' }' ) ; $ plugins [ $ pluginName ] = $ globalConfig ; } return $ plugins ; }
Return the plugins config
44,051
protected function getSource ( ) { $ rootDir = __DIR__ . '/..' ; $ src = '' ; $ logger = ( in_array ( 'getLogger' , $ this -> exports ) ) ? 'Logger.js' : 'NullLogger.js' ; $ files = glob ( $ rootDir . '/Parser/AttributeFilters/*.js' ) ; $ files [ ] = $ rootDir . '/Parser/utils.js' ; $ files [ ] = $ rootDir . '/Parser/FilterProcessing.js' ; $ files [ ] = $ rootDir . '/Parser/' . $ logger ; $ files [ ] = $ rootDir . '/Parser/Tag.js' ; $ files [ ] = $ rootDir . '/Parser.js' ; if ( in_array ( 'preview' , $ this -> exports , true ) ) { $ files [ ] = $ rootDir . '/render.js' ; $ src .= '/** @const */ var xsl=' . $ this -> getStylesheet ( ) . ";\n" ; } $ src .= implode ( "\n" , array_map ( 'file_get_contents' , $ files ) ) ; return $ src ; }
Return the parser s source
44,052
protected function getTagsConfig ( ) { $ tags = new Dictionary ; foreach ( $ this -> config [ 'tags' ] as $ tagName => $ tagConfig ) { if ( isset ( $ tagConfig [ 'attributes' ] ) ) { $ tagConfig [ 'attributes' ] = new Dictionary ( $ tagConfig [ 'attributes' ] ) ; } $ tags [ $ tagName ] = $ tagConfig ; } return $ tags ; }
Return the tags config
44,053
protected function injectConfig ( $ src ) { $ config = array_map ( [ $ this , 'encode' ] , $ this -> configOptimizer -> optimize ( [ 'plugins' => $ this -> getPluginsConfig ( ) , 'registeredVars' => $ this -> getRegisteredVarsConfig ( ) , 'rootContext' => $ this -> getRootContext ( ) , 'tagsConfig' => $ this -> getTagsConfig ( ) ] ) ) ; $ src = preg_replace_callback ( '/(\\nvar (' . implode ( '|' , array_keys ( $ config ) ) . '))(;)/' , function ( $ m ) use ( $ config ) { return $ m [ 1 ] . '=' . $ config [ $ m [ 2 ] ] . $ m [ 3 ] ; } , $ src ) ; $ src = $ this -> configOptimizer -> getVarDeclarations ( ) . $ src ; return $ src ; }
Inject the parser config into given source
44,054
public function getTemplate ( array $ config ) { foreach ( $ this -> templateGenerators as $ type => $ generator ) { if ( isset ( $ config [ $ type ] ) ) { return $ generator -> getTemplate ( $ config [ $ type ] ) ; } } return '' ; }
Generate and return a template based on given config
44,055
protected function addSiteId ( $ siteId , $ template ) { $ dom = TemplateLoader :: load ( $ template ) ; $ xpath = new DOMXPath ( $ dom ) ; $ query = '//*[namespace-uri() != "' . TemplateLoader :: XMLNS_XSL . '"]' . '[not(ancestor::*[namespace-uri() != "' . TemplateLoader :: XMLNS_XSL . '"])]' ; foreach ( $ xpath -> query ( $ query ) as $ element ) { $ element -> setAttribute ( 'data-s9e-mediaembed' , $ siteId ) ; } return TemplateLoader :: save ( $ dom ) ; }
Added the siteId value to given template in a data - s9e - mediaembed attribute
44,056
public function check ( DOMElement $ template , Tag $ tag ) { foreach ( $ this -> getNodes ( $ template ) as $ node ) { $ this -> checkNode ( $ node , $ tag ) ; } }
Look for improperly - filtered dynamic content
44,057
protected function checkAttribute ( DOMNode $ node , Tag $ tag , $ attrName ) { if ( ! isset ( $ tag -> attributes [ $ attrName ] ) ) { if ( $ this -> ignoreUnknownAttributes ) { return ; } throw new UnsafeTemplateException ( "Cannot assess the safety of unknown attribute '" . $ attrName . "'" , $ node ) ; } if ( ! $ this -> tagFiltersAttributes ( $ tag ) || ! $ this -> isSafe ( $ tag -> attributes [ $ attrName ] ) ) { throw new UnsafeTemplateException ( "Attribute '" . $ attrName . "' is not properly sanitized to be used in this context" , $ node ) ; } }
Test whether a tag attribute is safe
44,058
protected function checkAttributeExpression ( DOMNode $ node , Tag $ tag , $ expr ) { preg_match_all ( '(@([-\\w]+))' , $ expr , $ matches ) ; foreach ( $ matches [ 1 ] as $ attrName ) { $ this -> checkAttribute ( $ node , $ tag , $ attrName ) ; } }
Test whether an attribute expression is safe
44,059
protected function checkAttributeNode ( DOMAttr $ attribute , Tag $ tag ) { foreach ( AVTHelper :: parse ( $ attribute -> value ) as $ token ) { if ( $ token [ 0 ] === 'expression' ) { $ this -> checkExpression ( $ attribute , $ token [ 1 ] , $ tag ) ; } } }
Test whether an attribute node is safe
44,060
protected function checkContext ( DOMNode $ node ) { $ xpath = new DOMXPath ( $ node -> ownerDocument ) ; $ ancestors = $ xpath -> query ( 'ancestor::xsl:for-each' , $ node ) ; if ( $ ancestors -> length ) { throw new UnsafeTemplateException ( "Cannot assess context due to '" . $ ancestors -> item ( 0 ) -> nodeName . "'" , $ node ) ; } }
Test whether a node s context can be safely assessed
44,061
protected function checkElementNode ( DOMElement $ element , Tag $ tag ) { $ xpath = new DOMXPath ( $ element -> ownerDocument ) ; $ predicate = ( $ element -> localName === 'attribute' ) ? '' : '[not(ancestor::xsl:attribute)]' ; $ query = './/xsl:value-of' . $ predicate ; foreach ( $ xpath -> query ( $ query , $ element ) as $ valueOf ) { $ this -> checkSelectNode ( $ valueOf -> getAttributeNode ( 'select' ) , $ tag ) ; } $ query = './/xsl:apply-templates' . $ predicate ; foreach ( $ xpath -> query ( $ query , $ element ) as $ applyTemplates ) { throw new UnsafeTemplateException ( 'Cannot allow unfiltered data in this context' , $ applyTemplates ) ; } }
Test whether an element node is safe
44,062
protected function checkExpression ( DOMNode $ node , $ expr , Tag $ tag ) { $ this -> checkContext ( $ node ) ; if ( preg_match ( '/^\\$(\\w+)$/' , $ expr , $ m ) ) { $ this -> checkVariable ( $ node , $ tag , $ m [ 1 ] ) ; } elseif ( preg_match ( '/^@[-\\w]+(?:\\s*\\|\\s*@[-\\w]+)*$/' , $ expr ) ) { $ this -> checkAttributeExpression ( $ node , $ tag , $ expr ) ; } elseif ( ! $ this -> isExpressionSafe ( $ expr ) ) { throw new UnsafeTemplateException ( "Cannot assess the safety of expression '" . $ expr . "'" , $ node ) ; } }
Test the safety of an XPath expression
44,063
protected function checkNode ( DOMNode $ node , Tag $ tag ) { if ( $ node instanceof DOMAttr ) { $ this -> checkAttributeNode ( $ node , $ tag ) ; } elseif ( $ node instanceof DOMElement ) { if ( $ node -> namespaceURI === self :: XMLNS_XSL && $ node -> localName === 'copy-of' ) { $ this -> checkCopyOfNode ( $ node , $ tag ) ; } else { $ this -> checkElementNode ( $ node , $ tag ) ; } } }
Test whether a node is safe
44,064
protected function checkVariable ( DOMNode $ node , $ tag , $ qname ) { $ this -> checkVariableDeclaration ( $ node , $ tag , 'xsl:param[@name="' . $ qname . '"]' ) ; $ this -> checkVariableDeclaration ( $ node , $ tag , 'xsl:variable[@name="' . $ qname . '"]' ) ; }
Check whether a variable is safe in context
44,065
protected function checkVariableDeclaration ( DOMNode $ node , $ tag , $ query ) { $ query = 'ancestor-or-self::*/preceding-sibling::' . $ query . '[@select]' ; $ xpath = new DOMXPath ( $ node -> ownerDocument ) ; foreach ( $ xpath -> query ( $ query , $ node ) as $ varNode ) { try { $ this -> checkExpression ( $ varNode , $ varNode -> getAttribute ( 'select' ) , $ tag ) ; } catch ( UnsafeTemplateException $ e ) { $ e -> setNode ( $ node ) ; throw $ e ; } } }
Check whether a variable declaration is safe in context
44,066
protected function checkSelectNode ( DOMAttr $ select , Tag $ tag ) { $ this -> checkExpression ( $ select , $ select -> value , $ tag ) ; }
Test whether a select attribute of a node is safe
44,067
public function checkTag ( Tag $ tag ) { if ( isset ( $ tag -> template ) && ! ( $ tag -> template instanceof UnsafeTemplate ) ) { $ template = ( string ) $ tag -> template ; $ this -> checkTemplate ( $ template , $ tag ) ; } }
Check a given tag s templates for disallowed content
44,068
public function checkTemplate ( $ template , Tag $ tag = null ) { if ( $ this -> disabled ) { return ; } if ( ! isset ( $ tag ) ) { $ tag = new Tag ; } $ dom = TemplateLoader :: load ( $ template ) ; foreach ( $ this -> collection as $ check ) { $ check -> check ( $ dom -> documentElement , $ tag ) ; } }
Check a given template for disallowed content
44,069
public function optimize ( DOMDocument $ ir ) { $ this -> createXPath ( $ ir ) ; $ xml = $ ir -> saveXML ( ) ; $ remainingLoops = 10 ; do { $ old = $ xml ; $ this -> optimizeCloseTagElements ( $ ir ) ; $ xml = $ ir -> saveXML ( ) ; } while ( -- $ remainingLoops > 0 && $ xml !== $ old ) ; $ this -> removeCloseTagSiblings ( $ ir ) ; $ this -> removeContentFromVoidElements ( $ ir ) ; $ this -> mergeConsecutiveLiteralOutputElements ( $ ir ) ; $ this -> removeEmptyDefaultCases ( $ ir ) ; }
Optimize an IR
44,070
protected function cloneCloseTagElementsIntoSwitch ( DOMDocument $ ir ) { $ query = '//switch[name(following-sibling::*[1]) = "closeTag"]' ; foreach ( $ this -> query ( $ query ) as $ switch ) { $ closeTag = $ switch -> nextSibling ; foreach ( $ this -> query ( 'case' , $ switch ) as $ case ) { if ( ! $ case -> lastChild || $ case -> lastChild -> nodeName !== 'closeTag' ) { $ case -> appendChild ( $ closeTag -> cloneNode ( ) ) ; } } } }
Clone closeTag elements that follow a switch into said switch
44,071
protected function cloneCloseTagElementsOutOfSwitch ( DOMDocument $ ir ) { $ query = '//switch[case/closeTag][not(case[name(*[1]) != "closeTag"])]' ; foreach ( $ this -> query ( $ query ) as $ switch ) { $ case = $ this -> query ( 'case/closeTag' , $ switch ) -> item ( 0 ) ; $ switch -> parentNode -> insertBefore ( $ case -> cloneNode ( ) , $ switch ) ; } }
Clone closeTag elements from the head of a switch s cases before said switch
44,072
protected function mergeConsecutiveLiteralOutputElements ( DOMDocument $ ir ) { foreach ( $ this -> query ( '//output[@type="literal"]' ) as $ output ) { $ disableOutputEscaping = $ output -> getAttribute ( 'disable-output-escaping' ) ; while ( $ this -> nextSiblingIsLiteralOutput ( $ output , $ disableOutputEscaping ) ) { $ output -> nodeValue = htmlspecialchars ( $ output -> nodeValue . $ output -> nextSibling -> nodeValue ) ; $ output -> parentNode -> removeChild ( $ output -> nextSibling ) ; } } }
Merge consecutive literal outputs
44,073
protected function nextSiblingIsLiteralOutput ( DOMElement $ node , $ disableOutputEscaping ) { return isset ( $ node -> nextSibling ) && $ node -> nextSibling -> nodeName === 'output' && $ node -> nextSibling -> getAttribute ( 'type' ) === 'literal' && $ node -> nextSibling -> getAttribute ( 'disable-output-escaping' ) === $ disableOutputEscaping ; }
Test whether the next sibling of an element is a literal output element with matching escaping
44,074
protected function optimizeCloseTagElements ( DOMDocument $ ir ) { $ this -> cloneCloseTagElementsIntoSwitch ( $ ir ) ; $ this -> cloneCloseTagElementsOutOfSwitch ( $ ir ) ; $ this -> removeRedundantCloseTagElementsInSwitch ( $ ir ) ; $ this -> removeRedundantCloseTagElements ( $ ir ) ; }
Optimize closeTags elements
44,075
protected function removeContentFromVoidElements ( DOMDocument $ ir ) { foreach ( $ this -> query ( '//element[@void="yes"]' ) as $ element ) { $ id = $ element -> getAttribute ( 'id' ) ; $ query = './/closeTag[@id="' . $ id . '"]/following-sibling::*' ; $ this -> removeNodes ( $ ir , $ query , $ element ) ; } }
Remove content from void elements
44,076
protected function removeNodes ( DOMDocument $ ir , $ query , DOMNode $ contextNode = null ) { foreach ( $ this -> query ( $ query , $ contextNode ) as $ node ) { if ( $ node -> parentNode instanceof DOMElement ) { $ node -> parentNode -> removeChild ( $ node ) ; } } }
Remove all nodes that match given XPath query
44,077
public function getJS ( ) { if ( ! isset ( $ this -> jsRegexp ) ) { $ this -> jsRegexp = RegexpConvertor :: toJS ( $ this -> regexp , $ this -> isGlobal ) ; } return $ this -> jsRegexp ; }
Return this regexp s JavaScript representation
44,078
public function getNamedCaptures ( ) { $ captures = [ ] ; $ regexpInfo = RegexpParser :: parse ( $ this -> regexp ) ; $ start = $ regexpInfo [ 'delimiter' ] . '^' ; $ end = '$' . $ regexpInfo [ 'delimiter' ] . $ regexpInfo [ 'modifiers' ] ; if ( strpos ( $ regexpInfo [ 'modifiers' ] , 'D' ) === false ) { $ end .= 'D' ; } foreach ( $ this -> getNamedCapturesExpressions ( $ regexpInfo [ 'tokens' ] ) as $ name => $ expr ) { $ captures [ $ name ] = $ start . $ expr . $ end ; } return $ captures ; }
Return all the named captures with a standalone regexp that matches them
44,079
protected function getNamedCapturesExpressions ( array $ tokens ) { $ exprs = [ ] ; foreach ( $ tokens as $ token ) { if ( $ token [ 'type' ] !== 'capturingSubpatternStart' || ! isset ( $ token [ 'name' ] ) ) { continue ; } $ expr = $ token [ 'content' ] ; if ( strpos ( $ expr , '|' ) !== false ) { $ expr = '(?:' . $ expr . ')' ; } $ exprs [ $ token [ 'name' ] ] = $ expr ; } return $ exprs ; }
Return the expression used in each named capture
44,080
public static function getAttributeValues ( $ xml , $ tagName , $ attrName ) { $ values = [ ] ; if ( strpos ( $ xml , '<' . $ tagName ) !== false ) { $ regexp = '(<' . preg_quote ( $ tagName ) . '(?= )[^>]*? ' . preg_quote ( $ attrName ) . '="([^"]*+))' ; preg_match_all ( $ regexp , $ xml , $ matches ) ; foreach ( $ matches [ 1 ] as $ value ) { $ values [ ] = html_entity_decode ( $ value , ENT_QUOTES , 'UTF-8' ) ; } } return $ values ; }
Return every value used in given attribute from given tag
44,081
public static function removeFormatting ( $ xml ) { $ dom = self :: loadXML ( $ xml ) ; $ xpath = new DOMXPath ( $ dom ) ; foreach ( $ xpath -> query ( '//e | //s' ) as $ node ) { $ node -> parentNode -> removeChild ( $ node ) ; } return $ dom -> documentElement -> textContent ; }
Strip the formatting of an intermediate representation and return plain text
44,082
public static function removeTag ( $ xml , $ tagName , $ nestingLevel = 0 ) { if ( strpos ( $ xml , '<' . $ tagName ) === false ) { return $ xml ; } $ dom = self :: loadXML ( $ xml ) ; $ xpath = new DOMXPath ( $ dom ) ; $ query = '//' . $ tagName . '[count(ancestor::' . $ tagName . ') >= ' . $ nestingLevel . ']' ; $ nodes = $ xpath -> query ( $ query ) ; foreach ( $ nodes as $ node ) { $ node -> parentNode -> removeChild ( $ node ) ; } return self :: saveXML ( $ dom ) ; }
Remove all tags at given nesting level
44,083
public static function replaceAttributes ( $ xml , $ tagName , callable $ callback ) { if ( strpos ( $ xml , '<' . $ tagName ) === false ) { return $ xml ; } return preg_replace_callback ( '((<' . preg_quote ( $ tagName ) . ')(?=[ />])[^>]*?(/?>))' , function ( $ m ) use ( $ callback ) { return $ m [ 1 ] . self :: serializeAttributes ( $ callback ( self :: parseAttributes ( $ m [ 0 ] ) ) ) . $ m [ 2 ] ; } , $ xml ) ; }
Replace the attributes of all tags of given name in given XML
44,084
protected static function encodeUnicodeSupplementaryCharactersCallback ( array $ m ) { $ utf8 = $ m [ 0 ] ; $ cp = ( ord ( $ utf8 [ 0 ] ) << 18 ) + ( ord ( $ utf8 [ 1 ] ) << 12 ) + ( ord ( $ utf8 [ 2 ] ) << 6 ) + ord ( $ utf8 [ 3 ] ) - 0x3C82080 ; return '&#' . $ cp . ';' ; }
Encode given Unicode character into an XML entity
44,085
protected static function parseAttributes ( $ xml ) { $ attributes = [ ] ; if ( strpos ( $ xml , '="' ) !== false ) { preg_match_all ( '(([^ =]++)="([^"]*))S' , $ xml , $ matches ) ; foreach ( $ matches [ 1 ] as $ i => $ attrName ) { $ attributes [ $ attrName ] = html_entity_decode ( $ matches [ 2 ] [ $ i ] , ENT_QUOTES , 'UTF-8' ) ; } } return $ attributes ; }
Parse the attributes contained in given XML
44,086
protected static function serializeAttributes ( array $ attributes ) { $ xml = '' ; ksort ( $ attributes ) ; foreach ( $ attributes as $ attrName => $ attrValue ) { $ xml .= ' ' . htmlspecialchars ( $ attrName , ENT_QUOTES ) . '="' . htmlspecialchars ( $ attrValue , ENT_COMPAT ) . '"' ; } $ xml = preg_replace ( '/\\r\\n?/' , "\n" , $ xml ) ; $ xml = preg_replace ( '/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]+/S' , '' , $ xml ) ; $ xml = str_replace ( "\n" , '&#10;' , $ xml ) ; return self :: encodeUnicodeSupplementaryCharacters ( $ xml ) ; }
Serialize an array of attribute values
44,087
public static function getCachingClient ( $ cacheDir = null ) { $ client = new Cached ( self :: getClient ( ) ) ; $ client -> cacheDir = ( isset ( $ cacheDir ) ) ? $ cacheDir : sys_get_temp_dir ( ) ; return $ client ; }
Instantiate and return a caching HTTP client
44,088
public function merge ( $ rules , $ overwrite = true ) { if ( ! is_array ( $ rules ) && ! ( $ rules instanceof self ) ) { throw new InvalidArgumentException ( 'merge() expects an array or an instance of Ruleset' ) ; } foreach ( $ rules as $ action => $ value ) { if ( is_array ( $ value ) ) { foreach ( $ value as $ tagName ) { $ this -> $ action ( $ tagName ) ; } } elseif ( $ overwrite || ! isset ( $ this -> items [ $ action ] ) ) { $ this -> $ action ( $ value ) ; } } }
Merge a set of rules into this collection
44,089
public function remove ( $ type , $ tagName = null ) { if ( preg_match ( '(^default(?:Child|Descendant)Rule)' , $ type ) ) { throw new InvalidArgumentException ( 'Cannot remove ' . $ type ) ; } if ( isset ( $ tagName ) ) { $ tagName = TagName :: normalize ( $ tagName ) ; if ( isset ( $ this -> items [ $ type ] ) ) { $ this -> items [ $ type ] = array_diff ( $ this -> items [ $ type ] , [ $ tagName ] ) ; if ( empty ( $ this -> items [ $ type ] ) ) { unset ( $ this -> items [ $ type ] ) ; } else { $ this -> items [ $ type ] = array_values ( $ this -> items [ $ type ] ) ; } } } else { unset ( $ this -> items [ $ type ] ) ; } }
Remove a specific rule or all the rules of a given type
44,090
protected function addBooleanRule ( $ ruleName , $ bool = true ) { if ( ! is_bool ( $ bool ) ) { throw new InvalidArgumentException ( $ ruleName . '() expects a boolean' ) ; } $ this -> items [ $ ruleName ] = $ bool ; }
Add a boolean rule
44,091
public static function normalize ( $ name ) { if ( ! static :: isValid ( $ name ) ) { throw new InvalidArgumentException ( "Invalid tag name '" . $ name . "'" ) ; } if ( strpos ( $ name , ':' ) === false ) { $ name = strtoupper ( $ name ) ; } return $ name ; }
Normalize a tag name
44,092
protected function getLabels ( ) { preg_match_all ( '/\\[((?:[^\\x17[\\]]|\\[[^\\x17[\\]]*\\])*)\\]/' , $ this -> text , $ matches , PREG_OFFSET_CAPTURE ) ; $ labels = [ ] ; foreach ( $ matches [ 1 ] as $ m ) { $ labels [ $ m [ 1 ] - 1 ] = strtolower ( $ m [ 0 ] ) ; } return $ labels ; }
Capture and return labels used in current text
44,093
protected function parseInlineLinks ( ) { preg_match_all ( '/\\[(?:[^\\x17[\\]]|\\[[^\\x17[\\]]*\\])*\\]\\(( *(?:[^\\x17\\s()]|\\([^\\x17\\s()]*\\))*(?=[ )]) *(?:"[^\\x17]*?"|\'[^\\x17]*?\'|\\([^\\x17)]*\\))? *)\\)/' , $ this -> text , $ matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER ) ; foreach ( $ matches as $ m ) { $ linkInfo = $ m [ 1 ] [ 0 ] ; $ startPos = $ m [ 0 ] [ 1 ] ; $ endLen = 3 + strlen ( $ linkInfo ) ; $ endPos = $ startPos + strlen ( $ m [ 0 ] [ 0 ] ) - $ endLen ; $ this -> addLinkTag ( $ startPos , $ endPos , $ endLen , $ linkInfo ) ; } }
Parse inline links markup
44,094
protected function parseReferenceLinks ( ) { $ labels = $ this -> getLabels ( ) ; foreach ( $ labels as $ startPos => $ id ) { $ labelPos = $ startPos + 2 + strlen ( $ id ) ; $ endPos = $ labelPos - 1 ; $ endLen = 1 ; if ( $ this -> text -> charAt ( $ labelPos ) === ' ' ) { ++ $ labelPos ; } if ( isset ( $ labels [ $ labelPos ] , $ this -> text -> linkReferences [ $ labels [ $ labelPos ] ] ) ) { $ id = $ labels [ $ labelPos ] ; $ endLen = $ labelPos + 2 + strlen ( $ id ) - $ endPos ; } if ( isset ( $ this -> text -> linkReferences [ $ id ] ) ) { $ this -> addLinkTag ( $ startPos , $ endPos , $ endLen , $ this -> text -> linkReferences [ $ id ] ) ; } } }
Parse reference links markup
44,095
protected function closeList ( array $ list , $ textBoundary ) { $ this -> parser -> addEndTag ( 'LIST' , $ textBoundary , 0 ) -> pairWith ( $ list [ 'listTag' ] ) ; $ this -> parser -> addEndTag ( 'LI' , $ textBoundary , 0 ) -> pairWith ( $ list [ 'itemTag' ] ) ; if ( $ list [ 'tight' ] ) { foreach ( $ list [ 'itemTags' ] as $ itemTag ) { $ itemTag -> removeFlags ( Rules :: RULE_CREATE_PARAGRAPHS ) ; } } }
Close a list at given offset
44,096
protected function computeQuoteIgnoreLen ( $ str , $ maxQuoteDepth ) { $ remaining = $ str ; while ( -- $ maxQuoteDepth >= 0 ) { $ remaining = preg_replace ( '/^ *> ?/' , '' , $ remaining ) ; } return strlen ( $ str ) - strlen ( $ remaining ) ; }
Compute the amount of text to ignore at the start of a quote line
44,097
protected function getAtxHeaderEndTagLen ( $ startPos , $ endPos ) { $ content = substr ( $ this -> text , $ startPos , $ endPos - $ startPos ) ; preg_match ( '/[ \\t]*#*[ \\t]*$/' , $ content , $ m ) ; return strlen ( $ m [ 0 ] ) ; }
Return the length of the markup at the end of an ATX header
44,098
protected function matchSetextLines ( ) { if ( $ this -> text -> indexOf ( '-' ) === false && $ this -> text -> indexOf ( '=' ) === false ) { return ; } $ regexp = '/^(?=[-=>])(?:> ?)*(?=[-=])(?:-+|=+) *$/m' ; if ( ! preg_match_all ( $ regexp , $ this -> text , $ matches , PREG_OFFSET_CAPTURE ) ) { return ; } foreach ( $ matches [ 0 ] as list ( $ match , $ matchPos ) ) { $ endPos = $ matchPos - 1 ; while ( $ endPos > 0 && $ this -> text -> charAt ( $ endPos - 1 ) === ' ' ) { -- $ endPos ; } $ this -> setextLines [ $ matchPos - 1 ] = [ 'endLen' => $ matchPos + strlen ( $ match ) - $ endPos , 'endPos' => $ endPos , 'quoteDepth' => substr_count ( $ match , '>' ) , 'tagName' => ( $ match [ 0 ] === '=' ) ? 'H1' : 'H2' ] ; } }
Capture and store lines that contain a Setext - tyle header
44,099
public function add ( $ key , $ value = null ) { if ( $ this -> exists ( $ key ) ) { if ( $ this -> onDuplicateAction === 'ignore' ) { return $ this -> get ( $ key ) ; } elseif ( $ this -> onDuplicateAction === 'error' ) { throw $ this -> getAlreadyExistsException ( $ key ) ; } } return $ this -> set ( $ key , $ value ) ; }
Add an item to this collection