PageRenderTime 53ms CodeModel.GetById 3ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 0ms

/s3db3.5.10/rdf.php

https://code.google.com/p/s3db/
PHP | 926 lines | 604 code | 218 blank | 104 comment | 105 complexity | de9d87a3843f6b07114eefad5611055f MD5 | raw file
  1<?php
  2#rdfproject.php parses a project in s3db into n3.
  3#reads database info from the session or from key
  4ini_set('display_errors',0);
  5if($_REQUEST['su3d'])
  6ini_set('display_errors',1);
  7
  8if($_SERVER['HTTP_X_FORWARDED_HOST']!='')
  9			$def = $_SERVER['HTTP_X_FORWARDED_HOST'];
 10		else 
 11			$def = $_SERVER['HTTP_HOST'];
 12			
 13if(file_exists('config.inc.php'))
 14	{
 15		include('config.inc.php');
 16	}
 17	else
 18	{
 19		
 20
 21		Header('Location: http://'.$def.'/s3db/');
 22		exit;
 23	}
 24
 25$a = set_time_limit(0);
 26#ini_set('max_execution_time','30');
 27ini_set('upload_max_filesize', '128M');
 28ini_set('post_max_size', '256M');
 29ini_set('display_errors',0);
 30ini_set('memory_limit','3000M');
 31
 32	$key = $_GET['key'];
 33	if($key=='') $key = $s3ql['key'];
 34	if($key=='') $key=$argv[1];	
 35	$file=$_REQUEST['file'];
 36	if($file=='') $file=$argv[3];
 37	if($id=='') $id = $argv[4];
 38	if($argv!=''){
 39	#whn the script is called via CLI, we need a direc way to accept the inputs. The syntax will be the saem (attr-value pairs)
 40	$inputsOrder = array('key','file','outputOption','uid');
 41	
 42	for ($i=1; $i <count($argv) ; $i++) {
 43		list($keyWord, $val) = explode('=',$argv[$i]);
 44		
 45		$inputs[$keyWord] = $val;
 46	}
 47	#$inputs['key'] = $argv[1];
 48	#$inputs['file'] = $argv[2];
 49	}
 50	else {
 51		$inputs = $_REQUEST;
 52	}
 53	#$inputs = ($argv!='')?$argv:$_REQUEST;
 54
 55$key=$inputs['key'];
 56include_once('core.header.php');
 57include('dbstruct.php');
 58
 59
 60$FinalFfilename = ($inputs['file']!='')?$inputs['file']:$GLOBALS['s3db_info']['server']['db']['uploads_folder'].$GLOBALS['s3db_info']['server']['db']['uploads_file'].'/project'.$project_id.'_requested_'.$user_id.'_'.date('m.d.y-His').'.n3';
 61
 62#echo $FinalFfilename;exit;
 63#####
 64#create a file and start writting to it
 65$fid = fopen($FinalFfilename, 'a+');
 66#echo '<pre>';print_r($inputs);echo $user_id;exit;
 67#echo $fid;exit;
 68if($user_id!='')
 69{
 70
 71#$project_id = $_REQUEST['project_id'];
 72
 73#$url = ($def=='')?$GLOBALS['s3db_info']['deployment']['url']:S3DB_URI_BASE;
 74$url = S3DB_URI_BASE;
 75#start building the string, prefix will be the very fisrt thing shouwing up
 76$n3 .= sprintf('%s', '@prefix dc: <http://purl.org/dc/elements/1.1/> .'.chr(10));
 77$n3 .= sprintf('%s', '@prefix dcterms: <http://purl.org/dc/terms/> .'.chr(10));
 78$n3 .= sprintf('%s', '@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .'.chr(10));
 79$n3 .= sprintf('%s', '@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .'.chr(10));
 80$n3 .= sprintf('%s', '@prefix owl: <http://www.w3.org/2002/07/owl#> .'.chr(10));
 81$n3 .= sprintf('%s', '@prefix s3db: <http://www.s3db.org/core#> .'.chr(10));
 82$n3 .= sprintf('%s', '@prefix s3dbpc: <http://www.s3db.org/permission_codes#> .'.chr(10));
 83$n3 .= sprintf('%s', '@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .'.chr(10));
 84$n3 .= sprintf('%s', '@prefix foaf: <http://xmlns.com/foaf/0.1/> .'.chr(10));
 85$n3 .= sprintf('%s', '@prefix did: <'.$GLOBALS['s3db_info']['deployment']['mothership'].$GLOBALS['Did'].'/> .'.chr(10).chr(10));
 86$n3 .= sprintf('%s', '@prefix : <'.$url.((substr($url,strlen($url)-1,1)=='/')?'':'/').'> .'.chr(10).chr(10));
 87
 88$N3coreNames = array('deployment'=>'s3db:s3dbDeployment','project'=>'s3db:s3dbProject', 'collection'=>'s3db:s3dbCollection', 'rule'=>'s3db:s3dbRule', 'item'=>'s3db:s3dbItem', 'statement'=>'s3db:s3dbStatement', 'user'=>'s3db:s3dbUser', 'group'=>'s3db:s3dbGroup');
 89
 90if(!$inputs['nocore']) {
 91$core = fread(fopen('core.n3', 'r'), filesize('core.n3'));
 92$n3 .= sprintf('%s', $core);
 93#$n3 .= sprintf('%s', 'doc:'.$GLOBALS['Did'].' a s3db:s3dbDeployment .'.chr(10).chr(10));
 94
 95}
 96#else {
 97#	$N3coreNames = array('project'=>'rdfs:Class', 'collection'=>'rdfs:Class', 'rule'=>'rdf:Property', 'item'=>'rdf:Resource', 'statement'=>'rdf:Resource', 'user'=>'rdf:Resource', 'group'=>'rdf:Resource');
 98#}
 99#parse the core relatioships
100
101
102#############################################################################
103##define the Classes in the ontology of s3db
104
105$s3Types = array('deployment'=>array('user', 'group', 'project'),
106				'group'=>array('user'),
107				'project'=>array('collection', 'rule'),
108				'collection'=>array('item'), 
109				'rule'=>array('statement'));
110				
111	
112
113##############################################################
114#the unique identifier for each table
115$s3idNames = array('deployment'=>'deployment_id', 'project'=>'project_id', 'collection'=>'resource_id', 'item'=>'resource_id', 'rule'=>'rule_id', 'statement'=>'statement_id', 'user'=>'user_id', 'group'=>'group_id');
116
117#$coreElements = array_keys($s3Elements);
118
119#now is there any id specified?
120$specifiedInput = rootIDinfo($s3idNames, $inputs, $argv, $user_id, $key, $db);
121extract($specifiedInput);
122$specified_id_code = $GLOBALS['s3codesInv'][$specified_id_type];
123
124if(!$specified_id_info['view'])
125	{echo $GLOBALS['messages']['no_permission_message'].'<message>User does not have access in this '.$specified_id_type.'.</message>';
126 exit;
127 }
128
129
130$specified_id_info = array_filter($specified_id_info);
131$ruid_info=uid($letter.$rootID);
132#################################
133#Determine what should be output
134
135#Build the ROOT ontology
136$verbs=array();
137
138switch ($specified_id_code) {
139	case 'D':
140	
141	if($ruid_info['Did']==$GLOBALS['Did'])
142	{$rpre='doc:';$rsuf='';}
143	else{ $rpre='<';$sruf='>';}
144
145	$n3 .= sprintf($rpre.$ruid_info['uid'].$rsuf);
146	$objectPredicates=array('rdfs:comment'=>(
147									$specified_id_info[$COREcomment[$specified_id_type]]!='')?'"'.$specified_id_info[$COREcomment[$specified_id_type]].'"':'',
148									#'a'=> $N3coreNames[$specified_id_type],
149									'rdfs:label'=>'"'.$specified_id_info[$CORElabel[$specified_id]].'"',
150									
151									);
152		#if(!$inputs['nocore']){
153		#	$objectPredicates['a']=$N3coreNames[$specified_id_type];
154		#}
155break;
156	case 'P':
157	if($ruid_info['Did']==$GLOBALS['Did']){$pre=':';$suf='';}
158	else{ $rpre='<';$rsuf='>';}
159	$n3 .= sprintf(n3UID($ruid_info['uid']));
160	$objectPredicates=array('rdfs:comment'=>(
161									$specified_id_info[$COREcomment[$specified_id_type]]!='')?'"'.$specified_id_info['project_description'].'"':'',
162									#'a'=> $N3coreNames[$specified_id_type],
163									'rdfs:label'=>'"'.$specified_id_info[$CORElabel[$specified_id]].'"',
164									'dcterms:creator'=>n3UID('U'.$specified_id_info['created_by']),
165									'dcterms:created'=>'"'.$specified_id_info['created_on'].'"'
166									);
167
168					
169
170		break;
171	case 'R':
172					$n3 .= sprintf(n3UID($ruid_info['uid']));
173					$subject_id = n3UID('C'.$specified_id_info['subject_id']);
174					
175									
176					$verb_id = ($specified_id_info['verb_id']=="")?":I".random_string(5):n3UID("I".$specified_id_info['verb_id']);
177					#predicates can't be literals, so create a resource for literal verbs.
178					#when the verb is not an ID, a random string is generated that will simulate the ID of an instance.
179					if(!in_array($specified_id_info['verb'], array_keys($verbs)))
180					{
181					$addStat .= sprintf($verb_id);
182					$addStat .= sprintf(' rdfs:label "'.$specified_id_info['verb'].'" ;').chr(10);
183					if(!$inputs['nocore'])
184					$addStat .= chr(9).sprintf(' a s3db:s3dbItem ;').chr(10);
185					##Find collection of this item and output this information
186					$item_info = s3info('item', $specified_id_info['verb_id'], $db);
187					if(is_array($item_info))
188					$addStat .= chr(9).sprintf(' a '.n3UID("C".$item_info['resource_class_id']).' .').chr(10).chr(10);
189					else {#find a collection for the verbs
190						$verbCollection = projectVerbClass(array('project_id'=>$specified_id_info['project_id'], 'db'=>$db,'user_id'=>$user_id));
191						$addStat .= chr(9).sprintf(' a '.n3UID("C".$verbCollection['resource_id']).' .').chr(10).chr(10);
192					}
193
194					$verbs[$specified_id_info['verb']] =$verb_id;
195					}
196					else {
197						$verb_id = $verbs[$specified_id_info['verb']];
198												
199					}
200					
201					
202					$object_id = ($specified_id_info['object_id']=="")?'"'.$specified_id_info['object'].'"':n3UID("C".$specified_id_info['object_id']);
203					
204					
205				$objectPredicates=array(
206								
207								'rdfs:label'=>'"'.$specified_id_info['subject'].' '.$specified_id_info['verb'].' '.$specified_id_info['object'].'"',
208								#'dc:comment'=>'"'.$specified_id_info['notes'].'"', 
209								'rdfs:subClassOf'=>n3UID('P'.$specified_id_info['project_id']), 
210								'rdf:subject'=>$subject_id, 
211								'rdf:predicate'=>$verb_id,
212								'rdf:object'=>$object_id,
213								'dcterms:creator'=>n3UID('U'.$specified_id_info['created_by']),
214								'dcterms:created'=>'"'.$specified_id_info['created_on'].'"'
215								);
216				
217				##When no core is needed (when the document is not meant to be reloaded, there is no need for 
218				
219				$addStat .= sprintf($subject_id.' '.$verb_id .' '.$object_id.' .').chr(10);
220		break;
221	
222}
223
224if(!$inputs['nocore']){
225			$objectPredicates['a']=$N3coreNames[$specified_id_type];
226		}
227
228$objectPredicates=array_filter($objectPredicates);
229#echo '<pre>';print_r($objectPredicates);exit;
230
231#echo '<pre>';print_r($s3Types[$specified_id_type]);exit;
232foreach ($objectPredicates as $predicate=>$object) {
233	$n3 .= chr(9).sprintf($predicate.' '.$object.(($predicate==end(array_keys($objectPredicates)))?' .'.chr(10):' ;')).chr(10);
234}
235
236#Export user permissions on object
237#retrieve permission info on this URI
238
239if(in_array('permissions', array_keys($inputs))){
240$s3ql=compact('user_id','db');
241$s3ql['from']='users';
242$s3ql['where'][$specified_id]=$specified_id_info[$specified_id];
243$users = S3QLaction($s3ql);
244$me = $user_info;
245$me = include_all(array('elements'=>'users', 'element_info'=>$me, 'user_id'=>$user_id, 'db'=>$db));
246$me['permissionOnResource'] = $me['permission_level'];
247array_push($users, $me);
248
249$permissions=array_map('grab_permission', $users);
250$users=grab_id('user', $users);
251$specified_id_info['permissions']=array_combine($users, $permissions);
252
253#echo '<pre>';print_r($specified_id_info['permissions']);
254if(is_array($specified_id_info['permissions']))
255	
256	$n3permissions .= chr(10);sprintf($pre.$uid_info['uid'].$suf).chr(10);
257	
258	foreach ($specified_id_info['permissions'] as $user_code=>$pcode) {
259	
260	$n3permissions .= sprintf(n3UID($uid='U'.$user_code).' s3dbpc:VCU'.$pcode.' '.n3UID($ruid_info['uid']).' .').chr(10);
261}
262
263}
264$n3 .= $n3permissions;
265#echo $n3;exit;
266fwrite($fid, $n3);
267
268#echo $n3permissions;exit;
269#echo '<pre>';print_r($s3Types);exit;
270#now for the classes. What are rdfs:classes in an s3db ontology?
271#EVERTHING THAT HAS A LABEL IS A CLASS. This includes verbs, object and instances
272foreach ($s3Types[$specified_id_type] as $a_class) {
273	#each class has a descriptive statement
274	
275	$a_class_id = $s3idNames[$a_class];
276	
277	$a_class_letter = strtoupper(substr($a_class,0,1));
278	$a_class_type = $GLOBALS['s3codes'][$a_class_letter];
279	$s3ql=compact('user_id','db');
280	$s3ql['select']='*';
281	$s3ql['from']=$GLOBALS['plurals'][$a_class];
282	$s3ql['where'][$specified_id]=$specified_id_info[$specified_id];
283	
284	if(ereg('(rule|statement)', $a_class_type))
285		$s3ql['where']['object']="!=UID";
286
287	
288	
289	#echo '<pre>';print_r($s3ql);
290	#exit;
291	$subClasses = S3QLaction($s3ql);#find them, output them. 
292	#$verbs=array();
293	
294
295	if(is_array($subClasses))
296	foreach ($subClasses as $subClass_info) {
297		
298		
299		$subClass_info = array_filter($subClass_info);
300		#start by saying what sort of s3dbCore id this is.
301		
302		
303		$n3 = getSubClassStats($a_class_letter.$subClass_info[$a_class_id], $subClass_info, $inData, $user_id, $db, $N3coreNames, $inputs); 
304		#if($a_class_letter=='R'){
305		
306		#}
307		fwrite($fid, $n3);		
308	}
309}
310fclose($fid);
311chmod($FinalFfilename, 0777);
312
313##Prepare to output
314$linkname=random_string('10').'.n3';
315$filelink = $GLOBALS['URI'].'/extras/'.$linkname;
316
317if(!@copy($FinalFfilename, S3DB_SERVER_ROOT.'/extras/'.$linkname))
318		{
319		echo  "Could not copy the file. This could be because Apache does not have 'write' permission on the s3db folder or the /extras/.";
320		exit;
321		}
322
323if(in_array('output', array_keys($inputs)))
324	{
325	
326	#Try reading simile. If the site is not up, give an error message
327	
328	$simileLink = 'http://simile.mit.edu/babel/translator?reader=n3&writer=rdf-xml&mimetype=text%2Fplain&url='.$filelink;
329	$simile = @fopen($simileLink,'r');
330	if(!$simile)
331		{echo "Could not connect to the rdf conversion service (http://simile.mit.edu/babel), please make sure you are connected to the internet.";
332		exit;
333		}
334	$translation = stream_get_contents($simile);
335	if(ereg('<html>', $translation))
336		{
337		echo "Simile could not convert the file. Please copy the triples on this <a href='".$filelink."'>direct link</a> and submit it to <a href='http://simile.mit.edu/babel'>simile</a> for a conversion in your format of choice.";
338		exit;
339		}
340	
341	switch ($inputs['output']) {
342		case 'rdf-xml':
343		##Convert the n3 to a model; convert that model into rdf
344		include_once(S3DB_SERVER_ROOT.'/rdfheader.inc.php');
345		$model = ntriples2php($n3);
346		$model->saveAs(S3DB_SERVER_ROOT.'/tmp/'.str_replace('.n3', '.rdf', $linkname), 'RDF'); 
347		$filelink = str_replace('.n3', '.rdf', $filelink);
348		$simileLink = 'http://simile.mit.edu/babel/translator?reader=n3&writer=rdf-xml&mimetype=text%2Fplain&url='.$filelink;
349		break;
350
351		case 'json':
352		$filelink = str_replace('.n3', '.json', $filelink);
353		$simileLink = 'http://simile.mit.edu/babel/translator?reader=n3&writer=exhibit-json&mimetype=text%2Fplain&url='.$filelink;
354		break;
355		
356		default :
357			$filelink = str_replace('.n3', '.rdf', $filelink);
358			$simileLink = 'http://simile.mit.edu/babel/translator?reader=n3&writer=rdf-xml&mimetype=text%2Fplain&url='.$filelink;
359		break;
360	}
361	$simile = @fopen($simileLink,'r');
362	$translation = stream_get_contents($simile);
363	file_put_contents($translation, $filelink);
364	}
365if(in_array('link', array_keys($inputs))) {
366	echo "Link for n-triples <a href='".$filelink."'>".$filelink."</a><br />";
367	
368	$filelink = str_replace('.n3', '.rdf', $filelink);
369	$simileLink = 'http://simile.mit.edu/babel/translator?reader=n3&writer=rdf-xml&mimetype=text%2Fplain&url='.$filelink;
370	$simile = @fopen($simileLink,'r');
371	$translation = stream_get_contents($simile);
372	if($translation!='' && !ereg('<html>', $translation)) {
373	@file_put_contents($translation, $filelink);
374	echo "Link for xml-rdf <a href='".$filelink."'>".$filelink."</a><br />";
375	}
376	
377	$filelink = str_replace('.n3', '.json', $filelink);
378	$simileLink = 'http://simile.mit.edu/babel/translator?reader=n3&writer=exhibit-json&mimetype=text%2Fplain&url='.$filelink;
379	$simile = @fopen($simileLink,'r');
380	$translation = stream_get_contents($simile);
381	if($translation!=''&& !ereg('<html>', $translation)){
382	file_put_contents($translation, $filelink);
383	echo "Link for Json <a href='".$filelink."'>".$filelink."</a><br />";
384	}
385	#Header('Location:'.$filelink);
386	#exit;
387}
388else {
389	if($inputs['download']!='no'){
390	header("Content-Type: application/octet-stream");
391	header("Content-Disposition: attachment; filename=".$linkname);
392	header("Content-Transfer-Encoding: binary");
393	}	
394		echo file_get_contents($filelink);
395		exit;
396}
397
398exit;
399
400}
401
402function addCollectionItemStats($user_id,$db, $class_id, $inputs)
403{
404			
405			$s3ql=compact('user_id','db');
406			$s3ql['from']='items';
407			$s3ql['where']['collection_id']=$class_id;
408			
409			$items = S3QLaction($s3ql);
410			
411			if (is_array($items) && !empty($items)) {
412			foreach ($items as $key=>$item_info) {
413				if(!$inputs['nocore'])
414				$n3 .= sprintf(':I'.$item_info['item_id'].' a s3db:s3dbItem .').chr(10).chr(10);
415
416				$objectPredicates=array('rdfs:label'=>'"'.$item_info['notes'].'"',
417											'a'=>':C'.$class_id);
418			
419				$objectPredicates = array_filter($objectPredicates);
420
421				if(is_array($objectPredicates) && !empty($objectPredicates))
422				{	#Global "this is a resource" statement
423				$n3 .= sprintf(':I'.$item_info['item_id']);
424				
425				
426				foreach ($objectPredicates as $predicate=>$object) {
427					if($object!='""')
428					$n3 .= sprintf("%s", ' '.$predicate.' '.$object.(($predicate==end(array_keys($objectPredicates)))?' .'.chr(10).chr(10):' ;'.chr(10).chr(9)));
429				}
430				}
431			
432			}
433			}
434
435			return ($n3);
436			
437}
438
439function addRuleStats($user_id,$db, $url,$rule_id, $inputs)
440{$COREletter = $GLOBALS['COREletter'];
441	$s3ql=compact('user_id','db');
442	$s3ql['from']='statements';
443	$s3ql['where']['rule_id']=$rule_id;
444
445	$stats = S3QLaction($s3ql);	
446	
447	
448	$subject_name = 'item_id';	
449	$predicate_name = 'rule_id';
450	$object_name = 'item_id';
451	
452	if(is_array($stats) && !empty($stats))
453	foreach ($stats as $key=>$stat_info) {
454	if(!$inputs['nocore'])	
455	$n3 .= sprintf(n3UID('S'.$stat_info['statement_id']).' a s3db:s3dbStatement .').chr(10).chr(10);
456	
457	if($stat_info['file_name']!='')
458		{
459		#find the file. Write it as base64encoded
460			
461			#echo '<pre>';print_r($stat_info);exit;
462			$fileLocation = fileLocation($stat_info, $db);
463			
464			if($fileLocation!='')
465			{
466			
467			if(!$inputs['files']){
468			$content=@fread(@fopen($fileLocation, 'r'), @filesize($fileLocation));
469			
470			$content=base64_encode($content);
471			$object='"s3dbFile_'.$stat_info['file_name'].'_'.$content.'"';
472			}
473			else {
474				$object='"s3dbLink_'.$stat_info['file_name'].'_'.S3DB_URI_BASE.'/download.php?key='.$inputs['key'].'&statement_id='.$stat_info['statement_id'].'"';
475			}
476			#echo $object;exit;
477			#echo $subClass_info['file_name'].chr(13).chr(10);
478			}
479		#ereg('<a href(.*)download.php(.*)>(.*)</a>', $stat_info['value'], $linkdata);
480		#$statfilelink='<'.$url.'download.php'.str_replace('"', '', $linkdata[2]).'>';
481		#$object=$statfilelink;
482		}
483	elseif($stat_info['object_id']!='')
484		{
485		$object=':'.$COREletter[$object_name].$stat_info['value'];
486
487		}
488		else {
489			
490			ereg('<a href=(.*)>(.*)</a>', $stat_info['value'], $links);
491						if(!empty($links))
492								$object = '"'.str_replace(array('"', '\''),array('', ''), $links[1]).'"';
493						else					
494							$object='"'.$stat_info['value'].'"';
495			
496			#$object='"'.htmlentities($stat_info['value']).'"';
497			}
498
499		$objectPredicates=array('rdf:subject'=>n3UID($COREletter[$subject_name].$stat_info[$subject_name]),
500								'rdf:predicate'=>n3UID($COREletter[$predicate_name].$stat_info[$predicate_name]), 
501									
502								'rdf:object'=>$object);
503	
504		#$objectPredicates['rdfs:label'] ='"'.$stat_info['subject'].' '.$stat_info['instance_notes'].' (I'.$stat_info['instance_id'].') '.$stat_info['verb'].' '.$stat_info['object'].' '.(($stat_info['object_id']!='')?($stat_info['object_notes'].' (I'.$stat_info['value'].')'):(($stat_info['file_name']=='')?str_replace('"', '', $objectPredicates['rdf:object']):$stat_info['file_name'])).'"';
505		$objectPredicates['rdfs:label'] ='"'.$stat_info['subject'].' '.$stat_info['instance_notes'].' I'.$stat_info['instance_id'].' '.$stat_info['verb'].' '.$stat_info['object'].' '.(($stat_info['object_id']!='')?($stat_info['object_notes'].' I'.$stat_info['value'].''):(($stat_info['file_name']=='')?str_replace('"', '', $objectPredicates['rdf:object']):$stat_info['file_name'])).'"';
506				
507		
508		$objectPredicates = array_filter($objectPredicates);
509
510				if(is_array($objectPredicates) && !empty($objectPredicates) && !$inputs['nocore'])
511				{	#Global "this is a resource" statement
512				$n3 .= sprintf(':S'.$stat_info['statement_id']);
513				
514				
515				foreach ($objectPredicates as $predicate=>$object) {
516					if($object!='""')
517					$n3 .= sprintf("%s", ' '.$predicate.' '.$object.(($predicate==end(array_keys($objectPredicates)))?' .'.chr(10).chr(10):' ;'.chr(10).chr(9)));
518				}
519				}
520			
521		#unreified statement - the only one neeed where nocore is specified
522		$n3 .= sprintf("%s", $objectPredicates['rdf:subject']);
523		$n3 .= chr(9).sprintf("%s", $objectPredicates['rdf:predicate'].' '.(($subClass_info['object_id']!='')?$objectPredicates['rdf:object']:$objectPredicates['rdf:object']).' .').chr(10).chr(10);
524
525}
526	
527return ($n3);
528}
529
530function addProjectRulesAndCollections($user_id,$db, $url, $project_id, $inData)
531{
532$s3ql=compact('user_id','db');
533$s3ql['select']='*';
534$s3ql['from']='collections';
535$s3ql['where']['project_id']=$project_id;
536
537$collections = S3QLaction($s3ql);
538
539if(is_array($collections)){
540	
541	#echo '<pre>';print_r($collections);
542	foreach ($collections as $key=>$collection_info) {
543		$n3 .= getSubClassStats('C'.$collection_info['collection_id'], $collection_info, $inData, $user_id, $db, $N3coreNames, $inputs);
544		#echo $n3;exit;
545	}
546}
547
548$s3ql=compact('user_id','db');
549$s3ql['select']='*';
550$s3ql['from']='rules';
551$s3ql['where']['project_id']=$project_id;
552
553$rules = S3QLaction($s3ql);
554
555if(is_array($rules)){
556	
557	foreach ($rules as $key=>$rule_info) {
558		$n3 .= getSubClassStats('R'.$rule_info['rule_id'], $rule_info, $inData, $user_id, $db, $N3coreNames, $inputs);
559		#echo $n3;exit;
560	}
561
562}
563
564return ($n3);
565}
566
567function addGroupUsers($user_id,$db, $group_id)
568{
569	$s3ql=compact('user_id','db');
570	$s3ql['select']='*';
571	$s3ql['from']='users';
572	$s3ql['where']['group_id']=$group_id;
573
574	
575	$users = S3QLaction($s3ql);
576	$users = grab_id('user', $users);
577	if(is_array($users))
578	foreach ($users as $key=>$user_id) {
579		$n3 .= sprintf(n3UID('U'.$user_id).' rdfs:subClassOf '.n3UID('G'.$group_id).' .').chr(10);
580	}
581	return ($n3);
582}
583
584function rootIDinfo($s3idNames, $REQUESTdat, $argv, $user_id, $key, $db)
585{
586	if(!in_array('uid', array_keys($REQUESTdat)))
587	$specified_id = array_intersect($s3idNames, array_keys($REQUESTdat));
588	else {
589		
590		$specified_id = $GLOBALS['COREletterInv'][letter($REQUESTdat['uid'])];
591	}
592
593#echo '<pre>';print_r($REQUESTdat);exit;
594
595if(count($specified_id)!='1')
596	{
597	if(is_array($argv))
598	$inData = array_diff($argv, array($key, 'rdf.php'));
599	if(is_array($inData)){
600	foreach ($inData as $key=>$value) {
601		list($idname[], $id[])=explode('=', $value);
602
603	}
604	$specified_id = array_intersect($s3idNames, $idname);
605	}
606	
607	if(count($specified_id)!='1')
608		{
609		
610		echo $GLOBALS['messages']['something_missing']."<message>Please specify 1 and only 1 id for the root of the ontology</message>";
611		exit;
612		}
613	else {
614		$inData = array_combine($idname, $id);
615		$rootID = $id[0];
616		$specified_id = $idname[0];
617	}
618	}
619	else {
620		$inData = $REQUESTdat;
621		$specified_id=array_combine(array('0'), $specified_id);
622		$specified_id= $specified_id[0];
623		$rootID = $REQUESTdat[$specified_id];
624		
625		if($rootID=='')
626		{$rootID = ereg_replace('^'.letter($REQUESTdat['uid']), '', $REQUESTdat['uid']);
627		$specified_id = $GLOBALS['COREletterInv'][letter($REQUESTdat['uid'])];
628		}
629
630	}
631
632
633 $specified_id_type = array_search($specified_id, $s3idNames);
634 $letter = strtoupper(substr($specified_id,0,1));
635 
636 $specified_id_info = URIinfo($letter.$rootID, $user_id, $key, $db);
637
638return (compact('letter', 'specified_id', 'specified_id_type', 'specified_id_info', 'inData', 'rootID'));
639}
640
641function getSubClassStats($uid, $subClass_info, $inData, $user_id, $db, $N3coreNames, $inputs)
642		{
643		global $verbs;
644		
645		$uid_info = uid($uid);
646		
647		$letter = substr($uid,0,1);
648		$a_class_type = $GLOBALS['s3codes'][substr($uid,0,1)];
649		$a_class_id = $GLOBALS['COREids'][$a_class_type];
650		$CORElabel = $GLOBALS['CORElabel'];
651		$N3coreNames = ($N3coreNames!='')?$N3coreNames:$GLOBALS['N3coreNames'];
652
653		
654		if(!$inputs['nocore'])
655			$n3 .= sprintf(n3UID($uid_info['uid']).' a '.$N3coreNames[$a_class_type].' .').chr(10).chr(10);
656		
657		
658		switch ($a_class_type) {
659			case 'user':
660			if ($uid_info['Did']==$GLOBALS['s3db_info']['deployment']['Did']) {
661				$objectPredicates=array('rdfs:subClassOf' => n3UID($uid_info['Did']),
662										'rdfs:label'=>'"'.$subClass_info[$CORElabel[$a_class_id]].'"',
663										'foaf:mbox'=>'"'.$subClass_info['account_email'].'"',
664										'foaf:name'=>'"'.$subClass_info['account_uname'].'"',
665										'foaf:password'=>($user_id==1)?'"'.findPassword(ereg_replace('^'.$letter, '',$uid_info['uid']), $db).'"':'',
666										'dcterms:creator'=>n3UID('U'.$subClass_info['created_by']),
667										'dcterms:created'=>'"'.$subClass_info['created_on'].'"');
668			
669			}
670			else {
671				$objectPredicates=array('rdfs:subClassOf' => n3UID($GLOBALS['s3db_info']['deployment']['Did']));
672			}
673			
674			
675			
676			break;
677			
678			case 'group':
679				$objectPredicates=array('rdfs:subClassOf' => ':'.$uid_info['Did'],
680										'rdfs:label'=>'"'.$subClass_info[$CORElabel[$a_class_id]].'"',
681										'dcterms:creator'=>n3UID('U'.$subClass_info['created_by']),
682										'dcterms:created'=>'"'.$subClass_info['created_on'].'"');
683			
684
685			$addStat .= addGroupUsers($user_id,$db, $subClass_info[$a_class_id]);
686
687			break;
688			case 'project':
689				$objectPredicates=array(
690									'rdfs:subClassOf' => n3UID($uid_info['Did']),
691									'rdfs:label'=>'"'.$subClass_info[$CORElabel[$a_class_id]].'"',
692									'dcterms:creator'=>n3UID('U'.$subClass_info['created_by']),
693									'dcterms:created'=>'"'.$subClass_info['created_on'].'"'
694									);
695					
696				
697				$addStat .= addProjectRulesAndCollections($user_id,$db, $url, $subClass_info[$a_class_id], $inData);	
698				
699				break;
700			case 'collection':
701					
702			$objectPredicates=array(
703										'rdfs:subClassOf'=>n3UID('P'.$subClass_info['project_id']), 
704										'rdfs:label'=>'"'.$subClass_info['entity'].'"',
705										'rdfs:comment'=>'"'.$subClass_info['notes'].'"',
706										#'dcterms:creator'=>n3UID('U'.$subClass_info['created_by']),
707										#'dcterms:created'=>'"'.$subClass_info['created_on'].'"'
708										);
709					
710					
711			if(!$inputs['nometa']){
712			$objectPredicates['dcterms:creator'] =	n3UID('U'.$subClass_info['created_by']);
713			$objectPredicates['dcterms:created'] =	'"'.$subClass_info['created_on'].'"';
714			}
715			
716			if(in_array('all', array_keys($inputs)))
717			$addStat .= addCollectionItemStats($user_id,$db, $subClass_info[$a_class_id], $inputs);
718
719			#trying to see if the collection declarations are meesing up the query a lot
720			if($inputs['nocore'])
721			$n3 .= sprintf(n3UID($uid_info['uid']).' a '.$N3coreNames[$a_class_type].' .').chr(10).chr(10);
722			
723			break;
724			case 'rule':
725					
726					$subject_id = n3UID('C'.$subClass_info['subject_id']);
727					
728									
729					$verb_id = ($subClass_info['verb_id']=="")?":I".random_string(5):n3UID("I".$subClass_info['verb_id']);
730					#predicates can't be literals, so create a resource for literal verbs.
731					#when the verb is not an ID, a random string is generated that will simulate the ID of an instance.
732					if(!in_array($subClass_info['verb'], array_keys($verbs)))
733					{
734					$addStat .= sprintf($verb_id);
735					$addStat .= sprintf(' rdfs:label "'.$subClass_info['verb'].'" ;').chr(10);
736					if(!$inputs['nocore'])
737					$addStat .= chr(9).sprintf(' a s3db:s3dbItem ;').chr(10);
738					##Find collection of this item and output this information
739					$item_info = s3info('item', $subClass_info['verb_id'], $db);
740					if(is_array($item_info))
741					$addStat .= chr(9).sprintf(' a '.n3UID("C".$item_info['resource_class_id']).' .').chr(10).chr(10);
742					else {#find a collection for the verbs
743						$verbCollection = projectVerbClass(array('project_id'=>$subClass_info['project_id'], 'db'=>$db,'user_id'=>$user_id));
744						$addStat .= chr(9).sprintf(' a '.n3UID("C".$verbCollection['resource_id']).' .').chr(10).chr(10);
745					}
746
747					$verbs[$subClass_info['verb']] =$verb_id;
748					}
749					else {
750						$verb_id = $verbs[$subClass_info['verb']];
751												
752					}
753					
754					
755					$object_id = ($subClass_info['object_id']=="")?'"'.$subClass_info['object'].'"':n3UID("C".$subClass_info['object_id']);
756					
757					
758				$objectPredicates=array(
759								
760								'rdfs:label'=>'"'.$subClass_info['subject'].' '.$subClass_info['verb'].' '.$subClass_info['object'].'"',
761								#'dc:comment'=>'"'.$subClass_info['notes'].'"', 
762								'rdfs:subClassOf'=>n3UID('P'.$subClass_info['project_id']), 
763								'rdf:subject'=>$subject_id, 
764								'rdf:predicate'=>$verb_id,
765								'rdf:object'=>$object_id,
766								#'dcterms:creator'=>n3UID('U'.$subClass_info['created_by']),
767								#'dcterms:created'=>'"'.$subClass_info['created_on'].'"'
768								);
769				
770				if(!$inputs['nometa']){
771					$objectPredicates['dcterms:creator'] = n3UID('U'.$subClass_info['created_by']);
772					$objectPredicates['dcterms:created'] = '"'.$subClass_info['created_on'].'"';
773				}
774				
775				##When no core is needed (when the document is not meant to be reloaded, there is no need for 
776				
777				$addStat .= sprintf($subject_id.' '.$verb_id .' '.$object_id.' .').chr(10);
778				
779				
780				if(in_array('all', array_keys($inputs)))
781				$addStat .= addRuleStats($user_id,$db, $url, $subClass_info[$a_class_id], $inputs);	
782
783				#trying to see if the collection declarations are meesing up the query a lot
784				if($inputs['nocore'])
785				$n3 .= sprintf(n3UID($uid_info['uid']).' a '.$N3coreNames[$a_class_type].' .').chr(10).chr(10);
786			
787				
788				break;
789					case 'item':
790						
791					$objectPredicates=array('rdfs:label'=>'"'.$subClass_info['notes'].'"',
792											'a'=>n3UID('C'.$subClass_info['class_id']),
793											#'dcterms:creator'=>':U'.$subClass_info['created_by'],
794											#'dcterms:created'=>'"'.$subClass_info['created_on'].'"'
795											);
796					if(!$inputs['nometa']){
797					$objectPredicates['dcterms:creator'] = ':U'.$subClass_info['created_by'];
798					$objectPredicates['dcterms:created'] = '"'.$subClass_info['created_on'].'"';
799					}
800				
801					#trying to see if the collection declarations are meesing up the query a lot
802					if($inputs['nocore'])
803					$n3 .= sprintf(n3UID($uid_info['uid']).' a '.$N3coreNames[$a_class_type].' .').chr(10).chr(10);
804			
805				break;
806					
807					case 'statement':
808					
809					$subject_name = 'instance_id';	
810					$predicate_name = 'rule_id';
811					$object_name = 'instance_id';
812
813					if($subClass_info['file_name']!='')
814					{
815					#find the file. Write it as base64encoded
816						
817						#echo '<pre>';print_r($subClass_info);
818						
819						$fileLocation = fileLocation($subClass_info, $db);
820						
821						if($fileLocation!='')
822						{
823						
824						if(!$inputs['files']){
825						$content=@fread(@fopen($fileLocation, 'r'), @filesize($fileLocation));
826						
827						$content=base64_encode($content);
828						$object='"s3dbFile_'.$subClass_info['file_name'].'_'.$content.'"';
829						}
830						else {
831							$object='"s3dbLink_'.$subClass_info['file_name'].'_'.S3DB_URI_BASE.'/download.php?key='.$inputs['key'].'&statement_id='.$subClass_info['statement_id'].'"';
832						}
833						#echo $object;exit;
834						#echo $subClass_info['file_name'].chr(13).chr(10);
835						}
836					#echo $object;exit;
837					#ereg('<a href(.*)download.php(.*)>(.*)</a>', $stat_info['value'], $linkdata);
838					#$statfilelink='<'.$url.'download.php'.str_replace('"', '', $linkdata[2]).'>';
839					#$object=$statfilelink;
840					}
841					
842					elseif($subClass_info['object_id']!='')
843					{
844					$object=n3UID($COREletter[$object_name].$subClass_info['value']);
845					
846					}
847					else {
848						ereg('<a href=(.*)>(.*)</a>', $subClass_info['value'], $links);
849						if(!empty($links))
850								$object = '"'.str_replace(array('"', '\''),array('', ''), $links[1]).'"';
851						else					
852							$object='"'.$subClass_info['value'].'"';
853					}
854
855
856					
857					$objectPredicates=array(
858									#'rdf:subject'=>n3UID($COREletter[$subject_name].$subClass_info[$subject_name]),
859									'rdf:subject'=>n3UID('I'.$subClass_info[$subject_name]),
860									'rdf:predicate'=>n3UID('R'.$subClass_info[$predicate_name]), 
861									
862									#'rdf:object'=>($subClass_info['object_id']!='')?':'.$COREletter[$object_name].$subClass_info['value']:'"'.$subClass_info['value'].'"'
863									'rdf:object'=>$object,
864									'dcterms:creator'=>n3UID('U'.$subClass_info['created_by']),
865									'dcterms:created'=>'"'.$subClass_info['created_on'].'"'
866									);
867					
868				 #$objectPredicates['rdfs:label'] ='"'.$subClass_info['subject'].' '.$subClass_info['instance_notes'].' (I'.$subClass_info['instance_id'].') '.$subClass_info['verb'].' '.$subClass_info['object'].' '.(($subClass_info['object_id']!='')?($subClass_info['object_notes'].' (I'.$subClass_info['value'].')'):(($subClass_info['file_name']=='')?str_replace('"', '', $objectPredicates['rdf:object']):$subClass_info['file_name'])).'"';
869				 $objectPredicates['rdfs:label'] ='"'.$subClass_info['subject'].' '.$subClass_info['instance_notes'].' I'.$subClass_info['instance_id'].' '.$subClass_info['verb'].' '.$subClass_info['object'].' '.(($subClass_info['object_id']!='')?($subClass_info['object_notes'].' I'.$subClass_info['value'].''):(($subClass_info['file_name']=='')?str_replace('"', '', $objectPredicates['rdf:object']):$subClass_info['file_name'])).'"';
870				
871				#when no core is requested, return just the reified stat
872				if($inputs['nocore']) {
873					$objectPredicates=array();
874				}
875				
876				#unreified statement
877				
878				$addStat .= sprintf("%s", $objectPredicates['rdf:subject']);
879				$addStat .= chr(9).sprintf("%s", $objectPredicates['rdf:predicate'].' '.(($subClass_info['object_id']!='')?$objectPredicates['rdf:object']:$objectPredicates['rdf:object']).' .').chr(10);
880				break;
881		}
882		
883		#export user permissions in rdf 
884		if(in_array('p', array_keys($inData))){
885		$s3ql=compact('user_id','db');
886		$s3ql['from']='users';
887		$s3ql['where'][$GLOBALS['COREids'][$a_class_type]]=$subClass_info[$GLOBALS['COREids'][$a_class_type]];
888		$users = S3QLaction($s3ql);
889		
890		
891		if(is_array($users)){
892		$permissions=array_map('grab_permission', $users);
893		$users=grab_id('user', $users);
894		$specified_id_info['permissions']=array_combine($users, $permissions);
895		}
896		if(is_array($specified_id_info['permissions'])){
897			$n3permissions .= chr(10);
898			foreach ($specified_id_info['permissions'] as $user_code=>$pcode) {
899			$n3permissions .= sprintf(n3UID('U'.$user_code).' s3dbpc:VCU'.$pcode.' '.n3UID($uid_info['uid']).' .').chr(10);
900		}
901		}
902		}
903
904		$objectPredicates = array_filter($objectPredicates);
905
906		if(is_array($objectPredicates) && !empty($objectPredicates))
907		{	#Global "this is a resource" statement
908		$n3 .= sprintf(n3UID($uid_info['uid']));
909		
910		
911		foreach ($objectPredicates as $predicate=>$object) {
912			if($object!='""')
913			$n3 .= sprintf("%s", ' '.$predicate.' '.$object.(($predicate==end(array_keys($objectPredicates)))?' .'.chr(10).chr(10):' ;'.chr(10).chr(9)));
914		}
915		}
916		if(is_array($user2declare))
917		foreach ($user2declare as $user=>$toDeclare) {
918			$uid_info = uid($user);
919			$addStat .= sprintf(n3UID('U'.$user), 'rdfs:label "'. getUserName($user, $db).'"').chr(10);
920		}
921
922		$n3 .=$addStat.$n3permissions;
923		#echo $n3;exit;
924		return ($n3);
925	}
926?>