コード例 #1
0
ファイル: Xslt.php プロジェクト: volux/dom
 /**
  * @return \XSLTProcessor
  */
 protected function processor()
 {
     if (!$this->processor) {
         $this->processor = new \XSLTProcessor();
         if ('php' == $this->root()->attr('exclude-result-prefixes')) {
             $this->processor->registerPHPFunctions();
         }
         $this->processor->importStyleSheet($this);
     }
     return $this->processor;
 }
コード例 #2
0
ファイル: Pigment.php プロジェクト: JhunCabas/pigment
 public function render()
 {
     eval("\$this->content = \$this->parse{$this->requesttype}();");
     $this->checkFor404();
     if ($this->format === 'object') {
         $this->printObject($this);
     } else {
         ob_start();
         $file = $this->root . '/lib/xml/pigment.xml';
         echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
         if (is_file($file)) {
             include $file;
         }
         $xml = ob_get_contents();
         ob_end_clean();
     }
     if ($this->format === 'xml') {
         $type = $this->getHeader('xml');
         header("Content-Type: {$type}");
         echo $xml;
     } else {
         if ($this->format === 'default') {
             if ($this->requesttype === 'Content') {
                 $type = $this->getHeader('xml');
                 $file = "{$this->root}/lib/xsl/{$this->version}.xsl";
                 if (!is_file($file)) {
                     $file = "{$this->root}/lib/xsl/default.xsl";
                 }
                 $xmldoc = DOMDocument::loadXML($xml);
                 $xsldoc = new DomDocument();
                 $xsldoc->load($file);
                 $proc = new XSLTProcessor();
                 $proc->registerPHPFunctions();
                 $proc->importStyleSheet($xsldoc);
                 $output = $proc->transformToXML($xmldoc);
                 $selector = '</html>';
                 if (strstr($output, $selector)) {
                     $exp = explode($selector, $output);
                     $uri = $_SERVER['REQUEST_URI'];
                     $delim = strstr($uri, '?') ? '&' : '?';
                     $track = '<object type="text/html" width="1" height="1" data="' . $uri . $delim . 'log"></object>';
                     $output = implode($track . '</html>', $exp);
                 }
             } else {
                 $output = $this->content;
             }
         }
     }
     if (isset($output)) {
         if (isset($this->is404) && $this->is404 === true) {
             header(' ', true, 404);
         } else {
             header("Content-Type: {$this->header}");
         }
         echo $output;
         if ($this->preferences['cache'] && !isset($this->querystring) && !isset($this->is404)) {
             $this->cache($output);
         }
     }
 }
コード例 #3
0
ファイル: Html5.php プロジェクト: CG77/ezpublish-kernel
 /**
  * Returns the XSLTProcessor to use to transform internal XML to HTML5.
  *
  * @return \XSLTProcessor
  */
 protected function getXSLTProcessor()
 {
     if (isset($this->xsltProcessor)) {
         return $this->xsltProcessor;
     }
     $xslDoc = new DOMDocument();
     $xslDoc->load($this->stylesheet);
     // Now loading custom xsl stylesheets dynamically.
     // According to XSL spec, each <xsl:import> tag MUST be loaded BEFORE any other element.
     $insertBeforeEl = $xslDoc->documentElement->firstChild;
     foreach ($this->getSortedCustomStylesheets() as $stylesheet) {
         if (!file_exists($stylesheet)) {
             throw new RuntimeException("Cannot find XSL stylesheet for XMLText rendering: {$stylesheet}");
         }
         $newEl = $xslDoc->createElement('xsl:import');
         $hrefAttr = $xslDoc->createAttribute('href');
         $hrefAttr->value = $stylesheet;
         $newEl->appendChild($hrefAttr);
         $xslDoc->documentElement->insertBefore($newEl, $insertBeforeEl);
     }
     // Now reload XSL DOM to "refresh" it.
     $xslDoc->loadXML($xslDoc->saveXML());
     $this->xsltProcessor = new XSLTProcessor();
     $this->xsltProcessor->importStyleSheet($xslDoc);
     $this->xsltProcessor->registerPHPFunctions();
     return $this->xsltProcessor;
 }
コード例 #4
0
 public function doAction(Zend_Controller_Action $action)
 {
     $entryId = $action->getRequest()->getParam('entry-id');
     $xslt = $action->getRequest()->getParam('xslt');
     $this->client = Infra_ClientHelper::getClient();
     $xml = $this->client->media->getMrss($entryId);
     $xslParams = array();
     $xslParams['entryDistributionId'] = '';
     $xslParams['distributionProfileId'] = '';
     ob_start();
     $xmlDoc = new DOMDocument();
     $xmlDoc->loadXML($xml);
     $xsltDoc = new DOMDocument();
     $xsltDoc->loadXML($xslt);
     $xslt = new XSLTProcessor();
     $xslt->registerPHPFunctions();
     // it is safe to register all php fuctions here
     $xslt->setParameter('', $xslParams);
     $xslt->importStyleSheet($xsltDoc);
     $ob = ob_get_clean();
     ob_end_clean();
     if ($ob) {
         $action->getHelper('json')->direct(array('error' => $ob));
     }
     $obj = array('result' => $xslt->transformToXml($xmlDoc));
     $action->getHelper('json')->direct($obj);
 }
コード例 #5
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $environment = $input->getOption('env');
     try {
         $transformer = $input->getOption('xsl');
         $xsl = new \DOMDocument();
         $xsl->load($transformer);
         $xslt = new \XSLTProcessor();
         $xslt->registerPHPFunctions();
         $xslt->importStylesheet($xsl);
         $files = $input->getOption('file');
         foreach ($files as $file) {
             $output->writeln('Transforming file: ' . $file);
             $doc = new \DOMDocument();
             $doc->load($file);
             $xml = $xslt->transformToXml($doc);
             $xmlobj = new \SimpleXMLElement($xml);
             $xmlobj->asXML('output.xml');
         }
     } catch (\Exception $ex) {
         $exception = new OutputFormatterStyle('red');
         $output->getFormatter()->setStyle('exception', $exception);
         $output->writeln("\n\n");
         $output->writeln('<exception>[Exception in: ' . get_class($this) . ']</exception>');
         $output->writeln('<exception>Exception: ' . get_class($ex) . ' with message: ' . $ex->getMessage() . '</exception>');
         $output->writeln('<exception>Stack Trace:</exception>');
         $output->writeln('<exception>' . $ex->getTraceAsString() . '</exception>');
         exit(1);
     }
     exit(0);
 }
コード例 #6
0
ファイル: BasicView.php プロジェクト: backstageel/neatReports
 /**
  * Initializes this Class' XSLTProcessor, if not yet instantiated.
  */
 public function __construct()
 {
     if (null === self::$_xsltProcessor) {
         self::$_xsltProcessor = new XSLTProcessor();
         self::$_xsltProcessor->registerPHPFunctions();
     }
 }
コード例 #7
0
ファイル: xsl.php プロジェクト: BGCX262/zwf-svn-to-git
function xsl_transform_feed($feedUrl, $xslPath)
{
    $doc = new DOMDocument();
    $xsl = new XSLTProcessor();
    $doc->load(parse_path($xslPath));
    $xsl->importStyleSheet($doc);
    $doc->loadXML(file_get_contents(parse_path($feedUrl)));
    $xsl->registerPHPFunctions(array('xsl_counter'));
    return $xsl->transformToXML($doc);
}
コード例 #8
0
 public function process()
 {
     $xslt = new XSLTProcessor();
     $xslt->registerPHPFunctions();
     $baseExt = 'Base';
     $xslt->setParameter('', 'ext', $baseExt);
     $xslt->importStylesheet($this->stylesheet);
     $baseTypes = $xslt->transformToXml($this->schema);
     $fp = fopen('BaseTypes.php', 'w');
     fwrite($fp, $baseTypes);
     fclose($fp);
 }
コード例 #9
0
 /**
  * Converts the given XML tree and the given XSL file to a (HTML) file, with respect to the given XSL parameters.
  * The given XMLTree parameter may be of the SimpleXMLElement or the DOMDocument type, however, the latter is the fastest.
  * The generated output may be considered to be formatted properly.
  * @param mixed The XML Tree as a SimpleXMLElement or a DOMDocument
  * @param mixed The fullpath to the XSL file, or an instanced \SimpleXMLElement XSL tree
  * @param \System\Collection\Map The map with the parameters, or null for no parameters or default
  */
 public final function render()
 {
     $args = func_get_args();
     if (count($args) != 3) {
         throw new \InvalidArgumentException('Invalid amount of arguments given.');
     }
     list($xmlTree, $xslFile, $parameters) = $args;
     $processor = new \XSLTProcessor();
     //register the php functions
     if (count(self::$registeredPHPFunctions) > 0) {
         $processor->registerPHPFunctions(self::$registeredPHPFunctions);
     }
     //load the xsl file intro a dom
     $xsl = new \DOMDocument();
     if ($xslFile instanceof \SimpleXMLElement) {
         $xsl->loadXML($xslFile->asXML());
     } else {
         if (!file_exists($xslFile)) {
             throw new \System\Error\Exception\FileNotFoundException('XSL File: ' . $xslFile . ' cannot be found');
         }
         $xsl->load($xslFile);
     }
     //attach the xsl dom to the processor
     $processor->importStylesheet($xsl);
     //when we run as a local debug system, we output the profiling information
     if (defined('DEBUG')) {
         $processor->setProfiling(PATH_LOGS . 'XSLTRenderProfiling.txt');
     }
     $dom = new \DOMDocument();
     switch (true) {
         case $xmlTree instanceof \SimpleXMLElement:
             //we need to convert to a domdocument
             $dom = \System\XML\XML::convertSimpleXMLElementToDOMDocument($xmlTree);
             break;
         case $xmlTree instanceof \DOMDocument:
             //no conversion needed
             break;
         default:
             throw new \InvalidArgumentException('Given XML tree is of non supported tree type: ' . get_class($xmlTree));
     }
     $this->preprocessParameters($parameters);
     //we do not need any namespaces
     $processor->setParameter('', $parameters->getArrayCopy());
     $output = $processor->transformToXML($dom);
     if (!$output) {
         throw new \Exception('Could not transform the given XML and XSL to a valid HTML page');
     }
     if (MINIFY_ENABLE) {
         $output = \System\Web\Minify\HTML\Minify::minify($output);
     }
     $this->addToBuffer($output);
 }
コード例 #10
0
 public static function cbd_run()
 {
     $proc = new XSLTProcessor();
     $proc->importStyleSheet(DOMDocument::load('xsl/cbd.xsl'));
     global $registerPHPFunctions;
     if ($registerPHPFunctions) {
         $proc->registerPHPFunctions($registerPHPFunctions);
     }
     $cbd_xml = $proc->transformToDoc(DOMDocument::load('db://?all-data'));
     $xml = simplexml_import_dom($cbd_xml) or die('import failed');
     global $cbd_host, $cbd_db, $cbd_user, $cbd_pwd;
     $conn_pg = pg_connect("host='{$cbd_host}' dbname={$cbd_db} user={$cbd_user} password={$cbd_pwd}") or die("error on connection to {$cbd_db}");
     Importer::_run($xml, $conn_pg);
 }
コード例 #11
0
ファイル: AtomParser.php プロジェクト: kba/rssscrpr
 public function parse(Session $session)
 {
     $chan = new DOMDocument();
     $chan->loadXML(mb_convert_encoding($session->bytes, 'HTML-ENTITIES', 'UTF-8'));
     $sheet = new DOMDocument();
     $sheet->load('data/atom2rss/atom2rss.xsl');
     /* use stylesheet from this page */
     $processor = new XSLTProcessor();
     $processor->registerPHPFunctions();
     $processor->importStylesheet($sheet);
     $session->dom = $processor->transformToDoc($chan);
     $session->xpath = new DOMXPath($session->dom);
     $session->dom->save('/tmp/atom.xml');
     // error_log("RESULT: " . $session->dom->saveXML());
 }
コード例 #12
0
ファイル: SheetParser.php プロジェクト: Comandeer/overdocs
 public function parseContent()
 {
     $xml = new \DOMDocument();
     $xml->load($this->filename);
     $xsl = new \DOMDocument();
     $xsl->load('./sheet.xsl');
     $proc = new \XSLTProcessor();
     $proc->importStyleSheet($xsl);
     $proc->setParameter('', 'base_url', $this->config['base_url']);
     $proc->setParameter('', 'images_url', $this->config['base_url'] . '/images/sheets/' . $this->id . '/');
     $proc->registerPHPFunctions(['OverDocs\\SheetParser::canonicalize', 'OverDocs\\SheetParser::parseAbbreviation']);
     $output = $proc->transformToXML($xml);
     if (!$this->debug) {
         $output = $this->minify($output);
     }
     return $output;
 }
コード例 #13
0
 /**
  * @param array $ticket
  */
 public function convertTicket($ticket)
 {
     $processor = new \XSLTProcessor();
     $xmlSerializer = new XMLSerializer();
     $serializedTicket = $xmlSerializer->serialize($ticket);
     $dom = new \DOMDocument();
     $dom->loadXML($serializedTicket);
     $processor->registerPHPFunctions('config');
     try {
         $stylesheet = new \DOMDocument();
         $stylesheet->load(config('printer.XSLTemplatePath'));
         $processor->importStylesheet($stylesheet);
         $doc = $processor->transformToDoc($dom);
         $doc->save(config('printer.foOutputPath'));
     } catch (\Exception $e) {
         Log::error($e->getMessage());
     }
 }
コード例 #14
0
ファイル: View.php プロジェクト: joel-cass/structure-cms
 public function render(Page $page)
 {
     $viewPath = $this->path;
     if (strToLower(substr($viewPath, strlen($viewPath) - 5, 5)) == ".xslt") {
         // file is XSLT
         $objXML = $page->xml;
         $objXSL = new DomDocument();
         $objXSL->load(getViewPath($viewPath));
         $objProc = new XSLTProcessor();
         $objProc->registerPHPFunctions();
         $objProc->importStyleSheet($objXSL);
         echo $objProc->transformToXML($objXML);
     } else {
         // FILE IS PHP
         $PAGE = $page;
         include getViewPath($this->path);
     }
 }
コード例 #15
0
ファイル: restapi_repo.php プロジェクト: IASA-GR/appdb-core
 public static function transform($data, $type)
 {
     $xslt = APPLICATION_PATH . "/configs/repository/0.1/xslt/" . $type;
     $xslt = $xslt . ".xsl";
     if (file_exists($xslt)) {
         $xsl = new DOMDocument();
         $xsl->load($xslt);
         $xml = new DOMDocument();
         $xml->loadXML($data, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $data = $proc->transformToXml($xml);
         $data = str_replace('<?xml version="1.0"?' . '>', '', $data);
     } else {
         error_log('Cannot find ' . $xslt);
     }
     return $data;
 }
コード例 #16
0
ファイル: Record.php プロジェクト: bharatm/NDL-VuFind
 /**
  * Process incoming parameters and display the page.
  *
  * @return void
  * @access public
  */
 public function launch()
 {
     global $configArray;
     header('Content-Type: text/html; charset=ISO-8859-1');
     echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\">\n";
     // Load information on the requested record:
     // Setup Search Engine Connection
     $db = ConnectionManager::connectToIndex();
     // Retrieve the record from the index
     if (!($record = $db->getRecord($_REQUEST['id']))) {
         PEAR::raiseError(new PEAR_Error('Record Does Not Exist'));
     }
     if (strlen($record['fullrecord'])) {
         $xml = $record['fullrecord'];
         $result = simplexml_load_string($xml);
     }
     $url = isset($result->url) ? trim($result->url) : false;
     if (empty($url)) {
         PEAR::raiseError(new PEAR_Error('Not a VuDL Record'));
     }
     // Set up the XSLT processor:
     $xslt = new XSLTProcessor();
     // Register all non-private methods other than "launch" for access via XSLT:
     $class = get_class($this);
     $methods = get_class_methods($class);
     foreach ($methods as $method) {
         if ($method != 'launch' && substr($method, 0, 1) != '_') {
             $xslt->registerPHPFunctions($class . '::' . $method);
         }
     }
     $xsl = new DOMDocument();
     $xsl->load(dirname(__FILE__) . '/xsl/transform.xsl');
     $xslt->importStylesheet($xsl);
     $xslt->setParameter('', 'path', $configArray['Site']['path']);
     $sXml = file_get_contents($url);
     $XML = new DOMDocument();
     $XML->loadXML($sXml);
     $html = $xslt->transformToXML($XML);
     $html = str_replace('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">', '', $html);
     $html = preg_replace('/<html[^>]*>/', '<html>', $html);
     echo $html;
 }
コード例 #17
0
ファイル: ConvertToXsd.php プロジェクト: goetas/doctrine2xsd
 public function convert($destination, $destinationNs, array $nsMap, array $allowMap, $ext = 'xml')
 {
     if (is_dir($destination)) {
         throw new \RuntimeException("Destination could not be a directory.");
     }
     if (!$nsMap) {
         throw new \RuntimeException(__CLASS__ . " requires at least one ns-map (for {$destinationNs} namespace).");
     }
     $files = array();
     foreach ($nsMap as $value) {
         $dir = rtrim($value["dir"], "\\//");
         TypeMapper::addNamespace($value["phpNs"], $value["xmlNs"]);
         $files = array_merge($files, glob("{$dir}/*.{$ext}"));
     }
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $root = $dom->createElement('root');
     $dom->appendChild($root);
     foreach ($files as $file) {
         $mapping = new \DOMDocument('1.0', 'UTF-8');
         $mapping->load($file);
         $newnode = $dom->importNode($mapping->documentElement, true);
         $root->appendChild($newnode);
     }
     $this->handleAllowMap($allowMap, $dom);
     $xsd = new \DOMDocument('1.0', 'UTF-8');
     $xsd->load(__DIR__ . '/../Resources/xsd/convert.xsl');
     $processor = new \XSLTProcessor();
     $processor->registerPHPFunctions();
     $processor->setParameter('', 'targetNs', $destinationNs);
     $processor->importStylesheet($xsd);
     $newDom = $processor->transformToDoc($dom);
     $this->fixXsd($newDom, $destinationNs);
     $ret = $newDom->save($destination);
     if ($ret > 0) {
         return true;
     } else {
         return false;
     }
 }
コード例 #18
0
ファイル: XSLTService.php プロジェクト: tomaka17/niysu
 /**
  * Transforms XML using XSLT.
  *
  * The $xml parameter can be either raw XML or an array that can be passed to OutputXMLService::toString.
  *
  * @param string 	$template 	Name of the file containing the XSLT template
  * @param mixed 	$xml 		The XML data to transform
  * @throws RuntimeException In case of a problem when parsing the XML, the XSLT, or during the transformation
  */
 public function transform($template, $xml)
 {
     if (is_array($xml)) {
         $xmldoc = new \DOMDocument();
         $xmldoc->encoding = 'utf-8';
         $xmldoc->recover = true;
         $data = $this->outputXMLService->toString($xml);
         if (!$xmldoc->loadXML($data)) {
             throw new \RuntimeException('Unable to parse XML data: ' . $data);
         }
     } else {
         if (is_string($xml)) {
             $xmldoc = new \DOMDocument();
             $xmldoc->encoding = 'utf-8';
             $xmldoc->recover = true;
             if (!$xmldoc->loadXML($xml)) {
                 throw new \RuntimeException('Unable to parse XML file: ' . $xml);
             }
         } else {
             throw new \LogicException('Wrong format for XML');
         }
     }
     $xslDoc = new \DOMDocument();
     $xslDoc->load($template);
     if (!$xslDoc) {
         throw new \RuntimeException('Unable to load XSLT template: ' . $template);
     }
     $xsl = new \XSLTProcessor();
     $xsl->registerPHPFunctions();
     $xsl->importStyleSheet($xslDoc);
     $output = $xsl->transformToXML($xmldoc);
     if (!$output) {
         throw new \RuntimeException('Error during XSLT transformation');
     }
     return $output;
 }
コード例 #19
0
 public function testAmpersandEscaped()
 {
     $xslDoc = new DOMDocument();
     $xslDoc->load('Stubs/ampersand-escaped.xsl');
     $xmlDoc = new DOMDocument();
     $xmlDoc->load('Stubs/collection.xml');
     $native = new \XSLTProcessor();
     $native->importStylesheet($xslDoc);
     $native->registerPHPFunctions();
     $nativeResult = trim($native->transformToXML($xmlDoc));
     $transpiler = new XsltProcessor();
     $transpiler->importStylesheet($xslDoc);
     $transpiler->registerPHPFunctions();
     $transpilerResult = trim($transpiler->transformToXML($xmlDoc));
     $this->assertEquals($nativeResult, $transpilerResult);
 }
コード例 #20
0
 /**
  * Transform Xml file with conversion profile xsl
  * If xsl is not found, original Xml returned
  * @param string $filePath the original xml that was taken from partner file path
  * @return string - transformed Xml
  */
 protected function xslTransform($filePath)
 {
     $xdoc = file_get_contents($filePath);
     if (is_null($xdoc) || is_null($this->conversionProfileXsl)) {
         return $xdoc;
     }
     libxml_clear_errors();
     $xml = new KDOMDocument();
     if (!$xml->loadXML($xdoc)) {
         KalturaLog::debug("Could not load xml");
         $errorMessage = kXml::getLibXmlErrorDescription($xdoc);
         throw new KalturaBatchException("Could not load xml [{$this->job->id}], {$errorMessage}", KalturaBatchJobAppErrors::BULK_VALIDATION_FAILED);
     }
     libxml_clear_errors();
     $proc = new XSLTProcessor();
     $proc->registerPHPFunctions(kXml::getXslEnabledPhpFunctions());
     $xsl = new KDOMDocument();
     if (!$xsl->loadXML($this->conversionProfileXsl)) {
         KalturaLog::debug("Could not load xsl" . $this->conversionProfileXsl);
         $errorMessage = kXml::getLibXmlErrorDescription($this->conversionProfileXsl);
         throw new KalturaBatchException("Could not load xsl [{$this->job->id}], {$errorMessage}", KalturaBatchJobAppErrors::BULK_VALIDATION_FAILED);
     }
     $proc->importStyleSheet($xsl);
     libxml_clear_errors();
     $transformedXml = $proc->transformToXML($xml);
     if (!$transformedXml) {
         KalturaLog::debug("Could not transform xml" . $this->conversionProfileXsl);
         $errorMessage = kXml::getLibXmlErrorDescription($this->conversionProfileXsl);
         throw new KalturaBatchException("Could not transform xml [{$this->job->id}], {$errorMessage}", KalturaBatchJobAppErrors::BULK_VALIDATION_FAILED);
     }
     return $transformedXml;
 }
コード例 #21
0
 /**
  * Transform the wsdl document using XSL.
  *
  * The result is a DOMDocument containing transformed WSDL elements for
  * generating class files.
  *
  * @param DOMNode $dom the dom document
  * @param string $xslFilePath the file path of the xsl to apply
  * @param string|null $saveOutputTo the output file to save the result to
  */
 protected function transformWsdl($xslFilePath, $saveOutputTo = null)
 {
     $transformedDom = null;
     $xsl = new XSLTProcessor();
     $xslDom = new DOMDocument();
     try {
         $xslDom->load($xslFilePath);
         $xsl->registerPHPFunctions();
         $xsl->importStyleSheet($xslDom);
         $transformedDom = $xsl->transformToDoc($this->dom);
         if ($saveOutputTo) {
             $transformedDom->formatOutput = true;
             $transformedDom->save($saveOutputTo);
         }
     } catch (Exception $e) {
         throw new WSDLInterpreterException(sprintf("Error interpreting WSDL " . "document (%s)", $e->getMessage()));
     }
     $this->dom = $transformedDom;
 }
コード例 #22
0
 /**
  * Use PHP5's DOMDocument and XSLTProcessor to do the transformation
  * @param $xml mixed
  * @param $xmlType integer
  * @param $xsl mixed
  * @param $xslType integer
  * @param $resultType integer
  * @return mixed return type depends on the $returnType parameter and can be
  *  DOMDocument or string. Returns boolean "false" on error.
  */
 function &_transformPHP5(&$xml, $xmlType, &$xsl, $xslType, $resultType)
 {
     // Prepare the XML DOM
     if ($xmlType == XSL_TRANSFORMER_DOCTYPE_DOM) {
         // We already have a DOM document, no need to create one
         assert(is_a($xml, 'DOMDocument'));
         $xmlDOM =& $xml;
     } else {
         // Instantiate and configure the XML DOM document
         $xmlDOM = new DOMDocument('1.0', XSLT_PROCESSOR_ENCODING);
         // These are required for external entity resolution (eg. &nbsp;), but can slow processing
         // substantially (20-100x), often up to 60s.  This can be solved by use of local catalogs, ie.
         // putenv("XML_CATALOG_FILES=/path/to/catalog.ent");
         //
         // see:  http://www.whump.com/moreLikeThis/link/03815
         $xmlDOM->recover = true;
         $xmlDOM->substituteEntities = true;
         $xmlDOM->resolveExternals = true;
         // Load the XML based on its type
         switch ($xmlType) {
             case XSL_TRANSFORMER_DOCTYPE_FILE:
                 $xmlDOM->load($xml);
                 break;
             case XSL_TRANSFORMER_DOCTYPE_STRING:
                 $xmlDOM->loadXML($xml);
                 break;
             default:
                 assert(false);
         }
     }
     // Prepare the XSL DOM
     if ($xslType == XSL_TRANSFORMER_DOCTYPE_DOM) {
         // We already have a DOM document, no need to create one
         assert(is_a($xsl, 'DOMDocument'));
         $xslDOM =& $xsl;
     } else {
         // Instantiate the XSL DOM document
         $xslDOM = new DOMDocument('1.0', XSLT_PROCESSOR_ENCODING);
         // Load the XSL based on its type
         switch ($xslType) {
             case XSL_TRANSFORMER_DOCTYPE_FILE:
                 $xslDOM->load($xsl);
                 break;
             case XSL_TRANSFORMER_DOCTYPE_STRING:
                 $xslDOM->loadXML($xsl);
                 break;
             default:
                 assert(false);
         }
     }
     // Create and configure the XSL processor
     $processor = new XSLTProcessor();
     // Register PHP functions if requested.
     // NB: This can open potential security issues; see FAQ/README
     if ($this->registerPHPFunctions) {
         $processor->registerPHPFunctions($this->registerPHPFunctions);
     }
     // Set XSL parameters (if any)
     if (is_array($this->parameters)) {
         foreach ($this->parameters as $param => $value) {
             $processor->setParameter(null, $param, $value);
         }
     }
     //  Import the style sheet
     $processor->importStylesheet($xslDOM);
     // Process depending on the requested result type
     switch ($resultType) {
         case XSL_TRANSFORMER_DOCTYPE_STRING:
             $resultXML = $processor->transformToXML($xmlDOM);
             return $resultXML;
         case XSL_TRANSFORMER_DOCTYPE_DOM:
             $resultDOM = $processor->transformToDoc($xmlDOM);
             return $resultDOM;
         default:
             assert(false);
     }
 }
 public function transformXslForEntry(EntryDistribution $entryDistribution, $xsl, $xslParams = array())
 {
     $xslParams['entryDistributionId'] = $entryDistribution->getId();
     $xslParams['distributionProfileId'] = $entryDistribution->getDistributionProfileId();
     $mrssDoc = $this->getEntryMrssDoc($entryDistribution);
     $xslDoc = new DOMDocument();
     $xslDoc->loadXML($xsl);
     $xslt = new XSLTProcessor();
     $xslt->registerPHPFunctions();
     // it is safe to register all php fuctions here
     $xslt->setParameter('', $xslParams);
     $xslt->importStyleSheet($xslDoc);
     return $xslt->transformToXml($mrssDoc);
 }
コード例 #24
0
ファイル: import-xsl.php プロジェクト: bharatm/NDL-VuFind
/**
 * Support function -- initialize an XSLT processor using settings from the
 * user-specified properties file.
 *
 * @param array $options Parsed contents of properties file.
 *
 * @return object        XSLT processor.
 */
function initializeXSL($options)
{
    global $importPath;
    // Prepare an XSLT processor and pass it some variables
    $xsl = new XSLTProcessor();
    // Register PHP functions, if specified:
    if (isset($options['General']['php_function'])) {
        $functions = is_array($options['General']['php_function']) ? $options['General']['php_function'] : array($options['General']['php_function']);
        foreach ($functions as $function) {
            $xsl->registerPHPFunctions($function);
        }
    }
    // Register custom classes, if specified:
    if (isset($options['General']['custom_class'])) {
        $classes = is_array($options['General']['custom_class']) ? $options['General']['custom_class'] : array($options['General']['custom_class']);
        foreach ($classes as $class) {
            // Find the file containing the class; if necessary, be forgiving
            // about filename case.
            $fullPath = $importPath . '/xsl/' . $class . '.php';
            if (!file_exists($fullPath)) {
                $fullPath = $importPath . '/xsl/' . strtolower($class) . '.php';
            }
            include_once $fullPath;
            $methods = get_class_methods($class);
            foreach ($methods as $method) {
                $xsl->registerPHPFunctions($class . '::' . $method);
            }
        }
    }
    // Load parameters, if provided:
    if (isset($options['Parameters'])) {
        $xsl->setParameter('', $options['Parameters']);
    }
    return $xsl;
}
コード例 #25
0
 /**
  * @param string $results
  * @param KalturaGenericDistributionProviderParser $resultParserType
  * @param string $resultParseData
  * @return array of parsed values
  */
 protected function parseResults($results, $resultParserType, $resultParseData)
 {
     switch ($resultParserType) {
         case KalturaGenericDistributionProviderParser::XSL:
             $xml = new DOMDocument();
             if (!$xml->loadXML($results)) {
                 return false;
             }
             $xsl = new DOMDocument();
             $xsl->loadXML($resultParseData);
             $proc = new XSLTProcessor();
             $proc->registerPHPFunctions(kXml::getXslEnabledPhpFunctions());
             $proc->importStyleSheet($xsl);
             $data = $proc->transformToDoc($xml);
             if (!$data) {
                 return false;
             }
             return explode(',', $data);
         case KalturaGenericDistributionProviderParser::XPATH:
             $xml = new DOMDocument();
             if (!$xml->loadXML($results)) {
                 return false;
             }
             $xpath = new DOMXPath($xml);
             $elements = $xpath->query($resultParseData);
             if (is_null($elements)) {
                 return false;
             }
             $matches = array();
             foreach ($elements as $element) {
                 $matches[] = $element->textContent;
             }
             return $matches;
         case KalturaGenericDistributionProviderParser::REGEX:
             $matches = array();
             if (!preg_match("/{$resultParseData}/", $results, $matches)) {
                 return false;
             }
             return array_shift($matches);
         default:
             return false;
     }
 }
コード例 #26
0
ファイル: Xsl.php プロジェクト: xiaoguizhidao/devfashion
 public function convertData($exportArray)
 {
     if (!@class_exists('XSLTProcessor')) {
         Mage::throwException(Mage::helper('xtento_orderexport')->__('The XSLTProcessor class could not be found. This means your PHP installation is missing XSL features. You cannot export output formats using XSL Templates without the PHP XSL extension. Please get in touch with your hoster or server administrator to add XSL to your PHP configuration.'));
     }
     // Some libxml settings, constants
     $libxmlConstants = null;
     if (defined('LIBXML_PARSEHUGE')) {
         $libxmlConstants = LIBXML_PARSEHUGE;
     }
     $useInternalXmlErrors = libxml_use_internal_errors(true);
     if (function_exists('libxml_disable_entity_loader')) {
         #$loadXmlEntities = libxml_disable_entity_loader(true);
     }
     libxml_clear_errors();
     $outputArray = array();
     // Should the ampersand character etc. be encoded?
     $escapeSpecialChars = false;
     if (preg_match('/method="(xml|html)"/', $this->getProfile()->getXslTemplate())) {
         $escapeSpecialChars = true;
     }
     // Convert to XML first
     $convertedData = Mage::getModel('xtento_orderexport/output_xml', array('profile' => $this->getProfile(), 'escape_special_chars' => $escapeSpecialChars))->convertData($exportArray);
     // Get "first" file from returned data.
     $convertedXml = array_pop($convertedData);
     // If there are problems with bad/destroyed encodings in the DB:
     // $convertedXml = utf8_encode(utf8_decode($convertedXml));
     $xmlDoc = new DOMDocument();
     if (!$xmlDoc->loadXML($convertedXml, $libxmlConstants)) {
         $this->_throwXmlException(Mage::helper('xtento_orderexport')->__("Could not load internally processed XML. Bad data maybe?"));
     }
     // Load different file templates
     $outputFormatMarkup = $this->getProfile()->getXslTemplate();
     if (empty($outputFormatMarkup)) {
         Mage::throwException(Mage::helper('xtento_orderexport')->__('Error: No XSL Template has been set up for this export profile. Please open the export profile and set up your XSL Template in the "Output Format" tab.'));
     }
     try {
         $outputFormatXml = new SimpleXMLElement($outputFormatMarkup, null, strpos($outputFormatMarkup, '<') === false);
     } catch (Exception $e) {
         $this->_throwXmlException(Mage::helper('xtento_orderexport')->__("Please repair the XSL Template of this profile. You need to have a valid XSL Template in order to export orders. Could not load XSL Template:"));
     }
     $outputFormats = $outputFormatXml->xpath('//files/file');
     if (empty($outputFormats)) {
         Mage::throwException(Mage::helper('xtento_orderexport')->__('No <files><file></file></files> markup found in XSL Template. Please repair your XSL Template.'));
     }
     // Loop through each <file> node
     foreach ($outputFormats as $outputFormat) {
         $fileAttributes = $outputFormat->attributes();
         $filename = $this->_replaceFilenameVariables(current($fileAttributes->filename), $exportArray);
         $fileType = @current($fileAttributes->type);
         // Currently supported: xsl (default), invoice_pdf, packingslip_pdf
         if (!$fileType || empty($fileType) || $fileType == 'xsl') {
             $charsetEncoding = @current($fileAttributes->encoding);
             $searchCharacters = @current($fileAttributes->search);
             $replaceCharacters = @current($fileAttributes->replace);
             $quoteHandling = @current($fileAttributes->quotes);
             $xslTemplate = current($outputFormat->xpath('*'))->asXML();
             $xslTemplate = $this->_preparseXslTemplate($xslTemplate);
             // XSL Template
             $xslTemplateObj = new XSLTProcessor();
             $xslTemplateObj->registerPHPFunctions();
             // Add some parameters accessible as $variables in the XSL Template (example: <xsl:value-of select="$exportid"/>)
             $this->_addVariablesToXSLT($xslTemplateObj, $exportArray, $xslTemplate);
             // Import stylesheet
             /* Alternative DOMDocument version for versions that don't like SimpleXMLElements in importStylesheet */
             /*
             $domDocument = new DOMDocument();
             $domDocument->loadXML($xslTemplate);
             $xslTemplateObj->importStylesheet($domDocument);
             */
             $xslTemplateObj->importStylesheet(new SimpleXMLElement($xslTemplate));
             if (libxml_get_last_error() !== FALSE) {
                 $this->_throwXmlException(Mage::helper('xtento_orderexport')->__("Please repair the XSL Template of this profile. There was a problem processing the XSL Template:"));
             }
             $adjustedXml = false;
             // Replace certain characters
             if (!empty($searchCharacters)) {
                 $this->_searchCharacters = str_split(str_replace(array('quote'), array('"'), $searchCharacters));
                 if (in_array('"', $this->_searchCharacters)) {
                     $replacePosition = array_search('"', $this->_searchCharacters);
                     if ($replacePosition !== false) {
                         $this->_searchCharacters[$replacePosition] = '&quot;';
                     }
                 }
                 $this->_replaceCharacters = str_split($replaceCharacters);
                 $adjustedXml = preg_replace_callback('/<(.*)>(.*)<\\/(.*)>/um', array($this, '_replaceCharacters'), $convertedXml);
             }
             // Handle quotes in field data
             if (!empty($quoteHandling)) {
                 $ampSign = '&';
                 if ($escapeSpecialChars) {
                     $ampSign = '&amp;';
                 }
                 if ($quoteHandling == 'double') {
                     $quoteReplaceData = $ampSign . 'quot;' . $ampSign . 'quot;';
                 } else {
                     if ($quoteHandling == 'remove') {
                         $quoteReplaceData = '';
                     } else {
                         $quoteReplaceData = $quoteHandling;
                     }
                 }
                 if ($adjustedXml !== false) {
                     $adjustedXml = str_replace($ampSign . "quot;", $quoteReplaceData, $adjustedXml);
                 } else {
                     $adjustedXml = str_replace($ampSign . "quot;", $quoteReplaceData, $convertedXml);
                 }
             }
             if ($adjustedXml !== false) {
                 $xmlDoc->loadXML($adjustedXml, $libxmlConstants);
             }
             $outputBeforeEncoding = @$xslTemplateObj->transformToXML($xmlDoc);
             $output = $this->_changeEncoding($outputBeforeEncoding, $charsetEncoding);
             if (!$output && !empty($outputBeforeEncoding)) {
                 $this->_throwXmlException(Mage::helper('xtento_orderexport')->__("Please repair the XSL Template of this profile, check the encoding tag, or make sure output has been generated by this template. No output has been generated."));
             }
             $outputArray[$filename] = $output;
         }
         if (($fileType == 'invoice_pdf' || $fileType == 'packingslip_pdf') && Mage::registry('is_test_orderexport') !== true) {
             $orderIds = array();
             foreach ($exportArray as $exportObject) {
                 if (isset($exportObject['order']) && isset($exportObject['order']['entity_id'])) {
                     $orderIds[] = $exportObject['order']['entity_id'];
                 } else {
                     $orderIds[] = $exportObject['entity_id'];
                 }
             }
             if (!empty($orderIds)) {
                 $pdfContent = $this->_getPdfsForOrderIds($orderIds, $fileType);
                 if ($pdfContent) {
                     $outputArray[$filename] = $pdfContent;
                 }
             }
         }
     }
     // Reset libxml settings
     libxml_use_internal_errors($useInternalXmlErrors);
     if (function_exists('libxml_disable_entity_loader')) {
         #libxml_disable_entity_loader($loadXmlEntities);
     }
     // Return generated files
     return $outputArray;
 }
コード例 #27
0
 /**
  * @param string $entryId
  * @param KalturaIdeticDistributionJobProviderData $providerData
  * @return DOMDocument
  */
 public static function generateXML($entryId, KalturaIdeticDistributionJobProviderData $providerData)
 {
     $entry = entryPeer::retrieveByPKNoFilter($entryId);
     $mrss = kMrssManager::getEntryMrss($entry);
     if (!$mrss) {
         KalturaLog::err("No MRSS returned for entry [{$entryId}]");
         return null;
     }
     $xml = new KDOMDocument();
     if (!$xml->loadXML($mrss)) {
         KalturaLog::err("Could not load MRSS as XML for entry [{$entryId}]");
         return null;
     }
     $xslPath = realpath(dirname(__FILE__) . '/../') . '/xml/submit.xsl';
     if (!file_exists($xslPath)) {
         KalturaLog::err("XSL file not found [{$xslPath}]");
         return null;
     }
     $xsl = new KDOMDocument();
     $xsl->load($xslPath);
     // set variables in the xsl
     $varNodes = $xsl->getElementsByTagName('variable');
     foreach ($varNodes as $varNode) {
         $nameAttr = $varNode->attributes->getNamedItem('name');
         if (!$nameAttr) {
             continue;
         }
         $name = $nameAttr->value;
         if ($name && $providerData->{$name}) {
             $varNode->textContent = $providerData->{$name};
             $varNode->appendChild($xsl->createTextNode($providerData->{$name}));
             KalturaLog::debug("Set variable [{$name}] to [{$providerData->{$name}}]");
         }
     }
     $proc = new XSLTProcessor();
     $proc->registerPHPFunctions();
     $proc->importStyleSheet($xsl);
     $xml = $proc->transformToDoc($xml);
     if (!$xml) {
         KalturaLog::err("XML Transformation failed");
         return null;
     }
     // TODO create validation XSD
     $xsdPath = realpath(dirname(__FILE__) . '/../') . '/xml/submit.xsd';
     if (file_exists($xsdPath) && !$xml->schemaValidate($xsdPath)) {
         KalturaLog::err("Schema validation failed");
         return null;
     }
     return $xml;
 }
コード例 #28
0
ファイル: ReportGenerator.php プロジェクト: igez/gaiaehr
            $sqlStatement = str_ireplace($prepareKey, $prepareVariable, $sqlStatement);
            $sqlStatement = str_ireplace($prepareKey . '_operator', $variable['operator'], $sqlStatement);
        }
        return $sqlStatement;
    }
}
/**
 * This will combine the XML and the XSL
 * or generate the HTML, Text
 */
$rg = new ReportGenerator();
$rg->setRequest($_REQUEST);
$date = new DateTime();
$Stamp = $date->format('Ymd-His');
$xslt = new XSLTProcessor();
$xslt->registerPHPFunctions();
switch ($rg->format) {
    case 'html':
        header('Content-Type: application/xslt+xml');
        header('Content-Disposition: inline; filename=' . strtolower($rg->reportDir) . '-' . $Stamp . '".html"');
        $xslt->importStylesheet(new SimpleXMLElement($rg->getXSLTemplate()));
        echo $xslt->transformToXml(new SimpleXMLElement($rg->getXMLDocument()));
        break;
    case 'pdf':
        require_once '../../../lib/html2pdf_v4.03/html2pdf.class.php';
        $xslt->importStylesheet(new SimpleXMLElement($rg->getXSLTemplate()));
        $html2pdf = new HTML2PDF('P', 'A4', 'en');
        $html2pdf->pdf->SetAuthor('GaiaEHR');
        $html2pdf->WriteHTML($xslt->transformToXml(new SimpleXMLElement($rg->getXMLDocument())));
        $PDFDocument = base64_encode($html2pdf->Output(strtolower($rg->reportDir) . '-' . $Stamp . '.pdf', "S"));
        echo '<object data="data:application/pdf;base64,' . $PDFDocument . '" type="application/pdf" width="100%" height="100%"></object>';
コード例 #29
0
ファイル: test.php プロジェクト: redhoodie/ConsumePHP
                    }
                }
                $recipe->bake();
            }
            if (array_key_exists('cache', $_POST)) {
                $_SESSION['cache'] = $recipe;
            }
            $resultXML = $recipe->getResult();
            print '<pre>' . htmlentities(var_export($resultXML, true)) . '</pre>';
            if (array_key_exists('stylesheetURL', $_POST) && $_POST['stylesheetURL']) {
                $xslDoc = new DOMDocument();
                $xslDoc->load($_POST['stylesheetURL']);
                $xmlDoc = DOMDocument::loadXML($resultXML);
                $proc = new XSLTProcessor();
                $proc->importStylesheet($xslDoc);
                $proc->registerPHPFunctions();
                $resultXML = $proc->transformToXML($xmlDoc);
            }
            print $resultXML;
        }
        ?>
    </section>
      <?php 
    }
    Consume::printErrors();
    ?>
  </article>
  <?php 
}
?>
</section>
コード例 #30
0
 /**
  * Real XSLT transformation:
  *
  * @return string generated content
  */
 protected function _render(\DOMDocument $xmldoc, $path)
 {
     // Load XSL file:
     $xsldoc = new \DOMDocument();
     $xsldoc->load($path);
     // Generate the content:
     $proc = new \XSLTProcessor();
     $proc->registerPHPFunctions($this->_options['phpFunctions']);
     $proc->importStyleSheet($xsldoc);
     $content = $proc->transformToXML($xmldoc);
     return $content;
 }