<?
# Nearest Airport
# (c) 2003-2014 Morten Frederiksen
# License: http://www.gnu.org/licenses/gpl

define('REDLANDURI','mysql://mysql/redland');
include_once(
'service.php');

# Support old interface.
if (''!=@$_REQUEST['ntriples'])
    
$_REQUEST['format']='ntriples';
if (
''!=@$_REQUEST['rdfxml'])
    
$_REQUEST['format']='rdfxml';
if (
''==@$_REQUEST['format'] && preg_match('|application/rdf\+xml|', @$_SERVER['HTTP_ACCEPT']))
    
$_REQUEST['format']='rdfxml';

# Initialization.
$service=new Service(array(
        
'defaults'=>array(''=>array(
                
'format'=>'html'))));
$sql='';
$formats=array(
        
'rdfxml'=>'application/rdf+xml; charset=utf-8',
        
'xml'=>'application/xml; charset=utf-8',
        
'turtle'=>'application/x-turtle',
        
'ntriples'=>'text/plain; charset=utf-8');

if (
$service->match('Airport by IATA Service Profile')) {
    
# Find airport by IATA code.
    
$format=$service->input('Airport by IATA Service Profile','format');
    
$iata=strtoupper($service->input('Airport by IATA Service Profile','iata'));
    
$sql='select id as iata, country, name, shortname, timezone, latitude, longitude
from airports where id='
.$db->qstr($iata).' limit 1';
} elseif (
$service->match('Airport by Location Service Profile')) {
    
# Find airport by location.
    
$format=$service->input('Airport by Location Service Profile','format');
    
$lat=$service->input('Airport by Location Service Profile','latitude');
    
$long=$service->input('Airport by Location Service Profile','longitude');
    
$sql="select id as iata, country, name, shortname, timezone, latitude, longitude,
6371.04 * acos(cos(pi()/2-radians(90-latitude)) * cos(pi()/2-radians(90-<latitude>)) * cos(radians(longitude)-radians(<longitude>)) + sin(pi()/2-radians(90-latitude)) * sin(pi()/2-radians(90-<latitude>))) as distance
from airports where latitude!=0 and longitude!=0
order by distance limit 1"
;
    
$sql=str_replace('<latitude>',$db->qstr($lat),$sql);
    
$sql=str_replace('<longitude>',$db->qstr($long),$sql);
}

# Query?
if (''!=$sql) {
    
$base='http://'.$_SERVER['SERVER_NAME'].
            (
$_SERVER['SERVER_PORT']!=80?$_SERVER['SERVER_PORT']:'').
            
$_SERVER['REQUEST_URI'];
    
$Storage=0;
    
$Model=0;
    if (!(
$airport=$db->Execute($sql)))
        
$service->error('500 Internal Server Error [Invalid query: '.htmlspecialchars($sql).']');
    elseif (!(
$airport=$airport->FetchRow()))
        
$service->error('404 Airport not found [No airport(s) found, perhaps a non-existing IATA code?]');
    elseif (!(
$Storage=librdf_new_storage($World,
            
'hashes','temp',"hash-type='memory',contexts='no'")))
        
$service->error('500 Internal Server Error [Unable to create temporary storage for model.]');
    elseif (!(
$Model=librdf_new_model($World$Storage'')))
        
$service->error('500 Internal Server Error [Unable to create temporary model.]');
    elseif (
_cas($Model0, array(
            array(
_n('<'.$base.'>'), _n('foaf:primaryTopic'), _n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>')),
            array(
_n('<'.$base.'>'), _n('rdfs:seeAlso'), _n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>')),
            array(
_n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>'), _n('rdf:type'), _n('air:Airport')),
            array(
_n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>'), _n('air:iataCode'), _n($airport['iata'])),
            array(
_n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>'), _n('foaf:name'), _n(($airport['shortname']?$airport['shortname']:$airport['name']).($airport['country']!=''?', '.$airport['country']:''))),
            array(
_n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>'), _n('geo:lat'), _n($airport['latitude'])),
            array(
_n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>'), _n('geo:long'), _n($airport['longitude'])))))
        
$service->error('500 Internal Server Error [Unable to add statements to temporary model.]');
    elseif (!(
$result=librdfutil_model_to_string($Model,'rdfxml'==$format?'r3x':$format)))
        
$service->error('500 Internal Server Error [Unable to serialise results.]');
    elseif (
array_key_exists($format,$formats)) {
        
header('Content-Type: '.$formats[$format]);
        print 
$result;
        
$service->free();
    } else {
        
$service->add($Model);
        
$service->result(_n('<http://www.daml.org/cgi-bin/airport?'.$airport['iata'].'>'));
    }
    if (
$Model)
        
librdf_free_model($Model);
    if (
$Storage)
        
librdf_free_storage($Storage);
}

# Finish.
$service->finish();

?>