<?php
ini_set
('memory_limit''100M');

//define('INPUT_FILE', 'php://input');
define('INPUT_FILE''commandline.tmp');
define('UID'       '120146'); // user='TIGERcnl'
//define('UID'       , '36121'); // user='Chris Lawrence'
define('VERSION'   1);

define('WPAPIURL'  'http://${lang}.wikipedia.org/w/api.php?');
define('LANG'      'hr');
define('USER_AGENT''osm.jjaf.de/1.0 (http://osm.jjaf.de/wiwosm/bot/; http://de.wikipedia.org/wiki/Benutzer:Jjaf.de)');

define('CACHE_PREFIX''cache/');
define('TTL'         60 60 24 7); // P1w

if (isset($_GET['source'])) {
    
highlight_file(__FILE__);
    exit();
}

function 
JOSMticket8442() {
    
// JOSM CommandLine: OSM objects parameter via stdin are not XML since 2 XML documents <https://josm.openstreetmap.de/ticket/8442>
    
file_put_contents(
        
INPUT_FILE,
        
str_replace(
            <<<XML
</osm>
<?xml version='1.0' encoding='UTF-8'?>
<osm version='0.6' generator='JOSM'>

XML
            , 
''
            
file_get_contents('php://input')
        )
    );
}

function 
GetCachedHTTP($URL$CACHE_PREFIX$TTL) {
    
// JOSMCommandLineLog('GetCachedHTTP: '.$URL);
    
$CACHE $CACHE_PREFIX.sha1($URL);
    if (
file_exists($CACHE)
//!        && ((time() - filemtime($CACHE)) < $TTL)
        
) {
        
// use cache
        
$DATA file_get_contents($CACHE'r');
    } else {
        
// HTTP
        
$http curl_init();
        
curl_setopt($httpCURLOPT_URL           $URL);
        
curl_setopt($httpCURLOPT_USERAGENT     USER_AGENT);
        
curl_setopt($httpCURLOPT_HEADER        FALSE);
        
curl_setopt($httpCURLOPT_RETURNTRANSFERTRUE);
        
curl_setopt($httpCURLOPT_TIMEOUT       30);
        
curl_setopt($httpCURLOPT_CONNECTTIMEOUT10);
        
curl_setopt($httpCURLOPT_HTTPGET       TRUE);
        
curl_setopt($httpCURLOPT_FAILONERROR   FALSE);
        
$DATA curl_exec($http);
        
// refresh cache
        
file_put_contents($CACHE$DATALOCK_EX);
    }
    return 
$DATA;
}

function 
JOSMCommandLineLog($TEXT) {
    
// CommandLine seems picky on this one.
    
if ('Finished' == $TEXT) {
//!        echo '<!-- '.htmlentities($TEXT).' -->'."\n";
    
}
}

function 
WPAPINormalize($lang$title) {
    
// TODO:
    // source=TIGER/LineŽ 2008 Place Shapefiles (http://www.census.gov/geo/www/tiger/)
    // has "'" as '"', e.g.:
    // wikipedia=Morgan"s_Point,_Texas
    
JOSMCommandLineLog('WPAPINormalize: '.$lang.':'.$title);
    
$query = array(
        
'format'    => 'php',
        
'action'    => 'query',
        
'redirects' => 1,
        
'prop'      => 'coordinates',
        
'titles'    => $title
    
);
    
$WPAPIURL str_replace('${lang}'$langWPAPIURL);
    
$url $WPAPIURL.http_build_query($query);
    
$data unserialize(GetCachedHTTP($urlCACHE_PREFIXTTL));
    
$page array_pop($data['query']['pages']);
    if (
        (isset(
$page['pageid']))
        && (
$page['coordinates'])
    ) {
        
// <page pageid="21025324" ns="0" title="&#039;Aoa" /> => vorhanden
        
return $page['title'];
    }
    
// <page ns="0" title="Amanave, American Samoa" missing="" /> => nicht vorhanden
    
return FALSE;
}

// ### MAIN ###

header('Content-Type: text/xml');

$osm = new DOMDocument();
$osm->preserveWhiteSpace FALSE;

JOSMticket8442();
if (@
$osm->load(INPUT_FILE)) {
    
JOSMCommandLineLog('Start');
    
$xpath = new DOMXpath($osm);
    
    
$tigers OSMGetWIWOSM($xpath);
    foreach (
$tigers as $tiger) {
        
$original OSMGetTagValue($xpath'wikipedia'$tiger);
        
JOSMCommandLineLog('Tiger '.$original);
        
$checked  WPAPINormalize(LANG$original);
        if ((
FALSE != $checked) && ($original != checked)) {
            
$log .= htmlentities($original.' => '.$checked."\n");
            
OSMSetTagValue($xpath'wikipedia'$tigerLANG.':'.$checked);
            
OSMSetAttributeValue($xpath'action'$tiger'modify');
        } else {
            
// remove unmodified OSM object from document
            
$parent $tiger->parentNode;
            
$parent->removeChild($tiger);
        }
    }

    
// delete all unmodified from result
    
$unmodified OSMGetUnmodified($xpath);
    foreach (
$unmodified as $to_delete) {
        
$parent $to_delete->parentNode;
        
$parent->removeChild($to_delete);
    }
    
    
//$log = "\n".'<![CDATA['.$log.']]>'."\n";
    //$osm->getElementsByTagName('osm')->item(0)->appendChild(new DOMComment($log));

    //echo $osm->schemaValidate('osm-0.6.dtd');
    
JOSMCommandLineLog('Finished');
    echo 
$osm->saveXML();

} else {
    
header("HTTP/1.0 404 Not Found");
    
header('Content-Type: text/html');
    echo 
'<pre>';
    
print_r(error_get_last());
    echo 
'</pre>';
    echo 
'<p>Did you send your OSM-XML in the HTTP request body?</p>';
    echo 
'<p>See <a href="http://wiki.openstreetmap.org/wiki/Mechanical_Edits/jjaf.de">usage</a>.</p>';
}

// ### OSM ###

function OSMGetTIGERcnl($osm) {
    
$objects $osm->query('/osm/*[@uid="'.UID.'"][@version="1"]');
    return 
$objects;
}

function 
OSMGetWIWOSM($osm) {
    
$objects $osm->query('/osm/*/tag[@k="wikipedia"]/..');
    return 
$objects;
}

function 
OSMGetUnmodified($osm) {
    
$objects $osm->query('/osm/*[not(@action)]');
    return 
$objects;
}

function 
OSMGetTagValue($osm$key$element) {
    
$tags $osm->query("./tag[@k='$key'][1]"$element);
    if (
$tags->length) {
        return 
$tags->item(0)->getAttribute('v');
    }
}

function 
OSMSetTagValue($osm$key$element$value) {
    
$tags $osm->query("./tag[@k='$key'][1]"$element);
    if (
$tags->length) {
        return 
$tags->item(0)->setAttribute('v'$value);
    }
}

function 
OSMSetAttributeValue($osm$key$element$value) {
    return 
$element->setAttribute($key$value);
}
?>