<?php
namespace Addons\Moments;

use Services\Service;

class Helper extends Service
{
    //获取域名
	public function get_http_server_name(){
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
		return  $http_type.$_SERVER['SERVER_NAME'];
	}
	
	/**
	 * 设置返回头
	 * @param $key
	 * @param $value
	 * @return array
	 */
	function set_header($key=null,$value=null){
		static $header=[];
		if($key)$header[$key]=$value;
		return $header;
	}
	
	/**
     * import css js image out of pub director
     * @param $path
     * @param bool $refresh
     * @return mixed|string
     */
    public function import($path){
        $ext = substr(strrchr($path, '.'), 1);
        $source_path= __DIR__.'/View/'.ltrim($path,'/\\');

        if(($ext == 'html'||$ext == 'php')&&is_file($source_path)){
            include($source_path);
            return;
        }
        if(  is_file($source_path)){
            $pub_son_path ="tempassets/".basename(__DIR__)."/".ltrim($path,'/\\');
            $publish_path=pub_path($pub_son_path);
            $param='';
            //文件如果被改变就重新发布
            if(!is_file($publish_path)|| filemtime($source_path) > filemtime($publish_path)){
                $this->set_header('X-Accel-Buffering','no'); // 刷新缓存
                $this->set_header("Expires","Mon, 26 Jul 1997 05:00:00 GMT");
                $this->set_header("Cache-Control","no-cache, must-revalidate");
                $this->set_header("Pragma: no-cache");
                is_dir(dirname($publish_path)) or mkdir(dirname($publish_path),0751,true);
                copy($source_path,$publish_path);

            }
            $param='?t='.time();
            $url=get_host($pub_son_path);
            if($ext == 'js'){
                return "<script src='{$url}{$param}'></script>";
            }elseif ($ext == 'css'){
                return '<link rel="stylesheet" type="text/css" href="'.$url.'" media="all" />';
            }else{
                return $url;
            }
        }

        return '';

    }
	
}
