<?php
@ ini_set('display_errors', false);

@ header("content-type: text/html; charset=utf-8");


function city_err_journal($city) {
  global $web;
  $city_err_file = $GLOBALS['WEATHER_DATA'].'writable/__temp__/weather/'.$web['weather_from'].'/img/city_err_journal.txt';
  if ($f = file_get_contents($city_err_file)) {
    if (preg_match("/".preg_quote($city, "/")."[\n\r]+/", $f)) {
      return false;
    }
  }
  if ($fp = @fopen($city_err_file, 'ab')) {
    @fwrite($fp, "".$city."\n");
    @fclose($fp);
  }
}

function get_w_img_($matches) {
  global $web;
  $img = $matches[1];
  $img = preg_replace('/\?.*$/', '', $img);
  if (preg_match('/\.(gif|jpe?g|png|bmp)$/i', $img)) {
    $img_ = basename(dirname($img)).'_'.basename($img);
    $img_file = 'writable/__temp__/weather/'.$web['weather_from'].'/img/'.$img_.'';
    if (file_exists($GLOBALS['WEATHER_DATA'].$img_file)) {
      return '<img src="'.$img_file.'" style="height:34px !important;" />';
    } else {
      if ($img_file_ = read_file($img)) {
        write_file($GLOBALS['WEATHER_DATA'].$img_file, $img_file_);
        return '<img src="'.$img_file.'" style="height:34px !important;" />';
      } else {
        return '<img src="'.$img.'" style="height:34px !important;" />';
      }
    }
  } else {
    return '';
  }
}


if (isset($_GET['type']) && $_GET['type'] == 2) :

$t = '2';
//得到天气 完善的
function getWEATHER($city, $city2) {
  global $tmp;
  $city_ = @explode('|', $city2);
  $weatherurl = 'http://www.nmc.cn/publish/forecast/'.$city_[1].'/'.$city_[0].'.html';
  $weather = '
<script type="text/javascript" language="javaScript">
if (par != null) {
  var bodyW = 550;
  var bodyH = 422;
  document.write(\'<style>body { width:550px!important; height:422px!important; overflow:hidden!important; margin:0!important; }.weather_all {width:150px; height:419px; color:#FFFFFF; position:fixed; top:35px; left:100%; margin-left:-150px; z-index:1; display:block;}</style>\');
}
</script>

<div style="width:100%; min-width:1210px; height:1822px; overflow:hidden;"><a href="weather.php" class="weather_all" target="_blank">更多详情&raquo;</a>
<iframe id="weather162100" name="weather162100" src="'.$weatherurl.'" width="100%" height="2002" allowtransparency="true" frameborder="0" marginwidth="0" marginheight="0" scrolling="No" style="margin-top:-180px;"></iframe></div>';
  if (!empty($weather)) {
    $GLOBALS['WEATHER_BORN'] = 1;
    write_file($tmp, $weather);
  } else {
    @ setcookie('weathercity', '', -(time() + 365 * 24 * 60 * 60), '/'); //+8*3600
    @ setcookie('weathercity2', '', -(time() + 365 * 24 * 60 * 60), '/'); //+8*3600
    @unlink($tmp);
	$GLOBALS['WEATHER_BORN'] = 0;
    $weather .= '<span style="background-color:#FFFFFF;">天气预报获取失败！请稍候再试。<br />
可能采集源：中央气象台出错[<a href="weather.php?err='.urlencode($weatherurl).'" target="_blank" style="color:blue;">去解决</a>]</span>';
  }
  return $weather;
}

else :

$t = '';
//得到天气 简单的
function getWEATHER($city, $city2) {
  global $web, $tmp;
  $city_ = @explode('|', $city2);
  $weatherurl = 'http://www.nmc.cn/publish/forecast/'.$city_[1].'/'.$city_[0].'.html';
  $weather = '';
  if ($W_FR = read_file($weatherurl)) {
    $weather .= '
<span class="weather">
  <span id="city_where" onmouseover="ct=window.setInterval(function(){showWD($(\'city_where\'), \'weather.php?area=china\', \'660px\', \'auto\');}, 100);" onmouseout="window.clearInterval(ct);">
    <!--a href="weather.php?area=china" id="weather_where"><img src="readonly/images/po.png" /></a-->
    <a href="weather.php" id="weather_city" title="切换城市">'.$city.'</a>
  </span>
  <a href="weather.php" id="weather_show">
';

    $today = $night = '';
    if (preg_match('/id=[\"\']?day7[\"\']?(.+<\/div>)[\n\r\s]*<\/div>[\n\r\s]*<\/div>/isU', $W_FR, $m)) {
      $W_FR = $m[1];
      unset($m);
      preg_match_all('/<div [^>]*>(.+)<\/div>/isU', $W_FR, $m);
      if (count($m[1]) > 0) {
	    $m[1] = preg_replace('/\&nbsp\;/i', '', $m[1]);
	    $m[1] = preg_replace('/[\n\r\s]+/i', '', $m[1]);
        list($no0, $img_1, $desc_1, $no1, $no2, $tmp_1, $tmp_2, $img_2, $desc_2, $no3, $no4) = $m[1];
        unset($m);
        unset($W_FR);
		//白天
		if ($img_1 != '') {
          $img_1 = preg_replace_callback('/^.+src="([^\"\'\>\s]+)".+$/is', 'get_w_img_', $img_1);
	      $today = '<span id="w_today" title="白天" onmouseover="sSD(this,event);"><img src="readonly/weather/'.$web['weather_from'].'/t.png" class="w_img2" /><span class="w_img">'.$img_1.'</span><span class="w_qingkuang">'.$desc_1.'</span><span class="w_wendu'.(floatval($tmp_1)>0 ? ' w_wendu_ls':' w_wendu_lx').'">'.$tmp_1.'</span>';
          $today .= '</span>';
		}
		if ($img_2 != '') {
          $img_2 = preg_replace_callback('/^.+src="([^\"\'\>\s]+)".+$/is', 'get_w_img_', $img_2);
	      $night = '<span id="w_moday" title="夜间" onmouseover="sSD(this,event);"><img src="readonly/weather/'.$web['weather_from'].'/n.png" class="w_img2" /><span class="w_img">'.$img_2.'</span><span class="w_qingkuang">'.$desc_2.'</span><span class="w_wendu'.(floatval($tmp_2)>0 ? ' w_wendu_ls':' w_wendu_lx').'">'.$tmp_2.'</span>';
          $night .= '</span>';
        }

      }
    }
  }
  if ($today || $night) {
    //$to = $today && $night ? ' ～ ' : '';
    //$only = $today == '' && $night != '' ? '<img src="readonly/weather/'.$web['weather_from'].'/n.png" class="w_img2" />' : '';
	$to = $only = ' ';
	$weather .= $today.$to.$only.$night;
    $weather .= '<!--span class="w_xiangqing" title="未来详情">︾</span-->';
    $weather .= '</a>
</span>';
	$GLOBALS['WEATHER_BORN'] = 1;
    write_file($tmp, $weather);
  } else {
  	$GLOBALS['WEATHER_BORN'] = 0;
    @ setcookie('weathercity', '', -(time() + 365 * 24 * 60 * 60), '/'); //+8*3600
    @ setcookie('weathercity2', '', -(time() + 365 * 24 * 60 * 60), '/'); //+8*3600
    @unlink($tmp);
    $weather .= '天气预报获取失败！</a>[<a href="weather.php?err='.urlencode($weatherurl).'" target="_blank" style="color:blue;">去解决</a>]</span>';
  }
  return $weather;
}

endif;


//得到城市
function getCITY($str) {
  if (!empty($str)) {

    $str = preg_replace('/^.*(新疆|广西|内蒙古|宁夏|西藏)(.*自治区)?/', '', $str);
    $str = preg_replace('/^.*(台湾|广东|江苏|浙江|山东|福建|辽宁|黑龙江|河北|湖北|湖南|安徽|吉林|海南|四川|陕西|山西|河南|云南|甘肃|江西|青海|贵州)(省)?/', '', $str);
    //镇
    $str = preg_replace('/^.*(固|清|景德|北|丰|天)镇.*$/', '$1镇', $str);
    //区
    $str = preg_replace('/^.*(黄山风景|赫山|淮阴|呼市郊|尖草坪|小店)区.*$/', '$1区', $str);
    //县
    $str = preg_replace('/^(.*市)?(芜湖|遵义|承德|通化|上饶|本溪|辽阳|大同|宜宾|蓟|忠|开|和|泗|萧|黟|歙|泾|寿|沙|漳|岷|环|宁|成|文|康|礼|徽|梅|横|藤|容|盘|赵|唐|易|蠡|雄|蔚|滦|青|献|沧|景|威|任|涉|磁|邱|魏|滑|辉|郏|叶|息|新|杞|嵩|睢|温|浚|淇|范|陕|宾|郧|房|攸|澧|南|道|丰|沛|赣|义|建平|托|陵|费|曹|单|莒|冠|莘|盂|祁|沁|隰|吉|蒲|古|绛|夏|应|五台|代|临|兴|岚|户|乾|彬|富|佳|华|勉|洋|眉|凤|陇|耀|郫|荣|安|渠|达|泸|高|珙|理|茂|朗|索|云)县.*$/', '$2xian', $str);
    //县转回
    $str = preg_replace('/^(.*市)?(.+)县.*$/', '$2', $str);
    $str = preg_replace('/^(.+)xian$/', '$1县', $str);
    //盟
    $str = preg_replace('/^(.*市)?(阿拉善|西)盟.*$/', '$2盟', $str);
    //旗
    $str = preg_replace('/^(.*市)?(社|土左|土右|达茂|察右前|察右中|察右后|四子王|科左中|科左后|阿鲁|巴林左|巴林右|鄂前|杭锦|乌审|乌前|乌中|乌后|杭锦后|苏左|苏右|东乌|西乌|镶黄|正镶白|正兰|阿荣|鄂伦春|鄂温克|陈|新左|新右|科右中|阿左|阿右)旗.*$/', '$2旗', $str);
    //市
    $str = preg_replace('/^(.*市)?(.+)市.*$/', '$2', $str);
    $str = preg_replace('/^(沙|津)$/', '$1市', $str);

  }
  $city = (!empty($str) && !strstr($str,'本机地址') && !strstr($str,'局域网') && !strstr($str,'IANA保留地址')) ? $str : '北京';
  //@ setcookie('weathercity', '', -(time() + 365 * 24 * 60 * 60), '/'); //+8*3600
  //@ setcookie('weathercity', $city, time() + 365 * 24 * 60 * 60, '/'); //+8*3600
  //unset($str);
  return $city;
}

function getCITY2($city) {
  global $web;
  @ setcookie('weathercity2', '', -(time() + 365 * 24 * 60 * 60), '/'); //+8*3600
  if ($city_arr_file = file_get_contents($GLOBALS['WEATHER_DATA'].'readonly/weather/'.$web['weather_from'].'/getweather_seek.php')) {
    if (preg_match('/\''.preg_quote($city, '/').'\|([\w\-]+\|[A-Z]+)\'/', $city_arr_file, $m)) {
      return $m[1];
    } else {
      city_err_journal($city);
    }
  } else {
    city_err_journal($city);
  }
  return '';
}

if (!$city = $_GET['city']) {
  if (!$city = $_COOKIE['weathercity']) {
    require($GLOBALS['WEATHER_DATA'].'readonly/weather/getip.php');
    $myobj = new ipLocation();
    $ip = $myobj->getIP();
    $address = $myobj->getaddress($ip);
    $myobj = NULL;
    $city = getCITY(iconv("gbk", "utf-8", $address["area1"]));
    //$city = getCITY($address["area1"]);
  }
} else {
  $get = 1;
}

if (empty($city)) {
  $city = '北京';
}

if (!$city2 = $_GET['city2']) {
  if (isset($get)) {
    if (!$city2 = getCITY2($city)) {
      $city = '北京';
      $city2 = 'beijing|ABJ';
    }
  } else {
    if (!$city2 = $_COOKIE['weathercity2']) {
      if (!$city2 = getCITY2($city)) {
        $city = '北京';
        $city2 = 'beijing|ABJ';
     }
    }
  }
}

unset($get);

@ setcookie('weathercity', $city, time() + 365 * 24 * 60 * 60, '/'); //+8*3600
@ setcookie('weathercity2', $city2, time() + 365 * 24 * 60 * 60, '/'); //+8*3600









$weather = '';
$tmp = $GLOBALS['WEATHER_DATA'].'writable/__temp__/weather/'.$web['weather_from'].'/'.urlencode($city).''.$t.'.txt';
$time = time();
$filemtime = @file_exists($tmp) ? @filemtime($tmp) : 0;
/*
$time = time();
$pass = date('G') * 3600 + date('i') * 60 + date('s');
$time_0000 = $time - $pass;
$step_1710 = 17 * 3600 + 30 * 60;
$step_0810 = 8 * 3600 + 20 * 60;

if ($pass >= $step_1710) {
  if ($filemtime != 0 && $filemtime >= $time_0000 + $step_1710) {
    $weather = @file_get_contents($tmp);
  }
  //缓存到第二天08:10
  $diff_s = $step_0810 - $pass + 86400;
} else {
  if ($pass >= $step_0810) {
    if ($filemtime != 0 && $filemtime >= $time_0000 + $step_0810) {
      $weather = @file_get_contents($tmp);
    }
    //缓存到17:10 新浪17:00更新一次
    $diff_s = $step_1710 - $pass;
  } else {
    if ($filemtime != 0 && $filemtime >= $time_0000 + $step_1710 - 86400) {
      $weather = @file_get_contents($tmp);
    }
    //缓存到08:10 新浪8:00更新一次
    $diff_s = $step_0810 - $pass;
  }
}
*/

$step = (isset($web['weather_step']) && is_numeric($web['weather_step']) && $web['weather_step'] > 0) ? $web['weather_step'] * 3600 : 7200; //缓存2小时

//有效期截止时刻
$ekey = $filemtime - (gmdate('i', $filemtime + floatval($web['time_pos']) * 3600) * 60 + gmdate('s', $filemtime + floatval($web['time_pos']) * 3600)) + $step;
//下一个有效期截止时刻
$next = $time - (gmdate('i', $time + floatval($web['time_pos']) * 3600) * 60 + gmdate('s', $time + floatval($web['time_pos']) * 3600)) + $step;


if ($time >= $ekey) {
  $weather = getWEATHER($city, $city2);
  if ($GLOBALS['WEATHER_BORN'] == 1) {
    header("Cache-Control: max-age = ".($next - $time)."");
    $expires = gmdate("D, d M Y H:i:s", $next + floatval($web['time_pos']) * 3600).' GMT';
    header('Expires: '.$expires.'');
  }
} else {
  header("Cache-Control: max-age = ".($ekey - $time)."");
  $expires = gmdate("D, d M Y H:i:s", $ekey + floatval($web['time_pos']) * 3600).' GMT';
  header('Expires: '.$expires.'');
  //include($tmp);
  $weather = @file_get_contents($tmp);
}

//ob_end_flush();

echo $weather;





















?>