<?php
/* 
Get regional alarm/warning from http://www.meteoalarm.eu/
Orginal script by Ken True - saratoga-weather.org
Modded by Henkka, nordicweather.net, July 2012
 
-------------Settings ---------------------------------*/
$Lang = 'fi';     // default language
$isFIN = true;   // Does the warning show warnings from Finland? true/false 
                 // If true, we need to crop the texts as all languages (3) are all in one row...
#
# WarningUrls, $Sea_EUA_URL is for using second warningarea for ex. seawarnings
$EUA_URL = 'http://www.meteoalarm.eu/su_FI/0/0/FI032-Varsinais-Suomi.html';
$Sea_EUA_URL = 'http://www.meteoalarm.eu/su_FI/0/0/FI811-Sea_of_Archipelago.htmll';
$multiwarn = true;    // Use two areas for ex seawarnings if your Metoffice supports it, true/false,
#
# create a cache-folder and chmod it to 0777.
$EUAcacheName = "cache/meteoalarm.txt"; // prototype for path/filename for cache file
$Sea_EUAcacheName = "cache/sea-meteoalarm.txt";
# note: $EUAcacheName will be changed to -$Lang.txt (like -en.txt) to allow languages to have unique cache files.
#
$EUArefetchSeconds = 600;  // refresh every hour
#
/* the following note is required by agreement with the authors of the website www.meteoalarm.eu
-----------------------------------------------------------------------------------------
Date: Thu, 11 Sep 2008 11:39:52 +0200
From: karin buchauer <karin.buchauer@zamg.ac.at>
Organization: zamg

Dear Mr True,

you are quite right:
you can use the material featured on the website, without modifying it, providing the source (link) as well as time and date of issue of the data, as stipulated in the Terms & Conditions.

With best regards,
Karin Buchauer

Ken True schrieb:
> Dear Sirs,
>
> I am an amateur weather enthusiast who also writes scripting for other weather enthusiasts to incorporate weather data into their personal, non-commercial weather websites.  Many of my scripts (which I write as a hobby, and are distributed gratis) are in use on personal weather websites worldwide.
>
> I've had requests to package the excellent data from www.meteoalarm.eu for weather advisories in EU countries, and before I generate a script for that purpose, I'd like to have your permission to proceed.
>
> Your Terms and Conditions page (http://www.meteoalarm.eu/terms.asp?lang=EN ) says:
>
> "The material featured on this site is the common property of the Meteoalarm partners, and is subject to copyright protection.
> The ownership and intellectual rights on all operational and updated awareness and warning information delivered to the Meteoalarm system remain with the Meteoalarm partners who originally delivered this information. The information on this web site may be used freely by the public.
> Before using information obtained from this server special attention should be given to the date & time of the data and products being displayed.
> In case this information is re-used: This information shall not be modified in content and the source of the information has always to be displayed as EUMETNET - MeteoAlarm, or if a single country, the providing national Institute (for internet application in all cases in the form of a link to: www.meteoalarm.eu). The time of issue at www.meteoalarm.eu must be count.
>
> Third parties producing copyrighted works consisting predominantly of the material of this website must provide notice with such work(s) identifying the source of material incorporated and stating that such material is not subject to copyright protection. Further information can be obtained from this following address: meteoalarm@zamg.ac.at"
>
> My reading of this implies that you do permit re-use/publishing of the information with attribution and an active link to the source page for the data on your site, and a note that the data is copyrighted by the data providing organization (and not subject to copyright by the 3rd-party website including/displaying the data).  Is that correct?
>
> Is it ok with you for me to generate a script for displaying national/regional weather alerts using your data from www.meteoalarm.eu with the appropriate attribution.
>
> Please feel free to examine other scripts I've written which use NOAA, Environment Canada, US Geological Services, and temis.nl as data sources (http://saratoga-weather.org/scripts.php ).
>
> Thank you in advance for your response,
>
> Best regards,
> Ken True
> webmaster@saratoga-weather.org
> Saratoga, California, USA

-- 

Karin Buchauer
Assistant to the Project Manager EMMA

Zentralanstalt für Meteorologie und Geodynamik
Regionalstelle für Salzburg und Oberösterreich
Freisaalweg 16
A - 5020 SALZBURG
Fon ++43 (0)662 626301-22
Fax ++43 (0)662 625838
karin.buchauer@zamg.ac.at       www.zamg.ac.at
----------------------------------------------------------------------------------------- */

$EUA_languages = array( 
  'en' => 'en_UK',  // english
  'ct' => 'ca_ES',  // català
  'dk' => 'da_DK',  // dansk
  'de' => 'de_GE',  // deutsch
  'es' => 'es_ES',  // español
  'fr' => 'fr_FR',  // français
  'it' => 'it_IT',  // italiano
  'hu' => 'ma_HU',  // magyar
  'nl' => 'ne_NL',  // nederlands
  'no' => 'no_NO',  // norsk
  'pl' => 'po_PL',  // polski
  'pt' => 'po_PT',  // português
  'ro' => 'ro_RO',  // româna
  'fi' => 'su_FI',  // suomi
  'sv' => 'sv_SE',  // svenska
  'el' => 'gr_GR',  // greek
);

$EUA_warncolors = array(
'l0' => '#ffffff',      // white .. Missing, insufficient, outdated or suspicious data.
'l1' => '#29d660',   // green .. No particular awareness of the weather is required.
'l2' => '#ffff66',  // yellow ..The weather is potentially dangerous.
'l3' => '#ffCC33',  // orange ..The weather is dangerous.
'l4' => '#ff6666'   // red ..   The weather is very dangerous.
);

$Lang = $lang;
if (isset($_REQUEST['lang'])) {  // 
  $tlang = strtolower($_REQUEST['lang']);
  if (isset($EUA_languages[$tlang])) {
  $EUA_lang = $EUA_languages[$tlang];
	$Lang = $tlang;
  }
}
$EUA_lang = $EUA_languages[$Lang];

print "<!-- lang=$Lang ($EUA_lang) used -->\n";
$EUA_URL = preg_replace('|meteoalarm.eu/[^/]+/|',"meteoalarm.eu/$EUA_lang/",$EUA_URL);
$EUAcacheName = preg_replace('|\.txt$|',"-$Lang.txt",$EUAcacheName);
$EUA_URLLink = htmlspecialchars($EUA_URL);
$Sea_EUA_URL = preg_replace('|meteoalarm.eu/[^/]+/|',"meteoalarm.eu/$EUA_lang/",$Sea_EUA_URL);;
$Sea_EUAcacheName = preg_replace('|\.txt$|',"-$Lang.txt",$Sea_EUAcacheName);
$Sea_EUA_URLLink = htmlspecialchars($Sea_EUA_URL);

/// Translations
if($Lang == "sv" || $Lang == "se") {
$activ = "Följande varningar är i kraft i:";
$showtxt = 'Visa';
$hidetxt = 'Stäng';
$requiredNoteEUA = 'Varningarna utfärdas av och är copyright &copy; <a href="'.$EUA_URLLink.'"  target="_blank">EUMETNET-MeteoAlarm</a>. Tidskillnad mellan denna websida och www.meteoalarm.eu-websidan kan förekomma. För varningar i realtid som publiceras av deltagande nationella vädertjänsterna hänvisas vänligen till <a href="'.$EUA_URLLink.'" target="_blank">www.meteoalarm.eu</a>. Använt med lov. De finska varningarna produceras av';

} else if($Lang == "fi") {
$activ = "Voimassa olevat varoitukset:";
$showtxt = 'Näytä';
$hidetxt = 'Piilota';
$requiredNoteEUA = 'Varoitustiedot tuottaa ja on copyright &copy; <a href="'.$EUA_URLLink.'"  target="_blank">EUMETNET-MeteoAlarm</a>. Viiveet tämän sivuston ja www.meteoalarm.eu –sivuston välillä ovat mahdollisia. Reaaliaikaiset tiedot osallistujamaiden kansallisten sääpalveluiden julkaisemista vaaratasoista ovat nähtävissä sivulla <a href="'.$EUA_URLLink.'" target="_blank">www.meteoalarm.eu</a>. Käytetty luvalla. Suomen varoitukset tuottaa';

} else {
$activ = "Active warnings in:";
$showtxt = 'Show';
$hidetxt = 'Hide';
$requiredNoteEUA = 'Warning data courtesy of and Copyright &copy; <a href="'.$EUA_URLLink.'"  target="_blank">EUMETNET-MeteoAlarm</a>. Time delays between this website and the www.meteoalarm.eu website are possible, for the most up to date information about alert levels as published by the participating National Meteorological Services please use <a href="'.$EUA_URLLink.'" target="_blank">www.meteoalarm.eu</a>. Used with permission. Finnish warnings provided by';
}
// Translations end

print "<!-- ".strip_tags($requiredNoteEUA)." -->\n";

// refresh cached copy of page if needed
// fetch/cache code by Tom at carterlake.org
$EUAwarning = '';
$active = false;
getalarm($EUA_URL,$EUAcacheName);
if($multiwarn){getalarm($Sea_EUA_URL,$Sea_EUAcacheName);}

function getalarm($EUA_URL,$EUAcacheName) {
global $EUAMetOffice,$EUAtop,$EUAwarning,$EUAregionName,$EUArefetchSeconds,$Lang,$isFIN,$fr;
global $warnValid,$EUA_warncolors,$EUAbg,$active,$lii;
$rname = '';
$fr++;

  //$html = file_get_contents($EUAcacheName);
if (file_exists($EUAcacheName) and filemtime($EUAcacheName) + $EUArefetchSeconds > time()) {
      $WhereLoaded = "from cache $EUAcacheName";
      $html = file_get_contents($EUAcacheName);
    } else {
      $WhereLoaded = "from URL $EUA_URL";
      $html = getmeteo($EUA_URL);
      file_put_contents($EUAcacheName,$html);
      chmod($EUAcacheName,0666); 
    }
    
  print "<!-- Meteoalarm data load from $WhereLoaded -->\n";
  if(strlen($html) < 50 ) {print "<!-- data not available -->\n";return;}

  $EUAregionName = '';

  preg_match('|charset=([^"]+)\r\n"|i',$html,$matches);
  if (isset($matches[1])) {
	  	    $charsetInput = strtoupper($matches[1]);
  } else {
  	    $charsetInput = 'UTF-8';
  }

  // now slice it up
  // Get the table to use:
  preg_match_all('!<td[^>]*(class|width)="([^"]+)"[^>]*>(.*)</td>!Uis',$html,$betweenspan);
  $cData  = $betweenspan[3];  // contains the <td class="..">(.*)</td> data area
  //print "<!-- cData \n" . print_r($cData,true) . " -->\n";

  $cTypes = $betweenspan[1];  // contains 'class' or 'width'
  $cNames = $betweenspan[2];  // contains the class="(.*)" or width="(.*)" values
  $cData  = $betweenspan[3];  // contains the <td class="..">(.*)</td> data area
  
  $temp = explode('<br>',$cData[3]);  // split out the links
  $tstr = $temp[count($temp)-1];
  preg_match('|<a href="(.*)".*>\s*<p>(.*)</p>\s*<img.*alt="(.*)"|Uis',$tstr,$matches);
  if(isset($matches[0]) and count($matches[0]) > 0) {
  	    $moreInfo = '<a href="' . trim($matches[1]) . '">' . trim($matches[2]).'</a>';
  	    $EUAMetOffice = '<a href="' . trim($matches[1]) . '">' . trim($matches[3]).'</a>';
  	    $EUAMetOffice = preg_replace('|Go to |i','',$EUAMetOffice);
  }
  $EUAMetOffice = str_replace("<a href",'<a target="_blank" href',$EUAMetOffice);
  
  $EUAregionName = preg_replace('|&nbsp;|',"",strip_tags($cData[0]));
	$EUAregionName = substr(strrchr($EUAregionName, ": "), 1 );
  //echo $EUAregionName;
  
  
  preg_match_all('|<div class="warnbox[^"]+">(.*)\t</div>|Uis',$cData[1],$warnboxes);
  //print "<!-- warnboxes\n".print_r($warnboxes,true)." -->\n";

  for ($idx = 0;$idx < count($warnboxes[1]);$idx++) {  // loop over the warning box notices
    preg_match('|<div class="warnbox awt\s+\S+\s+\S+\s+([^"]+)">|is',$warnboxes[0][$idx],$colormatches);
    if(isset($colormatches[1]) ) {
      $tColorCode = $colormatches[1];
      //echo $tColorCode.'|';
    }
    if($tColorCode<>"l1"||$tColorCode<>"l1"){
      $active = true;
      $EUAwarning.= '<div style="padding:4px;">'."\n";
    
      $rawWarning = trim($warnboxes[1][$idx]);
      preg_match('|pictures/aw(.*).jpg|',$rawWarning,$matches);
      $tType = 't'.substr($matches[1],0,-1);
      //echo $tType.'|';
      $warnIcon = '<span class="awt '.$tColorCode.' '.$tType.'"></span>';
      $warnIC = '<span class="flr awt '.$tColorCode.' '.$tType.'"></span>';
      if($tType=="t2"){
      $lii = '<div style="padding:4px;">'.$warnValid.'</div>
      <div style="padding:4px;"><span class="flr awt '.$tColorCode.' '.$tType.'"></span>';
      }
    
      preg_match_all('|<div class="([info"]+)".*>(.*)</div>|Uis',$rawWarning,$matches);
      $t = strip_tags($matches[0][0],'<b>');
      if (strlen($t)>0) {$warnValid = ucfirst($t);}
      //echo $warnValid.'|';
      $warnType = strip_tags($matches[0][1],'<b>');
      $warnType = str_replace("&nbsp;","",substr($warnType , 0, strpos($warnType ,'</b> '))).'</b>';
      //echo $warnType.'|';
    
      preg_match_all('|<div class="([text"]+)".*>(.*)</div>|Uis',$rawWarning,$matches);
      foreach ($matches[2] as $i => $txt) {
        $t = strip_tags($txt,'<b>');
        if (strlen($t)>0) {$warnTxt = $t . "<br/>\n";}
      }
      $warnBox = $warnTxt;
    
      if($isFIN == true) {
      $strip = explode(")", $warnTxt);
      if($Lang == "fi") { 
        $warnBox = '<b>'.str_replace(":",":</b>",$strip[0]).')';
        $EUAregionName = utf8_decode(substr($strip[0] , 0, strpos($strip[0] ,': ')));
        $EUAMetOffice = str_replace("Finnish Meteorological Institute","Ilmatieteen laitos",$EUAMetOffice);
      } elseif($Lang == "sv"||$Lang == "se") { 
        $warnBox = '<b>'.str_replace(":",":</b>",$strip[1]).')'; 
        $EUAregionName = utf8_decode(substr($strip[1] , 0, strpos($strip[1] ,': ')));
        $EUAMetOffice = str_replace("Finnish Meteorological Institute","Meteorologiska institutet",$EUAMetOffice);
      } else { 
        $warnBox = '<b>'.str_replace(":",":</b>",$strip[2]).')'; 
      }
      }
      $EUAwarning.= $warnIC.utf8_decode($warnBox).'</div>';
      if($tType=="t2"){$lii.= utf8_decode($warnBox).'</div>';}
      if($rname<>$EUAregionName){
      if($fr==1){$EUAtop.= ' <span class="malarmhead" style="margin-left:6px">'.$EUAregionName.':</span> ';}
      else{$EUAtop.= ' <span class="malarmhead">'.$EUAregionName.': </span>';}
      $rname = $EUAregionName;
      }
      //$EUAtop.= $warnIcon.'<span class="malarmhead">'.$warnType.'</span>';
      $EUAtop.= '<span style="display:inline-block;position:relative;left:12px">'.$warnIcon.'</span>  <span class="malarmhead">'.str_replace("<b>","",$warnType).'</span>';
    }
  } 
  
  
return;
}

if($active){
$htxt = '
<script>
$(document).ready(function(){
var hidetxt = "'.$hidetxt.'";
var showtxt = "'.$showtxt.'";
$("#meteomore").toggle(function() {
      $(".malarmmore").slideDown("slow");
      $("#meteomore").html(\'<b>\'+hidetxt+\'</b> <span class="ui-icon ui-icon-minusthick" style="display:inline-block;position:relative;top:4px;"></span>\');
      },
      function(){
      $(".malarmmore").slideUp("slow");
      $("#meteomore").html(\'<b>\'+showtxt+\'</b> <span class="ui-icon ui-icon-plusthick" style="display:inline-block;position:relative;top:4px;"></span>\');
      });
});
</script>
<div class="malarmbox shadow2"><span id="meteomore"><b>'.$showtxt.'</b> <span class="ui-icon ui-icon-plusthick" style="display:inline-block;position:relative;top:4px;"></span></span><span class="malarmhead"><b>'.$activ.'</b></span> '.$EUAtop.'
<div class="malarmmore"><div style="padding:4px;">'.$warnValid.'</div>'.$EUAwarning.'<div style="text-align:left;padding:20px 4px 4px 4px;"><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span><small>'.$requiredNoteEUA.' '.$EUAMetOffice.'.</small></div></div></div>
';
}

// ----------------------------functions ----------------------------------- 

function getmeteo($url) {
      $ch = curl_init();
      curl_setopt ($ch, CURLOPT_URL, $url);
      curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20120424 Firefox/12.0 PaleMoon/12.0');
      curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt ($ch, CURLOPT_TIMEOUT,4);
      curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3);
      $stuff = curl_exec($ch);
      curl_close($ch);
      return $stuff;
}

// ----------------------------------------------------------
      
?>