<?php
/*
=====================
Модуль скачен с сайта:
Понедельников НЕТ! - Сайт альтернативной поддержки Slaed CMS! (http://www.ponedelnikov.net)
=====================
SHAKA1, 2009
e-mail: seregam007@mail.ru
=====================
*/
# include common lib and config file
include_once ("common.inc.php");


# download forecast data
if (($fp = fopen(WEATHER_FULL_FORECAST_URL, "r")) !== false) {
	$file_content = fread($fp, 16384);
  $file_content = mb_convert_encoding($file_content, 'cp1251', 'UTF-8');

	# checking forecast version
	if (preg_match('/fullforecast version="1.2"/', $file_content)) {

		while (!feof($fp)) {
			$file_content .= mb_convert_encoding(fread($fp, 16384), 'cp1251', 'UTF-8');

			# get all city forecast
			if (preg_match_all('@<forecast city="(\d+)">(.*?)</forecast>@is', $file_content, $forecast_found)) {

				foreach ($forecast_found[2] as $link_city_id => $inner_forecast_found) {
					$added_count = $all_count = 0;
					$city_id = $forecast_found[1][$link_city_id];

					# get city forecast divided by date-hour
					preg_match_all('@<day date="(\d{4}-\d{2}-\d{2})" hour="(\d{1,2})">(.*?)</day>@is', $inner_forecast_found, $hour_data);
					foreach ($hour_data[3] as $key => $params) {
						$forecast = readXmlElements($params, true);

						$all_count++;
						$sql = sprintf("INSERT INTO `%s` (`city_id`, `date`, `hour`, `cloud`, `precip`, `t_min`,
											`t_max`, `p_min`, `p_max`, `w_min`, `w_max`, `w_rumb`, `h_min`, `h_max`, `wpi`)
										VALUES (%d, '%s', %d, %d, %d, '%s', '%s', %d, %d, %d, %d, '%d', %d, %d, %d)
										ON DUPLICATE KEY UPDATE `cloud` = %5\$d, `precip` = %6\$d, `t_min` = '%7\$s',
											`t_max` = '%8\$s', `p_min` = %9\$d, `p_max` = %10\$d, `w_min` = %11\$d,
											`w_max` = %12\$d, `w_rumb` = '%13\$d', `h_min` = %14\$d, `h_max` = %15\$d,
											`wpi` = %16\$d",
								WEATHER_FORECAST_TABLE_NAME,
								$city_id,
								$hour_data[1][$key],
								$hour_data[2][$key],
								$forecast['cloud'],
								$forecast['ppcp'],
								$forecast['t_min'],
								$forecast['t_max'],
								$forecast['p_min'],
								$forecast['p_max'],
								$forecast['wind_min'],
								$forecast['wind_max'],
								$forecast['wind_rumb'],
								$forecast['h_min'],
								$forecast['h_max'],
								$forecast['wpi']
							);

						if (!mysql_ping()) {
							mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) OR DIE("Can't connect to a database server");
						}

						if (mysql_query($sql)) $added_count++;
						else die(mysql_error());
					}

					showMsg('Added '.$added_count.' of '.$all_count.' forecast records for '.$city_id);
					$file_content = str_replace($forecast_found[0][$link_city_id], '', $file_content);
				}
			}
		}
	}
	else showMsg('This is not 1.2 version of XML FullForecast data ('.$parced_xml[0]['attrs']['VERSION'].')');
}
else showMsg("Can't get XML FullForecast data from '".WEATHER_FULL_FORECAST_URL."'");


?>