Source for file SparqlEngine.php

Documentation is available at SparqlEngine.php

  1. <?php
  2.  
  3. // ----------------------------------------------------------------------------------
  4. // Class: SparqlEngine
  5. // ----------------------------------------------------------------------------------
  6.  
  7. /**
  8. * This engine executes SPARQL queries against an RDF Datatset.
  9. *
  10. @version  $Id: fsource_sparql__sparqlSparqlEngine.php.html,v 1.7 2006/06/26 12:34:18 tgauss Exp $
  11. @author   Tobias Gauß <tobias.gauss@web.de>
  12. *
  13. @package sparql
  14. */
  15.  
  16. Class SparqlEngine extends Object{
  17.  
  18.  
  19.     /**
  20.     * @var Query The query object.
  21.     */
  22.     private $query;
  23.  
  24.     /**
  25.     * @var Dataset The RDF Dataset.
  26.     */
  27.     private $dataset;
  28.  
  29.  
  30.  
  31.     /**
  32.     * The query engines main method.
  33.     *
  34.     * @param  Dataset       $dataset    the RDF Dataset
  35.     * @param  Query         $query      the parsed SPARQL query
  36.     * @param  String        $resultform the result form. If set to 'xml' the result will be
  37.     *                                    SPARQL Query Results XML Format as described in http://www.w3.org/TR/rdf-sparql-XMLres/ .
  38.     * @return Array/String  Type of the result depends on $resultform.
  39.     */
  40.     public function queryModel($dataset,$query,$resultform false){
  41.         $this->query   $query;
  42.         $this->dataset $dataset;
  43.  
  44.         if($this->query->isEmpty){
  45.             $vartable[0]['patternResult'null;
  46.             return $this->returnResult($vartable,$resultform);
  47.         }
  48.  
  49.         $graphlist $this->preselectGraphs();
  50.         /// match graph patterns against the RDF Dataset
  51.         $patternlist $this->matchPatterns($graphlist);
  52.         // filter results- apply inner filters
  53.         $patternlist $this->filterPatterns($patternlist,false);
  54.         // join pattern results
  55.         $vartable $this->joinResults($patternlist);
  56.         // filter results- apply outer filters
  57.         $vartable $this->filterPatterns($vartable,true);
  58.  
  59.         return $this->returnResult($vartable,$resultform);
  60.  
  61.     }
  62.  
  63.     /**
  64.     * Matches all graph Patterns against the dataset and generates an array which
  65.     * contains the result sets for every given GraphPattern.
  66.     *
  67.     * @param  Array      $graphlist   the graphlist which contains the names of the named
  68.     *                     graphs which has to be queried.
  69.     * @return Array 
  70.     */
  71.     protected function matchPatterns($graphlist){
  72.         $patternlist array();
  73.         // get the result part from the query
  74.         $resultPart $this->query->getResultPart();
  75.         // for each GrapPattern in the result part
  76.         if($resultPart)
  77.         foreach($resultPart as $graphPattern){
  78.             $this->matchPattern($patternlist$graphlist$graphPattern);
  79.         }
  80.         return $patternlist;
  81.     }
  82.  
  83.  
  84.     /**
  85.     * Finds tuples that match one graph pattern.
  86.     *
  87.     * @param  Array        $patternlist list that contains the graphPatterns
  88.     * @param  array        $graphlist   the graphlist
  89.     * @param  GraphPattern $graphPattern the pattern which has to be matched
  90.     * @return void 
  91.     */
  92.     protected function matchPattern(&$patternlist$graphlist&$graphPattern{
  93.         // generate an empty result set
  94.         $finalRes null;
  95.         // if the GraphPattern has triple patterns
  96.         if($graphPattern->getTriplePattern()>0){
  97.             // check if the pattern has a GRAPH clause and if this Iri is in $graphlist
  98.             $newGraphList $this->_checkGraphs($graphPattern,$graphlist);
  99.             if($newGraphList){
  100.                 $qt $graphPattern->getTriplePattern();
  101.                 $resultSet $this->findTuplesMatchingOnePattern($qt[0]$newGraphList);
  102.                 for ($i=1$i<count($qt)$i++{
  103.                     $rs $this->findTuplesMatchingOnePattern($qt[$i]$newGraphList);
  104.                     $resultSet $this->joinTuples($resultSet$rs);
  105.                     if(!$resultSet)
  106.                     break;
  107.                 }
  108.                 if($finalRes != null){
  109.                     $finalRes $this->joinTuples($finalRes,$resultSet);
  110.                 }else{
  111.                     $finalRes $resultSet;
  112.                 }
  113.             }
  114.         }
  115.         // dependencies between pattern results
  116.         $patternlist[$graphPattern->getId()]['hasOptional']     0;
  117.         $patternlist[$graphPattern->getId()]['hasUnion']        0;
  118.         $patternlist[$graphPattern->getId()]['patternResult']   $finalRes;
  119.  
  120.         $op $graphPattern->getOptional();
  121.         $un $graphPattern->getUnion();
  122.  
  123.         $patternlist[$graphPattern->getId()]['optionalTo']      $op;
  124.         if(is_int($op))
  125.         $patternlist[$op]['hasOptional']++;
  126.  
  127.         $patternlist[$graphPattern->getId()]['unionWith']       $un;
  128.         if(is_int($un))
  129.         $patternlist[$un]['hasUnion']++;
  130.  
  131.         $constraint $graphPattern->getConstraint();
  132.         if($constraint != null){
  133.             foreach($constraint as $constr){
  134.                 if($constr->isOuterFilter()){
  135.                     $patternlist[$graphPattern->getId()]['outerFilter'][]          $constr;
  136.                     $patternlist[$graphPattern->getId()]['innerFilter'][]          null;
  137.                 }else{
  138.                     $patternlist[$graphPattern->getId()]['innerFilter'][]          $constr;
  139.                     $patternlist[$graphPattern->getId()]['outerFilter'][]          null;
  140.                 }
  141.             }
  142.         }else{
  143.             $patternlist[$graphPattern->getId()]['innerFilter']          null;
  144.             $patternlist[$graphPattern->getId()]['outerFilter']          null;
  145.         }
  146.     }
  147.  
  148.  
  149.     /**
  150.     * Finds Tuples matching one TriplePattern.
  151.     *
  152.     * @param  TriplePattern $pattern 
  153.     * @param  Array         $graphlist 
  154.     * @return Array 
  155.     */
  156.     protected function findTuplesMatchingOnePattern($pattern$graphlist){
  157.         $var null;
  158.         $sub  $pattern->getSubject();
  159.         $pred $pattern->getPredicate();
  160.         $obj  $pattern->getObject();
  161.  
  162.         if(is_string($sub)||$sub instanceof BlankNode){
  163.             if(is_string($sub))
  164.             $var['sub'$sub;
  165.             $sub null;
  166.         }
  167.         if(is_string($pred)||$pred instanceof BlankNode ){
  168.             if(is_string($pred))
  169.             $var['pred'$pred;
  170.             $pred null;
  171.         }
  172.         if(is_string($obj)||$obj instanceof BlankNode){
  173.             if(is_string($obj))
  174.             $var['obj'$obj;
  175.             $obj null;
  176.         }
  177.         $intBindings $this->_buildIntBindings($var);
  178.         $k 0;
  179.  
  180.         $key 0;
  181.         // search in named graphs
  182.         if($graphlist['var'][0!= null||$graphlist['list'][0!= null){
  183.             foreach($graphlist['list'as $key => $graphnode){
  184.  
  185.                 // query the dataset
  186.                 $it $this->dataset->findInNamedGraphs($graphnode,$sub,$pred,$obj,false);
  187.                 if($it->valid()){
  188.                     // add statements to the result list
  189.                     while($it->valid()){    
  190.                         if($graphnode == null){
  191.                             $element $it->current()->getStatement();
  192.                             $grname  $it->current()->getGraphname();
  193.                         }else{
  194.                             if($it->current(instanceof Quad)
  195.                                 $element $it->current()->getStatement();
  196.                             else 
  197.                                 $element $it->current();
  198.                         
  199.                             $grname  $graphnode;
  200.                         }
  201.                         if($this->checkIntBindings($element,$intBindings)){
  202.                             $resmodel['trip'][$k]  $element;
  203.                             $resmodel['graph'][$k$grname;
  204.                         //    $resmodel['graphvar'][$k] = $graphlist['var'][$key];
  205.                             $resmodel['graphvar'][$k$graphlist['var'][0];
  206.                             $k++;
  207.  
  208.                         }
  209.                         $it->next();
  210.                     }
  211.                 }
  212.  
  213.             }
  214.         }
  215.         // search in the default graph
  216.         if($graphlist['list'][0== null && $graphlist['var'][0== null){
  217.             
  218.             
  219.             $gr $this->dataset->getDefaultGraph();
  220.             
  221.             $res $gr->find($sub,$pred,$obj);
  222.             
  223.             foreach($res->triples as $innerkey => $element){
  224.                 if($this->checkIntBindings($element,$intBindings)){
  225.                         $resmodel['trip'][$k]  $element;
  226.                         $resmodel['graph'][$knull;
  227.                         $resmodel['graphvar'][$k$graphlist['var'][$key];
  228.                         $k++;
  229.                     }
  230.             }        
  231.         }
  232.         if($k == 0)
  233.         return false;
  234.         return $this->_buildResultSet($pattern,$resmodel);
  235.     }
  236.  
  237.     /**
  238.     * Checks it there are internal bindings between variables.
  239.     *
  240.     * @param  Triple  $trip 
  241.     * @param  Array   $intBindings 
  242.     * @return boolean 
  243.     */
  244.     protected function checkIntBindings($trip$intBindings){
  245.         switch($intBindings){
  246.             case -1:
  247.             return true;
  248.             break;
  249.             case 0:
  250.             if($trip->subj != $trip->pred)
  251.             return false;
  252.             break;
  253.             case 1:
  254.             if(is_a($trip->obj,'Literal'))
  255.             return false;
  256.             if($trip->subj != $trip->obj)
  257.             return false;
  258.             break;
  259.             case 2:
  260.             if(is_a($trip->obj,'Literal'))
  261.             return false;
  262.             if($trip->pred != $trip->obj)
  263.             return false;
  264.             break;
  265.             case 3:
  266.             if(is_a($trip->obj,'Literal'))
  267.             return false;
  268.             if($trip->pred != $trip->obj || $trip->pred != $trip->subj )
  269.             return false;
  270.             break;
  271.         }
  272.         return true;
  273.     }
  274.  
  275.  
  276.     /**
  277.     * Perform an SQL-like inner join on two resultSets.
  278.     *
  279.     * @param   Array   &$finalRes 
  280.     * @param   Array   &$res 
  281.     * @return  Array 
  282.     */
  283.     protected function joinTuples(&$finalRes&$res{
  284.  
  285.         if (!$finalRes || !$res)
  286.         return array();
  287.  
  288.         // find joint variables and new variables to be added to $finalRes
  289.         $jointVars array();
  290.         $newVars array();
  291.         $k key($res);
  292.  
  293.         foreach ($res[$kas $varname => $node{
  294.             if (array_key_exists($varname$finalRes[0]))
  295.             $jointVars[$varname;
  296.             else
  297.             $newVars[$varname;
  298.         }
  299.  
  300.         // eliminate rows of $finalRes in which the values of $jointVars do not have
  301.         // a corresponding row in $res.
  302.         foreach ($finalRes as $n => $fRes{
  303.             foreach ($res as $i => $r{
  304.                 $ok TRUE;
  305.                 foreach ($jointVars as $j_varname)
  306.                 if ($r[$j_varname!= $fRes[$j_varname]{
  307.                     $ok FALSE;
  308.                     break;
  309.                 }
  310.                 if ($ok)
  311.                 break;
  312.             }
  313.             if (!$ok)
  314.             unset($finalRes[$n]);
  315.         }
  316.  
  317.         // join $res and $finalRes
  318.         $joinedRes array();
  319.         foreach ($res as $r{
  320.             foreach ($finalRes as $n => $fRes{
  321.                 $ok TRUE;
  322.                 foreach ($jointVars as $j_varname)
  323.                 if ($r[$j_varname!= $fRes[$j_varname]{
  324.                     $ok FALSE;
  325.                     break;
  326.                 }
  327.                 if ($ok{
  328.                     $joinedRow $finalRes[$n];
  329.                     foreach($newVars as $n_varname)
  330.                     $joinedRow[$n_varname$r[$n_varname];
  331.                     $joinedRes[$joinedRow;
  332.                 }
  333.             }
  334.         }
  335.         return $joinedRes;
  336.     }
  337.  
  338.  
  339.     /**
  340.     * Joins OPTIONAL pattern results.
  341.     *
  342.     * @param   Array   &$finalRes 
  343.     * @param   Array   &$res 
  344.     * @return  Array    the joined Array
  345.     */
  346.     protected function joinOptionalTuples(&$finalRes&$res{
  347.  
  348.         if(!$finalRes && !$res)
  349.         return array();
  350.  
  351.         if(!$finalRes)
  352.         return $res;
  353.  
  354.         if(!$res)
  355.         return $finalRes;
  356.  
  357.         // find joint variables and new variables to be added to $finalRes
  358.         $jointVars array();
  359.         $newVars array();
  360.         $result array();
  361.  
  362.         $k key($res);
  363.  
  364.         foreach ($res[$kas $varname => $node{
  365.             if (array_key_exists($varname$finalRes[0])){
  366.                 $jointVars[$varname;
  367.             }else{
  368.                 $newVars[$varname;
  369.             }
  370.         }
  371.         $joined array();
  372.         foreach($finalRes as $i =>$fRes){
  373.             foreach($res as $n =>$r){
  374.                 $join false;
  375.                 foreach($jointVars as $j_varname){
  376.                     if($r[$j_varname]==$fRes[$j_varname]){
  377.                         $join true;
  378.                         break;
  379.                     }
  380.                 }
  381.                 if($join){
  382.                     $result[$i$fRes;
  383.                     foreach($newVars as $n_varname)
  384.                     $result[$i][$n_varname$r[$n_varname];
  385.                     $joined[]=$n;
  386.                 }
  387.  
  388.             }
  389.         }
  390.  
  391.         $count count($result);
  392.         foreach($res as $k =>$val){
  393.             if(!in_array($k,$joined)){
  394.                 $result[$count$finalRes[0];
  395.                 foreach($result[$countas $varname => $varVal){
  396.                     $result[$count][$varname]='';
  397.                 }
  398.  
  399.                 foreach($val as $varname2 => $varVal2){
  400.                     $result[$count][$varname2]=$varVal2;
  401.                 }
  402.                 $count++;
  403.             }
  404.         }
  405.         return $result;
  406.     }
  407.  
  408.  
  409.  
  410.     /**
  411.     * Looks in from and from named part of the query and
  412.     * adds the graphs to the graphlist.
  413.     *
  414.     * @return Array 
  415.     */
  416.     protected function preselectGraphs(){
  417.         $fromNamed $this->query->getFromNamedPart();
  418.         if($fromNamed == null)
  419.         $fromNamed[null;
  420.         return $fromNamed;
  421.     }
  422.  
  423.  
  424.     /**
  425.     * Evaluates the GRPAH clause if there is one. Checks if
  426.     * the GRAPH clause contains an IRI, variable or nothing.
  427.     * Returns an array which contains the graphs that has to be matched.
  428.     *
  429.     * @param  GraphPattern $pattern 
  430.     * @param  Array        $graphlist 
  431.     * @return Array 
  432.     */
  433.     protected function _checkGraphs(&$pattern,$graphlist){
  434.  
  435.         $gr $pattern->getGraphname();
  436.         if($gr instanceof Resource ){
  437.             if($graphlist[0]==null || in_array($gr,$graphlist)){
  438.                 $newGraphList['list'][$gr;
  439.                 $newGraphList['var'][]  null;
  440.             }else{
  441.                 return false;
  442.             }
  443.         }elseif (is_string($gr)){
  444.             $newGraphList['list'$graphlist;
  445.             $newGraphList['var'][]  $gr;
  446.         }else{
  447.             $newGraphList['list'$graphlist;
  448.             $newGraphList['var'][]  null;
  449.         }
  450.         return $newGraphList;
  451.     }
  452.  
  453.     /**
  454.     * Marks triples with internal bindings.
  455.     * int bindings -1 :none 0:sub=pred 1:sub=obj 2:pred=obj 3:sub=pred=obj.
  456.     *
  457.     * @param  Array $var 
  458.     * @return Array 
  459.     */
  460.     protected function _buildIntBindings($var){
  461.         $intBindings = -1;
  462.         if(!$var)
  463.         return $intBindings;
  464.  
  465.         if(isset($var['sub'])){
  466.             if(isset($var['pred']))
  467.             if($var['sub'== $var['pred'])
  468.             $intBindings 0;
  469.             if(isset($var['obj']))
  470.             if($var['sub'== $var['obj']){
  471.                 if$intBindings == 0){
  472.                     $intBindings 3;
  473.                 }else{
  474.                     $intBindings 1;
  475.                 }
  476.             }
  477.         }
  478.         if(isset($var['pred'])){
  479.             if(isset($var['obj']))
  480.             if($var['pred']==$var['obj']&&$intBindings!=3)
  481.             $intBindings 2;
  482.         }
  483.         return $intBindings;
  484.     }
  485.  
  486.     /**
  487.     * Builds the resultset.
  488.     *
  489.     * @param  GraphPattern $pattern 
  490.     * @param  Array        $resmodel 
  491.     * @return Array 
  492.     */
  493.     protected function _buildResultSet($pattern,$resmodel){
  494.         // determine variables and their corresponding values
  495.         $result null;
  496.         if(is_string($pattern->getSubject())){
  497.             $n 0;
  498.             foreach($resmodel['trip'as $key => $triple){
  499.                 if(isset($resmodel['graphvar'][$key]))
  500.                 $result[$n][$resmodel['graphvar'][$key]] $resmodel['graph'][$key];
  501.                 $result[$n++][$pattern->getSubject()$triple->subj;
  502.             }
  503.         }
  504.         if(is_string($pattern->getPredicate())){
  505.             $n 0;
  506.             foreach($resmodel['trip'as $key => $triple){
  507.                 if(isset($resmodel['graphvar'][$key]))
  508.                 $result[$n][$resmodel['graphvar'][$key]] $resmodel['graph'][$key];
  509.                 $result[$n++][$pattern->getPredicate()$triple->pred;
  510.             }
  511.         }
  512.         if(is_string($pattern->getObject())){
  513.             $n 0;
  514.             foreach($resmodel['trip'as $key => $triple){
  515.                 if(isset($resmodel['graphvar'][$key]))
  516.                 $result[$n][$resmodel['graphvar'][$key]] $resmodel['graph'][$key];
  517.                 $result[$n++][$pattern->getObject()$triple->obj;
  518.             }
  519.         }
  520.         return $result;
  521.     }
  522.  
  523.     /**
  524.     * Selects the result variables and builds a result table.
  525.     *
  526.     * @param  Array  $table the result table
  527.     * @param  Array  $vars the result variables
  528.     * @return Array 
  529.     */
  530.     protected function selectVars($table,$vars){
  531.         if($vars[0]=='*')
  532.         $vars $this->query->getAllVars();
  533.         $resTable array();
  534.         $hits 0;
  535.         foreach($table as $val){
  536.             foreach($vars as $var){
  537.                 if(isset($val[$var])){
  538.                     $resTable[$hits][$var]=$val[$var];
  539.                 }else{
  540.                     $resTable[$hits][$var]="";
  541.                 }
  542.             }
  543.             $hits++;
  544.         }
  545.         return $resTable;
  546.     }
  547.  
  548.     /**
  549.     * Joins the results of the different Graphpatterns.
  550.     *
  551.     * @param  Array $patternlist 
  552.     * @return Array 
  553.     */
  554.     protected function joinResults($patternlist){
  555.         $joined[0]['patternResult'null;
  556.         $joined[0]['outerFilter'null;
  557.  
  558.         while(count($patternlist)>0){
  559.             foreach($patternlist as $key => $pattern){
  560.                 if($pattern['hasOptional'== && $pattern['hasUnion'== 0){
  561.                     if(is_int($pattern['optionalTo'])){
  562.                         $patternlist[$pattern['optionalTo']]['hasOptional']--;
  563.                         $patternlist[$pattern['optionalTo']]['patternResult'$this->joinOptionalTuples($pattern['patternResult'],$patternlist[$pattern['optionalTo']]['patternResult']);
  564.                         unset($patternlist[$key]);
  565.                         break;
  566.                     }
  567.                     else if(is_int($pattern['unionWith'])){
  568.                         $patternlist[$pattern['unionWith']]['hasUnion']--;
  569.                         foreach($pattern['patternResult'as $value)
  570.                         array_push($patternlist[$pattern['unionWith']]['patternResult'],$value);
  571.                         unset($patternlist[$key]);
  572.                         break;
  573.                     }else{
  574.                         if($joined[0]['patternResult'== null){
  575.                             $joined[0]['patternResult'$pattern['patternResult'];
  576.                             if($joined[0]['outerFilter'== null )
  577.                             $joined[0]['outerFilter']  $pattern['outerFilter'];
  578.                             unset($patternlist[$key]);
  579.                             break;
  580.                         }
  581.                     //    if($pattern['patternResult'] !=null ){
  582.                             $joined[0]['patternResult'$this->joinTuples($joined[0]['patternResult'],$pattern['patternResult']);
  583.                             $joined[0]['outerFilter']   $pattern['outerFilter'];
  584.                             unset($patternlist[$key]);
  585.                             break;
  586.                     //    }    
  587.                     }
  588.                 }
  589.             }
  590.         }
  591.         return $joined;
  592.     }
  593.  
  594.     /**
  595.     * Filters the pattern results.
  596.     *
  597.     * @param  Array   $patternlist list containing the results of the GraphPatterns
  598.     * @param  boolean $outer TRUE if its an outer filter FALSE if not
  599.     * @return Array   the filtered patternlist
  600.     */
  601.     protected function filterPatterns($patternlist,$outer){
  602.         if($outer)
  603.         $filter 'outerFilter';
  604.         else
  605.         $filter 'innerFilter';
  606.         foreach($patternlist as $patkey => $pattern){
  607.             // get constraints
  608.             $constraint $pattern[$filter];
  609.  
  610.             if(count($constraint)>0){
  611.                 foreach($constraint as $constr){
  612.                     if($constr != null){
  613.                         // extract Vars and function calls
  614.                         $evalString $constr->getExpression();
  615.                         preg_match_all("/\?.[^\s\)\,]*/",$evalString,$vars);
  616.                         preg_match_all("/bound\((.[^\)]*)\)/i",$evalString,$boundcalls);
  617.                         preg_match_all("/isuri\((.[^\)]*)\)/i",$evalString,$isUricalls);
  618.                         preg_match_all("/isblank\((.[^\)]*)\)/i",$evalString,$isBlankcalls);
  619.                         preg_match_all("/isLiteral\((.[^\)]*)\)/i",$evalString,$isLiteralcalls);
  620.                         preg_match_all("/lang\((.[^\)]*)\)/i",$evalString,$langcalls);
  621.                         preg_match_all("/datatype\((.[^\)]*)\)/i",$evalString,$datatypecalls);
  622.                         preg_match_all("/str\((.[^\)]*)\)/i",$evalString,$stringcalls);
  623.  
  624.                         // is Bound
  625.                         if(count($boundcalls[1])>0)
  626.                         $function['bound'$boundcalls[1];
  627.                         else
  628.                         $function['bound'false;
  629.  
  630.                         // is URI
  631.                         if(count($isUricalls[1])>0)
  632.                         $function['isUri'$isUricalls[1];
  633.                         else
  634.                         $function['isUri'false;
  635.  
  636.                         // is Blank
  637.                         if(count($isBlankcalls[1])>0)
  638.                         $function['isBlank'$isBlankcalls[1];
  639.                         else
  640.                         $function['isBlank'false;
  641.  
  642.                         // is Literal
  643.                         if(count($isLiteralcalls[1])>0)
  644.                         $function['isLiteral'$isLiteralcalls[1];
  645.                         else
  646.                         $function['isLiteral'false;
  647.  
  648.                         // lang
  649.                         if(count($langcalls[1])>0)
  650.                         $function['lang'$langcalls[1];
  651.                         else
  652.                         $function['lang'false;
  653.  
  654.                         // datatype
  655.                         if(count($datatypecalls[1])>0)
  656.                         $function['datatype'$datatypecalls[1];
  657.                         else
  658.                         $function['datatype'false;
  659.  
  660.                         // string
  661.                         if(count($stringcalls[1])>0)
  662.                         $function['string'$stringcalls[1];
  663.                         else
  664.                         $function['string'false;
  665.  
  666.  
  667.                         foreach($pattern['patternResult'as $key => $res){
  668.                             $result false;
  669.                             $evalString $this->fillConstraintString($vars,$res,$constr,$function);
  670.                             $evalString '$result =('.$evalString.');';
  671.                             // evaluate Constraint
  672.                             @eval($evalString);
  673.  
  674.                             if(!$result)
  675.                             unset($patternlist[$patkey]['patternResult'][$key]);
  676.  
  677.                         }
  678.                     }
  679.                 }
  680.             }
  681.         }
  682.         return $patternlist;
  683.     }
  684.  
  685.     /**
  686.     * Builds an evaluation string to determine wether the result passes
  687.     * the filter or not. This string is evaluatet by the php buildin eval() function
  688.     *
  689.     * @param  Array      $vars a list which contains the used variables
  690.     * @param  Array      $res  the result part which have to be evaluated
  691.     * @param  Constraint $constraint the Constrain object
  692.     * @param  Array      $function an Array which contains the used functions
  693.     * @return String 
  694.     */
  695.  
  696.     protected function fillConstraintString($vars,$res,$constraint,$function){
  697.  
  698.         $boundExpr false;
  699.         $evalString $constraint->getExpression();
  700.  
  701.         // extract Literals
  702.         $pattern1 "/\".[^\"]*\"[^\^\@]/";
  703.         $pattern2 "/\'.[^\']*\'[^\^\@]/";
  704.         preg_match_all($pattern1,$evalString,$hits1);
  705.         preg_match_all($pattern2,$evalString,$hits2);
  706.  
  707.         foreach($hits1[0as $k => $val){
  708.             $evalString preg_replace('/\".[^\"]*\"[^\^]/','_REPLACED1_'.$k++,$evalString,1);
  709.         }
  710.         foreach($hits2[0as $k => $val){
  711.             $evalString preg_replace('/\".[^\"]*\"[^\^]/','_REPLACED2_'.$k++,$evalString,1);
  712.         }
  713.  
  714.         // replace namespaces
  715.         $prefs $this->query->getPrefixes();
  716.         foreach($prefs as $key => $val){
  717.             if($key == '')
  718.             $key ' ';
  719.             $evalString preg_replace("/^(".$key."\:)(.[^\s]*)|([\s\(]?[^\^])(".$key."\:)(.[^\s\)]*)([\s\)]?)/","$3'<".$val."$2$5>'$6",$evalString);
  720.  
  721.             $evalString preg_replace("/(\^)(".$key."\:)(.[^\s]*)/","$1<".$val."$3>",$evalString);
  722.         }
  723.  
  724.         $xsd "http\:\/\/www.w3.org\/2001\/XMLSchema\#";
  725.  
  726.         // evaluate bound calls
  727.         if($function['bound']){
  728.             $boundExpr true;
  729.             foreach($function['bound'as $var){
  730.                 if(isset($res[$var]&& $res[$var]!="")
  731.                 $replacement 'true';
  732.                 else
  733.                 $replacement 'false';
  734.                 $evalString preg_replace("/bound\(\\".$var."\)/i",$replacement,$evalString);
  735.             }
  736.  
  737.         }
  738.         // evaluate isBlank calls
  739.         if($function['isBlank']){
  740.             foreach($function['isBlank'as $var){
  741.                 if(isset($res[$var]&& $res[$var]!="" && $res[$varinstanceof BlankNode )
  742.                 $replacement 'true';
  743.                 else
  744.                 $replacement 'false';
  745.                 $evalString preg_replace("/isBlank\(\\".$var."\)/i",$replacement,$evalString);
  746.             }
  747.  
  748.         }
  749.         // evaluate isLiteral calls
  750.         if($function['isLiteral']){
  751.             foreach($function['isLiteral'as $var){
  752.                 if(isset($res[$var]&& $res[$var]!="" && $res[$varinstanceof Literal  )
  753.                 $replacement 'true';
  754.                 else
  755.                 $replacement 'false';
  756.                 $evalString preg_replace("/isLiteral\(\\".$var."\)/i",$replacement,$evalString);
  757.             }
  758.  
  759.         }
  760.         // evaluate isUri calls
  761.         if($function['isUri']){
  762.             foreach($function['isUri'as $var){
  763.                 if(isset($res[$var]&& $res[$var]!="" && $res[$varinstanceof Resource && $res[$var]->getUri(&& !$res[$varinstanceof BlankNode )
  764.                 $replacement 'true';
  765.                 else
  766.                 $replacement 'false';
  767.                 $evalString preg_replace("/isUri\(\\".$var."\)/i",$replacement,$evalString);
  768.             }
  769.         }
  770.         // evaluate lang calls
  771.         if($function['lang']){
  772.             foreach($function['lang'as $var){
  773.                 if(isset($res[$var]&& $res[$var]!="" && $res[$varinstanceof Literal && $res[$var]->getLanguage() )
  774.                 $replacement '"'.$res[$var]->getLanguage().'"';
  775.                 else
  776.                 $replacement 'null';
  777.                 $evalString preg_replace("/lang\(\\".$var."\)/i",$replacement,$evalString);
  778.             }
  779.         }
  780.         // evaluate datatype calls
  781.         if($function['datatype']){
  782.             foreach($function['datatype'as $var){
  783.                 if(isset($res[$var]&& $res[$var]!="" && $res[$varinstanceof Literal && $res[$var]->getDatatype() )
  784.                 $replacement '\'<'.$res[$var]->getDatatype().'>\'';
  785.                 else
  786.                 $replacement 'false';
  787.                 $evalString preg_replace("/datatype\(\\".$var."\)/i",$replacement,$evalString);
  788.             }
  789.         }
  790.         // evaluate string calls
  791.         if($function['string']){
  792.             foreach($function['string'as $var){
  793.                 if($var{0}=='?' || $var{0}=='$'){
  794.                     if(isset($res[$var]&& $res[$var]!=""){
  795.                         $replacement "'str_".$res[$var]->getLabel()."'";
  796.                         if($res[$varinstanceof BlankNode)
  797.                         $replacement "''";
  798.                     }else{
  799.                         $replacement 'false';
  800.                     }
  801.                     $evalString preg_replace("/str\(\\".$var."\)/i",$replacement,$evalString);
  802.                 }else{
  803.                     if($var{0}=='<'){
  804.                         $evalString preg_replace("/str\(\s*\<(.[^\>]*)\>\s*\)/i","'str_$1'",$evalString);
  805.                     }
  806.                     if($var{0}=='"'){
  807.                         $evalString preg_replace("/str\(\s*\"(.[^\>]*)\"\@[a-z]*\s*\)/i","'str_$1'",$evalString);
  808.                     }
  809.                 }
  810.  
  811.             }
  812.         }
  813.         // evaluate VARS
  814.         foreach($vars[0as $var){
  815.             if(isset($res[$var])&&$res[$var]!= ""){
  816.                 //$replacement = "'".$res[$var]->getLabel()."'";
  817.                 $replacement '" "';
  818.                 if($res[$varinstanceof Literal){
  819.                     if($res[$var]->getDatatype()!= null){
  820.                         if($res[$var]->getDatatype(== XML_SCHEMA.'boolean')
  821.                         $replacement $res[$var]->getLabel();
  822.                         if($res[$var]->getDatatype(== XML_SCHEMA.'double')
  823.                         $replacement $res[$var]->getLabel();
  824.                         if($res[$var]->getDatatype(== XML_SCHEMA.'integer')
  825.                         $replacement $res[$var]->getLabel();
  826.                         if($res[$var]->getDatatype(== XML_SCHEMA.'dateTime')
  827.                         $replacement strtotime($res[$var]->getLabel());
  828.                     }else{
  829.                         if($res[$var]->getLabel()=="")
  830.                         $replacement 'false';
  831.                         else
  832.                         $replacement "'str_".$res[$var]->getLabel()."'";
  833.                     }
  834.                 }else{
  835.                     if($res[$varinstanceof Resource){
  836.                         $replacement "'<".$res[$var]->getLabel().">'";
  837.                     }
  838.                 }
  839.                 $evalString preg_replace("/\\".$var."/",$replacement,$evalString);
  840.             }
  841.  
  842.             // problem with PHP: false < 13 is true
  843.             if(isset($res[$var])){
  844.                 if($res[$var== ""){
  845.                     if($boundExpr)
  846.                     $evalString preg_replace("/\\".$var."/","false",$evalString);
  847.                     else
  848.                     $evalString 'false';
  849.                 }
  850.             }else{
  851.                 $evalString preg_replace("/\\".$var."/","false",$evalString);
  852.             }
  853.  
  854.         }
  855.  
  856.         // replace '=' with '=='
  857.         $evalString preg_replace("/(.[^\=])(\=)(.[^\=])/","$1==$3",$evalString);
  858.  
  859.  
  860.         // rewrite Literals
  861.         foreach($hits1[0as $k => $val){
  862.             $pattern '/_REPLACED1_'.$k.'/';
  863.             $evalString preg_replace($pattern,$hits1[0][$k],$evalString,1);
  864.         }
  865.  
  866.         foreach($hits2[0as $k => $val){
  867.             $pattern '/_REPLACED2_'.$k.'/';
  868.             $evalString preg_replace($pattern,$hits2[0][$k],$evalString,1);
  869.         }
  870.  
  871.         // replace xsd:boolean expressions
  872.         $pattern $pattern '/\"\s?true\s?\"\^\^\<'.$xsd.'boolean\>|\'\s?true\s?\'\^\^xsd:boolean/';
  873.         $evalString preg_replace($pattern,"true",$evalString);
  874.  
  875.         $pattern $pattern '/\"\s?false\s?\"\^\^\<'.$xsd.'boolean\>|\'\s?false\s?\'\^\^xsd:boolean/';
  876.         $evalString preg_replace($pattern,"false",$evalString);
  877.  
  878.         // replace xsd:date expressions
  879.         $pattern "/\"(.[^\"]*)\"\^\^".$xsd."dateTime/";
  880.         preg_match_all($pattern,$evalString,$hits);
  881.  
  882.         foreach($hits[1as $dummy)
  883.         $evalString preg_replace("/\".[^\"]*\"\^\^".$xsd."dateTime/",strtotime($dummy),$evalString,1);
  884.  
  885.  
  886.         $evalString preg_replace("/(\'\<".$xsd."dateTime\()(.[^\)]*\))\>\'/","dateTime($2",$evalString);
  887.  
  888.         $evalString preg_replace("/(\'\<".$xsd."integer\()(.[^\)]*\))\>\'/","integer($2",$evalString);
  889.  
  890.         // tag plain literals
  891.         $evalString preg_replace("/\"(.[^\"]*)\"([^\^])|\"(.[^\"]*)\"$/","'str_$1$3'$2",$evalString);
  892.  
  893.         return $evalString;
  894.     }
  895.  
  896.     /**
  897.     * Sorts the results.
  898.     *
  899.     * @param  Array  $vartable List containing the unsorted result vars
  900.     * @return Array  List containing the sorted result vars
  901.     */
  902.     protected function sortVars($vartable){
  903.         $newTable array();
  904.         $mod $this->query->getSolutionModifier();
  905.         // if no ORDER BY solution modifier return vartable
  906.         if($mod['order by']!= null){
  907.             $order $mod['order by'];
  908.             $map $this->buildVarmap($order,$vartable);
  909.             foreach($map as $val){
  910.                 $newTable[$vartable[$val];
  911.             }
  912.         }else{
  913.             $newTable $vartable;
  914.         }
  915.  
  916.         if($mod['offset'!= null){
  917.             $newTable array_slice ($newTable$mod['offset']);
  918.         }
  919.         if($mod['limit'!= null){
  920.             $newTable array_slice($newTable,0,$mod['limit']);
  921.         }
  922.  
  923.         return $newTable;
  924.     }
  925.  
  926.     /**
  927.     * Sorts the result table.
  928.     *
  929.     * @param  String $order (ASC/DESC)
  930.     * @param  Array  $vartable the vartable
  931.     * @return Array  A map that contains the new order of the result vars
  932.     */
  933.     protected function buildVarmap($order$vartable){
  934.         $n0;
  935.         $result array();
  936.         $num_var array();
  937.         foreach($order as $variable)
  938.         $num_var[$variable['val']] 0;
  939.  
  940.         foreach($vartable as $k => $x){
  941.             foreach($order as $value){
  942.                 // if the value is a typed Literal try to determine if it
  943.                 // a numeric datatype
  944.                 if($x[$value['val']] instanceof Literal){
  945.                     $dtype $x[$value['val']]->getDatatype();
  946.                     if($dtype){
  947.                         switch($dtype){
  948.                             case XML_SCHEMA."integer":
  949.                             $num_var[$value['val']]++;
  950.                             break;
  951.                             case XML_SCHEMA."double":
  952.                             $num_var[$value['val']]++;
  953.                             break;
  954.  
  955.                         }
  956.                     }
  957.                 }
  958.                 if($x[$value['val']]){
  959.                     if($x[$value['val']]instanceof Literal){
  960.                         $pref "2";
  961.                     }
  962.                     if($x[$value['val']]instanceof Resource){
  963.                         $pref "1";
  964.                     }
  965.                     if($x[$value['val']]instanceof BlankNode){
  966.                         $pref "0";
  967.                     }
  968.                     $result[$value['val']][$n$pref.$x[$value['val']]->getLabel();
  969.                 }else{
  970.                     $result[$value['val']][$n"";
  971.                 }
  972.             }
  973.             $result['oldKey'][$n$k;
  974.             $n++;
  975.         }
  976.         $sortString "";
  977.         foreach($order as $value){
  978.             if($num_var[$value['val']] == $n)
  979.             $sort SORT_NUMERIC;
  980.             else
  981.             $sort SORT_STRING;
  982.  
  983.             if($value['type'== 'asc')
  984.             $type SORT_ASC;
  985.             else
  986.             $type SORT_DESC;
  987.  
  988.             $sortString $sortString.'$result["'.$value['val'].'"],'.$type.','.$sort.',';
  989.         }
  990.         $sortString "array_multisort(".$sortString.'$result["oldKey"]);';
  991.  
  992.         @eval($sortString);
  993.         return $result['oldKey'];
  994.     }
  995.  
  996.  
  997.     /**
  998.     * Constructs a result graph.
  999.     *
  1000.     * @param  Array         $vartable a table containing the result vars and their bindings
  1001.     * @param  GraphPattern  $constructPattern the CONSTRUCT pattern
  1002.     * @return MemModel      the result graph which matches the CONSTRUCT pattern
  1003.     */
  1004.     protected function constructGraph($vartable,$constructPattern){
  1005.  
  1006.         $resultGraph new MemModel();
  1007.  
  1008.         if(!$vartable)
  1009.         return $resultGraph;
  1010.  
  1011.         $tp $constructPattern->getTriplePattern();
  1012.  
  1013.         $bnode 0;
  1014.         foreach($vartable as $value){
  1015.             foreach($tp as $triple){
  1016.                 $sub  $triple->getSubject();
  1017.                 $pred $triple->getPredicate();
  1018.                 $obj  $triple->getObject();
  1019.  
  1020.                 if(is_string($sub&& $sub{1}=='_' )
  1021.                 $sub  new BlankNode("_bN".$bnode);
  1022.                 if(is_string($pred&& $pred{1}=='_')
  1023.                 $pred new BlankNode("_bN".$bnode);
  1024.                 if(is_string($obj)  && $obj{1}=='_')
  1025.                 $obj  new BlankNode("_bN".$bnode);
  1026.  
  1027.  
  1028.                 if(is_string($sub))
  1029.                 $sub  $value[$sub];
  1030.                 if(is_string($pred))
  1031.                 $pred $value[$pred];
  1032.                 if(is_string($obj))
  1033.                 $obj  $value[$obj];
  1034.  
  1035.                 if($sub != "" && $pred != "" && $obj != "")
  1036.                 $resultGraph->add(new Statement($sub,$pred,$obj));
  1037.  
  1038.             }
  1039.             $bnode++;
  1040.         }
  1041.         return $resultGraph;
  1042.     }
  1043.  
  1044.     /**
  1045.     * Builds a describing named graph. To define an attribute list for a
  1046.     * several rdf:type look at constants.php
  1047.     *
  1048.     * @param  Array      $vartable 
  1049.     * @return MemModel 
  1050.     */
  1051.     protected function describeGraph($vartable){
  1052.         // build empty named graph
  1053.         $resultGraph new MemModel();
  1054.         // if no where clause fill $vartable
  1055.         $vars $this->query->getResultVars();
  1056.         if($vartable == null){
  1057.             if($vars){
  1058.                 $vartable[0array('?x' => new Resource(substr($vars[0],1,-1)));
  1059.                 $vars[0'?x';
  1060.             }
  1061.         }
  1062.         // fetch attribute list from constants.php
  1063.         global $sparql_describe;
  1064.         // for each resultset
  1065.         foreach($vartable as $resultset){
  1066.             foreach($vars as $varname){
  1067.                 $varvalue $resultset[$varname];
  1068.                 // try to determine rdf:type of the variable
  1069.                 $type $this->_determineType($varvalue,$resultGraph);
  1070.                 // search attribute list defined in constants.php
  1071.                 $list null;
  1072.                 if($type){
  1073.                     if(isset($sparql_describe[strtolower($type->getUri())]))
  1074.                     $list $sparql_describe[strtolower($type->getUri());
  1075.                 }
  1076.                 // search in dataset
  1077.                 $this->_getAttributes($list$resultGraph$varvalue);
  1078.             }
  1079.         }
  1080.  
  1081.         return $resultGraph;
  1082.     }
  1083.  
  1084.     /**
  1085.     * Tries to determine the rdf:type of the variable.
  1086.     *
  1087.     * @param  Node       $var The variable
  1088.     * @param  MemModel   $resultGraph The result graph which describes the Resource
  1089.     * @return String     Uri of the rdf:type
  1090.     */
  1091.     protected function _determineType($var ,$resultGraph ){
  1092.         $type null;
  1093.         // find in namedGraphs
  1094.         if(!$var instanceof Literal){
  1095.             $iter $this->dataset->findInNamedGraphs(null,$var,new Resource(RDF_NAMESPACE_URI.'type'),null,true);
  1096.             while($iter->valid()){
  1097.                 $statement $iter->current();
  1098.                 $type $statement->getObject();
  1099.                 $resultGraph->add($iter->current());
  1100.                 break;
  1101.             }
  1102.         }
  1103.         // if no type information found find in default graph
  1104.         if(!$type){
  1105.             if(!$var instanceof Literal){
  1106.                 $iter1 $this->dataset->findInDefaultGraph($var,new Resource(RDF_NAMESPACE_URI.'type'),null);
  1107.                 $type null;
  1108.                 while($iter1->valid()){
  1109.                     $statement $iter1->current();
  1110.                     $type $statement->getObject();
  1111.                     $resultGraph->add($iter1->current());
  1112.                     break;
  1113.                 }
  1114.             }
  1115.         }
  1116.         return $type;
  1117.     }
  1118.  
  1119.     /**
  1120.     * Search the attributes listed in $list in the dataset.
  1121.     *
  1122.     * @param Array      $list List containing the attributes
  1123.     * @param MemModel   $resultGraph The result graph which describes the Resource
  1124.     * @return void 
  1125.     */
  1126.     protected function _getAttributes($list,$resultGraph$varvalue){
  1127.         if($list){
  1128.             foreach($list as $attribute){
  1129.                 if(!$varvalue instanceof Literal){
  1130.                     $iter2 $this->dataset->findInNamedGraphs(null,$varvalue,new Resource($attribute),null,true);
  1131.                     while($iter2->valid()){
  1132.                         $resultGraph->add($iter2->current());
  1133.                         $iter2->next();
  1134.                     }
  1135.                     $iter3 $this->dataset->findInDefaultGraph($varvalue,new Resource($attribute),null);
  1136.                     while($iter3->valid()){
  1137.                         $resultGraph->add($iter3->current());
  1138.                         $iter3->next();
  1139.                     }
  1140.                 }
  1141.             }
  1142.         }
  1143.  
  1144.  
  1145.     }
  1146.  
  1147.     /**
  1148.     * Eliminates duplicate results.
  1149.     *
  1150.     * @param  Array  $vartable a table that contains the result vars and their bindings
  1151.     * @return Array the result table without duplicate results
  1152.     */
  1153.     protected function distinct($vartable){
  1154.         $index array();
  1155.         foreach($vartable as $key => $value){
  1156.             $key_index="";
  1157.             foreach($value as $k => $v)
  1158.             if($v instanceof Object)
  1159.                 $key_index $key_index.$k.$v->toString();
  1160.             if(isset($index[$key_index]))
  1161.             unset($vartable[$key]);
  1162.             else
  1163.             $index[$key_index]1;
  1164.         }
  1165.         return $vartable;
  1166.     }
  1167.  
  1168.     /**
  1169.     * Generates the result object.
  1170.     *
  1171.     * @param Array          $vartable The result table
  1172.     * @param String/boolean $resultform If set to 'xml' the result will be
  1173.     *                        SPARQL Query Results XML Format as described in http://www.w3.org/TR/rdf-sparql-XMLres/
  1174.     * @return Array/String  The result
  1175.     */
  1176.     protected function returnResult($vartable,$resultform false){
  1177.         $result "false";
  1178.         if($vartable[0]['patternResult']!=null){
  1179.             // sort vars (ORDER BY, LIMIT, OFFSET)
  1180.             $vartable $this->sortVars($vartable[0]['patternResult']);
  1181.  
  1182.             // CONSTRUCT, ASK, DESCRIBE, SELECT
  1183.             ifstrtolower($this->query->getResultForm()) == 'ask'){
  1184.                 if(count($vartable)>0)
  1185.                 $result "true";
  1186.                 else
  1187.                 $result "false";
  1188.             }else if(strtolower($this->query->getResultForm()) == 'construct'){
  1189.                 $result $this->constructGraph($vartable,$this->query->getConstructPattern());
  1190.             }else if(strtolower($this->query->getResultForm()) == 'describe'){
  1191.                 $result $this->describeGraph($vartable);
  1192.             }else{
  1193.                 // get result vars
  1194.                 $vars $this->query->getResultVars();
  1195.                 // select result vars and return a result table
  1196.                 $vartable $this->selectVars($vartable,$vars);
  1197.                 if($this->query->getResultForm()=='select distinct')
  1198.                 $result $this->distinct($vartable);
  1199.                 else
  1200.                 $result $vartable;
  1201.             }
  1202.         }else if(strtolower($this->query->getResultForm()) == 'describe'){
  1203.             $result $this->describeGraph(null);
  1204.         }else if(strtolower($this->query->getResultForm()) == 'construct'){
  1205.             $result $this->constructGraph(false,$this->query->getConstructPattern());
  1206.         }
  1207.         if($resultform == 'xml' && $this->query->getResultForm()!='construct' && $this->query->getResultForm()!='describe')
  1208.         $result $this->buildXmlResult($result);
  1209.  
  1210.         return $result;
  1211.     }
  1212.  
  1213.     /**
  1214.     * Generates an xml string from a given result table.
  1215.     *
  1216.     * @param  $vartable The result table
  1217.     * @return String    The xml result string
  1218.     */
  1219.     protected function buildXmlResult($vartable){
  1220.  
  1221.         if($vartable instanceof NamedGraphMem )
  1222.         return $vartable->writeRdfToString();
  1223.  
  1224.         $result '<sparql xmlns="http://www.w3.org/2005/sparql-results#">';
  1225.         $header '<head>';
  1226.  
  1227.         // build header
  1228.         if(is_array($vartable)){
  1229.             $vars $this->query->getResultVars();
  1230.             $header '<head>';
  1231.             foreach($vars as $value){
  1232.                 $header $header.'<variable name="'.substr($value,1).'"/>';
  1233.             }
  1234.             $header $header.'</head>';
  1235.  
  1236.             // build results
  1237.             $solm $this->query->getSolutionModifier();
  1238.             $sel  $this->query->getResultForm();
  1239.  
  1240.             $distinct 'false';
  1241.             if($sel == 'select distinct')
  1242.             $distinct 'true';
  1243.  
  1244.             $ordered 'false';
  1245.             if($solm['order by'!= 0)
  1246.             $ordered 'true';
  1247.  
  1248.             $results '<results ordered="'.$ordered.'" distinct="'.$distinct.'">';
  1249.             foreach($vartable as $value){
  1250.                 $results $results.'<result>';
  1251.                 foreach($value as $varname => $varvalue)
  1252.                 $results $results.$this->_getBindingString(substr($varname,1),$varvalue);
  1253.                 $results $results.'</result>';
  1254.             }
  1255.             $results $results.'</results>';
  1256.         }else{
  1257.             $results '</head><boolean>'.$vartable.'</boolean>';
  1258.         }
  1259.         $result $result.$header.$results.'</sparql>';
  1260.         $result simplexml_load_string($result);
  1261.         return $result->asXML();
  1262.  
  1263.     }
  1264.  
  1265.     /**
  1266.     * Helper Function for function buildXmlResult($vartable). Generates
  1267.     * an xml string for a single variable an their corresponding value.
  1268.     *
  1269.     * @param  String  $varname The variables name
  1270.     * @param  Node    $varvalue The value of the variable
  1271.     * @return String  The xml string
  1272.     */
  1273.     protected function _getBindingString($varname,$varvalue){
  1274.         $binding '<binding name="'.$varname.'">';
  1275.         $value '<unbound/>';
  1276.  
  1277.         if($varvalue instanceof BlankNode ){
  1278.             $value '<bnode>'.$varvalue->getLabel().'</bnode>';
  1279.         }elseif ($varvalue instanceof Resource){
  1280.             $value '<uri>'.$varvalue->getUri().'</uri>';
  1281.         }elseif ($varvalue instanceof Literal){
  1282.             $label htmlentities($varvalue->getLabel());
  1283.             $value '<literal>'.$label.'</literal>';
  1284.             if($varvalue->getDatatype(!= null)
  1285.             $value '<literal datatype="'.$varvalue->getDatatype().'">'.$label.'</literal>';
  1286.             if($varvalue->getLanguage(!= null)
  1287.             $value '<literal xml:lang="'.$varvalue->getLanguage().'">'.$label.'</literal>';
  1288.         }
  1289.         $binding $binding.$value.'</binding>';
  1290.  
  1291.         return $binding;
  1292.     }
  1293.  
  1294.  
  1295.     /**
  1296.     * Prints a query result as HTML table.
  1297.     * You can change the colors in the configuration file.
  1298.     *
  1299.     * @param array $queryResult [][?VARNAME] = object Node
  1300.     * @return void 
  1301.     */
  1302.     public function writeQueryResultAsHtmlTable($queryResult{
  1303.         // Import Package Utility
  1304.         include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
  1305.  
  1306.         if $queryResult[0== null{
  1307.             echo 'no match<br>';
  1308.             return;
  1309.         }
  1310.         if $queryResult == 'false'{
  1311.             echo 'boolean: false<br>';
  1312.             return;
  1313.         }
  1314.         if $queryResult == 'true'{
  1315.             echo 'boolean: true<br>';
  1316.             return;
  1317.         }
  1318.  
  1319.  
  1320.         echo '<table border="1" cellpadding="3" cellspacing="0"><tr><td><b>No.</b></td>';
  1321.         foreach ($queryResult[0as $varName => $value)
  1322.         echo "<td align='center'><b>$varName</b></td>";
  1323.         echo '</tr>';
  1324.  
  1325.         foreach ($queryResult as $n => $var{
  1326.  
  1327.  
  1328.             echo '<tr><td width="20" align="right">' .($n 1.'.</td>';
  1329.             foreach ($var as $varName => $value{
  1330.                 if($value !=''){
  1331.                     echo INDENTATION INDENTATION '<td bgcolor="';
  1332.                     echo RDFUtil::chooseColor($value);
  1333.                     echo '">';
  1334.                     echo '<p>';
  1335.  
  1336.                     $lang  NULL;
  1337.                     $dtype NULL;
  1338.                     if (is_a($value'Literal')) {
  1339.                         if ($value->getLanguage(!= NULL)
  1340.                         $lang ' <b>(xml:lang="' $value->getLanguage('") </b> ';
  1341.                         if ($value->getDatatype(!= NULL)
  1342.                         $dtype ' <b>(rdf:datatype="' $value->getDatatype('") </b> ';
  1343.                     }
  1344.                     echo  RDFUtil::getNodeTypeName($value.$value->getLabel($lang $dtype .'</p>';
  1345.                 }else{
  1346.                     echo "<td bgcolor='white'>unbound";
  1347.                 }
  1348.             }
  1349.             echo '</tr>';
  1350.         }
  1351.         echo '</table>';
  1352.     }
  1353.  
  1354. // end: Class SparqlEngine
  1355.  
  1356. ?>

Documentation generated on Mon, 26 Jun 2006 14:26:16 +0200 by phpDocumentor 1.3.0RC6