/** * Simple XSLT transformation function * * @param mixed $xml DOMDocument or string containing xml * @param string $strXsltPath Relative file path to xslt document. Will look in both library location and * local app location for documents, and combine them so local overrides library * templates, if neccesary. * @param array $arrParams [optional] array of parameters to pass to stylesheet * @param bool $bolDoc [optional] return result as DOMDocument (default false) * @param array $arrInclude [optional] additional stylesheets that should be included in the transform * @return mixed newly formatted document as string or DOMDocument * @static */ public static function transform($xml, $strXsltPath, $arrParams = null, $bolDoc = false, $arrInclude = array()) { if ($strXsltPath == "") { throw new Exception("no stylesheet supplied"); } if (is_string($xml)) { // load xml document from string $objXml = new DOMDocument(); $objXml->loadXML($xml); $xml = $objXml; } $objXsl = self::generateBaseXsl($strXsltPath, $arrInclude); // create XSLT Processor $objProcessor = new XsltProcessor(); $objProcessor->registerPhpFunctions(); if ($arrParams != null) { // add in parameters foreach ($arrParams as $key => $value) { $objProcessor->setParameter(null, $key, $value); } } // transform $objXsl = $objProcessor->importStylesheet($objXsl); if ($bolDoc == true) { return $objProcessor->transformToDoc($xml); } else { return $objProcessor->transformToXml($xml); } }
/** * Simple, dynamic xsl transform */ protected function transform($xml, $path_to_xsl, $output_type = null, array $params = array(), array $import_array = array(), $to_string = true) { if ($path_to_xsl == "") { throw new \Exception("no stylesheet supplied"); } // make sure we have a domdocument if (is_string($xml)) { $xml = Parser::convertToDOMDocument($xml); } // create xslt processor $processor = new \XsltProcessor(); $processor->registerPhpFunctions(); // add parameters foreach ($params as $key => $value) { $processor->setParameter(null, $key, $value); } // add stylesheet $xsl = $this->generateBaseXsl($path_to_xsl, $import_array, $output_type); $processor->importStylesheet($xsl); // transform if ($to_string == true) { return $processor->transformToXml($xml); } else { return $processor->transformToDoc($xml); } }
/** * Execute render process * @param string $templatePath * @param \DOMDocument $source * @param array $parameters * @return string */ public function execute($templatePath, \DOMDocument $source, array $parameters = array()) { $xsl = new \DomDocument(); $xsl->load($templatePath); $processor = new \XsltProcessor(); $processor->importStylesheet($xsl); $outputDom = $processor->transformToDoc($source); if ($parameters['output.type'] && $parameters['output.type'] == 'xml') { $result = $outputDom->saveXML(); } else { $result = $outputDom->saveHTML(); } return $result; }
private function xsltTransform($xmlStr, $xslFile, $toDom = false) { $doc = new DOMDocument(); $doc->substituteEntities = TRUE; // $doc->resolveExternals = TRUE; $doc->load($xslFile); $proc = new XsltProcessor(); $proc->importStylesheet($doc); $doc->loadXML($xmlStr); if ($toDom) { return $proc->transformToDoc($doc); } else { return $proc->transformToXml($doc); } }
/** * Return a formatted html list of resources associated with a given * tag. * * The caller should check the $tr->status variable to see if the * query was successful. On anything but a 200 or 304, this method * returns nothing, but it would generally be useful to have a * warning for 204 (no resources yet for this tag) or 404 (tag not * found). * * @return string html for a list of resources referenced by the * given tag. * * */ public function resList() { if (strlen($this->xml) == 0) { $this->getData(); // args ? } if ($this->is_valid()) { $xsl = new DOMDocument(); $xsl->load($this->loc->xsl_dir . "public_resourcelist.xsl"); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); // possibly cached DOM $taglist = $proc->transformToDoc($this->xml_DOM()); $this->html = $taglist->saveXML(); return $this->html; } }
function outputXML($projectList) { $dom = new DOMDocument('1.0'); $dom->formatOutput = true; //header("Content-Type: text/plain"); $root = $dom->createElement('SVNDump'); $dom->appendChild($root); foreach ($projectList as &$project) { $this->addProjectNode($dom, $root, $project); } $xsl = new DOMDocument('1.0'); $xsl->load("cs242_portfolio.xsl"); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($dom); echo $newdom->saveHTML(); //echo $dom->saveXML(); }
public function transform($xsl_file = null, $xml_data = null) { CI()->benchmark->mark('xsl_transform (' . $xsl_file . ')_start'); set_error_handler(array('XSL_Transform', 'handleError')); $xsl = new DOMDocument('1.0', 'UTF-8'); $xsl->load($this->_getXSL($xsl_file)); $inputdom = new DomDocument('1.0', 'UTF-8'); $inputdom->loadXML($this->_getXML($xml_data)); $proc = new XsltProcessor(); $proc->importStylesheet($xsl); $proc->registerPhpFunctions($this->_allowedFunctions()); // $result = $proc->transformToXML($inputdom); $proc->setParameter('', 'ISAJAX', CI()->is_ajax); $result_doc = $proc->transformToDoc($inputdom); $result = $result_doc->saveXML(); restore_error_handler(); // Strip out any <?xml stuff at top out output $result = preg_replace('/\\<\\?xml.+\\?\\>/', '', $result, 1); CI()->benchmark->mark('xsl_transform (' . $xsl_file . ')_end'); return $result; }
/** * Retreives and formats a tag cloud for the current page. The html * remains available in $this->html. If html data is already * present, simply returns that. * * @param $url string (Optional) The url (or id) for which a cloud should be * made. Default is to use the current page. * @param $max_tags integer (Optional). Defaults to 0, meaning get all * the tags. * * @returns string The html cloud that is built. */ public function buildCloud($url = '', $max_tags = 0, $cloudtype = '') { if ($this->html) { return $this->html; } if (!$this->xml) { $this->getData($url ? $url : $this->url, $max_tags, $cloudtype); } if ($this->is_valid()) { $xsl = new DOMDocument(); $xsl->load($this->loc->xsl_dir . "publiccloud.xsl"); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); // setting url format so that it is not hard coded in the xsl. $proc->setParameter('', 'tagviewbase', $this->loc->server_web_path . 'tagview.php?tag='); //using cloud->xml_DOM() because this data might have been cached already. $cloud = $proc->transformToDoc($this->xml_DOM()); $this->html = $cloud->saveXML(); } return $this->html; }
private function compile($templateName, $block = '') { $paths = $this->getPaths($templateName, $block); $templatePath = $paths[0]; $stylePath = $paths[1]; if (!empty($templatePath) and !empty($stylePath)) { if (!$this->isCompiled($templateName)) { $xsl = new DomDocument(); $xsl->load($stylePath); $inputdom = new DomDocument(); $inputdom->load($templatePath); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); /* transform and output the xml document */ $newdom = $proc->transformToDoc($inputdom); $data = $newdom->saveHTML(); $data = str_replace('phpvar:', '<?php echo $', $data); $data = str_replace(':phpvar', '; ?>', $data); file_put_contents(__ALIEN_TEMPLATESDIR . "/compiled/{$templateName}.php", $data); return __ALIEN_TEMPLATESDIR . "/compiled/{$templateName}.php"; } } }
<?php $xsl = new DomDocument(); $xsl->load("style.xslt"); $inputdom = new DomDocument(); $inputdom->load("doc.xml"); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); /* transform and output the xml document */ $newdom = $proc->transformToDoc($inputdom); echo $newdom->saveXML();
public static function parseHcard($uri = "") { // Source file if (empty($uri) && isset($_REQUEST["uri"])) { $uri = $_REQUEST["uri"]; } if (!file_exists(INCLEVEL . PATH_MICROFORMATS . "/xhtml2vcard.xsl")) { $GLOBALS["documentClass"]->outputHttpHeaders(); print "<html>\r\n" . " <head>\r\n" . " <link type='text/css' rel='stylesheet' media='all' href='" . URL_PREFIX . "/_css/2011/screen.css'>\r\n" . " </head>\r\n" . " <body style='position:absolute;top:100px;left:100px;width:400px'>\r\n" . " <div class='box error background padding'>\r\n" . " <h1 class='red'>» SORRY «</h1>\r\n" . " <p class='red' style='font-size:1.5em'>Could not display the vCard.</p>\r\n" . " </div>\r\n" . " <p style='font-size:1.5em'><a href='" . $uri . "'>« Back</a></p>\r\n" . " </body>\r\n" . "</html>\r\n"; return ""; } // Read source and convert HTML code to XHTML $xml_string_tidy = file_get_contents("http://cgi.w3.org/cgi-bin/tidy?docAddr=" . urlencode($uri)); // Create the HTML DOM @($document = new DOMDocument()); @$document->loadHTML($xml_string_tidy); // Create the XSLT DOM $stylesheet = new DOMDocument(); $stylesheet->load(INCLEVEL . PATH_MICROFORMATS . "/xhtml2vcard.xsl"); // Create a new XSLT Processor, load the Stylesheet $processor = new XsltProcessor(); $processor->importStylesheet($stylesheet); // Run the transformation $result = $processor->transformToDoc($document); $output = $result->saveXML(); // Massage output $output = str_replace(" /+/ ", "@", $output); $output = str_replace("(Best Practices states this should be the URL the vcard was transformed from)", $uri, $output); $output = preg_replace("/<\\?.*>\\s/i", "", $output); $output = str_replace(" ", "", $output); // Output file name if (preg_match("/FN(;LANGUAGE=.*;CHARSET=.*)?:(.*)/i", $output, $res) && !empty($res[2])) { $name = trim(str_replace(" ", "_", $res[2])); } else { $name = "contact"; } // Send the vCard header with PHP header("Content-Disposition: attachment; filename=" . $name . ".vcf"); header("Content-Type: text/x-vcard; charset=UTF-8 name=" . $name . ".vcf"); print $output; return ""; }
public function getXPath($entry, $XSLTfilename = NULL, $fetch_associated_counts = NULL) { $entry_xml = new XMLElement('entry'); $data = $entry->getData(); $fields = array(); $entry_xml->setAttribute('id', $entry->get('id')); //Add date created and edited values $date = new XMLElement('system-date'); $date->appendChild(General::createXMLDateObject(DateTimeObj::get('U', $entry->get('creation_date')), 'created')); $date->appendChild(General::createXMLDateObject(DateTimeObj::get('U', $entry->get('modification_date')), 'modified')); $entry_xml->appendChild($date); //Reflect Workspace and Siteroot params $workspace = new XMLElement('workspace', URL . '/workspace'); $root = new XMLElement('root', URL); // Add associated entry counts if ($fetch_associated_counts == 'yes') { $associated = $entry->fetchAllAssociatedEntryCounts(); if (is_array($associated) and !empty($associated)) { foreach ($associated as $section_id => $count) { $section = SectionManager::fetch($section_id); if ($section instanceof Section === false) { continue; } $entry_xml->setAttribute($section->get('handle'), (string) $count); } } } // Add fields: foreach ($data as $field_id => $values) { if (empty($field_id)) { continue; } $field = FieldManager::fetch($field_id); $field->appendFormattedElement($entry_xml, $values, false, null, $entry->get('id')); } $xml = new XMLElement('data'); $xml->appendChild($entry_xml); $xml->appendChild($workspace); $xml->appendChild($root); // Build some context $section = SectionManager::fetch($entry->get('section_id')); $params = new XMLElement('params'); $params->appendChild(new XMLElement('section-handle', $section->get('handle'))); $params->appendChild(new XMLElement('entry-id', $entry->get('id'))); $xml->prependChild($params); $dom = new DOMDocument(); $dom->strictErrorChecking = false; $dom->loadXML($xml->generate(true)); if (!empty($XSLTfilename)) { $XSLTfilename = UTILITIES . '/' . preg_replace(array('%/+%', '%(^|/)../%'), '/', $XSLTfilename); if (file_exists($XSLTfilename)) { $XSLProc = new XsltProcessor(); $xslt = new DomDocument(); $xslt->load($XSLTfilename); $XSLProc->importStyleSheet($xslt); // Set some context $XSLProc->setParameter('', array('section-handle' => $section->get('handle'), 'entry-id' => $entry->get('id'))); $temp = $XSLProc->transformToDoc($dom); if ($temp instanceof DOMDocument) { $dom = $temp; } } } $xpath = new DOMXPath($dom); if (version_compare(phpversion(), '5.3', '>=')) { $xpath->registerPhpFunctions(); } return $xpath; }
/** * create google sitemap * * @return void * @author Andy Bennett */ public function google() { $xsl_path = Kohana::find_file('xsl', 'sitemap', TRUE, 'xsl'); /* load the xml file and stylesheet as domdocuments */ $xsl = new DomDocument(); $xsl->load($xsl_path); $inputdom = new DomDocument(); $inputdom->loadXML($this->sitemap_string); /* create the processor and import the stylesheet */ $proc = new XsltProcessor(); $proc->importStyleSheet($xsl); $proc->setParameter('', 'siteurl', url::base()); /* transform and output the xml document */ $newdom = $proc->transformToDoc($inputdom); print $newdom->saveXML(); }
/** * internal function * uses an xsl to parse the sparql xml returned from the ITQL query * * * @param $content String */ function parseContent($content, $pid, $dsId, $collection, $pageNumber = null) { $path = drupal_get_path('module', 'Fedora_Repository'); global $base_url; $collection_pid = $pid; //we will be changing the pid later maybe //module_load_include('php', ''Fedora_Repository'', 'ObjectHelper'); $objectHelper = $this; $parsedContent = NULL; $contentModels = $objectHelper->get_content_models_list($pid); $isCollection = false; //if this is a collection object store the $pid in the session as it will come in handy //after a purge or ingest to return to the correct collection. if (!empty($contentModels)) { foreach ($contentModels as $contentModel) { if ($contentModel == 'epistemetec:albumCModel' || $contentModel == 'epistemetec:compilationCModel' || $contentModel == 'epistemetec:videotecaCModel' || $contentModel == 'epistemetec:collectionCModel') { $_SESSION['fedora_collection'] = $pid; $isCollection = true; } } } //get a list of datastream for this object $datastreams = $this->get_formatted_datastream_list($pid, $contentModels); //$label=$content; $collectionName = $collection; if (!$pageNumber) { $pageNumber = 1; } if (!isset($collectionName)) { $collectionName = variable_get('fedora_repository_name', 'Collection'); } $xslContent = $this->getXslContent($pid, $path); //get collection list and display using xslt------------------------------------------- if (isset($content) && $content != false) { $input = new DomDocument(); $input->loadXML(trim($content)); $results = $input->getElementsByTagName('result'); if ($results->length > 0) { try { $proc = new XsltProcessor(); $proc->setParameter('', 'collectionPid', $collection_pid); $proc->setParameter('', 'collectionTitle', $collectionName); $proc->setParameter('', 'baseUrl', $base_url); $proc->setParameter('', 'path', $base_url . '/' . $path); $proc->setParameter('', 'hitPage', $pageNumber); $proc->registerPHPFunctions(); $xsl = new DomDocument(); $xsl->loadXML($xslContent); //php xsl does not seem to work with namespaces so removing it below //I may have just been being stupid here // $content = str_ireplace('xmlns="http://www.w3.org/2001/sw/DataAccess/rf1/result"', '', $content); $xsl = $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($input); $objectList = $newdom->saveXML(); //is the xml transformed to html as defined in the xslt associated with the collection object if (!$objectList) { throw new Exception("Invalid XML."); } } catch (Exception $e) { drupal_set_message(t($e->getMessage()), 'error'); return ''; } } } else { drupal_set_message(t("No Objects in this Collection or bad query.")); } //-------------------------------------------------------------------------------- //show the collections datastreams if ($results->length > 0 || $isCollection == true) { // if(strlen($objectList)>22||$contentModel=='Collection'||$contentModel=='Community'){//length of empty dom still equals 22 because of <table/> etc $collectionPolicyExists = $objectHelper->getMimeType($pid, 'COLLECTION_POLICY'); //drupal_set_message($collectionPolicyExists, 'error'); if (user_access(ObjectHelper::$INGEST_FEDORA_OBJECTS) && $collectionPolicyExists) { if (!empty($collectionPolicyExists) && strcasecmp($collectionPolicyExists, 'application/zip')) { $ingestObject = '<a title="' . t('Ingest a New object into ') . $collectionName . ' ' . $collection_pid . '" href="' . base_path() . 'fedora/ingestObject/' . $collection_pid . '/' . $collectionName . '"><img hspace = "8" src="' . $base_url . '/' . $path . '/images/ingest.png" alt="' . t('Ingest Object') . '"></a>'; } } else { $ingestObject = ' '; } $datastreams .= $ingestObject; $collection_fieldset = array('#title' => t('Collection Description'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#value' => $datastreams); $collectionListOut = theme('fieldset', $collection_fieldset); $object_list_fieldset = array('#title' => t('Items in this Collection'), '#collapsible' => TRUE, '#collapsed' => FALSE, '#value' => isset($objectList) ? $objectList : ''); $objectListOut = theme('fieldset', $object_list_fieldset); } else { //$collectionName=''; $collection_fieldset = array('#title' => "", '#collapsible' => TRUE, '#collapsed' => FALSE, '#value' => $datastreams); $collectionListOut = theme('fieldset', $collection_fieldset); $objectListOut = ''; //no collection objects to show so don't show field set } return "<STRONG>" . $collectionName . "</STRONG>" . ' <br />' . $collectionListOut . '<br />' . $objectListOut; }
<div id="container"> <?php if ($_GET['tag']) { $tagthing = strip_tags(substr($_GET['tag'], 0, 255)); $fc = new folksoClient('localhost', $loc->server_web_path . 'tag.php', 'get'); $fc->set_getfields(array('folksotag' => $tagthing, 'folksofancy' => '1')); $reslist = $fc->execute(); if ($fc->query_resultcode() == 200) { $resources = new DOMDocument(); $resources->loadXML($reslist); $xsl = new DOMDocument(); $xsl->load($loc->xsl_dir . "resourcelist.xsl"); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); $form = $proc->transformToDoc($resources); print $form->saveXML(); } else { print $fc->query_resultcode(); } } ?> <div id="pagebottom"> <form action="resourceview.php" method="get"> <p> Entrer un uri ou un identifiant de resource déjà présente dans la base </p> <p> <input type="text" name="tagthing" maxlength="3" size="3"></input> </p> <p>
/** * Returns all matching XML schema files and loads them into data models for * class. */ protected function loadDataModels() { $schemas = array(); $totalNbTables = 0; $dataModelFiles = $this->getSchemas(); $defaultPlatform = $this->getGeneratorConfig()->getConfiguredPlatform(); // Make a transaction for each file foreach ($dataModelFiles as $schema) { $dmFilename = $schema->getPathName(); $this->log('Processing: ' . $schema->getFileName()); $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->load($dmFilename); $this->includeExternalSchemas($dom, $schema->getPath()); // normalize (or transform) the XML document using XSLT if ($this->getGeneratorConfig()->get()['generator']['schema']['transform'] && $this->xsl) { $this->log('Transforming ' . $dmFilename . ' using stylesheet ' . $this->xsl->getPath()); if (!class_exists('\\XSLTProcessor')) { $this->log('Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.'); } else { // normalize the document using normalizer stylesheet $xslDom = new \DOMDocument('1.0', 'UTF-8'); $xslDom->load($this->xsl->getAbsolutePath()); $xsl = new \XsltProcessor(); $xsl->importStyleSheet($xslDom); $dom = $xsl->transformToDoc($dom); } } // validate the XML document using XSD schema if ($this->validate && $this->xsd) { $this->log(' Validating XML using schema ' . $this->xsd->getPath()); if (!$dom->schemaValidate($this->xsd->getAbsolutePath())) { throw new EngineException(sprintf("XML schema file (%s) does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $dmFilename), $this->getLocation()); } } $xmlParser = new SchemaReader($defaultPlatform, $this->dbEncoding); $xmlParser->setGeneratorConfig($this->getGeneratorConfig()); $schema = $xmlParser->parseString($dom->saveXML(), $dmFilename); $nbTables = $schema->getDatabase(null, false)->countTables(); $totalNbTables += $nbTables; $this->log(sprintf(' %d tables processed successfully', $nbTables)); $schema->setName($dmFilename); $schemas[] = $schema; } $this->log(sprintf('%d tables found in %d schema files.', $totalNbTables, count($dataModelFiles))); if (empty($schemas)) { throw new BuildException('No schema files were found (matching your schema fileset definition).'); } foreach ($schemas as $schema) { // map schema filename with database name $this->dataModelDbMap[$schema->getName()] = $schema->getDatabase(null, false)->getName(); } if (count($schemas) > 1 && $this->getGeneratorConfig()->get()['generator']['packageObjectModel']) { $schema = $this->joinDataModels($schemas); $this->dataModels = array($schema); } else { $this->dataModels = $schemas; } foreach ($this->dataModels as &$schema) { $schema->doFinalInitialization(); } $this->dataModelsLoaded = true; }
/** * translate xml * * @param string $xml_dom * @param string $xsl_dom * @param string $params * @param string $php_functions * @return void * @author Andy Bennett */ private static function translate($xml_dom, $xsl_dom, $params = array(), $php_functions = array()) { /* create the processor and import the stylesheet */ $proc = new XsltProcessor(); $proc->importStyleSheet($xsl_dom); foreach ($params as $name => $param) { $proc->setParameter('', $name, $param); } if (is_array($php_functions)) { $proc->registerPHPFunctions($php_functions); } /* transform and output the xml document */ $newdom = $proc->transformToDoc($xml_dom); return $newdom->saveXML(); }
function xml2array($xml, $template) { $xp = new XsltProcessor(); $xsl = new DomDocument(); $xsl->load($template); $xp->importStyleSheet($xsl); $dom = $xp->transformToDoc($xml); //--- ladeni --- //header('Content-type: application/xml'); //echo $dom->saveXML(); exit; // --- $this->xml = $xml; //--- vyreseni locales --- $locales = $this->xml->getElementsByTagNameNS("http://www.isotc211.org/2005/gmd", "PT_Locale"); foreach ($locales as $locale) { if ($locale->hasAttributes()) { $langCode = $locale->getElementsByTagNameNS("http://www.isotc211.org/2005/gmd", "LanguageCode"); $this->langCodes['#' . $locale->getAttribute('id')] = $langCode->item(0)->getAttribute('codeListValue'); $this->langCodes[$locale->getAttribute('id')] = $langCode->item(0)->getAttribute('codeListValue'); // DOCASNE kvuli ruznym chybam ve starych XML } } if ($dom->documentElement) { $data = $this->writeNode("", $dom->documentElement, 0); } if (substr($data, 0, 3) != '$md') { return array(); } // pokud jsou prazdne $data = str_replace(array("['language'][0]['gco:CharacterString']", "['MD_Identifier']", "ns1:"), array("['language'][0]['LanguageCode']", "['RS_Identifier']", "gco:"), $data); //kvuli portalu INSPIRE // quick and dirty patch for distance $data = str_replace(array("['gco:Distance'][0]['uom']", "['gco:Distance']"), array("['uom'][0]['uomName']", "['value']"), $data); // DEBUG //echo "<pre>$data</pre>"; exit; $data = str_replace(array("gmd:", "gmi:"), "", $data); //FIXME udelat pres sablony //$data = str_replace("csw:", "", $data); //FIXME udelat pres sablony $data = str_replace("'false'", "0", $data); $data = str_replace("['language'][0]['gco:CharacterString']", "['language'][0]['LanguageCode']", $data); //kvuli portalu INSPIRE $elim = array("'gco:CharacterString'", "'gco:Date'", "'gco:DateTime'", "'gco:Decimal'", "'gco:Integer'", "'gco:Boolean'", "'gco:LocalName'", "'URL'", "'gco:Real'", "'gco:Record'", "'gco:RecordType'", "'LocalisedCharacterString'", "gml:", "srv:", "gco:", "['PT_FreeText'][0]", "[][0]", "'DCPList'", "['gts:TM_PeriodDuration'][0]", "['Polygon'][0]['exterior'][0]['LinearRing'][0]['posList'][0]", "'gmx:MimeFileType'"); $data = str_replace($elim, "", $data); $data = str_replace("['serviceType'][0]", "['serviceType'][0]['LocalName'][0]", $data); $data = str_replace(array("['begin'][0]['TimeInstant'][0]['timePosition'][0]", "['end'][0]['TimeInstant'][0]['timePosition'][0]", "['MD_Identifier']", "'false'", "'true'", "MI_Metadata"), array("['beginPosition'][0]", "['endPosition'][0]", "['RS_Identifier']", "0", "1", "MD_Metadata"), $data); $data = str_replace("['RS_Identifier'][0]['code'][0]['gmx:Anchor'][0]['href'][0]", "['RS_Identifier'][0]['code'][0]", $data); //*** pro DC $data = str_replace(array("csw:Record", "dc:", "dct:abstract", "[][0]"), array("metadata", "", "description", ""), $data); /*if($this->debug) echo "<pre>". $data . "</pre>"; */ //--------------------------------------- if (MICKA_CHARSET != 'UTF-8') { $data = iconv('UTF-8', MICKA_CHARSET . '//TRANSLIT', $data); } //echo "data=".$data; eval($data); // odstraneni Locale a dateTime for ($i = 0; $i < count($md['MD_Metadata']); $i++) { unset($md['MD_Metadata'][$i]['locale']); if (isset($md['MD_Metadata'][$i]['dateStamp']['@']) && strpos($md['MD_Metadata'][$i]['dateStamp']['@'], 'T')) { $pom = explode('T', $md['MD_Metadata'][$i]['dateStamp']['@']); // FIXME quick hack $md['MD_Metadata'][$i]['dateStamp']['@'] = $pom[0]; } // zpracovani polygonu for ($j = 0; $j < count($md['MD_Metadata'][$i]['identificationInfo'][0]['MD_DataIdentification'][0]['extent'][0]['EX_Extent'][0]['geographicElement']); $j++) { if ($md['MD_Metadata'][$i]['identificationInfo'][0]['MD_DataIdentification'][0]['extent'][0]['EX_Extent'][0]['geographicElement'][$j]['EX_BoundingPolygon'][0]['polygon'][0]['@']) { $geom = explode(" ", $md['MD_Metadata'][$i]['identificationInfo'][0]['MD_DataIdentification'][0]['extent'][0]['EX_Extent'][0]['geographicElement'][$j]['EX_BoundingPolygon'][0]['polygon'][0]['@']); $result = ""; for ($k = 0; $k < count($geom); $k = $k + 2) { if ($result) { $result .= ","; } $result .= $geom[$k] . " " . $geom[$k + 1]; } $md['MD_Metadata'][$i]['identificationInfo'][0]['MD_DataIdentification'][0]['extent'][0]['EX_Extent'][0]['geographicElement'][$j]['EX_BoundingPolygon'][0]['polygon'][0]['@'] = "MULTIPOLYGON(((" . $result . ")))"; } } // doplnění překladu INSPIRE // --- multiligvalni klic. slova $lang = $md['MD_Metadata'][$i]["language"][0]["LanguageCode"][0]['@']; if (!$lang) { $lang = 'eng'; } if ($md['MD_Metadata'][$i]['identificationInfo'][0]['SV_ServiceIdentification']) { $this->multiKeywords($md['MD_Metadata'][$i]['identificationInfo'][0]['SV_ServiceIdentification'][0]['descriptiveKeywords'], $lang); } else { $this->multiKeywords($md['MD_Metadata'][$i]['identificationInfo'][0]['MD_DataIdentification'][0]['descriptiveKeywords'], $lang); } } //var_dump($md); return $md; }
function retriever_apply_xslt_text($xslt_text, $doc) { if (!$xslt_text) { logger('retriever_apply_xslt_text: empty XSLT text', LOGGER_NORMAL); return $doc; } $xslt_doc = new DOMDocument(); if (!$xslt_doc->loadXML($xslt_text)) { logger('retriever_apply_xslt_text: could not load XML', LOGGER_NORMAL); return $doc; } $xp = new XsltProcessor(); $xp->importStylesheet($xslt_doc); $result = $xp->transformToDoc($doc); return $result; }
function applyXSLT($resultData, $orderBy = 0) { $path = drupal_get_path('module', 'Fedora_Repository'); $proc = null; if (!$resultData) { //drupal_set_message(t('No Results!')); return ' '; //no results } try { $proc = new XsltProcessor(); } catch (Exception $e) { drupal_set_message(t('Error loading results xslt! ') . $e->getMessage()); return ' '; } //inject into xsl stylesheet //$proc->setParameter('', 'searchToken', drupal_get_token('search_form')); //token generated by Drupal, keeps tack of what tab etc we are on $proc->setParameter('', 'userID', $user->uid); $proc->setParameter('', 'searchUrl', url('search') . '/fedora_repository'); //needed in our xsl $proc->setParameter('', 'objectsPage', base_path()); $proc->setParameter('', 'allowedPidNameSpaces', variable_get('fedora_pids_allowed', 'demo: changeme:')); $proc->setParameter('', 'orderBy', $orderBy); $xsl = new DomDocument(); $test = $xsl->load($path . '/ir/xsl/results.xsl'); if (!isset($test)) { drupal_set_message(t('Error loading search results xslt!')); return t('Error loading search results xslt! '); } $input = new DomDocument(); $didLoadOk = $input->loadXML($resultData); if (!isset($didLoadOk)) { drupal_set_message(t('Error loading search results!')); return t('Error loading search results! '); } else { $xsl = $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($input); return $newdom->saveXML(); } }
function getEpistemetecData($pid) { global $base_url; $path = drupal_get_path('module', 'Fedora_Repository'); module_load_include('php', 'Fedora_Repository', 'ConnectionHelper'); $soapHelper = new ConnectionHelper(); $client = $soapHelper->getSoapClient(variable_get('fedora_soap_url', 'http://localhost:8080/fedora/services/access?wsdl')); $dsId = 'MAG'; $params = array('pid' => "{$pid}", 'dsID' => "{$dsId}", 'asOfDateTime' => ""); try { $object = $client->__soapCAll('getDatastreamDissemination', array('parameters' => $params)); } catch (Exception $e2) { try { //probably no QDC so we will try for the DC stream. $dsId = 'MAG'; $params = array('pid' => "{$pid}", 'dsID' => "{$dsId}", 'asOfDateTime' => ""); $object = $client->__soapCAll('getDatastreamDissemination', array('parameters' => $params)); } catch (exception $e2) { drupal_set_message($e2->getMessage(), 'error'); return; } } $xmlstr = $object->dissemination->stream; try { $proc = new XsltProcessor(); } catch (Exception $e) { drupal_set_message($e->getMessage(), 'error'); return; } $proc->setParameter('', 'baseUrl', $base_url); $proc->setParameter('', 'path', $base_url . '/' . $path); $input = null; $xsl = new DomDocument(); try { $xsl->load($path . '/epistemetec/xsl/epistemetecData.xsl'); $input = new DomDocument(); $input->loadXML(trim($xmlstr)); } catch (exception $e) { watchdog("Fedora_Repository", "Problem loading xsl file!"); } $xsl = $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($input); $output = $newdom->saveXML(); $baseUrl = base_path(); $baseUrl = substr($baseUrl, 0, strpos($baseUrl, "/") - 1); // if (user_access(ObjectHelper :: $EDIT_FEDORA_METADATA)) { // $output .= '<br /><a title = "' . t('Edit Meta Data') . '" href="' . $base_url . '/fedora/repository/' . 'editmetadata/' . $pid . '/' . $dsId . '"><img src="' . $base_url . '/' . $path . '/images/edit.gif" alt="' . t('Edit Meta Data') . '" /></a>'; // } return $output; }
/** * Gets all matching XML schema files and loads them into data models for class. * @return void */ protected function loadDataModels() { $ads = array(); $totalNbTables = 0; $this->log('Loading XML schema files...'); // Get all matched files from schemaFilesets foreach ($this->schemaFilesets as $fs) { $ds = $fs->getDirectoryScanner($this->project); $srcDir = $fs->getDir($this->project); $dataModelFiles = $ds->getIncludedFiles(); sort($dataModelFiles); $defaultPlatform = $this->getGeneratorConfig()->getConfiguredPlatform(); // Make a transaction for each file foreach ($dataModelFiles as $dmFilename) { $this->log("Processing: " . $dmFilename, Project::MSG_VERBOSE); $xmlFile = new PhingFile($srcDir, $dmFilename); $dom = new DomDocument('1.0', 'UTF-8'); $dom->load($xmlFile->getAbsolutePath()); // modify schema to include any external schemas (and remove the external-schema nodes) $this->includeExternalSchemas($dom, $srcDir); // normalize (or transform) the XML document using XSLT if ($this->getGeneratorConfig()->getBuildProperty('schemaTransform') && $this->xslFile) { $this->log("Transforming " . $dmFilename . " using stylesheet " . $this->xslFile->getPath(), Project::MSG_VERBOSE); if (!class_exists('XSLTProcessor')) { $this->log("Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.", Project::MSG_ERR); } else { // normalize the document using normalizer stylesheet $xslDom = new DomDocument('1.0', 'UTF-8'); $xslDom->load($this->xslFile->getAbsolutePath()); $xsl = new XsltProcessor(); $xsl->importStyleSheet($xslDom); $dom = $xsl->transformToDoc($dom); } } // validate the XML document using XSD schema if ($this->validate && $this->xsdFile) { $this->log(" Validating XML using schema " . $this->xsdFile->getPath(), Project::MSG_VERBOSE); if (!$dom->schemaValidate($this->xsdFile->getAbsolutePath())) { throw new EngineException("XML schema file (" . $xmlFile->getPath() . ") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $this->getLocation()); } } $xmlParser = new XmlToAppData($defaultPlatform, $this->getTargetPackage(), $this->dbEncoding); $xmlParser->setGeneratorConfig($this->getGeneratorConfig()); $ad = $xmlParser->parseString($dom->saveXML(), $xmlFile->getAbsolutePath()); $nbTables = $ad->getDatabase(null, false)->countTables(); $totalNbTables += $nbTables; $this->log(sprintf(' %d tables processed successfully', $nbTables), Project::MSG_VERBOSE); $ad->setName($dmFilename); $ads[] = $ad; } $this->log(sprintf('%d tables found in %d schema files.', $totalNbTables, count($dataModelFiles))); } if (empty($ads)) { throw new BuildException("No schema files were found (matching your schema fileset definition)."); } foreach ($ads as $ad) { // map schema filename with database name $this->dataModelDbMap[$ad->getName()] = $ad->getDatabase(null, false)->getName(); } if (count($ads) > 1 && $this->packageObjectModel) { $ad = $this->joinDataModels($ads); $this->dataModels = array($ad); } else { $this->dataModels = $ads; } foreach ($this->dataModels as &$ad) { $ad->doFinalInitialization(); } if ($this->validate) { foreach ($this->dataModels as $dataModel) { $validator = new PropelSchemaValidator($dataModel); if (!$validator->validate()) { throw new EngineException(sprintf("The database schema contains errors:\n - %s", join("\n - ", $validator->getErrors()))); } } } $this->dataModelsLoaded = true; }
function showRomeo($collapsed = false) { $path = drupal_get_path('module', 'Fedora_Repository'); module_load_include('php', 'Fedora_Repository', 'CollectionClass'); $collectionHelper = new CollectionClass(); //$returnValue['title']="Description"; $xmlstr = $collectionHelper->getStream($this->pid, "ROMEO", 0); if ($xmlstr == null || strlen($xmlstr) < 5) { return " "; } try { $proc = new XsltProcessor(); } catch (Exception $e) { drupal_set_message(t($e->getMessage()), 'error'); return; } $xsl = new DomDocument(); $xsl->load($path . '/xsl/romeo.xsl'); $input = new DomDocument(); $input->loadXML(trim($xmlstr)); $xsl = $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($input); $content = $newdom->saveXML(); $collection_fieldset = array('#title' => t('Romeo'), '#collapsible' => TRUE, '#collapsed' => $collapsed, '#value' => $content); return theme('fieldset', $collection_fieldset); }
/** * Merge the data and the XML template into an HTML page. * @param type $xslDocument the template. * @return type * @throws Dom\Exception */ public function transform($xslDocument) { if ($xslDocument->domDocument) { $processor = new \XsltProcessor(); $processor->importStylesheet($xslDocument->domDocument); $htmlDomDocument = new self(); $htmlDomDocument->domDocument = $processor->transformToDoc($this->domDocument); if (!$htmlDomDocument->domDocument) { throw new Dom\Exception('The XSL transformation has failed.'); } } else { throw new Dom\Exception('There is no XSL template to transform with.'); } try { return $htmlDomDocument->toString(false); } catch (\Exception $exception) { $this->logger->error($exception->getMessage()); throw new Dom\Exception("dom-transform-failed"); } }
/** * return xml translated by XSL * @param object $xml_object * @param string/object $xsl * @param array $params * @return string * @author Andy Bennett */ function xslt_return_translated($xml_object, $xsl, $params = array()) { /* create the processor and import the stylesheet */ $proc = new XsltProcessor(); // $proc->registerPhpFunctions(); if (!is_object($xsl)) { $xsl_url = $xsl; /* load the xml file and stylesheet as domdocuments */ $xsl = new DomDocument(); $xsl->load($xsl_url); } $xsl = $proc->importStylesheet($xsl); foreach ($params as $pk => $pv) { $proc->setParameter(null, $pk, $pv); } /* transform and output the xml document */ $newdom = $proc->transformToDoc($xml_object); $trans = $newdom->saveXML(); $trans = str_replace('<?xml version="1.0" standalone="yes"?>', '', $trans); $trans = str_replace('<?xml version="1.0"?>', '', $trans); $trans = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $trans); return html_entity_decode($trans); }
public function google() { $xsl_path = Kohana::find_file('xsl', 'google_sitemap', TRUE, 'xsl'); // load the xml file and stylesheet as domdocuments $xsl = new DomDocument(); $xsl->load($xsl_path); $inputdom = new DomDocument(); $inputdom->loadXML($this->sitemap_string); // create the processor and import the stylesheet $proc = new XsltProcessor(); $proc->importStyleSheet($xsl); $proc->setParameter('', 'siteurl', url::base()); // transform and output the xml document $newdom = $proc->transformToDoc($inputdom); $tmp = $newdom->saveXML(); $tmp = str_replace(' xmlns=""', '', $tmp); echo $tmp; }
function showCompound() { $dsid = 'COMPOUND'; $path = drupal_get_path('module', 'Fedora_Repository'); require_once drupal_get_path('module', 'Fedora_Repository') . '/ObjectHelper.php'; require_once drupal_get_path('module', 'Fedora_Repository') . '/CollectionClass.php'; $collectionHelper = new CollectionClass(); $xmlstr = $collectionHelper->getStream($this->pid, "COMPOUND"); html_entity_decode($xmlstr); if ($xmlstr == null || strlen($xmlstr) < 5) { return " "; } try { $proc = new XsltProcessor(); } catch (Exception $e) { drupal_set_message(t($e->getMessage()), 'error'); return " "; } $xsl = new DomDocument(); $xsl->load($path . '/mnpl/xsl/compound.xsl'); $input = new DomDocument(); $input->loadXML(trim($xmlstr)); $xsl = $proc->importStylesheet($xsl); $newdom = $proc->transformToDoc($input); $content = $newdom->saveXML(); // get parent pid and build link $pid = $this->pid; $itqlquery = 'select $object from <#ri> where <info:fedora/' . $pid . '><fedora-rels-ext:isPartOf> $object '; $relatedItems = $collectionHelper->getRelatedItems($this->pid, $itqlquery); $sxe = new SimpleXMLElement($relatedItems); $nmspace = $sxe->getNamespaces(true); $regspace = $sxe->registerXPathNamespace('ri', implode($nmspace)); // begin fractions $flabel = '<h4>Parent Specimen Record for This Compound</h4><p>'; $link = implode($sxe->xpath('//@uri')); $link = substr($link, 12); global $base_url; $plink .= '<a href =' . $base_url . '/fedora/repository/' . $link . '>Parent Specimen</a><br>'; if (user_access('edit fedora meta data')) { $editcomp = '<a href =' . $base_url . '/fedora/repository/editmetadata/' . $pid . '/' . $dsid . '>Edit This Compound</a><br>'; } else { $editcomp = ''; } // display other compounds for this parent $itqlQuery = 'select $object $title from <#ri> where $object <fedora-model:label> $title and $object <fedora-rels-ext:isPartOf> <info:fedora/' . $link . '> and $object <fedora-model:state> <info:fedora/fedora-system:def/model#Active> order by $title'; $relatedItems = $collectionHelper->getRelatedItems($this->pid, $itqlQuery); $sxe = new SimpleXMLElement($relatedItems); $nmspace = $sxe->getNamespaces(true); $regspace = $sxe->registerXPathNamespace('ri', implode($nmspace)); // begin display compounds global $base_url; $altcomp = '<h4> Other Compounds For Parent Sepcimen</h4><div>'; if (stristr(implode($sxe->xpath('//ri:title')), 'compound')) { foreach ($sxe->xpath('//@uri') as $link2) { if (strstr($link2, 'compound')) { $pidlink = substr($link2, 12); if ($pidlink != $pid) { $compound .= '<a href = "' . $base_url . '/fedora/repository/' . $pidlink . '">' . substr($link2, 30) . '</a><br>'; } } } } if ($compound == NULL) { $compound = "<div>No other Compounds present for this Specimen</div>"; } $collection_fieldset = array('#title' => t('MNPL Compound Record'), '#collapsible' => TRUE, '#collapsed' => FALSE, '#value' => $content . $editcomp . $flabel . $plink . $altcomp . $compound); return theme('fieldset', $collection_fieldset); }
/** * Gets all matching XML schema files and loads them into data models for class. * @return void */ protected function loadDataModels() { $ads = array(); // Get all matched files from schemaFilesets foreach ($this->schemaFilesets as $fs) { $ds = $fs->getDirectoryScanner($this->project); $srcDir = $fs->getDir($this->project); $dataModelFiles = $ds->getIncludedFiles(); $platform = $this->getGeneratorConfig()->getConfiguredPlatform(); // Make a transaction for each file foreach ($dataModelFiles as $dmFilename) { $this->log("Processing: " . $dmFilename); $xmlFile = new PhingFile($srcDir, $dmFilename); $dom = new DomDocument('1.0', 'UTF-8'); $dom->load($xmlFile->getAbsolutePath()); // normalize (or transform) the XML document using XSLT if ($this->xslFile) { $this->log("Transforming " . $xmlFile->getPath() . " using stylesheet " . $this->xslFile->getPath(), Project::MSG_VERBOSE); if (!class_exists('XSLTProcessor')) { $this->log("Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.", Project::MSG_ERR); } else { // modify schema to include any external schema's (and remove the external-schema nodes) $this->includeExternalSchemas($dom, $srcDir); // normalize the document using normalizer stylesheet $xsl = new XsltProcessor(); $xsl->importStyleSheet(DomDocument::load($this->xslFile->getAbsolutePath())); $transformed = $xsl->transformToDoc($dom); $newXmlFilename = substr($xmlFile->getName(), 0, strrpos($xmlFile->getName(), '.')) . '-transformed.xml'; // now overwrite previous vars to point to newly transformed file $xmlFile = new PhingFile($srcDir, $newXmlFilename); $transformed->save($xmlFile->getAbsolutePath()); $this->log("\t- Using new (post-transformation) XML file: " . $xmlFile->getPath(), Project::MSG_VERBOSE); $dom = new DomDocument('1.0', 'UTF-8'); $dom->load($xmlFile->getAbsolutePath()); } } // validate the XML document using XSD schema if ($this->validate && $this->xsdFile) { $this->log("Validating XML doc (" . $xmlFile->getPath() . ") using schema file " . $this->xsdFile->getPath(), Project::MSG_VERBOSE); if (!$dom->schemaValidate($this->xsdFile->getAbsolutePath())) { throw new EngineException("XML schema file (" . $xmlFile->getPath() . ") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $this->getLocation()); } } $xmlParser = new XmlToAppData($platform, $this->getTargetPackage(), $this->dbEncoding); $ad = $xmlParser->parseFile($xmlFile->getAbsolutePath()); $ad->setName($dmFilename); // <-- Important: use the original name, not the -transformed name. $ads[] = $ad; } } if (empty($ads)) { throw new BuildException("No schema files were found (matching your schema fileset definition)."); } if (!$this->packageObjectModel) { $this->dataModels = $ads; $this->databaseNames = array(); // doesn't seem to be used anywhere $this->dataModelDbMap = array(); // Different datamodels may state the same database // names, we just want the unique names of databases. foreach ($this->dataModels as $dm) { $database = $dm->getDatabase(); $this->dataModelDbMap[$dm->getName()] = $database->getName(); $this->databaseNames[$database->getName()] = $database->getName(); // making list of *unique* dbnames. } } else { $this->joinDatamodels($ads); $this->dataModels[0]->getDatabases(); // calls doFinalInitialization() } $this->dataModelsLoaded = true; }
/** * This looks deprecated... * * @param $tag Either a tag name or a tag id. * @returns folksPageData */ public function public_tag_resource_list($tag) { /* $r is a folksoPageData object*/ $r = $this->resource_list($tag); if ($r->is_valid()) { $taglist_xml = new DOMDocument(); $taglist_xml->loadXML($r->xml); $r->title = $this->getTitle($taglist_xml); $xsl = new DOMDocument(); $xsl->load($this->loc->xsl_dir . "public_resourcelist.xsl"); $proc = new XsltProcessor(); $xsl = $proc->importStylesheet($xsl); $taglist = $proc->transformToDoc($taglist_xml); $r->html = $taglist->saveXML(); } elseif ($r->status == 204) { $r->html = '<p>Aucune ressource n\'est associée à ce tag.</p>'; } elseif ($r->status == 404) { $r->html = '<p>Tag non trouvé.</p>'; $r->title = "Tag non trouvé."; } else { $r->html = '<p>Erreur. Excusez-nous.</p>'; $r->title = 'Erreur de tag'; } return $r; }