<?php
/*
Plugin Name: Google Weather 4 WP
Plugin URI: http://www.virtual2.net/
Description: Plugin to show the weather on your blog.
Author: César Araújo & Ricardo Jorge
Version: 1.3
Author URI: http://www.virtual2.net/
*/


// ATENÇÃO QUE O OUTPUT É DIFERENTE SE FOR ESTADO ACTUAL OU PREVISÃO
//
// **************************
// **  ESTADO ACTUAL TEM   **
// **************************
// TEMP -> TEMPERATURA ACTUAL
// HUMI -> HUMIDADE ACTUAL
// ICON -> IMAGEM DO GOOGLE
// COND -> DESCRIÇÃO DO ESTADO
// VENTO -> VENTO ACTUAL
//
// **************************
// **     PREVISÃO TEM     **
// **************************
// MIN -> TEMP MINIMA
// MAX -> TEMP MAXIMA
// ICON -> IMAGEM DO GOOGLE
// COND -> DESCRIÇÃO DO ESTADO
// DOW -> DIA DA SEMANA
//
// ATENÇÃO QUE O OUTPUT É DIFERENTE SE FOR ESTADO ACTUAL OU PREVISÃO


function get_meteorologia($lingua, $cidade){
	// Cria Google API url
	$meteorologia_url = 'http://www.google.com/ig/api?weather='. $cidade . '&hl=' . $lingua;

	$resultado = array();	
	// Obtem o ficheiro XML
	if ($wxml = @file($meteorologia_url)) {
		$wxml[0] = utf8_encode($wxml[0]);
		$xml = new SimpleXMLElement($wxml[0]); 

		// ESTADO ACTUAL
		$weather = $xml->weather->current_conditions;
		// $resultado[tempf] = $weather->temp_f['data']; //Farenheit não interessa a ninguem :p
		$resultado['temp0'] = $weather->temp_c['data']; 
		$resultado['vento0'] = $weather->wind_condition['data'];
		$resultado['humi0'] = $weather->humidity['data'];
		$resultado['icon0'] = substr(strrchr($weather->icon['data'],"/"),1,-3) . 'png';
	  	$resultado['cond0'] = $weather->condition['data'];

		// PREVISAO
		$weather = $xml->weather->forecast_conditions;
		$contador=1;
		foreach ($weather as $values ) {
			$resultado['min' . $contador] = $values->low['data'];
			$resultado['max' . $contador] = $values->high['data'];
			$resultado['dow' . $contador] = $values->day_of_week['data'];					
			$resultado['icon' . $contador] = substr(strrchr($values ->icon['data'],"/"),1,-3) . 'png';
			$resultado['cond' . $contador] = $values->condition['data'];
			$contador++;
		}
	}
	return  $resultado;
}

// Fim de funções auxiliares de calculo

function calc_googleWeather4WP() // Onde desenhamos o conteudo :)
{

	// Vou verificar se o user defeniu qTranslate ou não e se o mesmo nao existir defenimos uma linguagem default.
	if($option['translate']){
		if (function_exists(qtrans_getLanguage)){ //Temos qTranslate?
			$lang= qtrans_getLanguage();	// Parece que sim portanto vamos usar a linguagem lá defenida
		 }else{
		 	$lang = $option['defaultlang']; // Não temos qTranslate portanto linguagem default
		 }
	}else{
		$lang = $option['defaultlang']; // Ora bem o user não selecionou a  opção qTranslate por isso linguagem default
	}

	if (!$lang){ $lang = 'pt-pt'; } // Não temos nada? está a usar um plugin fresquinho sem configurar por isso é tuga =D
	if (!$option['city']) { $city = 'porto,portugal'; }else{ $city= $option['city']; } // No caso de cidade não defenida, é cá dos nossos, Porto carago

	// Vamos obter o estado metereologico para um array
	$resultado =  get_meteorologia($lang, $city);

	desenha_widget($resultado);

}

function desenha_widget($resultado){
?>
<div id="gw4wpimg" style="position:relative; text-align:center;"><img src="<?php echo get_bloginfo('wpurl') . '/wp-content/plugins/google-weather-4-wp/imgs/' . $resultado['icon0']; ?>" alt="<?php echo$resultado['icon0']; ?>" title="<?php echo $resultado['cond0']; ?>" />
<div id="gw4wpdesc" style="font-size:40px; position:absolute; bottom:10px; width:100%; margin-left:auto; margin-right:auto; text-align:center;"><?php echo $resultado['temp0']; ?> <sup>o</sup>C</div>
</div>
<?php
}

 // ************************************************************************************ //
 
 
 
function widget_googleWeather4WP($args) {
  extract($args);
  $options = get_option("widget_googleWeather4WP");
  if (!is_array( $options )){
		$options = array(
      	'title' => 'GoogleWeather 4 WP',
      	'days' => 0,
      	'translate' => true,
      	'defaultlang' => 'pt-pt'
      	
      );
  }
  
  echo $before_widget;
  echo $before_title;?><?php echo $options['title'] ?><?php echo $after_title; calc_googleWeather4WP();
  echo $after_widget;
}
 
 
 // ************************************************************************************ //
 
 
 function googleWeather4WP_control()
{
	$options = get_option("widget_googleWeather4WP");
	if (!is_array( $options )){
		$options = array(
      	'title' => 'GoogleWeather 4 WP',
      	'days' => 0,
      	'translate' => true,
      	'defaultlang' => 'pt-pt'
		);
	}
 
  if ($_POST['googleWeather4WP-Submit'])
  {
    $options['title'] = htmlspecialchars($_POST['googleWeather4WP-WidgetTitle']);
    $options['city'] = htmlspecialchars($_POST['googleWeather4WP-Widgetcity']);
    $options['days'] = htmlspecialchars($_POST['googleWeather4WP-Widgetdays']);
    $options['translate'] = htmlspecialchars($_POST['googleWeather4WP-Widgettranslate']);
    $options['defaultlang'] = htmlspecialchars($_POST['googleWeather4WP-Widgetdefaultlang']);
    update_option("widget_googleWeather4WP", $options);
  }

	// Verificação da existencia do plugin qTranslate
	if (function_exists(qtrans_getLanguage)){
		$autolang= qtrans_getLanguage();
	 }else{
	 	$autolang="";
	 }

?>

<p>
	<label for="googleWeather4WP-WidgetTitle">Widget title: </label><br />
   <input type="text" id="googleWeather4WP-WidgetTitle" name="googleWeather4WP-WidgetTitle" value="<?php echo $options['title'];?>" />
</p>
<p>
	<label for="googleWeather4WP-Widgetcity">City: (ex: porto,portugal)</label><br />
   <input type="text" id="googleWeather4WP-Widgetcity" name="googleWeather4WP-Widgetcity" value="<?php echo $options['city'];?>" />
</p>
<p>
   <label for="googleWeather4WP-Widgetdays">Show forecast for: </label><br />
   <select id="googleWeather4WP-Widgetdays" name="googleWeather4WP-Widgetdays">
		<option value="0" <?php if ($options['days']==0){ echo 'selected="true"'; } ?>>Do not show</option>
		<option value="1" <?php if ($options['days']==1){ echo 'selected="true"'; } ?>>1 day</option>
		<option value="2" <?php if ($options['days']==2){ echo 'selected="true"'; } ?>>2 days</option>
		<option value="3" <?php if ($options['days']==3){ echo 'selected="true"'; } ?>>3 days</option>
		<option value="4" <?php if ($options['days']==4){ echo 'selected="true"'; } ?>>4 days</option>
		<option value="5" <?php if ($options['days']==5){ echo 'selected="true"'; } ?>>5 days</option>
	</select>
</p>
<p>


	<input type="checkbox" id="googleWeather4WP-Widgettranslate" name="googleWeather4WP-Widgettranslate" value="translate" <?php if ($options['translate']){ echo 'checked="true"'; } ?> <?php  if (!$autolang){ echo 'disabled="true"'; } ?>> Use Qtranslate<br />

<br />
	<label for="googleWeather4WP-Widgetdefaultlang">Language by default: (ex: es) </label><br />
   <input type="text" id="googleWeather4WP-Widgetdefaultlang" name="googleWeather4WP-Widgetdefaultlang" value="<?php echo $options['defaultlang'];?>" />

</p>
<p>
	<input type="hidden" id="googleWeather4WP-Submit" name="googleWeather4WP-Submit" value="1" />
</p>
<?php
}


 // ************************************************************************************ //


function googleWeather4WP_init()
{
  register_sidebar_widget(__('Google Weather 4 WP'), 'widget_googleWeather4WP');
  register_widget_control(   'Google Weather 4 WP', 'googleWeather4WP_control', 300, 200 );
}


 // ************************************************************************************ //


add_action("plugins_loaded", "googleWeather4WP_init");
