Example #1
0
 private static function fromAtom(SimpleXMLElement $xml)
 {
     if (!in_array('http://www.w3.org/2005/Atom', $xml->getDocNamespaces(), TRUE) && !in_array('http://purl.org/atom/ns#', $xml->getDocNamespaces(), TRUE)) {
         throw new FeedException('Invalid feed.');
     }
     // generate 'timestamp' tag
     foreach ($xml->entry as $entry) {
         $entry->timestamp = strtotime($entry->updated);
     }
     $feed = new self();
     $feed->xml = $xml;
     return $feed;
 }
 /**
  * Parses additional exception information from the response body
  *
  * @param \SimpleXMLElement $body The response body as XML
  * @param array             $data The current set of exception data
  */
 protected function parseBody(\SimpleXMLElement $body, array &$data)
 {
     $data['parsed'] = $body;
     $namespaces = $body->getDocNamespaces();
     if (isset($namespaces[''])) {
         // Account for the default namespace being defined and PHP not being able to handle it :(
         $body->registerXPathNamespace('ns', $namespaces['']);
         $prefix = 'ns:';
     } else {
         $prefix = '';
     }
     if ($tempXml = $body->xpath("//{$prefix}Code[1]")) {
         $data['code'] = (string) $tempXml[0];
     }
     if ($tempXml = $body->xpath("//{$prefix}Message[1]")) {
         $data['message'] = (string) $tempXml[0];
     }
     $tempXml = $body->xpath("//{$prefix}RequestId[1]");
     if (empty($tempXml)) {
         $tempXml = $body->xpath("//{$prefix}RequestID[1]");
     }
     if (isset($tempXml[0])) {
         $data['request_id'] = (string) $tempXml[0];
     }
 }
Example #3
0
 /**
  * @param string $wsdl
  */
 public function __construct($wsdl)
 {
     $this->wsdl = $wsdl;
     $xml = new \SimpleXMLElement(\file_get_contents($wsdl));
     $this->namespaces = $xml->getDocNamespaces();
     $this->tns = isset($xml['targetNamespace']) ? (string) $xml['targetNamespace'] : null;
 }
 /**
  * @param \SimpleXMLElement $node
  *
  * @return \Bundle\WebServiceBundle\ServiceDefinition\Type
  */
 protected function parseType(\SimpleXMLElement $node)
 {
     $namespaces = $node->getDocNamespaces(true);
     $qname = explode(':', $node['xml-type'], 2);
     $xmlType = sprintf('{%s}%s', $namespaces[$qname[0]], $qname[1]);
     $type = new Type((string) $node['php-type'], $xmlType, (string) $node['converter']);
     return $type;
 }
Example #5
0
 /**
  * Converts XML into an array, respecting namespaces, attributes, and text values.
  *
  * @return array
  */
 public function parse()
 {
     $namespaces = $this->xml->getDocNamespaces();
     $namespaces[''] = null;
     //add base (empty) namespace
     $attributes = $this->getAttributes($namespaces);
     //get child nodes from all namespaces
     $tags = array();
     foreach ($namespaces as $prefix => $namespace) {
         foreach ($this->xml->children($namespace) as $childXml) {
             $new_parser = new XmlParser($childXml, $this->options);
             $child = $new_parser->parse();
             list($childTag, $childProperties) = each($child);
             //add namespace prefix, if any
             if ($prefix) {
                 $childTag = $prefix . $this->namespaceSeparator . $childTag;
             }
             if (!isset($tags[$childTag])) {
                 $alwaysArray = $this->options['alwaysArray'];
                 $autoArray = $this->options['autoArray'];
                 $tags[$childTag] = $childProperties;
                 if (in_array($childTag, $alwaysArray) || !$autoArray) {
                     $tags[$childTag] = [$childProperties];
                 }
             } elseif ($this->isIntegerIndexedArray($tags[$childTag])) {
                 $tags[$childTag][] = $childProperties;
             } else {
                 //key exists so convert to integer indexed array with previous value in position 0
                 $tags[$childTag] = array($tags[$childTag], $childProperties);
             }
         }
     }
     //get text content of node
     $textContent = array();
     $plainText = trim((string) $this->xml);
     if ($plainText !== '') {
         $textContent[$this->options['textContent']] = $plainText;
     }
     //stick it all together
     $properties = $plainText;
     if (!$this->options['autoText'] || $attributes || $tags || $plainText === '') {
         $properties = array_merge($attributes, $tags, $textContent);
     }
     //return node as array
     return array($this->xml->getName() => $properties);
 }
Example #6
0
/**
 * Create plain PHP associative array from XML.
 *
 * Example usage:
 *   $xmlNode = simplexml_load_file('example.xml');
 *   $arrayData = xmlToArray($xmlNode);
 *   echo json_encode($arrayData);
 *
 * @param SimpleXMLElement $xml The root node
 * @param array $options Associative array of options
 * @return array
 * @link http://outlandishideas.co.uk/blog/2012/08/xml-to-json/ More info
 * @author Tamlyn Rhodes <http://tamlyn.org>
 * @license http://creativecommons.org/publicdomain/mark/1.0/ Public Domain
 */
function xmlToArray($xml, $options = array())
{
    $defaults = array('namespaceSeparator' => ':', 'attributePrefix' => '', 'alwaysArray' => array(), 'autoArray' => true, 'textContent' => '$', 'autoText' => true, 'keySearch' => '@', 'keyReplace' => '');
    $options = array_merge($defaults, $options);
    $namespaces = $xml->getDocNamespaces();
    $namespaces[''] = null;
    //add base (empty) namespace
    //get attributes from all namespaces
    $attributesArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
            //replace characters in attribute name
            if ($options['keySearch']) {
                $attributeName = str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
            }
            $attributeKey = $options['attributePrefix'] . ($prefix ? $prefix . $options['namespaceSeparator'] : '') . $attributeName;
            $attributesArray[$attributeKey] = (string) $attribute;
        }
    }
    //get child nodes from all namespaces
    $tagsArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->children($namespace) as $childXml) {
            //recurse into child nodes
            $childArray = xmlToArray($childXml, $options);
            list($childTagName, $childProperties) = each($childArray);
            //replace characters in tag name
            if ($options['keySearch']) {
                $childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
            }
            //add namespace prefix, if any
            if ($prefix) {
                $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
            }
            if (!isset($tagsArray[$childTagName])) {
                //only entry with this key
                //test if tags of this type should always be arrays, no matter the element count
                $tagsArray[$childTagName] = in_array($childTagName, $options['alwaysArray']) || !$options['autoArray'] ? array($childProperties) : $childProperties;
            } elseif (is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName]) === range(0, count($tagsArray[$childTagName]) - 1)) {
                //key already exists and is integer indexed array
                $tagsArray[$childTagName][] = $childProperties;
            } else {
                //key exists so convert to integer indexed array with previous value in position 0
                $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
            }
        }
    }
    //get text content of node
    $textContentArray = array();
    $plainText = trim((string) $xml);
    if ($plainText !== '') {
        $textContentArray[$options['textContent']] = $plainText;
    }
    //stick it all together
    $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || $plainText === '' ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
    //return node as array
    return array($xml->getName() => $propertiesArray);
}
Example #7
0
 /**
  * Registers found doc namespaces to xpath for being able to access
  * elements via xpath
  *
  * @param \SimpleXMLElement $doc
  */
 protected function registerXPathNamespaces(\SimpleXMLElement $doc)
 {
     foreach ($doc->getDocNamespaces() as $strPrefix => $strNamespace) {
         if (strlen($strPrefix) == 0) {
             $strPrefix = $strNamespace;
         }
         $doc->registerXPathNamespace($strPrefix, $strNamespace);
     }
 }
Example #8
0
 /**
  * Calls the correct XML reader function depending on its type
  *
  * @param \SimpleXMLElement $xml        	
  * @param BitScout\Sepa\Statement $statement        	
  * @param string $filename        	
  */
 private static function readXML($xml, $statement, $filename = null)
 {
     // Check what type of CAMT file this is
     $xmlNamespace = $xml->getDocNamespaces()[''];
     if (strpos($xmlNamespace, 'camt.052') !== false) {
         Sepa::readC52($xml, $statement, $filename);
     } else {
         return null;
     }
 }
Example #9
0
 /**
  * Ацкий костыль. В ответе частенько пеперпутаны неймспейсы, которые пытаемся тут поправить
  * 
  * @param <type> $request
  * @param <type> $location
  * @param <type> $action
  * @param <type> $version
  * @param <type> $one_way
  * @return <type>
  */
 public function __doRequest($request, $location, $action, $version, $one_way = 0)
 {
     $req = parent::__doRequest($request, $location, $action, $version, $one_way);
     $xml = new \SimpleXMLElement($req);
     if (isset($nss[self::NS_SOAPLITE]) && isset($nss[self::NS_API])) {
         $nss = \array_flip($xml->getDocNamespaces(true));
         $req = \str_replace($nss[self::NS_SOAPLITE] . ':', $nss[self::NS_API] . ':', $req);
     }
     return $req;
 }
 public function action_block_content_rssblock($block)
 {
     $items = array();
     $cachename = array('rssblock', md5($block->feed_url));
     if (Cache::expired($cachename)) {
         //			CronTab::add_single_cron('single_update_rrs_blocks', 'rrsblocks_update', HabariDateTime::date_create());
     }
     $feed = Cache::get($cachename);
     try {
         $xml = new SimpleXMLElement($feed);
         $dns = $xml->getDocNamespaces();
         $itemcount = 0;
         foreach ($xml->channel->item as $xitem) {
             $item = new StdClass();
             foreach ($xitem->children() as $child) {
                 $item->{$child->getName()} = (string) $child;
             }
             foreach ($dns as $ns => $nsurl) {
                 foreach ($xitem->children($nsurl) as $child) {
                     $item->{$ns . '__' . $child->getName()} = (string) $child;
                     foreach ($child->attributes() as $name => $value) {
                         $item->{$ns . '__' . $child->getName() . '__' . $name} = (string) $value;
                     }
                 }
             }
             $items[] = $item;
             $itemcount++;
             if ($block->item_limit > 0 && $itemcount >= $block->item_limit) {
                 break;
             }
         }
         foreach ($xml->item as $xitem) {
             $item = new StdClass();
             foreach ($xitem->children() as $child) {
                 $item->{$child->getName()} = (string) $child;
             }
             foreach ($dns as $ns => $nsurl) {
                 foreach ($xitem->children($nsurl) as $child) {
                     $item->{$ns . '__' . $child->getName()} = (string) $child;
                     foreach ($child->attributes() as $name => $value) {
                         $item->{$ns . '__' . $child->getName() . '__' . $name} = (string) $value;
                     }
                 }
             }
             $items[] = $item;
             $itemcount++;
             if ($block->item_limit > 0 && $itemcount >= $block->item_limit) {
                 break;
             }
         }
     } catch (Exception $e) {
     }
     $block->items = $items;
     $block->markup_id = Utils::slugify($block->title);
 }
Example #11
0
 /**
  * Loads Atom channel.
  * @param  string  Atom feed URL
  * @param  string  optional user name
  * @param  string  optional password
  * @return Feed
  * @throws FeedException
  */
 public static function loadAtom($url, $user = NULL, $pass = NULL)
 {
     $xml = new SimpleXMLElement(self::httpRequest($url, $user, $pass), LIBXML_NOWARNING | LIBXML_NOERROR);
     if (!in_array('http://www.w3.org/2005/Atom', $xml->getDocNamespaces(), TRUE)) {
         throw new FeedException('Invalid channel.');
     }
     // generate 'timestamp' tag
     foreach ($xml->entry as $entry) {
         $entry->timestamp = strtotime($entry->updated);
     }
     $feed = new self();
     $feed->xml = $xml;
     return $feed;
 }
Example #12
0
 /**
  * {@inheritdoc}
  *
  * @internal
  */
 public function __doRequest($request, $location, $action, $version, $oneWay = null)
 {
     $this->requestId = substr(str_replace(' ', '', microtime()), 2);
     $response = parent::__doRequest($request, $location, $action, $version, $oneWay);
     if (!empty($response)) {
         $xml = new \SimpleXMLElement($response);
         $nss = array_flip($xml->getDocNamespaces(true));
         $invalidNs = 'http://namespaces.soaplite.com/perl';
         if (isset($nss[$invalidNs]) && isset($nss['API'])) {
             $response = str_replace($nss[$invalidNs] . ':', $nss['API'] . ':', $response);
         }
     }
     return $response;
 }
Example #13
0
 /**
  * @test
  * @group sitemap
  */
 public function test_root()
 {
     // Base Sitemap
     $sitemap = new Sitemap();
     // Create basic Mobile Sitemap
     $instance = new Sitemap_URL(new Sitemap_Geo());
     $instance->set_loc('http://google.com');
     $sitemap->add($instance);
     // Load the end XML
     $xml = new SimpleXMLElement($sitemap->render());
     // Namespaces.
     $namespaces = $xml->getDocNamespaces();
     $this->assertSame(TRUE, isset($namespaces['geo']));
     $this->assertSame('http://www.google.com/geo/schemas/sitemap/1.0', $namespaces['geo']);
 }
Example #14
0
 public function parser()
 {
     $error = 'El archivo no tiene un formato xml correcto';
     try {
         $sxe = new \SimpleXMLElement($this->text);
     } catch (\ErrorException $e) {
         throw new \ErrorException($error);
     }
     $namespaces = $sxe->getDocNamespaces(true);
     $error = 'El archivo no esta en formato CFDI';
     if (!array_key_exists('cfdi', $namespaces)) {
         throw new \ErrorException($error);
     }
     $this->finished = true;
     $this->parsed = $this->xmlAttr($sxe, $sxe->getName(), $namespaces, 'cfdi');
 }
 /**
  * Transforms XML data to array.
  *
  * @param string $xml XML data.
  * @param string[] $namespaces List of namespaces to include in parsing or empty to include all namespaces.
  * @return array
  */
 function ky_xml_to_array($xml, $namespaces = null)
 {
     $iter = 0;
     $arr = array();
     if (is_string($xml)) {
         $xml = new SimpleXMLElement($xml);
     }
     if (!$xml instanceof SimpleXMLElement) {
         return $arr;
     }
     if ($namespaces === null) {
         $namespaces = $xml->getDocNamespaces(true);
     }
     foreach ($xml->attributes() as $attributeName => $attributeValue) {
         $arr["_attributes"][$attributeName] = trim($attributeValue);
     }
     foreach ($namespaces as $namespace_prefix => $namespace_name) {
         foreach ($xml->attributes($namespace_prefix, true) as $attributeName => $attributeValue) {
             $arr["_attributes"][$namespace_prefix . ':' . $attributeName] = trim($attributeValue);
         }
     }
     $has_children = false;
     foreach ($xml->children() as $element) {
         /** @var $element SimpleXMLElement */
         $has_children = true;
         $elementName = $element->getName();
         if ($element->children()) {
             $arr[$elementName][] = ky_xml_to_array($element, $namespaces);
         } else {
             $shouldCreateArray = array_key_exists($elementName, $arr) && !is_array($arr[$elementName]);
             if ($shouldCreateArray) {
                 $arr[$elementName] = array($arr[$elementName]);
             }
             $shouldAddValueToArray = array_key_exists($elementName, $arr) && is_array($arr[$elementName]);
             if ($shouldAddValueToArray) {
                 $arr[$elementName][] = trim($element[0]);
             } else {
                 $arr[$elementName] = trim($element[0]);
             }
         }
         $iter++;
     }
     if (!$has_children) {
         $arr['_contents'] = trim($xml[0]);
     }
     return $arr;
 }
Example #16
0
 public function parseBody($body, $feed)
 {
     $xml = new \SimpleXMLElement($body);
     foreach ($xml->attributes() as $key => $val) {
         $feed->attributes += [$key => $val];
     }
     $feed->namespaces += $xml->getDocNamespaces();
     $metadata = $this->parseChildrenValues($xml->channel);
     unset($metadata['item']);
     $feed->metadata += $metadata;
     foreach ($xml->channel->item as $key => $element) {
         $item = new Item();
         $item->setData($this->parseChildrenValues($element));
         $item->attributes += $this->parseAllAttributes($element);
         $feed->items[] = $item;
     }
 }
 public function __construct($xml = null)
 {
     if ($xml) {
         // first, lets find the cmis namespace to use
         $sx = new SimpleXMLElement($xml);
         $namespaces = $sx->getDocNamespaces();
         $ns = isset($namespaces['cmis']) ? $namespaces['cmis'] : 'http://docs.oasis-open.org/ns/cmis/core/200901';
         // go through the XML and pull out the things we're interested in
         Zend_Feed::registerNamespace('cmis', $ns);
         // 'http://www.cmis.org/2008/05');
         $this->rawXml = $xml;
         $feed = Zend_Feed::importString($this->rawXml);
         foreach ($feed as $item) {
             $this->loadFromFeed($item);
         }
     }
 }
Example #18
0
 public function parseBody($body, $feed)
 {
     $xml = new \SimpleXMLElement($body);
     foreach ($xml->attributes() as $key => $val) {
         $feed->attributes += [$key => $val];
     }
     $feed->namespaces += $xml->getDocNamespaces();
     $metadata = $this->parseChildrenValues($xml);
     unset($metadata['entry']);
     $feed->metadata += $metadata;
     foreach ($xml->entry as $key => $element) {
         $item = new Item();
         $item->guid = (string) $element->id;
         $item->description = (string) $element->content;
         $item->setData($this->parseChildrenValues($element));
         $item->attributes += $this->parseAllAttributes($element);
         $feed->items[] = $item;
     }
 }
 function __construct($xml)
 {
     parent::__construct();
     if ($xml) {
         // first, lets find the cmis namespace to use
         $sx = new SimpleXMLElement($xml);
         $namespaces = $sx->getDocNamespaces();
         $ns = isset($namespaces['cmis']) ? $namespaces['cmis'] : 'http://docs.oasis-open.org/ns/cmis/core/200901';
         // go through the entries and create some objects
         Zend_Feed::registerNamespace('cmis', $ns);
         // 'http://www.cmis.org/2008/05');
         $this->rawXml = $xml;
         $feed = Zend_Feed::importString($this->rawXml);
         foreach ($feed as $entry) {
             $obj = new SeaMistObject();
             $obj->loadFromFeed($entry);
             $this[] = $obj;
         }
     }
 }
/**
 * Convert an array to a SimpleXML child of the passed tree.
 *
 * @param array $data array containing element value pairs, including other arrays, for XML contruction
 * @param SimpleXMLElement $tree A SimpleXMLElement class object used to attach new children
 * @return SimpleXMLElement full tree with new children mapped from array
 */
function wpcom_sitemap_array_to_simplexml($data, &$tree)
{
    $doc_namespaces = $tree->getDocNamespaces();
    foreach ($data as $key => $value) {
        // Allow namespaced keys by use of colon in $key, namespaces must be part of the document
        $namespace = null;
        if (false !== strpos($key, ':')) {
            list($namespace_prefix, $key) = explode(':', $key);
            if (isset($doc_namespaces[$namespace_prefix])) {
                $namespace = $doc_namespaces[$namespace_prefix];
            }
        }
        if (is_array($value)) {
            $child = $tree->addChild($key, null, $namespace);
            wpcom_sitemap_array_to_simplexml($value, $child);
        } else {
            $tree->addChild($key, esc_html($value), $namespace);
        }
    }
    return $tree;
}
Example #21
0
 /**
  * Output a tree-view of the node or list of nodes referenced by a particular SimpleXML object
  * Unlike simplexml_dump(), this processes the entire XML tree recursively, while attempting
  *    to be more concise and readable than the XML itself.
  * Additionally, the output format is designed as a hint of the syntax needed to traverse the object.
  *
  * @param \SimpleXMLElement $sxml The object to inspect
  * @param boolean $include_string_content Default false. If true, will summarise textual content,
  *    as well as child elements and attribute names
  * @param boolean $return Default false. If true, return the "dumped" info rather than echoing it
  * @return null|string Nothing, or output, depending on $return param
  *
  * @author Rowan Collins
  * @see https://github.com/IMSoP/simplexml_debug
  * @license None. Do what you like with it, but please give me credit if you like it. :)
  * Equally, no warranty: don't blame me if your aircraft or nuclear power plant fails because of this code!
  */
 public static function simplexmlTree(\SimpleXMLElement $sxml, $include_string_content = false, $return = false)
 {
     $indent = "\t";
     $content_extract_size = 15;
     // Get all the namespaces declared at the *root* of this document
     // All the items we're looking at are in the same document, so we only need do this once
     $doc_ns = $sxml->getDocNamespaces(false);
     $dump = '';
     // Note that the header is added at the end, so we can add stats
     // The initial object passed in may be a single node or a list of nodes, so we need an outer loop first
     // Note that for a single node, foreach($node) acts like foreach($node->children())
     // Numeric array indexes, however, operate consistently: $node[0] just returns the node
     $root_item_index = 0;
     while (isset($sxml[$root_item_index])) {
         $root_item = $sxml[$root_item_index];
         // Special case if the root is actually an attribute
         // It's surprisingly hard to find something which behaves consistently differently for an attribute and an element within SimpleXML
         // The below relies on the fact that the DOM makes a much clearer distinction
         // Note that this is not an expensive conversion, as we are only swapping PHP wrappers around an existing LibXML resource
         if (dom_import_simplexml($root_item) instanceof DOMAttr) {
             // To what namespace does this attribute belong? Returns array( alias => URI )
             $ns = $root_item->getNamespaces(false);
             if (key($ns)) {
                 $dump .= key($ns) . ':';
             }
             $dump .= $root_item->getName() . '="' . (string) $root_item . '"' . PHP_EOL;
         } else {
             // Display the root node as a numeric key reference, plus a hint as to its tag name
             // e.g. '[42] // <Answer>'
             // To what namespace does this attribute belong? Returns array( alias => URI )
             $ns = $root_item->getNamespaces(false);
             if (key($ns)) {
                 $root_node_name = key($ns) . ':' . $root_item->getName();
             } else {
                 $root_node_name = $root_item->getName();
             }
             $dump .= "[{$root_item_index}] // <{$root_node_name}>" . PHP_EOL;
             // This function is effectively recursing depth-first through the tree,
             // but this is managed manually using a stack rather than actual recursion
             // Each item on the stack is of the form array(int $depth, SimpleXMLElement $element, string $header_row)
             $dump .= self::simplexmlTreeRecursivelyProcessNode($root_item, 1, $include_string_content, $indent, $content_extract_size);
         }
         $root_item_index++;
     }
     // Add on the header line, with the total number of items output
     $dump = 'SimpleXML object (' . $root_item_index . ' item' . ($root_item_index > 1 ? 's' : '') . ')' . PHP_EOL . $dump;
     if ($return) {
         return $dump;
     } else {
         echo $dump;
     }
 }
 /**
  * The main method which performs the actual package installation
  *
  * @param $instanceid the instanceID to install
  * @param $type the type of task to perform (installation, removal)
  */
 public function installHandler($instanceid, $type)
 {
     global $app;
     // Set the given handle type, currently supported: install, delete
     if ($type == 'install' || $type == 'delete') {
         $this->handle_type = $type;
     } else {
         return false;
     }
     // Get all instance metadata
     /*
             $task = $app->db->queryOneRecord("SELECT * FROM aps_instances AS i
                 INNER JOIN aps_packages AS p ON i.package_id = p.id
                 INNER JOIN client AS c ON i.customer_id = c.client_id
                 WHERE i.id = ".$instanceid.";");
     */
     $task = $app->db->queryOneRecord("SELECT * FROM aps_instances AS i\n            INNER JOIN aps_packages AS p ON i.package_id = p.id\n            WHERE i.id = " . $instanceid . ";");
     if (!$task) {
         return false;
     }
     // formerly: throw new Exception('The InstanceID doesn\'t exist.');
     if (!isset($task['instance_id'])) {
         $task['instance_id'] = $instanceid;
     }
     // Download aps package
     if (!file_exists($this->packages_dir . '/' . $task['path']) || filesize($this->packages_dir . '/' . $task['path']) == 0) {
         $ch = curl_init();
         $fh = fopen($this->packages_dir . '/' . $task['path'], 'wb');
         curl_setopt($ch, CURLOPT_FILE, $fh);
         //curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_URL, $task['package_url']);
         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
         curl_setopt($ch, CURLOPT_TIMEOUT, 0);
         curl_setopt($ch, CURLOPT_FAILONERROR, 1);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         if (curl_exec($ch) === false) {
             $app->log(curl_error($ch), 1);
         }
         fclose($fh);
         curl_close($ch);
     }
     /*
     $app_to_dl[] = array('name' => $task['path'],
                                 'url' => $task['package_url'],
                                 'filesize' => 0,
                                 'localtarget' => $this->packages_dir.'/'.$task['path']);
     
             $this->fetchFiles($app_to_dl);
     */
     // Make sure the requirements are given so that this script can execute
     $req_ret = $this->checkRequirements();
     if (!$req_ret) {
         return false;
     }
     $metafile = $this->getContentFromZIP($this->packages_dir . '/' . $task['path'], 'APP-META.xml');
     // Check if the meta file is existing
     if (!$metafile) {
         $app->dbmaster->query('UPDATE aps_instances SET instance_status = "' . INSTANCE_ERROR . '"
             WHERE id = "' . $app->db->quote($task['instance_id']) . '";');
         $app->log('Unable to find the meta data file of package ' . $task['path'], 1);
         return false;
     }
     // Rename namespaces and register them
     $metadata = str_replace("xmlns=", "ns=", $metafile);
     $sxe = new SimpleXMLElement($metadata);
     $namespaces = $sxe->getDocNamespaces(true);
     foreach ($namespaces as $ns => $url) {
         $sxe->registerXPathNamespace($ns, $url);
     }
     // Setup the environment with data for the install location
     $this->prepareLocation($task);
     // Create the database if necessary
     $this->prepareDatabase($task, $sxe);
     // Unpack the install scripts from the packages
     if ($this->prepareFiles($task, $sxe) && $this->handle_type == 'install') {
         // Setup the variables from the install script
         $this->prepareUserInputData($task);
         // Do the actual installation
         $this->doInstallation($task, $sxe);
         // Remove temporary files
         $this->cleanup($task, $sxe);
     }
     // Finally delete the instance entry + settings
     if ($this->handle_type == 'delete') {
         $app->db->query('DELETE FROM aps_instances WHERE id = "' . $app->db->quote($task['instance_id']) . '";');
         $app->db->query('DELETE FROM aps_instances_settings WHERE instance_id = "' . $app->db->quote($task['instance_id']) . '";');
         if ($app->dbmaster != $app->db) {
             $app->dbmaster->query('DELETE FROM aps_instances WHERE id = "' . $app->db->quote($task['instance_id']) . '";');
             $app->dbmaster->query('DELETE FROM aps_instances_settings WHERE instance_id = "' . $app->db->quote($task['instance_id']) . '";');
         }
     }
     unset($sxe);
 }
 /**
  * Insert sample datas when installing wpshop the first time if the admin choose
  */
 public static function import_sample_datas()
 {
     global $wpdb, $wp_rewrite;
     /** Default data array for add product */
     $product_default_args = array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_status' => 'publish', 'post_author' => get_current_user_id());
     /**	Get the default datas for installation - sample products	*/
     $sample_datas = file_get_contents(WP_PLUGIN_DIR . '/' . WPSHOP_PLUGIN_DIR . '/assets/datas/sample_datas.xml');
     $defined_sample_datas = new SimpleXMLElement($sample_datas, LIBXML_NOCDATA);
     $namespaces = $defined_sample_datas->getDocNamespaces();
     if (!isset($namespaces['wp'])) {
         $namespaces['wp'] = 'http://wordpress.org/export/1.1/';
     }
     if (!isset($namespaces['excerpt'])) {
         $namespaces['excerpt'] = 'http://wordpress.org/export/1.1/excerpt/';
     }
     foreach ($defined_sample_datas->xpath('//wpshop_products/wpshop_product') as $product) {
         $dc = $product->children('http://purl.org/dc/elements/1.1/');
         $content = $product->children('http://purl.org/rss/1.0/modules/content/');
         $excerpt = $product->children($namespaces['excerpt']);
         $wp = $product->children($namespaces['wp']);
         $product_args = wp_parse_args(array('post_title' => (string) $product->title, 'post_name' => (string) $wp->post_name, 'post_content' => (string) $content->encoded, 'post_excerpt' => (string) $excerpt->encoded, 'post_type' => (string) $wp->post_type), $product_default_args);
         $product_id = wp_insert_post($product_args);
         foreach ($wp->postmeta as $meta) {
             update_post_meta($product_id, (string) $meta->meta_key, (string) $meta->meta_value);
         }
         foreach ($defined_sample_datas->xpath('//wps_pdt_variations/wps_pdt_variation/wp:post_parent[. ="' . $wp->post_id . '"]/parent::*') as $product_variation) {
             $wps_pdt_var_dc = $product_variation->children('http://purl.org/dc/elements/1.1/');
             $wps_pdt_var_content = $product_variation->children('http://purl.org/rss/1.0/modules/content/');
             $wps_pdt_var_excerpt = $product_variation->children($namespaces['excerpt']);
             $wps_pdt_var_wp = $product_variation->children($namespaces['wp']);
             $product_args = wp_parse_args(array('post_title' => (string) $product_variation->title, 'post_name' => (string) $wps_pdt_var_wp->post_name, 'post_content' => (string) $wps_pdt_var_content->encoded, 'post_excerpt' => (string) $wps_pdt_var_excerpt->encoded, 'post_type' => (string) $wps_pdt_var_wp->post_type, 'post_parent' => $product_id), $product_default_args);
             $product_variation_id = wp_insert_post($product_args);
             foreach ($wps_pdt_var_wp->postmeta as $meta) {
                 update_post_meta($product_variation_id, (string) $meta->meta_key, (string) $meta->meta_value);
             }
         }
     }
 }
Example #24
0
 /**
  * Read in all possible packages from the interface packages folder and
  * check if they are not ASP.net code (as this can't be processed).
  *
  * Note: There's no need to check if the packages to register are newer
  * than those in the database because this already happended in startCrawler()
  */
 public function parseFolderToDB()
 {
     global $app;
     try {
         // This method must be used in interface mode
         if (!$this->interface_mode) {
             return false;
         }
         $pkg_list = array();
         // Read in every package having a correct filename
         $temp_handle = @dir($this->interface_pkg_dir);
         if (!$temp_handle) {
             throw new Exception('The temp directory is not accessible');
         }
         while ($folder = $temp_handle->read()) {
             if (substr($folder, -8) == '.app.zip') {
                 $pkg_list[] = $folder;
             }
         }
         $temp_handle->close();
         // If no packages are available -> exception (because at this point there should exist packages)
         if (empty($pkg_list)) {
             throw new Exception('No packages to read in');
         }
         // Get registered packages and mark non-existant packages with an error code to omit the install
         $existing_packages = array();
         $path_query = $app->db->queryAllRecords('SELECT path AS Path FROM aps_packages;');
         foreach ($path_query as $path) {
             $existing_packages[] = $path['Path'];
         }
         $diff = array_diff($existing_packages, $pkg_list);
         foreach ($diff as $todelete) {
             /*$app->db->query("UPDATE aps_packages SET package_status = '".PACKAGE_ERROR_NOMETA."'
               WHERE path = '".$app->db->quote($todelete)."';");*/
             $tmp = $app->db->queryOneRecord("SELECT id FROM aps_packages WHERE path = '" . $app->db->quote($todelete) . "';");
             $app->db->datalogUpdate('aps_packages', "package_status = " . PACKAGE_ERROR_NOMETA, 'id', $tmp['id']);
             unset($tmp);
         }
         // Register all new packages
         $new_packages = array_diff($pkg_list, $existing_packages);
         foreach ($new_packages as $pkg) {
             // Load in meta file if existing and register its namespaces
             $metafile = $this->interface_pkg_dir . '/' . $pkg . '/APP-META.xml';
             if (!file_exists($metafile)) {
                 $app->log($this->log_prefix . 'Cannot read metadata from ' . $pkg, LOGLEVEL_ERROR);
                 continue;
             }
             $metadata = file_get_contents($metafile);
             $metadata = str_replace("xmlns=", "ns=", $metadata);
             $sxe = new SimpleXMLElement($metadata);
             $namespaces = $sxe->getDocNamespaces(true);
             foreach ($namespaces as $ns => $url) {
                 $sxe->registerXPathNamespace($ns, $url);
             }
             // Insert the new package
             $pkg_name = parent::getXPathValue($sxe, 'name');
             $pkg_category = parent::getXPathValue($sxe, '//category');
             $pkg_version = parent::getXPathValue($sxe, 'version');
             $pkg_release = parent::getXPathValue($sxe, 'release');
             //$pkg_url = $this->app_download_url_list[$pkg];
             $pkg_url = @file_get_contents($this->interface_pkg_dir . '/' . $pkg . '/PKG_URL');
             /*
                             $app->db->query("INSERT INTO `aps_packages`
                                 (`path`, `name`, `category`, `version`, `release`, `package_status`) VALUES
                                 ('".$app->db->quote($pkg)."', '".$app->db->quote($pkg_name)."',
                                 '".$app->db->quote($pkg_category)."', '".$app->db->quote($pkg_version)."',
                                 ".$app->db->quote($pkg_release).", ".PACKAGE_ENABLED.");");
             */
             // Insert only if data is complete
             if ($pkg != '' && $pkg_name != '' && $pkg_category != '' && $pkg_version != '' && $pkg_release != '' && $pkg_url) {
                 $insert_data = "(`path`, `name`, `category`, `version`, `release`, `package_url`, `package_status`) VALUES\n                    ('" . $app->db->quote($pkg) . "', '" . $app->db->quote($pkg_name) . "',\n                    '" . $app->db->quote($pkg_category) . "', '" . $app->db->quote($pkg_version) . "',\n                    " . $app->db->quote($pkg_release) . ", '" . $app->db->quote($pkg_url) . "', " . PACKAGE_ENABLED . ");";
                 $app->db->datalogInsert('aps_packages', $insert_data, 'id');
             } else {
                 if (file_exists($this->interface_pkg_dir . '/' . $pkg)) {
                     $this->removeDirectory($this->interface_pkg_dir . '/' . $pkg);
                 }
             }
         }
     } catch (Exception $e) {
         $app->log($this->log_prefix . $e->getMessage(), LOGLEVEL_ERROR);
         $app->error($e->getMessage());
         return false;
     }
 }
Example #25
0
 /**
  * @param string $source
  *
  * @return $this|Document
  */
 public function loadNsXML($source)
 {
     $file = new File($source);
     $xml = new \SimpleXMLElement($file->getContents());
     $ns = $xml->getDocNamespaces(true);
     $xml = dom_import_simplexml($xml);
     foreach ($ns as $prefix => $uri) {
         $xml->removeAttributeNS($uri, $prefix);
     }
     $this->append($xml)->rename($xml->localName);
     #$this->normalizeDocument();
     $this->xPath = null;
     return $this;
 }
Example #26
0
<?php
//Example #2 Working with multiple namespaces
$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person t:id="1">John Doe</p:person>
    <p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
        Susie Q. Public
    </p:person>
</people>
XML;
 
$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(false);
var_dump($namespaces);

?>
Example #27
0
/**
 * @param string $xml_root
 *
 * @return string
 */
function cleanUpNamespaces($xml_root)
{
    $xml_root = str_replace('xsi:type', 'xsitype', $xml_root);
    $record_element = new SimpleXMLElement($xml_root);
    foreach ($record_element->getDocNamespaces() as $name => $ns) {
        if ($name != "") {
            $xml_root = str_replace($name . ':', '', $xml_root);
        }
    }
    $record_element = new SimpleXMLElement($xml_root);
    foreach ($record_element->children() as $field) {
        $field_element = new SimpleXMLElement($field->asXML());
        foreach ($field_element->getDocNamespaces() as $name2 => $ns2) {
            if ($name2 != "") {
                $xml_root = str_replace($name2 . ':', '', $xml_root);
            }
        }
    }
    return $xml_root;
}
Example #28
0
 private function processNamespaces(\SimpleXMLElement $xml)
 {
     $this->namespaces = $xml->getDocNamespaces();
     if (isset($this->namespaces['wp']) === false) {
         $this->namespaces['wp'] = 'http://wordpress.org/export/1.1/';
     }
     if (isset($this->namespaces['excerpt']) === false) {
         $this->namespaces['excerpt'] = 'http://wordpress.org/export/1.1/excerpt/';
     }
 }
 /**
  * For import the base XML when install or update wpshop
  */
 public static function import_xml()
 {
     global $wpdb, $wp_rewrite;
     /** Default data array for add product */
     $product_default_args = array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_status' => 'publish', 'post_author' => get_current_user_id());
     /**	Get the default datas for installation - sample products	*/
     $sample_datas = file_get_contents(WPS_GUIDED_PATH . '/assets/data/default-data-guided-tour.xml');
     $defined_sample_datas = new SimpleXMLElement($sample_datas, LIBXML_NOCDATA);
     $namespaces = $defined_sample_datas->getDocNamespaces();
     if (!isset($namespaces['wp'])) {
         $namespaces['wp'] = 'http://wordpress.org/export/1.1/';
     }
     if (!isset($namespaces['excerpt'])) {
         $namespaces['excerpt'] = 'http://wordpress.org/export/1.1/excerpt/';
     }
     foreach ($defined_sample_datas->xpath('//item') as $product) {
         $dc = $product->children('http://purl.org/dc/elements/1.1/');
         $content = $product->children('http://purl.org/rss/1.0/modules/content/');
         $excerpt = $product->children($namespaces['excerpt']);
         $wp = $product->children($namespaces['wp']);
         $product_args = wp_parse_args(array('post_title' => __((string) $product->title, self::$name_i18n), 'post_name' => (string) $wp->post_name, 'post_content' => __((string) $content->encoded, self::$name_i18n), 'post_excerpt' => (string) $excerpt->encoded, 'post_type' => (string) $wp->post_type), $product_default_args);
         $product_id = wp_insert_post($product_args);
         foreach ($wp->postmeta as $meta) {
             $m = self::xml_2_array($meta->meta_value);
             $m = maybe_unserialize($m[0]);
             update_post_meta($product_id, (string) $meta->meta_key, $m);
         }
     }
 }
Example #30
0
 public function toArray($xml, $firstCall = true)
 {
     if (is_string($xml)) {
         $xml = new SimpleXMLElement($xml);
     }
     $children = $xml->children();
     if (!$children) {
         $r = (string) $xml;
         if ($r == 'true' || $r == 'false') {
             $r = $r == 'true';
         }
         return $r;
     }
     $arr = array();
     if ($firstCall) {
         XmlFormat::$attribute_names = array();
         XmlFormat::$root_name = $xml->getName();
         if (XmlFormat::$parse_namespaces) {
             foreach ($xml->getDocNamespaces(TRUE) as $namepace => $uri) {
                 $arr[$namepace == '' ? 'xmlns' : 'xmlns:' . $namepace] = (string) $uri;
             }
         }
     }
     if (XmlFormat::$parse_attributes) {
         foreach ($xml->attributes() as $attName => $attValue) {
             $arr[$attName] = (string) $attValue;
             XmlFormat::$attribute_names[] = $attName;
         }
     }
     foreach ($children as $key => $node) {
         $node = $this->toArray($node, false);
         if ($key == 'anon') {
             $key = count($arr);
         }
         if (isset($arr[$key])) {
             if (!is_array($arr[$key]) || @$arr[$key][0] == null) {
                 $arr[$key] = array($arr[$key]);
             }
             $arr[$key][] = $node;
         } else {
             $arr[$key] = $node;
         }
     }
     return $arr;
 }