PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/s3db3.5.10/pearlib/rdfapi-php/api/model/Model.php

https://code.google.com/p/s3db/
PHP | 541 lines | 278 code | 67 blank | 196 comment | 52 complexity | 0b0d4deca80dcbdbb56e3b4b4d0d5334 MD5 | raw file
  1. <?php
  2. // ----------------------------------------------------------------------------------
  3. // Class: Model
  4. // ----------------------------------------------------------------------------------
  5. /**
  6. * Abstract superclass of MemModel and DbModel. A model is a programming interface to an RDF graph.
  7. * An RDF graph is a directed labeled graph, as described in http://www.w3.org/TR/rdf-mt/.
  8. * It can be defined as a set of <S, P, O> triples, where P is a uriref, S is either
  9. * a uriref or a blank node, and O is either a uriref, a blank node, or a literal.
  10. *
  11. *
  12. * @version $Id: Model.php,v 1.48 2007/05/01 12:59:18 cweiske Exp $
  13. * @author Radoslaw Oldakowski <radol@gmx.de>
  14. * @author Daniel Westphal <mail@d-westphal.de>
  15. *
  16. * @package model
  17. * @access public
  18. */
  19. class Model extends Object
  20. {
  21. /**
  22. * Base URI of the Model.
  23. * Affects creating of new resources and serialization syntax.
  24. *
  25. * @var string
  26. * @access private
  27. */
  28. var $baseURI;
  29. /**
  30. * Number of the last assigned bNode.
  31. *
  32. * @var integer
  33. * @access private
  34. */
  35. var $bNodeCount;
  36. /**
  37. * SparqlParser so we can re-use it
  38. * @var Parser
  39. */
  40. var $queryParser = null;
  41. /**
  42. * Notice for people who are used to work with older versions of RAP.
  43. *
  44. * @throws PHPError
  45. * @access public
  46. */
  47. function Model()
  48. {
  49. $errmsg = 'Since RAP 0.6 the class for manipulating memory models has been renamed to MemModel.';
  50. $errmsg .= '<br>Sorry for this inconvenience.<br>';
  51. trigger_error($errmsg, E_USER_ERROR);
  52. }
  53. /**
  54. * Return current baseURI.
  55. *
  56. * @return string
  57. * @access public
  58. */
  59. function getBaseURI()
  60. {
  61. return $this->baseURI;
  62. }
  63. /**
  64. * Load a model from a file containing RDF, N3, N-Triples or a xhtml document containing RDF.
  65. * This function recognizes the suffix of the filename (.n3 or .rdf) and
  66. * calls a suitable parser, if no $type is given as string ("rdf" "n3" "nt");
  67. * If the model is not empty, the contents of the file is added to this DbModel.
  68. *
  69. * @param string $filename
  70. * @param string $type
  71. * @param boolean $stream
  72. * @access public
  73. */
  74. function load($filename, $type = NULL, $stream=false)
  75. {
  76. if ((isset($type)) && ($type =='n3') OR ($type =='nt')) {
  77. // Import Package Syntax
  78. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
  79. $parser = new N3Parser();
  80. }elseif ((isset($type)) && ($type =='rdf')) {
  81. // Import Package Syntax
  82. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
  83. $parser = new RdfParser();
  84. }elseif ((isset($type)) && ($type =='grddl')) {
  85. // Import Package Syntax
  86. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_GRDDL);
  87. $parser = new GRDDLParser();
  88. }elseif ((isset($type)) && ($type =='rss')) {
  89. // Import Package Syntax
  90. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RSS);
  91. $parser = new RssParser();
  92. }else {
  93. // create a parser according to the suffix of the filename
  94. // if there is no suffix assume the file to be XML/RDF
  95. preg_match("/\.([a-zA-Z0-9_]+)$/", $filename, $suffix);
  96. if (isset($suffix[1]) && (strtolower($suffix[1]) == 'n3' OR strtolower($suffix[1]) == 'nt')){
  97. // Import Package Syntax
  98. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
  99. $parser = new N3Parser();
  100. }elseif (isset($suffix[1]) && (strtolower($suffix[1]) == 'htm' OR strtolower($suffix[1]) == 'html' OR strtolower($suffix[1]) == 'xhtml')){
  101. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_GRDDL);
  102. $parser = new GRDDLParser();
  103. }else{
  104. // Import Package Syntax
  105. include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
  106. $parser = new RdfParser();
  107. }
  108. };
  109. if (($stream && $type=='rdf')||($stream && $type=='n3')) {
  110. $temp=&$parser->generateModel($filename,false,$this);
  111. } else{
  112. $temp=&$parser->generateModel($filename);
  113. }
  114. $this->addModel($temp);
  115. if($this->getBaseURI()== null)
  116. $this->setBaseURI($temp->getBaseURI());
  117. }
  118. /**
  119. * Adds a statement from another model to this model.
  120. * If the statement to be added contains a blankNode with an identifier
  121. * already existing in this model, a new blankNode is generated.
  122. *
  123. * @param Object Statement $statement
  124. * @access private
  125. */
  126. function _addStatementFromAnotherModel($statement, &$blankNodes_tmp)
  127. {
  128. $subject = $statement->getSubject();
  129. $object = $statement->getObject();
  130. if (is_a($subject, "BlankNode")) {
  131. $label = $subject->getLabel();
  132. if (!array_key_exists($label, $blankNodes_tmp))
  133. {
  134. if ($this->findFirstMatchingStatement($subject, NULL, NULL)
  135. || $this->findFirstMatchingStatement(NULL, NULL, $subject))
  136. {
  137. $blankNodes_tmp[$label] = new BlankNode($this);
  138. $statement->subj = $blankNodes_tmp[$label];
  139. } else {
  140. $blankNodes_tmp[$label] = $subject;
  141. }
  142. } else
  143. $statement->subj = $blankNodes_tmp[$label];
  144. }
  145. if (is_a($object, "BlankNode")) {
  146. $label = $object->getLabel();
  147. if (!array_key_exists($label, $blankNodes_tmp))
  148. {
  149. if ($this->findFirstMatchingStatement($object, NULL, NULL)
  150. || $this->findFirstMatchingStatement(NULL, NULL, $object))
  151. {
  152. $blankNodes_tmp[$label] = new BlankNode($this);
  153. $statement->obj = $blankNodes_tmp[$label];
  154. } else {
  155. $blankNodes_tmp[$label] = $object;
  156. }
  157. } else
  158. $statement->obj = $blankNodes_tmp[$label];
  159. }
  160. $this->add($statement);
  161. }
  162. /**
  163. * Internal method, that returns a resource URI that is unique for the Model.
  164. * URIs are generated using the base_uri of the DbModel, the prefix and a unique number.
  165. * If no prefix is defined, the bNode prefix, defined in constants.php, is used.
  166. *
  167. * @param string $prefix
  168. * @return string
  169. * @access private
  170. */
  171. function getUniqueResourceURI($prefix = false)
  172. {
  173. static $bNodeCount;
  174. if(!$bNodeCount)
  175. $bNodeCount = 0;
  176. if(!$prefix)
  177. $prefix=BNODE_PREFIX;
  178. return $prefix.++$bNodeCount;
  179. }
  180. /**
  181. * Returns a ResModel with this model as baseModel. This is the same as
  182. * ModelFactory::getResModelForBaseModel($this).
  183. *
  184. * @return object ResModel
  185. * @access public
  186. */
  187. function & getResModel()
  188. {
  189. return ModelFactory::getResModelForBaseModel($this);
  190. }
  191. /**
  192. * Returns an OntModel with this model as baseModel.
  193. * $vocabulary has to be one of the following constants (currently only one is supported):
  194. * RDFS_VOCABULARY to select a RDFS Vocabulary.
  195. *
  196. * This is the same as ModelFactory::getOntModelForBaseModel($this, $vocabulary).
  197. *
  198. * @param constant $vocabulary
  199. * @return object OntModel
  200. * @access public
  201. */
  202. function & getOntModel($vocabulary)
  203. {
  204. return ModelFactory::getOntModelForBaseModel($this, $vocabulary);
  205. }
  206. /**
  207. * Searches for triples using find() and tracks forward blank nodes
  208. * until the final objects in the retrieved subgraphs are all named resources.
  209. * The method calls itself recursivly until the result is complete.
  210. * NULL input for subject, predicate or object will match anything.
  211. * Inputparameters are ignored for recursivly found statements.
  212. * Returns a new MemModel or adds (without checking for duplicates)
  213. * the found statements to a given MemModel.
  214. * Returns an empty MemModel, if nothing is found.
  215. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  216. * WARNING: This method can be slow with large models.
  217. * NOTE: Blank nodes are not renamed, they keep the same nodeIDs
  218. * as in the queried model!
  219. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  220. *
  221. * @author Anton Koestlbacher <anton1@koestlbacher.de>
  222. * @param object Node $subject
  223. * @param object Node $predicate
  224. * @param object Node $object
  225. * @param object MemModel $object
  226. * @return object MemModel
  227. * @access public
  228. * @throws PhpError
  229. */
  230. function findForward($subject, $predicate, $object, &$newModel = NULL)
  231. {
  232. if (!is_a($newModel, "MemModel"))
  233. {
  234. $newModel = New MemModel;
  235. }
  236. if (is_a($this, "DbModel"))
  237. {
  238. $model = $this;
  239. $res = $model->find($subject, $predicate, $object);
  240. $it = $res->getStatementIterator();
  241. }
  242. elseif (is_a($this, "MemModel")) {
  243. $model = $this;
  244. $it = $model->findAsIterator($subject, $predicate, $object);
  245. }
  246. elseif (is_a($this, "ResModel")) {
  247. $model = $this->model;
  248. $it = $model->findAsIterator($subject, $predicate, $object);
  249. }
  250. while ($it->hasNext())
  251. {
  252. $statement = $it->next();
  253. $newModel->add($statement);
  254. if (is_a($statement->object(),'BlankNode'))
  255. {
  256. $model->findForward($statement->object(), NULL, NULL, $newModel);
  257. }
  258. }
  259. return $newModel;
  260. }
  261. /**
  262. * Perform an RDQL query on this Model. Should work with all types of models.
  263. * This method returns a MemModel containing the result statements.
  264. * If $closure is set to TRUE, the result will additionally contain
  265. * statements found by the findForward-method for blank nodes.
  266. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  267. * WARNING: If called with $closure = TRUE this method
  268. * can be slow with large models.
  269. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  270. *
  271. * @author Anton K???tlbacher <anton1@koestlbacher.de>
  272. * @author code snippets taken from the RAP Netapi by Phil Dawes and Chris Bizer
  273. * @access public
  274. * @param string $queryString
  275. * @param boolean $closure
  276. * @return object MemModel
  277. *
  278. */
  279. function & getMemModelByRDQL($queryString, $closure = FALSE)
  280. {
  281. require_once(RDFAPI_INCLUDE_DIR.PACKAGE_RDQL);
  282. $parser = new RdqlParser();
  283. $parsedQuery =& $parser->parseQuery($queryString);
  284. // If there are variables used in the pattern but not
  285. // in the select clause, add them to the select clause
  286. foreach ($parsedQuery['patterns'] as $n => $pattern)
  287. {
  288. foreach ($pattern as $key => $val_1)
  289. {
  290. if ($val_1['value']{0}=='?')
  291. {
  292. if (!in_array($val_1['value'],$parsedQuery['selectVars']))
  293. {
  294. array_push($parsedQuery['selectVars'],$val_1['value']);
  295. }
  296. }
  297. }
  298. }
  299. if (is_a($this, "DbModel"))
  300. {
  301. $engine = new RdqlDbEngine();
  302. $model = $this;
  303. }
  304. elseif (is_a($this, "MemModel"))
  305. {
  306. $engine = new RdqlMemEngine();
  307. $model = $this;
  308. }
  309. elseif (is_a($this, "ResModel"))
  310. {
  311. $engine = new RdqlMemEngine();
  312. $model = $this->model;
  313. }
  314. $res = $engine->queryModel($model,$parsedQuery,TRUE);
  315. $rdqlIter = new RdqlResultIterator($res);
  316. $newModel = new MemModel();
  317. // Build statements from RdqlResultIterator
  318. while ($rdqlIter->hasNext()) {
  319. $result = $rdqlIter->next();
  320. foreach ($parsedQuery['patterns'] as $n => $pattern)
  321. {
  322. if (substr($pattern['subject']['value'], 0, 1) == '?')
  323. {
  324. $subj = $result[$pattern['subject']['value']];
  325. }
  326. else
  327. {
  328. $subj = new Resource($pattern['subject']['value']);
  329. }
  330. if (substr($pattern['predicate']['value'], 0, 1) == '?')
  331. {
  332. $pred = $result[$pattern['predicate']['value']];
  333. }
  334. else
  335. {
  336. $pred = new Resource($pattern['predicate']['value']);
  337. }
  338. if (substr($pattern['object']['value'], 0, 1) == '?')
  339. {
  340. $obj = $result[$pattern['object']['value']];
  341. }
  342. else
  343. {
  344. if (isset($pattern['object']['is_literal']))
  345. {
  346. $obj = new Literal($pattern['object']['value']);
  347. $obj->setDatatype($pattern['object']['l_dtype']);
  348. $obj->setLanguage($pattern['object']['l_lang']);
  349. }
  350. else
  351. {
  352. $obj = new Resource($pattern['object']['value']);
  353. }
  354. }
  355. $statement = new Statement($subj,$pred,$obj);
  356. $newModel->add($statement);
  357. // findForward() Statements containing an eventually given blank node
  358. // and add them to the result, if closure = true
  359. if (is_a($statement->object(),'BlankNode') && $closure == True)
  360. {
  361. $newModel = $model->findForward($statement->object(),NULL,NULL, $newModel);
  362. }
  363. if (is_a($statement->subject(),'BlankNode') && $closure == True)
  364. {
  365. $newModel = $model->findForward($statement->subject(),NULL,NULL, $newModel);
  366. }
  367. }
  368. }
  369. return $newModel;
  370. }
  371. /**
  372. * Alias for RDFUtil::visualiseGraph(&$model, $format, $short_prefix)
  373. *
  374. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  375. * Note: See RDFUtil for further Information.
  376. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  377. *
  378. * @author Anton K???tlbacher <anton1@koestlbacher.de>
  379. * @param string $format
  380. * @param boolean $short_prefix
  381. * @return string, binary
  382. * @access public
  383. * @throws PhpError
  384. */
  385. function visualize($format = "dot", $short_prefix = TRUE)
  386. {
  387. return RDFUtil::visualizeGraph($this, $format, $short_prefix);
  388. }
  389. /**
  390. * Performs a SPARQL query against a model. The model is converted to
  391. * an RDF Dataset. The result can be retrived in SPARQL Query Results XML Format or
  392. * as an array containing the variables an their bindings.
  393. *
  394. * @param string $query the sparql query string
  395. * @param string $resultform the result form ('xml' for SPARQL Query Results XML Format)
  396. * @return string/array
  397. */
  398. function sparqlQuery($query, $resultform = false)
  399. {
  400. list($engine, $dataset) = $this->_prepareSparql();
  401. return $engine->queryModel(
  402. $dataset,
  403. $this->_parseSparqlQuery($query),
  404. $resultform
  405. );
  406. }//function sparqlQuery($query,$resultform = false)
  407. /**
  408. * Prepares a sparql query and returns a prepared statement
  409. * that can be executed with data later on.
  410. *
  411. * @param string $query Sparql query to prepare.
  412. * @return SparqlEngine_PreparedStatement prepared statement object
  413. */
  414. function sparqlPrepare($query)
  415. {
  416. list($engine, $dataset) = $this->_prepareSparql();
  417. return $engine->prepare(
  418. $dataset,
  419. $this->_parseSparqlQuery($query)
  420. );
  421. }//function sparqlPrepare($query)
  422. /**
  423. * Prepares everything for SparqlEngine-usage
  424. * Loads the files, creates instances for SparqlEngine and
  425. * Dataset...
  426. *
  427. * @return array First value is the sparql engine, second the dataset
  428. */
  429. function _prepareSparql()
  430. {
  431. require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine.php';
  432. require_once RDFAPI_INCLUDE_DIR . 'dataset/DatasetMem.php';
  433. $dataset = new DatasetMem();
  434. $dataset->setDefaultGraph($this);
  435. return array(
  436. SparqlEngine::factory($this),
  437. $dataset
  438. );
  439. }//function _prepareSparql()
  440. /**
  441. * Parses an query and returns the parsed form.
  442. * If the query is not a string but a Query object,
  443. * it will just be returned.
  444. *
  445. * @param $query mixed String or Query object
  446. * @return Query query object
  447. * @throws Exception If $query is no string and no Query object
  448. */
  449. function _parseSparqlQuery($query)
  450. {
  451. if ($this->queryParser === null) {
  452. require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlParser.php';
  453. $this->queryParser = new SparqlParser();
  454. }
  455. return $this->queryParser->parse($query);
  456. }//function _parseSparqlQuery($query)
  457. function s3db_parseSparqlQuery($query)
  458. {#Stays here until i figure out a way to call this function without messing up the original one
  459. if ($this->queryParser === null) {
  460. require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlParser.php';
  461. $this->queryParser = new SparqlParser();
  462. }
  463. #echo '<pre>';print_r($this); exit;
  464. $parsedQuery = $this->queryParser->s3db_parse($query);
  465. #echo '<pre>';print_r($parsedQuery);exit;
  466. return $parsedQuery;
  467. }//function _parseSparqlQuery($query)
  468. function grabResult()
  469. {
  470. #echo '<pre>';print_r($this);exit;
  471. return ($this->queryParser->query->base);
  472. }
  473. } // end: Model
  474. ?>