public function render($internal = false) { if (empty($this->templateDocument)) { $this->compile(); } return $this->templateDocument->saveHTML(); }
/** * @param string $rfcLocation */ private function loadRfc($rfcLocation, $rfcCode) { // Suppress HTML5 errors libxml_use_internal_errors(true); $this->document = new \DOMDocument(); $this->document->loadHTMLFile($rfcLocation); // Turn errors back on libxml_use_internal_errors(false); $this->rfc = new Rfc(); $this->rfc->setCode($rfcCode); $this->rfc->setRawContent($this->document->saveHTML()); }
protected function setUp() { // Setup DOM $this->domDocument = new \DOMDocument('1', 'UTF-8'); $html = $this->domDocument->createElement('html'); $this->domAnchor = $this->domDocument->createElement('a', 'fake'); $this->domAnchor->setAttribute('href', 'http://php-spider.org/contact/'); $this->domDocument->appendChild($html); $html->appendChild($this->domAnchor); $this->uri = new DiscoveredUri(new Uri($this->domAnchor->getAttribute('href'))); // Setup Spider\Resource $content = $this->domDocument->saveHTML(); $this->spiderResource = new Resource($this->uri, new Response(200, [], $content)); }
public function truncatehtml($html, $minimum) { $oldDocument = new \DomDocument(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); $oldDocument->loadHTML('<div>' . $html . '</div>'); // remove DOCTYPE, HTML and BODY tags $oldDocument->removeChild($oldDocument->firstChild); $oldDocument->replaceChild($oldDocument->firstChild->firstChild->firstChild, $oldDocument->firstChild); $currentLength = 0; // displayed text length (without markup) $newDocument = new \DomDocument(); foreach ($oldDocument->documentElement->childNodes as $node) { if ($node->nodeType != 3) { // not text node $imported = $newDocument->importNode($node, true); $newDocument->appendChild($imported); // copy original node to output document $currentLength += strlen(html_entity_decode($imported->nodeValue)); if ($currentLength >= $minimum) { // check if the minimum is reached break; } } } $output = $newDocument->saveHTML(); return html_entity_decode($output); }
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) )); } }
public function __construct($gsite, $entry) { parent::__construct($gsite, $entry); $content = $entry->content->xpath("descendant::xhtml:table/descendant::xhtml:div[@dir = 'ltr']"); $dom = new DomDocument(); $dom->loadHTML((string)$entry->content->div->children()->asXML()); $this->conteudo = $dom->saveHTML(); //$this->conteudo = (string)$entry->content->div->children()->asXML(); $this->_remover_links_das_imagens_do_conteudo(); $this->_remover_links_tocs(); }
private function convertUrls() { $uri = phpUri::parse($this->url); foreach ($this->xpath->query('//img[@src]') as $el) { $el->setAttribute('src', $uri->join($el->getAttribute('src'))); } foreach ($this->xpath->query('//a[@href]') as $el) { $el->setAttribute('href', $uri->join($el->getAttribute('href'))); } $this->html = $this->is_xml ? $this->dom->saveXML() : $this->dom->saveHTML(); }
/** * Perform the conversion * * @param string Input json to convert * @param array Custom HTML to insert - array [{paragraph_num} => {Closure} (,{paragraph_num} => {Closure})] * @return string HTML */ public function convert($json, $customInserts = null) { $this->customInserts = $customInserts; if (($this->json = json_decode($json)) === null) { throw new Exceptions\NotTraversableException('The JSON provided is not valid'); } // sections is *always* our first node if (!isset($this->json->sections)) { throw new Exceptions\InvalidStructureException('The JSON provided is not in a Carbon Editor format.'); } $this->convertRecursive($this->json->sections); return trim($this->dom->saveHTML($this->dom->documentElement)); }
function bady2cdata($html, $xml) { //Get XML params $dom = new DomDocument(); $dom->preserveWhiteSpace = FALSE; $dom->loadHtml($html); $params = $dom->getElementsByTagName('body'); foreach ($params as $k => $v) { $html = $v->nodeValue; } $params = $dom->getElementsByTagName('title'); foreach ($params as $k => $v) { $title = $v->nodeValue; } $params = $dom->getElementsByTagName('meta'); foreach ($params as $k => $v) { if ($v->getAttribute('name') == 'description') { $description = $v->getAttribute('content'); } if ($v->getAttribute('name') == 'Author') { $author = $v->getAttribute('content'); } } //Write to XML $dom = new DomDocument(); $dom->preserveWhiteSpace = FALSE; $dom->loadXML($xml); $ModulePrefs = $dom->getElementsByTagName('ModulePrefs'); foreach ($ModulePrefs as $prefs) { $prefs->setAttribute('title', $title); $prefs->setAttribute('description', $description); $prefs->setAttribute('author', $author); } $params = $dom->getElementsByTagName('Content'); foreach ($params as $k => $v) { //echo $v->nodeValue; $v->nodeValue = $html; } $s = '<?xml version="1.0" encoding="UTF-8" ?>'; $s .= $dom->saveHTML(); return $s; }
function onAfterRender() { $db = JFactory::getDBO(); if (JFactory::getApplication()->isAdmin()) { return; } if (JFactory::getApplication()->getCfg('sef') == 0) { return; } if (JRequest::getVar('tmpl') == 'component') { return; } if (JRequest::getVar('format', 'html') != 'html') { return; } $body = JResponse::getBody(); $doc = new DomDocument("1.0"); $doc->loadHTML($body); $xpath = new DomXPath($doc); $hrefs = $xpath->query("//a"); foreach ($hrefs as $href) { $link = $href->getAttribute('href'); if (JFactory::getURI()->isInternal($link) == false) { continue; } $link = substr($link, 1); if ($this->params->get('raw')) { $origurl = JoomSEF::_createUri(new JURI($link)); } else { $origurl = JoomSEF::getNonSEFURL($link); } if (strlen($origurl)) { $href->setAttribute('class', 'link_tip'); $href->setAttribute('title', $origurl); } } $body = $doc->saveHTML(); JResponse::setBody($body); }
} var proxied = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function() { if (arguments[1] !== null && arguments[1] !== undefined) { var url = arguments[1]; url = rel2abs("' . $url . '", url); url = "' . PROXY_PREFIX . '" + url; arguments[1] = url; } return proxied.apply(this, [].slice.call(arguments)); }; } })();'); $scriptElem->setAttribute("type", "text/javascript"); $prependElem->insertBefore($scriptElem, $prependElem->firstChild); } echo "<!-- Proxified page constructed by miniProxy -->\n" . $doc->saveHTML(); } else { if (stripos($contentType, "text/css") !== false) { //This is CSS, so proxify url() references. echo proxifyCSS($responseBody, $url); } else { //This isn't a web page or CSS, so serve unmodified through the proxy with the correct headers (images, JavaScript, etc.) header("Content-Length: " . strlen($responseBody)); echo $responseBody; } }
function html_balance($html, $remove_empty = true) { if (!extension_loaded('dom')) { return $html; } if (!trim($html)) { return $html; } $doc = new DomDocument(); $xhtml = '<?xml encoding="utf-8"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' . "<div>{$html}</div>"; $doc->encoding = 'utf-8'; $doc->preserveWhitespace = false; $doc->recover = true; if (false === @$doc->loadHTML($xhtml)) { return $html; } if ($remove_empty) { // Remove empty nodes $xpath = new DOMXPath($doc); static $eE = array('area' => 1, 'br' => 1, 'col' => 1, 'embed' => 1, 'hr' => 1, 'img' => 1, 'input' => 1, 'isindex' => 1, 'param' => 1); do { $done = true; $nodes = $xpath->query('//*[not(text()) and not(node())]'); foreach ($nodes as $n) { if (isset($eE[$n->nodeName])) { continue; } $n->parentNode->removeChild($n); $done = false; } } while (!$done); } static $phpversion; if (!isset($phpversion)) { $phpversion = phpversion(); } $body = $doc->getElementsByTagName('body'); if (!$body->length) { return $html; } if ($phpversion > '5.3.6') { $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0)->firstChild); } else { $html = $doc->saveHTML(); $html = preg_replace('`^<!DOCTYPE.+?>|<\\?xml .+?>|</?html>|</?body>|</?head>|<meta .+?/?>`', '', $html); # <?php } return preg_replace('`^<div>|</div>$`', '', trim($html)); }
function exportThumbnailPage() { global $CONFIG; $album = $_GET['album']; $page = $_GET['page']; $path = $_GET['path']; $filename = "thumbnails.php"; include $filename; $contents = ob_get_contents(); ob_end_clean(); $pictures = cpg_db_query("SELECT pid,title,filename,filepath FROM {$CONFIG['TABLE_PICTURES']} WHERE `aid` = '{$album}'"); $picture_r = array(); while ($picture = mysql_fetch_array($pictures)) { $picture_r[$picture['pid']] = $picture['filepath'] . $picture['filename']; } // Create a DOM Object to parse the html (Removing links to dynamic content/functions that require php) $doc = new DomDocument(); $doc->loadHtml($contents); $divs = $doc->getElementsByTagName('div'); foreach ($divs as $div) { if ($div->getAttribute('id') == 'MENUS' || $div->getAttribute('class') == 'admin_menu_wrapper') { $div->setAttribute('style', 'display:none'); } } $tds = $doc->getElementsByTagName('td'); foreach ($tds as $td) { if ($td->getAttribute('class') == 'sortorder_options') { $td->setAttribute('style', 'display:none'); } } $contents = $doc->saveHTML(); foreach ($picture_r as $id => $filename) { $contents = preg_replace("/displayimage.php\\?album={$album}&pid={$id}/", "albums/{$filename}", $contents); } $contents = preg_replace("/thumbnails.php\\?album=2&page=([\\d]+)/", 'thumbnails_$1.html', $contents); // Find out the theme currently used and copy over necessary files to replicate this $result = cpg_db_query("SELECT value FROM {$CONFIG['TABLE_CONFIG']} WHERE `name` = 'theme'"); $theme = mysql_fetch_array($result); recursive_copy("themes/{$theme['value']}", "{$path}/themes/{$theme['value']}"); file_put_contents("{$path}/thumbnails_{$page}.html", $contents); if ($page == 1) { copy("{$path}/thumbnails_{$page}.html", "{$path}/index.html"); } }
public function rework_navigation(Block $block) { $h = $block->header; $b = $block->body; $i = $block->id; $dom = new DomDocument(); $dom->loadHTML($b); $output = array(); $html = "<section id='{$i}'>\n<nav class='mdl-navigation'>\n"; foreach ($dom->getElementsByTagName('a') as $item) { $item->setAttribute('class', 'mdl-navigation__link'); $html .= $dom->saveHTML($item); // $output[] = array ( // ,'str' => $dom->saveHTML($item) // // ,'href' => $item->getAttribute('href') // // ,'anchorText' => $item->nodeValue // ); } $html .= "</nav>\n</section>\n"; return $html; }
function _boinc_firstlink(&$alink) { if (!empty($alink)) { $dom = new DomDocument(); $dom->loadHTML($alink); $myli = $dom->getElementsByTagName('li'); if ($myli->length > 0) { $newclasses = trim($myli[0]->getAttribute("class") . " first"); $myli[0]->setAttribute("class", $newclasses); $alink = $dom->saveHTML($myli[0]); } } }
/** * convert SimpleXMLElement to string, replace root nodes * * @param SimpleXMLElement $scriptlet * @return string */ public static function toString($scriptlet) { $dom_api_node = dom_import_simplexml($scriptlet); $dom = new DomDocument(); $dom_api_node = $dom->importNode($dom_api_node, true); $dom->appendChild($dom_api_node); $output = str_replace("<root>", "", $dom->saveHTML()); $output = str_replace("</root>", "", $output); $output = str_replace("</script>", "</script>\n", $output); return $output; }
/** * Filter the page html and look for an <a><img> element added by the chooser * or an <a> element added by the moodle file picker * * NOTE: Thumbnail html from the Chooser and a link from the old filepicker * are of the same form (see $_re_api1_public_urls). * A thumbnail link from the new repository filepicker plugin is * different (see $_re_api2_public_urls). * The latest version of the local lib and rich text editor plugins * use both a trusted and a regular embed url as the href value of * the thumbnail html (this is the preferred route going forward). * Both types of embed_urls will need a user to be authenticated * before they can view the embed. * * @param string $html * @param array $options * @return string */ public function filter($html, array $options = array()) { global $COURSE; $courseid = isset($COURSE->id) ? $COURSE->id : null; if (empty($html) || !is_string($html) || strpos($html, $this->_mcore_client->get_host()) === false) { return $html; } $dom = new DomDocument(); @$dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); $xpath = new DOMXPath($dom); foreach ($xpath->query('//a') as $node) { $href = $node->getAttribute('href'); if (empty($href)) { continue; } if ((bool) preg_match($this->_re_embed_url, $href)) { $newnode = $dom->createDocumentFragment(); $imgnode = $node->firstChild; if ($this->_mcore_client->has_lti_config() && !is_null($courseid)) { $href = $this->_generate_embed_url($href, $courseid); } else { $href = htmlspecialchars($href); } extract($this->_get_image_elem_dimensions($imgnode)); $html = $this->_get_iframe_embed_html($href, $width, $height); $newnode->appendXML($html); $node->parentNode->replaceChild($newnode, $node); } else { if ((bool) preg_match($this->_re_api1_public_urls, $href)) { $newnode = $dom->createDocumentFragment(); $imgnode = $node->firstChild; extract($this->_get_image_elem_dimensions($imgnode)); $html = $this->_get_embed_html_from_api1_public_url($href, $width, $height, $courseid); $newnode->appendXML($html); $node->parentNode->replaceChild($newnode, $node); } else { if ((bool) preg_match($this->_re_api2_public_urls, $href)) { $newnode = $dom->createDocumentFragment(); $width = $this->_default_thumb_width; $height = $this->_default_thumb_height; $html = $this->_get_embed_html_from_api2_public_url($href, $width, $height, $courseid); $newnode->appendXML($html); $node->parentNode->replaceChild($newnode, $node); } } } } return $dom->saveHTML(); }
/** * Performs a Plesk API request, returns raw API response text * * @param string $packet * * @return string * @throws ApiRequestException */ private function sendRequest($packet) { $domdoc = new \DomDocument('1.0', 'UTF-8'); if ($domdoc->loadXml($packet) === false) { $this->error = 'Failed to load payload'; return false; } $body = $domdoc->saveHTML(); return $this->http->sendRequest($body); }
private function save_content() { $xpath = "/html/body/bogus/child::node()"; $DOMXPath = new DOMXPath($this->dom); $snippetNode = $DOMXPath->query($xpath); $targetDom = new DomDocument(); $childNodes = $snippetNode; for ($i = 0; $i < $childNodes->length; $i++) { $importNode = $childNodes->item($i); $importedSnippetNode = $targetDom->importNode($importNode, true); // and append to our child $targetDom->appendChild($importedSnippetNode); } faf_debug($targetDom->saveHTML()); return trim($targetDom->saveHTML()); // trim because saveHTML adds enters for some reason }
$input_classes[] = Bem::bem($form_class, 'input'); $input_classes[] = Bem::bem($form_class, 'input', 'email'); break; case 'url': $input_classes[] = Bem::bem($form_class, 'input'); $input_classes[] = Bem::bem($form_class, 'input', 'url'); break; case 'submit': $input_classes[] = Bem::bem($form_class, 'button'); $input_classes[] = Bem::bem($form_class, 'button', 'submit'); break; case 'reset': $input_classes[] = Bem::bem($form_class, 'button'); $input_classes[] = Bem::bem($form_class, 'button', 'reset'); break; case 'button': $input_classes[] = Bem::bem($form_class, 'button'); break; default: $input_classes[] = Bem::bem($form_class, 'input'); $input_classes[] = Bem::bem($form_class, 'input', 'text'); break; } $input->setAttribute('class', implode(' ', $input_classes)); } if ($textarea = $dom->getElementById('comment')) { $textarea->setAttribute('class', implode(' ', [Bem::bem($form_class, 'textarea'), Bem::bem($form_class, 'input', 'textarea'), Bem::bem($form_class, 'comments-box')])); } echo $dom->saveHTML($root); }, apply_filters('wpbem_comment_form_priority', 30)); }
/** * Get formatted output body * * @param $content * @param $type * * @return string */ public function body($content, $type) { if (empty($content)) { return '<pre data-format-text><span style="color:darkgrey;">Empty body</span></pre>'; } if (is_array($content)) { $content = http_build_query($content); } $contentType = 'text'; foreach (['json', 'xml', 'html'] as $possibleType) { if (strpos(strtolower($type), $possibleType) !== false) { $contentType = $possibleType; break; } } $contentFormatted = ''; switch ($contentType) { case 'json': $contentFormatted = json_encode(json_decode($content), JSON_PRETTY_PRINT); break; case 'xml': $doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; @$doc->loadXML($content); //our code is not responsible for badly formatted content $contentFormatted = $doc->saveXML(); break; case 'html': $doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; @$doc->loadHTML($content); //our code is not responsible for badly formatted content $contentFormatted = $doc->saveHTML(); break; } $copyButton = '<a href="javascript:;" class="select-response">Select</a>'; $rawButton = '<a href="javascript:;" class="formatted" onclick="$(this).text($(this).text() == \'Raw\' ? \'Formatted\' : \'Raw\').next(\'pre\').find(\'> code\').toggle();">Raw</a>'; $html = $copyButton; if (!empty($contentFormatted)) { $html .= $rawButton . '<pre>'; $html .= $this->Html->tag('code', htmlentities($contentFormatted), ['class' => 'language-' . $contentType]); $html .= $this->Html->tag('code', htmlentities($content), ['class' => 'raw', 'style' => 'display:none;']); } else { $html .= '<pre>'; $html .= $this->Html->tag('code', htmlentities($content), ['class' => 'raw']); } $html .= '</pre>'; return $html; }
/** * rendering * - prepares js source * - builds xml * - converts xml to xhtml * * @param string $name * @param boolean $return * @return mixed */ public function render($name = false, $return = false) { $this->prepare(); $dom_api_node = dom_import_simplexml($this->object["api"]); if (empty($this->ignoreContainer)) { // build chart type browser container $dom_div_node = dom_import_simplexml($this->object["div"]); } // use base or alt. container as root $dom_node = !empty($name) ? dom_import_simplexml($this->object[$name]) : dom_import_simplexml($this->object["base"]); $dom = new DomDocument(); // append add-ons if (empty($this->usePackage) and isset($this->packageSetup)) { $addons = $this->object["addon"]; if (is_array($addons)) { foreach ($addons as $addon) { $dom_addon = $dom->importNode(dom_import_simplexml($addon), true); $dom->appendChild($dom_addon); } } if (method_exists($this, "loadCustomPackage") and isset($this->object["customPackage"])) { $dom_addon = $dom->importNode(dom_import_simplexml($this->object["customPackage"]), true); $dom->appendChild($dom_addon); } } elseif (isset($this->packageSetup)) { $addons = $this->object["addon"]; if (is_array($addons)) { foreach ($addons as $addon) { $dom_addon = $dom->importNode(dom_import_simplexml($addon), true); $dom->appendChild($dom_addon); } } if (method_exists($this, "loadCustomPackage") and isset($this->object["customPackage"])) { $dom_addon = $dom->importNode(dom_import_simplexml($this->object["customPackage"]), true); $dom->appendChild($dom_addon); } } // append presentation container if (empty($this->ignoreContainer)) { $dom_div_node = $dom->importNode($dom_div_node, true); $dom->appendChild($dom_div_node); } // append api source $dom_api_node = $dom->importNode($dom_api_node, true); $dom->appendChild($dom_api_node); // append defaults $dom_node = $dom->importNode($dom_node, true); $dom->appendChild($dom_node); // strip root node tags for they are not used $output = str_replace("<" . $this->rootNode . ">", "", $dom->saveHTML()); $output = str_replace("</" . $this->rootNode . ">", "", $output); if ($return) { return $output; } else { echo $output; } return false; }
/** * A function hook that the WordPress core launches at 'init' points */ function dtthemes_modules_init() { global $dtthemes_columns, $dtthemes_sample_layouts, $theme_name, $dt_widgets; $dtthemes_columns = apply_filters('dtthemes_columns', $dtthemes_columns); global $wp_widget_factory; foreach ($wp_widget_factory->widgets as $class => $info) { $widget = new $class(); $id = $info->id; $wt_name = $widget->name; $wt_wpname = $widget->widget_options['classname']; $wt_class = $class; $wt_tooltip = ''; if (isset($widget->widget_options['description'])) { $wt_tooltip = $widget->widget_options['description']; } ob_start(); $widget->form(array()); $form = ob_get_clean(); $exp = preg_quote($widget->get_field_name('____')); $exp = str_replace('____', '(.*?)', $exp); $dt_form = preg_replace('/' . $exp . '/', "widgets[{$id}][\$1]", $form); $dt_form = str_replace('<br>', '', $dt_form); $doc = new DomDocument(); $file = @$doc->loadHTML($dt_form); $opt = array(); $inputtag = $doc->getElementsByTagName('input'); foreach ($inputtag as $item) { $prev_class = $item->getAttribute('class'); $item->setAttribute('class', $prev_class . ' dtthemes_widget_attr'); $input_type = $item->getAttribute('type'); if ($input_type == 'checkbox') { $e = $item->parentNode; $e->setAttribute('class', 'dtthemes_checkbox'); } } $textareatag = $doc->getElementsByTagName('textarea'); foreach ($textareatag as $item) { $prev_class = $item->getAttribute('class'); $item->setAttribute('class', $prev_class . ' dtthemes_widget_attr'); } $selecttag = $doc->getElementsByTagName('select'); foreach ($selecttag as $item) { $sname = $item->getAttribute('name'); $sname = str_replace('[]', '', $sname); $item->setAttribute('name', $sname); $sid = $item->getAttribute('id'); $sid = str_replace('[]', '', $sid); $item->setAttribute('id', $sid); $prev_class = $item->getAttribute('class'); if ($item->getAttribute('multiple') == 'multiple') { $prev_class .= ' dt_multiselect'; } $item->setAttribute('class', $prev_class . ' dtthemes_widget_attr'); } $modified_form = @$doc->saveHTML(); $dt_widgets[$wt_class] = array('name' => $wt_name, 'wpname' => $wt_wpname, 'wpid' => $id, 'tooltip' => $wt_tooltip, 'form' => $modified_form); } $dtthemes_settings = get_option('dtthemes_settings'); if (isset($dtthemes_settings['custom_sample_layouts'])) { $dtthemes_sample_layouts = array_merge((array) $dtthemes_sample_layouts, (array) $dtthemes_settings['custom_sample_layouts']); } $dtthemes_sample_layouts = apply_filters('dtthemes_sample_layouts', $dtthemes_sample_layouts); }
/** * Método que verifica la validez de la firma de un XML utilizando RSA y SHA1 * @param xml_data Archivo XML que se desea validar * @return =true si la firma del documento XML es válida o =false si no lo es * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) * @version 2014-12-08 */ public function verifyXML($xml_data) { $doc = new \DomDocument(); $doc->loadXML($xml_data); $dom = $doc->documentElement; // preparar datos que se verificarán $Signature = $dom->removeChild($dom->getElementsByTagName('Signature')[0]); $SignedInfo = $Signature->getElementsByTagName('SignedInfo')[0]; $SignedInfo->setAttribute('xmlns', $Signature->getAttribute('xmlns')); $signed_info = $doc->saveHTML($SignedInfo); $signature = $Signature->getElementsByTagName('SignatureValue')[0]->nodeValue; $pub_key = $Signature->getElementsByTagName('X509Certificate')[0]->nodeValue; // verificar firma if (!$this->verify($signed_info, $signature, $pub_key)) { return false; } // verificar digest $digest_original = $Signature->getElementsByTagName('DigestValue')[0]->nodeValue; $digest_calculado = base64_encode(sha1($dom->C14N(), true)); if ($digest_original != $digest_calculado) { return false; } return true; }
static function getTextFromHTML($html) { if (strlen($html) == 0) { return false; } // convert tabs and newlines to spaces $html = str_ireplace(array("\t", "\n", "\r"), ' ', $html); // add spaces after closing html tags so when we strip tags there are still spaces $html = str_ireplace('>', '> ', $html); // xpath occasionally cocks up stripping javascript containing html, so manually remove it $html = preg_replace('@<script[^>]*?>.*?</script>@si', ' ', $html); $dom = new DomDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $important = array(); $queries = ['//title[1]', '//meta[@name="description"]/@content', '//meta[@name="keywords"]/@content', '//h1', '//h2', '//h3', '//h4', '//h5', '//h6']; foreach ($queries as $query) { foreach ($xpath->query($query) as $node) { $important[] = self::get_inner_html($node); } } // image alt tags /*$tags = $xpath->query('//img'); foreach ($tags as $tag){ $important[] = $tag->getAttribute('alt'); if ($tag->getAttribute('alt') != $tag->getAttribute('title')) $important[] = $tag->getAttribute('title'); }*/ self::removeElements($xpath->query('//head')); self::removeElements($xpath->query('//title')); self::removeElements($xpath->query('//meta')); self::removeElements($xpath->query('//script')); self::removeElements($xpath->query('//noscript')); self::removeElements($xpath->query('//link')); self::removeElements($xpath->query('//style')); self::removeElements($xpath->query('//comment()')); self::removeElements($xpath->query('//iframe')); self::removeElements($xpath->query('//nav')); self::removeElements($xpath->query('//footer')); self::removeElements($xpath->query('//header')); self::removeElements($xpath->query('//aside')); self::removeElements($xpath->query('//input')); self::removeElements($xpath->query('//textarea')); self::removeElements($xpath->query('//select')); self::removeElements($xpath->query('//label')); self::removeElements($xpath->query('//img')); //self::removeElements($xpath->query('//a')); // links refer to *other* pages, not the content on this page? self::removeElements($xpath->query("//*[contains(@style,'display:none')]")); self::removeElements($xpath->query("//*[contains(@class,'hidden')]")); self::removeElements($xpath->query("//*[contains(@class,'header')]")); self::removeElements($xpath->query("//*[contains(@class,'footer')]")); self::removeElements($xpath->query("//*[contains(@role,'navigation')]")); self::removeElements($xpath->query("//*[contains(@class,'navigation')]")); self::removeElements($xpath->query("//*[contains(@class,'nav')]")); // we already extract these, so ignore self::removeElements($xpath->query("//h1")); self::removeElements($xpath->query("//h2")); self::removeElements($xpath->query("//h3")); self::removeElements($xpath->query("//h4")); self::removeElements($xpath->query("//h5")); self::removeElements($xpath->query("//h6")); $html = $dom->saveHTML(); $html = implode('. ', $important) . '. ' . $html; // convert to utf-8 if we can $encoding = mb_detect_encoding($html, 'ASCII, windows-1251, ISO-8859-1, UTF-8', true); $html = mb_convert_encoding($html, $encoding, 'UTF-8'); $str = strip_tags(html_entity_decode($html, ENT_QUOTES, 'UTF-8')); $str = str_replace(' ', '. ', $str); while (stristr($str, '. . ')) { $str = preg_replace('/' . preg_quote('. . ') . '/', '. ', $str); $str = preg_replace('/(\\s)+/', ' ', $str); $str = preg_replace('/\\.+/', '.', $str); } $str = trim($str); if ($str == '.') { return false; } return $str; }
function onBeforeRender() { $app = self::$app; $reqParams = self::$reqParams; $id = $reqParams['id']; if (!$app->isAdmin()) { return; } $user = self::$user; if (!$user->authorise('core.edit', 'com_content')) { return; } // termina la ejecución del plugin si los parametros recibidos no cumplen // con las condiciones preestablecidas para modificar el contexto de edición de // artículos if ($reqParams["view"] != "article" || $reqParams["layout"] != "edit") { return; } $doc = JFactory::getDocument(); $doc->addStyleSheet(JURI::root() . 'plugins/system/jokte_adjuntos/assets/css/estilos.css'); // obtiene el buffer del documento que será renderizado $buffer = mb_convert_encoding($doc->getBuffer('component'), 'html-entities', 'utf-8'); // inicializa la manipulación del DOM para el buffer del documento $dom = new DomDocument(); $dom->validateOnParse = true; $dom->loadHTML($buffer); // obtiene los datos de los adjuntos $data = self::getAttachmentsData($id); // selecciona elemento del DOM que contendrá los registros de los archivos adjuntos $contenedor = $dom->getElementById("adjuntos"); // realiza la construcción de la tabla con el listado de adjuntos $wrap = $dom->createElement("div"); $wrap->setAttribute("class", "wrap"); $tabla = $dom->createElement("table"); $tbody = $dom->createElement("tbody"); $c = 0; foreach ($data as $item) { $itemId = 'item-' . $c; $rutaArchivo = '/uploads' . DS . $item->hash . '-' . $item->nombre_archivo; $iconSrc = JMime::checkIcon($item->mime_type); $fileSize = JFile::getSize(JPATH_ROOT . $rutaArchivo); $row = $dom->createElement("tr"); $row->setAttribute('id', $itemId); $mime = $dom->createElement("td"); $file = $dom->createElement("td"); $info = $dom->createElement("td"); $info->setAttribute('class', 'center'); $trash = $dom->createElement("td"); $trash->setAttribute('class', 'center'); $mimeImg = $dom->createElement("img"); $mimeImg->setAttribute('src', $iconSrc); $mime->appendChild($mimeImg); $name = $dom->createElement("span"); $nameAnchor = $dom->createElement("a"); $nameAnchor->setAttribute('href', $rutaArchivo); $nameAnchor->setAttribute('target', '_blank'); $nameAnchor->nodeValue = $item->nombre_archivo; $name->appendChild($nameAnchor); $file->appendChild($name); $infoBtn = $dom->createElement("a"); $infoBtn->setAttribute('onclick', 'mostrarInfo(this, event)'); $infoBtn->setAttribute('title', 'Información'); $infoBtn->setAttribute('class', 'modal'); $infoBtn->setAttribute('href', 'javascript:void(0)'); $infoBtn->setAttribute('data-file', $item->nombre_archivo); $infoBtn->setAttribute('data-mimeIcon', $iconSrc); $infoBtn->setAttribute('data-hash', $item->hash); $infoBtn->setAttribute('data-size', $fileSize); $infoBtn->setAttribute('data-mime', $item->mime_type); $infoImg = $dom->createElement("img"); $infoImg->setAttribute('src', JURI::root() . '/media/adjuntos/file-info-icon.png'); $infoBtn->appendChild($infoImg); $info->appendChild($infoBtn); $trashBtn = $dom->createElement("button"); $trashBtn->setAttribute('onclick', 'eliminarAdjunto(this, event)'); $trashBtn->setAttribute('title', 'Eliminar archivo'); $trashBtn->setAttribute('data-hash', $item->hash); $trashBtn->setAttribute('data-id', $itemId); $trashImg = $dom->createElement("img"); $trashImg->setAttribute('src', JURI::root() . '/media/adjuntos/caneca.png'); $trashBtn->appendChild($trashImg); $trash->appendChild($trashBtn); $row->appendChild($mime); $row->appendChild($file); $row->appendChild($info); $row->appendChild($trash); $tbody->appendChild($row); $c++; } $wrap->appendChild($tabla); $tabla->appendChild($tbody); $contenedor->appendChild($wrap); // aplica los cambios realizados al DOM en un nuevo buffer para actualizar la presentación // del la vista del componente en el contexto indicado $newBuffer = $dom->saveHTML(); $doc->setBuffer($newBuffer, 'component'); }
static function link_style($color, $content) { if (class_exists("DomDocument")) { $dom = new DomDocument('1.0', 'UTF-8'); //$content = str_replace (' ', '@nbsp;', $content); if (function_exists('mb_convert_encoding')) { $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'); // htmlspecialchars($content); } $dom->strictErrorChecking = false; @$dom->loadHtml($content); $aTags = $dom->getElementsByTagName('a'); foreach ($aTags as $aElement) { $style = $aElement->getAttribute('style'); $style .= ' color: ' . $color . '; '; $aElement->setAttribute('style', $style); } //$content = $dom->saveHTML(); $content = preg_replace(array("/^\\<\\!DOCTYPE.*?<html><body>/si", "!</body></html>\$!si"), "", $dom->saveHTML()); $content = str_replace("%7B", "{", $content); $content = str_replace("%7D", "}", $content); return $content; } return $content; }
/** * Performs a Plesk API request, returns raw API response text * * @param string packet * @return string * @throws ApiRequestException */ private function sendRequest($packet) { $domdoc = new \DomDocument('1.0', 'UTF-8'); if ($domdoc->loadXml($packet) === FALSE) { $this->error = 'Failed to load payload'; return FALSE; } curl_setopt($this->curl, CURLOPT_POSTFIELDS, $domdoc->saveHTML()); $result = curl_exec($this->curl); if (curl_errno($this->curl)) { $errmsg = curl_error($this->curl); $errcode = curl_errno($this->curl); curl_close($this->curl); throw new ApiRequestException($errmsg, $errcode); } $info = curl_getinfo($this->curl); $this->request_header = curl_getinfo($this->curl, CURLINFO_HEADER_OUT); curl_close($this->curl); return $result; }
/** * Returns the underlying HTML document as a string * * @return string */ function output_html() { return $this->_xml->saveHTML(); }
$element->setAttribute("style", proxifyCSS($element->getAttribute("style"), $url)); } //Proxify any of these attributes appearing in any tag. $proxifyAttributes = array("href", "src"); foreach ($proxifyAttributes as $attrName) { //For every element with the given attribute... foreach ($xpath->query('//*[@' . $attrName . ']') as $element) { $attrContent = $element->getAttribute($attrName); if ($attrName == "href" && (stripos($attrContent, "javascript:") === 0 || stripos($attrContent, "mailto:") === 0)) { continue; } $attrContent = rel2abs($attrContent, $url); //Replace any leftmost question mark with an ampersand to blend an existing query string into the proxified URL $attrContent = preg_replace("/\\?/", "&", $attrContent, 1); $attrContent = PROXY_PREFIX . $attrContent; $element->setAttribute($attrName, $attrContent); } } echo $doc->saveHTML(); } else { if (stripos($file["contentType"], "text/css") !== false) { echo proxifyCSS($file["data"], $url); } else { if (stripos($file["contentType"], "javascript") !== false) { echo proxifyJS($file["data"], $url); } else { header("Content-Length: " . strlen($file["data"])); echo $file["data"]; } } }