Esempio n. 1
0
 /**
  * Performs a SPARQL query against an RDF Dataset. 
  * The result can be retrived in SPARQL Query Results XML Format or
  * as an array containing the variables an their bindings.
  *
  * @param  String $query      the sparql query string
  * @param  String $resultform the result form ('xml' for SPARQL Query Results XML Format)
  * @return String/array       
  */
 function sparqlQuery($query, $resultform = false)
 {
     include_once RDFAPI_INCLUDE_DIR . PACKAGE_SPARQL;
     $parser = new SparqlParser();
     $q = $parser->parse($query);
     $eng = new SparqlEngine();
     return $eng->queryModel($this, $q, $resultform);
 }
Esempio n. 2
0
 /**
  *   Converts a MemModel into a query result array.
  *   Required for the DAWG test cases.
  *
  *   @param Model $model Model object to extract data from
  *   @return array Result array
  *
  *   @see http://www.w3.org/2001/sw/DataAccess/tests/README
  *   @see http://www.w3.org/2001/sw/DataAccess/tests/result-set.n3
  */
 static function convertModelToResultArray($model)
 {
     $graphset = ModelFactory::getDatasetMem('Dataset1');
     $graphset->setDefaultGraph($model);
     $parser = new SparqlParser();
     $engine = SparqlEngine::factory($model);
     $strSparqlQuery = '
         PREFIX rs: <http://www.w3.org/2001/sw/DataAccess/tests/result-set#>
         SELECT ?varname WHERE { ?x rs:resultVariable ?varname }
     ';
     $q = $parser->parse($strSparqlQuery);
     $variables = $engine->queryModel($graphset, $q, false);
     $arVars = array();
     $strSparqlQueryPart = '';
     $nCount = 0;
     foreach ($variables as $var) {
         $varname = '?' . $var['?varname']->label;
         $name = substr($varname, 1);
         $arVars[] = $varname;
         $strSparqlQueryPart .= ' ?thing rs:binding ?binding' . $nCount . '.
              ?binding' . $nCount . ' rs:value ' . $varname . '.
              ?binding' . $nCount . ' rs:variable "' . $name . '".';
         ++$nCount;
     }
     $strSparqlQuery = '
         PREFIX rs: <http://www.w3.org/2001/sw/DataAccess/tests/result-set#>
         SELECT ' . implode($arVars, ' ') . '
         WHERE {
             ?some rs:solution ?thing.
            ' . $strSparqlQueryPart . '
         }
     ';
     //echo $strSparqlQuery;
     $q = $parser->parse($strSparqlQuery);
     $arResult = $engine->queryModel($graphset, $q, false);
     //var_dump($arResult);
     //die();
     return $arResult;
 }
 function testParseNested()
 {
     //echo "<b>Nested queries tests</b><br/>\n";
     foreach ($GLOBALS['testSparqlParserTestsNested'] as $arNestedTest) {
         list($query, $strExpected) = $arNestedTest;
         $p = new SparqlParser();
         $q = $p->parse($query);
         $qs = new SparqlEngineDb_QuerySimplifier();
         $qs->simplify($q);
         $strRendResult = SparqlTestHelper::renderResult($q);
         $this->assertEqual($strExpected, $strRendResult);
     }
 }
Esempio n. 4
0
 function testArqTestcases()
 {
     foreach ($_SESSION['sparql_arq_tests'] as $name) {
         $_SESSION['test'] = $name['query'] . " test";
         $parser = new SparqlParser();
         $graphset = ModelFactory::getDatasetMem('Dataset1');
         $def = $graphset->getDefaultGraph();
         $def->load(SPARQL_TESTFILES . 'data/' . $name['data']);
         $qs = file_get_contents(SPARQL_TESTFILES . 'query/' . $name['query'] . ".rq", 'r');
         $res = file_get_contents(SPARQL_TESTFILES . 'result/' . $name['result'] . ".res", 'r');
         eval($res);
         $q = $parser->parse($qs);
         $engine = SparqlEngine::factory();
         $t = $engine->queryModel($graphset, $q, false);
         if ($t instanceof MemModel) {
             $bOk = $t->equals($result);
         } else {
             $bOk = SparqlTestHelper::resultCheck($t, $result);
         }
         $this->assertTrue($bOk);
         if (!$bOk) {
             echo $name['query'] . "\n";
         }
     }
 }
Esempio n. 5
0
 /**
  *   Executes a SPARQL query on the data written in an
  *   file containing N3-formatted RDF data
  *
  *   @param string $strN3File      Path to file
  *   @param string $strSparqlQuery SPARQL query to execute
  *
  *   @return mixed SPARQL engine query results
  */
 public static function queryN3($strN3File, $strSparqlQuery)
 {
     $graphset = ModelFactory::getDatasetMem('Dataset1');
     $graph1 = $graphset->getDefaultGraph();
     $graph1->load($strN3File, 'n3');
     $parser = new SparqlParser();
     $q = $parser->parse($strSparqlQuery);
     $engine = SparqlEngine::factory();
     return $engine->queryModel($graphset, $q, false);
 }
Esempio n. 6
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);
    }
    #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,'');
    #}
}
Esempio n. 7
0
 public function testAllTestgroupsNoReload()
 {
     echo "<b>SparqlDbTests</b><br/>\n";
     //prepare
     $parser = new SparqlParser();
     $strLastDataFile = null;
     foreach ($_SESSION['sparqlTestGroups'] as $arGroup) {
         if (isset($arGroup['deact'])) {
             continue;
         }
         //echo count($_SESSION[$arGroup['tests']]) . " tests\n";
         foreach ($_SESSION[$arGroup['tests']] as $name) {
             if (isset($name['type']) && ($name['type'] == 'syntax-negative' || $name['type'] == 'syntax-positive')) {
                 //skip syntax tests; they are run in SparqlParserTests
                 continue;
             }
             $checkfunc = $arGroup['checkfunc'];
             $fileData = null;
             $fileResult = null;
             $fileQuery = null;
             if (is_array($name)) {
                 if (isset($name['data'])) {
                     if (!file_exists(SPARQL_TESTFILES . $name['data'])) {
                         $fileData = 'data/' . $name['data'];
                     } else {
                         $fileData = $name['data'];
                     }
                 }
                 if (!file_exists(SPARQL_TESTFILES . $name['query'])) {
                     $fileQuery = 'query/' . $name['query'] . '.rq';
                 } else {
                     $fileQuery = $name['query'];
                 }
                 if (isset($name['result'])) {
                     if (!file_exists(SPARQL_TESTFILES . $name['result'])) {
                         $fileResult = 'result/' . $name['result'] . '.res';
                     } else {
                         $fileResult = $name['result'];
                     }
                 }
                 if (isset($name['title'])) {
                     $title = $name['title'];
                 } else {
                     $title = $name['query'];
                 }
             } else {
                 $fileData = 'data/' . $name . '.n3';
                 $fileQuery = 'query/' . $name . '.rq';
                 $fileResult = 'result/' . $name . '.res';
                 $title = $name;
             }
             if (in_array($title, $_SESSION['testSparqlDbTestsIgnores'])) {
                 if (isset($GLOBALS['debugTests'])) {
                     echo Console_Color::convert('%y');
                     echo '  ignoring ' . $title . "\n";
                     echo Console_Color::convert('%n');
                 }
                 continue;
             }
             //echo '  ' . $title . "\n";
             $_SESSION['test'] = $title . ' test';
             $e = null;
             if (isset($name['earl:name'])) {
                 //fix some weird issue with simpletest
                 $earlname = $name['earl:name'];
                 $this->signal('earl:name', $earlname);
             }
             if ($fileData != null && $fileData != $strLastDataFile) {
                 //re-use database if not changed
                 list($database, $dbModel) = $this->prepareDatabase();
                 //import statements into database
                 $dbModel->load(SPARQL_TESTFILES . $fileData, 'n3');
                 $strLastDataFile = $fileData;
             }
             $qs = file_get_contents(SPARQL_TESTFILES . $fileQuery);
             if ($fileResult !== null) {
                 $res = file_get_contents(SPARQL_TESTFILES . $fileResult);
                 if (substr($fileResult, -4) == '.srx') {
                     //Sparql XML result
                     $resParser = new SparqlResultParser();
                     $result = $resParser->parse($res);
                 } else {
                     if (substr($fileResult, -4) == '.rdf') {
                         //same format as .ttl, but serialized as xml
                         //rdf xml sorted
                         $resModel = new MemModel();
                         $resModel->load(SPARQL_TESTFILES . $fileResult, 'rdf');
                         $result = SparqlTestHelper::convertModelToResultArray($resModel);
                         unset($resModel);
                         $checkfunc = 'resultCheckSort';
                     } else {
                         if (substr($fileResult, -4) == '.res') {
                             //our own php code
                             unset($result);
                             eval($res);
                         } else {
                             if (substr($fileResult, -4) == '.ttl') {
                                 //N3
                                 $resModel = new MemModel();
                                 $resModel->load(SPARQL_TESTFILES . $fileResult, 'n3');
                                 $result = SparqlTestHelper::convertModelToResultArray($resModel);
                                 unset($resModel);
                             } else {
                                 throw new Exception('Unknown result format in ' . $fileResult);
                             }
                         }
                     }
                 }
             }
             try {
                 $q = $parser->parse($qs);
             } catch (Exception $e) {
                 //normal query failed to be parsed
                 $this->assertTrue(false, 'Query failed to be parsed');
                 if (!isset($GLOBALS['debugTests'])) {
                     //echo '  ' . $title . "\n";
                 } else {
                     echo Console_Color::convert('%RTest failed: ' . $title . "%n\n");
                     if (isset($e)) {
                         echo $e->getMessage() . "\n";
                         //var_dump($e);
                     }
                     echo $strQuery . "\n";
                     die;
                 }
             }
             try {
                 $t = $dbModel->sparqlQuery($qs);
                 if ($t instanceof MemModel) {
                     $bOk = $t->equals($result);
                 } else {
                     $bOk = SparqlTestHelper::$checkfunc($t, $result);
                 }
                 $this->assertTrue($bOk);
             } catch (Exception $e) {
                 $bOk = false;
                 $t = null;
                 //an exception is an error
                 if (isset($GLOBALS['debugTests'])) {
                     var_dump($e->getMessage());
                 }
                 $this->assertTrue(false);
             }
             if (!$bOk) {
                 if (!isset($GLOBALS['debugTests'])) {
                     //echo '  ' . $title . "\n";
                 } else {
                     echo Console_Color::convert('%RTest failed: ' . $title . "%n\n");
                     if ($e != null) {
                         echo get_class($e) . ': ' . $e->getMessage() . "\n";
                     }
                     echo ' Data: ' . $fileData . "\n";
                     echo 'Query string: ' . $qs . "\n";
                     echo "Expected:\n";
                     echo Console_Color::convert('%p');
                     var_dump($result);
                     echo Console_Color::convert('%n');
                     echo "Result:\n";
                     echo Console_Color::convert('%r');
                     var_dump($t);
                     echo Console_Color::convert('%n');
                     //var_dump($q);
                     die;
                 }
             }
             /**/
         }
         //            echo $arGroup['title'] . " done\n";
     }
 }
Esempio n. 8
0
 /**
  * Performs a SPARQL query against a model. The model is converted to
  * an RDF Dataset. The result can be retrived in SPARQL Query Results XML Format or
  * as an array containing the variables an their bindings.
  *
  * @param  String $query      the sparql query string
  * @param  String $resultform the result form ('xml' for SPARQL Query Results XML Format)
  * @return String/array       
  */
 function sparqlQuery($query, $resultform = false)
 {
     include_once RDFAPI_INCLUDE_DIR . PACKAGE_SPARQL;
     include_once RDFAPI_INCLUDE_DIR . PACKAGE_DATASET;
     $dataset = new DatasetMem();
     $dataset->setDefaultGraph($this);
     $parser = new SparqlParser();
     $q = $parser->parse($query);
     $eng = new SparqlEngine();
     return $eng->queryModel($dataset, $q, $resultform);
 }