<?php

namespace Api\PhpUtils\Ksy;
use Api\PhpUtils\Http\Request;

/**
 * 金山云ks3相关
 * 仅实现了签名及删除单个方法,其他未实现
 * ks3直接访问地址: https://ks3-cn-beijing.ksyun.com/article-yidian/article/0JRvMeHk
 */
class Ks3Util
{
    const KS3_BASE_URL = 'ks3-cn-beijing.ksyun.com';
    const FALLBACK_BUIDLER_BUCKET = 'article-yidian';
    const KS_DATE_SCHEME = 'D, d M Y H:i:s \G\M\T';
    const KSYUN_SK = "OMw7UAOkrLVsRevuP44ctAlfzriDzUm9+JvOFoYuiSoLgaLJWi+kjUa+4G3EWXFakQ==";
    const KSYUN_AK = "AKLTnATdoXUnR72IDSGgN2WSOQ";
    const YIDIAN_PROXY = true;

    //删除fallback builder 对于ks3节点的文章
    public static function delete_doc($docid, $timeout = 1000)
    {
        return self::delete(self::FALLBACK_BUIDLER_BUCKET, 'article/'.$docid, $timeout);
    }
    public static function put_object($data,$bucket,$object_key, $timeout = 1000)
    {
        $url = self::get_url($bucket).'/'.$object_key;
        $canonicalized_resource = self::get_canonicalized_resource($bucket, $object_key);
        $headers = array(
            'Host'            => self::get_url($bucket),
            'Date'            => gmdate(self::KS_DATE_SCHEME),
            'Content-Type'    => 'multipart/form-data',
            'Referer'         => $url,
            'x-kss-acl'       => 'public-read',
            //'Expect'          => '100-continue',
        );
        $headers['Authorization'] = self::sign('PUT', $canonicalized_resource, $headers);
        foreach ($headers as $key => $value)
        {
            $header[] = $key.':'.$value;
        }
        $request = new Request();
        $str = $request->uploadPut($url, $data, $timeout, 1, $header, self::YIDIAN_PROXY);
        return $str;
    }
    //查询文章在ks3是否存在,返回金山云返回的head http状态吗
    public static function exist($bucket, $object_key, $timeout = 1000)
    {
        $url = self::get_url($bucket).'/'.$object_key;
        $canonicalized_resource = self::get_canonicalized_resource($bucket, $object_key);
        $headers = array(
            'Host'            => self::get_url($bucket),
            'Date'            => gmdate(self::KS_DATE_SCHEME),
            'Content-Type'    => 'application/xml',
        );
        $headers['Authorization'] = self::sign('HEAD', $canonicalized_resource, $headers);
        foreach ($headers as $key => $value)
        {
            $header[] = $key.':'.$value;
        }
        $request = new Request();
        $str = $request->head($url, $timeout, 1, $header, self::YIDIAN_PROXY);
        return $str;
    }

    //删除ks3 节点指定bucket中的object
    private static function delete($bucket, $object_key, $timeout)
    {
        $url = self::get_url($bucket).'/'.$object_key;
        $headers = array(
            'Host'            => self::get_url($bucket),
            'Accept'          => '*/*',
            'Accept-Encoding' => 'deflate, gzip',
            'Referer'         => $url,
            'Content-Type'    => 'application/xml',
            'Date'            => gmdate(self::KS_DATE_SCHEME),
            'Content-Length'  => 0,
        );
        $canonicalized_resource = self::get_canonicalized_resource($bucket, $object_key);
        $headers['Authorization'] = self::sign('DELETE', $canonicalized_resource, $headers);

        foreach ($headers as $key => $value)
        {
            $header[] = $key.':'.$value;
        }
        $request = new Request();
        $str = $request->delete($url, $timeout, 1, $header, self::YIDIAN_PROXY);
        return $str;
    }

    private static function get_url($bucket)
    {
        return $bucket.'.'.self::KS3_BASE_URL;
    }
    private static function sign($method,$canonicalized_resource, $headers=array(), $query = array())
    {
        $canonicalized_kss_headers = self::format_headers($headers);
        $tosign = $method . "\n"
                . '' . "\n"
                . $headers['Content-Type'] . "\n"
                . $headers['Date'] . "\n"
                . $canonicalized_kss_headers
                . $canonicalized_resource;

        $signature = base64_encode(hash_hmac('sha1', $tosign, self::KSYUN_SK, true));
        $signature = 'KSS ' . self::KSYUN_AK . ':' . $signature;
        return $signature;
    }
    //生成签名所需CanonicalizedKssHeaders,详见https://ks3.ksyun.com/doc/api/index.html
    private static function format_headers(array $headers)
    {
        if( empty($headers) )
        {
            return '';
        }
        foreach ($headers as $key => $header) {
            if( substr($key,0,6) == 'x-kss-' )
            {
                $headers_to_sign[strtolower($key)] = $header;
            }
        }
        if( empty($headers_to_sign) )
        {
            return '';
        }
        ksort($headers_to_sign);
        $ret = '';
        foreach ($headers_to_sign as $key => $value)
        {
            $ret = $key.':'.$value."\n";
        }
        return $ret;
    }
    //
    private static function get_canonicalized_resource($bucket, $object_key)
    {
        return '/'.$bucket.'/'.$object_key;
    }
}
