public static function insertTemplateLogic($search, $path, \DOMElement $node) { $template = $node->ownerDocument; $node->setAttribute('xml:space', 'preserve'); // fix whitespaces in mixed node /** @var $textNode \DOMText */ foreach ($node->childNodes as $textNode) { $nodeValue = $textNode->nodeValue; // utf8_decode // before [[tag]] after $nodeValueParts = explode($search, $nodeValue, 2); // fix similar tags in one node if (count($nodeValueParts) === 2) { $textNode->nodeValue = ''; // reset // text before $before = $template->createTextNode($nodeValueParts[0]); $node->insertBefore($before, $textNode); // add xsl logic $placeholder = $template->createElementNS(self::XSL_NS, 'xsl:value-of'); $placeholder->setAttribute('select', $path); $node->insertBefore($placeholder, $textNode); // text after $after = $template->createTextNode($nodeValueParts[1]); $node->insertBefore($after, $textNode); $node->removeChild($textNode); return true; } } return false; }
/** * Inserts a new child immediately after the specified frame * * @param $new_child Frame The new Frame to insert * @param $ref Frame The Frame before the new Frame * @param $update_node boolean Whether or not to update the DOM * * @throws DOMPDF_Exception */ function insert_child_after(Frame $new_child, Frame $ref, $update_node = true) { if ($ref === $this->_last_child) { $this->append_child($new_child, $update_node); return; } if (is_null($ref)) { $this->prepend_child($new_child, $update_node); return; } if ($ref->_parent !== $this) { throw new DOMPDF_Exception("Reference child is not a child of this node."); } // Update the node if ($update_node) { if ($ref->_next_sibling) { $next_node = $ref->_next_sibling->_node; $this->_node->insertBefore($new_child->_node, $next_node); } else { $new_child->_node = $this->_node->appendChild($new_child->_node); } } // Remove the child from its parent if ($new_child->_parent) { $new_child->_parent->remove_child($new_child, false); } $new_child->_parent = $this; $new_child->_prev_sibling = $ref; $new_child->_next_sibling = $ref->_next_sibling; if ($ref->_next_sibling) { $ref->_next_sibling->_prev_sibling = $new_child; } $ref->_next_sibling = $new_child; }
/** * Creates a ref-mark as the first element of the given $odtElement, based * on the ID attribute of the given $docbookElement. * * @param DOMElement $docbookElement * @param DOMElement $odtElement */ protected function createRefMark(DOMElement $docbookElement, DOMElement $odtElement) { // Work around for DocBook inconsistency in using ID or id. id // would be correct, if one follows the specs here… if ($docbookElement->hasAttribute('ID') || $docbookElement->hasAttribute('id')) { $refMark = $odtElement->insertBefore($odtElement->ownerDocument->createElementNS(ezcDocumentOdt::NS_ODT_TEXT, 'text:reference-mark'), $odtElement->firstChild); $refMark->setAttributeNS(ezcDocumentOdt::NS_ODT_TEXT, 'text:name', $docbookElement->hasAttribute('ID') ? $docbookElement->getAttribute('ID') : $docbookElement->getAttribute('id')); } }
/** * Wstaw element wewnątrz obecnego elementu * * @param HtmlElement $element * @param int $where * * @throws \RuntimeException */ public function insert(HtmlElement $element, $where = self::CHILD_APPEND) { if ($this->element === $element->getElement()) { throw new \RuntimeException('You can not insert the Element into a self.'); } switch ($where) { case self::CHILD_APPEND: $this->element->appendChild($element->getElement()); break; case self::CHILD_PREPEND: $this->element->insertBefore($element->getElement(), $this->element->childNodes->item(0)); break; } }
/** * * @param DOMElement $rootNode * @param DOMElement $newNode */ protected function _appendNodeAlphabetically(DOMElement $rootNode, DOMElement $newNode) { if ($newNode->hasChildNodes()) { $refNode = null; foreach ($rootNode->childNodes as $child) { if ($child instanceof DOMElement && $child->tagName > $newNode->tagName) { $refNode = $child; break; } } if ($refNode) { $rootNode->insertBefore($newNode, $refNode); } else { $rootNode->appendChild($newNode); } } }
private function cleanNode2(DOMElement $node) { // проверка допустимых свойств $j = 0; $checkAttribute = array_key_exists($node->nodeName, $this->allowedAttributes); while ($j < $node->attributes->length) { $attribute = $node->attributes->item($j); if ((!$checkAttribute || !in_array($attribute->name, $this->allowedAttributes[$node->nodeName])) && !in_array($attribute->name, $this->allowedAttributes['*'])) { $node->removeAttribute($attribute->name); $j--; } if ($attribute->name == 'href' || $attribute->name == 'src') { // что-то мне регуляярка эта не нравится if (preg_match('/^\\s*javascript\\s*:/', $attribute->value)) { $node->removeAttribute($attribute->name); $j--; } } $j++; } // проверка допустимых нод $i = 0; while ($i < $node->childNodes->length) { $child = $node->childNodes->item($i); if ($child instanceof DOMElement) { if (in_array($child->nodeName, $this->allowedTags)) { $this->cleanNode2($child); } else { var_dump($child->nodeName); //копируем содержимое запрещённой ноды foreach ($child->childNodes as $childChild) { $node->insertBefore($childChild->cloneNode(true), $child); } // и удаляем её $node->removeChild($child); $i--; $i--; } } elseif ($child instanceof DOMText) { // проверяем текстовые ноды на наличие '\n', заменяем '\n' на '<br>' $text = $child->nodeValue; $pieces = preg_split('/\\n/', $text); if (count($pieces) > 1) { for ($j = 0; $j < count($pieces); $j++) { $pieceTextNode = $node->ownerDocument->createTextNode($pieces[$j]); $node->insertBefore($pieceTextNode, $child); $i++; if ($j + 1 < count($pieces)) { $node->insertBefore($node->ownerDocument->createElement('br'), $child); $i++; /*$node->insertBefore($node->ownerDocument->createElement('br'), $child); $i++;*/ } } $node->removeChild($child); $i--; } } $i++; } }
/** * Adds a new directive before a reference node. * * @param HTTPd_DOMElement $newnode * @param HTTPd_DOMElement $refnode * @return HTTPd_DOMElement */ public function insertBefore(\DOMNode $newnode, \DOMNode $refnode = null) { if ($newnode instanceof \DOMAttr) { throw new DOMException("Don't call Q\\HTTPd_DOMElement::" . __FUNCTION__ . "() to add an attribute, use setAttributeNode() instead.", DOM_HIERARCHY_REQUEST_ERR); } if ($this->firstChild === null) { throw new \DOMException("It's not possible to add children to {$this->nodeName} direcive.", DOM_HIERARCHY_REQUEST_ERR); } if (!$newnode instanceof HTTPd_DOMElement && !$newnode instanceof HTTPd_DOMComment && !$newnode instanceof \DOMText) { throw new \DOMException("You may only add Q\\HTTPd_DOMElement, Q\\HTTPd_DOMComment and DOMText nodes to a section, not a " . get_class($newnode) . ".", DOM_HIERARCHY_REQUEST_ERR); } return \DOMElement::insertBefore($newnode, $refnode); }
protected function shrink_xml_element(DOMElement $el) { $prev = null; $sub_ind = null; for ($i = 0; $i < $el->childNodes->length; $i++) { $child = $el->childNodes->item($i); if ($child instanceof DOMText) { if ('' == trim($child->wholeText)) { $el->removeChild($child); $i--; continue; } } if ($child instanceof DOMComment) { continue; } if ($prev instanceof $child and $prev->nodeName == $child->nodeName) { $sub_ind++; } else { if ($sub_ind > $this->_sibling_limit) { $el->insertBefore(new DOMComment('[pmxi_more:' . ($sub_ind - $this->_sibling_limit) . ']'), $child); $i++; } $sub_ind = 1; $prev = null; } if ($child instanceof DOMElement) { $prev = $child; if ($sub_ind <= $this->_sibling_limit) { $this->shrink_xml_element($child); } else { $el->removeChild($child); $i--; } } } if ($sub_ind > $this->_sibling_limit) { $el->appendChild(new DOMComment('[pmxi_more:' . ($sub_ind - $this->_sibling_limit) . ']')); } return $el; }
/** * Insert the element given in argument before the $oNext element, if null insert at the end of the children's list * @param XML_Element $oChild The element to add to actual content * @param XML_Element $oNext The element that will follow the value * @return XML_Element The element added to content */ public function insertChild(\DOMNode $node, dom\node $referer = null, $bPrevious = false) { if ($node === $referer) { $referer = null; } if ($node->ownerDocument && $node->ownerDocument !== $this->getDocument()) { $node = $this->getDocument()->importNode($node); } if ($node instanceof \DOMAttr) { $referer = null; } $result = $node; if ($bPrevious) { if ($referer && $referer->getNext()) { $result = parent::insertBefore($node, $referer->getNext()); } else { if ($referer) { $result = parent::appendChild($node); } else { $result = parent::insertBefore($node, $this->getFirst()); } } } else { if ($referer) { $result = parent::insertBefore($node, $referer); } else { $result = parent::appendChild($node); } } return $result; }
/** * @param \DOMDocument $dom * @param \DOMElement $domNode * @param $keyElementsCnt * * @return int number of moved items */ public function moveCustomKeyAttributesIntoElements($dom, $domNode, $keyElementsCnt) { $attributesArr = array(); $totalMoved = 0; if ($domNode->hasAttributes()) { foreach ($domNode->attributes as $attr) { if (strpos($attr->nodeName, "GUIcustom_") === 0) { $elemName = str_replace("GUIcustom_", "", $attr->nodeName); $elemValue = $attr->nodeValue; if ($domNode->hasChildNodes()) { $domNode->insertBefore(new \DOMElement($elemName, $elemValue), $domNode->childNodes->item(0)); } else { $domNode->appendChild(new \DOMElement($elemName, $elemValue)); } $attributesArr[] = $attr->nodeName; $totalMoved++; } } // remove must be in new foreach, previous deletes only first one foreach ($attributesArr as $attrName) { $domNode->removeAttribute($attrName); } } if ($totalMoved < $keyElementsCnt && $domNode->hasChildNodes()) { foreach ($domNode->childNodes as $child) { $totalMoved += $this->moveCustomKeyAttributesIntoElements($dom, $child, $keyElementsCnt); } } return $totalMoved; }
/** * Compute position while computing overlay. * * @param \DOMElement $from Receiver fragment. * @param \DOMElement $to Overlay fragment. * @param array $overlays Overlays accumulator. * @return void */ private function _computeOverlayPosition(\DOMElement $from, \DOMElement $to, array &$overlays) { if (false === $to->hasAttribute('position')) { $from->appendChild($to); $overlays[] = $to; return; } $children = $from->childNodes; $positions = []; $e = 0; $search = []; $replace = []; $child = null; for ($i = 0, $m = $children->length; $i < $m; ++$i) { $child = $children->item($i); if (XML_ELEMENT_NODE != $child->nodeType) { continue; } $positions[$e] = $i; if ($child->hasAttribute('id')) { $search[] = 'element(#' . $child->getAttribute('id') . ')'; $replace[] = $e; } ++$e; } $last = count($positions); $search[] = 'last()'; $replace[] = $last; $handle = str_replace($search, $replace, $to->getAttribute('position')); $position = max(0, (int) static::evaluateXPath($handle)); if ($position < $last) { $from->insertBefore($to, $from->childNodes->item($positions[$position])); } else { $from->appendChild($to); } $to->removeAttribute('position'); $overlays[] = $to; return; }
/** * Format a DOM element. * * This function takes in a DOM element, and inserts whitespace to make it more readable. Note that whitespace * added previously will be removed. * * @param \DOMElement $root The root element which should be formatted. * @param string $indentBase The indentation this element should be assumed to have. Defaults to an empty * string. * * @throws \InvalidArgumentException If $root is not a DOMElement or $indentBase is not a string. * * @author Olav Morken, UNINETT AS <*****@*****.**> */ public static function formatDOMElement(\DOMElement $root, $indentBase = '') { if (!is_string($indentBase)) { throw new \InvalidArgumentException('Invalid input parameters'); } // check what this element contains $fullText = ''; // all text in this element $textNodes = array(); // text nodes which should be deleted $childNodes = array(); // other child nodes for ($i = 0; $i < $root->childNodes->length; $i++) { $child = $root->childNodes->item($i); if ($child instanceof \DOMText) { $textNodes[] = $child; $fullText .= $child->wholeText; } elseif ($child instanceof \DOMComment || $child instanceof \DOMElement) { $childNodes[] = $child; } else { // unknown node type. We don't know how to format this return; } } $fullText = trim($fullText); if (strlen($fullText) > 0) { // we contain textelf $hasText = true; } else { $hasText = false; } $hasChildNode = count($childNodes) > 0; if ($hasText && $hasChildNode) { // element contains both text and child nodes - we don't know how to format this one return; } // remove text nodes foreach ($textNodes as $node) { $root->removeChild($node); } if ($hasText) { // only text - add a single text node to the element with the full text $root->appendChild(new \DOMText($fullText)); return; } if (!$hasChildNode) { // empty node. Nothing to do return; } /* Element contains only child nodes - add indentation before each one, and * format child elements. */ $childIndentation = $indentBase . ' '; foreach ($childNodes as $node) { // add indentation before node $root->insertBefore(new \DOMText("\n" . $childIndentation), $node); // format child elements if ($node instanceof \DOMElement) { self::formatDOMElement($node, $childIndentation); } } // add indentation before closing tag $root->appendChild(new \DOMText("\n" . $indentBase)); }
/** * Adds a new child before a reference node * @link http://php.net/manual/en/domnode.insertbefore.php * @param DOMNode $newnode <p> * The new node. * </p> * @param DOMNode $refnode [optional] <p> * The reference node. If not supplied, <i>newnode</i> is * appended to the children. * </p> * @return DOMNode The inserted node. */ public function insertBefore(\DOMNode $newnode, \DOMNode $refnode = null) { $newNode = parent::insertBefore($newnode, $refnode); return $newNode; }
/** * Format a DOM element. * * This function takes in a DOM element, and inserts whitespace to make it more * readable. Note that whitespace added previously will be removed. * * @param DOMElement $root The root element which should be formatted. * @param string $indentBase The indentation this element should be assumed to * have. Default is an empty string. */ public static function formatDOMElement(DOMElement $root, $indentBase = '') { assert(is_string($indentBase)); /* Check what this element contains. */ $fullText = ''; /* All text in this element. */ $textNodes = array(); /* Text nodes which should be deleted. */ $childNodes = array(); /* Other child nodes. */ for ($i = 0; $i < $root->childNodes->length; $i++) { $child = $root->childNodes->item($i); if ($child instanceof DOMText) { $textNodes[] = $child; $fullText .= $child->wholeText; } elseif ($child instanceof DOMComment || $child instanceof DOMElement) { $childNodes[] = $child; } else { /* Unknown node type. We don't know how to format this. */ return; } } $fullText = trim($fullText); if (strlen($fullText) > 0) { /* We contain text. */ $hasText = TRUE; } else { $hasText = FALSE; } $hasChildNode = count($childNodes) > 0; if ($hasText && $hasChildNode) { /* Element contains both text and child nodes - we don't know how to format this one. */ return; } /* Remove text nodes. */ foreach ($textNodes as $node) { $root->removeChild($node); } if ($hasText) { /* Only text - add a single text node to the element with the full text. */ $root->appendChild(new DOMText($fullText)); return; } if (!$hasChildNode) { /* Empty node. Nothing to do. */ return; } /* Element contains only child nodes - add indentation before each one, and * format child elements. */ $childIndentation = $indentBase . ' '; foreach ($childNodes as $node) { /* Add indentation before node. */ $root->insertBefore(new DOMText("\n" . $childIndentation), $node); /* Format child elements. */ if ($node instanceof DOMElement) { self::formatDOMElement($node, $childIndentation); } } /* Add indentation before closing tag. */ $root->appendChild(new DOMText("\n" . $indentBase)); }
/** * Creates the toggle link and hidden div for extracted header and * summary element on cache pages * * @param DOMDocument $dom used to create new nodes to add to body object * for page * @param string $text_align whether rtl or ltr language * @param DOMElement $body represent body of cached page * @param string $summary_string header and summary that were extraced * @param array $cache_item contains infor about the cached item * @return DOMElement a div node with toggle link and hidden div */ function createSummaryAndToggleNodes($dom, $text_align, $body, $summary_string, $cache_item) { $first_child = $body->firstChild; $summaryNode = $this->createDomBoxNode($dom, $text_align, "display:none;", 'pre'); $summaryNode->setAttributeNS("", "id", "summary-page-id"); $summaryNode = $body->insertBefore($summaryNode, $first_child); $summary_string_prefix = ""; if (isset($cache_item[self::ROBOT_INSTANCE])) { $summary_string_prefix = "\n\n" . tl('search_controller_download_fetcher', $cache_item[self::ROBOT_INSTANCE]) . "\n\n"; } if (isset($cache_item[self::HEADER])) { //without mb_convert_encoding get conv error when do saveHTML $summary_string = $summary_string_prefix . $cache_item[self::HEADER] . "\n" . mb_convert_encoding($summary_string, "UTF-8", "UTF-8"); } $textNode = $dom->createTextNode($summary_string); $summaryNode->appendChild($textNode); $scriptNode = $dom->createElement('script'); $scriptNode = $body->insertBefore($scriptNode, $summaryNode); $textNode = $dom->createTextNode("var summary_show = 'none';"); $scriptNode->appendChild($textNode); $aDivNode = $this->createDomBoxNode($dom, $text_align); $aNode = $dom->createElement("a"); $aTextNode = $dom->createTextNode(tl('search_controller_header_summaries')); $toggle_code = "javascript:" . "summary_show = (summary_show != 'block') ? 'block' : 'none';" . "summary_pid = elt('summary-page-id');" . "summary_pid.style.display = summary_show;"; $aNode->setAttributeNS("", "onclick", $toggle_code); $aNode->setAttributeNS("", "style", "zIndex: 1;" . "text-decoration: underline; cursor: pointer"); $aNode->appendChild($aTextNode); $aDivNode->appendChild($aNode); $body->insertBefore($aDivNode, $summaryNode); return $aDivNode; }
public function AjouteHttpEquivMetas() { if ($this->autoriseAjouteHttpEquivMetas) { foreach ($this->entetes as $entete) { $meta = $entete->GetXhtmlMetaHttpEquiv($this->document); $this->elementHead->insertBefore($meta, $this->elementHead->firstChild); } $this->autoriseAjouteHttpEquivMetas = false; return true; } else { return false; } }
protected function createToElement(\DOMElement $node) { $from = $node->getElementsByTagName('from')->item(0); $ext = $node->getElementsByTagName('ext')->item(0); $dom = $node->ownerDocument; $data = ['col' => $from->childNodes->item(0)->nodeValue, 'colOff' => $ext->getAttribute('cx'), 'row' => $from->childNodes->item(2)->nodeValue, 'rowOff' => $ext->getAttribute('cy')]; $to = $dom->createElement('xdr:to'); $to->appendChild($dom->createElement('xdr:col', $data['col'])); $to->appendChild($dom->createElement('xdr:colOff', $data['colOff'])); $to->appendChild($dom->createElement('xdr:row', $data['row'])); $to->appendChild($dom->createElement('xdr:rowOff', $data['rowOff'])); $node->insertBefore($to, $from->nextSibling); $node->removeChild($ext); }
/** * Ajoute du text en premier position * * @param DOMElement $nodeParent DOMElement * @param String $value String * * @return void */ function insertTextFirst($nodeParent, $value) { $value = utf8_encode($value); $firstNode = $nodeParent->firstChild; $nodeParent->insertBefore($this->createTextNode($value), $firstNode); }
private function checkCrossForeignKeysOrder(DOMElement $table, DOMDocument $schema) { $tableName = $table->getAttribute('name'); $path = sprintf("//table[@name='%s']/column", $tableName); $xpath = new DOMXPath($schema); $columns = $xpath->evaluate($path); /* @var $columns DOMNodeList */ $primaryKeys = array(); /* @var $column DOMElement */ foreach ($columns as $column) { if ($column->getAttribute('primaryKey') && $column->getAttribute('primaryKey') == 'true') { $primaryKeys[] = $column->getAttribute('name'); } } $path = sprintf("//table[@name='%s']/foreign-key", $tableName); $xpath = new DOMXPath($schema); $foreign = $xpath->evaluate($path); /* @var $foreign DOMNodeList */ $foreignKeys = array(); /* @var $foreignKeys DOMNode */ foreach ($foreign as $foreignKey) { /** @var $child DOMElement */ $child = $foreignKey->firstChild; $foreignKeys[] = $child->getAttribute('local'); } $res = $primaryKeys == $foreignKeys; if (!$res) { $first = $foreign->item(0); $last = $foreign->item(1); $lastRemoved = $table->removeChild($last); $table->insertBefore($lastRemoved, $first); } }
/** * * @param type $dbObject * @param Entity $entity * @param type $skipBinaries * @param DOMDocument $domDoc * @param DOMElement $xmlElement * @param array $xmlElementsWithState * @return Boolean $isPublished = NULL, FALSE or TRUE */ private function addPropertiesToXML($dbObject, Entity $entity, $skipBinaries, DOMDocument $domDoc, DOMElement $xmlElement, array &$xmlElementsWithState) { $insertBeforeXmlSibling = $xmlElement->childNodes->item(0); $stateIdCreated = NULL; $stateIdTerminated = NULL; $publishedState = NULL; foreach ($dbObject as $columnName => $value) { if (strcasecmp($columnName, QueryEntity::ID_CREATED) == 0) { // Remember the 'created' timestamp for the current object. $stateIdCreated = $value; } else { if (strcasecmp($columnName, QueryEntity::ID_TERMINATED) == 0) { // Remember the 'terminated' state for the current object. $stateIdTerminated = $value; } else { if (strcasecmp($columnName, QueryEntity::ID_PUBLISHED) == 0) { // Remember the 'published' state of the current object. $publishedState = $value != NULL; } else { $property = $entity->getProperty($columnName); $typeIndicator = $property->getTypeIndicator(); if ($value != NULL) { // Check if it's a primary or foreign key. $keyIndicator = $property->getKeyIndicator(); // Output all properties, except primary and foreign keys. if ($keyIndicator != Property::KEY_PRIMARY && $keyIndicator != Property::KEY_FOREIGN) { $xmlChild = $domDoc->createElementNS($this->namespaceUri, $property->getName()); $xmlElement->insertBefore($xmlChild, $insertBeforeXmlSibling); // Adjust the String-format for some types. $value = $this->adjustValueFormat($value, $typeIndicator); // Mark specific data types. if ($typeIndicator != Property::TYPE_TEXT and $typeIndicator != Property::TYPE_DOUBLE and $typeIndicator != Property::TYPE_INTEGER) { $xmlChild->setAttribute(XmlConstants::TYPE, $typeIndicator); } // Add the value. if ($typeIndicator == Property::TYPE_TEXT) { // Text-data must always be wrapped in a CDATA section. $xmlChild->appendChild($domDoc->createCDATASection($value)); } else { $xmlChild->appendChild($domDoc->createTextNode($value)); } } } else { if ($typeIndicator === Property::TYPE_BINARY and $skipBinaries) { $xmlChild = $domDoc->createElementNS($this->namespaceUri, $property->getName()); $xmlElement->insertBefore($xmlChild, $insertBeforeXmlSibling); $xmlChild->setAttribute(XmlConstants::TYPE, $typeIndicator); // This is a 'suppressed LOB-property', i.e. with scope VALUE_P_REF. $xmlChild->setAttribute(XmlConstants::SCOPE, Scope::VALUE_P_REF); } } } } } } // Remember the state ids per xmlElement, to add the 'created' and 'terminated' attributes lateron. if ($stateIdCreated != NULL) { $xmlElementsWithState[] = array($xmlElement, $stateIdCreated, $stateIdTerminated); if ($publishedState == NULL) { $publishedState = FALSE; } } return $publishedState; }