/** * @param string $url * @param string $method * @param string $body * * @return FhirResponse */ public function request($url, $method = 'GET', $body = null) { $server_name = null; foreach ($this->servers as $name => $server) { if (substr($url, 0, strlen($server['base_url']))) { $server_name = $name; break; } } $this->applyServerConfig($server_name ? $this->servers[$server_name] : array()); $this->http_client->setUri($url); $this->http_client->setMethod($method); if ($body) { $this->http_client->setRawData($body, 'application/xml+fhir; charset=utf-8'); } $response = $this->http_client->request(); $this->http_client->resetParameters(); if ($body = $response->getBody()) { $use_errors = libxml_use_internal_errors(true); $value = Yii::app()->fhirMarshal->parseXml($body); $errors = libxml_get_errors(); libxml_use_internal_errors($use_errors); if ($errors) { throw new Exception("Error parsing XML response from {$method} to {$url}: " . print_r($errors, true)); } } else { $value = null; } return new FhirResponse($response->getStatus(), $value); }
/** * Method to test the value. * * @param JXMLElement &$element The JXMLElement object representing the <field /> tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * @param JRegistry &$input An optional JRegistry object with the entire data set to validate against the entire form. * @param object &$form The form object for which the field is being tested. * * @return boolean True if the value is valid, false otherwise. * * @since 11.1 * @throws JException on invalid rule. */ public function test(&$element, $value, $group = null, &$input = null, &$form = null) { if (empty($value)) { return true; } // compatibility workaround: in some environments XML document is // saved with all "<styles>" element opening tags replaced with // "<s-tyles>". We allow this replace (as it can be DB security // concerned: looks like an HTML element <style...) and do not // report error. Later the original element syntax will be restored $value = str_replace('<s-tyles>', '<styles>', $value); // now XML document should be valid jimport('joomla.utilities.xmlelement'); libxml_use_internal_errors(true); $xml = simplexml_load_string($value, 'JXMLElement'); if ($xml === false) { $errors = array(JText::_('MOD_SMARTCDPRO_ERROR_DIGITS_XML_ERROR')); foreach (libxml_get_errors() as $error) { $errors[] = 'XML: ' . $error->message; } $element['message'] = implode('<br />', $errors); return false; } $field = $xml->getName(); if ($field != 'config') { $element['message'] = JText::_('MOD_SMARTCDPRO_ERROR_DIGITS_XML_CONFIG_MISSING'); return false; } if (!$xml->xpath('//digit[@scope="*"]')) { $element['message'] = JText::_('MOD_SMARTCDPRO_ERROR_DIGITS_XML_DEFAULT_DIGIT_MISSING'); return false; } $element['message'] = ''; return true; }
public function testLoadFileWithInternalErrorsEnabled() { libxml_use_internal_errors(true); $this->assertSame(array(), libxml_get_errors()); $this->assertInstanceOf('DOMDocument', XmlUtils::loadFile(__DIR__ . '/../Fixtures/Util/invalid_schema.xml')); $this->assertSame(array(), libxml_get_errors()); }
public function onRenderProductListBefore(FilterResponseEvent $event) { $app = $this->app; $request = $event->getRequest(); $response = $event->getResponse(); $id = $request->query->get('category_id'); // category_idがない場合、レンダリングを変更しない if (is_null($id)) { return; } $CategoryContent = $app['category_content.repository.category_content']->find($id); // 登録がない、もしくは空で登録されている場合、レンダリングを変更しない if (is_null($CategoryContent) || $CategoryContent->getContent() == '') { return; } // 書き換えhtmlの初期化 $html = $response->getContent(); libxml_use_internal_errors(true); $dom = new \DOMDocument(); $dom->loadHTML('<?xml encoding="UTF-8">' . $html); $dom->encoding = "UTF-8"; $dom->formatOutput = true; // 挿入対象を取得 $navElement = $dom->getElementById('page_navi_top'); if (!$navElement instanceof \DOMElement) { return; } $template = $dom->createDocumentFragment(); $template->appendXML(htmlspecialchars($CategoryContent->getContent())); $node = $dom->importNode($template, true); $navElement->insertBefore($node); $newHtml = html_entity_decode($dom->saveHTML(), ENT_NOQUOTES, 'UTF-8'); $response->setContent($newHtml); $event->setResponse($response); }
function search($search, $language = 'en', $rpp = '10') { $return = array(); $item = array(); $feedUrl = "http://search.twitter.com/search.atom?q=" . urlencode($search) . "&lang={$language}&rpp={$rpp}"; libxml_use_internal_errors(true); $sxml = simplexml_load_file($feedUrl); if ($sxml && !empty($sxml->entry)) { foreach ($sxml->entry as $node) { $attrs_0 = $node->link[0]->attributes(); $attrs_1 = $node->link[1]->attributes(); $datePublished = strtotime($node->published); $author = explode(' ', $node->author[0]->name); $content = htmlentities($node->content); $item["id"] = $attrs_0['href']; $item["published"] = date("Y-m-d H:i:s", $datePublished); $item["content"] = $node->title; $item["thumbnail"] = $attrs_1['href']; $item["title"] = $node->title; $item["author"] = $node->author[0]->name; $item["rating"] = calculateDatarowRating(formatTag($search), $node->title, $author[0]); $return[] = $item; } } else { $this->log('Unable to parse twitter XML.'); } return $return; }
/** * @inheritdoc */ protected function doLoad($file) { libxml_use_internal_errors(true); $xml = new \DOMDocument(); $xml->load($file); if (!$xml->schemaValidate(__DIR__ . DIRECTORY_SEPARATOR . "XML" . DIRECTORY_SEPARATOR . "configuration.xsd")) { libxml_clear_errors(); throw MigrationException::configurationNotValid('XML configuration did not pass the validation test.'); } $xml = simplexml_load_file($file, "SimpleXMLElement", LIBXML_NOCDATA); $config = []; if (isset($xml->name)) { $config['name'] = (string) $xml->name; } if (isset($xml->table['name'])) { $config['table_name'] = (string) $xml->table['name']; } if (isset($xml->table['column'])) { $config['column_name'] = (string) $xml->table['column']; } if (isset($xml->{'migrations-namespace'})) { $config['migrations_namespace'] = (string) $xml->{'migrations-namespace'}; } if (isset($xml->{'organize-migrations'})) { $config['organize_migrations'] = $xml->{'organize-migrations'}; } if (isset($xml->{'migrations-directory'})) { $config['migrations_directory'] = $this->getDirectoryRelativeToFile($file, (string) $xml->{'migrations-directory'}); } if (isset($xml->migrations->migration)) { $config['migrations'] = $xml->migrations->migration; } $this->setConfiguration($config); }
/** * Class constructor initialises the SimpleXML object and sets a few properties. * @param string $filepath Optional filespec for the XML file to use. Will use default otherwise. * @throws \Exception If the XML is invalid. */ public function __construct($filepath = null) { if (empty($filepath)) { if (defined('nZEDb_VERSIONS')) { $filepath = nZEDb_VERSIONS; } } if (!file_exists($filepath)) { throw new \RuntimeException("Versions file '{$filepath}' does not exist!'"); } $this->_filespec = $filepath; $this->out = new \ColorCLI(); $this->git = new Git(); $temp = libxml_use_internal_errors(true); $this->_xml = simplexml_load_file($filepath); libxml_use_internal_errors($temp); if ($this->_xml === false) { if (Utility::isCLI()) { $this->out->error("Your versions XML file ({nZEDb_VERSIONS}) is broken, try updating from git."); } throw new \Exception("Failed to open versions XML file '{$filepath}'"); } if ($this->_xml->count() > 0) { $vers = $this->_xml->xpath('/nzedb/versions'); if ($vers[0]->count() == 0) { $this->out->error("Your versions XML file ({nZEDb_VERSIONS}) does not contain version info, try updating from git."); throw new \Exception("Failed to find versions node in XML file '{$filepath}'"); } else { $this->out->primary("Your versions XML file ({nZEDb_VERSIONS}) looks okay, continuing."); $this->_vers =& $this->_xml->versions; } } else { throw new \RuntimeException("No elements in file!\n"); } }
public function __construct() { $this->rssStream = null; $this->rss = null; //disable XML error libxml_use_internal_errors(true); }
/** * private function that generalizes parsing * @param $string * @param null $names * @return array */ private static function parse($string, $names = NULL) { $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($string); $metas = $dom->getElementsByTagName('meta'); $metaArray = array(); if ($names == NULL) { foreach ($metas as $meta) { $nameKey = $meta->getAttribute('name'); $contentValue = $meta->getAttribute('content'); $metaArray["{$nameKey}"] = $contentValue; } } else { foreach ($names as $name) { foreach ($metas as $meta) { if ($name === $meta->getAttribute('name')) { $nameKey = $meta->getAttribute('name'); $contentValue = $meta->getAttribute('content'); $metaArray["{$nameKey}"] = $contentValue; } } } } return $metaArray; }
/** * Parse the given file for apprentices and mentors. * * @param string $file Path to the File to parse. * * @return array */ public function parse($file) { $return = array('mentors' => array(), 'apprentices' => array()); $content = file_Get_contents($file); $content = str_Replace('<local-time', '<span tag="local-time"', $content); $content = str_Replace('</local-time', '</span', $content); $content = str_Replace('<time', '<span tag="time"', $content); $content = str_Replace('</time', '</span', $content); $this->dom = new \DomDocument('1.0', 'UTF-8'); $this->dom->strictErrorChecking = false; libxml_use_internal_errors(true); $this->dom->loadHTML('<?xml encoding="UTF-8" ?>' . $content); libxml_use_internal_errors(false); $xpathMentors = new \DOMXPath($this->dom); $mentors = $xpathMentors->query('//a[@id="user-content-mentors-currently-accepting-an-apprentice"]/../following-sibling::ul[1]/li'); foreach ($mentors as $mentor) { $user = $this->parseUser($mentor); if (!$user) { continue; } $user['type'] = 'mentor'; $return['mentors'][] = $user; } $xpathApprentices = new \DOMXPath($this->dom); $apprentices = $xpathApprentices->query('//a[@id="user-content-apprentices-currently-accepting-mentors"]/../following-sibling::ul[1]/li'); foreach ($apprentices as $apprentice) { $user = $this->parseUser($apprentice); if (!$user) { continue; } $user['type'] = 'apprentice'; $return['apprentices'][] = $user; } return $return; }
function parseHtml() { //$this->_html = str_replace("<!DOCTYPE html>", "", $this->_html); /* $p = xml_parser_create(); xml_parse_into_struct($p, $this->_html, $vals, $index); xml_parser_free($p); echo "Index array\n"; pr($index); echo "\nVals array\n"; pr($vals); die; */ /* $this->_html = str_replace("<!DOCTYPE html>", "", $this->_html); $__data = new SimpleXMLElement($this->_html); pr($__data); die; */ $dom = new DOMDocument(); //echo htmlentities($this->_html); die; libxml_use_internal_errors(true); //$this->_html = str_replace("<!DOCTYPE html>", "", $this->_html); //$this->_html = str_replace("</h1>", "", $this->_html); //echo htmlentities($this->_html); die; //echo htmlentities($this->_html); die; $dom->loadHTML($this->_html); foreach ($dom->getElementsByTagName('img') as $node) { $array[] = $dom->saveHTML($node); } //pr($array); //die; }
public function getXMLData() { $prevVal = libxml_use_internal_errors(true); $data = new \SimpleXMLElement($this->request->getRawData()); libxml_use_internal_errors($prevVal); return $data; }
public function setLaundryState(&$laundryPlace) { $user = '******'; $pass = '******'; try { $client = new Client($laundryPlace['url']); $request = $client->get('/LaundryState', [], ['auth' => [$user, $pass, 'Digest'], 'timeout' => 1.5, 'connect_timeout' => 1.5]); $response = $request->send(); $body = $response->getBody(); libxml_use_internal_errors(true); $crawler = new Crawler(); $crawler->addContent($body); foreach ($crawler->filter('img') as $img) { $resource = $img->getAttribute('src'); $img->setAttribute('src', 'http://129.241.126.11/' . trim($resource, '/')); } $crawler->addHtmlContent('<h1>foobar</h1>'); //'<link href="http://129.241.126.11/pic/public_n.css" type="text/css">'); $laundryPlace['html'] = $crawler->html(); libxml_use_internal_errors(false); preg_match_all('/bgColor=Green/', $body, $greenMatches); preg_match_all('/bgColor=Red/', $body, $redMatches); $laundryPlace['busy'] = count($redMatches[0]); $laundryPlace['available'] = count($greenMatches[0]); } catch (\Exception $e) { $laundryPlace['available'] = self::NETWORK_ERROR; $laundryPlace['busy'] = self::NETWORK_ERROR; $laundryPlace['html'] = self::NETWORK_ERROR; } }
public static function parse($html, $url) { $recipe = RecipeParser_Parser_MicrodataSchema::parse($html, $url); // Turn off libxml errors to prevent mismatched tag warnings. libxml_use_internal_errors(true); $doc = new DOMDocument(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); $doc->loadHTML('<?xml encoding="UTF-8">' . $html); $xpath = new DOMXPath($doc); // Photo -- skip logo if it was used in place of photo if (strpos($recipe->photo_url, "FDC_Logo_vertical.png") !== false || strpos($recipe->photo_url, "FDC_share-logo.png") !== false) { $recipe->photo_url = ''; } if ($recipe->photo_url) { $recipe->photo_url = str_replace("/thumbs/", "/large/", $recipe->photo_url); } // Yield $yield = ''; $nodes = $xpath->query('//*[@class="yield"]'); // Find as 'yield' if ($nodes->length) { $line = $nodes->item(0)->nodeValue; $line = RecipeParser_Text::formatYield($line); $recipe->yield = $line; // Or as number of 'servings' } else { $nodes = $xpath->query('//*[@class="servings"]//*[@class="value"]'); if ($nodes->length) { $line = $nodes->item(0)->nodeValue; $line = RecipeParser_Text::formatYield($line); $recipe->yield = $line; } } return $recipe; }
function openxml($filepath, &$error_str = false) { $xmlstr = @file_get_contents($filepath); if ($xmlstr == false) { $error_str = "failed to open file {$filepath}"; return false; } $options = LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_ERR_NONE | LIBXML_COMPACT; $xmldoc = new DOMDocument(); $xmldoc->strictErrorChecking = false; $xmldoc->recover = true; $old = error_reporting(0); $old_libxml = libxml_use_internal_errors(true); $ret = @$xmldoc->loadXml($xmlstr, $options); if ($ret == false) { $error_str = "failed to load xml from {$filepath}"; return false; } $errors = libxml_get_errors(); if (count($errors) > 0) { foreach ($errors as $error) { if ($error->level == LIBXML_ERR_FATAL) { $error_str = "file: {{$filepath}} line: {$error->line} column: {$error->column}: fatal error: {$error->code}: {$error->message}"; return false; } } } $xml = @simplexml_import_dom($xmldoc); error_reporting($old); libxml_use_internal_errors($old_libxml); return $xml; }
/** * Exclude some html parts by class inside content wrapped with TYPO3SEARCH_begin and TYPO3SEARCH_end * markers. * * @param string $indexableContent HTML markup * @return string HTML */ public function excludeContentByClass($indexableContent) { if (empty(trim($indexableContent))) { return html_entity_decode($indexableContent); } $excludeClasses = $this->getConfiguration()->getIndexQueuePagesExcludeContentByClassArray(); if (count($excludeClasses) === 0) { return html_entity_decode($indexableContent); } $isInContent = Util::containsOneOfTheStrings($indexableContent, $excludeClasses); if (!$isInContent) { return html_entity_decode($indexableContent); } $doc = new \DOMDocument('1.0', 'UTF-8'); libxml_use_internal_errors(true); $doc->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL . $indexableContent); $xpath = new \DOMXPath($doc); foreach ($excludeClasses as $excludePart) { $elements = $xpath->query("//*[contains(@class,'" . $excludePart . "')]"); if (count($elements) == 0) { continue; } foreach ($elements as $element) { $element->parentNode->removeChild($element); } } $html = $doc->saveHTML($doc->documentElement->parentNode); // remove XML-Preamble, newlines and doctype $html = preg_replace('/(<\\?xml[^>]+\\?>|\\r?\\n|<!DOCTYPE.+?>)/imS', '', $html); $html = str_replace(array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $html); return $html; }
public function __construct($strConfigSet = "") { libxml_use_internal_errors(); $this->objSimpleXml = simplexml_load_file(SVN2RSS_PROJECT_ROOT . "/" . SVN2RSS_CONFIG_FILE); $arrParseErrors = libxml_get_errors(); libxml_clear_errors(); if (count($arrParseErrors) > 0) { throw new Svn2RssException("Error parsing xml-config-file " . SVN2RSS_CONFIG_FILE . ".\nErrors:\n" . implode("\n", $arrParseErrors)); } if ($strConfigSet == "") { $strConfigSet = $this->getStrDefaultConfigSet(); } if ($strConfigSet == "") { throw new Svn2RssException("No default config-set defined in " . SVN2RSS_CONFIG_FILE); } //load the config-set requested $this->strConfigSetName = $strConfigSet; foreach ($this->objSimpleXml->configSets->configSet as $objOneConfigSet) { $arrAttributes = $objOneConfigSet->attributes(); if ($arrAttributes->id . "" == $strConfigSet) { $this->objCurrentConfigSetXml = $objOneConfigSet; } } if ($this->objCurrentConfigSetXml == null) { throw new Svn2RssException("Loading of config set " . $strConfigSet . " failed."); } }
/** * Returns array of simple xml objects, where key is a handle name * * @return SimpleXmlElement[] * @throws RuntimeException in case of load error (malformed xml, etc) */ public function load() { $this->validate(); $original = libxml_use_internal_errors(true); $simpleXmlElement = simplexml_load_file($this->filePath); $errors = libxml_get_errors(); libxml_clear_errors(); libxml_use_internal_errors($original); if ($simpleXmlElement === false) { $messages = array(); foreach ($errors as $error) { $messages[] = sprintf('%s, line %s, column %s', trim($error->message), $error->line, $error->column); } throw new RuntimeException(sprintf('File "%s" has a malformed xml structure: %s', $this->filePath, PHP_EOL . implode(PHP_EOL, $messages))); } $stringXml = array(); // First convert all elements to string, // as in xml file can be multiple string with the same handle names foreach ($simpleXmlElement->children() as $key => $element) { if (!isset($stringXml[$key])) { $stringXml[$key] = ''; } foreach ($element->children() as $child) { $stringXml[$key] .= $child->asXml(); } } $result = array(); foreach ($stringXml as $key => $xml) { $result[$key] = simplexml_load_string(sprintf('<%1$s>%2$s</%1$s>', $key, $xml)); } return $result; }
/** * Scan the input for XXE attacks. * * @param string $input * Unsafe input * @param Closure $callback * Callback called to build the dom. * Must be an instance of DomDocument and receives the input as argument * * @return bool|DomDocument False if an XXE attack was discovered, * otherwise the return of the callback */ private static function scanInput($input, Closure $callback) { $isRunningFpm = substr(php_sapi_name(), 0, 3) === 'fpm'; if ($isRunningFpm) { // If running with PHP-FPM and an entity is detected we refuse to parse the feed // @see https://bugs.php.net/bug.php?id=64938 if (strpos($input, '<!ENTITY') !== false) { return false; } } else { $entityLoaderDisabled = libxml_disable_entity_loader(true); } libxml_use_internal_errors(true); $dom = $callback($input); // Scan for potential XEE attacks using ENTITY foreach ($dom->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { if ($child->entities->length > 0) { return false; } } } if ($isRunningFpm === false) { libxml_disable_entity_loader($entityLoaderDisabled); } return $dom; }
/** * Validate XML to be valid for import * @param string $xml * @param WP_Error[optional] $errors * @return bool Validation status */ public static function validateXml(&$xml, $errors = NULL) { if (FALSE === $xml or '' == $xml) { $errors and $errors->add('form-validation', __('WP All Import can\'t read your file.<br/><br/>Probably, you are trying to import an invalid XML feed. Try opening the XML feed in a web browser (Google Chrome is recommended for opening XML files) to see if there is an error message.<br/>Alternatively, run the feed through a validator: http://validator.w3.org/<br/>99% of the time, the reason for this error is because your XML feed isn\'t valid.<br/>If you are 100% sure you are importing a valid XML feed, please contact WP All Import support.', 'wp_all_import_plugin')); } else { PMXI_Import_Record::preprocessXml($xml); if (function_exists('simplexml_load_string')) { libxml_use_internal_errors(true); libxml_clear_errors(); $_x = @simplexml_load_string($xml); $xml_errors = libxml_get_errors(); libxml_clear_errors(); if ($xml_errors) { $error_msg = '<strong>' . __('Invalid XML', 'wp_all_import_plugin') . '</strong><ul>'; foreach ($xml_errors as $error) { $error_msg .= '<li>'; $error_msg .= __('Line', 'wp_all_import_plugin') . ' ' . $error->line . ', '; $error_msg .= __('Column', 'wp_all_import_plugin') . ' ' . $error->column . ', '; $error_msg .= __('Code', 'wp_all_import_plugin') . ' ' . $error->code . ': '; $error_msg .= '<em>' . trim(esc_html($error->message)) . '</em>'; $error_msg .= '</li>'; } $error_msg .= '</ul>'; $errors and $errors->add('form-validation', $error_msg); } else { return true; } } else { $errors and $errors->add('form-validation', __('Required PHP components are missing.', 'wp_all_import_plugin')); $errors and $errors->add('form-validation', __('WP All Import requires the SimpleXML PHP module to be installed. This is a standard feature of PHP, and is necessary for WP All Import to read the files you are trying to import.<br/>Please contact your web hosting provider and ask them to install and activate the SimpleXML PHP module.', 'wp_all_import_plugin')); } } return false; }
/** * Returns an array of search suggestions from the unofficial completion API located * at the endpoint specified in this class. &q=query * * Parses the output into an array of associative arrays with keys of term, volume and * current. "current" is a boolean that determines whether the result in question is the searched * for term. * * @return array|WP_Error WP_Error if something goes wrong. Otherwise, an array as described above. */ public static function get_suggestions($search_term) { $search_term = trim($search_term); if (empty($search_term)) { return new WP_Error('empty_term', __('Please provide a search term.', 'scribeseo')); } $response = wp_remote_get(add_query_arg(array('q' => urlencode($search_term)), self::ENDPOINT)); if (is_wp_error($response)) { return $response; } $result = array(); // turn on user error handing $user_errors = libxml_use_internal_errors(true); $complete_suggestions = simplexml_load_string(wp_remote_retrieve_body($response)); // get any errors $xml_errors = libxml_get_errors(); // restore error handling setting libxml_use_internal_errors($user_errors); if (!empty($xml_errors)) { return new WP_Error('xml_error', __('The XML from the Google Completion API could not be loaded appropriately.', 'scribeseo')); } $complete_suggestions_po = json_decode(json_encode($complete_suggestions)); if (!is_object($complete_suggestions_po) || !isset($complete_suggestions_po->CompleteSuggestion)) { return new WP_Error('xml_error', __('The XML from the Google Completion API could not be loaded appropriately.', 'scribeseo')); } foreach ($complete_suggestions_po->CompleteSuggestion as $suggestion) { $term = $suggestion->suggestion->{'@attributes'}->data; $volume = intval($suggestion->num_queries->{'@attributes'}->int); $volume_nice = number_format_i18n($volume); $current = $term == $search_term; $result[] = compact('term', 'volume', 'volume_nice', 'current'); } return $result; }
public function validate($xml,$schema) { // Enable user error handling libxml_use_internal_errors(true); try { if(empty($xml)) { throw new Exception("You provided an empty XML string"); } $doc = DOMDocument::loadXML($xml); if(!($doc instanceof DOMDocument)){ $this->_errors = libxml_get_errors(); } if(!@$doc->schemaValidate($schema)){ $this->_errors = libxml_get_errors(); } } catch (Exception $e) { $this->_errors = array(0 => array('message'=>$e->getMessage())); } // Disable user error handling & Error Cleanup libxml_use_internal_errors(false); libxml_clear_errors(); // If there are no errors, assume that it is all OK! return empty($this->_errors); }
/** * Strips blacklisted tags and attributes from content. * * See following for blacklist: * https://github.com/ampproject/amphtml/blob/master/spec/amp-html-format.md#html-tags */ public static function strip($content) { if (empty($content)) { return $content; } $blacklisted_tags = self::get_blacklisted_tags(); $blacklisted_attributes = self::get_blacklisted_attributes(); $blacklisted_protocols = self::get_blacklisted_protocols(); $libxml_previous_state = libxml_use_internal_errors(true); $dom = new DOMDocument(); // Wrap in dummy tags, since XML needs one parent node. // It also makes it easier to loop through nodes. // We can later use this to extract our nodes. $result = $dom->loadHTML('<html><body>' . $content . '</body></html>'); libxml_clear_errors(); libxml_use_internal_errors($libxml_previous_state); if (!$result) { return $content; } $body = $dom->getElementsByTagName('body')->item(0); self::strip_tags($body, $blacklisted_tags); self::strip_attributes_recursive($body, $blacklisted_attributes, $blacklisted_protocols); // Only want children of the body tag, since we have a subset of HTML. $out = ''; foreach ($body->childNodes as $node) { $out .= $dom->saveXML($node); } return $out; }
function layerslider_init($atts) { // ID check if (empty($atts['id'])) { return '[LayerSliderWP] ' . __('Invalid shortcode', 'LayerSlider') . ''; } // Get slider $slider = LS_Sliders::find($atts['id']); // Get slider if any if (!$slider || $slider['flag_deleted'] == '1') { return '[LayerSliderWP] ' . __('Slider not found', 'LayerSlider') . ''; } // Slider and markup data $slides = $slider['data']; $id = $slider['id']; $data = ''; // Include slider file if (is_array($slides)) { // Get phpQuery if (!class_exists('phpQuery')) { libxml_use_internal_errors(true); include LS_ROOT_PATH . '/helpers/phpQuery.php'; } include LS_ROOT_PATH . '/config/defaults.php'; include LS_ROOT_PATH . '/includes/slider_markup_init.php'; include LS_ROOT_PATH . '/includes/slider_markup_html.php'; $data = implode('', $data); } // Return data if (get_option('ls_concatenate_output', true)) { $data = trim(preg_replace('/\\s+/u', ' ', $data)); } return $data; }
public function runTest() { libxml_use_internal_errors(true); $xml = XMLReader::open(join(DIRECTORY_SEPARATOR, array($this->directory, $this->fileName))); $xml->setSchema(join(DIRECTORY_SEPARATOR, array($this->directory, $this->xsdFilename))); $this->logger->trace(__METHOD__); $this->logger->info(' XML file to test validity is ' . $this->fileName . 'using XSD file ' . $this->xsdFilename); // You have to parse the XML-file if you want it to be validated $currentReadCount = 1; $validationFailed = false; while ($xml->read() && $validationFailed == false) { // I want to break as soon as file is shown not to be valid // We could allow it to collect a few messages, but I think it's best // to do a manual check once we have discovered the file is not // correct. Speed is really what we want here! if ($currentReadCount++ % Constants::XML_PROCESSESING_CHECK_ERROR_COUNT == 0) { if (count(libxml_get_errors()) > 0) { $validationFailed = true; } } } if (count(libxml_get_errors()) == 0) { $this->testProperty->addTestResult(true); $this->logger->info(' RESULT Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] succeeded'); $this->testProperty->addTestResultDescription('Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] succeeded'); $this->testProperty->addTestResultReportDescription('Filen ' . $this->fileName . ' validerer mot filen' . $this->xsdFilename); } else { $this->testProperty->addTestResult(false); $this->logger->error(' RESULT Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] failed'); $this->testProperty->addTestResultDescription('Validation of [' . $this->fileName . '] against [' . $this->xsdFilename . '] failed'); $this->testProperty->addTestResultReportDescription('Filen ' . $this->fileName . ' validerer ikke mot filen' . $this->xsdFilename); } libxml_clear_errors(); }
/** * Transform asset paths based on the report * * @param $content * @return string * @throws ExtensionNotLoadedException */ public function transformAssetPaths($content) { if (null === $content) { throw new ContentNotFoundException('No content was found to be rendered'); } libxml_use_internal_errors(true); $doc = new \DOMDocument(); $doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES')); $reportRouting = $this->extensionManager->findExtension('report_routing'); if (null === $reportRouting) { throw new ExtensionNotLoadedException('report_routing'); } /* Transform images */ $images = $doc->getElementsByTagName('img'); foreach ($images as $image) { $this->prepareAsset($image, 'src', $reportRouting); } /* Transform styles */ $styles = $doc->getElementsByTagName('link'); foreach ($styles as $style) { $this->prepareAsset($style, 'href', $reportRouting); } /* Transform scripts */ $scripts = $doc->getElementsByTagName('script'); foreach ($scripts as $script) { $this->prepareAsset($script, 'src', $reportRouting); } return $doc->saveHTML(); }
/** * This function attempts to validate an XML string against the specified schema. * * It will parse the string into a DOM document and validate this document against the schema. * * @param string $xml The XML string or document which should be validated. * @param string $schema The schema filename which should be used. * @param boolean $debug To disable/enable the debug mode * * @return string | DOMDocument $dom string that explains the problem or the DOMDocument */ public static function validateXML($xml, $schema, $debug = false) { assert('is_string($xml) || $xml instanceof DOMDocument'); assert('is_string($schema)'); libxml_clear_errors(); libxml_use_internal_errors(true); if ($xml instanceof DOMDocument) { $dom = $xml; } else { $dom = new DOMDocument(); $dom = self::loadXML($dom, $xml); if (!$dom) { return 'unloaded_xml'; } } $schemaFile = dirname(__FILE__) . '/schemas/' . $schema; $oldEntityLoader = libxml_disable_entity_loader(false); $res = $dom->schemaValidate($schemaFile); libxml_disable_entity_loader($oldEntityLoader); if (!$res) { $xmlErrors = libxml_get_errors(); syslog(LOG_INFO, 'Error validating the metadata: ' . var_export($xmlErrors, true)); if ($debug) { foreach ($xmlErrors as $error) { echo $error->message . "\n"; } } return 'invalid_xml'; } return $dom; }
/** * @covers Robo47_View_Helper_Gravatar::Gravatar * @dataProvider gravatarProvider */ public function testGravatar($email, $size, $rating, $default, $ssl, $separator, $params) { $view = new Zend_View(); $view->setEncoding('utf-8'); $view->Doctype(Zend_View_Helper_Doctype::XHTML1_STRICT); $service = new Robo47_Service_Gravatar(); $helper = new Robo47_View_Helper_Gravatar($service); $helper->setView($view); $gravatarImageTag = $helper->Gravatar($email, $size, $rating, $default, $ssl, $separator, $params); $src = $service->getUri($email, $size, $rating, $default, $ssl, $separator); $alt = 'Gravatar ' . $service->getGravatarHash($email); libxml_use_internal_errors(true); $dom = new DOMDocument(); $dom->loadHTML('<html><head><title></title></head><body>' . $gravatarImageTag . '</body></html>'); libxml_use_internal_errors(false); $nodes = $dom->getElementsByTagName('img'); $this->assertEquals(1, $nodes->length); $image = $nodes->item(0); $this->assertTrue($image->hasAttribute('src'), 'Image has no attribute "href"'); $this->assertTrue($image->hasAttribute('alt'), 'Image has no alt'); foreach ($params as $param => $value) { $this->assertTrue($image->hasAttribute($param), 'Image has no attribute "' . $param . '"'); $this->assertEquals($value, $image->getAttribute($param), 'Image attribute "' . $param . '" has wrong value'); } $srcAttribute = $image->getAttribute('src'); $this->assertEquals($src, $srcAttribute, 'Image attribute "src" has wrong value'); if (isset($params['alt'])) { $altAttribute = $image->getAttribute('alt'); $this->assertEquals($params['alt'], $altAttribute, 'Image attribute "alt" has wrong value'); } else { $altAttribute = $image->getAttribute('alt'); $this->assertEquals($alt, $altAttribute, 'Image attribute "alt" has wrong value'); } }
/** * Create an Array from XML * * This method sets up the SimpleXMLIterator and starts the parsing * of an xml body to iterate through it and transform it into * an array that can be used by the developers. * * @param string $xml * @return array An array mapped to the passed xml */ public static function arrayFromXml($xml) { // replace namespace defs $xml = str_replace('xmlns=', 'ns=', $xml); // catch libxml errors libxml_use_internal_errors(true); try { $iterator = new SimpleXMLIterator($xml); } catch(Exception $e) { $xmlErrors = libxml_get_errors(); return new Frapi_Exception( 'Xml Parsing Failed', 'INVALID_XML', 400, 'xml_parsing' ); libxml_clear_errors(); } $xmlRoot = $iterator->getName(); $type = $iterator->attributes()->type; // SimpleXML provides the root information on construct self::$_xmlRoot = $iterator->getName(); self::$_responseType = $type; // return the mapped array with the root element as the header return array($xmlRoot => self::_iteratorToArray($iterator)); }
/** * Reads the configuration file and creates the class attributes * */ protected function initialize() { $reader = new XMLReader(); $reader->open(parent::getConfigFilePath()); $reader->setRelaxNGSchemaSource(self::WURFL_CONF_SCHEMA); libxml_use_internal_errors(TRUE); while ($reader->read()) { if (!$reader->isValid()) { throw new Exception(libxml_get_last_error()->message); } $name = $reader->name; switch ($reader->nodeType) { case XMLReader::ELEMENT: $this->_handleStartElement($name); break; case XMLReader::TEXT: $this->_handleTextElement($reader->value); break; case XMLReader::END_ELEMENT: $this->_handleEndElement($name); break; } } $reader->close(); if (isset($this->cache["dir"])) { $this->logDir = $this->cache["dir"]; } }