Ejemplo n.º 1
0
 /**
  * Render the table.
  *
  * @param mixed $tableDom
  * @param mixed $config
  */
 public function render(Document $reportDom, Config $config)
 {
     $template = $config['template'];
     $out = $config['file'];
     if (!file_exists($template)) {
         throw new \RuntimeException(sprintf('XSLT template file "%s" does not exist', $template));
     }
     $stylesheetDom = new \DOMDocument('1.0');
     $stylesheetDom->load($template);
     $xsltProcessor = new \XsltProcessor();
     $xsltProcessor->importStylesheet($stylesheetDom);
     $xsltProcessor->setParameter(null, 'title', $config['title']);
     $xsltProcessor->setParameter(null, 'phpbench-version', PhpBench::VERSION);
     $xsltProcessor->setParameter(null, 'date', date('Y-m-d H:i:s'));
     $output = $xsltProcessor->transformToXml($reportDom);
     if (!$output) {
         throw new \InvalidArgumentException(sprintf('Could not render report with XSL file "%s"', $template));
     }
     if (null !== $out) {
         file_put_contents($out, $output);
         $this->output->writeln('Dumped XSLT report:');
         $this->output->writeln($out);
     } else {
         $this->output->write($output);
     }
 }
 public function xhtmlAction()
 {
     $xml = DOCS_PATH . $this->view->docid . '.xml';
     $xsl = APPLICATION_PATH . 'modules/contingent/controllers/xml2html.xsl';
     $doc = new DOMDocument();
     $doc->substituteEntities = TRUE;
     $doc->load($xsl);
     $proc = new XsltProcessor();
     $proc->importStylesheet($doc);
     $doc->load($xml);
     $proc->setParameter('', 'contextPath', '/');
     $proc->setParameter('', 'nodeResPath', '/res/' . $this->view->docid . '/');
     echo $proc->transformToXml($doc);
 }
Ejemplo n.º 3
0
/**
 * Metainformation catalogue
 * --------------------------------------------------
 *
 * Lib_XML for MicKa
 *
 * @link       http://www.bnhelp.cz
 * @package    Micka
 * @category   Metadata
 * @version    20121206
 *
 */
function applyTemplate($xmlSource, $xsltemplate)
{
    $rs = FALSE;
    if (File_Exists(CSW_XSL . '/' . $xsltemplate)) {
        if (!extension_loaded("xsl")) {
            if (substr(PHP_OS, 0, 3) == "WIN") {
                dl("php_xsl.dll");
            } else {
                dl("php_xsl.so");
            }
        }
        $xp = new XsltProcessor();
        $xml = new DomDocument();
        $xsl = new DomDocument();
        $xml->loadXML($xmlSource);
        $xsl->load(CSW_XSL . '/' . $xsltemplate);
        $xp->importStyleSheet($xsl);
        //$xp->setParameter("","lang",$lang);
        $xp->setParameter("", "user", $_SESSION['u']);
        $rs = $xp->transformToXml($xml);
    }
    if ($rs === FALSE) {
        setMickaLog('applyTemplate === FALSE', 'ERROR', 'micka_lib_xml.php');
    }
    return $rs;
}
Ejemplo n.º 4
0
 /**
  * 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);
     }
 }
 public function xhtmlAction()
 {
     $this->_helper->viewRenderer->setNoRender();
     $xml = DOCS_PATH . $this->view->docid . '.xml';
     $xsl = APPLICATION_PATH . 'modules/site/controllers/xml2html.xsl';
     $doc = new DOMDocument();
     $doc->substituteEntities = TRUE;
     $doc->load($xsl);
     $proc = new XsltProcessor();
     $proc->importStylesheet($doc);
     @$doc->load($xml);
     $proc->setParameter('', 'contextPath', '/');
     $proc->setParameter('', 'nodeResPath', '/res/' . $this->view->docid . '/');
     $proc->registerPHPFunctions('TypecontentController::widget');
     echo $proc->transformToXml($doc);
 }
Ejemplo n.º 6
0
 /**
  * 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);
     }
 }
Ejemplo n.º 7
0
 /**
  * Render the table.
  *
  * @param mixed $tableDom
  * @param mixed $config
  */
 public function render(Document $reportDom, Config $config)
 {
     $template = $config['template'];
     $out = strtr($config['file'], ['%report_name%' => $reportDom->firstChild->getAttribute('name')]);
     if (!file_exists($template)) {
         throw new \RuntimeException(sprintf('XSLT template file "%s" does not exist', $template));
     }
     foreach ($reportDom->query('.//row') as $rowEl) {
         $formatterParams = [];
         foreach ($rowEl->query('./formatter-param') as $paramEl) {
             $formatterParams[$paramEl->getAttribute('name')] = $paramEl->nodeValue;
         }
         foreach ($rowEl->query('./cell') as $cellEl) {
             $value = $cellEl->nodeValue;
             if ('' !== $value && $cellEl->hasAttribute('class')) {
                 $classes = explode(' ', $cellEl->getAttribute('class'));
                 $value = $this->formatter->applyClasses($classes, $value, $formatterParams);
                 $cellEl->nodeValue = $value;
             }
         }
     }
     $stylesheetDom = new \DOMDocument('1.0');
     $stylesheetDom->load($template);
     $xsltProcessor = new \XsltProcessor();
     $xsltProcessor->importStylesheet($stylesheetDom);
     $xsltProcessor->setParameter(null, 'title', $config['title']);
     $xsltProcessor->setParameter(null, 'phpbench-version', PhpBench::VERSION);
     $xsltProcessor->setParameter(null, 'date', date('Y-m-d H:i:s'));
     $output = $xsltProcessor->transformToXml($reportDom);
     if (!$output) {
         throw new \InvalidArgumentException(sprintf('Could not render report with XSL file "%s"', $template));
     }
     if ($out) {
         file_put_contents($out, $output);
         $this->output->writeln('Dumped XSLT report:');
         $this->output->writeln($out);
     } else {
         $this->output->write($output);
     }
 }
Ejemplo n.º 8
0
 public function run($args)
 {
     // Get variables from args array passed into detached process.
     $filepath = $args['filepath'];
     $filename = !empty($args['csv_filename']) ? $args['csv_filename'] : pathinfo($filename, PATHINFO_BASENAME);
     $format = $args['format'];
     $itemTypeId = $args['item_type_id'];
     $collectionId = $args['collection_id'];
     $createCollections = $args['create_collections'];
     $recordsArePublic = $args['public'];
     $recordsAreFeatured = $args['featured'];
     $elementsAreHtml = $args['html_elements'];
     $containsExtraData = $args['extra_data'];
     $tagName = $args['tag_name'];
     $columnDelimiter = $args['column_delimiter'];
     $enclosure = $args['enclosure'];
     $elementDelimiter = $args['element_delimiter'];
     $tagDelimiter = $args['tag_delimiter'];
     $fileDelimiter = $args['file_delimiter'];
     // TODO Intermediate stylesheets are not managed currently.
     // $stylesheetIntermediate = $args['stylesheet_intermediate'];
     $stylesheetParameters = $args['stylesheet_parameters'];
     $stylesheet = !empty($args['stylesheet']) ? $args['stylesheet'] : get_option('xml_import_xsl_directory') . DIRECTORY_SEPARATOR . get_option('xml_import_stylesheet');
     $csvfilesdir = !empty($args['destination_dir']) ? $args['destination_dir'] : sys_get_temp_dir();
     // Create a DOM document and load the XML data.
     $xml_doc = new DomDocument();
     $xml_doc->load($filepath);
     // Create a DOM document and load the XSL stylesheet.
     $xsl = new DomDocument();
     $xsl->load($stylesheet);
     // Import the XSL styelsheet into the XSLT process.
     $xp = new XsltProcessor();
     $xp->setParameter('', 'node', $tagName);
     $xp->importStylesheet($xsl);
     // Write transformed xml file to the temp csv file.
     try {
         if ($doc = $xp->transformToXML($xml_doc)) {
             $csvFilename = $csvfilesdir . DIRECTORY_SEPARATOR . pathinfo($filename, PATHINFO_FILENAME) . '.csv';
             $documentFile = fopen($csvFilename, 'w');
             fwrite($documentFile, $doc);
             fclose($documentFile);
             //$this->_initializeCsvImport($basename, $recordsArePublic, $recordsAreFeatured, $collectionId);
             $this->_helper->flashMessenger(__('Successfully generated CSV File'));
         } else {
             $this->_helper->flashMessenger(__('Could not transform XML file.  Be sure your XML document is valid.'), 'error');
         }
     } catch (Exception $e) {
         $this->view->error = $e->getMessage();
     }
 }
Ejemplo n.º 9
0
function createSQLScripts()
{
    $xp = new XsltProcessor();
    // create a DOM document and load the XSL stylesheet
    $xsl = new DomDocument();
    $xsl->load($_ENV['db_xslt_create']);
    // import the XSL styelsheet into the XSLT process
    $xp->importStylesheet($xsl);
    $xp->setParameter(null, 'target', 'drop');
    // create a DOM document and load the XML datat
    $xml_doc = new DomDocument();
    $xml_doc->load($_ENV['db_xml_file']);
    // transform the XML into HTML using the XSL file
    if ($result = $xp->transformToXML($xml_doc)) {
        // save result in uninstall.sql
        $handle = fopen($_ENV['sql_script_dir'] . 'uninstall.sql', 'w');
        if (fwrite($handle, $result) === false) {
            echo 'Konnte die Datei ' . $_ENV['sql_script_dir'] . 'uninstall.sql nicht beschreiben.';
        }
        fclose($handle);
        // save result as first command in install.sql
        $handle = fopen($_ENV['sql_script_dir'] . 'install.sql', 'w');
        //if (fwrite($handle, $result) === false) {
        //  echo 'Konnte die Datei ' .$_ENV['sql_script_dir'] . 'install.sql nicht beschreiben.';
        //}
        // run the same with parameter create
        $xp->setParameter(null, 'target', 'create');
        if ($result = $xp->transformToXML($xml_doc)) {
            if (fwrite($handle, $result) === false) {
                echo 'Konnte die Datei ' . $_ENV['sql_script_dir'] . 'install.sql nicht beschreiben.';
            }
        }
        fclose($handle);
    } else {
        echo 'XSL transformation failed.';
    }
}
Ejemplo n.º 10
0
 /**
  * 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();
 }
Ejemplo n.º 11
0
 function getReportDefinitionForm()
 {
     $fileName = "c:/web/afids_reports/trunk/writer/xsl_templates/reportDefinition.xsl";
     $xsl = new DomDocument();
     if (!$xsl->load($fileName)) {
         echo 'failed' . $fileName;
     }
     $stylesheet = new XsltProcessor();
     $stylesheet->importStylesheet($xsl);
     // pass the report name (id) to the xsl and the filtering is done there
     $stylesheet->setParameter(null, "reportName", $this->reportName);
     if (!($translatedResponse = $stylesheet->transformToXML($this->xml_report_definition))) {
         return "error";
     } else {
         return $translatedResponse;
         //echo $translatedResponse;
     }
 }
Ejemplo n.º 12
0
 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;
 }
Ejemplo n.º 13
0
 /**
  * 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;
 }
Ejemplo n.º 14
0
    fwrite($ob_file, $buffer);
}
// generate Core Documentation
$files = array('index', "objref", "configfiles", "scripttypes", "events", "builtintextcmds", "privileges", "attack");
foreach ($files as $f) {
    $ob_file = fopen('offline/' . $f . '.html', 'w');
    ob_start('ob_file_callback');
    require $f . '.php';
    ob_end_flush();
}
/* generate em Modules */
$xsltproc = new XsltProcessor();
$xsl = new DomDocument();
$xsl->load('escript.xslt');
$xsltproc->importStylesheet($xsl);
$xsltproc->setParameter('', 'offline', $offline);
$xml = simplexml_load_file('modules.xml');
foreach ($xml as $em) {
    $name = (string) $em['name'];
    $nicename = (string) $em['nice'];
    $ob_file = fopen('offline/' . $name . '.html', 'w');
    ob_start('ob_file_callback');
    siteheader('POL Scripting Reference ' . $nicename . '.em');
    $xml_doc = new DomDocument();
    $xml_doc->load($name . '.xml');
    if ($html = $xsltproc->transformToXML($xml_doc)) {
        echo $html;
    }
    sitefooter();
    ob_end_flush();
}
Ejemplo n.º 15
0
 /**
  * Uses `DomDocument` to transform the document. Any errors that
  * occur are trapped by custom error handlers, `trapXMLError` or
  * `trapXSLError`.
  *
  * @param XsltProcessor $XSLProc
  *  An instance of `XsltProcessor`
  * @param string $xml
  *  The XML for the transformation to be applied to
  * @param string $xsl
  *  The XSL for the transformation
  * @param array $parameters
  *  An array of available parameters the XSL will have access to
  * @return string
  */
 private function __process(XsltProcessor $XSLProc, $xml, $xsl, array $parameters = array())
 {
     // Create instances of the DomDocument class
     $xmlDoc = new DomDocument();
     $xslDoc = new DomDocument();
     // Set up error handling
     if (function_exists('ini_set')) {
         $ehOLD = ini_set('html_errors', false);
     }
     // Load the xml document
     set_error_handler(array($this, 'trapXMLError'));
     // Prevent remote entities from being loaded, RE: #1939
     $elOLD = libxml_disable_entity_loader(true);
     $xmlDoc->loadXML($xml, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0);
     libxml_disable_entity_loader($elOLD);
     // Must restore the error handler to avoid problems
     restore_error_handler();
     // Load the xsl document
     set_error_handler(array($this, 'trapXSLError'));
     // Ensure that the XSLT can be loaded with `false`. RE: #1939
     // Note that `true` will cause `<xsl:import />` to fail.
     $elOLD = libxml_disable_entity_loader(false);
     $xslDoc->loadXML($xsl, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0);
     libxml_disable_entity_loader($elOLD);
     // Load the xsl template
     $XSLProc->importStyleSheet($xslDoc);
     // Set parameters when defined
     if (!empty($parameters)) {
         General::flattenArray($parameters);
         $XSLProc->setParameter('', $parameters);
     }
     // Must restore the error handler to avoid problems
     restore_error_handler();
     // Start the transformation
     set_error_handler(array($this, 'trapXMLError'));
     $processed = $XSLProc->transformToXML($xmlDoc);
     // Restore error handling
     if (function_exists('ini_set') && isset($ehOLD)) {
         ini_set('html_errors', $ehOLD);
     }
     // Must restore the error handler to avoid problems
     restore_error_handler();
     return $processed;
 }
Ejemplo n.º 16
0
 /**
  * Return string containing the transformed XML output.
  * This function applies an XSLT transform to a given XML source.
  * @param $xmlFile pathname to the XML source file (absolute)
  * @param $xslFile pathname to the XSL stylesheet (absolute)
  * @param (optional) $xsltType type of XSLT renderer to use (PHP4, PHP5, or XSLT shell command)
  * @param (optional) $arguments array of param-value pairs to pass to the XSLT  
  * @return string
  */
 function transformXSLT($xmlFile, $xslFile, $xsltType = "", $arguments = null)
 {
     // if either XML or XSL file don't exist, then fail without trying to process XSLT
     $fileManager = new FileManager();
     if (!$fileManager->fileExists($xmlFile) || !$fileManager->fileExists($xslFile)) {
         return false;
     }
     // Determine the appropriate XSLT processor for the system
     if (version_compare(PHP_VERSION, '5', '>=') && extension_loaded('xsl') && extension_loaded('dom')) {
         // PHP5.x with XSL/DOM modules present
         if ($xsltType == "PHP5" || $xsltType == "") {
             // load the XML file as a domdocument
             $xmlDom = new DOMDocument("1.0", "UTF-8");
             // these are required for external entity resolution (eg. &nbsp;)
             // it slows loading substantially (20-100x), often up to 60s
             // this can be solved by use of local catalogs to speed resolution
             //
             // http://www.whump.com/moreLikeThis/link/03815
             // http://www.suite75.net/blog/mt/tim/archives/2004_07.php
             //putenv("XML_CATALOG_FILES=/Users/mj/Sites/ojs2/plugins/generic/xmlGalley/transform/Publishing-2_2-dtd-June/catalog.ent");
             $xmlDom->substituteEntities = true;
             $xmlDom->resolveExternals = true;
             $xmlDom->load($xmlFile);
             // create the processor and import the stylesheet
             $xslDom = new DOMDocument("1.0", "UTF-8");
             $xslDom->load($xslFile);
             $proc = new XsltProcessor();
             $proc->importStylesheet($xslDom);
             // set XSL parameters
             foreach ((array) $arguments as $param => $value) {
                 $proc->setParameter(null, $param, $value);
             }
             // transform the XML document to an XHTML fragment
             $contents = $proc->transformToXML($xmlDom);
             return $contents;
         }
     }
     if (version_compare(PHP_VERSION, '5', '<') && extension_loaded('xslt')) {
         // PHP4.x with XSLT module present
         if ($xsltType == "PHP4" || $xsltType == "") {
             // create the processor
             $proc = xslt_create();
             // transform the XML document to an XHTML fragment
             $contents = xslt_process($proc, $xmlFile, $xslFile, null, null, $arguments);
             return $contents;
         }
     }
     if ($xsltType != "") {
         // external command-line renderer
         // parse the external command to check for %xsl and %xml parameter substitution
         if (strpos($xsltType, '%xsl') === false) {
             return false;
         }
         // perform %xsl and %xml replacements for fully-qualified shell command
         $xsltCommand = str_replace(array('%xsl', '%xml'), array($xslFile, $xmlFile), $xsltType);
         // check for safe mode and escape the shell command
         if (!ini_get('safe_mode')) {
             $xsltCommand = escapeshellcmd($xsltCommand);
         }
         // run the shell command and get the results
         exec($xsltCommand . ' 2>&1', $contents, $status);
         // if there is an error, spit out the shell results to aid debugging
         if ($status != false) {
             if ($contents != '') {
                 echo implode("\n", $contents);
                 return true;
             } else {
                 return false;
             }
         }
         return implode("\n", $contents);
     } else {
         // No XSLT processor available
         return false;
     }
 }
Ejemplo n.º 17
0
        $xsl->load('xmltolua-compact.xsl');
        header('Content-Type: text/plain; charset=UTF-8');
    } else {
        if ($format === "json") {
            $xsl->load('xmltojson-compact.xsl');
            header('Content-Type: application/json; charset=UTF-8');
        } else {
            if ($format === "jsonp") {
                $xsl->load('xmltojsonp-compact.xsl');
                header('Content-Type: application/javascript; charset=UTF-8');
            }
        }
    }
}
$xp->importStyleSheet($xsl);
$xp->setParameter('', 'decimalSupported', 'no');
if ($callback && $format === "jsonp") {
    $xp->setParameter('', 'callback', $callback);
}
$xml = new DomDocument();
$contents = file_get_contents($url);
if ($contents) {
    $xml->loadXML($contents);
    if ($xform = $xp->transformToXML($xml)) {
        echo $xform;
    } else {
        trigger_error('XSL transformation failed.', E_USER_ERROR);
    }
} else {
    trigger_error('URL could not be loaded.', E_USER_ERROR);
}
Ejemplo n.º 18
0
/* add the header */
if ($offline) {
    siteheader('POL Scripting Reference');
}
// PHP-BB global stuff
global $request;
$request->enable_super_globals();
//
$xmlfile = $_GET['xmlfile'];
$xsltproc = new XsltProcessor();
$xsl = new DomDocument();
$xsl->load($webroot . 'escript.xslt');
$xsltproc->importStylesheet($xsl);
$xml_doc = new DomDocument();
$xml_doc->load($webroot . $xmlfile . '.xml');
$xsltproc->setParameter('', 'offline', $offline);
$xsltproc->setParameter('', 'xmlfile', $xmlfile);
if ($html = $xsltproc->transformToXML($xml_doc)) {
    echo $html;
}
if (!$offline) {
    echo '
    <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
    </script>
    <script type="text/javascript">
    _uacct = "UA-2869696-3";
    urchinTracker();
    </script>';
}
/* add the footer */
sitefooter($offline);
Ejemplo n.º 19
0
 static function transform($xsl_file, $xml, $params = null, $charset = 'UTF-8', $nohead = false)
 {
     global $o_global;
     $ent = '<!DOCTYPE page [
     <!ENTITY nbsp   "&#160;">
     <!ENTITY copy   "&#169;">
     <!ENTITY reg    "&#174;">
     <!ENTITY trade  "&#8482;">
     <!ENTITY mdash  "&#8212;">
     <!ENTITY ldquo  "&#0171;">
     <!ENTITY rdquo  "&#0187;">
     <!ENTITY pound  "&#163;">
     <!ENTITY sum    "&#0216;">
     <!ENTITY yen    "&#165;">
     <!ENTITY euro   "&#8364;">
 ]>';
     if (!$nohead) {
         $xml = "<?xml version=\"1.0\" encoding=\"" . $charset . "\"?>\n" . $ent . $xml;
     }
     $browser = null;
     if (empty($xml)) {
         $xml = '<empty_xml>Empty xml</empty_xml>';
     }
     //$xml=iconv('cp1251','cp1251',$xml);
     if (!$nohead && $charset == 'windows-1251') {
         $xml = preg_replace("{[�]}i", "", $xml);
     }
     $xsl = new DomDocument();
     //$xsl->resolveExternals = true;
     $xsl->substituteEntities = true;
     if (file_exists($o_global->themes_site_root . $xsl_file)) {
         $xsl->load($o_global->themes_site_root . $xsl_file);
     } elseif (file_exists($o_global->themes_engine_root . $xsl_file)) {
         $xsl->load($o_global->themes_engine_root . $xsl_file);
     } elseif (_GL_DEBUG === true) {
         return 'Function "transform". Error. File "' . $xsl_file . '" not found (' . $o_global->themes_site_root . $xsl_file . ', ' . $o_global->themes_engine_root . $xsl_file . ')<BR/>' . "\n";
     } else {
         return '';
     }
     //$inputdom = new DomDocument();
     //$inputdom->loadXML($xml);
     /* create the processor and import the stylesheet */
     $proc = new XsltProcessor();
     $proc->registerPhpFunctions();
     //$xsl = $proc->importStylesheet($xsl);
     if ($params) {
         foreach ($params as $key => $value) {
             $proc->setParameter(null, $key, $value);
         }
     }
     $inputdom = new DomDocument();
     $inputdom->substituteEntities = true;
     $inputdom->loadXML($xml);
     $proc->importStyleSheet($xsl);
     $res = $proc->transformToXML($inputdom);
     return $res;
 }
Ejemplo n.º 20
0
 /**
  * Set parameter to XsltProceror
  * @param string $name
  * @param string $value
  */
 public function setParameter($name, $value)
 {
     $this->_processor->setParameter('', (string) $name, (string) $value);
 }
Ejemplo n.º 21
0
 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();
     }
 }
Ejemplo n.º 22
0
 /**
  * Parse XML doc and apply XSL
  *
  * @param  [type] $content [description]
  * @return [type]          [description]
  */
 function xmldoc_parse()
 {
     global $post;
     $post_ID = $_POST['post_id'];
     // Nonce & $post_ID ok
     if (isset($post_ID) && is_numeric($post_ID) && check_ajax_referer("aa-parse-xml-nonce-{$post_ID}", '_ajax_nonce')) {
         // have xslt installed?
         if (!class_exists('XSLTProcessor') || !class_exists('DOMDocument')) {
             echo json_encode(array('success' => false, 'message' => 'XML and XSLT processing is not supported by your PHP installation. Please install <a href="http://www.php.net/manual/en/book.xsl.php">the PHP XSL module</a>'));
             die;
         }
         $teiFile = $this->get_xml_file($post_ID);
         // array comes back if there's an error message
         //
         if (is_wp_error($teiFile)) {
             echo json_encode(array('success' => false, 'message' => $teiFile->get_error_message()));
             die;
         }
         // Check for a user defined xsl file
         $stylesheet = $this->get_xsl_file($post_ID);
         if (is_wp_error($stylesheet)) {
             echo json_encode(array('success' => false, 'message' => $stylesheet->get_error_message()));
             die;
         }
         $xp = new XsltProcessor();
         // create a DOM document and load the XSL stylesheet
         $xsl = new DomDocument();
         // import the XSL styelsheet into the XSLT process
         $xsl->load($stylesheet);
         $xp->importStylesheet($xsl);
         //set query parameter to pass into stylesheet
         $displayType = 'entire';
         $section = 'body';
         $xp->setParameter('', 'display', $displayType);
         $xp->setParameter('', 'section', $section);
         // create a DOM document and load the XML data
         $xml_doc = new DomDocument();
         $xml_doc->load($teiFile);
         // xPath to extract the document title
         $xpath = new DOMXPath($xml_doc);
         $titleQueries = '//*[local-name() = "teiHeader"]/*[local-name() = "fileDesc"]/*[local-name() = "titleStmt"]/*[local-name() = "title"]';
         $nodes = $xpath->query($titleQueries);
         $newTitle = null;
         foreach ($nodes as $node) {
             //see if that text is already set and don't put in any blank or null fields
             $newTitle = preg_replace('/\\s\\s+/', ' ', trim($node->nodeValue));
         }
         try {
             // transform to html and update wordpress body content
             // and title
             if ($doc = $xp->transformToXML($xml_doc)) {
                 $postUpdate = array('ID' => $post_ID, 'post_content' => $doc);
                 if ($newTitle) {
                     $postUpdate['post_title'] = $newTitle;
                 }
                 wp_update_post($postUpdate);
                 echo json_encode($postUpdate);
                 die;
             }
         } catch (Exception $e) {
             echo json_encode(array('success' => false, 'message' => $e->getMessage()));
             die;
         }
     } else {
         // ajax nonce check fail
         echo json_encode(array('success' => false, 'message' => 'Access not allowed.'));
         die;
     }
     // var_dump($html);
     // die();
 }
 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;
 }
Ejemplo n.º 24
0
function axml2xslt_transform(&$row, &$params, $page)
{
    // funkce pluginu jako takoveho, zadava se do $mainframe
    $style_directory = get_parameter("style_directory");
    // parametr adresare se styly
    if (JPATH_BASE == JPATH_ADMINISTRATOR) {
        //zjistdz?me, jestli jsme v administraci a pokud ano, pdz?evedeme cestu na adresovdz?ndz? frontendu
        $style_directory = '../' . $style_directory;
    }
    $default_style = get_parameter("default_style");
    // defaultni styl ktery se nastavuje v params
    $schema_validation = get_parameter("schema_validation");
    // bude slouzit pro validaci dokumentu
    $validation_matters = get_parameter("validation_matters");
    // zalezi na validaci?
    // parametry definovandz? ---> jsou to ty parametry u toho nastaveni pluginu
    $chyba = false;
    // tak tohle uz je doufam standardni zalezitost, pokud bude true, neprojde transformem
    $nekontrolovat_file = false;
    // overeni zda je to opravdu XML -> prichazi zde
    if (substr($row->text, 0, 5) == "<?xml") {
        // mame se tim vubec zatezovat?
        if (empty($style_directory)) {
            // pokud je vyplneny
            $chyba = true;
            $row->text = zapis_error($row->text, "Adresar se styly musi byt nastaven!<br>");
        } else {
            // dodelat na konec lomitko
            if (eregi("\\\\", $style_directory)) {
                //kdyby tam byly ty idiotsky druhy lomitka
                $style_directory = str_replace("\\\\", "/", $style_directory);
                // tady se odstranuji
            }
            if (substr($style_directory, strlen($style_directory) - 1, 1) != "/") {
                //dodelani lomitka nakonec
                $style_directory = $style_directory . "/";
                //pridani lomitka pokud tam neni
            }
        }
        if (eregi("http://", $style_directory) || eregi("http://", $default_style)) {
            $chyba = true;
            $row->text = zapis_error($row->text, "Styl ani adresar nesmi byt na jinem serveru!<br>");
        }
        if (!file_exists($style_directory)) {
            $chyba = true;
            // pokud ten adresar neexistuje, tak to dame userovi vedet
            $row->text = zapis_error($row->text, "Adresar se styly je nastaven ale na serveru neexistuje!<br>");
        }
        if (stripos($row->text, "<?xml-stylesheet") !== false) {
            //je v souboru deklarace toho souboru?
            $text2 = vypreparuj_data("<?xml-stylesheet", "?>", $row->text);
            $text = vypreparuj_data('href="', '"', $text2);
            //nj uvozovky uvozovky
            if (empty($text)) {
                $text = vypreparuj_data("href='", "'", $text2);
                // dalsi cek, pokud je prazdno
            }
            $text = basename($text);
            $style_file = $style_directory . $text;
            // takze slozeni souboru z filu, kdyz je tam ta stylesheet
        } else {
            if (empty($default_style)) {
                // neni defaultni styl ani nastavena transformace, nic tedy nedelej
                $chyba = true;
                // neni default styl, neni ani neni deklarace ve filu
                $nekontrolovat_file = true;
            } else {
                //neni nastaveny styl, ale je defaultni, tak tedy pouzij ten
                $style_file = $style_directory . $default_style;
                // pro kontrolu zda soubor existuje
            }
            if ($nekontrolovat_file === false) {
                if (!file_exists($style_file)) {
                    // existuje ten soubor se stylem?
                    $chyba = true;
                    // nepusti dal, a vyhodi chybu pokud soubor se stylem neexistuje
                    $row->text = zapis_error($row->text, "Soubor ({$style_file}) s definovanym stylem neexistuje!<br>");
                }
                $file_extension = end(explode(".", $style_file));
                if ($file_extension != "xsl") {
                    $chyba = true;
                    $row->text = zapis_error($row->text, "Soubor obsahujici xsl data musi mit koncovku .xsl! Tento soubor ma koncovku .{$file_extension}.<br>");
                }
            }
            if ($chyba === false) {
                // vse je ok, probiha transformace
                $transform = true;
                $xp = new XsltProcessor();
                // create a DOM document and load the XSL stylesheet
                $f = fopen($style_file, "r");
                //otevrit soubor
                $file_data = fread($f, filesize($style_file));
                //precist ho a vzit si data (nacteni do pameti)
                $xsl = new DomDocument();
                // primo vlozeny XSL kod (je to o neco rychlejsi ac se musi udelat vic operaci)
                set_error_handler('handle_xsl_error');
                //kvuli errorum (jsou tu spatne vyreseny)
                $xsl->loadXML($file_data);
                restore_error_handler();
                // nastaveni erroru zpet, kvuli rychlosti provadeni
                //$row->text = zapis_error($row->text,"XSL kod neni v poradku.<br>");
                // nacteni stylesheetu do dokumentu
                if ($GLOBALS["xsl_code_error"] == 1) {
                    $transform = false;
                    $row->text = zapis_error($row->text, "XSL kod neni v poradku.<br>");
                } else {
                    $xp->importStylesheet($xsl);
                }
                // docasny DOM dokument s primo vlozenejma datama k transformaci
                $xml_document = new DomDocument();
                set_error_handler('handle_xml_error');
                //kvuli errorum (jsou tu spatne vyreseny)
                $xml_document->loadXML($row->text);
                restore_error_handler();
                // nastaveni erroru zpet, kvuli rychlosti provadeni
                if ($GLOBALS["xml_code_error"] == 1) {
                    $transform = false;
                    $row->text = zapis_error($row->text, "XML kod neni v poradku.<br>");
                }
                libxml_use_internal_errors(true);
                if (!empty($schema_validation)) {
                    if (!file_exists($style_directory . $schema_validation)) {
                        $transform = false;
                        $row->text = zapis_error($row->text, "Soubor se schdz?matem neexistuje.<br>");
                    } else {
                        if (!$xml_document->schemaValidate($style_directory . $schema_validation)) {
                            if ($validation_matters == 1) {
                                $transform = false;
                                $row->text = zapis_error($row->text, "XML dokument neni validni, transformace neprobehla.<br>");
                                //$row->text = zapis_error($row->text,libxml_display_errors());
                            } else {
                                $GLOBALS["validation_error"] = 1;
                            }
                        }
                    }
                }
                //nahozeni parametru dulezitych k transformaci (zavedeni namespacu)
                $xp->setParameter($namespace, 'id1', 'value1');
                $xp->setParameter($namespace, 'id2', 'value2');
                //transformace jako takovdz? se vsemi daty, ktera jsou zapotrebi
                if ($transform === true) {
                    if ($html = $xp->transformToXML($xml_document)) {
                        $row->text = $html;
                        //nasazeni toho pretransformovaneho textu misto puvodniho xml filu
                        if ($GLOBALS["validation_error"] == 1) {
                            // nebyla nahodou chyba pri validaci, na ktere ale tolik nezalezi?
                            $row->text = zapis_error($row->text, "XML dokument neni validni podle \"{$schema_validation}\", ale transformace probehla<br>");
                            $GLOBALS["validation_error"] = 0;
                        }
                    } else {
                        $row->text = zapis_error($row->text, "Transformace XML souboru se nezdarila!<br>");
                        //nejaka neznama chyba pri transformaci -> to se uz bohuzel skriptem neda ovlivnit
                    }
                } else {
                    $GLOBALS["xml_code_error"] = 0;
                    //kvuli tomu aby to pri pristim projiti, pokud nebude chyba pustilo transformaci neceho jinyho
                    $GLOBALS["xsl_code_error"] = 0;
                    //kvuli tomu aby to pri pristim projiti, pokud nebude chyba pustilo transformaci neceho jinyho
                }
            }
        }
    }
}
Ejemplo n.º 25
0
    $xsl = new DomDocument();
    $xsl->load('blast2fasta.xsl');
    $xp->importStylesheet($xsl);
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $xpath = new DOMXPath($dom);
    $xp->setParameter('', 'number', NumSequences);
    $fasta = $xp->transformToXML($dom);
    $obj->fastafile = 'tmp/' . $rid . '.fas';
    file_put_contents($obj->fastafile, $fasta);
    // NEXUS translation table
    $xp2 = new XsltProcessor();
    $xsl2 = new DomDocument();
    $xsl2->load('blast2translate.xsl');
    $xp2->importStylesheet($xsl2);
    $xp2->setParameter('', 'number', NumSequences);
    $translate = $xp2->transformToXML($dom);
    $obj->translatefile = 'tmp/' . $rid . '.txt';
    file_put_contents($obj->translatefile, $translate);
}
$callback = '';
if (isset($_GET['callback'])) {
    $callback = $_GET['callback'];
}
if ($callback != '') {
    echo $callback . '(';
}
echo json_encode($obj);
if ($callback != '') {
    echo ')';
}
 /**
  * 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;
 }
 /**
  * Uses `DomDocument` to transform the document. Any errors that
  * occur are trapped by custom error handlers, `trapXMLError` or
  * `trapXSLError`.
  *
  * @param XsltProcessor $XSLProc
  *  An instance of `XsltProcessor`
  * @param string $xml
  *  The XML for the transformation to be applied to
  * @param string $xsl
  *  The XSL for the transformation
  * @param array $parameters
  *  An array of available parameters the XSL will have access to
  * @return string
  */
 private function __process(XsltProcessor $XSLProc, $xml, $xsl, array $parameters = array())
 {
     // Create instances of the DomDocument class
     $xmlDoc = new DomDocument();
     $xslDoc = new DomDocument();
     // Set up error handling
     if (function_exists('ini_set')) {
         $ehOLD = ini_set('html_errors', false);
     }
     // Load the xml document
     set_error_handler(array($this, 'trapXMLError'));
     $xmlDoc->loadXML($xml);
     // Must restore the error handler to avoid problems
     restore_error_handler();
     // Load the xml document
     set_error_handler(array($this, 'trapXSLError'));
     $xslDoc->loadXML($xsl);
     // Load the xsl template
     $XSLProc->importStyleSheet($xslDoc);
     // Set parameters when defined
     if (!empty($parameters)) {
         General::flattenArray($parameters);
         $XSLProc->setParameter('', $parameters);
     }
     restore_error_handler();
     // Start the transformation
     set_error_handler(array($this, 'trapXMLError'));
     $processed = $XSLProc->transformToXML($xmlDoc);
     // Restore error handling
     if (function_exists('ini_set') && isset($ehOLD)) {
         ini_set('html_errors', $ehOLD);
     }
     restore_error_handler();
     return $processed;
 }
Ejemplo n.º 29
0
$term = $_GET['term'];
$couch_id = 'page/' . $PageID;
$resp = $couch->send("GET", "/" . $config['couchdb_options']['database'] . "/" . urlencode($couch_id));
$page = json_decode($resp);
if (isset($page->error)) {
    // badness
    $html = 'Oops';
} else {
    $imageUrl = 'http://www.biodiversitylibrary.org/pagethumb/' . $PageID . ',400,400';
    if (isset($page->xml)) {
        $xp = new XsltProcessor();
        $xsl = new DomDocument();
        $xsl->load(dirname(__FILE__) . '/djvu2html.xsl');
        $xp->importStylesheet($xsl);
        // Load XML
        $dom = new DOMDocument();
        $dom->loadXML($page->xml);
        $xpath = new DOMXPath($dom);
        // Export HTML with background image using XSLT
        $xp->setParameter('', 'imageUrl', $imageUrl);
        $xp->setParameter('', 'widthpx', 500);
        $xp->setParameter('', 'term', $term);
        $html = $xp->transformToXML($dom);
    } else {
        $html = '<span style="background-color:orange;color-white;">Warning: no XML!</span><img style="border:1px solid rgb(228,228,228);-webkit-filter: grayscale(100%) contrast(200%);" src="' . $imageUrl . '" width="500" />';
    }
}
//echo $html;
$data = new stdclass();
$data->html = $html;
echo json_encode($data);
Ejemplo n.º 30
0
function display_one_page_html($PageID, $format = 'html', $callback = '')
{
    global $config;
    global $couch;
    $obj = new stdclass();
    $obj->html = '';
    $obj->page = 'page/' . $PageID;
    $obj->status = 404;
    // Do we have this page in the database, with XML?
    $xml = '';
    $couch_id = 'page/' . $PageID;
    $resp = $couch->send("GET", "/" . $config['couchdb_options']['database'] . "/" . urlencode($couch_id));
    $page = json_decode($resp);
    if (isset($page->error)) {
        // we don't have this page
    } else {
        if (isset($page->xml)) {
            $xml = $page->xml;
        }
    }
    if ($xml != '') {
        // Source of image
        if ($config['image_source'] == 'bhl') {
            $image_url = 'http://www.biodiversitylibrary.org/pagethumb/' . $PageID . ',500,500"';
            if ($config['use_cloudimage']) {
                $image_url = 'http://exeg5le.cloudimg.io/s/width/700/' . $image_url;
            }
            if ($config['use_weserv']) {
                $image_url = 'https://images.weserv.nl/?url=' . str_replace('http://', '', $image_url);
            }
        } else {
            $image_url = 'http://direct.biostor.org/bhl_image.php?PageID=' . $PageID;
        }
        // Enable text selection
        $xp = new XsltProcessor();
        $xsl = new DomDocument();
        $xsl->load(dirname(__FILE__) . '/djvu2html.xsl');
        $xp->importStylesheet($xsl);
        $doc = new DOMDocument();
        $doc->loadXML($xml);
        $xp->setParameter('', 'widthpx', '700');
        $xp->setParameter('', 'imageUrl', $image_url);
        $obj->html = $xp->transformToXML($doc);
        $obj->status = 200;
    }
    api_output($obj, $callback);
}