<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST, ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace temmoku\lib;
use temmoku\lib\gd;
class images_get_down{

	public function get_img_url($content,$match){
		
		
        if(is_array($match)){
        	$pattern="/src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]|(?:\?.*?)))[\'|\"]/";
        	return  preg_replace_callback ($pattern,"self::img_replace",$content );
        }
		return $content;
		
	}
	
	public function img_replace($match){
		
		$imgUrl=$match[1];
		defined('M_MODULE' ) && $dir_name=M_MODULE;
		defined('P_MODULE' ) && $dir_name=P_MODULE;
		
		if (stripos($imgUrl, WEBURL)===0 && stripos($imgUrl, WEBURL.'/'.C('upfiles_Catalog')) !==0 ) {
			return "src=\"$imgUrl\"";
		}
		
		if (stripos($imgUrl, C('WEBURL'))) {
			$imgUrl=str_replace  ( WEBURL.'/'.C('upfiles_Catalog')  , '' ,  $imgUrl);
			$imgUrl=UploadFiles_MOVE(trim($imgUrl,"/"),$dir_name);
			$img='"'.WEBURL.'/'.C('upfiles_Catalog').'/'.$imgUrl.'"';
            return "src=$img";
      	}
		if(C('ArticleDirclass')){
    		$After = str_replace(".","",strtolower(strrchr($imgUrl,".")));
			$After =preg_replace ( "/(?:\?(.*))/" ,'' , $After );
    	}
		//http开头验证
        if (stripos($imgUrl, "http") !== 0) {
             return "src=\"$imgUrl\"";
        }

        preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
        $host_with_protocol = count($matches) > 1 ? $matches[1] : '';
		
        // 判断是否是合法 url
        if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
           return "src=\"$imgUrl\"";
        }

        preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
        $host_without_protocol = count($matches) > 1 ? $matches[1] : '';

        // 此时提取出来的可能是 ip 也有可能是域名，先获取 ip
        $ip = gethostbyname($host_without_protocol);
        // 判断是否是私有 ip
        if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
            return "src=\"$imgUrl\"";
        }

        //获取请求头并检测死链
        $heads = get_headers($imgUrl, 1);
        if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
            return "src=\"$imgUrl\"";
        }
        //格式验证(扩展名验证和Content-Type验证)
        $fileType = strtolower(strrchr($imgUrl, '.'));
        if ( !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
            return "src=\"$imgUrl\"";
        }
        //打开输出缓冲区并获取远程图片
        ob_start();
        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false // don't follow redirects
            ))
        );
        readfile($imgUrl, false, $context);
        $img = ob_get_contents();
        ob_end_clean();
        
        $ImgName = date("Ymdhis").rand(1000,9999).".".$After;
		if(C('ArticleTimeDir')){
			$TIME=date(C('ArticleTimeDir'),time());
		}
        $newfile=C('upfiles_Catalog').'/'.$dir_name.'/'.$After."/".$TIME.$ImgName;
        $newfile=Temmoku_PATH.$newfile;
    	$url=$After."/".$TIME.$ImgName;
		write_dir($newfile,'1');
        //移动文件
        if (!(file_put_contents($newfile, $img) && file_exists($newfile))) { //移动失败
            exit("ERROR_WRITE_CONTENT");
        } else { //移动成功
        	//这是文字水印
			if('1'==C('gd_water')){
				$imgurl=(new Gd($newfile))->water_images();
			}elseif('2'==C('gd_water')){
				$imgurl=(new Gd($newfile))->water_text();
			}else{
				$imgurl=$dir_name.'/'.$url;
			}
			$img='WWW_TEMMOKU_CN'.'/'.$imgurl;
            return "src=\"$img\"";
        }
	}

}
?>