function addTax(SimpleXMLElement $taxes, SimpleXMLElement $tax, array $attributesToUpdate = array(), array $attributesToRemove = array())
{
    $newTax = new SimpleXMLElement('<tax/>');
    $taxRulesGroups = $taxes->xpath('//taxRulesGroup[1]');
    $insertBefore = $taxRulesGroups[0];
    if (!$insertBefore) {
        die("Could not find any `taxRulesGroup`, don't know where to append the tax.\n");
    }
    /**
     * Add the `tax` node before the first `taxRulesGroup`.
     * Yes, the dom API is beautiful.
     */
    $dom = dom_import_simplexml($taxes);
    $new = $dom->insertBefore($dom->ownerDocument->importNode(dom_import_simplexml($newTax)), dom_import_simplexml($insertBefore));
    $newTax = simplexml_import_dom($new);
    $newAttributes = array();
    foreach ($tax->attributes() as $attribute) {
        $name = $attribute->getName();
        // This attribute seems to cause trouble, skip it.
        if ($name === 'account_number' || in_array($name, $attributesToRemove)) {
            continue;
        }
        $value = (string) $attribute;
        $newAttributes[$name] = $value;
    }
    $newAttributes = array_merge($newAttributes, $attributesToUpdate);
    foreach ($newAttributes as $name => $value) {
        $newTax->addAttribute($name, $value);
    }
    return $newTax;
}
 public function hydrate(\DOMNode $node)
 {
     $pupil = simplexml_import_dom($node);
     /** @var Pupil $entity */
     $entity = $this->entity->newInstance();
     $entity->setId((int) $pupil->attributes()->Id);
     $entity->setEmail((string) $pupil->EmailAddress);
     $entity->setName((string) $pupil->Fullname);
     $entity->setSchoolCode((string) $pupil->SchoolCode);
     $entity->setSchoolId((string) $pupil->SchoolId);
     $entity->setUserCode((string) $pupil->UserCode);
     $entity->setUserName((string) $pupil->UserName);
     $entity->setTitle((string) $pupil->Title);
     $entity->setForename((string) $pupil->Forename);
     $entity->setSurname((string) $pupil->Surname);
     $entity->setMiddlename((string) $pupil->Middlename);
     $entity->setInitials((string) $pupil->Initials);
     $entity->setPreferredName((string) $pupil->Preferredname);
     $entity->setFullname((string) $pupil->Fullname);
     $entity->setGender((string) $pupil->Gender);
     $entity->setDOB((string) $pupil->DOB);
     $entity->setBoardingHouse((string) $pupil->BoardingHouse);
     $entity->setNCYear((string) $pupil->NCYear);
     $entity->setPupilType((string) $pupil->PupilType);
     $entity->setEnrolmentDate((string) $pupil->EnrolmentDate);
     $entity->setEnrolmentTerm((string) $pupil->EnrolmentTerm);
     $entity->setEnrolmentSchoolYear((string) $pupil->EnrolmentSchoolYear);
     return $entity;
 }
Example #3
0
File: conf.php Project: neel/bong
 public function evaluate($path)
 {
     $xpath = $this->directiveToXPath($path);
     $nodes = $this->xpath->query($xpath);
     $pathElems = array();
     if ($nodes->length == 1) {
         $node = $nodes->item(0);
         $valueNode = $node->attributes->getNamedItem("value");
         if ($valueNode) {
             return $valueNode->nodeValue;
         } else {
             if ($node instanceof DOMAttr) {
                 return $nodes->nodeValue;
             } else {
                 return simplexml_import_dom($node);
             }
         }
     } else {
         if ($nodes->length > 1) {
             $nodeList = array();
             for ($i = 0; $i < $nodes->length; ++$i) {
                 if ($nodes->item($i) instanceof DOMAttr) {
                     $nodeList[] = $nodes->item($i)->nodeValue;
                 } elseif ($nodes->item($i)->attributes->getNamedItem("value")) {
                     $nodeList[] = $nodes->item($i)->attributes->getNamedItem("value")->nodeValue;
                 } else {
                     $nodeList[] = simplexml_import_dom($nodes->item($i));
                 }
             }
             return $nodeList;
         } else {
             return null;
         }
     }
 }
function openxml($filepath, &$error_str = false)
{
    $xmlstr = @file_get_contents($filepath);
    if ($xmlstr == false) {
        $error_str = "failed to open file {$filepath}";
        return false;
    }
    $options = LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_ERR_NONE | LIBXML_COMPACT;
    $xmldoc = new DOMDocument();
    $xmldoc->strictErrorChecking = false;
    $xmldoc->recover = true;
    $old = error_reporting(0);
    $old_libxml = libxml_use_internal_errors(true);
    $ret = @$xmldoc->loadXml($xmlstr, $options);
    if ($ret == false) {
        $error_str = "failed to load xml from {$filepath}";
        return false;
    }
    $errors = libxml_get_errors();
    if (count($errors) > 0) {
        foreach ($errors as $error) {
            if ($error->level == LIBXML_ERR_FATAL) {
                $error_str = "file: {{$filepath}} line: {$error->line} column: {$error->column}: fatal error: {$error->code}: {$error->message}";
                return false;
            }
        }
    }
    $xml = @simplexml_import_dom($xmldoc);
    error_reporting($old);
    libxml_use_internal_errors($old_libxml);
    return $xml;
}
Example #5
0
 public static function import_xml($file)
 {
     $defaults = array('forms' => 0, 'fields' => 0, 'terms' => 0);
     $imported = array('imported' => $defaults, 'updated' => $defaults, 'forms' => array());
     unset($defaults);
     if (!defined('WP_IMPORTING')) {
         define('WP_IMPORTING', true);
     }
     if (!class_exists('DOMDocument')) {
         return new WP_Error('SimpleXML_parse_error', __('Your server does not have XML enabled', 'formidable'), libxml_get_errors());
     }
     $dom = new DOMDocument();
     $success = $dom->loadXML(file_get_contents($file));
     if (!$success) {
         return new WP_Error('SimpleXML_parse_error', __('There was an error when reading this XML file', 'formidable'), libxml_get_errors());
     }
     $xml = simplexml_import_dom($dom);
     unset($dom);
     // halt if loading produces an error
     if (!$xml) {
         return new WP_Error('SimpleXML_parse_error', __('There was an error when reading this XML file', 'formidable'), libxml_get_errors());
     }
     // add terms, forms (form and field ids), posts (post ids), and entries to db, in that order
     // grab cats, tags and terms
     if (isset($xml->term)) {
         $imported = self::import_xml_terms($xml->term, $imported);
         unset($xml->term);
     }
     if (isset($xml->form)) {
         $imported = self::import_xml_forms($xml->form, $imported);
         unset($xml->form);
     }
     $return = apply_filters('frm_importing_xml', $imported, $xml);
     return $return;
 }
 /**
  * parse XML file into data array
  *
  * @param  string $file path to XML file
  * @return array        parsed data
  * @since  1.0.1
  */
 public function _parse_xml($file)
 {
     $file_content = file_get_contents($file);
     $file_content = iconv('utf-8', 'utf-8//IGNORE', $file_content);
     $file_content = preg_replace('/[^\\x{0009}\\x{000a}\\x{000d}\\x{0020}-\\x{D7FF}\\x{E000}-\\x{FFFD}]+/u', '', $file_content);
     if (!$file_content) {
         return false;
     }
     $dom = new DOMDocument('1.0');
     $dom->loadXML($file_content);
     $xml = simplexml_import_dom($dom);
     $old_upload_url = $xml->xpath('/rss/channel/wp:base_site_url');
     $old_upload_url = $old_upload_url[0];
     $upload_dir = wp_upload_dir();
     $upload_url = $upload_dir['url'] . '/';
     $upload_dir = $upload_dir['url'];
     $cut_upload_dir = substr($upload_dir, strpos($upload_dir, 'wp-content/uploads'), strlen($upload_dir) - 1);
     $cut_date_upload_dir = '<![CDATA[' . substr($upload_dir, strpos($upload_dir, 'wp-content/uploads') + 19, strlen($upload_dir) - 1);
     $cut_date_upload_dir_2 = "\"" . substr($upload_dir, strpos($upload_dir, 'wp-content/uploads') + 19, strlen($upload_dir) - 1);
     $pattern = '/[\\"\']http:.{2}(?!livedemo).[^\'\\"]*wp-content.[^\'\\"]*\\/(.[^\\/\'\\"]*\\.(?:jp[e]?g|png|mp4|webm|ogv))[\\"\']/i';
     $patternCDATA = '/<!\\[CDATA\\[\\d{4}\\/\\d{2}/i';
     $pattern_meta_value = '/("|\')\\d{4}\\/\\d{2}/i';
     $file_content = str_replace($old_upload_url, site_url(), $file_content);
     $file_content = preg_replace($patternCDATA, $cut_date_upload_dir, $file_content);
     $file_content = preg_replace($pattern_meta_value, $cut_date_upload_dir_2, $file_content);
     $file_content = preg_replace($pattern, '"' . $upload_url . '$1"', $file_content);
     $parser = new Cherry_WXR_Parser();
     $parser_array = $parser->parse($file_content, $file);
     return $parser_array;
 }
Example #7
0
function extract_vals($td_children)
{
    global $val, $key, $results, $line_broken;
    for ($i = 0; $i < $td_children->length; $i++) {
        $item = $td_children->item($i);
        switch ($item->nodeType) {
            case XML_TEXT_NODE:
                if (!$line_broken) {
                    $val .= $item->textContent;
                }
                break;
            case XML_ELEMENT_NODE:
                switch (strtolower($item->tagName)) {
                    case 'b':
                        push_val($item);
                        break;
                    case 'a':
                        if (!$line_broken) {
                            $val .= $item->textContent;
                        }
                        break;
                    case 'br':
                        $line_broken = true;
                        break;
                    case 'table':
                        if (!count($results)) {
                            @extract_vals(dom_import_simplexml(simplexml_import_dom($item)->tr[0]->td[0])->childNodes);
                        }
                        break 3;
                    case 'hr':
                        break 3;
                }
        }
    }
}
Example #8
0
 function run($file)
 {
     require_once 'CRM/Core/DAO/CustomGroup.php';
     require_once 'CRM/Core/DAO/CustomField.php';
     require_once 'CRM/Core/DAO/OptionValue.php';
     // read xml file
     $dom = DomDocument::load($file);
     $dom->xinclude();
     $xml = simplexml_import_dom($dom);
     $idMap = array('custom_group' => array(), 'option_group' => array());
     // first create option groups and values if any
     $this->optionGroups($xml, $idMap);
     $this->optionValues($xml, $idMap);
     $this->relationshipTypes($xml);
     $this->contributionTypes($xml);
     // now create custom groups
     $this->customGroups($xml, $idMap);
     $this->customFields($xml, $idMap);
     // now create profile groups
     $this->profileGroups($xml, $idMap);
     $this->profileFields($xml, $idMap);
     $this->profileJoins($xml, $idMap);
     //create DB Template String sample data
     $this->dbTemplateString($xml, $idMap);
 }
 /**
  * Return all rewrites
  *
  * @return array
  */
 protected function loadRewrites()
 {
     $return = array('blocks', 'models', 'helpers');
     // Load config of each module because modules can overwrite config each other. Globl config is already merged
     $modules = Mage::getConfig()->getNode('modules')->children();
     foreach ($modules as $moduleName => $moduleData) {
         // Check only active modules
         if (!$moduleData->is('active')) {
             continue;
         }
         // Load config of module
         $configXmlFile = Mage::getConfig()->getModuleDir('etc', $moduleName) . DIRECTORY_SEPARATOR . 'config.xml';
         if (!file_exists($configXmlFile)) {
             continue;
         }
         $xml = simplexml_load_file($configXmlFile);
         if ($xml) {
             $rewriteElements = $xml->xpath('//rewrite');
             foreach ($rewriteElements as $element) {
                 foreach ($element->children() as $child) {
                     $type = simplexml_import_dom(dom_import_simplexml($element)->parentNode->parentNode)->getName();
                     if (!in_array($type, $this->_rewriteTypes)) {
                         continue;
                     }
                     $groupClassName = simplexml_import_dom(dom_import_simplexml($element)->parentNode)->getName();
                     if (!isset($return[$type][$groupClassName . '/' . $child->getName()])) {
                         $return[$type][$groupClassName . '/' . $child->getName()] = array();
                     }
                     $return[$type][$groupClassName . '/' . $child->getName()][] = (string) $child;
                 }
             }
         }
     }
     return $return;
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function decode($data, $format)
 {
     $internalErrors = libxml_use_internal_errors(true);
     $disableEntities = libxml_disable_entity_loader(true);
     libxml_clear_errors();
     $dom = new \DOMDocument();
     $dom->loadXML($data, LIBXML_NONET);
     libxml_use_internal_errors($internalErrors);
     libxml_disable_entity_loader($disableEntities);
     foreach ($dom->childNodes as $child) {
         if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
             throw new UnexpectedValueException('Document types are not allowed.');
         }
     }
     $xml = simplexml_import_dom($dom);
     if ($error = libxml_get_last_error()) {
         throw new UnexpectedValueException($error->message);
     }
     if (!$xml->count()) {
         if (!$xml->attributes()) {
             return (string) $xml;
         }
         $data = array();
         foreach ($xml->attributes() as $attrkey => $attr) {
             $data['@' . $attrkey] = (string) $attr;
         }
         $data['#'] = (string) $xml;
         return $data;
     }
     return $this->parseXml($xml);
 }
 public static function dom($stream)
 {
     rewind($stream);
     $actual = stream_get_contents($stream);
     $html = DOMDocument::loadHTML($actual);
     return simplexml_import_dom($html);
 }
Example #12
0
function wp_nav_menu_extended($args = array())
{
    $_echo = array_key_exists('echo', $args) ? $args['echo'] : true;
    $args['echo'] = false;
    $menu = wp_nav_menu($args);
    // Load menu as xml
    $menu = simplexml_load_string($menu);
    // Find current menu item with xpath selector
    if (array_key_exists('xpath', $args)) {
        $xpath = $args['xpath'];
    } else {
        $xpath = '//li[contains(@class, "current-menu-item") or contains(@class, "current_page_item")]';
    }
    $current = $menu->xpath($xpath);
    // If current item exists
    if (!empty($current)) {
        $text_node = (string) $current[0]->children();
        // Remove link
        unset($current[0]->a);
        // Create required element with text from link
        $element_name = $args['replace_a_by'] ? $args['replace_a_by'] : 'span';
        $dom = dom_import_simplexml($current[0]);
        $n = $dom->insertBefore($dom->ownerDocument->createElement($element_name, $text_node), $dom->firstChild);
        $current[0] = simplexml_import_dom($n);
    }
    $xml_doc = new DOMDocument('1.0', 'utf-8');
    $menu_x = $xml_doc->importNode(dom_import_simplexml($menu), true);
    $xml_doc->appendChild($menu_x);
    $menu = $xml_doc->saveXML($xml_doc->documentElement);
    if ($_echo) {
        echo $menu;
    } else {
        return $menu;
    }
}
Example #13
0
function load_simplexml_page($page, $type = 'url')
{
    ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
    $dom = new DOMDocument('1.0', 'UTF-8');
    $type === 'url' ? @$dom->loadHTMLFile(trim($page)) : @$dom->loadHTML($page);
    return simplexml_import_dom($dom);
}
 /**
  * Generate the module
  */
 protected function compile()
 {
     //Categories selected in List-Module-Options
     $arrCategoriesToShow = deserialize($this->gloImmoConnectorTypeSelector);
     $filter = null;
     if (\Input::post('FORM_SUBMIT') == $this->_searchFormId) {
         $filter = array('objectType' => htmlspecialchars(\Input::post('objectType')), 'zipcode' => htmlspecialchars(\Input::post('zipcode')), 'city' => htmlspecialchars(\Input::post('city')), 'keyword' => htmlspecialchars(\Input::post('keyword')));
     }
     //Get Expose Page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->_objTarget = $objTarget;
     }
     $objImmoConnector = new ImmoConnector('is24', \Config::get('gloImmoConnectorKey'), \Config::get('gloImmoConnectorSecret'));
     //User auf null setzen bzw. Username auslesen
     $objUser = \IcAuthModel::findByPk($this->gloImmoConnectorUser);
     if (is_null($objUser)) {
         throw new \Exception("Missing or invalid User selected for API-Connection", 1);
     }
     $objRes = $objImmoConnector->getAllUserObjects($objUser, $filter);
     $arrRes = $this->orderObjects(simplexml_import_dom($objRes));
     // Filtern auf die Kategorien der der Moduleinstellungen
     if (count($arrCategoriesToShow) > 0) {
         $arrRes = array_intersect_key($arrRes, array_flip($arrCategoriesToShow));
     }
     unset($objXml);
     $arrTypes = array_keys($arrRes);
     //Rendern der Objekt-Daten
     $arrRendered = array();
     foreach ($arrRes as $strType => $objList) {
         $arrRendered[$strType] = $this->renderObjectTypeGroup($strType, $objList);
     }
     unset($arrRes);
     $this->Template->realEstateObjects = $arrRendered;
 }
Example #15
0
function htmlobject($html)
{
    $html = str_replace('charset=Shift_JIS', 'charset=CP932', $html);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    return simplexml_import_dom($doc);
}
 public function generateContent()
 {
     // Can't download the documectation directly (required facebook login)
     $form = new Form(array('class' => 'form-horizontal', 'legend' => 'Paste HTML from https://developers.facebook.com/docs/reference/api/$model/', 'fields' => array('HTML' => new Input(array('type' => 'textarea', 'name' => 'source')), new Input(array('type' => 'submit', 'value' => 'Generate class', 'class' => 'btn btn-primary')))));
     $data = $form->import($error);
     if ($data) {
         $dom = new \DOMDocument();
         @$dom->loadHTML($data['source']);
         $xml = simplexml_import_dom($dom);
         $link = $xml->xpath('//div[@class="breadcrumbs"]/a[last()]');
         $path = explode('/', trim($link[0]['href'], '/'));
         $elements = $xml->xpath('//div[@id="bodyText"]');
         $info = array('class' => ucfirst(end($path)), 'link' => 'https://developers.facebook.com/' . implode('/', $path) . '/', 'description' => strip_tags($elements[0]->p[0]->asXML()), 'fields' => $this->extractFields($elements[0]->table[0]->tr), 'connections' => array(), 'constructor' => strpos($elements[0]->table[0]->asXML(), 'only returned if'));
         if ($elements[0]->table[1] !== null) {
             $info['connections'] = $this->extractFields($elements[0]->table[1]->tr);
         }
         if (count($info['fields']) == 0 && count($info['connections']) != 0) {
             // Thread documentation
             $info['fields'] = $info['connections'];
             $info['connections'] = $this->extractFields($elements[0]->table[2]->tr);
         }
         return new Dump($this->generatePhp($info));
     } else {
         return $form;
     }
 }
Example #17
0
 /**
  * parse FolderDelete request
  */
 public function handle()
 {
     $xml = simplexml_import_dom($this->_requestBody);
     // parse xml request
     $syncKey = (int) $xml->SyncKey;
     $serverId = (string) $xml->ServerId;
     if ($this->_logger instanceof Syncroton_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " synckey is {$syncKey}");
     }
     if (!($this->_syncState = $this->_syncStateBackend->validate($this->_device, 'FolderSync', $syncKey)) instanceof Syncroton_Model_SyncState) {
         return;
     }
     try {
         $folder = $this->_folderBackend->getFolder($this->_device, $serverId);
         $dataController = Syncroton_Data_Factory::factory($folder->class, $this->_device, $this->_syncTimeStamp);
         // delete folder in data backend
         $dataController->deleteFolder($folder);
     } catch (Syncroton_Exception_NotFound $senf) {
         if ($this->_logger instanceof Syncroton_Log) {
             $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " " . $senf->getMessage());
         }
         return;
     }
     // delete folder in syncState backend
     $this->_folderBackend->delete($folder);
     $this->_folder = $folder;
 }
Example #18
0
 public function indexAction()
 {
     SxCms_Acl::requireAcl('ad', 'ad.edit');
     $filename = APPLICATION_PATH . '/var/ads.xml';
     $dom = new DOMDocument();
     $dom->preserveWhiteSpace = false;
     $dom->loadXml(file_get_contents($filename));
     $dom->formatOutput = true;
     $xpath = new DOMXpath($dom);
     $xml = simplexml_import_dom($dom);
     if ($this->getRequest()->isPost()) {
         $ads = $this->_getParam('ad');
         foreach ($ads as $key => $value) {
             $nodeList = $xpath->query("//zone[id='{$key}']/content");
             if ($nodeList->length) {
                 $cdata = $dom->createCDATASection(stripslashes($value));
                 $content = $dom->createElement('content');
                 $content->appendChild($cdata);
                 $nodeList->item(0)->parentNode->replaceChild($content, $nodeList->item(0));
             }
         }
         $dom->save($filename);
         $flashMessenger = $this->_helper->getHelper('FlashMessenger');
         $flashMessenger->addMessage('Advertentie werd succesvol aangepast');
     }
     $this->view->ads = $xml;
 }
Example #19
0
 public function optimize($buffer)
 {
     $output = '';
     // matched buffer comes in from preg_replace_callback() as array
     $buffer = $buffer[0];
     $dom = new DOMDocument();
     $dom->loadHTML($buffer);
     $html = simplexml_import_dom($dom);
     // gather file names -
     // get URL's for each CSS file in each CSS tag of the HTML block
     $files = array();
     foreach ($html->head->link as $link) {
         // filter out things like favicon
         if ((string) $link['rel'] == 'stylesheet') {
             $file = trim((string) $link['href']);
             $files[] = trim($file, '/');
         }
     }
     // build the combined, minified output file
     // the latest mod time of the set is in output file name
     try {
         $outfile = $this->_getName($files);
         $this->_phing->log("Building {$this->_toDir}/{$outfile}");
         $this->_build($outfile, $files);
     } catch (Exception $e) {
         throw new BuildException($e->getMessage());
     }
     // output the static CSS tag
     $twoBitValue = 0x3 & crc32("{$outfile}");
     $host = str_replace('?', $twoBitValue, $this->_host);
     $path = "http://{$host}/{$outfile}";
     $output = "<link href=\"{$path}\" rel=\"stylesheet\" type=\"text/css\" />\n";
     return $output;
 }
Example #20
0
 /**
  * @param string $html
  */
 public function __construct($html)
 {
     $this->html = $html;
     $document = new DOMDocument();
     $document->loadHTML($this->html);
     $this->xml = simplexml_import_dom($document);
 }
function appendChildForSimpleXML($parent, $child)
{
    $parentNode = dom_import_simplexml($parent);
    $childXml = dom_import_simplexml($child);
    $childNode = $parentNode->ownerDocument->importNode($childXml, true);
    return simplexml_import_dom($parentNode->appendChild($childNode));
}
 /**
  * Validate and extract product data from a single node. Returns an array of product data or null if errors occured.
  * @param DOMNode $domNode
  * @return array|null
  */
 public function getProductData($domNode)
 {
     $doc = new DOMDocument('1.', 'UTF-8');
     $node = $doc->importNode($domNode, true);
     $doc->appendChild($node);
     $xmlProductNode = simplexml_import_dom($node);
     $this->_errors = array();
     if (!property_exists($xmlProductNode, 'simple_data')) {
         $this->_errors[] = 'Missing <simple_data> node.';
         return null;
     }
     $productData = $this->_extractSimpleData($xmlProductNode, $this->_extractStoreCodes($xmlProductNode));
     if ($productData == null) {
         $this->_errors[] = 'Invalid simple data.';
         return null;
     }
     $productData = $this->_afterSimpleData($productData);
     if ($productData == null) {
         return null;
     }
     $complexAttributeData = $this->_extractComplexData($xmlProductNode);
     if ($complexAttributeData === null) {
         $this->_errors[] = 'Invalid complex data.';
         return null;
     }
     $complexAttributeData = $this->_afterComplexData($complexAttributeData, $productData['default']['sku']);
     if (!is_null($complexAttributeData) && !empty($complexAttributeData)) {
         $productData['default'] = array_merge($productData['default'], $complexAttributeData);
     }
     return $this->_formatData($productData);
 }
Example #23
0
    /**
     * Validates and parses the given file into a SimpleXMLElement
     *
     * @param  string $file
     * @return SimpleXMLElement
     */
    private function parseFile($file)
    {
        $dom = new \DOMDocument();
        $current = libxml_use_internal_errors(true);
        if (!@$dom->load($file, LIBXML_COMPACT)) {
            throw new \RuntimeException(implode("\n", $this->getXmlErrors()));
        }

        $location = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd';
        $parts = explode('/', $location);
        if (preg_match('#^phar://#i', $location)) {
            $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
            if ($tmpfile) {
                file_put_contents($tmpfile, file_get_contents($location));
                $tmpfiles[] = $tmpfile;
                $parts = explode('/', str_replace('\\', '/', $tmpfile));
            }
        }
        $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
        $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));

        $source = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
        $source = str_replace('http://www.w3.org/2001/xml.xsd', $location, $source);

        if (!@$dom->schemaValidateSource($source)) {
            throw new \RuntimeException(implode("\n", $this->getXmlErrors()));
        }
        $dom->validateOnParse = true;
        $dom->normalizeDocument();
        libxml_use_internal_errors($current);

        return simplexml_import_dom($dom);
    }
Example #24
0
 /**
  * Constructor
  *
  * @param string $xml is the string we want to parse
  * @throws Exceptions\ParseException
  */
 public function __construct($xml)
 {
     $this->xml = $xml;
     libxml_use_internal_errors();
     $dom = new DOMDocument();
     $dom->recover = true;
     $dom->strictErrorChecking = false;
     $dom->loadXML($this->xml, LIBXML_NOCDATA);
     $dom->encoding = self::ENCODING;
     $opml = simplexml_import_dom($dom);
     if ($opml === false) {
         throw new Exceptions\ParseException('Provided XML document is not valid');
     }
     $this->result = ['version' => (string) $opml['version'], 'head' => [], 'body' => []];
     if (!isset($opml->head)) {
         throw new Exceptions\ParseException('Provided XML is not an valid OPML document');
     }
     // First, we get all "head" elements. Head is required but its sub-elements are optional.
     foreach ($opml->head->children() as $key => $value) {
         if (in_array($key, self::OPTIONAL_HEAD_ELEMENTS, true)) {
             $this->result['head'][$key] = (string) $value;
         }
     }
     if (!isset($opml->body)) {
         return;
     }
     // Then, we get body outlines. Body must contain at least one outline element.
     foreach ($opml->body->children() as $key => $value) {
         if ($key === 'outline') {
             $this->result['body'][] = $this->parseOutline($value);
         }
     }
 }
 function imgFindUploadSaveFromHTML($html, $folderName)
 {
     /* Reference: http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php */
     /* added on 8/28/11 to get images from any HTML content */
     $html = stripslashes($html);
     $doc = new DOMDocument();
     $doc->loadHTML($html);
     $xml = simplexml_import_dom($doc);
     // just to make xpath more simple
     $images = $xml->xpath('//img');
     /* foreach ($images as $img) {
     				echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];
     			}
     			*/
     foreach ($images as $img) {
         // echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];
         if (fopen($img['src'], "r") == true) {
             // run this check to see, if the image is on external server. For internal server, do nothing!
             if (strlen($img['src']) > 4) {
                 $alt = substr(slug($img['alt']), 0, 75);
                 $filename = $this->Upload->save_image_from_url($img['src'], 640, 125, $folderName, false, $alt);
                 if (!empty($filename)) {
                     $new_image_path = '/img/' . $folderName . '/big/' . $this->Upload->save_image_from_url($img['src'], 640, 125, $folderName, false, $alt);
                     if ($new_image_path) {
                         $html = str_replace($img['src'], $new_image_path, $html);
                     }
                 }
             }
         }
     }
     return $html;
 }
 /**
  */
 public function handle()
 {
     $xml = simplexml_import_dom($this->_inputDom);
     foreach ($xml->Collections->Collection as $xmlCollection) {
         // fetch values from a different namespace
         $airSyncValues = $xmlCollection->children('uri:AirSync');
         $collectionData = array('syncKey' => (int) $airSyncValues->SyncKey, 'class' => (string) $xmlCollection->Class, 'collectionId' => (string) $xmlCollection->CollectionId, 'filterType' => isset($airSyncValues->FilterType) ? (int) $airSyncValues->FilterType : 0);
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->info(__METHOD__ . '::' . __LINE__ . " synckey is {$collectionData['syncKey']} class: {$collectionData['class']} collectionid: {$collectionData['collectionId']} filtertype: {$collectionData['filterType']}");
         }
         try {
             // does the folder exist?
             $collectionData['folder'] = $this->_folderBackend->getFolder($this->_device, $collectionData['collectionId']);
             $collectionData['folder']->lastfiltertype = $collectionData['filterType'];
             if ($collectionData['syncKey'] === 0) {
                 $collectionData['syncState'] = new Syncope_Model_SyncState(array('device_id' => $this->_device, 'counter' => 0, 'type' => $collectionData['folder'], 'lastsync' => $this->_syncTimeStamp));
                 // reset sync state for this folder
                 $this->_syncStateBackend->resetState($this->_device, $collectionData['folder']);
                 $this->_contentStateBackend->resetState($this->_device, $collectionData['folder']);
             } else {
                 $collectionData['syncState'] = $this->_syncStateBackend->validate($this->_device, $collectionData['folder'], $collectionData['syncKey']);
             }
         } catch (Syncope_Exception_NotFound $senf) {
             if ($this->_logger instanceof Zend_Log) {
                 $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " " . $senf->getMessage());
             }
         }
         $this->_collections[$collectionData['collectionId']] = $collectionData;
     }
 }
Example #27
0
 /**
  * parse FolderUpdate request
  *
  */
 public function handle()
 {
     $xml = simplexml_import_dom($this->_requestBody);
     $syncKey = (int) $xml->SyncKey;
     if ($this->_logger instanceof Syncroton_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " synckey is {$syncKey}");
     }
     if (!($this->_syncState = $this->_syncStateBackend->validate($this->_device, 'FolderSync', $syncKey)) instanceof Syncroton_Model_SyncState) {
         return;
     }
     $updatedFolder = new Syncroton_Model_Folder($xml);
     if ($this->_logger instanceof Syncroton_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " parentId: {$updatedFolder->parentId} displayName: {$updatedFolder->displayName}");
     }
     try {
         $folder = $this->_folderBackend->getFolder($this->_device, $updatedFolder->serverId);
         $folder->displayName = $updatedFolder->displayName;
         $folder->parentId = $updatedFolder->parentId;
         $dataController = Syncroton_Data_Factory::factory($folder->class, $this->_device, $this->_syncTimeStamp);
         // update folder in data backend
         $dataController->updateFolder($folder);
     } catch (Syncroton_Exception_NotFound $senf) {
         if ($this->_logger instanceof Syncroton_Log) {
             $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " " . $senf->getMessage());
         }
         return;
     }
     // update folder status in Syncroton backend
     $this->_folder = $this->_folderBackend->update($folder);
 }
Example #28
0
 /**
  * Parses DOM element and adds it as an admin menu item
  *
  * @param \DOMDocument $xml
  */
 protected function importItems(\DOMDocument $xml)
 {
     foreach ($xml->documentElement->getElementsByTagName('item') as $item) {
         $dom = simplexml_import_dom($item);
         $this->addMenuItem($dom);
     }
 }
 /**
  * compile the given class id.
  */
 public function compile($selector)
 {
     jDaoCompiler::$daoId = $selector->toString();
     jDaoCompiler::$daoPath = $selector->getPath();
     jDaoCompiler::$dbType = $selector->driver;
     // chargement du fichier XML
     $doc = new DOMDocument();
     if (!$doc->load(jDaoCompiler::$daoPath)) {
         throw new jException('jelix~daoxml.file.unknow', jDaoCompiler::$daoPath);
     }
     if ($doc->documentElement->namespaceURI != JELIX_NAMESPACE_BASE . 'dao/1.0') {
         throw new jException('jelix~daoxml.namespace.wrong', array(jDaoCompiler::$daoPath, $doc->namespaceURI));
     }
     $parser = new jDaoParser();
     $parser->parse(simplexml_import_dom($doc));
     global $gJConfig;
     if (!isset($gJConfig->_pluginsPathList_db[$selector->driver]) || !file_exists($gJConfig->_pluginsPathList_db[$selector->driver])) {
         throw new jException('jelix~db.error.driver.notfound', $selector->driver);
     }
     require_once $gJConfig->_pluginsPathList_db[$selector->driver] . $selector->driver . '.daobuilder.php';
     $class = $selector->driver . 'DaoBuilder';
     $generator = new $class($selector->getDaoClass(), $selector->getDaoRecordClass(), $parser);
     // génération des classes PHP correspondant à la définition de la DAO
     $compiled = '<?php ' . $generator->buildClasses() . "\n?>";
     jFile::write($selector->getCompiledFilePath(), $compiled);
     return true;
 }
 public function __doRequest($request, $location, $action, $version, $one_way = null)
 {
     $api = $this->getBaseApi();
     $user = $api->getConfigData('merchant_id');
     $password = $api->getConfigData('security_key');
     $soapHeader = "<SOAP-ENV:Header xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:Security SOAP-ENV:mustUnderstand=\"1\"><wsse:UsernameToken><wsse:Username>{$user}</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">{$password}</wsse:Password></wsse:UsernameToken></wsse:Security></SOAP-ENV:Header>";
     $requestDOM = new DOMDocument('1.0');
     $soapHeaderDOM = new DOMDocument('1.0');
     $requestDOM->loadXML($request);
     $soapHeaderDOM->loadXML($soapHeader);
     $node = $requestDOM->importNode($soapHeaderDOM->firstChild, true);
     $requestDOM->firstChild->insertBefore($node, $requestDOM->firstChild->firstChild);
     $request = $requestDOM->saveXML();
     if ($api->getConfigData('debug')) {
         /*Clean up PAN and CV2 for debug*/
         $clean = simplexml_import_dom($requestDOM);
         $del = $clean->xpath('//ns1:accountNumber | //ns1:cvNumber');
         foreach ($del as $el) {
             $el[0] = '';
         }
         $debugrequest = $clean->asXML();
         $debug = Mage::getModel('cybersource/api_debug')->setAction($action)->setRequestBody($debugrequest)->save();
     }
     $response = parent::__doRequest($request, $location, $action, $version);
     if (!empty($debug)) {
         $debug->setResponseBody($response)->save();
     }
     return $response;
 }