<?php

/* ========================================================================
 * $Id: ip.php 2012 2018-10-21 10:29:04Z onez $
 * 
 * Email: www@onez.cn
 * QQ: 6200103
 * HomePage: http://www.onezphp.com
 * ========================================================================
 * Copyright 2016-2017 佳蓝科技.
 * 
 * ======================================================================== */

!defined('IN_ONEZ') && exit('Access Denied');
class onezphp_ip extends onezphp{
  var $taobao_times=0;
  function __construct(){
    
  }
  function init($ip){
    $this->ip=$ip;
    return $this;
  }
  function address($full=0){
    $ip=$this->ip;
    if($full &&strpos($full,'.')!==false){
      $ip=$full;
    }
    !$ip && $ip=onez()->ip();
    #$address=$this->taobao($ip,$full?1:0);
    if(!$address){
      include_once(dirname(__FILE__)."/lib/ip.class.php");
      $p=new IpLocation();
      $l=$p->getlocation($ip);
      //print_r($l);
      $address=$l['country'];
      $full && $address.=$l['area'];
    }
    
    return $address;
  }
  function taobao($ip,$full=0){
    if($this->get('noapi')){
      return false;
    }
    $cacheFile=ONEZ_CACHE_PATH.'/plugins/ip/address.dat';
    if(file_exists($cacheFile)){
      $data=onez()->read($cacheFile);
      if(strpos($data,"$ip\t")!==false){
        list(,$address)=explode("$ip\t",$data);
        list($address)=explode("\n",$address);
        if($full){
          list($address)=explode("\t",$address);
        }else{
          list(,$address)=explode("\t",$address);
        }
        return $address;
      }
    }
    if($this->taobao_times>=10){
      return false;
    }
    $this->taobao_times++;
    $r=onez()->post('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
    $json=json_decode($r,1);
    if($json['code']==0){
      $all=$mini=array();
      
      $all[]=$json['data']['country'];
      #$all[]=$json['data']['area'];
      $all[]=$json['data']['region'];
      $all[]=$json['data']['city'];
      $all[]=$json['data']['county'];
      $all[]=$json['data']['isp'];
      
      $mini[]=$json['data']['region'];
      $mini[]=$json['data']['city'];
      $mini[]=$json['data']['county'];
      $mini[]=$json['data']['isp'];
      
      $all=implode('',$all);
      $mini=implode('',$mini);
      onez()->write($cacheFile,"$ip\t$all\t$mini\n",'a+');
      
      return $full?$all:$mini;
    }
    return false;
  }
}