Ejemplo n.º 1
0
function get_document($aNode)
{
    //get the directory in which the documents are contained from the config.php file
    global $xml_dir, $html_dir, $xslt, $html_xslt;
    //create the xslt
    $xp = new XsltProcessor();
    // create a DOM document and load the XSL stylesheet
    $xsl = new DomDocument();
    $xsl->load($xslt);
    // import the XSL styelsheet into the XSLT process
    $xp->importStylesheet($xsl);
    //open the xml document
    $xml = new DomDocument();
    $xml->loadXML($aNode);
    //transform
    if ($html = $xp->transformToXML($xml)) {
        $return = str_replace('<?xml version="1.0"?>' . "\n", "", $html);
        $return = str_replace('<!DOCTYPE div PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' . "\n", "", $return);
        $return = str_replace("\n", "", $return);
        $return = str_replace("\n ", "", $return);
        return str_replace("\t", "", $return);
    } else {
        trigger_error('XSL transformation failed.', E_USER_ERROR);
    }
}
Ejemplo n.º 2
0
 function handle($match, $state, $pos, Doku_Handler $handler)
 {
     switch ($state) {
         case DOKU_LEXER_SPECIAL:
             $matches = preg_split('/(&&XML&&\\n*|\\n*&&XSLT&&\\n*|\\n*&&END&&)/', $match, 5);
             $data = "XML: " . $matches[1] . "\nXSLT: " . $matches[2] . "(" . $match . ")";
             $xsltproc = new XsltProcessor();
             $xml = new DomDocument();
             $xsl = new DomDocument();
             $xml->loadXML($matches[1]);
             $xsl->loadXML($matches[2]);
             $xsltproc->registerPHPFunctions();
             $xsltproc->importStyleSheet($xsl);
             $data = $xsltproc->transformToXML($xml);
             if (!$data) {
                 $errors = libxml_get_errors();
                 foreach ($errors as $error) {
                     $data = display_xml_error($error, $xml);
                 }
                 libxml_clear_errors();
             }
             unset($xsltproc);
             return array($state, $data);
         case DOKU_LEXER_UNMATCHED:
             return array($state, $match);
         case DOKU_LEXER_EXIT:
             return array($state, '');
     }
     return array();
 }
Ejemplo n.º 3
0
 function pullStats($set)
 {
     $xp = new XsltProcessor();
     // create a DOM document and load the XSL stylesheet
     $xsl = new DomDocument();
     $xsl->load('stats.xslt');
     // import the XSL styelsheet into the XSLT process
     $xp->importStylesheet($xsl);
     // create a DOM document and load the XML datat
     $xml_doc = new DomDocument();
     $xml_doc->load('xmlcache/' . $set . '.xml');
     // transform the XML into HTML using the XSL file
     if ($xml = $xp->transformToXML($xml_doc)) {
         $stats_xml = simplexml_load_string($xml);
         $temp_bottom = array();
         $temp_top = array();
         foreach ($stats_xml->top as $top) {
             array_push($temp_top, (string) $top);
         }
         foreach ($stats_xml->bottom as $bottom) {
             array_push($temp_bottom, (string) $bottom);
         }
         $temp_return = array('bottom' => $temp_bottom, 'top' => $temp_top, 'total' => (string) $stats_xml->total);
         return $temp_return;
     }
 }
Ejemplo n.º 4
0
 public function TeiDisplay($file, array $options = array())
 {
     if ($file->getExtension() != "xml") {
         return "";
     }
     //queue_css_file('tei_display_public', 'screen', false, "plugins/TeiDisplay/views/public/css");
     //echo "<h3>displaying ", $file->original_filename, "</h3><br/>";
     $files = $file->getItem()->Files;
     foreach ($files as $f) {
         if ($f->getExtension() == "xsl") {
             $xsl_file = $f;
         }
         if ($f->getExtension() == "css") {
             $css_file = $f;
         }
     }
     //queue_css_url($css_file->getWebPath());
     echo '<link rel="stylesheet" media="screen" href="' . $css_file->getWebPath() . '"/>';
     //echo "transforming with ", $xsl_file->original_filename, "<br/>";
     $xp = new XsltProcessor();
     $xsl = new DomDocument();
     //echo "loading ", "files/original/".$xsl_file->filename, "<br/>";
     $xsl->load("files/original/" . $xsl_file->filename);
     $xp->importStylesheet($xsl);
     $xml_doc = new DomDocument();
     //echo "loading ", "files/original/".$file->filename, "<br/>";
     $xml_doc->load("files/original/" . $file->filename);
     try {
         if ($doc = $xp->transformToXML($xml_doc)) {
             return $doc;
         }
     } catch (Exception $e) {
         $this->view->error = $e->getMessage();
     }
 }
Ejemplo n.º 5
0
function pubmed_metadata($pmid, &$item)
{
    global $debug;
    $ok = false;
    $url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' . 'retmode=xml' . '&db=pubmed' . '&id=' . $pmid;
    //echo $url;
    $xml = get($url);
    //echo $xml;
    if (preg_match('/<\\?xml /', $xml)) {
        $ok = true;
        if ($debug) {
            echo $xml;
        }
        $dom = new DOMDocument();
        $dom->loadXML($xml);
        $xpath = new DOMXPath($dom);
        /*		$nodeCollection = $xpath->query ("//crossref/error");
        		foreach($nodeCollection as $node)
        		{
        			$ok = false;
        		}
        		if ($ok)
        		{*/
        // Get JSON
        $xp = new XsltProcessor();
        $xsl = new DomDocument();
        $xsl->load('xsl/pubmed2JSON.xsl');
        $xp->importStylesheet($xsl);
        $xml_doc = new DOMDocument();
        $xml_doc->loadXML($xml);
        $json = $xp->transformToXML($xml_doc);
        //echo $json;
        $item = json_decode($json);
        // post process
        // Ensure metadata is OK (assumes a journal for now)
        if (!isset($item->issn)) {
            $issn = '';
            if (isset($item->title)) {
                $issn = issn_from_journal_title($item->title);
            }
            if ($issn == '') {
                if (isset($item->eissn)) {
                    $issn = $item->eissn;
                }
            }
            if ($issn != '') {
                $item->issn = $issn;
            }
        }
        if ($debug) {
            echo '<h3>Boo</h3>';
            print_r($item);
        }
    }
    return $ok;
}
 /**
  * @param $path
  * @param array $data
  * @return string
  */
 protected function evaluatePath($path, array $data = [])
 {
     $preferences = $this->XSLTSimple->addChild('Preferences');
     $url = $preferences->addChild('url');
     $url->addAttribute('isHttps', Request::secure());
     $url->addAttribute('currentUrl', Request::url());
     $url->addAttribute('baseUrl', URL::to(''));
     $url->addAttribute('previousUrl', URL::previous());
     $server = $preferences->addChild('server');
     $server->addAttribute('curretnYear', date('Y'));
     $server->addAttribute('curretnMonth', date('m'));
     $server->addAttribute('curretnDay', date('d'));
     $server->addAttribute('currentDateTime', date('Y-m-d H:i:s'));
     $language = $preferences->addChild('language');
     $language->addAttribute('current', App::getLocale());
     $default_language = \Config::get('app.default_language');
     if (isset($default_language)) {
         $language->addAttribute('default', $default_language);
     }
     $languages = \Config::get('app.available_languages');
     if (is_array($languages)) {
         foreach ($languages as $lang) {
             $language->addChild('item', $lang);
         }
     }
     // from form generator
     if (isset($data['form'])) {
         $this->XSLTSimple->addChild('Form', form($data['form']));
     }
     // adding form errors to xml
     if (isset($data['errors'])) {
         $this->XSLTSimple->addData($data['errors']->all(), 'FormErrors', false);
     }
     // "barryvdh/laravel-debugbar":
     // adding XML tab
     if (true === class_exists('Debugbar')) {
         $dom = dom_import_simplexml($this->XSLTSimple)->ownerDocument;
         $dom->preserveWhiteSpace = false;
         $dom->formatOutput = true;
         $prettyXml = $dom->saveXML();
         // add new tab and append xml to it
         if (false === \Debugbar::hasCollector('XML')) {
             \Debugbar::addCollector(new \DebugBar\DataCollector\MessagesCollector('XML'));
         }
         \Debugbar::getCollector('XML')->addMessage($prettyXml, 'info', false);
     }
     $xsl_processor = new \XsltProcessor();
     $xsl_processor->registerPHPFunctions();
     $xsl_processor->importStylesheet(simplexml_load_file($path));
     return $xsl_processor->transformToXML($this->XSLTSimple);
 }
function getInterpretedXslt($xslPath, $xmlPath, $xsltProcessor = null)
{
    if ($xsltProcessor == null) {
        $xsltProcessor = new XsltProcessor();
        $xsltProcessor->registerPHPFunctions();
    }
    $xsl = new DOMDocument();
    $xsl->load($xslPath);
    $xsltProcessor->importStylesheet($xsl);
    $xml = new DOMDocument();
    $xml->load($xmlPath);
    $output = $xsltProcessor->transformToXML($xml) or die('Transformation error!');
    return $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
 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.º 11
0
 public function perform() {
     $action = $this->action;
     $xml_str = $action->perform();
     $xml_doc = simplexml_load_string($xml_str);
     if (!is_null($this->stylesheet)) {
         $xp = new XsltProcessor();
         $xsl = new DomDocument;
         $xsl->load($this->stylesheet);
         $xp->importStylesheet($xsl);
         if ($html = $xp->transformToXML($xml_doc)) {
             return $html;
         } else {
             throw new RtException('XSL transformation failed.');
         }
     } else {
         throw new RtException("Couldn't go on without xslt");
     }
 }
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);
     // http://www.php.net/manual/en/xsltprocessor.transformtoxml.php#62081
     //$result = $proc->transformToDoc($inputdom);
     //$result = $result->saveHTML();
     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;
 }
 /**
  * Transforms this class to HTML using the given stylesheet.
  */
 function toHtml()
 {
     // create a DOM document and load the XSL stylesheet
     $xsl = new DomDocument();
     $xsl->load($this->getXslFilename());
     // import the XSL styelsheet into the XSLT process
     $xp = new XsltProcessor();
     $xp->importStylesheet($xsl);
     // create a DOM document and load the XML datat
     $xml_doc = new DomDocument();
     $xml_doc->loadXML($this->toXml());
     // transform the XML into HTML using the XSL file
     if ($html = $xp->transformToXML($xml_doc)) {
         return $html;
     } else {
         //trigger_error('XSL transformation failed.', E_USER_ERROR);
         error_log("XSL transformation failed: " . $this->toXml());
         return 'XSL transformation failed.';
     }
     // if
     return 'XSL transformation failed.';
 }
Ejemplo n.º 14
0
/**
 * @brief Fetch an uBio RSS feed, and convert to object for ease of processing
 *
 * We convert RSS to JSON to create object. We use conditional GET to check whether
 * feed has been modified.
 *
 * @param url Feed URL
 * @param data Object
 *
 * @return Result from RSS fetch (0 is OK, 304 is feed unchanged, anything else is an error)
 */
function ubio_fetch_rss($url, &$data)
{
    $rss = '';
    $msg = '200';
    $result = GetRSS($url, $rss, true);
    if ($result == 0) {
        // Archive
        $dir = dirname(__FILE__) . '/tmp/' . date("Y-m-d");
        if (!file_exists($dir)) {
            $oldumask = umask(0);
            mkdir($dir, 0777);
            umask($oldumask);
        }
        $rss_file_name = $dir . '/' . md5($url) . '.xml';
        $rss_file = fopen($rss_file_name, "w+") or die("could't open file --\"{$rss_file_name}\"");
        fwrite($rss_file, $rss);
        fclose($rss_file);
        // Convert to JSON
        $xp = new XsltProcessor();
        $xsl = new DomDocument();
        $xsl->load(dirname(__FILE__) . '/xsl/ubiorss.xsl');
        $xp->importStylesheet($xsl);
        $xml_doc = new DOMDocument();
        $xml_doc->loadXML($rss);
        $json = $xp->transformToXML($xml_doc);
        $data = json_decode($json);
    } else {
        switch ($result) {
            case 304:
                $msg = 'Feed has not changed since last fetch (' . $result . ')';
                break;
            default:
                $msg = 'Badness happened (' . $result . ') ' . $url;
                break;
        }
    }
    echo $msg, "\n";
    return $result;
}
Ejemplo n.º 15
0
function get_element_tech_documentation($anElementName, $type)
{
    global $documentation, $doc_xslt;
    //create the xslt
    $xp = new XsltProcessor();
    //echo $documentation . $anElementName . '.html';exit;
    // create a DOM document and load the XSL stylesheet
    $xsl = new DomDocument();
    $xsl->load($doc_xslt);
    // import the XSL styelsheet into the XSLT process
    $xp->importStylesheet($xsl);
    //open the xml document
    $xml = new DomDocument();
    $xml->load($documentation . '/' . $anElementName . ".html");
    //set the parameter
    //$xp->setParameter('', array('element' => $anElementName, 'type' => $type));
    //transform
    if ($html = $xp->transformToXML($xml)) {
        return $html;
    } else {
        trigger_error('XSL transformation failed.', E_USER_ERROR);
    }
}
Ejemplo n.º 16
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.º 17
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 ')';
}
Ejemplo n.º 18
0
 function process()
 {
     global $gConf;
     if ('client' == $gConf['xsl_mode']) {
         echo 'depricated';
         exit;
     }
     header($this->_header);
     // xml: string, xsl: file
     if (!($this->_mode & BXXSLTRANSFORM_XML_FILE) && $this->_mode & BXXSLTRANSFORM_XSL_FILE) {
         $args = array('/_xml' => $this->_xml);
         validate_unicode($this->_xml);
         if ((int) phpversion() >= 5) {
             $xml = new DOMDocument();
             if (!@$xml->loadXML($this->_xml)) {
                 $mk = new Mistake();
                 $mk->log("BxXslTransform::process - can not load xml:\n " . $this->_xml);
                 $mk->displayError("[L[Site is unavailable]]");
             }
             $xsl = new DomDocument();
             $xsl->load($this->_xsl);
             $proc = new XsltProcessor();
             $proc->importStyleSheet($xsl);
             $res = $proc->transformToXML($xml);
         } else {
             if (function_exists('domxml_xslt_stylesheet_file')) {
                 $xmldoc = new DomDocument($this->_xml);
                 $xsldoc = domxml_xslt_stylesheet_file($this->_xsl);
                 $result = $xsldoc->process($xmldoc);
                 $res = $xsldoc->result_dump_mem($result);
             } elseif (function_exists('xslt_create')) {
                 $xh = xslt_create();
                 xslt_setopt($xh, XSLT_SABOPT_IGNORE_DOC_NOT_FOUND);
                 $res = xslt_process($xh, 'arg:/_xml', $this->_xsl, NULL, $args);
                 xslt_free($xh);
             } else {
                 die('Server XSLT support is not enabled, try to use client XSL transformation http://your-domain/orca_folder/?xsl_mode=client');
             }
         }
         return $res;
     }
     // xml: file, xsl: file
     if ($this->_mode & BXXSLTRANSFORM_XML_FILE && $this->_mode & BXXSLTRANSFORM_XSL_FILE) {
         if ((int) phpversion() >= 5) {
             $xml = new DOMDocument();
             $xml->load($this->_xml);
             $xsl = new DomDocument();
             $xsl->load($this->_xsl);
             $proc = new XsltProcessor();
             $proc->importStyleSheet($xsl);
             $res = $proc->transformToXML($xml);
         } else {
             if (function_exists('domxml_xslt_stylesheet_file')) {
                 $xmldoc = new DomDocument($this->_xml);
                 $xsldoc = domxml_xslt_stylesheet_file($this->_xsl);
                 $result = $xsldoc->process($xmldoc);
                 $res = $xsldoc->result_dump_mem($result);
             } elseif (function_exists('xslt_create')) {
                 $xh = xslt_create();
                 $res = xslt_process($xh, $this->_xml, $this->_xsl, NULL, $args);
                 xslt_setopt($xh, XSLT_SABOPT_IGNORE_DOC_NOT_FOUND);
                 xslt_free($xh);
             } else {
                 die('XSLT support is not enabled');
             }
         }
         return $res;
         //return  `/opt/jre1.5.0_06/bin/java -jar /opt/saxon/saxon.jar -ds {$this->_xml} {$this->_xsl}`;
     }
     return "<h1>not supported</h1>";
 }
Ejemplo n.º 19
0
 function Get2($institutionCode, $collectionCode, $catalogNumber)
 {
     if ($collectionCode != '') {
         $institution = $institutionCode . "-" . $collectionCode;
     } else {
         $institution = $institutionCode;
     }
     $url = $this->buildDIGIRQuery($institution, $catalogNumber);
     //echo $url;
     curl_setopt($this->ch, CURLOPT_URL, $url);
     $this->Call();
     storeInCache($institution, $catalogNumber, $this->result, 'xml');
     $xml = $this->result;
     //echo $xml;
     $data = '';
     $ok = false;
     if (preg_match('/<\\?xml version/', $xml)) {
         // we have XML
         $xml = preg_replace("/<response xmlns='http:\\/\\/digir.net\\/schema\\/protocol\\/2003\\/1.0'/", '<response', $xml);
         // We got XML, but did we get a hit?
         $record_count = 0;
         if (PHP_VERSION >= 5.0) {
             $dom = new DOMDocument();
             $dom->loadXML($xml);
             $xpath = new DOMXPath($dom);
             $xpath_query = "//diagnostic[@code='RECORD_COUNT']";
             $nodeCollection = $xpath->query($xpath_query);
             foreach ($nodeCollection as $node) {
                 $record_count = $node->firstChild->nodeValue;
             }
         } else {
             $xpath = new XPath();
             $xpath->importFromString($xml);
             $xpath_query = "//diagnostic[@code='RECORD_COUNT']";
             $nodeCollection = $xpath->match($xpath_query);
             foreach ($nodeCollection as $node) {
                 $record_count = $xpath->getData($node);
             }
         }
         //echo "Record count=$record_count\n";
         if ($record_count != 0) {
             //echo $xml;
             $xml = str_replace('&quot;', '\\"', $xml);
             //echo $xml;
             $xp = new XsltProcessor();
             $xsl = new DomDocument();
             $xsl->load('xsl/digir2JSON.xsl');
             $xp->importStylesheet($xsl);
             $xml_doc = new DOMDocument();
             $xml_doc->loadXML($xml);
             $json = $xp->transformToXML($xml_doc);
             //echo $json;
             $json = str_replace("{,", "{", $json);
             $json = str_replace("\n", "", $json);
             $data = json_decode($json);
             //print_r($data);
             //echo $data->status, "\n";
             // Clean weird KU stuff where they have lat=long=0
             if (isset($data->record[0]->latitude) && isset($data->record[0]->longitude)) {
                 if ($data->record[0]->latitude == 0 && $data->record[0]->longitude == 0) {
                     unset($data->record[0]->latitude);
                     unset($data->record[0]->longitude);
                 }
             }
             //print_r($data);
             if (isset($data->status)) {
                 if ($data->status == 'ok') {
                     $ok = true;
                 }
             }
         } else {
             $data->status = 'no record found';
         }
     } else {
         $data->status = 'no XML returned';
     }
     return $data;
 }
Ejemplo n.º 20
0
function get_sequence($accession, &$item)
{
    $id = find_genbank($accession);
    if ($id == 0) {
        // We don't have this sequence (but see below)
        $url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=' . $accession . '&rettype=gb&retmode=xml';
        //echo $url;
        $xml = get($url);
        //echo $xml;
        // Did we get an error?
        // Nothing returned
        if ($xml == '') {
            return 0;
        }
        //echo "\n\n" . __LINE__ . "\n\n";
        // NCBI error (sequence doesn't exist, or might not be released
        $dom = new DOMDocument();
        $dom->loadXML($xml);
        $xpath = new DOMXPath($dom);
        $xpath_query = "//Error";
        $nodeCollection = $xpath->query($xpath_query);
        $ok = true;
        foreach ($nodeCollection as $node) {
            if ($node->firstChild->nodeValue != '') {
                $ok = false;
            }
        }
        if (!$ok) {
            return 0;
        }
        //echo "\n\n" . __LINE__ . "\n\n";
        $xml = str_replace('<!DOCTYPE GBSet PUBLIC "-//NCBI//NCBI GBSeq/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_GBSeq.dtd">', '', $xml);
        $xp = new XsltProcessor();
        $xsl = new DomDocument();
        $xsl->load('xsl/gb2JSON.xsl');
        $xp->importStylesheet($xsl);
        $xml_doc = new DOMDocument();
        $xml_doc->loadXML($xml);
        $json = $xp->transformToXML($xml_doc);
        //echo $json;
        $data = json_decode($json);
        //print_r($data);
        // Handle case where was have this sequnece from EMBL harvesting
        $id = set_gi($data->accession, $data->gi);
        if ($id == 0) {
            // new sequence
            gb_postprocess($data);
            //print_r($data);
            $id = store_genbank($data);
            $item = $data;
        } else {
            // we have this already from EMBL
            $json = retrieve_genbank_json($id);
            $item = json_decode($json);
        }
    } else {
        //echo 'have it' . "\n";
        $json = retrieve_genbank_json($id);
        $item = json_decode($json);
    }
    // CouchDB modification
    if (isset($item->source->latitude)) {
        // Geometry for sequence
        $item->source->geometry = new stdclass();
        $item->source->geometry->type = "MultiPoint";
        $item->source->geometry->coordinates = array();
        $item->source->geometry->coordinates[] = array((double) $item->source->longitude, (double) $item->source->latitude);
    } else {
        if (isset($item->source->specimen)) {
            // Use geomtry from specimen
            if (isset($item->source->specimen->latitude)) {
                $item->source->geometry = new stdclass();
                $item->source->geometry->type = "MultiPoint";
                $item->source->geometry->coordinates = array();
                $item->source->geometry->coordinates[] = array((double) $item->source->specimen->longitude, (double) $item->source->specimen->latitude);
            }
        }
    }
    return $id;
}
Ejemplo n.º 21
0
function cinii_rdf($rdf_url, &$item, $issn = '', $debug = 0)
{
    $result = 0;
    $debug = 0;
    $rdf = get($rdf_url);
    //echo $rdf;
    // convert...
    $dom = new DOMDocument();
    $dom->loadXML($rdf);
    $xpath = new DOMXPath($dom);
    // Get JSON
    $xp = new XsltProcessor();
    $xsl = new DomDocument();
    $xsl->load('xsl/cinii.xsl');
    $xp->importStylesheet($xsl);
    $xml_doc = new DOMDocument();
    $xml_doc->loadXML($rdf);
    $json = $xp->transformToXML($xml_doc);
    if ($debug) {
        echo $json;
    }
    $item = json_decode($json);
    if ($debug) {
        print_r($item);
    }
    // Ensure we have ISSN (might not be in the metadata)
    if (!isset($item->issn) != '') {
        if ($issn != '') {
            $item->issn = $issn;
        } else {
            if (isset($item->title)) {
                $issn = issn_from_journal_title($item->title);
                if ($issn != '') {
                    $item->issn = $issn;
                }
            }
        }
    }
    // Check we have journal name
    if ($item->title == '') {
        $item->title = journal_title_from_issn($item->issn);
    }
    // Id
    $item->publisher_id = str_replace('http://ci.nii.ac.jp/naid/', '', $item->url);
    // Do some cleaning of authors
    foreach ($item->authors as $a) {
        // Last name in ALL CAPS
        if (preg_match('/^(?<lastname>[A-Z]+),?\\s*(?<forename>[A-Z](.*)$)/', $a->author, $matches)) {
            $a->lastname = mb_convert_case($matches['lastname'], MB_CASE_TITLE, mb_detect_encoding($matches['lastname']));
            $a->forename = mb_convert_case($matches['forename'], MB_CASE_TITLE, mb_detect_encoding($matches['forename']));
        } else {
            $parts = explode(",", $a->author);
            $a->lastname = trim($parts[0]);
            $a->forename = trim($parts[1]);
        }
    }
    // Clean pages
    if (isset($item->spage)) {
        $item->spage = preg_replace('/^p/', '', $item->spage);
    }
    // Title if not english...
    if ($item->atitle == '') {
        if (isset($item->jp_atitle)) {
            $item->atitle = $item->jp_atitle;
        }
    }
    if ($debug) {
        print_r($item);
    }
    return $result;
}
Ejemplo n.º 22
0
function main($uri)
{
    global $config;
    // Triple store
    global $store_config;
    global $store;
    $uri = urldecode($uri);
    $ntriples = get_canonical_uri($uri);
    //echo $ntriples; exit();
    if ($ntriples == 0) {
        // Fetch URI
        echo '<html>';
        echo '<body>';
        echo 'Sorry, don\'t have this URI <b>' . $uri . '</b>, trying to fetch it...';
        $uri_to_fetch = $uri;
        if (preg_match('/^urn:lsid:/', $uri_to_fetch)) {
            $uri_to_fetch = 'http://bioguid.info/' . $uri_to_fetch;
        }
        echo $uri_to_fetch;
        // can we get it, if so redirect...
        $query = "LOAD <" . $uri_to_fetch . ">";
        $r = $store->query($query);
        /*echo $query;
        		
        		echo '<pre>';
        		print_r($r);
        		echo '</pre>';
        		exit(); */
        if ($r['result']['t_count'] > 0) {
            // Got it, redirect to web page for this URI
            echo '<script type="text/javascript">';
            echo 'document.location="' . $config['web_root'] . 'uri/' . $uri . '";';
            echo '</script>';
        } else {
            // Bugger...
            echo "Badness happened";
        }
        echo '</body>';
        echo '</html>';
    } else {
        // Display info about this object (having issues with CONSTRUCT not returning language codes!?)
        $sparql = "\nCONSTRUCT\n{\n\t<{$uri}> ?o ?p\n}\n\nWHERE \n{ \n\t<{$uri}> ?o ?p\n}\n";
        $sparql = "DESCRIBE <{$uri}>";
        //echo $sparql . "\n";
        // get object
        $r = $store->query($sparql);
        $index = $r['result'];
        $parser = ARC2::getRDFParser();
        $rdfxml_doc = $parser->toRDFXML($index);
        //echo $rdfxml_doc;
        // What type if this?
        $dom = new DOMDocument();
        $dom->loadXML($rdfxml_doc);
        $xpath = new DOMXPath($dom);
        $xpath->registerNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
        $xpath->registerNamespace("dcterms", "http://purl.org/dc/terms/");
        $type = array();
        $xsl_filename = '';
        $html = '';
        $topic_title = '';
        //------------------------------------------------------------------------------------------
        // Get type(s) of objects
        $name = '';
        $nodeCollection = $xpath->query('//rdf:type/@rdf:resource');
        foreach ($nodeCollection as $node) {
            $type[] = $node->firstChild->nodeValue;
        }
        //------------------------------------------------------------------------------------------
        // Post process objects...
        // Publication add sequences...
        // possibe relations are isReferencedBy (stated in GenBank record) and references
        // which is stated in publication if we have links via PubMed.
        if (in_array('http://purl.org/ontology/bibo/Article', $type)) {
            $topic_title = get_title($uri);
            // Sequences
            $xml = query_sequences_from_publication($uri);
            append_xml($dom, $xml);
            // Taxa
            // Geography
            $xml = query_localities_from_publication($uri);
            append_xml($dom, $xml);
        }
        // Journal
        if (in_array('http://purl.org/ontology/bibo/Journal', $type)) {
            $topic_title = get_title($uri);
            $xml = query_articles_from_journal($uri);
            append_xml($dom, $xml);
        }
        // Collection
        if (in_array('http://rs.tdwg.org/ontology/voc/Collection#Collection', $type)) {
            $topic_title = get_title($uri);
            $xml = query_specimens_from_collection($uri);
            append_xml($dom, $xml);
        }
        // GenBank: Add specimen if we have it...
        if (in_array('http://purl.uniprot.org/core/Molecule', $type)) {
            $topic_title = get_title($uri);
            $specimen_uri = '';
            $nodeCollection = $xpath->query('//dcterms:relation/@rdf:resource');
            foreach ($nodeCollection as $node) {
                $specimen_uri = $node->firstChild->nodeValue;
            }
            if ($specimen_uri != '') {
                // Fetch RDF
                $r = describe($specimen_uri);
                $index = $r['result'];
                $extraXml = $parser->toRDFXML($index);
                // Load into current DOM
                $extraDom = new DOMDocument();
                $extraDom->loadXML($extraXml);
                $n = $dom->importNode($extraDom->documentElement, true);
                // Append to root node
                $dom->documentElement->appendChild($n);
            }
        }
        // Specimen
        if (in_array('http://rs.tdwg.org/ontology/voc/TaxonOccurrence#TaxonOccurrence', $type)) {
            // Get sequences from this specimen
            $xml = query_sequences_from_specimen($uri);
            append_xml($dom, $xml);
            $xml = query_publications_from_specimen($uri);
            append_xml($dom, $xml);
        }
        // NCBI taxon
        if (in_array('http://rs.tdwg.org/ontology/voc/TaxonConcept#TaxonConcept', $type)) {
            $topic_title = get_title($uri, '<http://rs.tdwg.org/ontology/voc/TaxonConcept#nameString>');
            // Get sequences from this specimen
            $xml = query_sequences_from_taxon($uri);
            append_xml($dom, $xml);
            $xml = query_localities_from_taxon($uri);
            append_xml($dom, $xml);
            $xml = query_publications_from_taxon($uri);
            append_xml($dom, $xml);
        }
        // Dbpedia
        if (in_array('http://www.opengis.net/gml/_Feature', $type)) {
            $topic_title = get_title($uri, 'rdfs:label', 'en');
        }
        if (in_array('http://www.w3.org/2002/07/owl#Thing', $type)) {
            $topic_title = get_title($uri, 'rdfs:label', 'en');
        }
        //print_r($type);
        //------------------------------------------------------------------------------------------
        // Display
        // Article
        if (in_array('http://purl.org/ontology/bibo/Article', $type)) {
            $xsl_filename = 'xsl/article.xsl';
        }
        // Journal
        if (in_array('http://purl.org/ontology/bibo/Journal', $type)) {
            $xsl_filename = 'xsl/journal.xsl';
        }
        // Dbpedia thing
        if (in_array('http://www.w3.org/2002/07/owl#Thing', $type)) {
            $xsl_filename = 'xsl/dbpedia.xsl';
        }
        // Dbpedia feature
        if (in_array('http://www.opengis.net/gml/_Feature', $type)) {
            $xsl_filename = 'xsl/dbpedia.xsl';
        }
        // genbank sequence
        if (in_array('http://purl.uniprot.org/core/Molecule', $type)) {
            $xsl_filename = 'xsl/genbank.xsl';
        }
        // taxon concept
        if (in_array('http://rs.tdwg.org/ontology/voc/TaxonConcept#TaxonConcept', $type)) {
            $xsl_filename = 'xsl/taxonomy.xsl';
        }
        // Collection
        if (in_array('http://rs.tdwg.org/ontology/voc/Collection#Collection', $type)) {
            $xsl_filename = 'xsl/collection.xsl';
        }
        // Specimen (by itself)
        if (in_array('http://rs.tdwg.org/ontology/voc/TaxonOccurrence#TaxonOccurrence', $type) && !in_array('http://purl.uniprot.org/core/Molecule', $type)) {
            $xsl_filename = 'xsl/occurrence.xsl';
        }
        //------------------------------------------------------------------------------------------
        if ($xsl_filename != '') {
            $xp = new XsltProcessor();
            $xsl = new DomDocument();
            $xsl->load($xsl_filename);
            $xp->importStylesheet($xsl);
            $html = $xp->transformToXML($dom);
        } else {
            $html .= '<p/>';
            $html .= '<div style="padding:10px;background:white;-webkit-border-radius:10px;">';
            $html .= '<pre class="brush:xml">' . htmlentities($dom->saveXML(), ENT_COMPAT, 'UTF-8') . '</pre>';
            $html .= '</div>';
        }
        // Display...
        header("Content-type: text/html; charset=utf-8\n\n");
        echo html_html_open();
        echo html_head_open();
        echo html_title($topic_title);
        echo html_include_css('css/main.css');
        echo html_include_script('js/prototype.js');
        echo html_include_script('js/lookahead.js');
        echo html_include_script('js/browse.js');
        // RDF display
        echo html_include_script('js/shCore.js');
        echo html_include_script('js/shBrushXml.js');
        echo html_include_css('css/shCore.css');
        echo html_include_css('css/shThemeDefault.css');
        echo html_head_close();
        echo html_body_open();
        //echo html_page_header(true, $uri);
        echo '<div id="container">' . "\n";
        echo '   <div id="banner">' . "\n";
        echo html_page_header(true, $uri);
        echo '   </div>' . "\n";
        /*echo '<div id="nav">';
        		echo '   </div>' . "\n";
        		echo '<div id="content">';
        		echo 'xxxxxx';
        		echo '   </div>' . "\n"; */
        /*		echo '<div class="main">';
        		
        		echo '<div class="maincontent">';
        		echo '<div class="maincontent_border">'; */
        if (1) {
            echo $html;
        } else {
            ?>
<div id="nav">
  <div>
    <b>On the Web</b>
    <br>
    <ul type="square">
      <li>
        <a href="http://dx.doi.org/10.1073/pnas.0907926106" target="_new">doi:10.1073/pnas.0907926106</a>
      </li>
    </ul>
    <b>Post to:</b>
    <br>
    <ul type="square">
      <li>Citeulike</li>
      <li>Connotea</li>
      <li>Mendeley</li>
    </ul>
  </div>
</div>
<div id="content">
  <h1>[Article] Bacterial gut symbionts are tightly linked with the evolution of herbivory in ants.</h1>
  <h2>Jacob A Russell, Corrie S Moreau, Benjamin Goldman-Huertas, Mikiko Fujiwara, David J Lohman, Naomi E Pierce</h2>
  <div><span class="internal_link" onclick="lookahead('http://bioguid.info/issn:0027-8424')">Proceedings of the National Academy of Sciences of the United States of America</span> 106: 21236 (2009) doi:10.1073/pnas.0907926106</div>
  <div class="abstract">Ants are a dominant feature of terrestrial ecosystems, yet we know little about the forces that drive their evolution. Recent findings illustrate that their diets range from herbivorous to predaceous, with &amp;quot;herbivores&amp;quot; feeding primarily on exudates from plants and sap-feeding insects. Persistence on these nitrogen-poor food sources raises the question of how ants obtain sufficient nutrition. To investigate the potential role of symbiotic microbes, we have surveyed 283 species from 18 of the 21 ant subfamilies using molecular techniques. Our findings uncovered a wealth of bacteria from across the ants. Notable among the surveyed hosts were herbivorous &amp;quot;turtle ants&amp;quot; from the related genera Cephalotes and Procryptocerus (tribe Cephalotini). These commonly harbored bacteria from ant-specific clades within the Burkholderiales, Pseudomonadales, Rhizobiales, Verrucomicrobiales, and Xanthomonadales, and studies of lab-reared Cephalotes varians characterized these microbes as symbiotic residents of ant guts. Although most of these symbionts were confined to turtle ants, bacteria from an ant-specific clade of Rhizobiales were more broadly distributed. Statistical analyses revealed a strong relationship between herbivory and the prevalence of Rhizobiales gut symbionts within ant genera. Furthermore, a consideration of the ant phylogeny identified at least five independent origins of symbioses between herbivorous ants and related Rhizobiales. Combined with previous findings and the potential for symbiotic nitrogen fixation, our results strongly support the hypothesis that bacteria have facilitated convergent evolution of herbivory across the ants, further implicating symbiosis as a major force in ant evolution.</div>
  <div>
    <ul type="square">
      <li><span class="internal_link" onclick="lookahead('http://bioguid.info/genbank:AF465438')">AF465438</span></li>
    </ul>
  </div>
</div>

	<?php 
        }
        echo '   <div id="footer">' . "\n";
        echo '     <p>About:</p>' . "\n";
        echo '   </div>' . "\n";
        echo '</div>' . "\n";
        // container
        echo '	
<div id="horizon">
	<div id="progress" style="display:none">
        <p>Hello</p>
	</div>
</div>';
        echo '
<script type="text/javascript">
	SyntaxHighlighter.all()
</script>';
        // footer
        echo html_body_close();
        echo html_html_close();
    }
}
Ejemplo n.º 23
0
 function Harvest()
 {
     $xml = get($this->url);
     //echo $xml;
     // Convert Plazi RSS to JSON
     $xp = new XsltProcessor();
     $xsl = new DomDocument();
     $xsl->load('xsl/rss1.xsl');
     $xp->importStylesheet($xsl);
     $xml_doc = new DOMDocument();
     $xml_doc->loadXML($xml);
     $json = $xp->transformToXML($xml_doc);
     // replace carriage returns and end of lines, which break JSON
     $json = str_replace("\n", " ", $json);
     $json = str_replace("\r", " ", $json);
     //echo $json;
     $obj = json_decode($json);
     //print_r($obj);
     // Extract details
     foreach ($obj->items as $i) {
         //echo $i->link . "\n";
         $item = new stdclass();
         //Add elements to the feed item
         $item->title = $i->title;
         $item->id = $i->link;
         $item->link = $i->link;
         $item->description = $i->description;
         $item->links = array();
         // Fetch record from DSpace using identfier based on handle
         $handle = $i->link;
         $handle = str_replace('http://hdl.handle.net/', '', $handle);
         // Store handle
         array_push($item->links, array('hdl' => $handle));
         $url = 'http://plazi.org:8080/dspace-oai/request?verb=GetRecord&identifier=oai:plazi.org:' . $handle . '&metadataPrefix=oai_dc';
         $oai_xml = get($url);
         $oai_xml = str_replace('xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"', '', $oai_xml);
         //echo $oai_xml;
         // extract what we need
         $dom = new DOMDocument();
         $dom->loadXML($oai_xml);
         $xpath = new DOMXPath($dom);
         // Register namespaces
         $xpath->registerNamespace("dc", "http://purl.org/dc/elements/1.1/");
         $xpath->registerNamespace("oai", "http://www.openarchives.org/OAI/2.0/");
         // Date of record
         $n = $xpath->query("//oai:datestamp");
         foreach ($n as $n2) {
             $item->updated = date("Y-m-d H:i:s", strtotime($n2->firstChild->nodeValue));
         }
         // Bibliographic details (mangled, sigh)
         $biblio = new stdclass();
         $biblio->hdl = $handle;
         $type = '';
         $n = $xpath->query("//dc:type");
         foreach ($n as $n2) {
             $type = $n2->firstChild->nodeValue;
             //echo $type . "\n";
         }
         $n = $xpath->query("//dc:title");
         foreach ($n as $n2) {
             $biblio->atitle = $n2->firstChild->nodeValue;
         }
         // Authors
         $biblio->authors = array();
         $n = $xpath->query("//dc:creator");
         foreach ($n as $n2) {
             $value = trim($n2->firstChild->nodeValue);
             // Make nice
             $value = mb_convert_case($value, MB_CASE_TITLE, mb_detect_encoding($value));
             // Get parts of name
             $parts = parse_name($value);
             $author = new stdClass();
             if (isset($parts['last'])) {
                 $author->lastname = $parts['last'];
             }
             if (isset($parts['suffix'])) {
                 $author->suffix = $parts['suffix'];
             }
             if (isset($parts['first'])) {
                 $author->forename = $parts['first'];
                 if (array_key_exists('middle', $parts)) {
                     $author->forename .= ' ' . $parts['middle'];
                 }
             }
             array_push($biblio->authors, $author);
         }
         // Subjects
         $biblio->tags = array();
         $n = $xpath->query("//dc:subject");
         foreach ($n as $n2) {
             array_push($biblio->tags, $n2->firstChild->nodeValue);
         }
         // Volume
         $n = $xpath->query("//dc:relation[1]");
         foreach ($n as $n2) {
             if (preg_match('/(?<volume>[0-9]+)(\\((?<issue>[0-9]+)\\))/', $n2->firstChild->nodeValue, $matches)) {
                 $biblio->volume = $matches['volume'];
                 $biblio->issue = $matches['issue'];
             } else {
                 $biblio->volume = $n2->firstChild->nodeValue;
             }
         }
         $n = $xpath->query("//dc:relation[2]");
         foreach ($n as $n2) {
             $biblio->title = $n2->firstChild->nodeValue;
         }
         $n = $xpath->query("//dc:relation[3]");
         foreach ($n as $n2) {
             $value = $n2->firstChild->nodeValue;
             if (preg_match('/pp.\\s*(?<spage>[0-9]+)\\-(?<epage>[0-9]+)/', $value, $matches)) {
                 $biblio->spage = $matches['spage'];
                 $biblio->epage = $matches['epage'];
             }
             if (preg_match('/.pdf$/', $value)) {
                 $biblio->pdf = $value;
             }
         }
         $n = $xpath->query("//dc:relation[4]");
         foreach ($n as $n2) {
             $value = $n2->firstChild->nodeValue;
             if (preg_match('/pp.\\s*(?<spage>[0-9]+)\\-(?<epage>[0-9]+)/', $value, $matches)) {
                 $biblio->spage = $matches['spage'];
                 $biblio->epage = $matches['epage'];
             }
             if (preg_match('/.pdf$/', $value)) {
                 $biblio->pdf = $value;
             }
         }
         $n = $xpath->query("//dc:date[3]");
         foreach ($n as $n2) {
             $biblio->year = $n2->firstChild->nodeValue;
         }
         // Look for existing identifiers
         if (isset($biblio->title) && isset($biblio->volume) && isset($biblio->spage)) {
             $url = 'http://bioguid.info/openurl/?genre=article';
             $url .= '&title=' . urlencode($biblio->title);
             $url .= '&volume=' . $biblio->volume;
             $url .= '&pages=' . $biblio->spage;
             $url .= '&display=json';
             //echo $url;
             $j = get($url);
             $ref = json_decode($j);
             //print_r($ref);
             if ($ref->status == 'ok') {
                 if (isset($ref->doi)) {
                     array_push($item->links, array('doi' => $ref->doi));
                     $item->description .= '<br/><a href="http://dx.doi.org/' . $ref->doi . '">doi:' . $ref->doi . '</a>';
                     $biblio->doi = $ref->doi;
                 }
                 if (isset($ref->url)) {
                     array_push($item->links, array('url' => $ref->url));
                     $biblio->url = $ref->url;
                 }
             }
         }
         //print_r($biblio);
         $item->payload = $biblio;
         $this->StoreFeedItem($item);
     }
 }
Ejemplo n.º 24
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.º 25
0
<article id="2">
	<title>Something Else Happened</title>
	<author>Different Person</author>
</article>
</articles>';
$xsl = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" encoding="iso-8859-1" />

<xsl:template match="/">
	<xsl:apply-templates select="//article"/>
</xsl:template>

<xsl:template match="article">
	Title: <xsl:value-of select="title"/><br />
	Author: <xsl:value-of select="author"/><br />
	<hr />
</xsl:template>

</xsl:stylesheet>';
/* load XSLT Stylesheet */
$xslDom = new domDocument();
$xslDom->loadXML($xsl);
/* load XML data */
$xmlDom = new domDocument();
$xmlDom->loadXML($xml);
$xsl = new XsltProcessor();
// instantiate XSLT processor
$xsl->importStylesheet($xslDom);
// load stylesheet
echo $xsl->transformToXML($xmlDom);
// perform the transformation & return HTML
Ejemplo n.º 26
0
function retriever_apply_dom_filter($retriever, &$item, $resource)
{
    logger('retriever_apply_dom_filter: applying XSLT to ' . $item['id'] . ' ' . $item['plink'], LOGGER_DEBUG);
    require_once 'include/html2bbcode.php';
    if (!$retriever['data']['include']) {
        return;
    }
    if (!$resource['data']) {
        logger('retriever_apply_dom_filter: no text to work with', LOGGER_NORMAL);
        return;
    }
    $encoding = retriever_get_encoding($resource);
    logger('@@@ item type ' . $resource['type'] . ' encoding ' . $encoding);
    $extracter_template = get_markup_template('extract.tpl', 'addon/retriever/');
    $doc = new DOMDocument('1.0', 'utf-8');
    if (strpos($resource['type'], 'html') !== false) {
        @$doc->loadHTML($resource['data']);
    } else {
        $doc->loadXML($resource['data']);
    }
    logger('@@@ actual encoding of document is ' . $doc->encoding);
    $components = parse_url($item['plink']);
    $rooturl = $components['scheme'] . "://" . $components['host'];
    $dirurl = $rooturl . dirname($components['path']) . "/";
    $params = array('$include' => retriever_construct_xpath($retriever['data']['include']), '$exclude' => retriever_construct_xpath($retriever['data']['exclude']), '$pageurl' => $item['plink'], '$dirurl' => $dirurl, '$rooturl' => $rooturl);
    $xslt = replace_macros($extracter_template, $params);
    $xmldoc = new DOMDocument();
    $xmldoc->loadXML($xslt);
    $xp = new XsltProcessor();
    $xp->importStylesheet($xmldoc);
    $transformed = $xp->transformToXML($doc);
    $item['body'] = html2bbcode($transformed);
    if (!strlen($item['body'])) {
        logger('retriever_apply_dom_filter retriever ' . $retriever['id'] . ' item ' . $item['id'] . ': output was empty', LOGGER_NORMAL);
        return;
    }
    $item['body'] .= "\n\n" . t('Retrieved') . ' ' . date("Y-m-d") . ': [url=';
    $item['body'] .= $item['plink'];
    $item['body'] .= ']' . $item['plink'] . '[/url]';
    q("UPDATE `item` SET `body` = '%s' WHERE `id` = %d", dbesc($item['body']), intval($item['id']));
}
Ejemplo n.º 27
0
<?php

// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument();
$xsl->load('extract.xsl');
// import the XSL styelsheet into the XSLT process
$xp = new XsltProcessor();
$xp->importStylesheet($xsl);
// create a DOM document and load the XML datat
$xml_doc = new DomDocument();
$xml_doc->load('/home/brian/projects/dilps/temp/tgn/tgn_xml_2004/tgn_dev2/_1_tgn2.xml');
// transform the XML  using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
    echo $html;
} else {
    trigger_error('XSL transformation failed.', E_USER_ERROR);
}
Ejemplo n.º 28
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;
     }
 }
 /**
  * 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.º 30
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;
 }