Example #1
0
 private function removeDocumentChildElementsByName($name)
 {
     $nodes = $this->xpath->query('/phpunit/' . $name);
     foreach ($nodes as $node) {
         $this->rootElement->removeChild($node);
     }
 }
Example #2
0
 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;
 }
Example #3
0
 /**
  * Remove a child frame
  *
  * @param Frame   $child
  * @param boolean $update_node  Whether or not to remove the DOM node
  *
  * @throws DOMPDF_Exception
  * @return Frame The removed child frame
  */
 function remove_child(Frame $child, $update_node = true)
 {
     if ($child->_parent !== $this) {
         throw new DOMPDF_Exception("Child not found in this frame");
     }
     if ($update_node) {
         $this->_node->removeChild($child->_node);
     }
     if ($child === $this->_first_child) {
         $this->_first_child = $child->_next_sibling;
     }
     if ($child === $this->_last_child) {
         $this->_last_child = $child->_prev_sibling;
     }
     if ($child->_prev_sibling) {
         $child->_prev_sibling->_next_sibling = $child->_next_sibling;
     }
     if ($child->_next_sibling) {
         $child->_next_sibling->_prev_sibling = $child->_prev_sibling;
     }
     $child->_next_sibling = null;
     $child->_prev_sibling = null;
     $child->_parent = null;
     return $child;
 }
 /**
  * Removes a rule from this store (must be passed an object, not string/name). Returns TRUE if found.
  * @param Rule|SecurityRule $rule
  * @param bool $deleteForever
  * @return bool
  */
 public function remove($rule, $deleteForever = false)
 {
     $found = false;
     $serial = spl_object_hash($rule);
     if (isset($this->fastMemToIndex[$serial])) {
         $found = true;
         unset($this->fastNameToIndex[$rule->name()]);
         unset($this->rules[$this->fastMemToIndex[$serial]]);
         unset($this->fastMemToIndex[$serial]);
         $this->xmlroot->removeChild($rule->xmlroot);
         $rule->owner = null;
         if ($deleteForever) {
             $rule->cleanForDestruction();
         }
     } elseif ($this->isPreOrPost) {
         if (isset($this->fastMemToIndex_forPost[$serial])) {
             $found = true;
             unset($this->fastNameToIndex_forPost[$rule->name()]);
             unset($this->postRules[$this->fastMemToIndex_forPost[$serial]]);
             unset($this->fastMemToIndex_forPost[$serial]);
             $this->postRulesRoot->removeChild($rule->xmlroot);
             $rule->owner = null;
             if ($deleteForever) {
                 $rule->cleanForDestruction();
             }
         }
     }
     return $found;
 }
Example #5
0
 /**
  * Remove child node from element.
  *
  * @param $node
  * @return void
  */
 public function removeChildNode($node)
 {
     if (false === $node instanceof \DOMNode) {
         throw new \InvalidArgumentException('Unsupported node type');
     }
     $this->element->removeChild($node);
 }
Example #6
0
function setText(DOMElement $el, $textcontent)
{
    while ($el->firstChild) {
        $el->removeChild($el->firstChild);
    }
    if (strlen($textcontent)) {
        $el->appendChild($el->ownerDocument->createTextNode($textcontent));
    }
}
 /**
  * Remove all DOM structures to build new
  */
 public function resetDocument()
 {
     foreach ($this->getElementsByTagName('argument') as $delNode) {
         $this->__rootNode->removeChild($delNode);
     }
     foreach ($this->getElementsByTagName('resourceDescriptor') as $delNode) {
         $this->__rootNode->removeChild($delNode);
     }
     $this->__documentReady = false;
 }
 function removeSmallTags(DOMElement $element)
 {
     $subElements = $element->getElementsByTagName("small");
     try {
         foreach ($subElements as $subElement) {
             $element->removeChild($subElement);
         }
     } catch (Exception $e) {
     }
     return $element->getElementsByTagName("small")->length;
 }
 /**
  * @param string $local
  * @param string $remote
  * @return bool
  */
 function removeProxyId($local, $remote)
 {
     foreach ($this->proxys as $index => &$proxy) {
         if ($proxy['local'] == $local && $proxy['remote'] == $remote) {
             unset($this->proxys[$index]);
             $this->proxyIdRoot->removeChild($proxy['xmlroot']);
             return true;
         }
     }
     return false;
 }
Example #10
0
 private function renameTag(DOMElement $oldTag, $newTagName)
 {
     $document = $oldTag->ownerDocument;
     $newTag = $document->createElement($newTagName);
     foreach ($oldTag->attributes as $attribute) {
         $newTag->setAttribute($attribute->name, $attribute->value);
     }
     foreach ($oldTag->childNodes as $child) {
         $newTag->appendChild($oldTag->removeChild($child));
     }
     $oldTag->parentNode->replaceChild($newTag, $oldTag);
     return $newTag;
 }
Example #11
0
 /**
  * @return DOMElement
  * @throws Exception
  */
 private function getCleanDomTable()
 {
     $dom_tables = $this->doc->getElementsByTagNameNS(static::$NS_TABLE, 'table');
     if ($dom_tables->length != 1) {
         throw new Exception("Could not parse ODS template");
     }
     $this->dom_table = $dom_tables->item(0);
     $children = $this->dom_table->childNodes;
     for ($i = $children->length - 1; $i >= 0; $i--) {
         $this->dom_table->removeChild($children->item($i));
     }
     return $this->dom_table;
 }
Example #12
0
 /**
  * Filter a single element.
  *
  * @param DOMElement $element
  * @return void
  */
 public function filterElement(DOMElement $element)
 {
     $element->setProperty('type', 'footnote');
     $citations = $element->getElementsByTagNameNS(ezcDocumentOdt::NS_ODT_TEXT, 'note-citation');
     // Should be only 1, foreach to remove all
     foreach ($citations as $cite) {
         $attrs = $element->getProperty('attributes');
         if ($attrs === false) {
             $attrs = array();
         }
         $attrs['label'] = $cite->nodeValue;
         $element->setProperty('attributes', $attrs);
         $element->removeChild($cite);
     }
 }
 public function setAlternativeName($newName)
 {
     if ($newName == $this->_alternativeName) {
         return false;
     }
     if ($newName === null || strlen($newName) == 0) {
         $node = DH::findFirstElement('display-name', $this->xmlroot);
         if ($node === false) {
             return false;
         }
         $this->xmlroot->removeChild($node);
         return true;
     }
     $node = DH::findFirstElementOrCreate('display-name', $this->xmlroot);
     DH::setDomNodeText($node, $newName);
     return true;
 }
Example #14
0
 /**
  * @param \DOMElement $oldElement
  * @param string $newNamespace
  * @return mixed
  */
 public static function copyElementInNs($oldElement, $newNamespace)
 {
     $element = $oldElement->ownerDocument->createElementNS($newNamespace, $oldElement->nodeName);
     // copy attributes
     foreach (iterator_to_array($oldElement->attributes) as $attr) {
         $oldElement->removeAttributeNode($attr);
         if ($attr->namespaceURI) {
             $element->setAttributeNodeNS($attr);
         } else {
             $element->setAttributeNode($attr);
         }
     }
     // copy children
     while ($child = $oldElement->firstChild) {
         $oldElement->removeChild($child);
         $element->appendChild($child);
     }
     $oldElement->parentNode->replaceChild($element, $oldElement);
     return $element;
 }
Example #15
0
 public function setSourcePort($newPorts)
 {
     if ($newPorts === null || strlen($newPorts) == 0) {
         if (strlen($this->_sport) == 0) {
             return false;
         }
         $this->_sport = $newPorts;
         $sportroot = DH::findFirstElement('source-port', $this->tcpOrUdpRoot);
         if ($sportroot !== false) {
             $this->tcpOrUdpRoot->removeChild($sportroot);
         }
         return true;
     }
     if ($this->_sport == $newPorts) {
         return false;
     }
     if (strlen($this->_sport) == 0) {
         DH::findFirstElementOrCreate('source-port', $this->tcpOrUdpRoot, $newPorts);
         return true;
     }
     $sportroot = DH::findFirstElementOrCreate('source-port', $this->tcpOrUdpRoot);
     DH::setDomNodeText($sportroot, $newPorts);
     return true;
 }
 /**
  * @param Address|AddressGroup $s
  * @param bool $rewriteXML
  * @return bool
  */
 public function remove($s, $rewriteXML = true)
 {
     $class = get_class($s);
     $objectName = $s->name();
     if (!isset($this->all[$objectName])) {
         mdeb('Tried to remove an object that is not part of this store');
         return false;
     }
     unset($this->all[$objectName]);
     if ($class == 'Address') {
         if ($s->isTmpAddr()) {
             unset($this->tmpaddr[$objectName]);
         } else {
             unset($this->addr[$objectName]);
         }
     } else {
         if ($class == 'AddressGroup') {
             unset($this->addrg[$objectName]);
         } else {
             derr('invalid class found');
         }
     }
     $s->owner = null;
     if ($rewriteXML && !$s->isTmpAddr()) {
         if ($class == "Address") {
             $this->addrroot->removeChild($s->xmlroot);
         } else {
             if ($class == "AddressGroup") {
                 $this->addrgroot->removeChild($s->xmlroot);
             } else {
                 derr('unsupported');
             }
         }
     }
     return true;
 }
Example #17
0
 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);
 }
Example #18
0
 /**
  * Builds the service options node
  *
  * @access protected
  * @param DOMElement $dom_element
  * @return boolean|DOMElement
  */
 protected function buildRequest_ServiceOptions(&$dom_element)
 {
     // build our elements
     $service_options = $dom_element->appendChild(new DOMElement('ShipmentServiceOptions'));
     $on_call_air = $service_options->appendChild(new DOMElement('OnCallAir'));
     $schedule = $on_call_air->appendChild(new DOMElement('Schedule'));
     // check to see if this is a satruday pickup
     if (isset($this->shipment['saturday']['pickup']) && $this->shipment['saturday']['pickup'] !== false) {
         $service_options->appendChild(new DOMElement('SaturdayPickup'));
     }
     // end if this is a saturday pickup
     // check to see if this is a saturday delivery
     if (isset($this->shipment['saturday']['delivery']) && $this->shipment['saturday']['delivery'] !== false) {
         $service_options->appendChild(new DOMElement('SaturdayDelivery'));
     }
     // end if this is a saturday delivery
     // check to see if we have a pickup day
     if (isset($this->shipment['pickup_day'])) {
         $schedule->appendChild(new DOMElement('PickupDay', $this->shipment['pickup_day']));
     }
     // end if we have a pickup day
     // check to see if we have a scheduling method
     if (isset($this->shipment['scheduling_method'])) {
         $schedule->appendChild(new DOMElement('Method', $this->shipment['scheduling_method']));
     }
     // end if we have a scheduling method
     // check to see if we have on call air options
     if (!$schedule->hasChildNodes()) {
         $service_options->removeChild($on_call_air);
     }
     // end if we have on call air options
     // check to see if we have service options
     if (!$service_options->hasChildNodes()) {
         $dom_element->removeChild($service_options);
         return false;
     }
     // end if we do not have service options
     return $service_options;
 }
Example #19
0
 /**
  * Removes all children from a DOMElement
  * @param DOMElement $node
  */
 private function removeDOMChildren(\DOMElement $node)
 {
     while ($node->firstChild) {
         while ($node->firstChild->firstChild) {
             self::removeDOMChildren($node->firstChild);
         }
         $node->removeChild($node->firstChild);
     }
 }
 /**
  * @param DOMElement $xml
  *      * should only be called from a Rule constructor
  * @ignore
  */
 public function load_from_domxml($xml)
 {
     $this->xmlroot = $xml;
     $toBeCleaned = array();
     foreach ($xml->childNodes as $node) {
         if ($node->nodeType != 1) {
             continue;
         }
         if (strlen($node->textContent) < 1) {
             mwarning('invalid (empty) tag name found in rule "' . $this->owner->toString() . '", IT WILL BE CLEANED', $node);
             $toBeCleaned[] = $node;
         } else {
             $f = $this->parentCentralStore->findOrCreate($node->textContent, $this);
             $this->o[] = $f;
         }
     }
     foreach ($toBeCleaned as $cleanMe) {
         $xml->removeChild($cleanMe);
     }
 }
Example #21
0
 /**
  * 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));
 }
Example #22
0
 /**
  * Adds comments around the <!CDATA section in a dom element
  *
  * This function attempts to solve the problem by creating a DocumentFragment,
  * commenting the CDATA tag.
  *
  * @param  DOMDocument  $dom_document   The DOMDocument containing the $dom_element
  * @param  DOMElement   $dom_element    The element potentially containing a CDATA node
  * @param  string       $comment_start  String to use as a comment start marker to escape the CDATA declaration [Optional]
  * @param  string       $comment_end    String to use as a comment end marker to escape the CDATA declaration [Optional]
  */
 private static function escape_cdata_element(DOMDocument $dom_document, DOMElement $dom_element, $comment_start = '//', $comment_end = '')
 {
     foreach ($dom_element->childNodes as $node) {
         if (get_class($node) == 'DOMCdataSection') {
             $embed_prefix = PHP_EOL . "<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}" . PHP_EOL;
             $embed_suffix = PHP_EOL . "{$comment_start}--><!]]>{$comment_end}" . PHP_EOL;
             // Prevent invalid cdata escaping as this would throw a DOM error.
             // This is the same behavior as found in libxml2.
             // Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection
             // Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting
             $data = str_replace(']]>', ']]]]><![CDATA[>', $node->data);
             $fragment = $dom_document->createDocumentFragment();
             $fragment->appendXML($embed_prefix . $data . $embed_suffix);
             $dom_element->appendChild($fragment);
             $dom_element->removeChild($node);
         }
     }
 }
Example #23
0
 /**
  * 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));
 }
 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++;
     }
 }
 /**
  * empty all childs from node
  * @param $parentNode
  * @return DOMElement
  */
 public function empty_node(DOMElement $parentNode)
 {
     while ($parentNode->hasChildNodes()) {
         $parentNode->removeChild($parentNode->firstChild);
     }
     return new self(null, $parentNode);
 }
Example #26
0
 /**
  * removes all children of element except of key elements, which has to remain
  *
  * @param      \DOMElement  $domNode
  * @param      \DOMNodeList $domNodeChildren
  * @param bool              $leaveKey
  * @param bool              $recursive
  *
  * @return int  number of key elements, that remains
  */
 public function removeChildrenExceptOfKeyElements($domNode, $domNodeChildren, $leaveKey = false, $recursive = false)
 {
     $keyElemIndex = $keyElemsCnt = 0;
     while ($domNodeChildren->length > $keyElemIndex) {
         $isKey = $isCreated = false;
         $child = $domNodeChildren->item($keyElemIndex);
         if ($child->hasAttributes()) {
             foreach ($child->attributes as $attr) {
                 if ($attr->nodeName == "iskey" && $attr->nodeValue == "true") {
                     if ($child->hasAttributes()) {
                         foreach ($child->attributes as $attr) {
                             if ($attr->nodeName !== 'xc:operation') {
                                 $attributesArr[] = $attr->nodeName;
                             }
                         }
                         // remove must be in new foreach, previous deletes only first one
                         foreach ($attributesArr as $attrName) {
                             $child->removeAttribute($attrName);
                         }
                     }
                     if ($leaveKey == true) {
                         $keyElemIndex++;
                         $isKey = true;
                     } else {
                         if (isset($child)) {
                             $nodeName = $child->nodeName;
                             $nodeValue = $child->nodeValue;
                             $domNode->setAttribute("GUIcustom_" . $nodeName, $nodeValue);
                         }
                     }
                     $keyElemsCnt++;
                 } elseif ($attr->nodeName == "xc:operation" && $attr->nodeValue == "create") {
                     $keyElemIndex++;
                     $isCreated = true;
                 }
             }
         }
         if (!$isKey && !$isCreated || $leaveKey == false) {
             try {
                 $childrenRemains = 0;
                 // recursively check all children for their key elements
                 if (sizeof($child->childNodes) && $recursive) {
                     foreach ($child->childNodes as $chnode) {
                         if (sizeof($chnode->childNodes)) {
                             $childrenRemains += $this->removeChildrenExceptOfKeyElements($chnode, $chnode->childNodes, $leaveKey, $recursive);
                         }
                     }
                 }
                 if ($childrenRemains == 0) {
                     $domNode->removeChild($child);
                 } else {
                     $keyElemIndex++;
                 }
             } catch (\DOMException $e) {
             }
         }
     }
     if ($domNode->hasAttributes()) {
         foreach ($domNode->attributes as $attr) {
             if (strpos($attr->nodeName, "GUIcustom_") !== 0) {
                 $attributesArr[] = $attr->nodeName;
             }
         }
         // remove must be in new foreach, previous deletes only first one
         foreach ($attributesArr as $attrName) {
             $domNode->removeAttribute($attrName);
         }
     }
     return $keyElemsCnt;
 }
Example #27
0
 /**
  * initHandlerHeader (init handler, pass 2 before childre tags)
  * sets anchor as attribute if setting is enabled
  *
  * @param DOMElement $element
  * @param array $param parameters for xml element
  * @return bool|null
  */
 function initHandlerHeader($element, &$params)
 {
     if ($this->anchorAsAttribute) {
         $anchorElement = $element->firstChild;
         if ($anchorElement->nodeName === 'anchor') {
             $element->setAttribute('anchor_name', $anchorElement->getAttribute('name'));
             $anchorElement = $element->removeChild($anchorElement);
         }
     }
     self::elementStylesToAttribute($element);
     return null;
 }
Example #28
0
 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;
 }
Example #29
0
 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);
     }
 }
/**
 * Applies high security restrictions to HTML input from moderated comments.
 * Recursive function.
 * @param $element DOM element
 */
function oublog_apply_high_security(DOMElement $element)
{
    // Note that Moodle security should probably already prevent this (and
    // should include a whitelist approach), but just to increase the paranoia
    // level a bit with these comments.
    static $allowtags = array('html' => 1, 'body' => 1, 'em' => 1, 'strong' => 1, 'b' => 1, 'i' => 1, 'del' => 1, 'sup' => 1, 'sub' => 1, 'span' => 1, 'a' => 1, 'img' => 1, 'p' => 1, 'div' => 1);
    // Chuck away any disallowed tags
    if (!array_key_exists(strtolower($element->tagName), $allowtags)) {
        $parent = $element->parentNode;
        while ($child = $element->firstChild) {
            $element->removeChild($child);
            $parent->insertBefore($child, $element);
            if ($child->nodeType == XML_ELEMENT_NODE) {
                oublog_apply_high_security($child);
            }
        }
        $parent->removeChild($element);
        return;
    }
    // Chuck away all attributes except href, src pointing to a folder or HTML, image
    // (this prevents SWF embed by link, if site is unwise enough to have that
    // turned on)
    $attributenames = array();
    $keepattributes = array();
    foreach ($element->attributes as $name => $value) {
        $attributenames[] = $name;
        $keep = false;
        if ($name === 'href' && preg_match('~^https?://~', $value->nodeValue)) {
            $keep = true;
        } else {
            if ($name === 'src' && preg_match('~^https?://.*\\.(jpg|jpeg|png|gif|svg)$~', $value->nodeValue)) {
                $keep = true;
            } else {
                if ($name === 'alt') {
                    $keep = true;
                }
            }
        }
        if ($keep) {
            $keepattributes[$name] = $value->nodeValue;
        }
    }
    foreach ($attributenames as $name) {
        $element->removeAttribute($name);
    }
    foreach ($keepattributes as $name => $value) {
        $element->setAttribute($name, $value);
    }
    // Recurse to children
    $children = array();
    foreach ($element->childNodes as $child) {
        $children[] = $child;
    }
    foreach ($children as $child) {
        if ($child->nodeType == XML_ELEMENT_NODE) {
            oublog_apply_high_security($child);
        }
    }
}