Ejemplo n.º 1
0
 /**
  * Unserializes the property.
  *
  * This static method should return a an instance of this object.
  *
  * @param \DOMElement $prop
  * @param array $propertyMap
  * @return DAV\IProperty
  */
 static function unserialize(\DOMElement $prop, array $propertyMap)
 {
     $xpath = new \DOMXPath($prop->ownerDocument);
     $xpath->registerNamespace('d', 'urn:DAV');
     // Finding the 'response' element
     $xResponses = $xpath->evaluate('d:response', $prop);
     $result = [];
     for ($jj = 0; $jj < $xResponses->length; $jj++) {
         $xResponse = $xResponses->item($jj);
         // Parsing 'href'
         $href = Href::unserialize($xResponse, $propertyMap);
         $properties = [];
         // Parsing 'status' in 'd:response'
         $responseStatus = $xpath->evaluate('string(d:status)', $xResponse);
         if ($responseStatus) {
             list(, $responseStatus, ) = explode(' ', $responseStatus, 3);
         }
         // Parsing 'propstat'
         $xPropstat = $xpath->query('d:propstat', $xResponse);
         for ($ii = 0; $ii < $xPropstat->length; $ii++) {
             // Parsing 'status'
             $status = $xpath->evaluate('string(d:status)', $xPropstat->item($ii));
             list(, $statusCode, ) = explode(' ', $status, 3);
             $usedPropertyMap = $statusCode == '200' ? $propertyMap : [];
             // Parsing 'prop'
             $properties[$statusCode] = DAV\XMLUtil::parseProperties($xPropstat->item($ii), $usedPropertyMap);
         }
         $result[] = new Response($href->getHref(), $properties, $responseStatus ? $responseStatus : null);
     }
     return new self($result);
 }
 /**
  * Parses the request.
  *
  * @return void
  */
 public function parse()
 {
     $filterNode = null;
     $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)');
     if (is_nan($limit)) {
         $limit = null;
     }
     $filter = $this->xpath->query('/card:addressbook-query/card:filter');
     if ($filter->length !== 1) {
         throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed');
     }
     $filter = $filter->item(0);
     $test = $this->xpath->evaluate('string(@test)', $filter);
     if (!$test) {
         $test = self::TEST_ANYOF;
     }
     if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) {
         throw new Sabre_DAV_Exception_BadRequest('The test attribute must either hold "anyof" or "allof"');
     }
     $propFilters = array();
     $propFilterNodes = $this->xpath->query('card:prop-filter', $filter);
     for ($ii = 0; $ii < $propFilterNodes->length; $ii++) {
         $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii));
     }
     $this->filters = $propFilters;
     $this->limit = $limit;
     $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild));
     $this->test = $test;
 }
Ejemplo n.º 3
0
 function parse()
 {
     $x = new DOMXPath($this->dom);
     $paragraphes = $x->evaluate('//*[@id="posts"]/li[ @id and not( contains(@class,"with_avatar") ) and not(@class="post") ]', $x->document);
     // prevent to leak sessionkey via referer.
     $anchors = $x->evaluate('//*[@id="posts"]/li//a', $x->document);
     foreach ($anchors as $k => $v) {
         $u = $v->getAttribute('href');
         if (preg_match('%^http://%i', $u)) {
             $u = to_mobile_url($u);
             $v->setAttribute('href', $u);
             $u = $v->getAttribute('href');
         }
     }
     $images = $x->evaluate('//*[@id="posts"]/li//img[ not(ancestor::li[contains(@class,"photo")]) ]', $x->document);
     foreach ($images as $k => $v) {
         $u = $v->getAttribute('src');
         if (!preg_match('%^http:\\/\\/(media|data|assets)\\.tumblr\\.com%i', (string) $u)) {
             $v->setAttribute('xOriginalsrc', $u);
             $v->setAttribute('src', '');
         }
     }
     $posts = array();
     foreach ($paragraphes as $k => $paragraph) {
         $posts[] = $p = new Post($x, $paragraph);
         $p->getPostInfo();
     }
     $this->posts = $posts;
 }
Ejemplo n.º 4
0
 protected function threadParse($raw)
 {
     $xml = new SimpleXMLElement($raw);
     $json = $xml->json;
     $html = $this->ampsfix($xml->html);
     $dom = new DOMDocument();
     @$dom->loadHTML($html);
     $dom->normalizeDocument();
     $xpath = new DOMXPath($dom);
     $array = [];
     $imgs = $xpath->evaluate('/html/body//div/div/div/table/tr/td/div/table/tr/td/table/tr/td/div/img');
     $i = 0;
     foreach ($imgs as $img) {
         $t = explode('?', $img->getAttribute('src'));
         $array[$i]['user']['avatar'] = $t[0];
         $i++;
     }
     $ppl = $xpath->evaluate('/html/body//div/div/div/table/tr/td/div/table/tr/td/table/tr/td/div/span/a');
     $i = 0;
     foreach ($ppl as $pp) {
         $t = $pp->nodeValue;
         $array[$i]['user']['name'] = $t;
         $i++;
     }
     return $array;
 }
Ejemplo n.º 5
0
function NewDocRequest($order_id)
{
    global $customer_id, $abo_id;
    FB::info('NewDocRequest Nummer' . $abo_id);
    if (SOAP_SERVER != '') {
        $client = new SoapClient(null, array('location' => SOAP_SERVER, 'uri' => SOAP_NAMESPACE, 'trace' => true, 'connection_timeout' => 5));
        $response = $client->__doRequest('<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://test" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
		  <SOAP-ENV:Body>
			<NewDocRequest xmlns="test">
				<Nummer>' . $abo_id . '</Nummer>
				<Soort>B</Soort>
				<Weborder>' . $order_id . '</Weborder>
			</NewDocRequest>
		  </SOAP-ENV:Body>
		</SOAP-ENV:Envelope>', SOAP_SERVER, SOAP_NAMESPACE, SOAP_1_2);
        if ($response) {
            $dom = new DOMDocument();
            $dom->loadXML($response);
            $xPath = new DOMXPath($dom);
            $result = array();
            if ($xPath->evaluate("//Status")->item(0)->nodeValue == 0) {
                $result = $xPath->evaluate("//StatusTekst")->item(0)->nodeValue;
            } else {
                $result = $xPath->evaluate("//Document")->item(0)->nodeValue;
            }
        }
    }
    return $result;
}
Ejemplo n.º 6
0
 private function discourse($volume, $discourse)
 {
     $this->Discourse =& ClassRegistry::init('Discourse');
     $volume = str_pad((int) $volume, 2, "0", STR_PAD_LEFT);
     $discourse = str_pad($discourse, 2, "0", STR_PAD_LEFT);
     App::import('Core', array('Xml', 'HttpSocket'));
     $this->Http =& new HttpSocket();
     $url = "http://scriptures.byu.edu/gettalk.php?vol={$volume}&disc={$discourse}";
     $html = $this->Http->get($url);
     if (strpos($html, 'file_get_contents') !== false) {
         return false;
     }
     $dom = new DOMDocument();
     @$dom->loadHTML($html);
     $xpath = new DOMXPath($dom);
     $start_page = (int) $xpath->evaluate('//a[@name][1]')->item(0)->getAttribute('name');
     $column_anchors = $xpath->evaluate('//a[@name]');
     $end_page = (int) $column_anchors->item($column_anchors->length - 1)->getAttribute('name');
     $title = clean_string(find_content($xpath, '//div[@class="title"]'));
     $subtitle = find_content($xpath, '//div[@class="subtitle"]');
     $reported_by = clean_string(find_content($xpath, '//div[@class="reportedBy"]'));
     $page_header = clean_string(find_content($xpath, '//div[@class="pageHeader"]'));
     $speaker = clean_string(find_content($xpath, '//div[@class="speaker"]'));
     $date = prepare_date(find_content($xpath, '//div[@class="date"]'));
     $content = find_content($xpath, '//div[@class="discourseBody"]');
     $this->Discourse->create();
     $this->Discourse->save(array('volume' => $volume, 'start_page' => $start_page, 'end_page' => $end_page, 'title' => $title, 'subtitle' => $subtitle, 'reported_by' => $reported_by, 'page_header' => $page_header, 'speaker' => $speaker, 'date' => $date, 'subtitle' => $subtitle, 'content' => $content));
     return true;
 }
Ejemplo n.º 7
0
 public function getDate()
 {
     $date_string = $this->xpath->evaluate("string(pubDate)", $this->element);
     $unix_time = strtotime($date_string);
     $date = new SwatDate();
     $date->setTimestamp($unix_time);
     $date->toUTC();
     return $date;
 }
Ejemplo n.º 8
0
function GetStockMaat($product_id, $maat, $data)
{
    if (SOAP_SERVER != '') {
        $get_model_query = tep_db_query("select products_model, products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . (int) $product_id . "'");
        $get_model = tep_db_fetch_array($get_model_query);
        $client = new SoapClient(null, array('location' => SOAP_SERVER, 'uri' => SOAP_NAMESPACE, 'trace' => true, 'connection_timeout' => 5));
        $response = $client->__doRequest('<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://test" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
		  <SOAP-ENV:Body>
			<ns1:stockRequest>
			  <Artikel>' . $get_model['products_model'] . '</Artikel>
			  <Maat>' . $maat . '</Maat>
			</ns1:stockRequest>
		  </SOAP-ENV:Body>
		</SOAP-ENV:Envelope>', SOAP_SERVER, SOAP_NAMESPACE, SOAP_1_2);
        if ($response) {
            $dom = new DOMDocument();
            $dom->loadXML($response);
            $xPath = new DOMXPath($dom);
            if ($xPath->evaluate("//Status")->item(0)->nodeValue == 0) {
                $result = $xPath->evaluate("//StatusTekst")->item(0)->nodeValue;
            } else {
                //Article contains XML inside, need to reparse it
                $dom->loadXML('<xml>' . $xPath->evaluate("//Artikel")->item(0)->nodeValue . '</xml>');
                $xPath = new DOMXPath($dom);
                $elements = $xPath->evaluate("//xml/*");
                if ($maat == '') {
                    foreach ($elements as $element) {
                        if ($element->nodeName == 'Maten') {
                            continue;
                        }
                        if ($element->nodeName == $data) {
                            $result .= $element->nodeValue . ' ';
                        }
                    }
                } else {
                    $maats = $xPath->evaluate("//xml/Maten/Maat");
                    if ($maats->length > 0) {
                        foreach ($maats as $maat) {
                            $elements = $xPath->evaluate("child::*", $maat);
                            foreach ($elements as $element) {
                                if ($element->nodeName == $data) {
                                    $result .= $element->nodeValue;
                                }
                            }
                        }
                    }
                }
            }
        } else {
            tep_mail('ABO Service Monitor', '*****@*****.**', 'SOAP Server offline', 'De SOAP Server op ' . STORE_NAME . ' - ' . HTTP_SERVER . ' is offline', STORE_NAME, STORE_OWNER_EMAIL_ADDRESS);
            $result .= $get_model['products_quantity'];
        }
    } else {
        $result = 'No SOAP server defined. Please check configuration';
    }
    return $result;
}
Ejemplo n.º 9
0
 /**
  * Construct the Send object by parsing the XML.
  * @param xml_doc the DOM XML document
  * @exception if the response is not valid
  */
 public function __construct(\DOMDocument $xml_doc)
 {
     parent::__construct($xml_doc);
     $xpath = new \DOMXPath($xml_doc);
     $this->message_id = $xpath->evaluate('/response/message_id')->item(0)->nodeValue;
     $this->hash = $xpath->evaluate('/response/hash')->item(0)->nodeValue;
     if (!isset($this->message_id, $this->hash)) {
         throw new \Exception('An error occured while parsing the XML data for the SEND call');
     }
 }
Ejemplo n.º 10
0
 public function testAssertEqualXMLStructure()
 {
     $doc = new DOMDocument();
     $doc->loadXML('<root><label>text content</label></root>');
     $xpath = new DOMXPath($doc);
     $labelElement = $doc->getElementsByTagName('label')->item(0);
     $this->assertEquals(1, $xpath->evaluate('count(//label[text() = "text content"])'));
     $expectedElmt = $doc->createElement('label', 'text content');
     $this->assertEqualXMLStructure($expectedElmt, $labelElement);
     // the following assertion fails, even though it passed before - which is due to the assertEqualXMLStructure() has modified the $labelElement
     $this->assertEquals(1, $xpath->evaluate('count(//label[text() = "text content"])'));
 }
Ejemplo n.º 11
0
 /**
  * Construct the Setopt object by parsing the XML.
  * @param xml_doc the DOM XML document
  * @exception if the response is not valid
  */
 public function __construct(\DOMDocument $xml_doc)
 {
     parent::__construct($xml_doc);
     $xpath = new \DOMXPath($xml_doc);
     $this->campaign_id = $xpath->evaluate('/response/campaign/@id')->item(0)->nodeValue;
     $this->campaign_status_code = $xpath->evaluate('/response/campaign/status/@code')->item(0)->nodeValue;
     $this->campaign_status = $xpath->evaluate('/response/campaign/status')->item(0)->nodeValue;
     $this->number = $xpath->evaluate('/response/number')->item(0)->nodeValue;
     if (!isset($this->campaign_id, $this->campaign_status_code, $this->campaign_status, $this->number)) {
         throw new \Exception('An error occured while parsing the XML data for the SETOPT call.');
     }
 }
Ejemplo n.º 12
0
 public static function baseFromHTML($doc, $htmlURL)
 {
     $xpath = new DOMXPath($doc);
     $xpath->registerNamespace('xhtml', 'http://www.w3.org/1999/xhtml');
     if ($url = $xpath->evaluate('string(//head/base/@href)')) {
         return $url;
     }
     if ($url = $xpath->evaluate('string(//xhtml:head/xhtml:base/@href)')) {
         return $url;
     }
     return $htmlURL;
 }
Ejemplo n.º 13
0
 public static function parser($url)
 {
     self::checkUrl($url);
     $dom = new DOMDocument();
     @$dom->loadHTMLFile($url);
     $xpath = new DOMXPath($dom);
     $arrEntry = array();
     foreach ($xpath->query('//table[@id="ranking_table"]/tr') as $node) {
         $arrEntry[] = ['rank' => (int) str_replace(array("位"), "", $xpath->evaluate('normalize-space(td[1]/div/strong)', $node)), 'work' => ['title' => $xpath->evaluate('normalize-space(td[3]/dl[@class="work_1col"]/dt[@class="work_name"]/a)', $node), 'url' => $xpath->evaluate('normalize-space(td[3]/dl[@class="work_1col"]/dt[@class="work_name"]/a/@href)', $node), 'thumbnail_url' => "http:" . $xpath->evaluate('normalize-space(td[2]/div/a/img/@src)', $node), 'price' => $xpath->evaluate('normalize-space(td[3]/dl[@class="work_1col"]/dd[@class="work_price"])', $node), 'description' => $xpath->evaluate('normalize-space(td[3]/dl[@class="work_1col"]/dd[@class="work_text"])', $node), 'genre' => self::convertNodesToNodeValueArray($xpath->query('td[3]/dl[@class="work_1col"]/dd[@class="work_genre"]//span', $node)), 'date' => str_replace(array("販売日: "), "", $xpath->evaluate('normalize-space(td[4]/ul[1]/li[1])', $node)), 'download_count' => (int) $xpath->evaluate('normalize-space(td[4]/ul[2]/li[1]/div/span)', $node)], 'maker' => ['title' => $xpath->evaluate('normalize-space(td[3]/dl[@class="work_1col"]/dd[@class="maker_name"]/a)', $node), 'url' => $xpath->evaluate('normalize-space(td[3]/dl[@class="work_1col"]/dd[@class="maker_name"]/a/@href)', $node)]];
     }
     return $arrEntry;
 }
Ejemplo n.º 14
0
 /**
  * Construct the Info object by parsing the XML.
  * @param xml_doc the DOM XML document
  * @exception if the response is not valid
  */
 public function __construct(\DOMDocument $xml_doc)
 {
     parent::__construct($xml_doc);
     $xpath = new \DOMXPath($xml_doc);
     $this->number = $xpath->evaluate('/response/number')->item(0)->nodeValue;
     $this->carrier_id = $xpath->evaluate('/response/carrier/@id')->item(0)->nodeValue;
     $this->carrier = $xpath->evaluate('/response/carrier')->item(0)->nodeValue;
     $this->handset_id = $xpath->evaluate('/response/handset/@id')->item(0)->nodeValue;
     $this->handset = $xpath->evaluate('/response/handset')->item(0)->nodeValue;
     if (!isset($this->number, $this->carrier_id, $this->carrier, $this->handset_id, $this->handset)) {
         throw new \Exception("Invalid Info response.");
     }
 }
 public function frontendPrePageResolve($context)
 {
     $document = new DOMDocument();
     $document->load(MANIFEST . '/rewrite.xml');
     $xpath = new DOMXPath($document);
     $url = $_SERVER['REQUEST_URI'];
     if (strpos($url, __SYM_COOKIE_PATH__) == 0) {
         $url = substr($url, strlen(__SYM_COOKIE_PATH__));
     }
     $url = trim($url, '/');
     foreach ($xpath->query('/rewrite/rule') as $rule) {
         $match = $xpath->evaluate('string(match/text())', $rule);
         $case = $xpath->evaluate('boolean(match/@case-sensetive = "yes")', $rule);
         $replace = $xpath->evaluate('string(replace/text())', $rule);
         // Escape slashes:
         $match = str_replace('/', '\\/', $match);
         // Add regexp flags:
         $match = '/' . $match . '/' . ($case ? '' : 'i');
         if (preg_match($match, $url, $matches)) {
             $bits = preg_split('/(\\\\[0-9]+)/', $replace, 0, PREG_SPLIT_DELIM_CAPTURE);
             $redirect = '';
             foreach ($bits as $bit) {
                 if (preg_match('/^\\\\[0-9]+$/', $bit)) {
                     $index = (int) trim($bit, '\\');
                     if (isset($matches[$index])) {
                         $redirect .= $matches[$index];
                     }
                     continue;
                 }
                 $redirect .= $bit;
             }
             break;
         }
     }
     // Found a new URL:
     if (isset($redirect)) {
         $url = parse_url($redirect);
         $symphony_page = trim($url['path'], '/');
         $query_string = $url['query'] . '&symphony-page=' . $symphony_page;
         $query_array = $this->parseQueryString($query_string);
         $context['page'] = '/' . $symphony_page . '/';
         $_SERVER['QUERY_STRING'] = $query_string;
         $_GET = $query_array;
         // Set headers
         foreach ($xpath->query('header', $rule) as $header) {
             $name = $header->getAttribute('name');
             $value = $header->getAttribute('value');
             self::$headers[$name] = $value;
         }
     }
 }
Ejemplo n.º 16
0
 /**
  * Construct the Response object by parsing the XML.
  * @param xml_doc the DOM XML document
  * @exception if the response is not valid
  */
 protected function __construct(\DOMDocument $xml_doc)
 {
     $this->xml_doc = $xml_doc;
     $xpath = new \DOMXPath($this->xml_doc);
     $this->response_status = $xpath->evaluate('/response/@status')->item(0)->nodeValue;
     $this->response_code = $xpath->evaluate('/response/@code')->item(0)->nodeValue;
     $this->message = $xpath->evaluate('/response/message')->item(0)->nodeValue;
     if (!isset($this->response_code, $this->response_status, $this->message)) {
         throw new \Exception('An error occured while getting the response code, status and message.');
     }
     if (!$this->responseIsValid()) {
         throw new \Exception("The response is not valid - {$this->message} (code {$this->response_code})");
     }
 }
Ejemplo n.º 17
0
function get_links($targetUrl, $depth)
{
    global $urls, $linkFilter, $frameDepth, $actualFrameDepth;
    if (!$targetUrl) {
        return;
    }
    if ($frameDepth - $depth > $actualFrameDepth) {
        $actualFrameDepth = $frameDepth - $depth;
    }
    $html = file_get_contents($targetUrl);
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    $bases = $xpath->evaluate("/html/head//base");
    if ($bases->length > 0) {
        $baseItem = $bases->item($bases->length - 1);
        $base = $baseItem->getAttribute('href');
    } else {
        $base = $targetUrl;
    }
    if ($depth > 0) {
        $frames = $xpath->evaluate("/html/body//iframe");
        for ($i = 0; $i < $frames->length; $i++) {
            $frame = $frames->item($i);
            $url = make_absolute($frame->getAttribute('src'), $base);
            if ($url != $targetUrl) {
                get_links($url, $depth - 1);
            }
        }
        $frames = $xpath->evaluate("/html/body//frame");
        for ($i = 0; $i < $frames->length; $i++) {
            $frame = $frames->item($i);
            $url = make_absolute($frame->getAttribute('src'), $base);
            if ($url != $targetUrl) {
                get_links($url, $depth - 1);
            }
        }
    }
    $hrefs = $xpath->evaluate("/html/body//a");
    for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');
        $absolute = make_absolute($url, $base);
        if (preg_match("@" . $linkFilter . "@i", parse_url($absolute, PHP_URL_PATH))) {
            array_push($urls, $absolute);
        }
    }
}
Ejemplo n.º 18
0
 public function run($args)
 {
     if (count($args) != 1) {
         $this->usageError('Please supply the path to fhir-single.xsd');
     }
     $output_dir = Yii::app()->basePath . '/components/fhir_schema';
     system('mkdir -p ' . escapeshellarg($output_dir));
     $doc = new DOMDocument();
     $doc->load($args[0]);
     $xpath = new DOMXPath($doc);
     $xpath->registerNamespace('xs', 'http://www.w3.org/2001/XMLSchema');
     $types = array();
     foreach ($xpath->query('xs:complexType') as $complexType) {
         $type = $complexType->getAttribute('name');
         $types[$type] = array();
         $base = $xpath->evaluate('string(.//xs:extension/@base)', $complexType);
         if ($base && isset($types[$base])) {
             $types[$type] = $types[$base];
         }
         foreach ($xpath->query('.//*[@maxOccurs]', $complexType) as $item) {
             $plural = $item->getAttribute('maxOccurs') != '1';
             if ($item->tagName == 'xs:element') {
                 $elements = array($item);
             } else {
                 $elements = $xpath->query('.//xs:element', $item);
             }
             foreach ($elements as $element) {
                 $el_name = $element->getAttribute('name') ?: $element->getAttribute('ref');
                 $el_type = $element->getAttribute('type') ?: $element->getAttribute('ref');
                 $types[$type][$el_name] = array('type' => $el_type, 'plural' => $plural);
             }
         }
         file_put_contents("{$output_dir}/{$type}.json", json_encode($types[$type], JSON_FORCE_OBJECT));
     }
 }
Ejemplo n.º 19
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     if (!stream_is_local($resource)) {
         throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
     }
     if (!file_exists($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     try {
         $dom = XmlUtils::loadFile($resource);
     } catch (\InvalidArgumentException $e) {
         throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
     }
     $internalErrors = libxml_use_internal_errors(true);
     libxml_clear_errors();
     $xpath = new \DOMXPath($dom);
     $nodes = $xpath->evaluate('//TS/context/name[text()="' . $domain . '"]');
     $catalogue = new MessageCatalogue($locale);
     if ($nodes->length == 1) {
         $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
         foreach ($translations as $translation) {
             $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
             if (!empty($translationValue)) {
                 $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain);
             }
             $translation = $translation->nextSibling;
         }
         $catalogue->addResource(new FileResource($resource));
     }
     libxml_use_internal_errors($internalErrors);
     return $catalogue;
 }
Ejemplo n.º 20
0
    protected function assertMatchesXpath($html, $expression, $count = 1)
    {
        $dom = new \DomDocument('UTF-8');
        try {
            // Wrap in <root> node so we can load HTML with multiple tags at
            // the top level
            $dom->loadXml('<root>'.$html.'</root>');
        } catch (\Exception $e) {
            return $this->fail(sprintf(
                "Failed loading HTML:\n\n%s\n\nError: %s",
                $html,
                $e->getMessage()
            ));
        }
        $xpath = new \DOMXPath($dom);
        $nodeList = $xpath->evaluate('/root'.$expression);

        if ($nodeList->length != $count) {
            $dom->formatOutput = true;
            $this->fail(sprintf(
                "Failed asserting that \n\n%s\n\nmatches exactly %s. Matches %s in \n\n%s",
                $expression,
                $count == 1 ? 'once' : $count . ' times',
                $nodeList->length == 1 ? 'once' : $nodeList->length . ' times',
                // strip away <root> and </root>
                substr($dom->saveHTML(), 6, -8)
            ));
        }
    }
Ejemplo n.º 21
0
 /**
  * @param Set    $set
  * @param string $path
  */
 public function __construct(Set $set, $path)
 {
     $this->set = $set;
     $this->path = $path;
     $this->dom = new \DOMDocument();
     $this->dom->load($path);
     $xpath = new \DOMXPath($this->dom);
     $xpath->registerNamespace('link', 'http://www.xbrl.org/2003/linkbase');
     $xpath->registerNamespace('linkbase', 'http://www.xbrl.org/2003/linkbase');
     $lls = array();
     /** @var $element \DOMElement */
     foreach ($xpath->evaluate('//link:linkbase/*') as $element) {
         switch ($element->nodeName) {
             case 'labelLink':
                 $lls[] = new Label\Link($this, $element);
                 break;
             case 'referenceLink':
                 $lls[] = new Reference\Link($this, $element);
                 break;
             case 'presentationLink':
                 $lls[] = new Presentation\Link($this, $element);
                 break;
             case 'calculationLink':
                 $lls[] = new Calculation\Link($this, $element);
                 break;
             case 'definitionLink':
                 $lls[] = new Definition\Link($this, $element);
                 break;
         }
     }
     $this->links = $lls;
 }
Ejemplo n.º 22
0
function get_next_url($url, $bannedurls, $visitedurls)
{
    $nexturls = array();
    $html = file_get_contents($url);
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    // grab all the on the page
    $xpath = new DOMXPath($dom);
    $hrefs = $xpath->evaluate("/html/body//a");
    for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');
        if (substr($url, 0, 1) === '/') {
            if (!in_array($url, $bannedurls)) {
                array_push($nexturls, $url);
            }
        }
    }
    array_unique($nexturls);
    $newnexturls = array();
    foreach ($nexturls as &$value) {
        if (strstr($value, '/torrent/')) {
            array_push($newnexturls, $value);
        }
    }
    if ($newnexturls) {
        $nexturls = array_merge($newnexturls, $nexturls);
    }
    shuffle($nexturls);
    // Mix it up a bit. ;-)
    return $nexturls;
}
Ejemplo n.º 23
0
 /** 
  * Function sets error messages to $respErrorsList. 
  * @access private
  * @return boolean true if xml document has error tag, false if it hasn't.
  */
 private function setResponseErrors()
 {
     $errors = $this->xpath->evaluate("/error");
     foreach ($errors as $e => $error) {
         $this->respErrorsList[$e] = array("code" => $this->xpath->evaluate(".//code")->item($e)->nodeValue, "message" => $this->xpath->evaluate(".//message")->item($e)->nodeValue);
     }
 }
function xsl_transform($filename, $xslname = null)
{
    // Get the original XML document
    $xml = new DOMDocument();
    $xml->load($filename);
    if ($xslname == null) {
        // extract bound stylesheet from embedded link
        $xp = new DOMXPath($xml);
        // use xpath to get the directive
        $pi = $xp->evaluate('/processing-instruction("xml-stylesheet")')->item(0);
        // extract the "data" part of it
        $data = $pi->data;
        // find out where the href starts
        $start = strpos($data, 'href=');
        // and extract the stylesheet name
        $xslname = XML_FOLDER . substr($data, $start + 6, -1);
    }
    // load the XSL stylesheet
    $xsl = new DOMDocument();
    $xsl->load($xslname);
    // prime the transform engine
    $xslt = new XSLTProcessor();
    $xslt->importStyleSheet($xsl);
    // and away we go!
    return $xslt->transformToXml($xml);
}
Ejemplo n.º 25
0
Archivo: db.php Proyecto: alakim/arundo
 function getXNode($query)
 {
     $xpath = new DOMXPath($this->xmlDoc);
     $dbNode = $this->xmlDoc->getElementsByTagName('db')->item(0);
     $nodes = $xpath->evaluate($query, $dbNode);
     return $nodes->item(0);
 }
    /**
     * Convert dom node tree to array
     *
     * @param \DOMDocument $source
     * @return array
     * @throws \InvalidArgumentException
     */
    public function convert($source)
    {
        $output = [];
        $xpath = new \DOMXPath($source);
        $views = $xpath->evaluate('/config/view');
        /** @var $viewNode \DOMNode */
        foreach ($views as $viewNode) {
            $data = [];
            $viewId = $this->getAttributeValue($viewNode, 'id');
            $data['view_id'] = $viewId;
            $data['action_class'] = $this->getAttributeValue($viewNode, 'class');
            $data['group'] = $this->getAttributeValue($viewNode, 'group');
            $data['subscriptions'] = [];

            /** @var $childNode \DOMNode */
            foreach ($viewNode->childNodes as $childNode) {
                if ($childNode->nodeType != XML_ELEMENT_NODE) {
                    continue;
                }

                $data = $this->convertChild($childNode, $data);
            }
            $output[$viewId] = $data;
        }
        return $output;
    }
Ejemplo n.º 27
0
 protected function assertPaginationWorks()
 {
     // get next page
     $href = $this->xpath->evaluate("string(/atom:feed/atom:link[@rel='next']/@href)");
     $this->assertNotEquals('', $href, 'No next link present in paginated feed.');
     // load next page
     $this->load($href);
     $this->assertNoErrors();
     // get last page
     $href = $this->xpath->evaluate("string(/atom:feed/atom:link[@rel='last']/@href)");
     $this->assertNotEquals('', $href, 'No last link present in paginated feed');
     // load last page
     $this->load($href);
     $this->assertNoErrors();
     // make sure there is no next page
     $list = $this->xpath->query("/atom:feed/atom:link[@rel='next']");
     $this->assertEquals(0, $list->length, 'Last page in feed contains a next link.');
     // get prev page
     $href = $this->xpath->evaluate("string(/atom:feed/atom:link[@rel='previous']/@href)");
     $this->assertNotEquals('', $href, 'No prev link present on last page of paginated feed.');
     // load prev page
     $this->load($href);
     $this->assertNoErrors();
     // get first page
     $href = $this->xpath->evaluate("string(/atom:feed/atom:link[@rel='first']/@href)");
     $this->assertNotEquals('', $href, 'No first link present in paginated feed.');
     // load first page
     $this->load($href);
     $this->assertNoErrors();
 }
Ejemplo n.º 28
0
 public function getSRank($domain)
 {
     $xml = '<?xml version="1.0" encoding="UTF-8"?><methodCall><methodName>getRank</methodName><params><param><value><string>0</string></value></param><param><value><string>' . htmlspecialchars($domain) . '</string></value></param><param><value><i4>0</i4></value></param></params></methodCall>';
     $request = "POST /RPC2 HTTP/1.1\r\n";
     $request .= "Host: srank.seznam.cz\r\n";
     $request .= "Content-Type: text/xml\r\n";
     $request .= "Content-Length: " . strlen($xml) . "\r\n";
     $request .= "Connection: Close\r\n\r\n";
     $request .= $xml;
     $errNo = $errStr = '';
     $socket = fsockopen('srank.seznam.cz', 80, $errNo, $errStr, 10);
     if ($socket === FALSE) {
         return -1;
     }
     fwrite($socket, $request);
     $response = '';
     while (!feof($socket)) {
         $response .= fgets($socket, 1024);
     }
     $response = preg_replace('/^(.+\\r\\n)+\\r\\n/', '', $response);
     $doc = new DOMDocument();
     if (!$doc->loadXml($response)) {
         return -1;
     }
     $xpath = new DOMXPath($doc);
     $result = $xpath->evaluate('string(//member[name = "rank"]/value)');
     if (!is_numeric($result)) {
         return -1;
     }
     $rank = round((int) $result * 100 / 255 / 10);
     return $rank;
 }
Ejemplo n.º 29
0
 /**
  * Convert dom node tree to array
  *
  * @param \DOMDocument $source
  * @return array
  * @throws \InvalidArgumentException
  */
 public function convert($source)
 {
     $output = [];
     $xpath = new \DOMXPath($source);
     $indexers = $xpath->evaluate('/config/indexer');
     /** @var $typeNode \DOMNode */
     foreach ($indexers as $indexerNode) {
         $data = [];
         $indexerId = $this->getAttributeValue($indexerNode, 'id');
         $data['indexer_id'] = $indexerId;
         $data['primary'] = $this->getAttributeValue($indexerNode, 'primary');
         $data['view_id'] = $this->getAttributeValue($indexerNode, 'view_id');
         $data['action_class'] = $this->getAttributeValue($indexerNode, 'class');
         $data['title'] = '';
         $data['description'] = '';
         /** @var $childNode \DOMNode */
         foreach ($indexerNode->childNodes as $childNode) {
             if ($childNode->nodeType != XML_ELEMENT_NODE) {
                 continue;
             }
             /** @var $childNode \DOMElement */
             $data = $this->convertChild($childNode, $data);
         }
         $output[$indexerId] = $data;
     }
     return $output;
 }
Ejemplo n.º 30
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     if (!stream_is_local($resource)) {
         throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
     }
     if (!file_exists($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     $dom = new \DOMDocument();
     $current = libxml_use_internal_errors(true);
     if (!@$dom->load($resource, defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0)) {
         throw new InvalidResourceException(implode("\n", $this->getXmlErrors()));
     }
     $xpath = new \DOMXPath($dom);
     $nodes = $xpath->evaluate('//TS/context/name[text()="' . $domain . '"]');
     $catalogue = new MessageCatalogue($locale);
     if ($nodes->length == 1) {
         $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
         foreach ($translations as $translation) {
             $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
             if (!empty($translationValue)) {
                 $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain);
             }
             $translation = $translation->nextSibling;
         }
         $catalogue->addResource(new FileResource($resource));
     }
     libxml_use_internal_errors($current);
     return $catalogue;
 }