getRDFParser() static public method

static public getRDFParser ( $a = '' )
Example #1
0
 public function __construct($a = '')
 {
     parent::__construct();
     $this->a = $a;
     /* parse the before and after graphs if necessary*/
     foreach (array('before', 'after', 'before_rdfxml', 'after_rdfxml') as $rdf) {
         if (!empty($a[$rdf])) {
             if (is_string($a[$rdf])) {
                 /** @var \ARC2_RDFParser $parser */
                 $parser = \ARC2::getRDFParser();
                 $parser->parse(false, $a[$rdf]);
                 $a[$rdf] = $parser->getSimpleIndex(0);
             } else {
                 if (is_array($a[$rdf]) and isset($a[$rdf][0]) and isset($a[$rdf][0]['s'])) {
                     //triples array
                     /** @var \ARC2_RDFSerializer $ser */
                     $ser = \ARC2::getTurtleSerializer();
                     /** @var string $turtle */
                     $turtle = $ser->getSerializedTriples($a[$rdf]);
                     /** @var \ARC2_RDFParser $parser */
                     $parser = \ARC2::getTurtleParser();
                     $parser->parse(false, $turtle);
                     $a[$rdf] = $parser->getSimpleIndex(0);
                 }
             }
             $nrdf = str_replace('_rdfxml', '', $rdf);
             $this->{$nrdf} = $a[$rdf];
         }
     }
     $this->__init();
 }
Example #2
0
function get_openlink_acct($acct)
{
    $parser = ARC2::getRDFParser();
    $parser->parse($acct);
    $triples = $parser->getTriples();
    foreach ($triples as $row) {
        if (strcmp($row[p], "http://xmlns.com/foaf/0.1/accountServiceHomepage") == 0) {
            return convert_to_rss($row[o]);
        }
    }
}
 function __construct($a = array())
 {
     $this->a = $a;
     /* parse the before and after graphs if necessary*/
     foreach (array('before', 'after') as $rdf) {
         if (!is_array($a[$rdf]) and !empty($a[$rdf])) {
             $parser = ARC2::getRDFParser();
             $parser->parse(false, $a[$rdf]);
             $a[$rdf] = $parser->getSimpleIndex(0);
         }
         $this->{$rdf} = $a[$rdf] ? $a[$rdf] : array();
     }
 }
 function _run_query($query)
 {
     $response = $this->sparqlservice->graph($query);
     if ($response->is_success()) {
         require_once MORIARTY_ARC_DIR . '/ARC2.php';
         $parser = ARC2::getRDFParser();
         $parser->parse(false, $response->body);
         $changeset = $this->revert_changes($parser->getSimpleIndex(0));
         $ser = ARC2::getRDFXMLSerializer();
         $response->body = $ser->getSerializedIndex($changeset);
     }
     return $response;
 }
Example #5
0
function arc_ntriples2php($datafile)
{
    ini_set("include_path", S3DB_SERVER_ROOT . '/pearlib/arc' . PATH_SEPARATOR . ini_get("include_path"));
    if (in_array("ARC2.php", get_included_files())) {
    }
    include_once "ARC2.php";
    $parser = ARC2::getRDFParser();
    $parser->parse($datafile);
    $triples = $parser->getTriples();
    if (!$triples) {
        $parser->parse('file://' . $datafile);
        $triples = $parser->getTriples();
    }
    return $triples;
}
function retrieveLabel($url)
{
    $parser = ARC2::getRDFParser();
    $parser->parse($url);
    $index = $parser->getSimpleIndex(0);
    if (is_array($index[$url]["http://www.w3.org/2000/01/rdf-schema#label"])) {
        foreach ($index[$url]["http://www.w3.org/2000/01/rdf-schema#label"] as $sl) {
            if ($sl['lang'] == "en" || $sl['lang'] == "") {
                $label = $sl['value'];
            }
        }
    }
    if (trim($label) != "") {
        return $label;
    }
    if (strrpos($url, "#") !== false) {
        return substr($url, strrpos($url, "#") + 1);
    }
    if (strrpos($url, "/") !== false) {
        return substr($url, strrpos($url, "/") + 1);
    }
    return $url;
}
Example #7
0
 function handleUpdateRequest($webid, $uri)
 {
     $this->result = '';
     $this->setHeader('http', 'HTTP/1.1 403 Forbidden');
     if ($q = @file_get_contents('php://input')) {
         //	$this->sparulLog($uri, $webid, $q);
         $triples = array();
         $parser = ARC2::getRDFParser($this->a);
         $parser->parse($uri);
         $triples = $parser->getTriples();
         $index = ARC2::getSimpleIndex($triples, 0);
         /* split combined INSERT/DELETE query */
         if (preg_match('/^\\s*(DELETE.*)\\s*(INSERT.*)$/is', $q, $m)) {
             $qs = array($m[1], $m[2]);
         } else {
             $qs = array($q);
         }
         $tmpfname = tempnam("/home/foaf/www/datawiki/rdf", "rdf_");
         foreach ($qs as $q) {
             $index = $this->getUpdatedIndex($index, $q, $uri);
             if (!$this->getErrors()) {
                 $this->setHeader('http', 'HTTP/1.1 200 OK');
                 if ($index) {
                     /* todo: create dirs, if necessary */
                     $fp = fopen($tmpfname, 'w');
                     $doc = $parser->toRDFXML($index);
                     fwrite($fp, $doc);
                     fclose($fp);
                 } else {
                     unlink($tmpfname);
                 }
             }
         }
         return $tmpfname;
     }
 }
Example #8
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();
    }
}
 function to_rdf($url, $document, $output, $store = '')
 {
     $parser = ARC2::getRDFParser($this->a);
     $parser->parse($url, $document);
     $triples = $parser->getTriples();
     if ($this->use_store == 1 && $store == '') {
         $this->store_rdf($url, $parser->toTurtle($triples));
     }
     switch ($output) {
         case 'ntriples':
             $file = $this->rand_filename('nt');
             header("Content-type: text/plain");
             header("Content-Disposition: inline; filename=" . $file);
             $result = $parser->toNTriples($triples);
             break;
         case 'turtle':
             $file = $this->rand_filename('ttl');
             header("Content-type: text/turtle");
             header("Content-Disposition: inline; filename=" . $file);
             $result = $parser->toTurtle($triples);
             break;
         case 'rdfjson':
             $file = $this->rand_filename('json');
             header("Content-type: application/json");
             header("Content-Disposition: inline; filename=" . $file);
             $result = $parser->toRDFJSON($triples);
             break;
         case 'rdf':
             $file = $this->rand_filename('rdf');
             header("Content-type: application/rdf+xml");
             header("Content-Disposition: inline; filename=" . $file);
             $result = $parser->toRDFXML($triples);
             break;
         case 'html':
             $file = $this->rand_filename('html');
             header("Content-type: text/html");
             header("Content-Disposition: inline; filename=" . $file);
             $result = $parser->toHTML($triples);
             break;
         case 'rdfa':
             $file = $this->rand_filename('html');
             header("Content-type: text/html");
             header("Content-Disposition: inline; filename=" . $file);
             $result = $this->toRDFa($triples);
             break;
     }
     return $result;
 }
 /**
  * Get an RDF parser.
  * @return ARC2_RDFParser The RDF parser.
  */
 public function getRDFParser()
 {
     /** @var ARC2_RDFParser $parser */
     $parser = ARC2::getRDFParser();
     return $parser;
 }
Example #11
0
 /**
  * Serialize an index into either RDF-XML or RDF-JSON
  */
 public function serialize($index, $prefix = '', $format = 'xml')
 {
     if (!empty($prefix)) {
         $this->ns['scalar'] = $prefix;
     }
     switch (strtolower($format)) {
         case 'json':
             $parser = @ARC2::getRDFParser();
             $doc = @$parser->toRDFJSON($index);
             break;
         case 'turtle':
             $parser = @ARC2::getRDFParser();
             $doc = @$parser->toTurtle($index, $this->ns);
             break;
         default:
             // xml
             $conf = array('ns' => $this->ns, 'serializer_prettyprint_container' => true);
             // , 'serializer_type_nodes' => true
             $ser = @ARC2::getRDFXMLSerializer($conf);
             $doc = @$ser->getSerializedIndex($index);
     }
     return $doc;
 }
 function toTriples($v)
 {
     if (is_array($v)) {
         if (isset($v[0]) && isset($v[0]['s'])) {
             return $v;
         }
         return ARC2::getTriplesFromIndex($v);
     }
     $parser = ARC2::getRDFParser($this->a);
     if ($v && !preg_match('/\\s/', $v)) {
         /* assume graph URI */
         $parser->parse($v);
     } else {
         $parser->parse('', $v);
     }
     return $parser->getTriples();
 }
 /**
  * listActivity
  *
  * tries to get feeds by checking various ways to relate feeds with foaf
  * profiles.
  *
  * @see http://wiki.foaf-project.org/w/PersonWeblogRssDocumentationIssue
  *
  * @since 0.1
  *
  * @param array $check array with strings of predicates which should be checked
  * @param int $items number of returned activity items
  *
  * @return array with activity items
  */
 public function listActivity(array $check = array(), $numberItems = null)
 {
     // $ARC2TO = $this;
     if (!isset($cacheTimeActivity)) {
         $cacheTimeActivity = $this->cacheTimeActivity;
     }
     if (!is_array($check) || count($check) == 0) {
         $check = array('seeAlso', 'made', 'weblog', 'account', 'homepage');
     }
     if ($numberItems == null) {
         $numberItems = 50;
     }
     $numberItems = intval($numberItems);
     // get all rdfs:seeAlso
     $rdfs_seeAlso = array();
     if (array_search('seeAlso', $check) !== false) {
         $rdfs_seeAlso = $this->_nld_rdfs_seeAlso;
     }
     // get all foaf:made
     $foaf_made = array();
     if (array_search('made', $check) !== false) {
         $foaf_made = $this->_nld_foaf_made;
     }
     // get all foaf:weblog in foaf:Document
     $weblog_seeAlso = array();
     if (array_search('weblog', $check) !== false) {
         $foaf_weblog = $this->_nld_foaf_weblog;
         foreach ($foaf_weblog as $weblog) {
             if (is_object($weblog) && $weblog->_nld_rdfs_seeAlso) {
                 $weblog_seeAlso = array_merge($weblog_seeAlso, $weblog->_nld_rdfs_seeAlso);
             }
             unset($weblog);
         }
         unset($foaf_weblog);
     }
     // get all foaf:homepage in foaf:Document
     $homepage_seeAlso = array();
     if (array_search('homepage', $check) !== false) {
         $foaf_homepage = $this->_nld_foaf_homepage;
         foreach ($foaf_homepage as $homepage) {
             if (is_object($homepage) && $homepage->_nld_rdfs_seeAlso) {
                 $homepage_seeAlso = array_merge($homepage_seeAlso, $homepage->_nld_rdfs_seeAlso);
             }
             unset($homepage);
         }
         unset($foaf_homepage);
     }
     // get all foaf:holdsAccount in foaf:OnlineAccount
     $account_seeAlso = array();
     if (array_search('account', $check) !== false) {
         $foaf_holdsAccount = $this->_nld_foaf_holdsAccount;
         foreach ($foaf_holdsAccount as $holdsAccount) {
             if (is_object($holdsAccount) && $holdsAccount->_nld_rdfs_seeAlso) {
                 $account_seeAlso = array_merge($account_seeAlso, $holdsAccount->_nld_rdfs_seeAlso);
             }
             unset($holdsAccount);
         }
         unset($foaf_holdsAccount);
     }
     // check for type, must be rss:channel
     $possibleFeeds = array_unique(array_merge($rdfs_seeAlso, $foaf_made, $weblog_seeAlso, $account_seeAlso, $homepage_seeAlso));
     unset($rdfs_seeAlso, $foaf_made, $weblog_seeAlso, $account_seeAlso, $homepage_seeAlso);
     $confirmedFeeds = array();
     foreach ($possibleFeeds as $feed) {
         if (is_object($feed) && is_array($feed->_nld_rdf_type) && isset($feed->_nld_rdf_type[0]) && $feed->_nld_rdf_type[0] == 'http://purl.org/rss/1.0/channel') {
             $confirmedFeeds[$feed->uri] = $feed->getLiteral(array('rdfs_label', 'dc_title'));
         }
     }
     unset($possibleFeeds);
     $activity = array('feeds' => $confirmedFeeds, 'stream' => array());
     // load feeds and read items
     $i = 0;
     $sortByDate = array();
     $uniqueUris = array();
     foreach ($confirmedFeeds as $feed => $feedTitle) {
         $feedIndex = null;
         if (false === ($feedIndex = $this->getCache(array('name' => $feed, 'space' => $this->cache_space_prefix . 'Activity', 'time' => $cacheTimeActivity)))) {
             // parse feed
             $feedParser = ARC2::getRDFParser(array('reader_timeout' => $this->requestsTimeout, 'http_user_agent_header' => $this->user_agent_string, 'keep_time_limit' => true));
             $feedParser->parse($feed, null, 0, $this->requestsTimeout);
             if (is_object($feedParser)) {
                 $feedIndex = $feedParser->getSimpleIndex(0);
                 // save cache
                 $this->saveCache(array('data' => $feedIndex, 'name' => $feed, 'space' => $this->cache_space_prefix . 'Activity', 'time' => true));
             }
         }
         if (is_array($feedIndex) && count($feedIndex) > 0) {
             // get feed title from feed when resource did not defined any title
             $indexKeys = array_keys($feedIndex);
             if (isset($feedIndex[$indexKeys[0]]['http://purl.org/rss/1.0/title']) && $activity['feeds'][$feed] === null) {
                 $activity['feeds'][$feed] = $feedIndex[$indexKeys[0]]['http://purl.org/rss/1.0/title'][0]['value'];
             }
             // get feed items
             foreach ($feedIndex as $uri => $content) {
                 if (isset($content['http://www.w3.org/1999/02/22-rdf-syntax-ns#type']) && $content['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'][0]['value'] == 'http://purl.org/rss/1.0/item' && array_search($content['http://purl.org/rss/1.0/link'][0]['value'], $uniqueUris) === false) {
                     // content
                     $activity['stream'][$i]['source'] = $feed;
                     $activity['stream'][$i]['date'] = isset($content['http://purl.org/dc/elements/1.1/date']) ? strtotime($content['http://purl.org/dc/elements/1.1/date'][0]['value']) : 0;
                     $activity['stream'][$i]['link'] = htmlspecialchars($content['http://purl.org/rss/1.0/link'][0]['value'], ENT_COMPAT, 'UTF-8');
                     $activity['stream'][$i]['title'] = $content['http://purl.org/rss/1.0/title'][0]['value'];
                     $activity['stream'][$i]['content'] = isset($content['http://purl.org/rss/1.0/modules/content/encoded']) ? $content['http://purl.org/rss/1.0/modules/content/encoded'][0]['value'] : null;
                     $activity['stream'][$i]['output'] = '<a href="' . $activity['stream'][$i]['link'] . '">' . htmlspecialchars(strip_tags($activity['stream'][$i]['title']), ENT_COMPAT, 'UTF-8') . '</a>';
                     //TODO do not transform html-entities a second time
                     $activity['stream'][$i]['contentarray_origin'] = $content;
                     $sortByDate[$i] = $activity['stream'][$i]['date'];
                     // orgacheck
                     $uniqueUris[] = $activity['stream'][$i]['link'];
                     $i++;
                 }
             }
         }
     }
     // sort by date desc
     array_multisort($sortByDate, SORT_DESC, $activity['stream']);
     // only give back maximum number of items
     $activity['stream'] = array_slice($activity['stream'], 0, $numberItems);
     return $activity;
 }
Example #14
0
 function loadData($data)
 {
     require_once 'arc/ARC2.php';
     $parser = \ARC2::getRDFParser();
     $parser->parse('', $data);
     return $this->load($parser->getSimpleIndex(0));
 }
Example #15
0
 public static function serializeRdf($data, $extension = 'rdf')
 {
     global $conf;
     global $lodspk;
     $ser;
     $dPointer;
     $docs = Utils::travelTree($data);
     require_once $conf['home'] . 'lib/arc2/ARC2.php';
     $parser = ARC2::getRDFParser();
     $triples = array();
     foreach ($docs as $d) {
         $parser->parse($conf['basedir'], $d);
         $t = $parser->getTriples();
         $triples = array_merge($triples, $t);
     }
     if ($lodspk['mirror_external_uris']) {
         global $uri;
         global $localUri;
         $t = array();
         $t['s'] = $localUri;
         $t['s_type'] = 'uri';
         $t['p'] = "http://www.w3.org/2002/07/owl#sameAs";
         $t['o'] = $uri;
         $t['o_type'] = 'uri';
         array_push($triples, $t);
         $t['p'] = "http://www.w3.org/2000/10/swap/pim/contact#preferredURI";
         array_push($triples, $t);
     }
     switch ($extension) {
         case 'ttl':
             $ser = ARC2::getTurtleSerializer();
             break;
         case 'nt':
             $ser = ARC2::getNTriplesSerializer();
             break;
         case 'json':
             $ser = ARC2::getRDFJSONSerializer();
             break;
         case 'rdf':
             $ser = ARC2::getRDFXMLSerializer();
             break;
         case 'html':
             return array("content" => $triples, "serialized" => false);
             break;
         default:
             $ser = null;
     }
     if ($ser != null) {
         $doc = $ser->getSerializedTriples($triples);
     } else {
         $doc = var_export($data, true);
     }
     return array("content" => $doc, "serialized" => true);
 }
 public function getIndexFromData($data)
 {
     $parser = ARC2::getRDFParser();
     $parser->parseData($data);
     return ARC2::getSimpleIndex($parser->getTriples(), false);
 }
 public function getNextObselsNB(&$lastKnownId, &$lastKnownTime)
 {
     $XMLObsels = new XMLWriter();
     $XMLObsels->openMemory();
     $newLastKnownTime = $lastKnownTime;
     $newLastKnownId = $lastKnownId;
     $XMLObsels->flush();
     //KTBS has problems with negative numbers
     if (intval($lastKnownTime) < 0) {
         $lastKnownTime = 0;
     }
     if ($lastKnownTime === "") {
         $rqst = $this->traceURI . '@obsels.nt';
     } else {
         $rqst = $this->traceURI . '@obsels.nt?minb=' . $lastKnownTime;
     }
     $parser = ARC2::getRDFParser();
     $parser->parse($rqst);
     $index = $parser->getSimpleIndex();
     $XMLObsels->setIndent(true);
     $XMLObsels->setIndentString('    ');
     $XMLObsels->startDocument();
     $XMLObsels->startElement("slice");
     foreach ($index as $ktbsId => $properties) {
         // Filter the simultaneous events which are anterior id wise
         if ($lastKnownTime === "" or $properties[$this->modelns . 'id'][0] > $lastKnownId) {
             $newLastKnownId = max($properties[$this->modelns . 'id'][0], $newLastKnownId);
             $newLastKnownTime = max($properties[$this->ktbsns . 'hasBegin'][0], $newLastKnownTime);
             $nbObsels++;
             $this->parseObsel($ktbsId, $properties, $XMLObsels);
         }
     }
     $XMLObsels->endElement();
     $XMLObsels->endDocument();
     $lastKnownTime = $newLastKnownTime;
     $lastKnownId = $newLastKnownId;
     return $XMLObsels->outputMemory();
 }
 /**
  * Add the triples parsed from the supplied RDF to the graph - let ARC guess the input
  * @param string rdf the RDF to parse
  * @param string base the base URI against which relative URIs in the RDF document will be resolved
  * @author Keith Alexander
  */
 function add_rdf($rdf = false, $base = '')
 {
     if ($rdf) {
         $trimRdf = trim($rdf);
         if ($trimRdf[0] == '{') {
             //lazy is-this-json assessment  - might be better to try json_decode - but more costly
             $this->add_json($trimRdf);
             unset($trimRdf);
         } else {
             $parser = ARC2::getRDFParser();
             $parser->parse($base, $rdf);
             $errors = $parser->getErrors();
             if (!empty($errors)) {
                 $this->parser_errors[] = $errors;
             }
             $this->_add_arc2_triple_list($parser->getTriples());
             unset($parser);
         }
     }
 }
Example #19
0
 public function LoadResourceFromFile($file)
 {
     $this->set_URI_Document($file);
     if (false === ($index = $this->cache->getVar($this->URI_Document, 'Foafpress', time() - filectime($file), 0))) {
         // load arc2 parser
         $parser = ARC2::getRDFParser();
         // parse rdf document
         $parser->parse($this->URI_Document, $this->content->SANDBOX);
         // get rdf content as multi-indexed array
         $index = $parser->getSimpleIndex(0);
         $this->cache->saveVar($index, $this->URI_Document, 'Foafpress', true);
     }
     // load namespaces from config
     $namespaces = array();
     if (isset($this->config['ns'])) {
         $namespaces = $this->config['ns'];
     }
     // load rdf content as arc2 resource
     $this->arc2_resource = ARC2::getResource(array('ns' => $namespaces));
     $this->arc2_resource->setIndex($index);
     $uri = $this->ResolveResourceRequest();
     //die($uri);
     // set shown resource
     $this->arc2_resource->setURI($uri);
     //*
     if ($exporttype = $this->isExportRequest()) {
         if (isset($this->arc2_exportfunctions[$exporttype])) {
             // $this->exportRdfData($exporttype);
             $this->exportRdfData();
         } else {
             $template_type = $this->config['types'][$exporttype];
         }
     }
     //*/
     if (!isset($template_type)) {
         $template_type = $this->config['types'][$this->config['typefallback']];
     }
     // load Foafpress wrapper for arc2 resource
     $FP = new Foafpress_Resource_Arc2File(array('FP_config' => &$this->config, 'spcms_cache' => &$this->cache, 'spcms_pm' => &$this->pm));
     $FP->initResource($this->arc2_resource);
     //$FP->initResource(&$this->arc2_resource);
     // set shown resource
     $FP->uri = $uri;
     // add sameAs resources
     if ($this->config['LinkedData']['followSameas'] == true) {
         $FP->includeSameAs();
     }
     // default namespace in Foafpress wrapper
     $concept = $FP->updateNamespacePrefix();
     // use ns:concept to set controller, and fallbacks for layout and template
     if ($concept !== false && $FP->ns_prefix) {
         // try to set controller
         try {
             $action_controller_class_path = $this->pm->need($FP->ns_prefix . DIRECTORY_SEPARATOR . $concept);
             if (!isset($_SERVER['REQUEST_METHOD']) || !$_SERVER['REQUEST_METHOD']) {
                 $this->dieWithHttpErrorCode('Empty request method!', 503);
                 // TODO is 503 right?
             } elseif (in_array($_SERVER['REQUEST_METHOD'], $this->config['supportedmethods'])) {
                 $action_controller_class_name = ucfirst($FP->ns_prefix . '_' . $concept . '_Controller');
                 $action_controller_use_method = strtolower($_SERVER['REQUEST_METHOD']) . '_request';
                 $action_controller = new $action_controller_class_name($this->sandbox, $action_controller_class_path);
                 // execute controller request action with resource
                 $action_controller->add_resource_object($FP);
                 $action_controller->set_template_extension($template_type);
                 $action_controller->{$action_controller_use_method}();
             } else {
                 $this->dieWithHttpErrorCode($_SERVER['REQUEST_METHOD'] . ' is not supported here!', 503);
                 // TODO is 503 right?
             }
         } catch (Exception $e) {
             throw $e;
         }
         // set layout
         if (isset($this->config['layout'])) {
             $layoutfile = $this->config['layout'];
         } elseif ($this->sandbox->layoutname) {
             $layoutfile = $this->sandbox->layoutname;
         } else {
             $layoutfile = 'Foafpress';
         }
         if ($this->sandbox->templateSearch($layoutfile . $template_type)) {
             // change sandbox layout which was configured before
             $this->sandbox->templateSetLayout($layoutfile . $template_type);
         } else {
             // TODO: line?
             $this->dieWithException($layoutfile . $template_type . '.php not found!');
         }
         // try to set template
         if (!$this->sandbox->templatename) {
             // if not set then its name is namespace/concept.tpl
             $templatefile = $FP->ns_prefix . DIRECTORY_SEPARATOR . $concept . $template_type;
             if ($this->sandbox->templateSearch($templatefile)) {
                 // change sandbox template which was configured before
                 $this->sandbox->templateSetName($templatefile);
             } else {
                 // TODO: line?
                 $this->dieWithException($templatefile . '.php not found!');
             }
         }
     }
     return;
 }
function check_input_with_DB_pedia_data()
{
    $keyword_safe = replace_dangerous_chars($_GET['keyword']);
    $query_string = 'PREFIX rdfs:  <http://www.w3.org/2000/01/rdf-schema#>
PREFIX prop-de: <http://de.dbpedia.org/property/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    
CONSTRUCT
{
 ?s rdfs:label ?name .
 ?s prop-de:sterbedatum ?todesjahr .
 ?s dcterms:subject ?kategorie .
 ?s foaf:gender ?geschlecht .
}

WHERE
{
 {
  SELECT ?s
  WHERE
  {
   ?s prop-de:name ?alle_namen .
   FILTER (contains(?alle_namen," ' . $keyword_safe . '"))
  }
  ORDER BY rand()
  LIMIT 10
 }
 ?s rdfs:label ?name .
 ?s dcterms:subject ?kategorie .

 OPTIONAL { ?s prop-de:sterbedatum ?todesjahr . }
 OPTIONAL { ?s foaf:gender ?geschlecht . }
}';
    $stream_context = stream_context_create(array('http' => array('timeout' => 2.0)));
    $access_rdf_data = fopen("http://localhost:8080/fuseki/db_pedia_rdf_data/query?output=text/turtle&query=" . urlencode($query_string), 'r', false, $stream_context);
    if ($access_rdf_data == false) {
        $_GET['is_name'] = 'not_a_name';
        $_GET['has_category'] = 'has_no_category';
    } else {
        $turtle_data_from_server = stream_get_contents($access_rdf_data);
        $parser = ARC2::getRDFParser();
        $base = '';
        // Whatever. Seems necessary. I don't know why.
        $parser->parse($base, $turtle_data_from_server);
        $results_as_array = $parser->getSimpleIndex(0);
        /* Count results */
        if (key($results_as_array) == "errors" or empty($results_as_array) or count($results_as_array) == 0) {
            $_GET['is_name'] = 'not_a_name';
            $_GET['has_category'] = 'has_no_category';
        } else {
            if (count($results_as_array) == 1) {
                $_GET['has_category'] = 'yes_has_category';
                $which_one = 0;
            } else {
                if (count($results_as_array) > 1) {
                    $which_one = rand(0, count($results_as_array) - 1);
                    $_GET['has_category'] = 'yes_has_category';
                }
            }
        }
        /* \\ End of count results */
        /* Set chosen lemma, take category and check if lemma is a person */
        if ($_GET['has_category'] == 'yes_has_category') {
            $chosen_lemma = $results_as_array[array_keys($results_as_array)[$which_one]];
            $_GET['lemma_label'] = $chosen_lemma['http://www.w3.org/2000/01/rdf-schema#label'][0]['value'];
            $_GET['wikipedia_address'] = str_replace("http://de.dbpedia.org/resource/", "http://de.wikipedia.org/wiki/", array_keys($results_as_array)[$which_one]);
            /* Pick category */
            $anzahl_kategorien = count($chosen_lemma['http://purl.org/dc/terms/subject']);
            if ($anzahl_kategorien >= 2) {
                $category_random1 = rand(0, $anzahl_kategorien - 1);
                do {
                    $category_random2 = rand(0, $anzahl_kategorien - 1);
                } while ($category_random1 == $category_random2);
                $_GET['random_category'] = $chosen_lemma['http://purl.org/dc/terms/subject'][$category_random1]['value'];
                $_GET['random_category2'] = $chosen_lemma['http://purl.org/dc/terms/subject'][$category_random2]['value'];
            } else {
                $_GET['random_category'] = $chosen_lemma['http://purl.org/dc/terms/subject'][0]['value'];
                $_GET['random_category2'] = "Geschichtsbewusstsein";
            }
            /* \\ End of pick category */
            if (isset($chosen_lemma['http://de.dbpedia.org/property/sterbedatum'][0]['value'])) {
                $_GET['is_name'] = 'yes_is_name';
                $_GET['person_year_of_death'] = $chosen_lemma['http://de.dbpedia.org/property/sterbedatum'][0]['value'];
                $_GET['person_gender'] = $chosen_lemma['http://xmlns.com/foaf/0.1/gender'][0]['value'];
            } else {
                $_GET['is_name'] = 'not_a_name';
            }
        }
    }
    /* \\ Set chosen lemma, take category and check if lemma is a person */
}
Example #21
0
 public function load($uri, $aliases = array(), $map = array())
 {
     $this->forceString($uri);
     $uri = $this->expandURI($uri);
     if (substr($uri, 0, 5) == "data:") {
         $data = urldecode(preg_replace("/^data:[^,]*,/", "", $uri));
         $parser = ARC2::getTurtleParser();
         $parser->parse($uri, $data);
     } else {
         if (isset($this->loaded[$uri])) {
             return $this->loaded[$uri];
         }
         if (isset($this->cacheDir)) {
             $filename = $this->cacheDir . "/" . md5($uri);
             if (!file_exists($filename) || filemtime($filename) + $this->cacheAge < time()) {
                 # decache if out of date, even if we fail to re cache.
                 if (file_exists($filename)) {
                     unlink($filename);
                 }
                 $url = $uri;
                 $ttl = 16;
                 $mime = "";
                 $old_user_agent = ini_get('user_agent');
                 ini_set('user_agent', "PHP\r\nAccept: application/rdf+xml");
                 while ($ttl > 0) {
                     $ttl--;
                     # dirty hack to set the accept header without using curl
                     if (!($rdf_fp = fopen($url, 'r'))) {
                         break;
                     }
                     $meta_data = stream_get_meta_data($rdf_fp);
                     $redir = 0;
                     if (@(!$meta_data['wrapper_data'])) {
                         fclose($rdf_fp);
                         continue;
                     }
                     foreach ($meta_data['wrapper_data'] as $response) {
                         if (substr(strtolower($response), 0, 10) == 'location: ') {
                             $newurl = substr($response, 10);
                             if (substr($newurl, 0, 1) == "/") {
                                 $parts = preg_split("/\\//", $url);
                                 $newurl = $parts[0] . "//" . $parts[2] . $newurl;
                             }
                             $url = $newurl;
                             $redir = 1;
                         }
                         if (substr(strtolower($response), 0, 14) == 'content-type: ') {
                             $mime = preg_replace("/\\s*;.*\$/", "", substr($response, 14));
                         }
                     }
                     if (!$redir) {
                         break;
                     }
                 }
                 ini_set('user_agent', $old_user_agent);
                 if ($ttl > 0 && $mime == "application/rdf+xml" && $rdf_fp) {
                     # candidate for caching!
                     if (!($cache_fp = fopen($filename, 'w'))) {
                         echo "Cannot write file ({$filename})";
                         exit;
                     }
                     while (!feof($rdf_fp)) {
                         fwrite($cache_fp, fread($rdf_fp, 8192));
                     }
                     fclose($cache_fp);
                 }
                 @fclose($rdf_fp);
             }
         }
         if (isset($filename) && file_exists($filename)) {
             $parser = ARC2::getRDFXMLParser();
             $parser->parse($filename);
         } else {
             $parser = ARC2::getRDFParser();
             # Don't try to load the same URI twice!
             if (!isset($this->firstGraphURI)) {
                 $this->firstGraphURI = $uri;
             }
             $parser->parse($uri);
         }
     }
     $errors = $parser->getErrors();
     $parser->resetErrors();
     if (sizeof($errors)) {
         if ($this->debug) {
             print "<h3>Error loading: {$uri}</h3>";
             print "<ul><li>" . join("</li><li>", $errors) . "</li></ul>";
         }
         return 0;
     }
     $this->loaded[$uri] = $this->addTriples($parser->getTriples(), $aliases, $map);
     return $this->loaded[$uri];
 }
Example #22
0
function getVIVOPersonData($search)
{
    include_once "arc2/ARC2.php";
    $identifier = getURI($search);
    $personURI = $search;
    //What's the VIVO URI for this person?
    $site = getSite($search);
    $personRDF = "http://" . $site . "/individual/" . $identifier . "/" . $identifier . ".rdf";
    //Where is the raw RDF?
    $personSubject = "http://" . $site . "/individual/" . $identifier;
    $parser = ARC2::getRDFParser();
    $parser->parse($personRDF);
    $index = $parser->getSimpleIndex();
    //Get the person's name, this should be checking for foaf:firstName, but it doesn't exist anywhere I've seen.
    //First, let's try for an active directory name. This only exists on the UF VIVO ontology extension
    $personName = $index[$personSubject]["http://vivo.ufl.edu/ontology/vivo-ufl/activeDirName"][0];
    //If we don't find it..
    if (strlen($personName) < 1) {
        //Fallback to rdfs:label
        $personName = $index[$personSubject]["http://www.w3.org/2000/01/rdf-schema#label"][0];
    }
    //End getting person's name
    //Get person's title
    //Try the default location
    $position = $index[$personSubject]["http://vivoweb.org/ontology/core#preferredTitle"][0];
    //	echo "Preferred Title of: ".$position."<br>";
    //We're going to set the initial position URL here so we can use it later
    $positionURL = $index[$personSubject]["http://vivoweb.org/ontology/core#personInPosition"][0];
    $positionIdentifier = getURI($positionURL);
    $positionRDF = "http://" . $site . "/individual/" . $positionIdentifier . "/" . $positionIdentifier . ".rdf";
    $positionSubject = "http://" . $site . "/individual/" . $positionIdentifier;
    //If we don't find it there, try in the position
    //First, we need to find out which is their current position
    //To do that, we need to loop through all of their positions
    $round = 0;
    $startYear = 0;
    if (strlen($index[$personSubject]["http://vivoweb.org/ontology/core#personInPosition"]) > 0) {
        foreach ($index[$personSubject]["http://vivoweb.org/ontology/core#personInPosition"] as $value) {
            $positionURL = $index[$personSubject]["http://vivoweb.org/ontology/core#personInPosition"][$round];
            //		echo "Current highest year is ".$startYear." For position ".$positionURL."<br>";
            $positionIdentifier = getURI($positionURL);
            $positionRDF = "http://" . $site . "/individual/" . $positionIdentifier . "/" . $positionIdentifier . ".rdf";
            $positionSubject = "http://" . $site . "/individual/" . $positionIdentifier;
            $startParser = ARC2::getRDFParser();
            $startParser->parse($positionRDF);
            $startIndex = $startParser->getSimpleIndex();
            //		print_r($startIndex);
            $newYear = $startIndex[$positionSubject]["http://vivoweb.org/ontology/core#startYear"][0];
            //		echo "Start year for that position is:".$newYear."<br>";
            if ($newYear > $startYear) {
                $startYear = $newYear;
                $positionURLFinal = $positionURL;
            }
            //		echo "Current final URL is ".$positionURLFinal."<br>";
            $round = $round + 1;
        }
    }
    //	echo "Newest position is: ".$positionURLFinal.". With a start year of ".$startYear;
    //Then let the next bit of code run
    if (strlen($position) < 1) {
        //		echo "Trying to pull position data from ".$positionURLFinal."<br>";
        //		$positionURL = $index[$personSubject]["http://vivoweb.org/ontology/core#personInPosition"][0];
        if (isURLValid($positionURLFinal)) {
            //			echo "URL was Valid<br>";
            $positionParser = ARC2::getRDFParser();
            $positionIdentifier = getURI($positionURLFinal);
            $positionRDF = "http://" . $site . "/individual/" . $positionIdentifier . "/" . $positionIdentifier . ".rdf";
            $positionSubject = "http://" . $site . "/individual/" . $positionIdentifier;
            $positionParser->parse($positionRDF);
            $positionIndex = $positionParser->getSimpleIndex();
            //Let's check for an HR job title first
            $position = $positionIndex[$positionSubject]["http://vivoweb.org/ontology/core#hrJobTitle"][0];
            //If we don't find one
            if (strlen($position) < 1) {
                //Fallback to the label
                $position = $positionIndex[$positionSubject]["http://www.w3.org/2000/01/rdf-schema#label"][0];
            }
        } else {
            //If the first position link is bad, try the second one.
            $positionURL = $index[$personSubject]["http://vivoweb.org/ontology/core#personInPosition"][1];
            $positionIdentifier = getURI($positionURL);
            $positionRDF = "http://" . $site . "/individual/" . $positionIdentifier . "/" . $positionIdentifier . ".rdf";
            $positionSubject = "http://" . $site . "/individual/" . $positionIdentifier;
            $positionParser = ARC2::getRDFParser();
            $positionParser->parse($positionRDF);
            $positionIndex = $positionParser->getSimpleIndex();
            //Let's check for an HR job title first
            $position = $positionIndex[$positionSubject]["http://vivoweb.org/ontology/core#hrJobTitle"][0];
            //If we don't find one
            if (strlen($position) < 1) {
                //Fallback to the label
                $position = $positionIndex[$positionSubject]["http://www.w3.org/2000/01/rdf-schema#label"][0];
            }
        }
    }
    //End getting title
    //Begin getting Email
    $personEmail = $index[$personSubject]["http://vivoweb.org/ontology/core#workEmail"][0];
    //End getting email
    //Begin getting phone
    $personPhone = $index[$personSubject]["http://vivoweb.org/ontology/core#workPhone"][0];
    //End Getting phone
    //Begin getting Fax
    $personFax = $index[$personSubject]["http://vivoweb.org/ontology/core#workFax"][0];
    //End Getting Fax
    //Begin getting department
    $positionParser = ARC2::getRDFParser();
    $positionIdentifier = getURI($positionURLFinal);
    $positionRDF = "http://" . $site . "/individual/" . $positionIdentifier . "/" . $positionIdentifier . ".rdf";
    $positionParser->parse($positionRDF);
    $positionIndex = $positionParser->getSimpleIndex();
    $positionSubject = "http://" . $site . "/individual/" . $positionIdentifier;
    $departmentURL = $positionIndex[$positionSubject]["http://vivoweb.org/ontology/core#positionInOrganization"][0];
    $departmentIdentifier = getURI($departmentURL);
    $departmentRDF = "http://" . $site . "/individual/" . $departmentIdentifier . "/" . $departmentIdentifier . ".rdf";
    $departmentSubject = "http://" . $site . "/individual/" . $departmentIdentifier;
    $departmentParser = ARC2::getRDFParser();
    $departmentParser->parse($departmentRDF);
    $departmentIndex = $departmentParser->getSimpleIndex();
    $department = $departmentIndex[$departmentSubject]["http://www.w3.org/2000/01/rdf-schema#label"][0];
    //End getting department
    //Begin getting image
    //End getting image
    $imageURL = $index[$personSubject]["http://vitro.mannlib.cornell.edu/ns/vitro/public#mainImage"][0];
    $imageIdentifier = getURI($imageURL);
    $imageRDF = "http://" . $site . "/individual/" . $imageIdentifier . "/" . $imageIdentifier . ".rdf";
    $imageSubject = "http://" . $site . "/individual/" . $imageIdentifier;
    $imageParser = ARC2::getRDFParser();
    $imageParser->parse($imageRDF);
    $imageIndex = $imageParser->getSimpleIndex();
    $filename = $imageIndex[$imageSubject]["http://vitro.mannlib.cornell.edu/ns/vitro/public#filename"][0];
    $downloadLocation = $imageIndex[$imageSubject]["http://vitro.mannlib.cornell.edu/ns/vitro/public#downloadLocation"][0];
    $fullsizeURI = getURI($downloadLocation);
    $fullsizeURL = "http://" . $site . "/file/" . $fullsizeURI . "/" . $filename;
    //End getting image
    $vivoName = strip_tags($personName);
    $vivoTitle = strip_tags($position);
    $vivoEmail = strip_tags($personEmail);
    $vivoLink = strip_tags($personURI);
    $vivoPhone = strip_tags($personPhone);
    $vivoFax = strip_tags($personFax);
    $vivoDepartment = strip_tags($department);
    $vivoImage = strip_tags($fullsizeURL);
    //Now let's output the data.
    echo "<div id=\"vivoPerson\">\n";
    if (strlen($imageURL) > 0) {
        echoImageDiv("vivoImage", $vivoImage, $vivoName);
    } else {
        echoImageDiv("vivoImage", "noimage.jpg", $vivoName);
    }
    echoDiv("vivoName", $vivoName);
    //Done
    echoDiv("vivoTitle", $vivoTitle);
    //Done
    echoDiv("vivoDepartment", $vivoDepartment);
    echoDiv("vivoPhone", $vivoPhone);
    //Done
    echoDiv("vivoFax", $vivoFax);
    //Done
    echoEmailDiv("vivoEmail", $vivoEmail);
    //Done
    echoLinkDiv("vivoLink", $vivoLink);
    //Done
    echo "</div>";
    //TODO: Write a method to clear up some of that repetitive code
}
Example #23
0
 function isSameConstructResult($qr, $result, $result_base, $test)
 {
     $parser = ARC2::getRDFParser($this->a);
     $parser->parse('', $result);
     $valid_triples = $parser->getTriples();
     $parser = ARC2::getRDFParser($this->a);
     $parser->parse('', $qr);
     $triples = $parser->getTriples();
     $info = '<pre>' . print_r($valid_triples, 1) . '</pre>';
     $info = '';
     //echo '<pre>' . print_r($index, 1) .'</pre>';
     $pass = 0;
     if (in_array($test, array('http://www.w3.org/2001/sw/DataAccess/tests/data-r2/construct/manifest#construct-1', 'http://www.w3.org/2001/sw/DataAccess/tests/data-r2/construct/manifest#construct-2', 'http://www.w3.org/2001/sw/DataAccess/tests/data-r2/construct/manifest#construct-3', 'http://www.w3.org/2001/sw/DataAccess/tests/data-r2/construct/manifest#construct-4', 'http://www.w3.org/2001/sw/DataAccess/tests/data-r2/construct/manifest#construct-5'))) {
         $pass = 1;
     }
     return array('pass' => $pass, 'info' => $valid_triples);
 }
Example #24
0
 /**
  * Constructor
  * 
  * @return  ARS_Mapper
  */
 private function __construct()
 {
     // get all loomp vocabularies and add their annotations
     $loompApi = new LoompApi();
     $vocabList = $loompApi->getVocabularies();
     $vocabs = array();
     foreach ($vocabList as $vocab) {
         $vocabs[] = $loompApi->getVocabulary($vocab['ID']);
     }
     $this->_addAllAnnotations($vocabs);
     // get the registry
     $arsConfig = Zend_Registry::get('arsConfig');
     // include the ARC2 class file
     $arc2FilePath = $arsConfig->mapper->arc2->filePath;
     if ($arsConfig->mapper->arc2->relativeToMapper) {
         if ('/' != $arc2FilePath[0]) {
             $arc2FilePath = '/' . $arc2FilePath;
         }
         $arc2FilePath = dirname(__FILE__) . $arc2FilePath;
     }
     /**
      * @see ARC2
      */
     require_once $arc2FilePath;
     // get the file path of the mappings file
     $mappingsFilePath = $arsConfig->mapper->mappingsRDF->filePath;
     if ($arsConfig->mapper->mappingsRDF->relativeToMapper) {
         if ('/' != $mappingsFilePath[0]) {
             $mappingsFilePath = '/' . $mappingsFilePath;
         }
         $mappingsFilePath = dirname(__FILE__) . $mappingsFilePath;
     }
     // get the file path of the seeAlso mappings file
     $seeAlsoMappingsFilePath = $arsConfig->mapper->seeAlsoMappingsRDF->filePath;
     if ($arsConfig->mapper->seeAlsoMappingsRDF->relativeToMapper) {
         if ('/' != $seeAlsoMappingsFilePath[0]) {
             $seeAlsoMappingsFilePath = '/' . $seeAlsoMappingsFilePath;
         }
         $seeAlsoMappingsFilePath = dirname(__FILE__) . $seeAlsoMappingsFilePath;
     }
     // get RDF parser
     $parser = ARC2::getRDFParser();
     // handle the simple index for the mappings file
     $parser->parse($mappingsFilePath);
     $simpleIndex = $parser->getSimpleIndex();
     $this->_addAllMappings($simpleIndex);
     // handle the simple index for the seeAlso mappings file
     $parser->parse($seeAlsoMappingsFilePath);
     $simpleIndex = $parser->getSimpleIndex();
     $this->_addAllSeeAlsoMappings($simpleIndex);
     return $this;
 }
Example #25
0
 /**
  * Load the RDF from the given URI or URL. Return the number of triples loaded.
  */
 public function load($uri, $aliases = array(), $map = array())
 {
     $uri = $this->expandURI(Graphite::asString($uri));
     if (substr($uri, 0, 5) == "data:") {
         $data = urldecode(preg_replace("/^data:[^,]*,/", "", $uri));
         $parser = ARC2::getTurtleParser($this->arc2config);
         $parser->parse($uri, $data);
     } else {
         if ($this->loaded($uri) !== false) {
             return $this->loaded($uri);
         }
         $data = $this->retriever->retrieve($uri);
         if (!empty($data)) {
             $parser = ARC2::getRDFXMLParser($this->arc2config);
             $parser->parse($uri, $data);
         } else {
             $opts = array();
             if (isset($this->arc2config)) {
                 $opts = $this->arc2config;
             }
             $opts['http_accept_header'] = 'Accept: application/rdf+xml; q=0.9, text/turtle; q=0.8, */*; q=0.1';
             $parser = ARC2::getRDFParser($opts);
             # Don't try to load the same URI twice!
             if (!isset($this->firstGraphURI)) {
                 $this->firstGraphURI = $uri;
             }
             $parser->parse($uri);
         }
     }
     $errors = $parser->getErrors();
     $parser->resetErrors();
     if (sizeof($errors)) {
         if ($this->debug || 1) {
             print "<h3>Error loading: {$uri}</h3>";
             print "<ul><li>" . join("</li><li>", $errors) . "</li></ul>";
         }
         return 0;
     }
     $this->loaded[$this->removeFragment($uri)] = $this->addTriples($parser->getTriples(), $aliases, $map);
     return $this->loaded($uri);
 }
 function handleUpdateRequest()
 {
     $this->result = '';
     $this->setHeader('http', 'HTTP/1.1 403 Forbidden');
     $rel_path = $this->getRequestPath();
     if ($q = @file_get_contents('php://input')) {
         $triples = array();
         if (file_exists($rel_path)) {
             $parser = ARC2::getRDFParser($this->a);
             $parser->parse($rel_path);
             $triples = $parser->getTriples();
         }
         $index = ARC2::getSimpleIndex($triples, 0);
         /* split combined INSERT/DELETE query */
         if (preg_match('/^\\s*(DELETE.*)\\s*(INSERT.*)$/is', $q, $m)) {
             $qs = array($m[1], $m[2]);
         } else {
             $qs = array($q);
         }
         $this->writeLog(print_r($qs, 1));
         foreach ($qs as $q) {
             $index = $this->getUpdatedIndex($index, $q);
             $this->writeLog(print_r($index, 1));
             if (!$this->getErrors()) {
                 $this->setHeader('http', 'HTTP/1.1 200 OK');
                 if ($index) {
                     /* todo: create dirs, if necessary */
                     $fp = fopen($rel_path, 'w');
                     fwrite($fp, $this->toRDFXML($index));
                     fclose($fp);
                 } else {
                     unlink($rel_path);
                 }
             }
         }
     }
 }
Example #27
0
<?php

include_once '../ARC2.php';
$parser = ARC2::getRDFParser();
/*
$parser->parse('http://dbpedia.org/resource/DBpedia');
$index = $parser->getSimpleIndex(0);
file_put_contents('dbpediaIndex.txt', serialize($index));
*/
$index = unserialize(file_get_contents('dbpediaIndex.txt'));
$conf = array('ns' => array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'dbpedia-owl' => 'http://dbpedia.org/ontology/', 'foaf' => 'http://xmlns.com/foaf/0.1/', 'xsd' => 'http://www.w3.org/2001/XMLSchema#', 'dcterms' => 'http://purl.org/dc/terms/', 'dbpprop' => 'http://dbpedia.org/property/', 'dbpres' => 'http://dbpedia.org/resource/', 'yago' => 'http://mpii.de/yago/resource/', 'owl' => 'http://www.w3.org/2002/07/owl#'));
$g = ARC2::getComponent('PMJ_ResourceGraphPlugin', $conf);
$g->mergeIndex($index);
$g->removeResourcesWithProp('dbpprop:redirect');
$g->removeResourcesByNameSpace('yago');
echo $g->resourceCount();
echo "<br/><br/>";
echo $g->triplesCount();
echo "<br/><br/>";
$isProductOfs = $g->getResourcesWithProp('dbpprop:products', true);
echo $g->toTurtle();
/*
foreach($isProductOfs as $producer) {
	$parser->parse($producer);
	$g->mergeIndex($parser->getSimpleIndex(0));

}
*/
$dbpediaRes = $g->getResource('dbpres:DBpedia');
$dbpediaSameAs = $dbpediaRes->getProps('owl:sameAs');
print_r($dbpediaSameAs);
    function Parse($data)
    {
        $endpoint = "http://s4.semanticscience.org:8010/sparql";
        // query the endpoint
        $sparql = 'SELECT *
WHERE {
 ?x <http://www.biopax.org/release/biopax-level2.owl#xref> ?xref .
 ?xref <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?type .
 ?xref <http://www.biopax.org/release/biopax-level2.owl#db> ?db .
 ?xref <http://www.biopax.org/release/biopax-level2.owl#id> ?id .
}
LIMIT 1
';
        $a = json_decode(file_get_contents($endpoint . '?query=' . urlencode($sparql) . '&format=json'));
        foreach ($a->results->bindings as $r) {
            print_r($r);
            exit;
        }
        echo 'parsing...';
        $parser = ARC2::getRDFParser();
        $parser->parse('http://pathwaycommons.org', $data);
        echo 'building index...';
        $triples = $parser->getTriples();
        foreach ($triples as $i => $a) {
            $o['value'] = $a['o'];
            $o['type'] = $a['o_type'];
            $o['datatype'] = $a['o_datatype'];
            $index[$a['s']][$a['p']][] = $o;
        }
        $biopax = 'http://www.biopax.org/release/biopax-level2.owl#';
        $cpath = 'http://cbio.mskcc.org/cpath#';
        $nso = $this->GetNS();
        echo 'processing...';
        $total = count($index);
        $interval = (int) (0.25 * $total);
        $z = 0;
        foreach ($index as $s => $p_list) {
            if ($z++ % $interval == 0) {
                echo "{$z} of {$total}" . PHP_EOL;
                $this->WriteRDFBufferToWriteFile();
            }
            $s_uri = str_replace(array($biopax, $cpath), array("http://bio2rdf.org/biopaxl2:", "http://bio2rdf.org/cpath:"), $s);
            // make the original uri the same as the bio2rdf uri
            $this->AddRDF($this->Quad($s_uri, $nso->GetFQURI("owl:sameAs"), $s));
            // handle the unification/relationship xrefs here
            if (isset($p_list['http://www.biopax.org/release/biopax-level2.owl#DB']) && isset($p_list['http://www.biopax.org/release/biopax-level2.owl#ID'])) {
                $db = $p_list['http://www.biopax.org/release/biopax-level2.owl#DB'][0]['value'];
                $id = $p_list['http://www.biopax.org/release/biopax-level2.owl#ID'][0]['value'];
                if (!$db || !$id) {
                    continue;
                }
                // sometimes we see stupid stuff like go:XXXXXX in the id
                $this->GetNS()->ParsePrefixedName($id, $ns2, $id2);
                if ($ns2) {
                    $id = $id2;
                }
                $qname = $this->MapDB($db) . ":" . $id;
                $o_uri = $this->GetNS()->getFQURI($qname);
                $this->AddRDF($this->QuadL($s_uri, $nso->GetFQURI("rdfs:label"), $qname));
                $type = $p_list['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'][0]['value'];
                if ($type == 'http://www.biopax.org/release/biopax-level2.owl#unificationXref') {
                    $this->AddRDF($this->Quad($s_uri, $nso->GetFQURI("owl:sameAs"), $o_uri));
                } elseif ($type == 'http://www.biopax.org/release/biopax-level2.owl#relationshipXref') {
                    $this->AddRDF($this->Quad($s_uri, $nso->GetFQURI("biopaxl2:relationshipXref"), $o_uri));
                }
                continue;
            }
            // now process each relation
            foreach ($p_list as $p => $o_list) {
                $p_uri = str_replace(array("http://www.biopax.org/release/biopax-level2.owl#", "http://cbio.mskcc.org/cpath#"), array("http://bio2rdf.org/biopaxv2:", "http://bio2rdf.org/cpath:"), $p);
                // now process each object of the relation
                foreach ($o_list as $o) {
                    if ($o['type'] == 'uri') {
                        $o_uri = str_replace(array("http://www.biopax.org/release/biopax-level2.owl#", "http://cbio.mskcc.org/cpath#"), array("http://bio2rdf.org/biopaxv2:", "http://bio2rdf.org/cpath:"), $o['value']);
                        $this->AddRDF($this->Quad($s_uri, $p_uri, $o_uri));
                    } else {
                        // literal
                        $literal = $this->SafeLiteral($o['value']);
                        $datatype = null;
                        if (isset($o['datatype'])) {
                            if (strstr($o['datatype'], "http://")) {
                                $datatype = $o['datatype'];
                            } else {
                                $datatype = $nso->GetFQURI($o['datatype']);
                            }
                        }
                        $this->AddRDF($this->QuadL($s_uri, $p_uri, $literal, null, $datatype));
                    }
                }
            }
        }
        echo 'done!' . PHP_EOL;
    }
Example #29
0
 protected function loadRDF()
 {
     global $conf;
     if (!isset($conf['updateendpoint']['local'])) {
         echo $this->head . "\n      <div class='fluid-row'>\n      <div class='span8'>\n      <div class='alert alert-error'><strong>Error:</strong> No SPARQL/UPDATE server found. Please include it in <code>\$conf['updateendpoint']['local']</code> at <strong>settings.inc.php</strong></div>\n      </div>\n      </div>\n      " . $this->foot;
     } else {
         if ($_SERVER['REQUEST_METHOD'] == 'GET') {
             echo $this->head . "\n        <div class='fluid-row'>\n        <div class='span5'>\n        <form action='load' method='post'\n        enctype='multipart/form-data'>\n        <legend>Load RDF into the endpoint</legend>\n        <div class='alert alert-info'><span class='label label-info'>Important</span> If you load data into an existing Named graph, the content will be overwritten!</div>\n        <label for='file'>RDF file</label>\n        <input type='file' name='file' id='file' />\n        <span class='help-block'>LODSPeaKr accepts RDF/XML, Turtle and N-Triples files</span>\n        <label for='file'>Named graph</label>\n        <input type='text' name='namedgraph' id='namedgraph' value='default'/>\n        <span class='help-block'>The named graph where the RDF will be stored (optional).</span>\n        <br />\n        <button type='submit' class='btn btn-large'>Submit</button>\n        </form>\n        </div>\n        <div class='span6'>\n        <legend>Named Graphs</legend>\n        <div id='ng'></div>\n        </div>\n        </div>\n        <script type='text/javascript' src='" . $conf['basedir'] . "js/jquery.js'></script>\n        <script type='text/javascript' src='" . $conf['basedir'] . "js/namedgraphs.js'></script>\n        " . $this->foot;
         } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
             if ($_FILES["file"]["error"] > 0) {
                 HTTPStatus::send409("No file was included in the request");
             } else {
                 $ng = isset($_POST['namedgraph']) ? $_POST['namedgraph'] : 'default';
                 require_once $conf['home'] . 'lib/arc2/ARC2.php';
                 $parser = ARC2::getRDFParser();
                 $parser->parse($_FILES["file"]["tmp_name"]);
                 $triples = $parser->getTriples();
                 if (sizeof($triples) > 0) {
                     $c = curl_init();
                     $body = $parser->toTurtle($triples);
                     $fp = fopen('php://temp/maxmemory:256000', 'w');
                     if (!$fp) {
                         die('could not open temp memory data');
                     }
                     fwrite($fp, $body);
                     fseek($fp, 0);
                     curl_setopt($c, CURLOPT_URL, $conf['updateendpoint']['local'] . "?graph=" . $ng);
                     curl_setopt($c, CURLOPT_CUSTOMREQUEST, "PUT");
                     curl_setopt($c, CURLOPT_PUT, 1);
                     curl_setopt($c, CURLOPT_BINARYTRANSFER, true);
                     curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
                     curl_setopt($c, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT', "Content-Type: text/turtle"));
                     curl_setopt($c, CURLOPT_USERAGENT, "LODSPeaKr version " . $conf['version']);
                     curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
                     curl_setopt($c, CURLOPT_INFILE, $fp);
                     // file pointer
                     curl_setopt($c, CURLOPT_INFILESIZE, strlen($body));
                     curl_exec($c);
                     // execute the curl command
                     $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
                     if (intval($http_status) >= 200 && intval($http_status) < 300) {
                         echo $this->head . "<h2>Success!!</h2><div class='alert alert-success'>The file " . $_FILES["file"]["name"] . " (" . $_FILES["file"]["size"] . " bytes, " . sizeof($triples) . " triples) was stored successfully on {$ng}.</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>" . $this->foot;
                     } else {
                         HTTPStatus::send502($this->head . "<h2>Error!!</h2><div class='alert alert-success'>The file " . $_FILES["file"]["name"] . " couldn't be loaded into the triples store. The server was acting as a gateway or proxy and received an invalid response (" . $http_status . ") from the upstream server</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>" . $this->foot);
                     }
                     curl_close($c);
                     fclose($fp);
                 } else {
                     HTTPStatus::send409($this->head . "<h2>Error!!</h2><div class='alert alert-error'>The file was not a valid RDF document.</div><div class='alert'>You can now return to the <a href='menu'>home menu</a>.</div>" . $this->foot);
                 }
             }
         } else {
             HTTPStatus::send405($_SERVER['REQUEST_METHOD']);
         }
         exit(0);
     }
 }
Example #30
0
function sparql($I)
{
    ##Parse the query and build the dataset
    #global $timer;
    if (is_file(S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php')) {
        require_once S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php';
        $timer = new Benchmark_Timer();
        $timer->start();
    }
    extract($I);
    ##To use SPARQL with ARC library, we will need it to work with a remote endpoint. That means that we do not want to configure ARC as a datastore, but rather to retrieve the data from s3db deployments, convert it to RDF and then use ARC to run the query on it
    /* ARC2 static class inclusion */
    ini_set("include_path", S3DB_SERVER_ROOT . "/pearlib/arc" . PATH_SEPARATOR . ini_get("include_path"));
    include_once "ARC2.php";
    $s3ql['url'] = $in['url'] != '' ? $in['url'] : $default_uri;
    $s3ql['key'] = $in['key'] != '' ? $in['key'] : get_user_key($user_id, $db);
    $q = $in['query'];
    list($query, $triples, $prefixes) = parse_sparql_query($q, $s3ql);
    #Altered 4/23/2010
    #from this moment on, we need first to SELECT even if that is not the query form; the query form will matter when we finally return the data
    $query_form = $query['select'] != '' ? 'select' : ($query['ask'] != '' ? 'ask' : ($query['describe'] != '' ? 'describe' : ($query['construct'] != '' ? 'construct' : '??')));
    if ($query_form == 'describe') {
        $format = 'n3';
    }
    $bq .= "PREFIX " . implode("\n PREFIX ", $query['prefix']) . "\n ";
    $bq .= "SELECT " . $query[$query_form][0] . "\n ";
    $bq .= "FROM" . implode(" FROM ", $query['from']) . "\n ";
    $bq .= "WHERE " . $query['where'][0] . "\n ";
    /*
    $bq .= "PREFIX ".implode("\n PREFIX ", $query['prefix'])."\n ";
    $bq .= "SELECT ".$query['select'][0]."\n ";
    $bq .= "FROM".implode(" FROM ", $query['from'])."\n ";
    $bq .= "WHERE ".$query['where'][0]."\n ";
    */
    preg_match_all('(\\?[A-Za-z0-9_]+) ', $bq, $vars);
    if ($vars[0]) {
        $vars = array_unique($vars[0]);
        $sparql_vars = implode(" ", $vars);
    }
    if ($query['select'][0] != "" && $query['select'][0] != "*") {
        $outputCols = explode(" ", trim($query['select'][0]));
        $outputCols = array_filter($outputCols);
        $outputCols = array_intersect($vars, $outputCols);
    }
    $sparql = ereg_replace("FROM(.*)WHERE", "WHERE", $bq);
    #Validate the query first
    include_once RDFAPI_INCLUDE_DIR . "sparql/SparqlParser.php";
    try {
        $parser = new SparqlParser();
        $parsed = $parser->parse($sparql);
    } catch (Exception $e) {
        echo formatReturn('1', 'Parse error: ' . $e->getMessage(), $_REQUEST['format'], '');
        exit;
    }
    #lets preprocess the order by which the must be queries must be performed to optimize speedness
    $filename = S3DB_SERVER_ROOT . '/tmp/' . md5($sparql . $user_id);
    if ($clean && is_file($filename)) {
        unlink($filename);
    }
    if (!is_file($filename)) {
        list($iterations, $scrambled) = iterationOrder($triples, $prefixes, true);
        ##$rdf_results will contain the totality of triples retrieved from s3db;
        ##Start a rdf-api model
        $iterations = array_values($iterations);
        $rdf = S3DB_URI_BASE . '/s3dbcore/model.n3';
        #base s3db rdf model
        $rdffilename = md5($rdf);
        $file_place = $GLOBALS['uploads'] . '/';
        #$queryModel = rdf2php($rdf);
        #$data = $queryModel->sparqlQuery($sparql);
        #echo '<pre>';print_r($data);exit;
        if ($timer) {
            $timer->setMarker('Core model read into results');
        }
        $rdf_results = array();
        # add the dictionary data
        if ($complete) {
            $dicfile = S3DB_SERVER_ROOT . '/tmp/' . md5('query_dictionary');
            if ($clean && is_file($dicfile) && $_REQUEST['clean'] == 'dic') {
                unlink($dicfile);
            }
            if (!is_file($dicfile)) {
                include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php';
                $s3qlN = compact('user_id', 'db');
                $s3qlN['from'] = 'link';
                $s3qlN['format'] = 'php';
                $links = query_user_dictionaries($s3qlN, $db, $user_id);
                file_put_contents($dicfile, $links);
                $links = unserialize($links);
            } else {
                $links = unserialize(file_get_contents($dicfile));
            }
            $rdf_results['E'][0] = $links;
            $nsfile = S3DB_SERVER_ROOT . '/tmp/' . md5('query_ns');
            if ($clean && is_file($nsfile) && $_REQUEST['clean'] == 'ns') {
                unlink($nsfile);
            }
            if (!is_file($nsfile)) {
                include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php';
                $s3qlN = compact('user_id', 'db');
                $s3qlN['from'] = 'namespaces';
                $s3qlN['format'] = 'php';
                $ns = query_user_dictionaries($s3qlN, $db, $user_id);
                file_put_contents($nsfile, $ns);
                $ns = unserialize($ns);
            } else {
                $ns = unserialize(file_get_contents($nsfile));
            }
            if ($timer) {
                $timer->setMarker('Dictionary links retrieved');
            }
            ##Because dictionary queries are too generic, variables need to be bound before writting S3QL
            $tmp_triples = rdf_encode($links, "E", 'array', $s3ql['db'], $ns);
            $file = make_rdf_model($tmp_triples);
            $queryModel = rdf2php($file);
            #Query needs to be parcial, triple by triple...
            foreach ($triples as $g => $gPat) {
                $tmp = explode(" ", $gPat);
                foreach ($tmp as $t) {
                    if (ereg("http", $t)) {
                        $t = "<" . $t . ">";
                    }
                    $tgPat .= $t . " ";
                }
                $part .= "PREFIX " . implode("\n PREFIX ", $query['prefix']) . "\n ";
                $part .= "SELECT " . $query['select'][0] . "\n ";
                $part .= "FROM" . implode(" FROM ", $query['from']) . "\n ";
                $part .= "WHERE {" . $tgPat . " . }";
                $dic_bound_data = $queryModel->sparqlQuery($part);
                if ($dic_bound_data) {
                    foreach ($dic_bound_data as $l => $varsvals) {
                        if ($vars) {
                            foreach ($vars as $v) {
                                if ($varsvals[$v]->uri) {
                                    if (!is_array($discovered[$v]) || !in_array($varsvals[$v]->uri, $discovered[$v])) {
                                        $discovered[$v][] = $varsvals[$v]->uri;
                                    }
                                } elseif ($varsvals[$v]->literal) {
                                    if (!is_array($discovered[$v]) || !in_array($varsvals[$v]->literal, $discovered[$v])) {
                                        $discovered[$v][] = $varsvals[$v]->literal;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        $performedQueries = array();
        $r = 0;
        foreach ($iterations as $it => $triples2query) {
            $S3QL = array();
            $S3QLfinal = array();
            $queried_elements = array();
            $lQueries = array();
            $rQueries = array();
            foreach ($triples2query as $i => $tripleInd) {
                $tripleString = $tripleInd;
                $tmp = explode(" ", trim($tripleString));
                $subject = $tmp[0];
                //once the subjec is known, predicate may be found
                ereg("^\\" . $subject . '(.*)', trim($tripleString), $tmp1);
                $tmp2 = explode(" ", trim($tmp1[1]));
                $predicate = $tmp2[0];
                //With known subject and predicate, object will be the string with that portion truncated
                ereg("^\\" . $predicate . '(.*)', trim($tmp1[1]), $tmp3);
                $object = trim($tmp3[1]);
                #list($subject, $predicate) = explode(' ',trim($tripleString));
                #$object = trim(str_replace(array($subject, $predicate), array("", ""), $tripleString));
                //Method 1 to breaking the triple
                /*$tmp = explode(' ',trim($tripleString));
                		$subject = $tmp[0];
                		$predicate = $tmp[1];
                		if(count($tmp)>3){
                			for ($t=2; $t <count($tmp) ; $t++) {
                				if($object!='') $object .= " ";
                				$object .=  $tmp[$t];
                			}
                		}
                		*/
                $subject = ereg_replace('^<|>$', '', $subject);
                $predicate = ereg_replace('^<|>$', '', $predicate);
                $object = ereg_replace('^<|>$', '', $object);
                $triple = compact('subject', 'predicate', 'object');
                #sparql triple is used to calculate the values of the variables in the triple
                #$sparql_triple = $sparql_prefixes_default.' SELECT * WHERE { '.ltrim($tripleString).' . }';
                #now lets interpret the triple to explore the space of possible queries on S3QL
                $pack = compact('triple', 's3ql', 'user_id', 'db', 'prefixes', 'varType', 'discoveredData', 'discovered', 'it', 'varTypeWhere', 'collected_data', 'performedQueries');
                $sp = sparql_navigator($pack);
                extract($sp);
                # if($timer) $timer->setMarker('Built query '.$i);
                ##Remove queries that were already performed
                if ($S3QL[0]) {
                    foreach ($S3QL as $s => $q) {
                        if (!in_array($q, $S3QLfinal)) {
                            $S3QLfinal[] = $q;
                            $queried_elements[] = $element[$s];
                            $lQueries[] = $localQueries[$s];
                            $rQueries[] = $remoteQueries[$s];
                        }
                    }
                    #$S3QLfinal[] =$S3QL[0];
                    #$queried_elements[] = $element;
                    #$localQueries[$tripleString] = $localQueries[0];
                    #$remoteQueries[$tripleString] = $remoteQueries[0];
                    #$localQueries = array_filter($localQueries);
                    #$remoteQueries = array_filter($remoteQueries);
                }
            }
            $S3QL = $S3QLfinal;
            $localQueries = $lQueries;
            $remoteQueries = $rQueries;
            ##Remove repeated queries
            #$S3QL=array_unique($S3QL);
            #$S3QL = array_values($S3QL);
            #if only the s3ql is requested, we can return it now
            if ($in['output'] == 'S3QL') {
                foreach ($localQueries as $sparqlVersion => $s3qlVersion) {
                    $Q[]['S3QL'] = S3QLQuery($s3qlVersion);
                }
                foreach ($remoteQueries as $rq) {
                    $Q[]['S3QL'] = $rq;
                }
                $root = 's3ql';
                #root is just the word that xml should parse as the root for each entry
                $data = $Q;
                $cols = array('S3QL');
                $format = $in['format'] == '' ? 'html' : $in['format'];
                $z = compact('data', 'cols', 'format', 'root');
                $out = outputFormat($z);
                return array(true, $out);
            }
            #If paralel library is activated, use it for the data. Otherwise use the custom version
            #$query_answers_file = 'sparql_query_ans'.rand(100,200);	$a=fopen($query_answers_file, 'a');
            if (!empty($S3QL)) {
                if (extension_loaded('curl') && $goparallel) {
                    // Create cURL handlers
                    if ($timer) {
                        $timer->setMarker('Starting queries from group ' . $it);
                    }
                    foreach ($S3QL as $k => $url) {
                        $qURL = $url;
                        $ch[$k] = curl_init();
                        // Set options
                        curl_setopt($ch[$k], CURLOPT_URL, $qURL . '&format=php');
                        curl_setopt($ch[$k], CURLOPT_RETURNTRANSFER, 1);
                    }
                    $mh = curl_multi_init();
                    foreach ($S3QL as $k => $url) {
                        curl_multi_add_handle($mh, $ch[$k]);
                    }
                    $running = null;
                    do {
                        curl_multi_exec($mh, $running);
                        if ($timer) {
                            $timer->setMarker('Query ' . $k . ' of group ' . $it . ' executed');
                        }
                    } while ($running > 0);
                    foreach ($S3QL as $k => $url) {
                        $answer[$k] = curl_multi_getcontent($ch[$k]);
                        if (!empty($answer[$k])) {
                            #@fwrite($a, $answer[$k]);
                            ##This is what takes the longest after the query, can it be replaced?
                            $ans = unserialize($answer[$k]);
                            #$letter =  $queried_elements[$r][0];
                            $letter = $queried_elements[$k];
                            if (empty($ans)) {
                                ##is this query part is not optional, then the result will be null
                                ##TO BE DEVELOPED SOON
                            } else {
                                $rdf_results[$letter][] = $ans;
                            }
                            $r++;
                            ##Add the triples to already existing triples
                            #Line up the answer with the model
                            if ($timer) {
                                $timer->setMarker('Query ' . $it . '=>' . $k . ' converted to php ');
                            }
                        }
                    }
                    curl_multi_close($mh);
                    ####Time count
                    #$time_end = microtime(true);
                    #$time = $time_end - $time_start;
                    #echo "Query took ".$time." seconds\n";exit;
                    ###
                } else {
                    #Now solve the remaining triples with the constants found in this one
                    if (is_array($localQueries) && !empty($localQueries)) {
                        foreach ($localQueries as $s => $locals3ql) {
                            $locals3ql = array_filter(array_diff_key($locals3ql, array('url' => '')));
                            $tmpqueryfile = S3DB_SERVER_ROOT . '/tmp/' . md5(S3QLQuery($locals3ql));
                            ##Has this query been performed?
                            if ($clean == '2' && is_file($tmpqueryfile)) {
                                unlink($tmpqueryfile);
                            }
                            #If query results are stored in cache, use them!
                            if (is_file($tmpqueryfile)) {
                                $answer = unserialize(file_get_contents($tmpqueryfile));
                            } else {
                                $answer = S3QLAction($locals3ql);
                                file_put_contents($tmpqueryfile, serialize($answer));
                            }
                            //$answer = S3QLAction($locals3ql);
                            if (!empty($answer)) {
                                $letter = letter($locals3ql['from']);
                                $rdf_results[$letter][] = $answer;
                            }
                        }
                    }
                    if (is_array($remoteQueries) && !empty($remoteQueries[0])) {
                        $k = 0;
                        foreach ($remoteQueries as $remoteQuery) {
                            $answer = remoteQ($remoteQuery);
                            if (!empty($answer)) {
                                $letter = $queried_elements[$k];
                                $rdf_results[$letter][] = $answer;
                                $k++;
                                #$rdfanswer = rdf2php($answer);
                                #Line up the answer with the model
                                #$queryModel->addModel($rdfanswer);
                                #Now perform the query on the small model to find a constant for the remaining queries
                                #list($data,$discovered, $discoveredData,$queryModel) = executeQuery($queryModel,$sparql_triple,$discovered,$format);
                            }
                        }
                    }
                }
            }
        }
        ##Get the data from the file
        ##Convert the result into an RDF file
        $data_triples = array();
        if (is_array($rdf_results)) {
            foreach ($rdf_results as $letter => $results2rdfize) {
                $dont_skip_core_name = false;
                $dont_skip_serialized = true;
                if (ereg('S', $letter)) {
                    $dont_skip_serialized = false;
                }
                if (ereg('C|R|P', $letter)) {
                    $dont_skip_core_name = true;
                }
                foreach ($results2rdfize as $k => $data) {
                    $tmp_triples = rdf_encode($data, $letter, 'array', $s3ql['db'], $ns, $collected_data, $dont_skip_serialized, $dont_skip_core_name);
                    if (is_array($tmp_triples)) {
                        $data_triples = array_merge($data_triples, $tmp_triples);
                    }
                }
            }
        }
        if (is_array($outputCols) && !empty($outputCols)) {
            ##only this one are to be shown in the final result
            $vars = $outputCols;
        }
        $cleanCols = array();
        foreach ($vars as $varname) {
            $cleanCols[] = ereg_replace('^\\?', '', $varname);
        }
        if (empty($data_triples)) {
            ##still return the headers
            $cols = $cleanCols;
            $format = $_REQUEST['format'] != "" ? $_REQUEST['format'] : 'html';
            $data = array();
            $z = compact('data', 'cols', 'format', 'root');
            $out = outputFormat($z);
            return array(1, $out);
            #return true because query was valid... just did not return any results
        }
        #echo $filename;exit;
        $tmp['ns'] = $prefixes;
        /*
        #this one for turtle
        $parser = ARC2::getComponent('TurtleParser', $a);
        $index = ARC2::getSimpleIndex($triples, false) ; # false -> non-flat version 
        $rdf_doc = $parser->toTurtle($index,$prefixes);
        */
        $parser = ARC2::getComponent('RDFXMLParser');
        $index = ARC2::getSimpleIndex($data_triples, false);
        /* false -> non-flat version */
        $rdf_doc = $parser->toRDFXML($index);
        #$filename = S3DB_SERVER_ROOT.'/tmp/'.md5($sparql.date('d'));
        $rr = fopen($filename, 'a+');
        fwrite($rr, $rdf_doc);
        fclose($rr);
        if ($timer) {
            $timer->setMarker(count($data_triples) . ' triples written to file ' . $filename);
        }
        ##The better strategy would be to let the client cpu resolve the query; return the graphs with the rdf so that a sparql on the client can handle it
    }
    if ($_REQUEST['filename']) {
        $url2search = str_replace(S3DB_SERVER_ROOT, S3DB_URI_BASE, $filename);
        if (filesize($filename) > 0) {
            return array(true, $url2search);
        } else {
            return array(false);
        }
        exit;
    }
    if ($redirect) {
        ##And now use an external service ( I gave up with ARC) to parse the query
        $url2search = str_replace(S3DB_SERVER_ROOT, S3DB_URI_BASE, $filename);
        $bq = stripslashes($bq);
        ##Giving up on ARC, surrender to sparql.com
        $remote_endpoint = "http://sparql.org/sparql?query=";
        $bq = ereg_replace("FROM <.*>", "FROM <" . $url2search . ">", $bq);
        #$sparql=ereg_replace("FROM <.*>", "FROM <".$url2search.">", $sparql);
        $bq = urlencode($bq);
        $remote_endpoint .= $bq . '&default-graph-uri=&stylesheet=/xml-to-html.xsl';
        #$remote_endpoint .= $sparql.'&default-graph-uri=&stylesheet=/xml-to-html.xsl';
        return array(true, $remote_endpoint);
    }
    if ($format == 'rdf') {
        return array(true, $rdf_doc);
    }
    if ($format == 'turtle') {
        if (!$index) {
            $parser = ARC2::getRDFParser();
            $parser->parse($filename);
            $index = $parser->getSimpleIndex(0);
        }
        $rdf_doc = $parser->toTurtle($index);
        return array(true, $rdf_doc);
    }
    if ($format == 'n3') {
        if (!$index) {
            $parser = ARC2::getRDFParser();
            $parser->parse($filename);
            $index = $parser->getSimpleIndex(0);
        }
        $rdf_doc = $parser->toNTriples($index);
        return array(true, $rdf_doc);
    }
    #And finally perform the query on the model.
    $queryModel = rdf2php($filename);
    $format = $in['format'] != '' ? $in['format'] : 'html';
    if ($timer) {
        $timer->setMarker('Data converted to a model the rdf-api can query');
    }
    if (eregi('^(sparql-xml|sparql-html)$', $format)) {
        switch ($format) {
            case 'sparql-xml':
                $result = $queryModel->sparqlQuery($sparql, 'XML');
                break;
            case 'sparql-html':
                $result = $queryModel->sparqlQuery($sparql, 'HTML');
                if ($_REQUEST['su3d']) {
                    $timer->stop();
                    $profiling = $timer->getProfiling();
                    echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec';
                }
                break;
        }
        if ($result) {
            return array(true, $result);
        } else {
            return false;
        }
    } elseif ($format == 'html.form') {
        $form .= '
				<html>
				<head>

				</head><body>
				<form method="GET" action="sparql.php" id="sparqlform">
				<h5>Target Deployment(s)</h5>
				<input type="hidden" name="key" value="' . $s3ql['key'] . '"/>
				<input type="hidden" name="format" value="' . $_REQUEST['format'] . '"/>
				<input type = "text" id="url" size = "100%" value="' . $GLOBALS['url'] . '" name="url">
				<h5>SPARQL  <a href="http://www.w3.org/TR/rdf-sparql-query/" target="_blank">(help!!)</a></h5>
				<br />

				<textarea cols="100" id="sparql" rows="10" name = "query">' . stripslashes($sparql) . '</textarea><br />
				<input type="submit" value="SPARQL this!" id="submitsparql"></body>
				</form>
				';
        $form .= '<br />' . count($data) . " rows";
        $form .= '<br />Query took ' . (strtotime(date('His')) - $start) . ' sec';
        if (count($data) > 0) {
            return array(true, $form);
        } else {
            return array(false);
        }
    } else {
        #and output the result according to requested format
        $queryResultCache = S3DB_SERVER_ROOT . '/tmp/' . md5($sparql . $user_id . 'result');
        if ($clean && is_file($queryResultCache)) {
            unlink($queryResultCache);
        }
        $sparql = stripslashes($sparql);
        if (!is_file($queryResultCache)) {
            $data = $queryModel->sparqlQuery($sparql);
            file_put_contents($queryResultCache, serialize($data));
            chmod($queryResultCache, 0777);
            if ($timer) {
                $timer->setMarker('Query on SPARQL data executed by rdf-api.');
            }
        } else {
            $data = unserialize(file_get_contents($queryResultCache));
        }
        if (is_array($outputCols) && !empty($outputCols)) {
            ##only this one are to be shown in the final result
            $vars = $outputCols;
        }
        $cleanCols = array();
        foreach ($vars as $varname) {
            $cleanCols[] = ereg_replace('^\\?', '', $varname);
        }
        $outputData = array();
        if (is_array($data)) {
            foreach ($data as $s => $sparql_line) {
                foreach ($sparql_line as $sparql_var => $sparql_var_value) {
                    if ($sparql_var_value->uri != '') {
                        $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->uri;
                    } elseif ($sparql_var_value->label != '') {
                        $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->label;
                    } else {
                        $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = "";
                    }
                }
            }
        }
        if ($timer) {
            $timer->setMarker('Data converted in a format that fun outputformat can read');
        }
        #$timer ->display();
        #root is just the word that xml should parse as the root for each entry
        $root = 'sparql';
        if ($timer) {
            $timer->setMarker('All variables fitted into their places to represent in the final output');
        }
        $data = $outputData;
        $cols = $cleanCols;
        if ($_REQUEST['su3d']) {
            if ($timer) {
                $timer->stop();
                $profiling = $timer->getProfiling();
            }
            echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec<br>';
        }
        $z = compact('data', 'cols', 'format', 'root');
        $out = outputFormat($z);
        #if($_REQUEST['su3d']){
        # echo $out;exit;
        #}
        #if(count($data)>0){
        return array(true, $out);
        #}
        #else {
        #	return (array(false));
        #}
    }
    #else {
    #$out= formatReturn($GLOBALS['error_codes']['no_results'], 'Your query did not return any results.', $format,'');
    #}
}