Commons:Wiki Loves Monuments 2011/Tools/kml-ee.php

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
<?
// network link files at http://www.wikilovesmonuments.ee/kml/kultuurimalestised.kml (for Google Earth)
//   and http://wikilovesmonuments.ee/kml/kultuurimalestised-lihtne.kml (for Google Maps)

error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);

function commons_thumb_url( $fname,$w ) {
 $wgUploadDirectory="http://upload.wikimedia.org/wikipedia/commons/thumb";  
 
    $hash = md5( $fname );
    $dest = $wgUploadDirectory . '/' . $hash{0} . '/' . substr( $hash, 0, 2 ).'/' .$fname."/".$w."-".$fname;
 
 return $dest;
}

function replace_spaces( $in_string ) {
    return str_replace(' ', '_', $in_string);
}

function connect_monuments_db() {
    $host = 'sql.toolserver.org';
    ///$database = "p_erfgoed_p";
    $database = 'u_kentaur_wlm_p';

    $ts_pw = posix_getpwuid(posix_getuid());
    $ts_mycnf = parse_ini_file($ts_pw['dir'] . "/.my.cnf");
    $db = mysql_connect($host, $ts_mycnf['user'], $ts_mycnf['password']);
    unset($ts_mycnf, $ts_pw);
    if (!$db) {
        die('Not connected : ' . mysql_error());
    }

    $db_selected = mysql_select_db($database, $db); 
    if (!$db_selected) {
        die('Can\'t use db : ' . mysql_error());
    }    
    
    return $db;
} //func

//make string safe for XML
function XMLClean($string, $fullclean = true) {

    $strout = null;

    for ($i = 0; $i < strlen($string); $i++) {
        $ord = ord($string[$i]);

        if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
            if ($fullclean) {
                $strout .= "&amp;#{$ord};";
            } else {
                //needed to display name with õäöü in Google Earth
                $strout .= $string[$i];
            }
        } else {
            switch ($string[$i]) {
                case '<':
                    $strout .= '&lt;';
                    break;
                case '>':
                    $strout .= '&gt;';
                    break;
                case '&':
                    $strout .= '&amp;';
                    break;
                case '"':
                    $strout .= '&quot;';
                    break;
                default:
                    $strout .= $string[$i];
            }
        }
    } //for

    return $strout;
} //func
 
function create_wiki_urllink($matches) {

    global $wiki_url;
    $ret_urllink = '';
    
    $ret_urllink = '<A href="' . $wiki_url . urlencode(replace_spaces($matches[1])) . '">';
    if ( isset($matches[2]) ) {
        $ret_urllink .= $matches[2];
    } else {
        $ret_urllink .= $matches[1];
    }
    $ret_urllink .= '</a>';

    return $ret_urllink;
} //func


//main

$BOX = '';
$coords[0]=1;
$coords[1]=1;
$coords[2]=31;
$coords[3]=90;

// split the client's BBOX return by commas and spaces to obtain an array of coordinates
if (isset($_GET["BBOX"])) {
    $BOX = mysql_escape_string(urldecode( $_GET["BBOX"] ));
}
if (isset($_GET["bbox"]) ) {
    if ($BOX==""){$BOX = mysql_escape_string(urldecode( $_GET["bbox"] ));}
}
if ($BOX) {
    $coords = preg_split('/,|\s/', $BOX);
}
// for clarity, place each coordinate into a clearly marked bottom_left or top_right variable
$bl_lon = $coords[0];
$bl_lat = $coords[1];
$tr_lon = $coords[2];
$tr_lat = $coords[3];

$registrant_url = 'http://register.muinas.ee/?menuID=monument&action=view&id=';
$wiki_url = 'http://et.wikipedia.org/wiki/';


// Opens a connection to a MySQL server.

connect_monuments_db();

//FIXME N 0, E 0 are actually legal coordinates, fix database structure
//                      WHERE lat <> 0 AND lon <> 0 AND
$query = sprintf("SELECT * FROM `monuments_ee_(et)`
                     WHERE lat <> 0 AND lon <> 0 AND 
                       lon >= '%s' AND lon <= '%s' AND
                       lat >= '%s' AND lat <= '%s'
                     ORDER BY pilt DESC LIMIT 80",
                 $bl_lon,
                 $tr_lon,
                 $bl_lat,
                 $tr_lat);


$result = mysql_query($query);

if (!$result) 
{
  die('Invalid query: ' . mysql_error());
}

// Creates the Document.
$dom = new DOMDocument('1.0', 'UTF-8');

// Creates the root KML element and appends it to the root document.
$node = $dom->createElementNS('http://www.opengis.net/kml/2.2', 'kml');
$parNode = $dom->appendChild($node);

// Creates a KML Document element and append it to the KML element.
$dnode = $dom->createElement('Document');
$docNode = $parNode->appendChild($dnode);

// Creates Style elements
$monStyleNode = $dom->createElement('Style');
$monStyleNode->setAttribute('id', 'monumentStyle');
$monIconstyleNode = $dom->createElement('IconStyle');
$monIconstyleNode->setAttribute('id', 'monumentIcon');
$monIconNode = $dom->createElement('Icon');
$monHref = $dom->createElement('href', 'http://maps.google.com/mapfiles/kml/paddle/red-blank.png');
$monIconNode->appendChild($monHref);
$monIconstyleNode->appendChild($monIconNode);
$monStyleNode->appendChild($monIconstyleNode);
$docNode->appendChild($monStyleNode);

$monStyleNode = $dom->createElement('Style');
$monStyleNode->setAttribute('id', 'monPicStyle');
$monIconstyleNode = $dom->createElement('IconStyle');
$monIconstyleNode->setAttribute('id', 'monPicIcon');
$monIconNode = $dom->createElement('Icon');
$monHref = $dom->createElement('href', 'http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
$monIconNode->appendChild($monHref);
$monIconstyleNode->appendChild($monIconNode);
$monStyleNode->appendChild($monIconstyleNode);
$docNode->appendChild($monStyleNode);


// Iterates through the MySQL results, creating one Placemark for each row.
while ($row = @mysql_fetch_assoc($result))
{
  // Creates a Placemark and append it to the Document.

  $node = $dom->createElement('Placemark');
  $placeNode = $docNode->appendChild($node);

  // Creates an id attribute and assign it the value of id column.
  $placeNode->setAttribute('id', 'placemark' . $row['number']);

  // Create name, and description elements and assigns them the values of the name and address columns from the results.

    $name = $row['nimi'];
    $address = '';
    if (preg_match("/\[\[/", $name) ) {            //include wikilinked name in address
        $address = $name . ', ';
    }
    $name = preg_replace ("/\[\[(.+?)\|(.+?)\]\]/",  "$2", $name);
    $name = preg_replace ("/\[\[(.+?)\]\]/",  "$1", $name);
        
    $fullclean = false;   
    $name = XMLClean( utf8_encode($name), $fullclean);
    $nameNode = $dom->createElement('name',  $name);
    $placeNode->appendChild($nameNode);

    $reg_url = $registrant_url . $row['number'];
    $address .= $row['aadress'] . ', ' . $row['omavalitsus'];
  
    $address = preg_replace_callback(
            "/\[\[([^\]]+?)\|([^\]]+?)\]\]/",
            "create_wiki_urllink",
            $address);  
    $address = preg_replace_callback(
            "/\[\[([^\]]+?)\]\]/",
            "create_wiki_urllink",
            $address);  

//FIXME all utf-8 filenames don't work, for example: Нарвский_замок_2.jpg
            
    $image = '';
    if ($row['pilt']) {
        $image = XMLClean('<img src="') . commons_thumb_url( urlencode(utf8_encode($row['pilt'])), "80px") . XMLClean('">');
    }
    
    if (preg_match("/^(.+?)&/", $row['source'], $matches) ) { 
        $wiki_list_url = $matches[1];
    }    
    $description = $image . XMLClean($address . ' <A href="' . $reg_url . '">Kultuurimälestiste registis...</a>' );
    $description .= XMLClean(' <A href="' . $wiki_list_url . '">loendis...</a>');
  
  
///  $description = '<![CDATA[' . $description . ']]>';
  $descNode = $dom->createElement('description', $description);
  $placeNode->appendChild($descNode);
  if ($row['pilt']) {
    $styleUrl = $dom->createElement('styleUrl', '#monPicStyle');
  } else {
    $styleUrl = $dom->createElement('styleUrl', '#monumentStyle');
  }
  $placeNode->appendChild($styleUrl);

  // Creates a Point element.
  $pointNode = $dom->createElement('Point');
  $placeNode->appendChild($pointNode);

  // Creates a coordinates element and gives it the value of the lon and lat columns from the results.
  $coorStr = $row['lon'] . ','  . $row['lat'];
  $coorNode = $dom->createElement('coordinates', $coorStr);
  $pointNode->appendChild($coorNode);
} //while

$kmlOutput = $dom->saveXML();
header('Content-type: application/vnd.google-earth.kml+xml');
echo $kmlOutput;

?>