Exemple #1
0
 /**
  * Returns if significant whitespaces occur in the paragraph.
  *
  * This method checks if the paragraph $element contains significant
  * whitespaces in form of <text:s/> or <text:tab/> elements.
  * 
  * @param DOMElement $element 
  * @return bool
  */
 protected function hasSignificantWhitespace(DOMElement $element)
 {
     $xpath = new DOMXpath($element->ownerDocument);
     $xpath->registerNamespace('text', ezcDocumentOdt::NS_ODT_TEXT);
     $whitespaces = $xpath->evaluate('.//text:s|.//text:tab|.//text:line-break', $element);
     return $whitespaces instanceof DOMNodeList && $whitespaces->length > 0;
 }
 /**
  * @param \OCA\News\Db\Item $item
  * @return \OCA\News\Db\Item enhanced item
  */
 public function enhance(Item $item)
 {
     foreach ($this->regexXPathPair as $regex => $search) {
         if (preg_match($regex, $item->getUrl())) {
             $file = $this->getFile($item->getUrl());
             // convert encoding by detecting charset from header
             $contentType = $file->headers['content-type'];
             if (preg_match('/(?<=charset=)[^;]*/', $contentType, $matches)) {
                 $body = mb_convert_encoding($file->body, 'HTML-ENTITIES', $matches[0]);
             } else {
                 $body = $file->body;
             }
             $dom = new \DOMDocument();
             @$dom->loadHTML($body);
             $xpath = new \DOMXpath($dom);
             $xpathResult = $xpath->evaluate($search);
             // in case it wasnt a text query assume its a single
             if (!is_string($xpathResult)) {
                 $xpathResult = $this->domToString($xpathResult);
             }
             // convert all relative to absolute URLs
             $xpathResult = $this->substituteRelativeLinks($xpathResult, $item->getUrl());
             if ($xpathResult) {
                 $item->setBody($xpathResult);
             }
         }
     }
     return $item;
 }
 function testOff()
 {
     $doc = $this->process_post("[bibshow file=custom://data show_links=0][bibcite key=test]", ShowLinks::$data);
     $xpath = new DOMXpath($doc);
     $href = $xpath->evaluate("//a[@class = 'papercite_bibcite']/@href");
     $this->assertEquals(0, $href->length, "There were {$href->length} links detected - expected none");
 }
 public function metascore($type = "game", $name, $platform = NULL)
 {
     if (!$name) {
         throw new Exception("No parameters.");
     }
     $name = self::stripUrl($name);
     if ($platform) {
         $platform = self::stripUrl($platform);
     }
     $dom = new DomDocument();
     if ($type != ("movie" || "tv")) {
         $dom->loadHtmlFile("http://www.metacritic.com/{$type}/{$platform}/{$name}/");
         //replace this with Metacritics JSON search
     } else {
         $dom->loadHtmlFile("http://www.metacritic.com/{$type}/{$name}/");
         //replace this with Metacritics JSON search
     }
     $xpath = new DOMXpath($dom);
     $nodes = $xpath->evaluate("//span[@property='v:average']");
     if ($nodes) {
         return $nodes->item(0)->nodeValue;
     } else {
         throw new Exception("Could not find Metascore.");
     }
 }
    /**
     * Copy ServiceConfiguration over to build directory given with target path
     * and modify some of the settings to point to development settings.
     *
     * @param string $targetPath
     * @return void
     */
    public function copyForDeployment($targetPath, $development = true)
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->loadXML($this->dom->saveXML());
        $xpath = new \DOMXpath($dom);
        $xpath->registerNamespace('sc', $dom->lookupNamespaceUri($dom->namespaceURI));
        $settings = $xpath->evaluate('//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]');
        foreach ($settings as $setting) {
            if ($development) {
                $setting->setAttribute('value', 'UseDevelopmentStorage=true');
            } else {
                if (strlen($setting->getAttribute('value')) === 0) {
                    if ($this->storage) {
                        $setting->setAttribute('value', sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->storage['accountName'], $this->storage['accountKey']));
                    } else {
                        throw new \RuntimeException(<<<EXC
ServiceConfiguration.csdef: Missing value for
'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'.

You have to modify the app/azure/ServiceConfiguration.csdef to contain
a value for the diagnostics connection string or better configure
'windows_azure_distribution.diagnostics.accountName' and
'windows_azure_distribution.diagnostics.accountKey' in your
app/config/config.yml

If you don't want to enable diagnostics you should delete the
connection string elements from ServiceConfiguration.csdef file.
EXC
);
                    }
                }
            }
        }
        $dom->save($targetPath . '/ServiceConfiguration.cscfg');
    }
 public function preFilter($sHtml, $config, $context)
 {
     if (false === strstr($sHtml, '<a ')) {
         return $sHtml;
     }
     $sId = 'bx-links-' . md5(microtime());
     $dom = new DOMDocument();
     @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtml . '</div>');
     $xpath = new DOMXpath($dom);
     $oLinks = $xpath->evaluate('//a');
     for ($i = 0; $i < $oLinks->length; $i++) {
         $oLink = $oLinks->item($i);
         $sClasses = $oLink->getAttribute('class');
         if (!$sClasses || false === strpos($sClasses, $this->class)) {
             $sClasses = ($sClasses ? $sClasses . ' ' : '') . $this->class;
         }
         $oLink->removeAttribute('class');
         $oLink->setAttribute("class", $sClasses);
     }
     if (false === ($s = $dom->saveXML($dom->getElementById($sId)))) {
         // in case of error return original string
         return $sHtml;
     }
     return mb_substr($s, 52, -6);
     // strip added tags
 }
 function testOn()
 {
     $doc = $this->process_post("[bibtex file=custom://data process_titles=1]", Issue95::$data);
     $xpath = new DOMXpath($doc);
     $title = $xpath->evaluate("//ul[@class = 'papercite_bibliography']//span[1]/text()");
     $this->assertTrue($title->length == 1, "There were {$title->length} span detected - expected 1");
     $title = $title->item(0)->textContent;
     $this->assertEquals($title, "11th usenix symposium on networked systems design and implementation (nsdi 14)");
 }
function casValidate($cas)
{
    $service = SimpleSAML_Utilities::selfURL();
    $service = preg_replace("/(\\?|&)?ticket=.*/", "", $service);
    # always tagged on by cas
    /**
     * Got response from CAS server.
     */
    if (isset($_GET['ticket'])) {
        $ticket = urlencode($_GET['ticket']);
        #ini_set('default_socket_timeout', 15);
        if (isset($cas['validate'])) {
            # cas v1 yes|no\r<username> style
            $paramPrefix = strpos($cas['validate'], '?') ? '&' : '?';
            $result = SimpleSAML_Utilities::fetch($cas['validate'] . $paramPrefix . 'ticket=' . $ticket . '&service=' . urlencode($service));
            $res = preg_split("/\r?\n/", $result);
            if (strcmp($res[0], "yes") == 0) {
                return array($res[1], array());
            } else {
                throw new Exception("Failed to validate CAS service ticket: {$ticket}");
            }
        } elseif (isset($cas['serviceValidate'])) {
            # cas v2 xml style
            $paramPrefix = strpos($cas['serviceValidate'], '?') ? '&' : '?';
            $result = SimpleSAML_Utilities::fetch($cas['serviceValidate'] . $paramPrefix . 'ticket=' . $ticket . '&service=' . urlencode($service));
            $dom = DOMDocument::loadXML($result);
            $xPath = new DOMXpath($dom);
            $xPath->registerNamespace("cas", 'http://www.yale.edu/tp/cas');
            $success = $xPath->query("/cas:serviceResponse/cas:authenticationSuccess/cas:user");
            if ($success->length == 0) {
                $failure = $xPath->evaluate("/cas:serviceResponse/cas:authenticationFailure");
                throw new Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent);
            } else {
                $attributes = array();
                if ($casattributes = $cas['attributes']) {
                    # some has attributes in the xml - attributes is a list of XPath expressions to get them
                    foreach ($casattributes as $name => $query) {
                        $attrs = $xPath->query($query);
                        foreach ($attrs as $attrvalue) {
                            $attributes[$name][] = $attrvalue->textContent;
                        }
                    }
                }
                $casusername = $success->item(0)->textContent;
                return array($casusername, $attributes);
            }
        } else {
            throw new Exception("validate or serviceValidate not specified");
        }
        /**
         * First request, will redirect the user to the CAS server for authentication.
         */
    } else {
        SimpleSAML_Logger::info("AUTH - cas-ldap: redirecting to {$cas['login']}");
        SimpleSAML_Utilities::redirectTrustedURL($cas['login'], array('service' => $service));
    }
}
 /**
  * {@inheritdoc}
  */
 public function setResponse($response)
 {
     $dom = new \DOMDocument();
     try {
         if (!$dom->loadXML($response)) {
             throw new \ErrorException('Could not transform this xml to a \\DOMDocument instance.');
         }
     } catch (\Exception $e) {
         throw new AuthenticationException('Could not retrieve valid user info.');
     }
     $this->xpath = new \DOMXpath($dom);
     $nodes = $this->xpath->evaluate('/api/root');
     $user = $this->xpath->query('./foaf:Person', $nodes->item(0));
     if (1 !== $user->length) {
         throw new AuthenticationException('Could not retrieve user info.');
     }
     $this->response = $user->item(0);
 }
    /**
     * @param string $text
     * @return string
     */
    public function sanitize($text)
    {
        $doc = new DOMDocument('1.0', "UTF-8");
        $text = mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8');
        $doc->loadHTML('<?xml encoding="UTF-8">'.$text);
        $doc->encoding = "UTF-8";
        $doc->formatOutput = true;

        // get all the script tags
        $script_tags = $doc->getElementsByTagName('script');
        $length = $script_tags->length;
        // for each tag, remove it from the DOM
        for ($i = 0; $i < $length; $i++) {
            if(($parentNode = $script_tags->item($i)->parentNode))
                $parentNode->removeChild($script_tags->item($i));
        }

        /* @type $parentNode DOMNode */

        $xpath = new DOMXpath($doc);
        foreach ($xpath->evaluate('//*[@onmouseover]') as $input)
        {
            if(($parentNode = $input->parentNode))
                $parentNode->removeChild($input);
        }
        foreach ($xpath->evaluate('//*[@onmouseout]') as $input)
        {
            if(($parentNode = $input->parentNode))
                $parentNode->removeChild($input);
        }
        foreach ($xpath->evaluate('//*[@onerror]') as $input)
        {
            if(($parentNode = $input->parentNode))
                $parentNode->removeChild($input);
        }
        foreach ($xpath->evaluate('//*[@onclick]') as $input)
        {
            if(($parentNode =$input->parentNode))
                $parentNode->removeChild($input);
        }

        $result = $doc->saveHTML();
        return strip_tags($result, "<span><strong><br><div>");
    }
Exemple #11
0
 function test()
 {
     $url = "https://gist.githubusercontent.com/bpiwowar/9793f4e2da48dfb34cde/raw/5fbff41218107aa9dcfab4fc53fe8e2b86ea8416/test.bib";
     $doc = $this->process_post("[bibtex ssl_check=true file={$url}]");
     $xpath = new DOMXpath($doc);
     $items = $xpath->evaluate("//ul[@class = 'papercite_bibliography']/li");
     $this->assertTrue($items->length == 1, "{$items->length} items detected - expected 1");
     $text = $items->item(0)->textContent;
     $this->assertRegExp("#Piwowarski#", $text);
 }
 function testHighlight()
 {
     $doc = $this->process_post("[bibtex file=custom://data highlight=\"Piwowarski\"]", HighlightTest::$data);
     // print $doc->saveXML();
     $xpath = new DOMXpath($doc);
     $highlight = $xpath->evaluate("//span[@class = 'papercite_highlight']/text()");
     $this->assertTrue($highlight->length == 1, "{$highlight->length} highlights detected - expected 1");
     $highlight = $highlight->item(0)->wholeText;
     $this->assertTrue($highlight == "Piwowarski", "The hilight [{$highlight}] is not as expected");
 }
Exemple #13
0
 /**
  * Selects elements that match a CSS selector
  * 
  * Based on the implementation of TJ Holowaychuk <*****@*****.**>
  * @link https://github.com/tj/php-selector
  * @param string $selector
  * @param \DOMDocument $htmlOrDom
  * @return \DOMNodeList
  */
 public static function selectElements($selector, $htmlOrDom)
 {
     if ($htmlOrDom instanceof \DOMDocument) {
         $xpath = new \DOMXpath($htmlOrDom);
     } else {
         $dom = new \DOMDocument();
         @$dom->loadHTML($htmlOrDom);
         $xpath = new \DOMXpath($dom);
     }
     return $xpath->evaluate(self::selectorToXpath($selector));
 }
 function check($modifier, $expected)
 {
     $doc = $this->process_post("[bibtex file=custom://data template=custom://template]", array("data" => HTMLModifierTest::$data, "template" => HTMLModifierTest::getTemplate($modifier)));
     $xpath = new DOMXpath($doc);
     $result = $xpath->evaluate("//div[@id = 'abstract']/node()");
     $text = "";
     for ($i = 0; $i < $result->length; $i++) {
         $text .= $doc->saveXML($result->item($i));
     }
     $this->assertEquals($text, $expected, "Error with modifier {$modifier}");
 }
Exemple #15
0
 /**
  * Parses the OPML file.
  *
  * @param bool $normalize_case
  *   (optional) True to convert all attributes to lowercase. False, to leave
  *   them as is. Defaults to false.
  *
  * @return array
  *   A structed array.
  *
  * @todo Document the return value.
  */
 public function parse($normalize_case = FALSE)
 {
     $this->normalizeCase = $normalize_case;
     $return = ['head' => ['#title' => '']];
     // Title is a required field, let parsers assume its existence.
     foreach ($this->xpath->query('/opml/head/*') as $element) {
         if ($this->normalizeCase) {
             $return['head']['#' . strtolower($element->nodeName)] = $element->nodeValue;
         } else {
             $return['head']['#' . $element->nodeName] = $element->nodeValue;
         }
     }
     if (isset($return['head']['#expansionState'])) {
         $return['head']['#expansionState'] = array_filter(explode(',', $return['head']['#expansionState']));
     }
     $return['outlines'] = [];
     if ($content = $this->xpath->evaluate('/opml/body', $this->xpath->document)->item(0)) {
         $return['outlines'] = $this->getOutlines($content);
     }
     return $return;
 }
 private function toPacket($xml)
 {
     $xml = '<?xml version="1.0" encoding="utf-8"?>' . $xml;
     $packet = array();
     $dom = new \DOMDocument();
     if ($dom->loadXML($xml)) {
         $xpath = new \DOMXpath($dom);
         $type = $xpath->evaluate('string(//xml/MsgType)');
         if ($type == 'text') {
             $packet['type'] = Platform::POCKET_TEXT;
             $packet['content'] = $xpath->evaluate('string(//xml/Content)');
         }
         if ($type == 'news') {
             $packet['type'] = Platform::POCKET_NEWS;
             $packet['news'] = array();
             $items = $xpath->query('//xml/Articles/item');
             foreach ($items as $item) {
                 $row = array();
                 $row['title'] = $xpath->evaluate('string(Title)', $item);
                 $row['description'] = $xpath->evaluate('string(Description)', $item);
                 $row['picurl'] = $xpath->evaluate('string(PicUrl)', $item);
                 $row['url'] = $xpath->evaluate('string(Url)', $item);
                 $packet['news'][] = $row;
             }
         }
     }
     return $packet;
 }
 function update_quality_metadata($runBenchMark = false)
 {
     $this->_CI->load->model('registry_object/quality_checker', 'qa');
     // Get and update our quality metadata
     // use the optimised version of getRelatedClassesString (which does not use getConnections())
     $relatedClassStr = $this->ro->getRelatedClassesString(false);
     if ($runBenchMark) {
         $this->_CI->benchmark->mark('ro_qa_s1_end');
     }
     $quality_metadata = $this->_CI->qa->get_quality_test_result($this->ro, $relatedClassStr);
     if ($runBenchMark) {
         $this->_CI->benchmark->mark('ro_qa_s2_end');
     }
     $this->ro->error_count = substr_count($quality_metadata, 'class="error');
     $this->ro->warning_count = substr_count($quality_metadata, 'class="error');
     $this->ro->setMetadata('quality_html', $quality_metadata);
     // Get and update our quality LEVELs
     $quality_metadata = $this->_CI->qa->get_qa_level_test_result($this->ro, $relatedClassStr);
     if ($runBenchMark) {
         $this->_CI->benchmark->mark('ro_qa_s3_end');
     }
     // LEO'S BLACK MAGIC FOR DETERMINING THE MAXIMAL LEVEL
     $reportDoc = new DOMDocument();
     $reportDoc->loadXML($quality_metadata);
     $nXPath = new DOMXpath($reportDoc);
     $errorElement = $nXPath->evaluate("//span[@class = 'qa_error']");
     $level = 4;
     for ($j = 0; $j < $errorElement->length; $j++) {
         if ($errorElement->item($j)->getAttribute("level") < $level) {
             $level = $errorElement->item($j)->getAttribute("level");
             //print "error found".$level."\n";
         }
     }
     $level = $level - 1;
     // GOLD STANDARD SHOULD BE 4!!!
     if ($this->ro->gold_status_flag == 't') {
         $this->ro->quality_level = 4;
     } else {
         $this->ro->quality_level = $level;
     }
     $this->ro->setMetadata('level_html', $quality_metadata);
     $this->ro->save();
 }
Exemple #18
0
    function testSample()
    {
        $user_id = $this->factory->user->create();
        $content = "[bibtex file=custom://data key=test]";
        $post_id = $this->factory->post->create(array('post_author' => $user_id, 'post_content' => $content));
        $data = <<<EOF
@inproceedings{test,
    title="Hello world",
    author="B. Piwowarski"
}
EOF;
        add_post_meta($post_id, "papercite_data", $data);
        $GLOBALS['post'] = $post_id;
        $doc = new DOMDocument();
        $processed = apply_filters('the_content', $content);
        $doc->loadXML("{$processed}");
        $xpath = new DOMXpath($doc);
        $title = trim($xpath->evaluate("string(//li/text()[1])"));
        // print $doc->saveXML();
        $this->assertStringStartsWith("B. Piwowarski, “Hello world.”", $title);
    }
Exemple #19
0
 public function parseError($content)
 {
     if (!$content) {
         throw new ApiParserException('Could not transform this xml to a \\DOMDocument instance.');
     }
     $internalErrors = libxml_use_internal_errors(true);
     $disableEntities = libxml_disable_entity_loader(true);
     libxml_clear_errors();
     $document = new \DOMDocument();
     $document->validateOnParse = true;
     if (!$document->loadXML($content, LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
         libxml_disable_entity_loader($disableEntities);
         libxml_clear_errors();
         libxml_use_internal_errors($internalErrors);
         throw new ApiParserException('Could not transform this xml to a \\DOMDocument instance.');
     }
     $document->normalizeDocument();
     libxml_use_internal_errors($internalErrors);
     libxml_disable_entity_loader($disableEntities);
     $xpath = new \DOMXpath($document);
     $nodes = $xpath->evaluate('./error');
     if (1 === $nodes->length) {
         throw new ApiParserException('The dom contains more than one error node.');
     }
     $error = new Error();
     $parameters = $xpath->query('./entity/body/parameter', $nodes->item(0));
     foreach ($parameters as $parameter) {
         $name = $parameter->getAttribute('name');
         $error->addEntityBodyParameter($name);
         $messages = $xpath->query('./message', $parameter);
         foreach ($messages as $message) {
             $error->addEntityBodyParameterError($name, $this->sanitizeValue($message->nodeValue));
         }
     }
     return $error;
 }
Exemple #20
0
 public function evaluate($xpath, array $ns = array())
 {
     $xp = new \DOMXpath($this);
     foreach ($ns as $prefix => $uri) {
         $xp->registerNamespace($prefix, $uri);
     }
     // https://bugs.php.net/bug.php?id=65375
     return $xp->evaluate($xpath, null, false);
 }
Exemple #21
0
 /**
  * Send a xpath query to the XML document <code>$doc</code>.
  * @param $query XPath query
  * @param $test should always be false, used to test UnresolvedXPathException
  *              for typed results not being string, double or boolean.
  * @return  representing the nodes found evaluating $query.
  */
 public function xpath($query = "/", $test = false)
 {
     $nodeeval = "";
     $domx = new \DOMXpath($this->doc);
     $nodedoc = new \DOMDocument();
     $unresolved = false;
     // catch some invalid xpath expressions before evaluation
     if (is_null($query)) {
         $this->logger->logge("%", array(new \core\exception\xml\xpath\InvalidXPathExpressionException("Invalid XPath expression - Query=" . $query, 1)), "ERR");
         throw new \core\exception\xml\xpath\InvalidXPathExpressionException("Invalid XPath expression - Query=" . $query, 1);
     } else {
         if (strncmp($query, "", 1) == 0) {
             $this->logger->logge("%", array(new \core\exception\xml\xpath\InvalidXPathExpressionException("Invalid XPath expression - Query=" . $query, 2)), "ERR");
             throw new \core\exception\xml\xpath\InvalidXPathExpressionException("Invalid XPath expression - Query=" . $query, 2);
         }
     }
     // run the evaluation, $test should always be false and only set from
     // test classes to check the unrecognized typed result branch
     // NOTE: as NULL defaults to false the following lines will throw an
     //       InvalidXPathExpressionException. therefor use type 'array'
     //       when $test = true or expand !$nlist with this $test check
     $nlist = null;
     if (!$test) {
         $nlist = @$domx->evaluate($query);
     }
     // if it still fails raise a general exception
     // NOTE: $nlist is boolean 'false' if evaluation fails
     //         so evaluting 'false()' simply always throws an exception too
     //       https://bugs.php.net/bug.php?id=70523
     if (!$test && !$nlist) {
         $this->logger->logge("%", array(new \core\exception\xml\xpath\InvalidXPathExpressionException()), "ERR");
         throw new \core\exception\xml\xpath\InvalidXPathExpressionException();
     }
     // if we got some usable values returned
     if (strncmp(gettype($nlist), "object", 6) == 0 && strncmp(get_class($nlist), "DOMNodeList", 11) == 0) {
         foreach ($nlist as $n) {
             if (strncmp(get_class($n), "DOMDocument", 11) == 0) {
                 $nodeeval = $nodeeval . " " . preg_replace("/<\\?xml.*" . "\\?" . ">/", "", $n->saveXML());
             } else {
                 if (strncmp(get_class($n), "DOMElement", 10) == 0) {
                     $nodedoc->appendChild($nodedoc->importNode($n->cloneNode(TRUE), TRUE));
                     $nodeeval = $nodeeval . " " . preg_replace("/<\\?xml.*" . "\\?" . ">/", "", $nodedoc->saveXML());
                 } else {
                     if (strncmp(get_class($n), "DOMAttr", 7) == 0) {
                         $nodeeval = $nodeeval . " " . $n->name . "=\"" . $n->value . "\"";
                     } else {
                         if (strncmp(get_class($n), "DOMText", 7) == 0) {
                             $nodeeval = $nodeeval . " " . $n->wholeText . "";
                             // NOTE: DOMComment is used to throw an UnresolvedXPathException
                             //       as comments can be ignored. therefor the followng lines
                             //       are dead code. remove comment prefix to enable DOMComment
                             //       detection
                             //} else if (strncmp(get_class($n),"DOMComment",10)==0) {
                             //  $nodedoc->appendChild($nodedoc->importNode($n->cloneNode(TRUE),TRUE));
                             //  $nodeeval = $nodeeval." ".preg_replace("/<\?xml.*"."\?".">/","",
                             //                                         $nodedoc->saveXML());
                         } else {
                             $unresolved = true;
                             break;
                         }
                     }
                 }
             }
         }
     } else {
         if (strncmp(gettype($nlist), "string", 6) == 0) {
             $nodeeval = $nodeeval . "" . $nlist;
         } else {
             if (strncmp(gettype($nlist), "double", 6) == 0) {
                 $nodeeval = $nodeeval . "" . $nlist;
             } else {
                 if (strncmp(gettype($nlist), "boolean", 7) == 0) {
                     $nodeeval = $nodeeval . "" . ($nlist ? "true" : "false");
                 } else {
                     $unresolved = true;
                 }
             }
         }
     }
     // throw an exception if there was an object class or
     // return type unresolved by this function
     if ($unresolved) {
         $this->logger->logge("%", array(new \core\exception\xml\xpath\UnresolvedXPathException("Unresolved XPath expression for " . (strncmp(gettype($nlist), "object", 6) != 0 ? "type " : "") . gettype($nlist) . (strncmp(gettype($nlist), "object", 6) == 0 ? " class " : "") . (strncmp(gettype($nlist), "object", 6) == 0 ? get_class($nlist) : ""))), "ERR");
         throw new \core\exception\xml\xpath\UnresolvedXPathException("Unresolved XPath expression for " . (strncmp(gettype($nlist), "object", 6) != 0 ? "type " : "") . gettype($nlist) . (strncmp(gettype($nlist), "object", 6) == 0 ? " class " : "") . (strncmp(gettype($nlist), "object", 6) == 0 ? get_class($nlist) : ""));
     }
     // replace (multiple) white spaces and newline characters
     $nodeeval = preg_replace("/> </", "><", preg_replace("/^([ \t])+|([ \t])+\$/", "", preg_replace("/([ \t])+/", " ", preg_replace("/[\r\n]/", " ", $nodeeval))));
     // log the query result
     $this->logger->logge("%", array($nodeeval));
     return $nodeeval;
 }
        $mylink = $l->getAttribute("href");
        echo $mylink . "<br>";
        $links[] = $mylink;
    }
    $p = "";
    $nextLink = $xpath->evaluate($expNext)->item(0);
    if ($nextLink) {
        $p = $nextLink->getAttribute("data-page");
    }
}
foreach ($links as $l) {
    $html = file_get_contents($l);
    $document = new DOMDocument();
    $document->loadHTML($html);
    $xpath = new DOMXpath($document);
    $myDate = $xpath->evaluate($expDate)->item(0)->nodeValue;
    $myTitle = $xpath->evaluate($expTitle)->item(0)->nodeValue;
    $myDesc = $xpath->evaluate($expDesc)->item(0)->nodeValue;
    if (substr($myDesc, -8) == ". close ") {
        $myDesc = substr($myDesc, 0, -7);
    }
    $peopleDiv = $xpath->evaluate($expPeopleDiv)->item(0);
    $people = $xpath->evaluate($expPeople, $peopleDiv);
    $myPeople2 = array();
    foreach ($people as $p) {
        $myPeople2[] = $p->getElementsByTagName('a')->item(0)->nodeValue;
    }
    $myPeople = implode("|", $myPeople2);
    echo "<tr>";
    echo "<td>{$showid}</td>";
    echo "<td>{$myDate}</td>";
    public function getNodeTypeDOMElement($name)
    {
        $xml = <<<XML
<nodeTypes>
    <nodeType hasOrderableChildNodes="true" isQueryable="true" name="nt:base" isMixin="false" isAbstract="true">
        <propertyDefinition name="jcr:primaryType" requiredType="NAME" autoCreated="true" mandatory="true" protected="true" multiple="false" fullTextSearchable="true" queryOrderable="true" onParentVersion="COMPUTE" />
        <propertyDefinition name="jcr:mixinTypes" requiredType="NAME" autoCreated="true" mandatory="true" protected="true" multiple="true" fullTextSearchable="true" queryOrderable="true" onParentVersion="COMPUTE" />
    </nodeType>
    <nodeType hasOrderableChildNodes="true" isQueryable="true" name="nt:unstructured" isMixin="false" isAbstract="false">
        <supertypes>
            <supertype>nt:base</supertype>
        </supertypes>
        <childNodeDefinition autoCreated="false" declaringNodeType="nt:unstructured" defaultPrimaryType="nt:unstructured" mandatory="false" name="*" onParentVersion="VERSION" protected="false" sameNameSiblings="false">
          <requiredPrimaryTypes>
            <requiredPrimaryType>nt:base</requiredPrimaryType>
          </requiredPrimaryTypes>
        </childNodeDefinition>
        <propertyDefinition autoCreated="false" declaringNodeType="nt:unstructured" fullTextSearchable="true" mandatory="false" multiple="true" name="*" onParentVersion="COPY" protected="false" queryOrderable="true" requiredType="undefined" />
    </nodeType>
    <nodeType hasOrderableChildNodes="false" isQueryable="false" name="mix:etag" isMixin="true">
        <propertyDefinition name="jcr:etag" requiredType="STRING" autoCreated="true" protected="true" onParentVersion="COMPUTE" />
    </nodeType>
    <nodeType name="nt:hierachy" isAbstract="true">
        <supertypes>
            <supertype>mix:created</supertype>
        </supertypes>
    </nodeType>
    <nodeType name="nt:file" isMixin="false" isAbstract="false">
        <supertypes>
            <supertype>nt:hierachy</supertype>
        </supertypes>
    </nodeType>
    <nodeType name="nt:folder" isMixin="false" isAbstract="false">
        <supertypes>
            <supertype>nt:hierachy</supertype>
        </supertypes>
    </nodeType>
    <nodeType name="nt:resource" isMixin="false" isAbstract="false" primaryItemName="jcr:data">
        <supertypes>
            <supertype>mix:mimeType</supertype>
            <supertype>mix:modified</supertype>
        </supertypes>
        <propertyDefinition name="jcr:created" requiredType="BINARY" autoCreated="false" protected="false" onParentVersion="COPY" />
    </nodeType>
    <nodeType name="mix:created" isMixin="true">
        <propertyDefinition name="jcr:created" requiredType="DATE" autoCreated="true" protected="true" onParentVersion="COMPUTE" />
        <propertyDefinition name="jcr:createdBy" requiredType="STRING" autoCreated="true" protected="true" onParentVersion="COMPUTE" />
    </nodeType>
    <nodeType name="mix:mimeType" isMixin="true">
        <propertyDefinition name="jcr:mimeType" requiredType="DATE" autoCreated="false" protected="true" onParentVersion="COPY" />
        <propertyDefinition name="jcr:encoding" requiredType="STRING" autoCreated="false" protected="true" onParentVersion="COPY" />
    </nodeType>
    <nodeType name="mix:lastModified" isMixin="true">
        <propertyDefinition name="jcr:lastModified" requiredType="DATE" autoCreated="true" protected="true" onParentVersion="COMPUTE" />
        <propertyDefinition name="jcr:lastModifiedBy" requiredType="STRING" autoCreated="true" protected="true" onParentVersion="COMPUTE" />
    </nodeType>
</nodeTypes>

XML;
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->loadXML($xml);
        $xpath = new \DOMXpath($dom);
        $nodes = $xpath->evaluate('//nodeTypes/nodeType[@name="' . $name . '"]');
        if ($nodes->length != 1) {
            $this->fail("Should have found exactly one element <nodeType> with name " . $name);
        }
        return $nodes->item(0);
    }
Exemple #24
0
 /**
  * Uses the cas service validate, this provides additional attributes
  *
  * @param string $ticket
  * @param string $service
  * @return list username and attributes
  */
 private function casServiceValidate($ticket, $service)
 {
     $url = SimpleSAML_Utilities::addURLparameter($this->_casConfig['serviceValidate'], array('ticket' => $ticket, 'service' => $service));
     $result = SimpleSAML_Utilities::fetch($url);
     $dom = DOMDocument::loadXML($result);
     $xPath = new DOMXpath($dom);
     $xPath->registerNamespace("cas", 'http://www.yale.edu/tp/cas');
     $success = $xPath->query("/cas:serviceResponse/cas:authenticationSuccess/cas:user");
     if ($success->length == 0) {
         $failure = $xPath->evaluate("/cas:serviceResponse/cas:authenticationFailure");
         throw new Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent);
     } else {
         $attributes = array();
         if ($casattributes = $this->_casConfig['attributes']) {
             # some has attributes in the xml - attributes is a list of XPath expressions to get them
             foreach ($casattributes as $name => $query) {
                 $attrs = $xPath->query($query);
                 foreach ($attrs as $attrvalue) {
                     $attributes[$name][] = $attrvalue->textContent;
                 }
             }
         }
         $casusername = $success->item(0)->textContent;
         return array($casusername, $attributes);
     }
 }
        $jsonData = json_encode($jsonData);
        echo $callback . "(" . $jsonData . ");";
        exit;
    }
    $gXPath = new DOMXpath($gazetteerDoc);
    $jsonData['status'] = 'OK';
} catch (Exception $e) {
    $jsonData['status'] = 'ERROR';
    $jsonData['exception'] = $e->getMessage();
    $jsonData = json_encode($jsonData);
    echo $callback . "(" . $jsonData . ");";
    exit;
}
if ($searchText) {
    // Resolve and order the results (we only want a few of the feature types to avoid a massive list)
    $featureMemberListTOP = $gXPath->evaluate('gml:featureMember[descendant::node()[contains(@codeSpace,"STAT")] or descendant::node()[contains(@codeSpace,"SUB")] or descendant::node()[contains(@codeSpace,"URBN")]]');
    $featureMemberListBOTTOM = $gXPath->evaluate('gml:featureMember[not(descendant::node()[contains(@codeSpace,"STAT")] or descendant::node()[contains(@codeSpace,"SUB")] or descendant::node()[contains(@codeSpace,"URBN")])]');
    $jsonData['items_count'] = $featureMemberListTOP->length + $featureMemberListBOTTOM->length;
    $items = array();
    for ($i = 0; $i < $featureMemberListTOP->length; $i++) {
        $item = array();
        $featureMember = $featureMemberListTOP->item($i);
        $item['title'] = $gXPath->evaluate('.//iso19112:name', $featureMember)->item(0)->nodeValue;
        $coordsStr = $gXPath->evaluate('.//gml:pos', $featureMember)->item(0)->nodeValue;
        $spPos = strpos($coordsStr, ' ');
        $item['coords'] = $coordsStr;
        $item['lat'] = substr($coordsStr, 0, $spPos);
        $item['lng'] = substr($coordsStr, $spPos + 1);
        $typeArray = array();
        $featureTypes = $gXPath->evaluate('iso19112:SI_LocationInstance/iso19112:locationType/@codeSpace', $featureMember);
        for ($j = 0; $j < $featureTypes->length; $j++) {
 private function tryContentDetect($html)
 {
     if ($patterns = SourcesSettings::findAll(['source_id' => $this->source->id, 'name' => 'content_pattern'])) {
         $doc = new \DOMDocument("1.0", "utf-8");
         $doc->preserveWhiteSpace = false;
         libxml_use_internal_errors(true);
         $doc->loadHTML($html);
         $xpath = new \DOMXpath($doc);
         $contentResult = false;
         foreach ($patterns as $pattern) {
             if ($content = $xpath->evaluate($pattern->value)) {
                 $contentResult .= $doc->saveHTML($content->item(0));
             }
         }
         return $contentResult;
     }
     return false;
 }
 /**
  * @test
  */
 function expand()
 {
     $reader = new XMLReaderStub('<products>
         <!--suppress HtmlUnknownAttribute -->
         <product category="Desktop">
             <name> Desktop 1 (d)</name>
             <price>499.99</price>
         </product>
         <!--suppress HtmlUnknownAttribute -->
         <product category="Tablet">
             <name>Tablet 1 (t)</name>
             <price>1099.99</price>
         </product>
     </products>');
     $products = new XMLElementIterator($reader, 'product');
     $doc = new DOMDocument();
     $xpath = new DOMXpath($doc);
     foreach ($products as $product) {
         $node = $product->expand($doc);
         $this->assertInstanceOf('DOMNode', $node);
         $this->assertSame($node->ownerDocument, $doc);
         $this->assertEquals('product', $xpath->evaluate('local-name(.)', $node));
         $this->addToAssertionCount(1);
     }
     $this->assertGreaterThan(0, $previous = $this->getNumAssertions());
     unset($doc);
     $reader->rewind();
     foreach ($products as $product) {
         $node = $product->expand();
         $this->assertInstanceOf('DOMNode', $node);
         $this->assertInstanceOf('DOMDocument', $node->ownerDocument);
         $doc = $node->ownerDocument;
         $xpath = new DOMXpath($doc);
         $this->assertSame($node->ownerDocument, $doc);
         $this->assertEquals('product', $xpath->evaluate('local-name(.)', $node));
         $this->addToAssertionCount(1);
     }
     $this->assertGreaterThan($previous, $this->getNumAssertions());
 }
Exemple #28
0
 function show_xpathes()
 {
     print "{$this->CRLFs}---- show_xpathes count types: ---";
     $xp = new DOMXpath($this);
     foreach ($this->nodePathes as $rotulo => $path) {
         print "\n\t{$rotulo}: " . $xp->evaluate("count({$path})");
     }
 }
 public function executeRangeQuery(RangeQuery $query, $storageName, $key, \Closure $hydrateRow = null)
 {
     $headers = ['Content-Type' => 'application/atom+xml', 'x-ms-date' => $this->now(), 'Content-Length' => 0];
     $filters = ["PartitionKey eq " . $this->quoteFilterValue($query->getPartitionKey())];
     foreach ($query->getConditions() as $condition) {
         if (!in_array($condition[0], ['eq', 'neq', 'le', 'lt', 'ge', 'gt'])) {
             throw new \InvalidArgumentException("Windows Azure Table only supports eq, neq, le, lt, ge, gt as conditions.");
         }
         $filters[] = $key[1] . " " . $condition[0] . " " . $this->quoteFilterValue($condition[1]);
     }
     // TODO: This sucks
     $tableName = $storageName;
     $url = $this->baseUrl . '/' . $tableName . '()?$filter=' . rawurlencode(implode(' ', $filters));
     if ($query->getLimit()) {
         $url .= '&$top=' . $query->getLimit();
     }
     $response = $this->request('GET', $url, '', $headers);
     if ($response->getStatusCode() >= 400) {
         $this->convertResponseToException($response);
     }
     $dom = new \DomDocument('1.0', 'UTF-8');
     $dom->loadXML($response->getBody());
     $xpath = new \DOMXpath($dom);
     $xpath->registerNamespace('d', 'http://schemas.microsoft.com/ado/2007/08/dataservices');
     $xpath->registerNamespace('m', 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
     $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
     $entries = $xpath->evaluate('/atom:feed/atom:entry');
     $results = [];
     foreach ($entries as $entry) {
         $data = $this->createRow($key, $xpath, $entry);
         $results[] = $hydrateRow ? $hydrateRow($data) : $data;
     }
     return $results;
 }
 private static function parseDefineFile($xml)
 {
     $dom = new \DOMDocument();
     if ($dom->loadXML($xml)) {
         if ($dom->schemaValidate(MB_ROOT . "source/Conf/define.xsd")) {
             $xpath = new \DOMXpath($dom);
             $xpath->registerNamespace('mb', 'http://www.microbuilder.cn');
             $addon = array();
             $addon['title'] = $xpath->evaluate('string(//mb:addon/mb:title)');
             $addon['name'] = $xpath->evaluate('string(//mb:addon/mb:name)');
             $addon['version'] = $xpath->evaluate('string(//mb:addon/mb:version)');
             $addon['require'] = $xpath->evaluate('string(//mb:addon/mb:require)');
             $addon['type'] = $xpath->evaluate('string(//mb:addon/mb:type)');
             $addon['description'] = $xpath->evaluate('string(//mb:addon/mb:description)');
             $addon['author'] = $xpath->evaluate('string(//mb:addon/mb:author)');
             $addon['url'] = $xpath->evaluate('string(//mb:addon/mb:url)');
             return $addon;
         } else {
             $err = error_get_last();
             if ($err['type'] == 2) {
                 return error(-2, '扩展定义文件格式错误, 详细信息: ' . $err['message']);
             }
             return error(-2, '扩展定义文件格式错误');
         }
     } else {
         return error(-2, '扩展定义文件格式错误');
     }
 }