<?php
//ob_start();
@ ini_set('display_errors', false);
@ error_reporting(E_ERROR | E_WARNING | E_PARSE);
@ header("content-type: text/html; charset=gb2312");


$GLOBALS['WEATHER_DATA'] = (basename(dirname($_SERVER['PHP_SELF'])) == 'weather' ? '../../' : './').'';
$GLOBALS['WEATHER_BORN'] = 0;

require ($GLOBALS['WEATHER_DATA'].'writable/set/set.php');
require ($GLOBALS['WEATHER_DATA'].'readonly/function/read_file.php');
require ($GLOBALS['WEATHER_DATA'].'readonly/function/write_file.php');

/*
if (isset($_GET['char']) && $_GET['char'] == 'utf-8') {
  $w = '"".iconv("gbk", "utf-8", $weather).""';
} else {
  $w = '"".$weather.""';
}
*/
if (isset($_GET['type']) && $_GET['type'] == 2) :

$t = '2';
//得到天气 完善的
function getWEATHER($city) {
  global $tmp;
  $weatherurl = 'http://php.weather.sina.com.cn/search.php?c=1&city='.$city.'&dpc=1';
  if ($W_FR = read_file($weatherurl)) {
    preg_match('/<\!--\s*右侧主内容\s*begin\s*-->(.*)<\!--\s*右侧主内容\s*end\s*-->/isU', $W_FR, $matches);
    unset($W_FR, $weatherurl);
    if (!empty($matches[1])) {
      $matches[1] = preg_replace('/<ul\s+class="list_01">.*<\/script>/isU', '</div></div>', $matches[1]);
	  $today = $matches[1];
    }
    unset($matches);
  }
  if (!empty($today)) {
    $weather = $today;
    write_file($tmp, $weather);
    return $weather;
  } else {
    //setcookie('weathercity', '', 0, '/');
    return '';
  }
}

else :

$t = '';
//得到天气 简单的
function getWEATHER($city) {
  global $tmp;
  $weatherurl = 'http://php.weather.sina.com.cn/search.php?c=1&city='.$city.'&dpc=1';
  $weather = '';
  if ($W_FR = read_file($weatherurl)) {
    $weather .= '<style>
.weather span, .weather #weather_show { vertical-align:middle; display:inline-block !important; display:inline; zoom:1; font-size:12px; line-height:180%; text-align:center; white-space:nowrap; }
#city_where, #w_today, #w_moday { }
#weather_city, #weather_where { display:block; }
#weather_city { font-weight:bold; }
a#weather_where { color:#BBB; }
.w_img { width:58px; height:40px; overflow:hidden; }
.w_img img { width:58px; height:58px; margin-top:-6px; }
</style>
<span class="weather">
  <span id="city_where">
    <a href="weather.php?type=2&city='.urlencode($city).'" id="weather_city">'.$city.'</a>
    <a href="weather.php?area=china" id="weather_where">[换城市]</a>
  </span>
  <a href="weather.php?type=2&city='.urlencode($city).'" id="weather_show">
';

    if (preg_match('/<h5>今天白天<\/h5>[\s\r\n]*<div title=\'([^\'\"\>]+)\' [^\>]+url\(([^\)]*)\).*<span class="fs_30 tpte">([\-\d]+℃)<\/span>.*<h5>今天夜间<\/h5>[\s\r\n]*<div title=\'([^\'\"\>]+)\' [^\>]+url\(([^\)]*)\).*<span class="fs_30 tpte">([\-\d]+℃)<\/span>/isU', $W_FR, $matches)) {
      $weather .= '<span id="w_today">';
	  $weather .= $today = '<span class="w_img"><img src="'.$matches[2].'" /></span><span>今天 '.$matches[1].'<br />'.$matches[3].'</span>';
      $weather .= '</span><span id="w_moday">';
	  $weather .= $night = '<span class="w_img"><img src="'.$matches[5].'" /></span><span>夜间 '.$matches[4].'<br />'.$matches[6].'</span>';
      $weather .= '</span><span title="未来详情" style="margin-left:10px;">》</span></a>
</span>';
      unset($matches);
	  $GLOBALS['WEATHER_BORN'] = 1;
      write_file($tmp, $weather);
	} else {
	  $GLOBALS['WEATHER_BORN'] = 0;
      $weather .= '天气预报获取失败！<br />请稍候再试</a>
</span>';
	}
    unset($W_FR);
  }
  return $weather;
}

endif;


//写文件
if (!function_exists('write_file')) {
  function write_file($file, $text) {
    global $web;
    eval('@chmod(dirname($tempo_dir), 0'.$web['chmod'].');');
    if (($fp = @fopen($file, 'wb+')) && @fwrite($fp, $text)) {
      @fclose($fp);
    } else {
      @file_put_contents($file, $text);
    }
  }
}

if (!function_exists('read_file')) {
  function read_file($url){
    $timeout = array(
      'http' => array(
          'timeout' => 3 //设置一个超时时间，单位为秒
      )
    );
    $ctx = stream_context_create($timeout);
    $r=@file_get_contents($url, 0, $ctx);
    if(!$r){
      $ch = curl_init();   
      curl_setopt($ch, CURLOPT_URL, $url);            //设置访问的url地址   
      //curl_setopt($ch,CURLOPT_HEADER,1);            //是否显示头部信息   
      curl_setopt($ch, CURLOPT_TIMEOUT, 3);           //设置超时   
      curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);   //用户访问代理 User-Agent   
      curl_setopt($ch, CURLOPT_REFERER,_REFERER_);        //设置 referer   
      curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);      //跟踪301   
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果   
      $r = curl_exec($ch);
      curl_close($ch);
    }
    return $r;
  }
}

//得到城市
function getCITY($str) {
  if (!empty($str)) {
    $str = preg_replace('/^.*(自治区|省)/', '', $str);
    $str = preg_replace('/^.*(台湾|广东|江苏|浙江|山东|福建|辽宁|黑龙江|河北|湖北|湖南|安徽|吉林|海南|四川|陕西|山西|河南|新疆|江西|广西|内蒙古|云南|甘肃|宁夏|青海|贵州|西藏)/', '', $str);
	$str = preg_replace('/(蓟|开|忠|黟|歙|芜湖|肖|宿|泗|和|泾|寿|滁|沙|宁|环|漳|岷|文|康|成|徽|礼|梅|横|容|藤|盘|赵|承德|唐|易|蠡|雄|滦|涉|魏|磁|丘|任|威|蔚|青|献|霸|景|密|嵩|杞|郏|叶|温|孟|淇|浚|滑|范|睢|宾|房|南|攸|炎陵|衡阳|邵阳|通化|丰|沛|南昌|上饶|义|本溪|辽阳|莒|陵|费|冠|惠民|曹|单|大同|盂|沁|应|祁|代|吉|蒲|古|隰|临|岚|兴|户|富|耀|陇|眉|凤|华|郫|安|荣|珙|高|宜宾|理|茂|泸|云|鄞)县/', '$1xian', $str);
	$str = preg_replace('/(固|玉门|西峰|清|景德|鹰潭|北|丰|天)镇/', '$1zhen', $str);
	$str = preg_replace('/(北道)区/', '$1qu', $str);
	$str = preg_replace('/(西)盟/', '$1meng', $str);
    $str = preg_replace('/(.+)市.*$/', '$1', $str);
	$str = preg_replace('/(.+)县.*$/', '$1', $str);
	$str = preg_replace('/(.+)镇.*$/', '$1', $str);
	$str = preg_replace('/(.+)区.*$/', '$1', $str);
	$str = preg_replace('/(.+)盟.*$/', '$1', $str);
	$str = str_replace('xian', '县', $str);
	$str = str_replace('zhen', '镇', $str);
	$str = str_replace('qu', '区', $str);
	$str = str_replace('meng', '盟', $str);
  }
  $city = (!empty($str) && !strstr($str,'本机地址') && !strstr($str,'局域网')) ? $str : '北京';
  setcookie('weathercity', $city, time() + 365 * 24 * 60 * 60, '/'); //+8*3600
  //unset($str);
  return $city;
}





if (!$city = $_GET['city']) {
  if (!$city = $_COOKIE['weathercity']) {
    require('getip.php');
    $myobj = new ipLocation();
    $ip = $myobj->getIP();
    $address = $myobj->getaddress($ip);
    $myobj = NULL;
    $city = getCITY($address["area1"]);
  }
} else {
  @ setcookie('weathercity', $city, time() + 365 * 24 * 60 * 60, '/'); //+8*3600
}

$weather = '';
$tmp = $GLOBALS['WEATHER_DATA'].'writable/__temp__/weather_'.urlencode($city).''.$t.'.txt';
$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 = 7200; //缓存2小时
$time = time();

//有效期截止时刻
$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);
  if ($GLOBALS['WEATHER_BORN'] == 1) {
    header("Cache-Control: max-age = ".($next - $time)."");
  }
} else {
  header("Cache-Control: max-age = ".($ekey - $time)."");
  //include($tmp);
  $weather = @file_get_contents($tmp);
}

//ob_end_flush();
echo $weather;

//echo eval('return '.$w.';');




















?>