source: Dev/branches/rest-dojo-ui/Demo/rdfapi/util/RdfUtil.php @ 312

Last change on this file since 312 was 312, checked in by jkraaijeveld, 13 years ago
File size: 16.5 KB
Line 
1<?php
2
3// ----------------------------------------------------------------------------------
4// Class: RDFUtil
5// ----------------------------------------------------------------------------------
6
7/**
8* Useful utility methods.
9* Static class.
10*
11* @version  $Id: RdfUtil.php 295 2006-06-23 06:45:53Z tgauss $
12* @author Chris Bizer <chris@bizer.de>, Daniel Westphal <dawe@gmx.de>
13* @author   Anton Köstlbacher <anton1@koestlbacher.de>
14* @package utility
15* @access       public
16**/
17class RDFUtil extends Object {
18
19        /**
20        * Extracts the namespace prefix out of a URI.
21        *
22        * @param        String  $uri
23        * @return       string
24        * @access       public
25        */
26        function guessNamespace($uri) {
27                $l = RDFUtil::getNamespaceEnd($uri);
28                return $l > 1 ? substr($uri ,0, $l) : "";
29        }
30
31        /**
32        * Delivers the name out of the URI (without the namespace prefix).
33        *
34        * @param        String  $uri
35        * @return       string
36        * @access       public
37        */
38        function guessName($uri) {
39                return substr($uri,RDFUtil::getNamespaceEnd($uri));
40        }
41
42        /**
43        * Extracts the namespace prefix out of the URI of a Resource.
44        *
45        * @param        Object Resource $resource
46        * @return       string
47        * @access       public
48        */
49        function getNamespace($resource) {
50                return RDFUtil::guessNamespace($resource->getURI());
51        }
52
53        /**
54        * Delivers the Localname (without the namespace prefix) out of the URI of a Resource.
55        *
56        * @param        Object Resource $resource
57        * @return       string
58        * @access       public
59        */
60        function getLocalName($resource) {
61                return RDFUtil::guessName($resource->getURI());
62        }
63
64        /**
65        * Position of the namespace end
66        * Method looks for # : and /
67        * @param        String  $uri
68        * @access       private
69        */
70        function getNamespaceEnd($uri) {
71                $l = strlen($uri)-1;
72                do {
73                        $c = substr($uri, $l, 1);
74                        if($c == '#' || $c == ':' || $c == '/')
75                        break;
76                        $l--;
77                } while ($l >= 0);
78                $l++;
79                return $l;
80        }
81
82                /**
83        * Short Prefix for known Namespaces by given URI
84        * @param        String  $uri
85        * @access       public
86        */
87        function getPrefix($uri) {
88            switch (RDFUtil::guessNamespace($uri))
89            {
90                case RDF_NAMESPACE_URI:
91                $prefix = RDF_NAMESPACE_PREFIX;
92                break;
93
94                case RDF_SCHEMA_URI:
95                $short_p = RDF_SCHEMA_PREFIX;
96                break;
97
98                case OWL_URI:
99                $short_p = OWL_PREFIX;
100                break;
101
102                default:
103                $short_p = $statement->getLabelPredicate();
104            }
105            return $short_p;
106        }
107
108
109        /**
110        * Tests if the URI of a resource belongs to the RDF syntax/model namespace.
111        *
112        * @param        Object Resource $resource
113        * @return       boolean
114        * @access       public
115        */
116        function isRDF($resource) {
117                return ($resource != NULL && RDFUtil::getNamespace($resource) == RDF_NAMESPACE_URI);
118        }
119
120        /**
121        * Escapes < > and &
122        *
123        * @param        String  $textValue
124        * @return       String
125        * @access       public
126        */
127        function escapeValue($textValue) {
128
129                $textValue = str_replace('<', '&lt;', $textValue);
130                $textValue = str_replace('>', '&gt;', $textValue);
131                $textValue = str_replace('&', '&amp;', $textValue);
132
133                return $textValue;
134        }
135
136        /**
137        * Converts an ordinal RDF resource to an integer.
138        * e.g. Resource(RDF:_1) => 1
139        *
140        * @param        object Resource $resource
141        * @return       Integer
142        * @access       public
143        */
144        function getOrd($resource)  {
145                if($resource == NULL || !is_a($resource, 'Resource') || !RDFUtil::isRDF($resource))
146                return -1;
147                $name = RDFUtil::getLocalName($resource);
148                echo substr($name, 1).' '.RDFUtil::getLocalName($resource);
149                $n = substr($name, 1);
150                //noch rein : chekcen ob $n Nummer ist !!!!!!!!!!!!!!!!!!!!!!if($n)
151                return $n;
152                return -1;
153        }
154
155        /**
156        * Creates ordinal RDF resource out of an integer.
157        *
158        * @param        Integer $num
159        * @return       object Resource
160        * @access       public
161        */
162        function createOrd($num)  {
163                return new Resource(RDF_NAMESPACE_URI . '_' . $num);
164        }
165
166        /**
167        * Prints a MemModel as HTML table.
168        * You can change the colors in the configuration file.
169        *
170        * @param        object MemModel         &$model
171        * @access       public
172        */
173        function writeHTMLTable(&$model)  {
174                $nms = $model->getParsedNamespaces();
175                $names = '';
176                $pre = '';
177
178
179                echo '<table border="1" cellpadding="3" cellspacing="0" width="100%">' . LINEFEED;
180                echo INDENTATION . '<tr bgcolor="' . HTML_TABLE_HEADER_COLOR . '">' . LINEFEED . INDENTATION . INDENTATION . '<td td width="68%" colspan="3">';
181                echo '<p><b>Base URI:</b> ' . $model->getBaseURI() . '</p></td>' . LINEFEED;
182                echo INDENTATION . INDENTATION . '<td width="32%"><p><b>Size:</b> ' . $model->size() . '</p></td>' . LINEFEED . INDENTATION . '</tr>';
183
184                echo '<tr><td><b>Prefix:</b>'.'<br/></td><td colspan="3"><b>Namespace:</b>'.'<br/></td></tr>';
185                $i=0;
186                if($nms != false){
187                        foreach($nms as $namespace => $prefix){
188                                if($i==0){
189                                        $col = HTML_TABLE_NS_ROW_COLOR0;
190                                }else{
191                                        $col = HTML_TABLE_NS_ROW_COLOR1;
192                                }
193                                echo '<tr bgcolor="'.$col.'"><td>'.$prefix.'</td><td colspan="3">'.$namespace.'</td></tr>';
194                                $i++;
195                                $i%=2;
196                        }
197                }else{
198                        echo '<tr><td>-</td><td colspan="3">-</td></tr>';
199                }
200
201
202
203
204                echo INDENTATION . '<tr bgcolor="' . HTML_TABLE_HEADER_COLOR . '">' . LINEFEED . INDENTATION . INDENTATION . '<td width="4%"><p align=center><b>No.</b></p></td>' . LINEFEED . INDENTATION . INDENTATION . '<td width="32%"><p><b>Subject</b></p></td>' . LINEFEED . INDENTATION . INDENTATION . '<td width="32%"><p><b>Predicate</b></p></td>' . LINEFEED . INDENTATION . INDENTATION . '<td width="32%"><p><b>Object</b></p></td>' . LINEFEED . INDENTATION . '</tr>' . LINEFEED;
205
206                $i = 1;
207                foreach($model->triples as $key => $statement) {
208                        $infered='';
209                        if (is_a($statement,'InfStatement')) $infered='<small>(infered)</small>';
210                        echo INDENTATION . '<tr valign="top">' . LINEFEED . INDENTATION . INDENTATION . '<td><p align=center>' . $i . '.<BR>'.$infered.'</p></td>' . LINEFEED;
211                        // subject
212                        echo INDENTATION . INDENTATION . '<td bgcolor="';
213                        echo RDFUtil::chooseColor($statement->getSubject());
214                        echo '">';
215                        echo '<p>' .  RDFUtil::getNodeTypeName($statement->getSubject());
216                        if(is_a($statement->subj,'Resource')){
217                                $ns = $statement->subj->getNamespace();
218                                if(isset($nms[$ns])){
219                                        echo $nms[$ns].':'.RDFUtil::getLocalName($statement->subj);
220                                }else{
221                                        echo $statement->subj->getLabel();
222                                }
223                        }
224                        echo '</p></td>' .  LINEFEED;
225                        // predicate
226                        echo INDENTATION . INDENTATION . '<td bgcolor="';
227                        echo RDFUtil::chooseColor($statement->getPredicate());
228                        echo '">';
229                        echo '<p>' . RDFUtil::getNodeTypeName($statement->getPredicate());
230                        if(is_a($statement->pred,'Resource')){
231                                $ns = $statement->pred->getNamespace();
232                                if(isset($nms[$ns])){
233                                        echo $nms[$ns].':'.RDFUtil::getLocalName($statement->pred);
234                                }else{
235                                        echo $statement->pred->getLabel();
236                                }
237                        }
238                        echo '</p></td>' .  LINEFEED;
239                        // object
240                        echo INDENTATION . INDENTATION . '<td bgcolor="';
241                        echo RDFUtil::chooseColor($statement->getObject());
242                        echo '">';
243                        echo '<p>';
244                        if (is_a($statement->getObject(), 'Literal')) {
245                                if ($statement->obj->getLanguage() != null) {
246                                        $lang = ' <b>(xml:lang="' . $statement->obj->getLanguage() . '") </b> ';
247                                } ELSE $lang = '';
248                                if ($statement->obj->getDatatype() != null) {
249                                        $dtype = ' <b>(rdf:datatype="' . $statement->obj->getDatatype() . '") </b> ';
250                                } ELSE $dtype = '';
251                        } else {
252                                $lang = '';
253                                $dtype = '';
254                        }
255                        $label = $statement->obj->getLabel();
256                        if(is_a($statement->obj,'Resource')){
257                                $ns = $statement->obj->getNamespace();
258                                if(isset($nms[$ns])){
259                                        $label = $nms[$ns].':'.RDFUtil::getLocalName($statement->obj);
260                                }else{
261                                        $label = $statement->obj->getLabel();
262                                }
263                        }
264
265                        echo  RDFUtil::getNodeTypeName($statement->getObject())
266                        .nl2br(htmlspecialchars($label)) . $lang . $dtype;
267
268                        echo '</p></td>' . LINEFEED;
269                        echo INDENTATION . '</tr>' . LINEFEED;
270                        $i++;
271                }
272                echo '</table>' . LINEFEED;
273        }
274
275        /**
276        * Chooses a node color.
277        * Used by RDFUtil::writeHTMLTable()
278        *
279        * @param        object Node     $node
280        * @return       object Resource
281        * @access       private
282        */
283        function chooseColor($node)  {
284                if (is_a($node, 'BlankNode'))
285                return HTML_TABLE_BNODE_COLOR;
286                elseif (is_a($node, 'Literal'))
287                return HTML_TABLE_LITERAL_COLOR;
288                else {
289                        if (RDFUtil::getNamespace($node) == RDF_NAMESPACE_URI ||
290                        RDFUtil::getNamespace($node) == RDF_SCHEMA_URI ||
291                        RDFUtil::getNamespace($node) == OWL_URI
292                        )
293
294                        return HTML_TABLE_RDF_NS_COLOR;
295                }
296                return HTML_TABLE_RESOURCE_COLOR;
297
298        }
299
300        /**
301        * Get Node Type.
302        * Used by RDFUtil::writeHTMLTable()
303        *
304        * @param        object Node     $node
305        * @return       object Resource
306        * @access       private
307        */
308        function getNodeTypeName($node)  {
309                if (is_a($node, "BlankNode"))
310                return 'Blank Node: ';
311                elseif (is_a($node, 'Literal'))
312                return 'Literal: ';
313                else {
314                        if (RDFUtil::getNamespace($node) == RDF_NAMESPACE_URI ||
315                        RDFUtil::getNamespace($node) == RDF_SCHEMA_URI ||
316                        RDFUtil::getNamespace($node) == OWL_URI)
317                        return 'RDF Node: ';
318                }
319                return 'Resource: ';
320
321        }
322
323
324 /**
325 * Short Prefix for known and/or parsed Namespaces by given URI and Model
326 * Uses $default_prefixes defined in constants.php and getParsedNamespaces()
327 * Returns FALSE if no matching prefix is found
328 *
329 * @author   Anton Köstlbacher <anton1@koestlbacher.de>
330 * @param    string  $uri
331 * @param    object $model
332 * @return   string, boolean
333 * @access   public
334 * @throws   PhpError
335 */
336
337 function guessPrefix($uri, &$model)
338 {
339     global $default_prefixes;
340     $namespace = RDFUtil::guessNamespace($uri);
341     $par_nms   = $model->getParsedNamespaces();
342     if (isset($par_nms[$namespace]))
343     {
344         $prefix = $par_nms[$namespace];
345     }
346     else
347     {
348         $prefix = array_search($namespace, $default_prefixes);
349     }
350     if($prefix !== false)
351     {
352        return $prefix;
353     }
354     else
355     {
356        return false;
357     }
358 }
359
360
361 /**
362 * Generates a dot-file for drawing graphical output with the
363 * graphviz-application which can be downloaded at http://www.graphviz.org
364 * If the graphviz-application is installed and its path is set to the
365 * correct value in constants.php we can directly generate any
366 * file format graphviz supports, e.g. SVG, PNG
367 * Parameters: model to visualize, output format, use prefixes
368 *
369 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
370 * WARNING: Graphviz can be slow with large models.
371 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
372 *
373 * @author   Anton Köstlbacher <anton1@koestlbacher.de>
374 * @param    object  Model
375 * @param    string  $format
376 * @param    boolean $short_prefix
377 * @return   string, binary
378 * @access   public
379 * @throws   PhpError
380 */
381
382 function visualizeGraph(&$model, $format = "input_dot", $short_prefix = TRUE)
383 {
384     global $graphviz_param;
385     $i = 0;
386
387     foreach ($model->triples as $key => $statement)
388     {
389         $subject   = $statement->getLabelSubject();
390         $predicate = $statement->getLabelPredicate();
391         $object    = $statement->getLabelObject();
392
393         // format subject
394         if (!isset($attrib[$subject]))
395         {
396             if (is_a($statement->subject(),'BlankNode'))
397             {
398                 $attrib[$subject] = $graphviz_param['BLANKNODE_STYLE'];
399             }
400             else
401             {
402                 if ($short_prefix == TRUE && RDFUtil::guessPrefix($subject, $model) != FALSE)
403                 {
404                     $prefix = RDFUtil::guessPrefix($subject, $model);
405                     $subject_label = $prefix.":".RDFUtil::guessName($subject);
406                     $attrib[$subject] = "label=\"".$subject_label."\" ";
407                     if(!isset($prefix_array[$prefix]))
408                     {
409                         $prefix_array[$prefix] = RDFUtil::guessNamespace($subject);
410                     }
411                 }
412                 if (GRAPHVIZ_URI == TRUE)
413                 {
414                     $attrib[$subject] .= "URL=\"".$subject."\"";
415                 }
416             }
417         }
418
419         // format predicate
420         if ($short_prefix == TRUE && RDFUtil::guessPrefix($predicate, $model) != FALSE)
421         {
422             $prefix = RDFUtil::guessPrefix($predicate, $model);
423             $predicate_label = "label=\"".$prefix.":".RDFUtil::guessName($predicate)."\"";
424             if(!isset($prefix_array[$prefix]))
425             {
426                 $prefix_array[$prefix] = RDFUtil::guessNamespace($predicate);
427             }
428         }
429         else
430         {
431             $predicate_label = "label=\"".$predicate."\"";
432         }
433
434        if (is_a($statement,'InfStatement'))
435         {
436             $predicate_label .= " ".$graphviz_param['INFERRED_STYLE'];
437         }
438         else
439         {
440             if (GRAPHVIZ_URI == TRUE)
441             {
442                 $predicate_label .= "URL=\"".$predicate."\"";
443             }
444         }
445
446         // format object
447         if (!isset($attrib[$object]))
448         {
449             if (is_a($statement->object(),'BlankNode'))
450             {
451                 $attrib[$object] = $graphviz_param['BLANKNODE_STYLE'];
452             }
453             elseif (is_a($statement->object(),'Literal'))
454             {
455                 $object_label = $object;
456                 $object = "literal".$i;
457                 $i++;
458                 $attrib[$object] = "label=\"$object_label\" ".$graphviz_param['LITERAL_STYLE'];
459             }
460             else
461             {
462                 if ($short_prefix == TRUE && RDFUtil::guessPrefix($object, $model) != FALSE)
463                 {
464                     $prefix = RDFUtil::guessPrefix($object, $model);
465                     $object_label = $prefix.":".RDFUtil::guessName($object);
466                     $attrib[$object] = "label=\"".$object_label."\" ";
467                     if(!isset($prefix_array[$prefix]))
468                     {
469                         $prefix_array[$prefix] = RDFUtil::guessNamespace($object);
470                     }
471                 }
472                 if (GRAPHVIZ_URI == TRUE)
473                 {
474                     $attrib[$object] .= "URL=\"".$object."\"";
475                 }
476             }
477         }
478
479         // fill graph array
480         $graph[] = "\"".$subject."\" -> \"".$object."\" [".$predicate_label."];";
481     }
482
483     //generate DOT-file
484     $dot = "digraph G { ".$graphviz_param['GRAPH_STYLE']."\n edge [".$graphviz_param['PREDICATE_STYLE']."]\n node [".$graphviz_param['RESOURCE_STYLE']."]\n";
485     if (isset($attrib))
486     {
487         foreach ($attrib AS $key => $value)
488         {
489             $dot .= "\"$key\" [$value];\n";
490         }
491     }
492     if (!isset($graph))
493     {
494         $dot .= "error [shape=box,label=\"No Statements found!\"]";
495     }
496     else
497     {
498         $dot .= implode("\n", $graph);
499     }
500
501
502     if (GRAPHVIZ_STAT == TRUE)
503     {
504        $stat_label = "| ".$model->size()." Statements drawn";
505     }
506     if ((strstr($graphviz_param['GRAPH_STYLE'], 'rankdir="LR"') === FALSE) && (strstr($graphviz_param['GRAPH_STYLE'], 'rankdir=LR') === FALSE))
507     {
508         $sep1 = "}";
509         $sep2 = "";
510     }
511     else
512     {
513         $sep1 = "";
514         $sep2 = "}";
515     }
516
517     if ($short_prefix == TRUE && isset($prefix_array))
518     {
519         $struct_label = "{ { Base URI: ".$model->getBaseURI()." $sep1 | { { ".implode("|", array_keys($prefix_array))." } | { ".implode("|", $prefix_array)." } } $stat_label } $sep2";
520     }
521     else
522     {
523         $struct_label = "{ { Base URI: ".$model->getBaseURI()."$sep1 ".$stat_label." } }";
524     }
525
526     $dot .= "\n struct [shape=Mrecord,label=\"$struct_label\",".$graphviz_param['BOX_STYLE']."];\n";
527     $dot .= " vocabulary [style=invis];\n struct -> vocabulary [style=invis];\n}";
528
529     // if needed call dot.exe
530     if (($format != "input_dot") && (defined('GRAPHVIZ_PATH')) && (strstr(GRAPHVIZ_FORMAT, $format) !== FALSE))
531     {
532         mt_srand((double)microtime()*1000000);
533         $filename=GRAPHVIZ_TEMP.md5(uniqid(mt_rand())).".dot";
534         $file_handle = @fopen($filename, 'w');
535         if ($file_handle)
536         {
537             fwrite($file_handle, $dot);
538             fclose($file_handle);
539         }
540         $dotinput = " -T".$format." ".$filename;
541
542         ob_start();
543        passthru(GRAPHVIZ_PATH.$dotinput);
544         $output = ob_get_contents();
545        ob_end_clean();
546         unlink($filename);
547         echo $output;
548         return TRUE;
549     }
550     elseif ($format == "input_dot")
551     {
552         echo $dot;
553         return TRUE;
554     }
555     else
556     {
557         return FALSE;
558     }
559 }
560
561} // end: RDfUtil
562
563?>
Note: See TracBrowser for help on using the repository browser.