Evaluate and replace a constant XPath expression

@param  array  $m
@return string
6206
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;
	}
923774
private function getNodesToExclude(\DOMXPath $xPath)
    {
        $excludedNodes = [];
        foreach (\array_keys($this->excludedSelectors) as $selectorToExclude) {
            try {
                $matchingNodes = $xPath->query($this->cssSelectorConverter->toXPath($selectorToExclude));
            } catch (SyntaxErrorException $e) {
                if ($this->debug) {
                    throw $e;
                }
                continue;
            }
            foreach ($matchingNodes as $node) {
                $excludedNodes[] = $node;
            }
        }

        return $excludedNodes;
    }
842802
public function evaluate($expr, DOMElement $node = null)
	{
		return $this->xpath->evaluate($expr, $node);
	}
660534
public function find($expression)
    {
        $xpath = new Dom\XPath($this);

        $xpath->registerNamespace("php", "http://php.net/xpath");
        $xpath->registerPhpFunctions();

        return $xpath->query($expression);
    }
862879
public static function escapeQuotes($xpathToEscape)
    {
        // Single quotes not present => we can quote in them
        if (mb_strpos($xpathToEscape, "'") === false) {
            return sprintf("'%s'", $xpathToEscape);
        }

        // Double quotes not present => we can quote in them
        if (mb_strpos($xpathToEscape, '"') === false) {
            return sprintf('"%s"', $xpathToEscape);
        }

        // Both single and double quotes are present
        return sprintf(
            "concat('%s')",
            str_replace("'", "', \"'\" ,'", $xpathToEscape)
        );
    }
57669
private function injectNsToXpathQuery($xpath, $ns)
    {
        $literals = array();
        $offset = 0;
        $keywords = array(
            '$$_AND_$$' => 'and',
            '$$_OR_$$' => 'or'
        );

        // identified escaped backslashes
        $extractor = function($m) use (&$literals, &$offset) {
            $placeholder = '$$_' . $offset . '_$$';
            $literals[$placeholder] = $m[0];
            $offset++;

            return $placeholder;
        };

        // Extract literals
        $modified = preg_replace_callback('~(\'|").*?\1~is', $extractor, $xpath);
        $modified = preg_replace_callback('~\b(and|or)\b~i', function($match) {
            return '$$_' . strtoupper(trim($match[1])) . '_$$';
        }, $modified);

        // Now find all unqualified names and prefix them with the namespace
        $modified = preg_replace('~(?<!@|:)\b[a-z][a-z0-9_-]*\b(?!:|\s*\()~i', $ns . ':$0', $modified);

        // re-insert keywords and literals
        $modified = strtr($modified, $keywords);
        $modified = strtr($modified, $literals);

        return $modified;
    }
739565
protected function getArrayForSpecialCase($xml)
    {
        $regEx            = '#\s*(&lt;\?xml.*interface&gt;)\s*#is';
        $regExReplace     = '#\s*>\s*(&lt;\?xml.*interface&gt;)\s*<[^>]+>\s*#is';
        $regExReplaceWith = '/>';

        // what can happen is that the valid XML element suddenly has,
        // as its element content, a full version of url-encoded XML.
        if ( ! preg_match($regEx, $xml)) {
            return [0 => $xml];
        }
        $xml = preg_replace($regExReplace, $regExReplaceWith, $xml);

        return $this->parse($xml);
    }
1021387
protected function build($m)
    {
        $string = $m[1];

        if (substr($string, 0, 1) != '<') {
            // We matched a lone ">" character.
            return '&gt;';
        } elseif (strlen($string) == 1) {
            // We matched a lone "<" character.
            return '&lt;';
        }

        if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
            // Seriously malformed.
            return '';
        }

        $slash = trim($matches[1]);
        $elem = &$matches[2];
        $attrlist = &$matches[3];
        $comment = &$matches[4];

        if ($comment) {
            $elem = '!--';
        }

        if (!in_array(strtolower($elem), $this->tags, true)) {
            return ''; // Disallowed HTML element.
        }

        if ($comment) {
            return $comment;
        }

        if ($slash != '') {
            return "</$elem>";
        }

        // Is there a closing XHTML slash at the end of the attributes?
        $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
        $xhtml_slash = $count ? ' /' : '';

        // Clean up attributes.
        $attr2 = implode(' ', $this->explodeAttributes($attrlist));
        $attr2 = preg_replace('/[<>]/', '', $attr2);
        $attr2 = strlen($attr2) ? ' ' . $attr2 : '';

        return "<$elem$attr2$xhtml_slash>";
    }
895306
protected function filterCssUrlCb(array $m)
    {
        if (mb_stripos($m['url'], 'data:') === 0) {
            return $m[0]; // Don't filter `data:` URIs.
        }
        return $m['url_'].$m['open_bracket'].$m['open_encap'].$this->hook_api->applyFilters('css_url()', $m['url']).$m['close_encap'].$m['close_bracket'];
    }
819106
public function generateXml()
    {
        $xml = $this->getUpdate()->asSimplexml();
        $removeInstructions = $xml->xpath("//remove");
        if (is_array($removeInstructions)) {
            foreach ($removeInstructions as $infoNode) {
                /** @var Mage_Core_Model_Layout_Element $infoNode */
                if (!$this->checkConditionals($infoNode, false)) {
                    continue;
                }
                $blockName = trim((string)$infoNode['name']);
                if ($blockName) {
                    $ignoreNodes = $xml->xpath("//block[@name='" . $blockName . "'] | //reference[@name='" . $blockName . "']");
                    if (is_array($ignoreNodes)) {
                        foreach ($ignoreNodes as $ignoreNode) {
                            /** @var Mage_Core_Model_Layout_Element $ignoreNode */
                            $ignoreNode['ignore'] = true;
                        }
                    }
                }
            }
        }
        $this->setXml($xml);
        return $this;
    }
460173
protected function resolveCssRelativesImportCb(array $m)
    {
        return $m['import'].$m['open_encap'].$this->resolveRelativeUrl($m['url'], $this->current_base).$m['close_encap'];
    }
543028
public function _getValue($xpath)
    {
        $xpathEscaped = json_encode($xpath);
        $script = <<<JS
var node = this.browserbot.locateElementByXPath({$xpathEscaped}, window.document),
tagName = node.tagName.toLowerCase(),
value = null;
if (tagName == 'input' || tagName == 'textarea') {
var type = node.getAttribute('type');
if (type == 'checkbox') {
value = node.checked;
} else if (type == 'radio') {
var name = node.getAttribute('name');
if (name) {
var fields = window.document.getElementsByName(name),
i, l = fields.length;
for (i = 0; i < l; i++) {
var field = fields.item(i);
if (field.checked) {
value = field.value;
break;
}
}
}
} else {
value = node.value;
}
} else if (tagName == 'select') {
if (node.getAttribute('multiple')) {
value = [];
for (var i = 0; i < node.options.length; i++) {
if (node.options[i].selected) {
value.push(node.options[i].value);
}
}
} else {
var idx = node.selectedIndex;
if (idx >= 0) {
value = node.options.item(idx).value;
} else {
value = null;
}
}
} else {
value = node.getAttribute('value');
}
JSON.stringify(value)
JS;
        $sResult = json_decode($this->getMinkSession()->getDriver()->getBrowser()->getEval($script));

        return preg_replace("/[ \n]+/", " ", $sResult);
    }
1321533
public function getRibbonXMLData($What = 'all') //we need some constants here...
    {
        $ReturnData = null;
        $What = strtolower($What);
        switch ($What){
            case 'all':
                $ReturnData = $this->ribbonXMLData;
                break;
            case 'target':
            case 'data':
                if (is_array($this->ribbonXMLData) && array_key_exists($What, $this->ribbonXMLData)) {
                    $ReturnData = $this->ribbonXMLData[$What];
                }
                break;
        }

        return $ReturnData;
    }
1049812
public function xpath($expression, $context = null)
    {
        if (is_array($expression)) {
            $tr = [];

            /** @noinspection ForeachSourceInspection */
            foreach ($expression as $k => $v) {
                $tr['$' . $k] = is_int($v) ? $v : "'$v'";
            }

            $expression = strtr($expression[0], $tr);
        }

        $r = @$this->_xpath->query($expression, $context);
        if ($r === false) {
            throw new MisuseException(['`:xpath` xpath is invalid expression', 'xpath' => $expression]);
        }

        return $r;
    }
799542
private function getFromDOMDocument($xpathExpression, $alwaysReturnArray = false)
    {
        if (($this->xpath instanceof DOMXPath) === false) {
            return;
        }

        $nodeList = @$this->xpath->query($xpathExpression);
        if ($nodeList instanceof DOMNodeList) {
            if ($nodeList->length === 1) {
                if ($alwaysReturnArray === true) {
                    return array($this->nodeToArray($nodeList->item(0)));
                }

                return $this->nodeToArray($nodeList->item(0));
            } else {
                $result = array();
                foreach ($nodeList as $node) {
                    $result[] = $this->nodeToArray($node);
                }

                return $result;
            }
        } elseif ($alwaysReturnArray === true) {
            return array();
        }
    }
182411
public function substituteFileContent($markdown, array $meta = array())
    {
        $variables = array();

        // replace %version%
        $variables['%version%'] = static::VERSION;

        // replace %site_title%
        $variables['%site_title%'] = $this->getConfig('site_title');

        // replace %base_url%
        if ($this->isUrlRewritingEnabled()) {
            // always use `%base_url%?sub/page` syntax for internal links
            // we'll replace the links accordingly, depending on enabled rewriting
            $variables['%base_url%?'] = $this->getBaseUrl();
        } else {
            // actually not necessary, but makes the URL look a little nicer
            $variables['%base_url%?'] = $this->getBaseUrl() . '?';
        }
        $variables['%base_url%'] = rtrim($this->getBaseUrl(), '/');

        // replace %theme_url%
        $variables['%theme_url%'] = $this->getBaseThemeUrl() . $this->getConfig('theme');

        // replace %meta.*%
        if ($meta) {
            foreach ($meta as $metaKey => $metaValue) {
                if (is_scalar($metaValue) || ($metaValue === null)) {
                    $variables['%meta.' . $metaKey . '%'] = (string) $metaValue;
                }
            }
        }

        return str_replace(array_keys($variables), $variables, $markdown);
    }
1123606
private function whereXML (array $q) {
		$queryString = '';
		$counter = 0;

		foreach ($q as $col => $value) {
			$counter++;
			$queryString .= '<Eq><FieldRef Name="' . $col . '" /><Value Type="Text">' . htmlspecialchars($value) . '</Value></Eq>';

			// Add additional "and"s if there are multiple query levels needed.
			if ($counter >= 2) {
				$queryString = '<And>' . $queryString . '</And>';
			}
		}

		return '<Where>' . $queryString . '</Where>';
	}