WordPress与七牛的一些整合

七牛云存储

  由于在更新一些样式文件的时候需要同步更新七牛的一些资源,但又有个小小的问题,去七牛删文件实在太麻烦了,每次登陆什么的要弄好一会,所以就整合了一些相关数据,在版本有更新的时候直接去远程删除文件,这样就方便多了。

  这样只有在主题文件中加入check_resource_version()就可行了,当然如果数据多了还是略有不便,待改进吧。

/**
 * 检查CDN版本资源信息,依据其来更新外部资源
 */

function check_resource_version(){
    $options = unserialize(get_option('cdn_resource_version'));
    if($options === false || !is_array($options) || !isset($options['js']) || !isset($options['css'])){
        $options = ['js' => '', 'css' => ''];
    }
    $now_options = ['js' => CDN_VERSION_JS, 'css' => CDN_VERSION_CSS];
    $qiniu = new QiniuAct("cdn");
    foreach(['js', 'css'] as $v){
        if($options[$v] !== $now_options[$v]){
            switch($v){
                case 'js':
                    //update js
                    $qiniu->delete_file('wp-content/themes/twoheart/js/functions.js');
                    break;
                case 'css':
                    //update css
                    $qiniu->delete_file('wp-content/themes/twoheart/style.css');
                    break;
            }
        }
    }
    update_option('cdn_resource_version', serialize($now_options));
}

  单单这样一段代码肯定不行,还要用到七牛的API,不得不说api不怎么好用,下面这个简单的实现了下,完全照抄官方代码。

<?php
/**
 * 七牛操作对象类
 * Class QiniuAct
 */

class QiniuAct{
    const IO_HOST = 'http://iovip.qbox.me';            // 七牛源站Host
    const RS_HOST = 'http://rs.qbox.me';               // 文件元信息管理操作Host
    const RSF_HOST = 'http://rsf.qbox.me';              // 列举操作Host
    const API_HOST = 'http://api.qiniu.com';            // 数据处理操作Host
    /**
     * @var array 所有的空间信息
     */

    private $zone_map = array(
        'cdn' => array('bucket' => 'loveyu-cdn'));

    /**
     * @var array 当前的空间信息
     */

    private $zone;

    /**
     * @var string 访问秘钥
     */

    private $accessKey = "[You accessKey]";

    /**
     * @var string 加密秘钥
     */

    private $secretKey = "[You secretKey]";

    /**
     * @var string 错误数据
     */

    private $error;


    /**
     * QiniuAct constructor.
     * @param string $zone
     * @throws Exception
     */

    public function __construct($zone){
        if(isset($this->zone_map[$zone])){
            $this->zone = $this->zone_map[$zone];
        } else{
            throw new Exception("No found zone config.");
        }
    }

    /**
     * 删除一个文件
     * @param string $path
     * @return bool
     */

    public function delete_file($path){
        $path = '/delete/' . $this->entry($this->zone['bucket'], $path);
        $rt = $this->post(self::RS_HOST . $path, NULL, $code);
        if($code == 200){
            return true;
        } else{
            return false;
        }
    }

    /**
     * 发送POST请求
     * @param string      $path
     * @param string|null $body
     * @param string      $code
     * @return array
     */

    private function post($path, $body = NULL, &$code){
        $header = $this->authorization($path, $body, 'application/x-www-form-urlencoded');
        $ch = curl_init();
        $options = array(
            CURLOPT_USERAGENT => "Qiniu API From Wordpress",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HEADER => true,
            CURLOPT_NOBODY => false,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_URL => $path);
        if(!empty($header)){
            $headers = array();
            foreach($header as $key => $val){
                array_push($headers, "$key: $val");
            }
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        if(!empty($body)){
            $options[CURLOPT_POSTFIELDS] = $body;
        }
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        $ret = curl_errno($ch);
        if($ret !== 0){
            $this->setError(curl_error($ch));
            curl_close($ch);
            return false;
        }
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($result, $header_size);
        curl_close($ch);
        return $body;
    }


    /**
     * 生成加密验证头部
     * @param string      $url
     * @param null|string $body
     * @param null|string $contentType
     * @return array
     */

    private function authorization($url, $body = NULL, $contentType = NULL){
        $url = parse_url($url);
        $data = '';
        if(isset($url['path'])){
            $data = $url['path'];
        }
        if(isset($url['query'])){
            $data .= '?' . $url['query'];
        }
        $data .= "\n";
        if($body != NULL && ($contentType == 'application/x-www-form-urlencoded') || $contentType == 'application/json'){
            $data .= $body;
        }
        $h_mac = hash_hmac('sha1', $data, $this->secretKey, true);
        $authorization = $this->accessKey . ':' . $this->base64_urlSafeEncode($h_mac);
        return array('Authorization' => 'QBox ' . $authorization);
    }

    /**
     * 计算七牛API中的数据格式
     * @param string $bucket 待操作的空间名
     * @param string $key    待操作的文件名
     * @return string 符合七牛API规格的数据格式
     * @link http://developer.qiniu.com/docs/v6/api/reference/data-formats.html
     */

    public function entry($bucket, $key){
        $en = $bucket;
        if(!empty($key)){
            $en = $bucket . ':' . $key;
        }
        return $this->base64_urlSafeEncode($en);
    }

    /**
     * 对提供的urlsafe的base64编码的数据进行解码
     * @param string $str 待解码的数据,一般为字符串
     * @return string 解码后的字符串
     */

    public function base64_urlSafeDecode($str){
        $find = array('-', '_');
        $replace = array('+', '/');
        return base64_decode(str_replace($find, $replace, $str));
    }

    /**
     * 对提供的数据进行urlsafe的base64编码。
     * @param string $data 待编码的数据,一般为字符串
     * @return string 编码后的字符串
     * @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64
     */

    public function base64_urlSafeEncode($data){
        $find = array('+', '/');
        $replace = array('-', '_');
        return str_replace($find, $replace, base64_encode($data));
    }

    /**
     * @return string
     */

    public function getError(){
        return $this->error;
    }

    /**
     * @param string $error
     */

    private function setError($error){
        $this->error = $error;
    }
}

8条评论在“WordPress与七牛的一些整合”

    1. 话虽然如此,但偶尔整些东西丰富下生活乐趣也是可以的。不过博客速度有些慢,这样还是不错的

        1. 没用过此类主题,你具体的问题我也不清楚,建议在七牛中开个镜像源比较好,本地和七牛存两份,这样比较保险。修改下地址就好了,绝对不会出现所谓的错位问题。

回复 明月登楼   取消