Ejemplo n.º 1
1
 function props_to_xml()
 {
     # make the source xml
     # make doc and root
     $xml = new DomDocument();
     $root = $xml->createElement('request');
     $root->setAttribute('controller', params('controller'));
     $root->setAttribute('action', params('action'));
     $root = $xml->appendChild($root);
     # unpack the props into xml
     foreach ($this->props as $k => $v) {
         # if it will become xml, do that, otherwise make a dumb tag
         if (is_object($v) && method_exists($v, 'to_xml')) {
             $obj_xml = $v->to_xml(array(), true, true);
             $obj_xml = $xml->importNode($obj_xml->documentElement, true);
             $root->appendChild($obj_xml);
         } else {
             $node = $xml->createElement($k);
             if (strpos($v, '<') !== false || strpos($v, '>') !== false || strpos($v, '&') !== false) {
                 $cdata = $xml->createCDATASection($v);
             } else {
                 $cdata = $xml->createTextNode($v);
             }
             $node->appendChild($cdata);
             $node = $root->appendChild($node);
         }
     }
     return $xml;
 }
Ejemplo n.º 2
0
 /**
  * Renders the gathered nodes into a XML document.
  *
  * @param string $xml Text to be imported to a DomDocument.
  *
  * @return XmlManipulator
  */
 public function renderDocument($xml)
 {
     $this->document = $this->initDomDocument($xml);
     foreach ($this->nodes as $nodeXml) {
         $mergeDoc = $this->initDomDocument($nodeXml);
         $importNode = $mergeDoc->getElementsByTagNameNS('http://symfony.com/schema/dic/constraint-mapping', 'class')->item(0);
         $importNode = $this->document->importNode($importNode, true);
         $this->document->documentElement->appendChild($importNode);
     }
     return $this;
 }
Ejemplo n.º 3
0
 static function response($status, $status_message, $domdocument = null)
 {
     $dom = new DomDocument('1.0', 'UTF-8');
     $results = $dom->appendChild($dom->createElement('response'));
     $results->appendChild($dom->createElement('status', $status));
     $results->appendChild($dom->createElement('status_message', $status_message));
     if (is_null($domdocument)) {
         $domdocument = new DomDocument('1.0', 'UTF-8');
         $domdocument->appendChild($domdocument->createElement('data'));
     }
     if ($domdocument->documentElement->nodeName === 'data') {
         $newdom = $domdocument;
     } else {
         $newdom = new DOMDocument('1.0', 'UTF-8');
         $data = $newdom->appendChild($newdom->createElement('data'));
         foreach ($domdocument->documentElement->childNodes as $domElement) {
             $domNode = $newdom->importNode($domElement, true);
             $data->appendChild($domNode);
         }
     }
     $import = $dom->importNode($newdom->documentElement, TRUE);
     $results->appendChild($import);
     $dom->formatOutput = true;
     echo $dom->saveXML();
 }
Ejemplo n.º 4
0
 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);
 }
Ejemplo n.º 5
0
 protected function injectText(DOMNode $parent, DOMNode $sibling, $string)
 {
     $textNode = new DOMText();
     $textNode->nodeValue = $string;
     $textNode = $this->templateDocument->importNode($textNode);
     $parent->insertBefore($textNode, $sibling);
 }
Ejemplo n.º 6
0
 /**
  * This method replace the <abbr> tag with a new html tag.
  * @param DomDocument $parentDom
  * @param array $wikiInfo
  * @param string $text
  * @param DomElement $oldNode
  */
 private function replaceDomNode($parentDom, $wikiInfo, $text, $oldNode)
 {
     $wikiInfo = (array) $wikiInfo;
     $urlPattern = stripslashes(get_option('wikiUrlPattern'));
     $newUrl = str_replace('$articleurl', $wikiInfo['wikiurl'], $urlPattern);
     $newUrl = str_replace('$title', $wikiInfo['title'], $newUrl);
     $newUrl = str_replace('$text', $text, $newUrl);
     $newDom = new DOMDocument();
     $newDom->loadHTML($newUrl);
     $node = $newDom->getElementsByTagName("a")->item(0);
     $oldNode->parentNode->replaceChild($parentDom->importNode($node, true), $oldNode);
 }
Ejemplo n.º 7
0
 /**
  * Returns a SimpleXMLElement for the given config.
  * 
  * @see    Zend_Build_Resource_Interface
  * @param  Zend_Build_Resource_Interface Resource to convert to XML
  * @return string String in valid XML 1.0 format
  */
 public static function getXmlForConfig(Zend_Config $config)
 {
     // First create the empty XML element
     $xml = self::_arrayToXml($config->toArray(), new SimpleXMLElement('<' . self::CONFIG_XML_ROOT_ELEMENT . '/>'), true);
     // Format output for readable XML and save to $filename
     $dom = new DomDocument('1.0');
     $domnode = dom_import_simplexml($xml);
     $domnode = $dom->importNode($domnode, true);
     $domnode = $dom->appendChild($domnode);
     $dom->formatOutput = true;
     return $dom->saveXML();
 }
Ejemplo n.º 8
0
 /**
  * Merge two SimpleXMLElements into a single object
  * @param SimpleXMLElement $xml1
  * @param SimpleXMLElement $xml2
  */
 public static function SimpleXml_Merge(SimpleXMLElement &$xml1, SimpleXMLElement $xml2)
 {
     $dom1 = new DomDocument();
     $dom2 = new DomDocument();
     $dom1->loadXML($xml1->asXML());
     $dom2->loadXML($xml2->asXML());
     $xpath = new domXPath($dom2);
     $xpathQuery = $xpath->query('/*/*');
     for ($i = 0; $i < $xpathQuery->length; $i++) {
         $dom1->documentElement->appendChild($dom1->importNode($xpathQuery->item($i), true));
     }
     $xml1 = simplexml_import_dom($dom1);
 }
Ejemplo n.º 9
0
 public static function unmarshalRoot($string)
 {
     $dom = new \DomDocument();
     $dom->loadXml($string);
     $xpath = new \DomXPath($dom);
     $query = "child::*";
     $childs = $xpath->query($query);
     $binding = array();
     foreach ($childs as $child) {
         $legko = new Bind();
         $lDom = new \DomDocument();
         $lDom->appendChild($lDom->importNode($child, true));
         $binding = $legko->unmarshal($lDom->saveXml());
     }
     return $binding;
 }
Ejemplo n.º 10
0
function simplexml_mergeLand(SimpleXMLElement &$xml1, SimpleXMLElement $xml2)
{
    // convert SimpleXML objects into DOM ones
    $dom1 = new DomDocument();
    $dom2 = new DomDocument();
    $dom1->loadXML($xml1->asXML());
    $dom2->loadXML($xml2->asXML());
    // pull all child elements of second XML
    $xpath = new domXPath($dom2);
    $xpathQuery = $xpath->query('/propertyList/land');
    for ($i = 0; $i < $xpathQuery->length; $i++) {
        // and pump them into first one
        $dom1->documentElement->appendChild($dom1->importNode($xpathQuery->item($i), true));
    }
    // for($i = 0; $i < $xpathQuery->length; $i++)
    $xml1 = simplexml_import_dom($dom1);
}
Ejemplo n.º 11
0
 public function matches($schemaFile)
 {
     foreach ($this->xml as $id => $dom) {
         $configElement = $dom->getElementsByTagName('config');
         if (1 !== $configElement->length) {
             throw new \InvalidArgumentException(sprintf('Can only test a file if it contains 1 <config> element, %d given', $configElement->length));
         }
         $configDom = new \DomDocument();
         $configDom->appendChild($configDom->importNode($configElement->item(0), true));
         libxml_use_internal_errors(true);
         if (!$configDom->schemaValidate($schemaFile)) {
             $this->errors = libxml_get_errors();
             $this->failingElement = $id;
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 12
0
 public function filterTables()
 {
     $this->filter = $this->query->query(sprintf("//value[@struct-name='db.mysql.Table']"));
     if ($this->filter instanceof DOMNodeList and $this->filter->length > 0) {
         $f = $this->filter;
         for ($i = 0; $i < $f->length; $i++) {
             $owner = $f->item($i)->getAttribute("id");
             $x = new DOMXPath($this->reader);
             $res = $x->query("//value[@id='{$owner}']/value[@key='columns']");
             $y = new DOMXPath($this->reader);
             $fks = $y->query("//value[@id='{$owner}']/value[@key='foreignKeys']");
             $node = $f->item($i);
             $node->setAttribute("key", "tables");
             if ($node) {
                 $node = $f->item($i);
                 $cols = $this->writer->createElement("value");
                 $cols->setAttribute("key", "columns");
                 for ($j = 0; $j < $res->length; $j++) {
                     $cols->appendChild($this->writer->importNode($res->item($j), true));
                 }
                 $this->writer->documentElement->appendChild($this->writer->importNode($node, true));
                 $this->writer->documentElement->childNodes->item($i)->appendChild($cols);
                 $fk = $this->writer->createElement("value");
                 $fk->setAttribute("key", "foreignkeys");
                 for ($j = 0; $j < $fks->length; $j++) {
                     $fk->appendChild($this->writer->importNode($fks->item($j), true));
                 }
                 $this->writer->documentElement->childNodes->item($i)->appendChild($fk);
             }
         }
         $res = $this->query->query("//value[@key='catalog']/value[@key='schemata']/value[@struct-name='db.mysql.Schema']/value[@key='comment']/text()");
         if ($res->length > 0) {
             $json = preg_replace('/([{,])(\\s*)([^"]+?)\\s*:/', '$1"$3":', trim((string) $res->item(0)->nodeValue));
             $obj = json_decode($json, true);
             $control = $this->writer->createElement("application");
             $control->setAttribute("key", "install");
             foreach ($obj as $key => $val) {
                 $control->setAttribute($key, $val);
             }
             $this->writer->documentElement->lastChild->appendChild($control);
         }
     }
     return $this;
 }
Ejemplo n.º 13
0
 /**
  * given some content that might be html or xhtml, try to coerce it to xhtml and return it.
  *
  * @param string $content some html or xhtmlish content
  *
  * @return xhtml content or false for unmodified text content
  */
 public static function parse_xhtmlish_content($content, $viewid = null)
 {
     $dom = new DomDocument();
     $topel = $dom->createElement('tmp');
     $tmp = new DomDocument();
     if (strpos($content, '<') === false && strpos($content, '>') === false) {
         return false;
     }
     if (@$tmp->loadXML('<div>' . $content . '</div>')) {
         $topel->setAttribute('type', 'xhtml');
         $content = $dom->importNode($tmp->documentElement, true);
         $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
         $topel->appendChild($content);
         // if that fails, it could still be html
         // DomDocument::loadHTML() parses the input as iso-8859-1 if no
         // encoding is declared. Since we are only loading a HTML fragment
         // there is no  encoding declared which results in garbled output
         // since the content is actually in utf-8. To work around this
         // we force the encoding by appending an xml declaration.
         // see http://php.net/manual/de/domdocument.loadhtml.php#95251
     } else {
         if (@$tmp->loadHTML('<?xml encoding="UTF-8"><div>' . $content . '</div>')) {
             $xpath = new DOMXpath($tmp);
             $elements = $xpath->query('/html/body/div');
             if ($elements->length != 1) {
                 if ($viewid) {
                     log_warn("Leap2a export: invalid html found in view {$viewid}");
                 }
                 if ($elements->length < 1) {
                     return false;
                 }
             }
             $ourelement = $elements->item(0);
             $content = $dom->importNode($ourelement, true);
             $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
             $topel->appendChild($content);
         } else {
             return false;
             // wtf is it then?
         }
     }
     $dom->appendChild($topel->firstChild);
     return $dom->saveXML($dom->documentElement);
 }
Ejemplo n.º 14
0
 public function getRowsToProcess($filesToProcess)
 {
     # Get some more detailed error information from libxml
     libxml_use_internal_errors(true);
     $log = null;
     try {
         # Logger for this processor
         $writer = new Zend_Log_Writer_Stream(Mage::getBaseDir('log') . DS . 'order_status_import_processor_xml.log');
         $log = new Zend_Log($writer);
     } catch (Exception $e) {
         # Do nothing.. :|
     }
     # Updates to process, later the result
     $updatesInFilesToProcess = array();
     # Get mapping model
     $this->mappingModel = Mage::getModel('orderstatusimport/processor_mapping_fields');
     $this->mappingModel->setDataPath('orderstatusimport/processor_xml/import_mapping');
     # Load mapping
     $this->mapping = $this->mappingModel->getMappingConfig();
     # Load configuration:
     $config = array('IMPORT_DATA_XPATH' => Mage::getStoreConfig('orderstatusimport/processor_xml/xpath_data'), 'IMPORT_SHIPPED_ONE_FIELD' => Mage::getStoreConfigFlag('orderstatusimport/processor_xml/shipped_one_field'), 'IMPORT_NESTED_ITEMS' => Mage::getStoreConfigFlag('orderstatusimport/processor_xml/node_nested_items'), 'IMPORT_NESTED_ITEM_XPATH' => Mage::getStoreConfig('orderstatusimport/processor_xml/node_nested_path'), 'IMPORT_NESTED_TRACKINGS' => Mage::getStoreConfigFlag('orderstatusimport/processor_xml/node_nested_trackings'), 'IMPORT_NESTED_TRACKING_XPATH' => Mage::getStoreConfig('orderstatusimport/processor_xml/node_nested_tracking_path'));
     if ($this->mapping->getOrderNumber() == null) {
         Mage::throwException('Please configure the XML processor in the configuration section of the Tracking Number Import Module. The order number field may not be empty and must be mapped.');
     }
     if ($config['IMPORT_DATA_XPATH'] == '') {
         Mage::throwException('Please configure the XML Processor in the configuration section of the Tracking Number Import Module. The Data XPath field may not be empty.');
     }
     foreach ($filesToProcess as $importFile) {
         $data = $importFile['data'];
         $filename = $importFile['filename'];
         $type = $importFile['type'];
         unset($importFile['data']);
         // Remove UTF8 BOM
         $bom = pack('H*', 'EFBBBF');
         $data = preg_replace("/^{$bom}/", '', $data);
         $updatesToProcess = array();
         // Prepare data - replace namespace
         $data = str_replace('xmlns=', 'ns=', $data);
         // http://www.php.net/manual/en/simplexmlelement.xpath.php#96153
         $data = str_replace('xmlns:', 'ns:', $data);
         // http://www.php.net/manual/en/simplexmlelement.xpath.php#96153
         try {
             $xmlDOM = new DOMDocument();
             $xmlDOM->loadXML($data);
         } catch (Exception $e) {
             $errors = "Could not load XML File '" . $filename . "' from '" . $type . "':\n" . $e->getMessage();
             foreach (libxml_get_errors() as $error) {
                 $errors .= "\t" . $error->message;
             }
             if ($log instanceof Zend_Log) {
                 $log->info($errors);
             }
             continue;
             # Process next file..
         }
         if (!$xmlDOM) {
             $errors = "Could not load XML File '" . $filename . "' from '" . $type . "':\n" . $e->getMessage();
             foreach (libxml_get_errors() as $error) {
                 $errors .= "\t" . $error->message;
             }
             if ($log instanceof Zend_Log) {
                 $log->info($errors);
             }
             continue;
             # Process next file..
         }
         $domXPath = new DOMXPath($xmlDOM);
         $updates = $domXPath->query($config['IMPORT_DATA_XPATH']);
         foreach ($updates as $update) {
             // Init "sub dom"
             $updateDOM = new DomDocument();
             $updateDOM->appendChild($updateDOM->importNode($update, true));
             $updateXPath = new DOMXPath($updateDOM);
             $this->update = $updateXPath;
             $orderNumber = $this->getFieldData('order_number');
             if (empty($orderNumber)) {
                 continue;
             }
             $carrierCode = $this->getFieldData('carrier_code');
             $carrierName = $this->getFieldData('carrier_name');
             $trackingNumber = $this->getFieldData('tracking_number');
             $status = $this->getFieldData('order_status');
             $orderComment = $this->getFieldData('order_status_history_comment');
             $skuToShip = strtolower($this->getFieldData('sku'));
             $qtyToShip = $this->getFieldData('qty');
             $customData1 = $this->getFieldData('custom1');
             $customData2 = $this->getFieldData('custom2');
             if (!isset($updatesToProcess[$orderNumber])) {
                 $updatesToProcess[$orderNumber] = array("STATUS" => $status, "ORDER_COMMENT" => $orderComment, "CUSTOM_DATA1" => $customData1, "CUSTOM_DATA2" => $customData2);
                 $updatesToProcess[$orderNumber]['tracks'] = array();
                 if ($config['IMPORT_NESTED_TRACKINGS']) {
                     // Tracking data is nested..
                     $tracks = $updateXPath->query($config['IMPORT_NESTED_TRACKING_XPATH']);
                     foreach ($tracks as $track) {
                         $this->track = $track;
                         $carrierCode = $this->getFieldData('carrier_code', 'track');
                         $carrierName = $this->getFieldData('carrier_name', 'track');
                         $trackingNumber = $this->getFieldData('tracking_number', 'track');
                         if ($trackingNumber !== '') {
                             $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                             $trackingNumbers = explode(";", $trackingNumber);
                             // Multiple tracking numbers in one field
                             foreach ($trackingNumbers as $trackingNumber) {
                                 $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                             }
                         }
                     }
                 } else {
                     if ($trackingNumber !== '') {
                         $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                         $trackingNumbers = explode(";", $trackingNumber);
                         // Multiple tracking numbers in one field
                         foreach ($trackingNumbers as $trackingNumber) {
                             $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                         }
                     }
                 }
                 $updatesToProcess[$orderNumber]['items'] = array();
                 $itemsToAdd = array();
                 if ($config['IMPORT_NESTED_ITEMS']) {
                     // Item data is nested..
                     $items = $updateXPath->query($config['IMPORT_NESTED_ITEM_XPATH']);
                     foreach ($items as $item) {
                         $this->item = $item;
                         $skuToShip = strtolower($this->getFieldData('sku', 'item'));
                         $qtyToShip = $this->getFieldData('qty', 'item');
                         if ($skuToShip !== '') {
                             $itemsToAdd[$skuToShip] = $qtyToShip;
                         }
                     }
                 } else {
                     if ($skuToShip !== '') {
                         $itemsToAdd[$skuToShip] = $qtyToShip;
                     }
                 }
                 foreach ($itemsToAdd as $skuToShip => $qtyToShip) {
                     if ($config['IMPORT_SHIPPED_ONE_FIELD'] == true) {
                         // We're supposed to import the SKU and Qtys all from one field. Each combination separated by a ; and sku/qty separated by :
                         $skuAndQtys = explode(";", $skuToShip);
                         foreach ($skuAndQtys as $skuAndQty) {
                             list($sku, $qty) = explode(":", $skuAndQty);
                             $sku = strtolower($sku);
                             if ($sku !== '') {
                                 $updatesToProcess[$orderNumber]['items'][$sku] = array("SKU" => $sku, "QTY" => $qty);
                             }
                         }
                     } else {
                         // One row per SKU and QTY
                         if ($skuToShip !== '') {
                             if (isset($updatesToProcess[$orderNumber]['items'][$skuToShip])) {
                                 $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $updatesToProcess[$orderNumber]['items'][$skuToShip]['QTY'] + $qtyToShip);
                             } else {
                                 $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $qtyToShip);
                             }
                         }
                     }
                 }
             } else {
                 /*$orderNumber .= "|" . uniqid();
                   $updatesToProcess[$orderNumber] = array(
                       "STATUS" => "",
                       "ORDER_COMMENT" => "",
                       "CUSTOM_DATA1" => "",
                       "CUSTOM_DATA2" => "",
                   );*/
                 // Add multiple tracking numbers and items to ship to $updates
                 if ($config['IMPORT_NESTED_TRACKINGS']) {
                     // Tracking data is nested..
                     $tracks = $updateXPath->query($config['IMPORT_NESTED_TRACKING_XPATH']);
                     foreach ($tracks as $track) {
                         // Init "sub dom"
                         $trackDOM = new DomDocument();
                         $trackDOM->appendChild($trackDOM->importNode($track, true));
                         $trackXPath = new DOMXPath($trackDOM);
                         $this->track = $trackXPath;
                         $carrierCode = $this->getFieldData('carrier_code', 'track');
                         $carrierName = $this->getFieldData('carrier_name', 'track');
                         $trackingNumber = $this->getFieldData('tracking_number', 'track');
                         if ($trackingNumber !== '') {
                             $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                             $trackingNumbers = explode(";", $trackingNumber);
                             // Multiple tracking numbers in one field
                             foreach ($trackingNumbers as $trackingNumber) {
                                 $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                             }
                         }
                     }
                 } else {
                     if ($trackingNumber !== '') {
                         $trackingNumber = str_replace(array("/", ",", "|"), ";", $trackingNumber);
                         $trackingNumbers = explode(";", $trackingNumber);
                         // Multiple tracking numbers in one field
                         foreach ($trackingNumbers as $trackingNumber) {
                             $updatesToProcess[$orderNumber]['tracks'][$trackingNumber] = array("TRACKINGNUMBER" => $trackingNumber, "CARRIER_CODE" => $carrierCode, "CARRIER_NAME" => $carrierName);
                         }
                     }
                 }
                 $itemsToAdd = array();
                 if ($config['IMPORT_NESTED_ITEMS']) {
                     // Item data is nested..
                     $items = $updateXPath->query($config['IMPORT_NESTED_ITEM_XPATH']);
                     foreach ($items as $item) {
                         $this->item = $item;
                         $skuToShip = strtolower($this->getFieldData('sku', 'item'));
                         $qtyToShip = $this->getFieldData('qty', 'item');
                         if ($skuToShip !== '') {
                             if (isset($itemsToAdd[$skuToShip])) {
                                 $itemsToAdd[$skuToShip] = $itemsToAdd[$skuToShip] + $qtyToShip;
                             } else {
                                 $itemsToAdd[$skuToShip] = $qtyToShip;
                             }
                         }
                     }
                 } else {
                     if ($skuToShip !== '') {
                         if (isset($itemsToAdd[$skuToShip])) {
                             $itemsToAdd[$skuToShip] = $itemsToAdd[$skuToShip] + $qtyToShip;
                         } else {
                             $itemsToAdd[$skuToShip] = $qtyToShip;
                         }
                     }
                 }
                 foreach ($itemsToAdd as $skuToShip => $qtyToShip) {
                     if ($skuToShip !== '') {
                         if (isset($updatesToProcess[$orderNumber]['items'][$skuToShip])) {
                             $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $updatesToProcess[$orderNumber]['items'][$skuToShip]['QTY'] + $qtyToShip);
                         } else {
                             $updatesToProcess[$orderNumber]['items'][$skuToShip] = array("SKU" => $skuToShip, "QTY" => $qtyToShip);
                         }
                     }
                 }
             }
         }
         // File processed
         $updatesInFilesToProcess[] = array("FILE_INFORMATION" => $importFile, "HAS_SKU_INFO" => $this->mapping->getSku() !== null ? true : false, "ORDERS" => $updatesToProcess);
     }
     #ini_set('xdebug.var_display_max_depth', 10);
     #Zend_Debug::dump($updatesToProcess);
     #die();
     return $updatesInFilesToProcess;
 }
Ejemplo n.º 15
0
 /**
  * 
  * gets a dom to append and an element and another dom to append into them.
  * @param DomDocument $domToAppend
  * @param DOMElement $element
  * @param DomDocument $elementsDom
  * @throws Exception
  */
 public static function appendDomToElement(DomDocument $domToAppend, DOMElement &$element, DomDocument $elementsDom)
 {
     if ($domToAppend->documentElement != NULL) {
         $importedNode = $elementsDom->importNode($domToAppend->documentElement, true);
         //Add him to the output reference elements
         $element->appendChild($importedNode);
     } else {
         //DO nothing because the Dom is empty
         //			throw new Exception("The dom to append document element was null : " . $domToAppend);
     }
 }
Ejemplo n.º 16
0
 /**
  * Convert this document from SXE to DOM
  * 
  * @return DomDocument
  */
 public function toDom()
 {
     $dom_sxe = dom_import_simplexml($this->sxe);
     $dom = new DomDocument();
     $dom_sxe = $dom->importNode($dom_sxe, true);
     $dom_sxe = $dom->appendChild($dom_sxe);
     return $dom;
 }
    /**
     * Returns a DOM structure of the content object and it's attributes.
     *
     * Transaction unsafe. If you call several transaction unsafe methods you must enclose
     * the calls within a db transaction; thus within db->begin and db->commit.
     *
     * @param mixed $package
     * @param int|bool $specificVersion Content object version, true for current version, false for all, else array containing specific versions.
     * @param array|bool $options Package options or false
     * @param int[]|bool $contentNodeIDArray Array of allowed nodes or false
     * @param int[]|bool $topNodeIDArray Array of top nodes in current package export or false
     * @return bool|DOMElement
     */
    function serialize( $package, $specificVersion = false, $options = false, $contentNodeIDArray = false, $topNodeIDArray = false )
    {
        if ( $options &&
             $options['node_assignment'] == 'main' )
        {
            if ( !isset( $contentNodeIDArray[$this->attribute( 'main_node_id' )] ) )
            {
                return false;
            }
        }

        $dom = new DomDocument();
        $objectNode = $dom->createElementNS( 'http://ez.no/ezobject', 'ezremote:object' );

        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:id', $this->ID );
        $objectNode->setAttribute( 'name', $this->Name );
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:section_id', $this->SectionID );
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:owner_id', $this->OwnerID );
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:class_id', $this->ClassID );
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:published', eZDateUtils::rfc1123Date( $this->attribute( 'published' ) ) );
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:modified', eZDateUtils::rfc1123Date( $this->attribute( 'modified' ) ) );
        if ( !$this->attribute( 'remote_id' ) )
        {
            $this->setAttribute( 'remote_id', eZRemoteIdUtility::generate( 'object' ) );
            $this->store();
        }
        $objectNode->setAttribute( 'remote_id', $this->attribute( 'remote_id' ) );
        $contentClass = $this->attribute( 'content_class' );
        $objectNode->setAttribute( 'class_remote_id', $contentClass->attribute( 'remote_id' ) );
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:class_identifier', $contentClass->attribute( 'identifier' ) );
        $alwaysAvailableText = '0';
        if ( (int)$this->attribute( 'language_mask' ) & 1 )
        {
            $alwaysAvailableText = '1';
        }
        $objectNode->setAttributeNS( 'http://ez.no/ezobject', 'ezremote:always_available', $alwaysAvailableText );

        $versions = array();
        $oneLanguagePerVersion = false;
        if ( $specificVersion === false )
        {
            $versions = $this->versions();
            // Since we are exporting all versions it should only contain
            // one language per version
            //$oneLanguagePerVersion = true; // uncomment to get one language per version
        }
        else if ( $specificVersion === true )
        {
            $versions[] = $this->currentVersion();
        }
        else
        {
            $versions[] = $this->version( $specificVersion );
            // Since we are exporting a specific version it should only contain
            // one language per version?
            $oneLanguagePerVersion = true;
        }

        $this->fetchClassAttributes();

        $exportedLanguages = array();

        $versionsNode = $dom->createElementNS( 'http://ez.no/object/', 'ezobject:version-list' );
        $versionsNode->setAttribute( 'active_version', $this->CurrentVersion );
        foreach ( $versions as $version )
        {
            if ( !$version )
            {
                continue;
            }
            $options['only_initial_language'] = $oneLanguagePerVersion;
            $versionNode = $version->serialize( $package, $options, $contentNodeIDArray, $topNodeIDArray );
            if ( $versionNode )
            {
                $importedVersionNode = $dom->importNode( $versionNode, true );
                $versionsNode->appendChild( $importedVersionNode );
                foreach ( $versionNode->getElementsByTagName( 'object-translation' ) as $versionNodeChild )
                {
                    $exportedLanguage = $versionNodeChild->getAttribute( 'language' );
                    $exportedLanguages[] = $exportedLanguage;
                    $exportedLanguages = array_unique( $exportedLanguages );
                }
            }
            unset( $versionNode );
            unset( $versionNode );
        }
        $initialLanguageCode = $this->attribute( 'initial_language_code' );
        if ( in_array( $initialLanguageCode, $exportedLanguages ) )
        {
            $objectNode->setAttribute( 'initial_language', $initialLanguageCode );
        }
        $objectNode->appendChild( $versionsNode );
        return $objectNode;
    }
Ejemplo n.º 18
0
 /**
  * @return array
  * @throws FailedToParseFileException
  */
 public function parse()
 {
     /*
      * ReaXML Feed schema and information from http://reaxml.realestate.com.au/propertyList.dtd
      * and http://reaxml.realestate.com.au/docs/reaxml1-xml-format.html
      */
     $property_classes = ["business", "commercial", "commercialLand", "land", "rental", "holidayRental", "residential", "rural"];
     $results = [];
     $xmlreader = new XMLReader();
     try {
         $xmlreader->open($this->file);
     } catch (\Exception $e) {
         throw new FailedToParseFileException("Failed to parse file at " . $this->file);
     }
     while ($xmlreader->read()) {
         if ($xmlreader->nodeType == XMLReader::ELEMENT and in_array($xmlreader->localName, $property_classes)) {
             $node = $xmlreader->expand();
             $dom = new DomDocument();
             $n = $dom->importNode($node, true);
             $dom->appendChild($n);
             $xml = simplexml_import_dom($n);
             switch ($xmlreader->localName) {
                 // business
                 case 'business':
                     $parser = BusinessListing::class;
                     break;
                     // commercial
                 // commercial
                 case 'commercial':
                     $parser = CommercialListing::class;
                     break;
                     // commercial land
                 // commercial land
                 case 'commercialLand':
                     $parser = CommercialLandListing::class;
                     break;
                     // residential land
                 // residential land
                 case 'land':
                     $parser = LandListing::class;
                     break;
                     // rental
                 // rental
                 case 'rental':
                     $parser = RentalListing::class;
                     break;
                     // holiday rental
                 // holiday rental
                 case 'holidayRental':
                     $parser = HolidayRentalListing::class;
                     break;
                     // residential
                 // residential
                 case 'residential':
                     $parser = ResidentialListing::class;
                     break;
                     // rural
                 // rural
                 case 'rural':
                     $parser = RuralListing::class;
                     break;
             }
             /* @var Listing $parser */
             $results[] = new $parser($xml);
             unset($node);
             unset($dom);
             unset($xml);
         }
     }
     return $results;
 }
 /**
  * turn a simplexml object into a domXML object
  *
  * @param simplexml object $SimpleXMLElement 
  * @return object - domXML
  * @author Andy Bennett
  */
 function into_dom(SimpleXMLElement $xml)
 {
     $dom = new DomDocument('1.0', 'UTF-8');
     $dom_sxe = dom_import_simplexml($xml);
     $dom_sxe = $dom->importNode($dom_sxe, true);
     $dom->appendChild($dom_sxe);
     return $dom;
 }
Ejemplo n.º 20
0
 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
 }
Ejemplo n.º 21
0
 /**
  * A method acting as a harvesting handler for the Trove service.
  *
  * @return object | $response
  */
 private function _harvestTROVE()
 {
     $params = array('paths' => array("q={$this->_searchTerm} date:[1850 TO 1955]&zone=newspaper&include=tags,workversions&reclevel=full&l-title=1007", "q={$this->_searchTerm} date:[1850 TO 1955]&zone=newspaper&include=tags,workversions&reclevel=full&l-title=35"), 'max' => 8000);
     $output = '';
     $model = $this->getDoctrine()->getManager();
     $result = $model->createQuery("DELETE FROM SLDataHarvestBundle:Data sl WHERE sl.source = 'trove'")->execute();
     $helper = new Trove_Helper();
     if ($result >= 0) {
         if ($objects = $helper->getObjects($params)) {
             $output = new \DomDocument();
             $output->formatOutput = TRUE;
             $output->loadXML('<responses></responses>');
             foreach ($objects as $object) {
                 // Create a new instance of the Symfony DOM Crawler, new XML will be loaded for each iteration.
                 $crawler = new Crawler();
                 // Create the XML structure from the response object.
                 $crawler->addContent($object);
                 // Filter the XML document by the records node.
                 $records = $crawler->filterXPath('//records');
                 // Filter the XML document by the zone node (parent to records).
                 $zones = $crawler->filterXPath('//zone');
                 // Create a new instance of the in-built (global namespace) DOM class.
                 $document = new \DomDocument();
                 // Load XML onto the object based on the filter applied by the crawler.
                 $document->loadXML($zones->html());
                 // Import the children of zone into the document to be used for output. There will only ever be one child 'records' node, therefore we can access it using a static index.
                 $node = $output->importNode($document->getElementsByTagName('records')->item(0), TRUE);
                 // Append the imported return node to the root element of the output document.
                 $output->documentElement->appendChild($node);
                 foreach ($records->children() as $record) {
                     $data = new Data();
                     $data->setTitle($record->getElementsByTagName('heading')->item(0)->nodeValue);
                     $data->setDescription($record->getElementsByTagName('snippet')->item(0)->nodeValue);
                     $data->setData(serialize(array('title' => $record->getElementsByTagName('title')->item(0)->getAttribute('id'))));
                     $data->setDate(new \DateTime($record->getElementsByTagName('date')->item(0)->nodeValue));
                     $data->setUrl($record->getElementsByTagName('trovePageUrl')->item(0)->nodeValue);
                     $data->setSource('trove');
                     $model->persist($data);
                 }
             }
         }
     }
     $model->flush();
     $response = new Response($output->saveXML());
     $response->headers->set('Content-type', 'text/xml');
     return $response;
 }
Ejemplo n.º 22
0
 /**
  * Expand current node to DomDocument
  *
  * @param  string $version
  * @param  string $encoding
  * @return DomDocument
  */
 public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
 {
     $element = $this->expand();
     $document = new DomDocument($version, $encoding);
     if ($element instanceof DOMCharacterData) {
         $nodeName = array_splice($this->nodesParsed, -2, 1);
         $nodeName = isset($nodeName[0]) && $nodeName[0] ? $nodeName[0] : "root";
         $node = $document->createElement($nodeName);
         $node->appendChild($element);
         $element = $node;
     }
     $node = $document->importNode($element, true);
     $document->appendChild($node);
     return $document;
 }
 function getXmlOperator($type)
 {
     $dom = new DomDocument();
     $operator = $dom->createElement("operator");
     $dom->appendChild($operator);
     $operator->setAttribute("type", $type);
     foreach ($this->children as $child) {
         $operator->appendChild($dom->importNode($child->getXml()->documentElement, true));
     }
     return $dom;
 }
Ejemplo n.º 24
0
 /**
  * given some content that might be html or xhtml, try to coerce it to xhtml and return it.
  *
  * @param string $content some html or xhtmlish content
  *
  * @return xhtml content or false for unmodified text content
  */
 public static function parse_xhtmlish_content($content, $viewid = null)
 {
     $dom = new DomDocument();
     $topel = $dom->createElement('tmp');
     $tmp = new DomDocument();
     if (strpos($content, '<') === false && strpos($content, '>') === false) {
         return false;
     }
     if (@$tmp->loadXML('<div>' . $content . '</div>')) {
         $topel->setAttribute('type', 'xhtml');
         $content = $dom->importNode($tmp->documentElement, true);
         $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
         $topel->appendChild($content);
         // if that fails, it could still be html
     } else {
         if (@$tmp->loadHTML('<div>' . $content . '</div>')) {
             $xpath = new DOMXpath($tmp);
             $elements = $xpath->query('/html/body/div');
             if ($elements->length != 1) {
                 if ($viewid) {
                     log_warn("Leap2a export: invalid html found in view {$viewid}");
                 }
                 if ($elements->length < 1) {
                     return false;
                 }
             }
             $ourelement = $elements->item(0);
             $content = $dom->importNode($ourelement, true);
             $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
             $topel->appendChild($content);
         } else {
             return false;
             // wtf is it then?
         }
     }
     $dom->appendChild($topel->firstChild);
     return $dom->saveXML($dom->documentElement);
 }
Ejemplo n.º 25
0
/**
 * Recursive function to create schema from import schema
 * and also used to resove wsdl import problem
 * @param DomNode $parent parent dom node
 * @param DomNode $child dom node of import schema
 * @param DomDocument $doc DomDocument of parent DomNode
 */
function wsf_wsdl_append_node($parent, $child, $doc)
{
    if ($child == NULL) {
        return;
    }
    $imported_node = $doc->importNode($child, TRUE);
    if ($imported_node) {
        $parent->appendChild($imported_node);
    }
}
Ejemplo n.º 26
0
 public function appendToX(\DomDocument $dom)
 {
     $fields = $this->_form->getElementsByTagName('field');
     $list = $dom->getElementsByTagName('x');
     foreach ($fields as $field) {
         $field = $dom->importNode($field, true);
         $list[0]->appendChild($field);
     }
 }
Ejemplo n.º 27
0
$reader = new XMLReader();
$reader->open('xml-schema/KeyFamily.xml');
while ($reader->read()) {
    switch ($reader->nodeType) {
        case XMLREADER::ELEMENT:
            if ($reader->localName == "Concept") {
                $node = $reader->expand();
                $agencyID = $node->getAttribute('agencyID');
                $id = $node->getAttribute('id');
                $Name = $node->getELementsByTagName('Name')->item(0)->textContent;
                $concepts[$agencyID][$id]['label'] = $Name;
            } else {
                if ($reader->localName == "Dimension") {
                    $node = $reader->expand();
                    $dom = new DomDocument();
                    $n = $dom->importNode($node, true);
                    $dom->appendChild($n);
                    $concepts[$node->getAttribute('conceptAgency')][$node->getAttribute('conceptRef')]['codeLists'][] = $node->getAttribute('codelist');
                    $concepts[$node->getAttribute('conceptAgency')][$node->getAttribute('conceptRef')]['codeLists'] = array_unique($concepts[$node->getAttribute('conceptAgency')][$node->getAttribute('conceptRef')]['codeLists']);
                } else {
                    if ($reader->localName == "CodeList") {
                        $node = $reader->expand();
                        $id = $node->getAttribute('id');
                        $Name = $node->getELementsByTagName('Name')->item(0)->textContent;
                        $codeLists[$id]['label'] = $Name;
                        foreach ($node->getElementsByTagName('Code') as $Code) {
                            $codeVal = $Code->getAttribute('value');
                            $codeLists[$id]['codes'][$codeVal] = $Code->getElementsByTagName('Description')->item(0)->textContent;
                        }
                    } else {
                        if ($reader->localName == "KeyFamily") {
 /**
  * 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;
 }
Ejemplo n.º 29
0
 /**
  * Replaces all external-schema nodes with the content of xml schema that node refers to
  *
  * Recurses to include any external schema referenced from in an included xml (and deeper)
  * Note: this function very much assumes at least a reasonable XML schema, maybe it'll proof
  * users don't have those and adding some more informative exceptions would be better
  *
  * @param      DomDocument $dom
  * @param      string $srcDir
  * @return     void (objects, DomDocument, are references by default in PHP 5, so returning it is useless)
  **/
 protected function includeExternalSchemas(DomDocument $dom, $srcDir)
 {
     $databaseNode = $dom->getElementsByTagName("database")->item(0);
     $externalSchemaNodes = $dom->getElementsByTagName("external-schema");
     $fs = FileSystem::getFileSystem();
     while ($externalSchema = $externalSchemaNodes->item(0)) {
         $include = $externalSchema->getAttribute("filename");
         $externalSchema->parentNode->removeChild($externalSchema);
         if ($fs->prefixLength($include) != 0) {
             $externalSchemaFile = new PhingFile($include);
         } else {
             $externalSchemaFile = new PhingFile($srcDir, $include);
         }
         $externalSchemaDom = new DomDocument('1.0', 'UTF-8');
         $externalSchemaDom->load($externalSchemaFile->getAbsolutePath());
         $this->includeExternalSchemas($externalSchemaDom, $srcDir);
         foreach ($externalSchemaDom->getElementsByTagName("table") as $tableNode) {
             // see xsd, datatase may only have table or external-schema, the latter was just deleted so this should cover everything
             $databaseNode->appendChild($dom->importNode($tableNode, true));
         }
     }
 }
Ejemplo n.º 30
0
 /**
  * Convert a DOMNode to an SXE node -- simplexml_import_node() won't actually work
  *
  * @param DOMNode $node
  * @return SimpleXMLElement
  */
 private static function domNode_to_sxeNode($node)
 {
     $dom = new \DomDocument();
     $n = $dom->importNode($node, true);
     $sxeNode = simplexml_import_dom($n);
     $dom->appendChild($n);
     return $sxeNode;
 }