diff --git a/addons/address/config.php b/addons/address/config.php index 208286b..242ccbd 100644 --- a/addons/address/config.php +++ b/addons/address/config.php @@ -9,8 +9,9 @@ return [ 'baidu' => '百度地图', 'amap' => '高德地图', 'tencent' => '腾讯地图', + 'tianditu' => '天地图', ], - 'value' => 'tencent', + 'value' => 'tianditu', 'rule' => 'required', 'msg' => '', 'tip' => '', @@ -101,6 +102,30 @@ return [ 'ok' => '', 'extend' => '', ], + [ + 'name' => 'tianditukey', + 'title' => '天地图服务端Key', + 'type' => 'string', + 'content' => [], + 'value' => '55aee666be14cd0100874d6faf3c963c', + 'rule' => '', + 'msg' => '', + 'tip' => '服务端逆地理编码用的密钥,在 lbs.tianditu.gov.cn 申请', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'tiandituwebkey', + 'title' => '天地图Web端Key', + 'type' => 'string', + 'content' => [], + 'value' => 'a13cdd845c9e92ebc17f6c76ecab49f6', + 'rule' => '', + 'msg' => '', + 'tip' => '网页端地图JS API用的密钥,在 lbs.tianditu.gov.cn 申请', + 'ok' => '', + 'extend' => '', + ], [ 'name' => 'coordtype', 'title' => '坐标系类型', diff --git a/addons/address/view/index/tianditu.html b/addons/address/view/index/tianditu.html new file mode 100644 index 0000000..a156150 --- /dev/null +++ b/addons/address/view/index/tianditu.html @@ -0,0 +1,530 @@ + + + + + 地址选择器 + + + + + + +
直接点击地图任意位置或拖动红标即可选点
+
+
+
点击地图选择位置...
+
坐标:--
+
+ +
+
+ + + + + + + + + + diff --git a/addons/alioss/.addonrc b/addons/alioss/.addonrc new file mode 100644 index 0000000..cc64de5 --- /dev/null +++ b/addons/alioss/.addonrc @@ -0,0 +1 @@ +{"files":["public\\assets\\addons\\alioss\\js\\spark.js"],"license":"regular","licenseto":"26425","licensekey":"65aeJ0OxSqWPyHTn 09+R8Mbu97S1xGLocBmU0g==","domains":["fenleixinxi"],"licensecodes":[],"validations":["bd9cd2ccafa213b7a49c36d1a5919d55"]} \ No newline at end of file diff --git a/addons/alioss/Alioss.php b/addons/alioss/Alioss.php new file mode 100644 index 0000000..e503c61 --- /dev/null +++ b/addons/alioss/Alioss.php @@ -0,0 +1,124 @@ +getConfig(); + $module = strtolower($request->module()); + // 判断api/common/upload 是否使用云存储上传 + if ($module == 'api' && ($config['apiupload'] ?? 0) && + strtolower($request->controller()) == 'common' && + strtolower($request->action()) == 'upload') { + request()->param('isApi', true); + App::invokeMethod(["\\addons\\alioss\\controller\\Index", "upload"], ['isApi' => true]); + } + } + + /** + * 加载配置 + */ + public function uploadConfigInit(&$upload) + { + $config = $this->getConfig(); + + $data = ['deadline' => time() + $config['expire']]; + $signature = hash_hmac('sha1', json_encode($data), $config['accessKeySecret'], true); + + $token = ''; + if (Auth::isModuleAllow()) { + $token = $config['accessKeyId'] . ':' . base64_encode($signature) . ':' . base64_encode(json_encode($data)); + } + $multipart = [ + 'aliosstoken' => $token + ]; + $config['uploadurl'] = 'https://' . $config['bucket'] . '.' . $config['endpoint']; + $upload = array_merge($upload, [ + 'cdnurl' => $config['cdnurl'], + 'uploadurl' => $config['uploadmode'] == 'client' ? $config['uploadurl'] : addon_url('alioss/index/upload', [], false, true), + 'uploadmode' => $config['uploadmode'], + 'bucket' => $config['bucket'], + 'maxsize' => $config['maxsize'], + 'mimetype' => $config['mimetype'], + 'savekey' => $config['savekey'], + 'chunking' => (bool)($config['chunking'] ?? $upload['chunking']), + 'chunksize' => (int)($config['chunksize'] ?? $upload['chunksize']), + 'multipart' => $multipart, + 'storage' => $this->getName(), + 'multiple' => (bool)$config['multiple'], + ]); + } + + /** + * 附件删除后 + */ + public function uploadDelete($attachment) + { + $config = $this->getConfig(); + if ($attachment['storage'] == 'alioss' && isset($config['syncdelete']) && $config['syncdelete']) { + // 删除云存储端文件 + try { + $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']); + $ossClient->deleteObject($config['bucket'], ltrim($attachment->url, '/')); + } catch (OssException $e) { + return false; + } + + //如果是服务端中转,还需要删除本地文件 + //if ($config['uploadmode'] == 'server') { + // $filePath = ROOT_PATH . 'public' . str_replace('/', DS, $attachment->url); + // if ($filePath) { + // @unlink($filePath); + // } + //} + } + return true; + } + +} diff --git a/addons/alioss/bootstrap.js b/addons/alioss/bootstrap.js new file mode 100644 index 0000000..d212ec9 --- /dev/null +++ b/addons/alioss/bootstrap.js @@ -0,0 +1,247 @@ +if (typeof Config.upload.storage !== 'undefined' && Config.upload.storage === 'alioss') { + require(['upload'], function (Upload) { + //获取文件MD5值 + var getFileMd5 = function (file, cb) { + //如果savekey中未检测到md5,则无需获取文件md5,直接返回upload的uuid + if (!Config.upload.savekey.match(/\{(file)?md5\}/)) { + cb && cb(file.upload.uuid); + return; + } + require(['../addons/alioss/js/spark'], function (SparkMD5) { + var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice, + chunkSize = 10 * 1024 * 1024, + chunks = Math.ceil(file.size / chunkSize), + currentChunk = 0, + spark = new SparkMD5.ArrayBuffer(), + fileReader = new FileReader(); + + fileReader.onload = function (e) { + spark.append(e.target.result); + currentChunk++; + if (currentChunk < chunks) { + loadNext(); + } else { + cb && cb(spark.end()); + } + }; + + fileReader.onerror = function () { + console.warn('文件读取错误'); + }; + + function loadNext() { + var start = currentChunk * chunkSize, + end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize; + + fileReader.readAsArrayBuffer(blobSlice.call(file, start, end)); + } + + loadNext(); + + }); + }; + + var _onInit = Upload.events.onInit; + //初始化中完成判断 + Upload.events.onInit = function () { + _onInit.apply(this, Array.prototype.slice.apply(arguments)); + //如果上传接口不是阿里OSS,则不处理 + if (this.options.url !== Config.upload.uploadurl) { + return; + } + $.extend(this.options, { + //关闭自动处理队列功能 + autoQueue: false, + params: function (files, xhr, chunk) { + var params = Config.upload.multipart; + if (chunk) { + return $.extend({}, params, { + filesize: chunk.file.size, + filename: chunk.file.name, + chunkid: chunk.file.upload.uuid, + chunkindex: chunk.index, + chunkcount: chunk.file.upload.totalChunkCount, + chunksize: this.options.chunkSize, + chunkfilesize: chunk.dataBlock.data.size, + width: chunk.file.width || 0, + height: chunk.file.height || 0, + type: chunk.file.type, + uploadId: chunk.file.uploadId, + key: chunk.file.key, + }); + } else { + params = $.extend({}, params, files[0].params); + params.category = files[0].category || ''; + } + return params; + }, + chunkSuccess: function (chunk, file, response) { + var etag = chunk.xhr.getResponseHeader("ETag").replace(/(^")|("$)/g, ''); + file.etags = file.etags ? file.etags : []; + file.etags[chunk.index] = etag; + }, + chunksUploaded: function (file, done) { + var that = this; + Fast.api.ajax({ + url: "/addons/alioss/index/upload", + data: { + action: 'merge', + filesize: file.size, + filename: file.name, + chunkid: file.upload.uuid, + chunkcount: file.upload.totalChunkCount, + md5: file.md5, + key: file.key, + uploadId: file.uploadId, + etags: file.etags, + category: file.category || '', + aliosstoken: Config.upload.multipart.aliosstoken, + }, + }, function (data, ret) { + done(JSON.stringify(ret)); + return false; + }, function (data, ret) { + file.accepted = false; + that._errorProcessing([file], ret.msg); + return false; + }); + + }, + }); + + var _success = this.options.success; + //先移除已有的事件 + this.off("success", _success).on("success", function (file, response) { + var that = this; + var ret = {code: 0, msg: response}; + try { + if (response) { + ret = typeof response === 'string' ? JSON.parse(response) : response; + } + if (file.xhr.status === 200) { + if (Config.upload.uploadmode === 'client') { + var url = '/' + file.key; + ret = {code: 1, msg: '', data: {url: url, fullurl: Fast.api.cdnurl(url, true), filename: file.name, filesize: file.size, mimetype: file.type, category: file.category || ''}}; + Fast.api.ajax({ + url: "/addons/alioss/index/notify", + data: {name: file.name, url: url, md5: file.md5, size: file.size, width: file.width || 0, height: file.height || 0, type: file.type, category: file.category || '', aliosstoken: Config.upload.multipart.aliosstoken} + }, function (data, notifyRet) { + // 如果notify有返回则使用notify返回 + _success.call(that, file, data ? notifyRet : ret); + return false; + }, function (data, ret) { + Toastr.error("发生错误:" + (ret.msg || "未知错误")); + return false; + }); + } else { + _success.call(that, file, ret); + } + } else { + console.error(file.xhr); + Toastr.error("发生未知错误"); + } + } catch (e) { + console.error(e); + Toastr.error("发生未知错误"); + } + }); + + this.on("addedfile", function (file) { + var that = this; + setTimeout(function () { + if (file.status === 'error') { + return; + } + getFileMd5(file, function (md5) { + var chunk = that.options.chunking && file.size > that.options.chunkSize ? 1 : 0; + var params = $(that.element).data("params") || {}; + var category = typeof params.category !== 'undefined' ? params.category : ($(that.element).data("category") || ''); + category = typeof category === 'function' ? category.call(that, file) : category; + Fast.api.ajax({ + url: "/addons/alioss/index/params", + data: {method: 'POST', category: category, md5: md5, name: file.name, type: file.type, size: file.size, chunk: chunk, chunksize: that.options.chunkSize, aliosstoken: Config.upload.multipart.aliosstoken}, + }, function (data) { + file.md5 = md5; + file.id = data.id; + file.key = data.key; + file.date = data.date; + file.uploadId = data.uploadId; + file.policy = data.policy; + file.signature = data.signature; + file.partsAuthorization = data.partsAuthorization; + file.params = data; + file.category = category; + + if (file.status != 'error') { + //开始上传 + that.enqueueFile(file); + } else { + that.removeFile(file); + } + return false; + }, function () { + that.removeFile(file); + }); + }); + }, 0); + }); + + if (Config.upload.uploadmode === 'client') { + var _method = this.options.method; + var _url = this.options.url; + this.options.method = function (files) { + if (files[0].upload.chunked) { + var chunk = null; + files[0].upload.chunks.forEach(function (item) { + if (item.status === 'uploading') { + chunk = item; + } + }); + if (!chunk) { + return "POST"; + } else { + return "PUT"; + } + } + return _method; + }; + this.options.url = function (files) { + if (files[0].upload.chunked) { + var chunk = null; + files[0].upload.chunks.forEach(function (item) { + if (item.status === 'uploading') { + chunk = item; + } + }); + var index = chunk.dataBlock.chunkIndex; + // debugger; + this.options.headers = {"Authorization": "OSS " + files[0]['id'] + ":" + files[0]['partsAuthorization'][index], "x-oss-date": files[0]['date']}; + if (!chunk) { + return Config.upload.uploadurl + "/" + files[0].key + "?uploadId=" + files[0].uploadId; + } else { + return Config.upload.uploadurl + "/" + files[0].key + "?partNumber=" + (index + 1) + "&uploadId=" + files[0].uploadId; + } + } + return _url; + }; + this.on("sending", function (file, xhr, formData) { + var that = this; + if (file.upload.chunked) { + var _send = xhr.send; + xhr.send = function () { + var chunk = null; + file.upload.chunks.forEach(function (item) { + if (item.status == 'uploading') { + chunk = item; + } + }); + if (chunk) { + _send.call(xhr, chunk.dataBlock.data); + } + }; + } + }); + } + }; + }); +} diff --git a/addons/alioss/config.php b/addons/alioss/config.php new file mode 100644 index 0000000..55ae4a2 --- /dev/null +++ b/addons/alioss/config.php @@ -0,0 +1,233 @@ + 'accessKeyId', + 'title' => 'AccessKey ID', + 'type' => 'string', + 'content' => [], + 'value' => 'LTAI5t7S47cwfaK1vo87VxCZ', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'accessKeySecret', + 'title' => 'AccessKey Secret', + 'type' => 'string', + 'content' => [], + 'value' => 'LJzowSI57d0NvmnL40d5df3TZJVRNh', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'bucket', + 'title' => 'Bucket名称', + 'type' => 'string', + 'content' => [], + 'value' => 'tjxc-xinxi', + 'rule' => 'required;bucket', + 'msg' => '', + 'tip' => '阿里云OSS的空间名', + 'ok' => '', + 'extend' => 'data-rule-bucket="[/^[0-9a-z_\-]{3,63}$/, \'请输入正确的Bucket名称\']"', + ], + [ + 'name' => 'endpoint', + 'title' => 'Endpoint', + 'type' => 'string', + 'content' => [], + 'value' => 'oss-cn-shenzhen.aliyuncs.com', + 'rule' => 'required;endpoint', + 'msg' => '', + 'tip' => '请填写从阿里云存储获取的Endpoint', + 'ok' => '', + 'extend' => 'data-rule-endpoint="[/^(?!http(s)?:\/\/).*$/, \'不能以http(s)://开头\']"', + ], + [ + 'name' => 'cdnurl', + 'title' => 'CDN地址', + 'type' => 'string', + 'content' => [], + 'value' => 'https://tjxc-xinxi.oss-cn-shenzhen.aliyuncs.com', + 'rule' => 'required;cdnurl', + 'msg' => '', + 'tip' => '请填写CDN地址,必须以http(s)://开头', + 'ok' => '', + 'extend' => 'data-rule-cdnurl="[/^http(s)?:\/\/.*$/, \'必需以http(s)://开头\']"', + ], + [ + 'name' => 'uploadmode', + 'title' => '上传模式', + 'type' => 'select', + 'content' => [ + 'client' => '客户端直传(速度快,无备份)', + 'server' => '服务器中转(占用服务器带宽,可备份)', + ], + 'value' => 'server', + 'rule' => '', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'serverbackup', + 'title' => '服务器中转模式备份', + 'type' => 'radio', + 'content' => [ + 1 => '备份(附件管理将产生2条记录)', + 0 => '不备份', + ], + 'value' => '0', + 'rule' => '', + 'msg' => '', + 'tip' => '服务器中转模式下是否备份文件', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'savekey', + 'title' => '保存文件名', + 'type' => 'string', + 'content' => [], + 'value' => '/uploads/{year}{mon}{day}/{filemd5}{.suffix}', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'expire', + 'title' => '上传有效时长', + 'type' => 'string', + 'content' => [], + 'value' => '600', + 'rule' => 'required', + 'msg' => '', + 'tip' => '用户停留页面上传有效时长,单位秒', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'maxsize', + 'title' => '最大可上传', + 'type' => 'string', + 'content' => [], + 'value' => '10M', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'mimetype', + 'title' => '可上传后缀格式', + 'type' => 'string', + 'content' => [], + 'value' => 'jpg,png,bmp,jpeg,gif,zip,rar', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'multiple', + 'title' => '多文件上传', + 'type' => 'bool', + 'content' => [], + 'value' => '0', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'thumbstyle', + 'title' => '缩略图样式', + 'type' => 'string', + 'content' => [], + 'value' => '', + 'rule' => '', + 'msg' => '', + 'tip' => '用于后台列表缩略图样式,可使用:?x-oss-process=image/resize,m_lfit,w_120,h_90', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'chunking', + 'title' => '分片上传', + 'type' => 'radio', + 'content' => [ + 1 => '开启', + 0 => '关闭', + ], + 'value' => '0', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'chunksize', + 'title' => '分片大小', + 'type' => 'number', + 'content' => [], + 'value' => '4194304', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'syncdelete', + 'title' => '附件删除时是否同步删除云存储文件', + 'type' => 'bool', + 'content' => [], + 'value' => '1', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'apiupload', + 'title' => 'API接口使用云存储', + 'type' => 'bool', + 'content' => [], + 'value' => '0', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], + [ + 'name' => 'noneedlogin', + 'title' => '免登录上传', + 'type' => 'checkbox', + 'content' => [ + 'api' => 'API', + 'index' => '前台', + 'admin' => '后台', + ], + 'value' => '', + 'rule' => '', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ], +]; diff --git a/addons/alioss/controller/Index.php b/addons/alioss/controller/Index.php new file mode 100644 index 0000000..3a2fbf2 --- /dev/null +++ b/addons/alioss/controller/Index.php @@ -0,0 +1,312 @@ +error("当前插件暂无前台页面"); + } + + /** + * 获取签名 + */ + public function params() + { + $this->check(); + + $config = get_addon_config('alioss'); + $name = $this->request->post('name'); + $md5 = $this->request->post('md5'); + $chunk = $this->request->post('chunk'); + $name = xss_clean($name); + + // 检查文件后缀 + $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); + $allowedExtensions = explode(',', strtolower($config['mimetype'])); + if (!in_array($extension, $allowedExtensions) || in_array($extension, ['php', 'html', 'htm', 'phar', 'phtml']) || preg_match("/^php(.*)/i", $extension)) { + $this->error('不允许的文件类型'); + } + + $auth = new \addons\alioss\library\Auth(); + $params = $auth->params($name, $md5); + $params['OSSAccessKeyId'] = $params['id']; + $params['success_action_status'] = 200; + $config = get_addon_config('alioss'); + + if ($chunk) { + $options = [ + 'accessKeyId' => $config['accessKeyId'], + 'endpoint' => $config['endpoint'], + 'bucket' => $config['bucket'], + 'region' => str_replace('-internal', '', substr(explode('.', $config['endpoint'])[0], 4)), + 'provider' => new StaticCredentialsProvider($config['accessKeyId'], $config['accessKeySecret']), + 'signatureVersion' => OssClient::OSS_SIGNATURE_VERSION_V4 + ]; + $oss = new OssClient($options); + + // 初始化 + $fileSize = $this->request->post('size'); + $chunkSize = $this->request->post('chunksize'); + $uploadId = $oss->initiateMultipartUpload($config['bucket'], $params['key']); + $params['uploadId'] = $uploadId; + $params['parts'] = $oss->generateMultiuploadParts($fileSize, $chunkSize); + $params['partsAuthorization'] = []; + $date = gmdate('D, d M Y H:i:s \G\M\T'); + foreach ($params['parts'] as $index => $part) { + $partNumber = $index + 1; + $signstr = "PUT\n\n\n{$date}\nx-oss-date:{$date}\n/{$config['bucket']}/{$params['key']}?partNumber={$partNumber}&uploadId={$uploadId}"; + $authorization = base64_encode(hash_hmac('sha1', $signstr, $config['accessKeySecret'], true)); + $params['partsAuthorization'][$index] = $authorization; + } + $params['date'] = $date; + } + + $this->success('', null, $params); + } + + /** + * 服务器中转上传文件 + * 上传分片 + * 合并分片 + * @param bool $isApi + */ + public function upload($isApi = false) + { + $config = get_addon_config('alioss'); + if ($isApi === true) { + if (!Auth::isModuleAllow()) { + $this->error("请登录后再进行操作"); + } + } else { + $this->check(); + } + $options = [ + 'accessKeyId' => $config['accessKeyId'], + 'endpoint' => $config['endpoint'], + 'bucket' => $config['bucket'], + 'region' => str_replace('-internal', '', substr(explode('.', $config['endpoint'])[0], 4)), + 'provider' => new StaticCredentialsProvider($config['accessKeyId'], $config['accessKeySecret']), + 'signatureVersion' => OssClient::OSS_SIGNATURE_VERSION_V4 + ]; + $oss = new OssClient($options); + + //检测删除文件或附件 + $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) { + //如果设定为不备份则删除文件和记录 或 强制删除 + if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) { + if ($attachment && !empty($attachment['id'])) { + $attachment->delete(); + } + if ($upload) { + //文件绝对路径 + $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname(); + @unlink($filePath); + } + } + }; + + $chunkid = $this->request->post("chunkid"); + if ($chunkid) { + $action = $this->request->post("action"); + $chunkindex = $this->request->post("chunkindex/d"); + $chunkcount = $this->request->post("chunkcount/d"); + $filesize = $this->request->post("filesize"); + $filename = $this->request->post("filename"); + $method = $this->request->method(true); + $key = $this->request->post("key"); + $uploadId = $this->request->post("uploadId"); + + if ($action == 'merge') { + $attachment = null; + $upload = null; + //合并分片 + if ($config['uploadmode'] == 'server') { + //合并分片文件 + try { + $upload = new Upload(); + $attachment = $upload->merge($chunkid, $chunkcount, $filename); + } catch (UploadException $e) { + $this->error(__($e->getMessage())); + } + } + + $etags = $this->request->post("etags/a", []); + if (count($etags) != $chunkcount) { + $checkDeleteFile($attachment, $upload, true); + $this->error("分片数据错误"); + } + $listParts = []; + for ($i = 0; $i < $chunkcount; $i++) { + $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]); + } + try { + $ret = $oss->completeMultipartUpload($config['bucket'], $key, $uploadId, $listParts); + } catch (\Exception $e) { + $checkDeleteFile($attachment, $upload, true); + $this->error(__($e->getMessage())); + } + + $result = json_decode(json_encode(simplexml_load_string($ret['body'], "SimpleXMLElement", LIBXML_NOCDATA)), true); + if (!isset($result['Key'])) { + $checkDeleteFile($attachment, $upload, true); + $this->error("上传失败(1001)"); + } else { + $data = $attachment && method_exists($attachment, 'getBaseData') ? $attachment->getBaseData() : ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]; + $checkDeleteFile($attachment, $upload); + $this->success("上传成功", '', $data); + } + } else { + //默认普通上传文件 + $file = $this->request->file('file'); + try { + $upload = new Upload($file); + $file = $upload->chunk($chunkid, $chunkindex, $chunkcount); + } catch (UploadException $e) { + $this->error(__($e->getMessage())); + } + try { + //上传分片到OSS + $ret = $oss->uploadPart($config['bucket'], $key, $uploadId, ['fileUpload' => $file->getRealPath(), 'partNumber' => $chunkindex + 1]); + } catch (\Exception $e) { + $this->error(__($e->getMessage())); + } + + $this->success("上传成功", "", [], 3, ['ETag' => $ret]); + } + } else { + $attachment = null; + //默认普通上传文件 + $file = $this->request->file('file'); + try { + $upload = new Upload($file); + $attachment = $upload->upload(); + } catch (UploadException $e) { + $this->error(__($e->getMessage())); + } + + //文件绝对路径 + $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname(); + + $url = $attachment->url; + + try { + $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath); + //成功不做任何操作 + } catch (\Exception $e) { + $checkDeleteFile($attachment, $upload, true); + \think\Log::write($e->getMessage()); + $this->error("上传失败(1002)"); + } + $checkDeleteFile($attachment, $upload); + + // 记录云存储记录 + $data = $attachment->toArray(); + unset($data['id']); + $data['storage'] = 'alioss'; + $attachment = Attachment::create($data, true); + + $this->success("上传成功", '', method_exists($attachment, 'getBaseData') ? $attachment->getBaseData() : ['url' => $url, 'fullurl' => cdnurl($url, true)]); + } + return; + } + + /** + * 回调 + */ + public function notify() + { + $this->check(); + $config = get_addon_config('alioss'); + if ($config['uploadmode'] != 'client') { + $this->error("无需执行该操作"); + } + $this->request->filter('trim,strip_tags,htmlspecialchars,xss_clean'); + $size = $this->request->post('size/d'); + $name = $this->request->post('name', ''); + $md5 = $this->request->post('md5', ''); + $type = $this->request->post('type', ''); + $url = $this->request->post('url', ''); + $width = $this->request->post('width/d'); + $height = $this->request->post('height/d'); + $category = $this->request->post('category', ''); + $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : ''; + $suffix = strtolower(pathinfo($name, PATHINFO_EXTENSION)); + $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file'; + $attachment = Attachment::where('url', $url)->where('storage', 'alioss')->find(); + if (!$attachment) { + $params = array( + 'category' => $category, + 'admin_id' => (int)session('admin.id'), + 'user_id' => (int)$this->auth->id, + 'filesize' => $size, + 'filename' => $name, + 'imagewidth' => $width, + 'imageheight' => $height, + 'imagetype' => $suffix, + 'imageframes' => 0, + 'mimetype' => $type, + 'url' => $url, + 'uploadtime' => time(), + 'storage' => 'alioss', + 'sha1' => $md5, + ); + $attachment = Attachment::create($params, true); + } + $data = $attachment && method_exists($attachment, 'getBaseData') ? $attachment->getBaseData() : ['url' => $url, 'fullurl' => cdnurl($url, true)]; + $this->success('', null, $data); + } + + /** + * 检查签名是否正确或过期 + */ + protected function check() + { + $aliosstoken = $this->request->post('aliosstoken', '', 'trim'); + if (!$aliosstoken) { + $this->error("参数不正确(code:1)"); + } + $config = get_addon_config('alioss'); + list($accessKeyId, $sign, $data) = explode(':', $aliosstoken); + if (!$accessKeyId || !$sign || !$data) { + $this->error("参数不能为空(code:2)"); + } + if ($accessKeyId !== $config['accessKeyId']) { + $this->error("参数不正确(code:3)"); + } + if ($sign !== base64_encode(hash_hmac('sha1', base64_decode($data), $config['accessKeySecret'], true))) { + $this->error("签名不正确"); + } + $json = json_decode(base64_decode($data), true); + if ($json['deadline'] < time()) { + $this->error("请求已经超时"); + } + } + +} diff --git a/addons/alioss/info.ini b/addons/alioss/info.ini new file mode 100644 index 0000000..ca286cc --- /dev/null +++ b/addons/alioss/info.ini @@ -0,0 +1,10 @@ +name = alioss +title = 阿里云OSS云储存 +intro = 使用阿里云OSS云储存,支持直传、服务器中转、分片上传 +author = FastAdmin +website = +version = 1.3.0 +state = 1 +url = /addons/alioss +license = regular +licenseto = 26425 diff --git a/addons/alioss/lang/zh-cn.php b/addons/alioss/lang/zh-cn.php new file mode 100644 index 0000000..70a03d7 --- /dev/null +++ b/addons/alioss/lang/zh-cn.php @@ -0,0 +1,21 @@ + '上传成功', + 'You can upload up to %d file%s' => '你最多还可以上传%d个文件', + 'You can choose up to %d file%s' => '你最多还可以选择%d个文件', + 'Chunk file write error' => '分片写入失败', + 'Chunk file info error' => '分片文件错误', + 'Chunk file merge error' => '分片合并错误', + 'Chunk file disabled' => '未开启分片上传功能', + 'Cancel upload' => '取消上传', + 'Upload canceled' => '上传已取消', + 'No file upload or server upload limit exceeded' => '未上传文件或超出服务器上传限制', + 'Uploaded file format is limited' => '上传文件格式受限制', + 'Invalid MIME type format' => '无效的MIME类型格式', + 'Uploaded file is not a valid image' => '上传文件不是有效的图片文件', + 'You can only upload a maximum of %s files' => '你最多允许上传 %s 个文件', + 'You can\'t upload files of this type' => '不允许上传的文件类型', + 'Server responded with %s code' => '服务端响应(Code:%s)', + 'File is too big (%sMiB), Max filesize: %sMiB' => '当前上传(%sM),最大允许上传文件大小:%sM', + 'An unexpected error occurred' => '发生了一个意外错误,程序猿正在紧急处理中', +]; \ No newline at end of file diff --git a/addons/alioss/library/Auth.php b/addons/alioss/library/Auth.php new file mode 100644 index 0000000..bab328f --- /dev/null +++ b/addons/alioss/library/Auth.php @@ -0,0 +1,132 @@ + $config['notifyurl'] ?? '', + 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}', + 'callbackBodyType' => "application/x-www-form-urlencoded" + ); + + $jsonOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; + $base64_callback_body = base64_encode(json_encode($callback_param)); + + $now = time(); + $end = $now + $config['expire']; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问 + $expiration = $this->gmt_iso8601($end); + + preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches); + $type = strtolower($matches[2]); + $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3]; + $size = (int)$config['maxsize'] * pow(1024, $typeDict[$type] ?? 0); + + //最大文件大小.用户可以自己设置 + $condition = array(0 => 'content-length-range', 1 => 0, 2 => $size); + $conditions[] = $condition; + + //V4签名 + // 获取当前UTC时间并格式化 + $utcTime = new DateTime('now', new DateTimeZone('UTC')); + $date = $utcTime->format('Ymd'); // 当前日期,用于签名计算 + $product = 'oss'; + $version = 'OSS4-HMAC-SHA256'; + $region = str_replace('-internal', '', substr(explode('.', $config['endpoint'])[0], 4)); + $credential = "{$config['accessKeyId']}/{$date}/{$region}/{$product}/aliyun_v4_request"; + + $conditions[] = ['x-oss-signature-version' => $version]; + $conditions[] = ['x-oss-credential' => $credential]; + $conditions[] = ['x-oss-date' => $utcTime->format('Ymd\THis\Z')]; + + $arr = ['expiration' => $expiration, 'conditions' => $conditions]; + + $policy = base64_encode(json_encode($arr, $jsonOptions)); + + // 计算签名所需的信息 + $signingKey = "aliyun_v4" . $config['accessKeySecret']; // 构造签名密钥 + $h1Key = $this->hmacSign($signingKey, $date); // 第一步:对日期签名 + $h2Key = $this->hmacSign($h1Key, $region); // 第二步:对区域签名 + $h3Key = $this->hmacSign($h2Key, $product); // 第三步:对产品签名 + $h4Key = $this->hmacSign($h3Key, "aliyun_v4_request"); // 第四步:对请求签名 + + // 计算最终签名 + $signature = hash_hmac('sha256', $policy, $h4Key); + + + $key = (new Upload())->getSavekey($config['savekey'], $name, $md5); + $key = ltrim($key, "/"); + + $response = array(); + $response['id'] = $config['accessKeyId']; + $response['key'] = $key; + $response['policy'] = $policy; + $response['expire'] = $end; + $response['callback'] = ''; + $response['x-oss-signature-version'] = $version; + $response['x-oss-credential'] = $credential; + $response['x-oss-date'] = $utcTime->format('Ymd\THis\Z'); + $response['x-oss-signature'] = $signature; + return $response; + } + + public function check($signature, $policy) + { + $config = get_addon_config('alioss'); + $sign = base64_encode(hash_hmac('sha1', $policy, $config['accessKeySecret'], true)); + return $signature == $sign; + } + + private function hmacSign($key, $data) + { + return hash_hmac('sha256', $data, $key, true); + } + + private function gmt_iso8601($time) + { + $dtStr = date("c", $time); + $mydatetime = new \DateTime($dtStr); + $expiration = $mydatetime->format(\DateTime::ISO8601); + $pos = strpos($expiration, '+'); + $expiration = substr($expiration, 0, $pos); + return $expiration . "Z"; + } + + public static function isModuleAllow() + { + $config = get_addon_config('alioss'); + $module = request()->module(); + $module = $module ? strtolower($module) : 'index'; + $noNeedLogin = array_filter(explode(',', $config['noneedlogin'] ?? '')); + $isModuleLogin = false; + $tagName = 'upload_config_checklogin'; + foreach (\think\Hook::get($tagName) as $index => $name) { + if (\think\Hook::exec($name, $tagName)) { + $isModuleLogin = true; + break; + } + } + if (in_array($module, $noNeedLogin) + || ($module == 'admin' && \app\admin\library\Auth::instance()->id) + || ($module != 'admin' && \app\common\library\Auth::instance()->id) + || $isModuleLogin) { + return true; + } else { + return false; + } + } + +} diff --git a/addons/alioss/library/File.php b/addons/alioss/library/File.php new file mode 100644 index 0000000..7c75c3f --- /dev/null +++ b/addons/alioss/library/File.php @@ -0,0 +1,36 @@ +info[$offset]); + } + + public function offsetGet($offset) + { + return $this->info[$offset]; + } + + public function offsetSet($offset, $value) + { + $this->info[$offset] = $value; + } + + public function offsetUnset($offset) + { + unset($this->info[$offset]); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Core/MimeTypes.php b/addons/alioss/library/OSS/Core/MimeTypes.php new file mode 100644 index 0000000..17685c3 --- /dev/null +++ b/addons/alioss/library/OSS/Core/MimeTypes.php @@ -0,0 +1,263 @@ + 1) { + $ext = strtolower(end($parts)); + if (isset(self::$mime_types[$ext])) { + return self::$mime_types[$ext]; + } + } + + return null; + } + + private static $mime_types = array( + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'apk' => 'application/vnd.android.package-archive', + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'doc' => 'application/msword', + 'ogg' => 'audio/ogg', + 'pdf' => 'application/pdf', + 'rtf' => 'text/rtf', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'sxw' => 'application/vnd.sun.xml.writer', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'sxc' => 'application/vnd.sun.xml.calc', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'sxd' => 'application/vnd.sun.xml.draw', + 'std' => 'application/vnd.sun.xml.draw.template', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxm' => 'application/vnd.sun.xml.math', + 'sis' => 'application/vnd.symbian.install', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'bcpio' => 'application/x-bcpio', + 'torrent' => 'application/x-bittorrent', + 'bz2' => 'application/x-bzip2', + 'vcd' => 'application/x-cdlink', + 'pgn' => 'application/x-chess-pgn', + 'cpio' => 'application/x-cpio', + 'csh' => 'application/x-csh', + 'dvi' => 'application/x-dvi', + 'spl' => 'application/x-futuresplash', + 'gtar' => 'application/x-gtar', + 'hdf' => 'application/x-hdf', + 'jar' => 'application/java-archive', + 'jnlp' => 'application/x-java-jnlp-file', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'ksp' => 'application/x-kspread', + 'chrt' => 'application/x-kchart', + 'kil' => 'application/x-killustrator', + 'latex' => 'application/x-latex', + 'rpm' => 'application/x-rpm', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'tar' => 'application/x-tar', + 'tcl' => 'application/x-tcl', + 'tex' => 'application/x-tex', + 'man' => 'application/x-troff-man', + 'me' => 'application/x-troff-me', + 'ms' => 'application/x-troff-ms', + 'ustar' => 'application/x-ustar', + 'src' => 'application/x-wais-source', + 'zip' => 'application/zip', + 'm3u' => 'audio/x-mpegurl', + 'ra' => 'audio/x-pn-realaudio', + 'wav' => 'audio/x-wav', + 'wma' => 'audio/x-ms-wma', + 'wax' => 'audio/x-ms-wax', + 'pdb' => 'chemical/x-pdb', + 'xyz' => 'chemical/x-xyz', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'ief' => 'image/ief', + 'png' => 'image/png', + 'wbmp' => 'image/vnd.wap.wbmp', + 'ras' => 'image/x-cmu-raster', + 'pnm' => 'image/x-portable-anymap', + 'pbm' => 'image/x-portable-bitmap', + 'pgm' => 'image/x-portable-graymap', + 'ppm' => 'image/x-portable-pixmap', + 'rgb' => 'image/x-rgb', + 'xbm' => 'image/x-xbitmap', + 'xpm' => 'image/x-xpixmap', + 'xwd' => 'image/x-xwindowdump', + 'css' => 'text/css', + 'rtx' => 'text/richtext', + 'tsv' => 'text/tab-separated-values', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'wml' => 'text/vnd.wap.wml', + 'wmls' => 'text/vnd.wap.wmlscript', + 'etx' => 'text/x-setext', + 'mxu' => 'video/vnd.mpegurl', + 'flv' => 'video/x-flv', + 'wm' => 'video/x-ms-wm', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wvx' => 'video/x-ms-wvx', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'ice' => 'x-conference/x-cooltalk', + '3gp' => 'video/3gpp', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'asc' => 'text/plain', + 'atom' => 'application/atom+xml', + 'au' => 'audio/basic', + 'bin' => 'application/octet-stream', + 'cdf' => 'application/x-netcdf', + 'cgm' => 'image/cgm', + 'class' => 'application/octet-stream', + 'dcr' => 'application/x-director', + 'dif' => 'video/x-dv', + 'dir' => 'application/x-director', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'dtd' => 'application/xml-dtd', + 'dv' => 'video/x-dv', + 'dxr' => 'application/x-director', + 'eps' => 'application/postscript', + 'exe' => 'application/octet-stream', + 'ez' => 'application/andrew-inset', + 'gram' => 'application/srgs', + 'grxml' => 'application/srgs+xml', + 'gz' => 'application/x-gzip', + 'htm' => 'text/html', + 'html' => 'text/html', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ifb' => 'text/calendar', + 'iges' => 'model/iges', + 'igs' => 'model/iges', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'kar' => 'audio/midi', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'm4a' => 'audio/mp4a-latm', + 'm4p' => 'audio/mp4a-latm', + 'm4u' => 'video/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'mac' => 'image/x-macpaint', + 'mathml' => 'application/mathml+xml', + 'mesh' => 'model/mesh', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpga' => 'audio/mpeg', + 'msh' => 'model/mesh', + 'nc' => 'application/x-netcdf', + 'oda' => 'application/oda', + 'ogv' => 'video/ogv', + 'pct' => 'image/pict', + 'pic' => 'image/pict', + 'pict' => 'image/pict', + 'pnt' => 'image/x-macpaint', + 'pntg' => 'image/x-macpaint', + 'ps' => 'application/postscript', + 'qt' => 'video/quicktime', + 'qti' => 'image/x-quicktime', + 'qtif' => 'image/x-quicktime', + 'ram' => 'audio/x-pn-realaudio', + 'rdf' => 'application/rdf+xml', + 'rm' => 'application/vnd.rn-realmedia', + 'roff' => 'application/x-troff', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'silo' => 'model/mesh', + 'skd' => 'application/x-koan', + 'skm' => 'application/x-koan', + 'skp' => 'application/x-koan', + 'skt' => 'application/x-koan', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'snd' => 'audio/basic', + 'so' => 'application/octet-stream', + 'svg' => 'image/svg+xml', + 't' => 'application/x-troff', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tr' => 'application/x-troff', + 'txt' => 'text/plain', + 'vrml' => 'model/vrml', + 'vxml' => 'application/voicexml+xml', + 'webm' => 'video/webm', + 'webp' => 'image/webp', + 'wrl' => 'model/vrml', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xml' => 'application/xml', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + ); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Core/OssException.php b/addons/alioss/library/OSS/Core/OssException.php new file mode 100644 index 0000000..2320c9e --- /dev/null +++ b/addons/alioss/library/OSS/Core/OssException.php @@ -0,0 +1,54 @@ +details = $details; + } else { + $message = $details; + parent::__construct($message); + } + } + + public function getHTTPStatus() + { + return isset($this->details['status']) ? $this->details['status'] : ''; + } + + public function getRequestId() + { + return isset($this->details['request-id']) ? $this->details['request-id'] : ''; + } + + public function getErrorCode() + { + return isset($this->details['code']) ? $this->details['code'] : ''; + } + + public function getErrorMessage() + { + return isset($this->details['message']) ? $this->details['message'] : ''; + } + + public function getDetails() + { + return isset($this->details['body']) ? $this->details['body'] : ''; + } +} diff --git a/addons/alioss/library/OSS/Core/OssUtil.php b/addons/alioss/library/OSS/Core/OssUtil.php new file mode 100644 index 0000000..e70609a --- /dev/null +++ b/addons/alioss/library/OSS/Core/OssUtil.php @@ -0,0 +1,543 @@ + $value) { + if (is_string($key) && !is_array($value)) { + if (strlen($value) > 0) { + $temp[] = rawurlencode($key) . '=' . rawurlencode($value); + } else { + $temp[] = rawurlencode($key); + } + } + } + return implode('&', $temp); + } + + /** + * Html encoding '<', '>', '&', '\', '"' in subject parameter. + * + * @param string $subject + * @return string + */ + public static function sReplace($subject) + { + $search = array('<', '>', '&', '\'', '"'); + $replace = array('<', '>', '&', ''', '"'); + return str_replace($search, $replace, $subject); + } + + /** + * Check whether the string includes any chinese character + * + * @param $str + * @return int + */ + public static function chkChinese($str) + { + return preg_match('/[\x80-\xff]./', $str); + } + + /** + * Checks if the string is encoded by GB2312. + * + * @param string $str + * @return boolean false UTF-8 encoding TRUE GB2312 encoding + */ + public static function isGb2312($str) + { + for ($i = 0; $i < strlen($str); $i++) { + $v = ord($str[$i]); + if ($v > 127) { + if (($v >= 228) && ($v <= 233)) { + if (($i + 2) >= (strlen($str) - 1)) return true; // not enough characters + $v1 = ord($str[$i + 1]); + $v2 = ord($str[$i + 2]); + if (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191)) + return false; + else + return true; + } + } + } + return false; + } + + /** + * Checks if the string is encoded by GBK + * + * @param string $str + * @param boolean $gbk + * @return boolean + */ + public static function checkChar($str, $gbk = true) + { + for ($i = 0; $i < strlen($str); $i++) { + $v = ord($str[$i]); + if ($v > 127) { + if (($v >= 228) && ($v <= 233)) { + if (($i + 2) >= (strlen($str) - 1)) return $gbk ? true : FALSE; // not enough characters + $v1 = ord($str[$i + 1]); + $v2 = ord($str[$i + 2]); + if ($gbk) { + return (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191)) ? FALSE : TRUE;//GBK + } else { + return (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191)) ? TRUE : FALSE; + } + } + } + } + return $gbk ? TRUE : FALSE; + } + + /** + * Checks if the bucket name is valid + * bucket naming rules + * 1. Can only include lowercase letters, numbers, or dashes + * 2. Must start and end with lowercase letters or numbers + * 3. Must be within a length from 3 to 63 bytes. + * + * @param string $bucket Bucket name + * @return boolean + */ + public static function validateBucket($bucket) + { + $pattern = '/^[a-z0-9][a-z0-9-]{2,62}$/'; + if (!preg_match($pattern, $bucket)) { + return false; + } + return true; + } + + /** + * Checks if object name is valid + * object naming rules: + * 1. Must be within a length from 1 to 1023 bytes + * 2. Cannot start with '/' or '\\'. + * 3. Must be encoded in UTF-8. + * + * @param string $object Object名称 + * @return boolean + */ + public static function validateObject($object) + { + $pattern = '/^.{1,1023}$/'; + if (!preg_match($pattern, $object) || + self::startsWith($object, '/') || self::startsWith($object, '\\') + ) { + return false; + } + return true; + } + + + /** + * Checks if $str starts with $findMe + * + * @param string $str + * @param string $findMe + * @return bool + */ + public static function startsWith($str, $findMe) + { + if (strpos($str, $findMe) === 0) { + return true; + } else { + return false; + } + } + + + /** + * Generate the xml message of createBucketXmlBody. + * + * @param string $storageClass + * @return string + */ + public static function createBucketXmlBody($storageClass) + { + $xml = new \SimpleXMLElement(''); + $xml->addChild('StorageClass', $storageClass); + return $xml->asXML(); + } + + /** + * validate $options + * + * @param array $options + * @throws OssException + */ + public static function validateOptions($options) + { + //$options + if ($options != NULL && !is_array($options)) { + throw new OssException ($options . ':' . 'option must be array'); + } + } + + /** + * check whether the Content is valid. + * + * @param $content string + * @throws OssException + */ + public static function validateContent($content) + { + if (empty($content)) { + throw new OssException("http body content is invalid"); + } + } + + /** + * Check if BUCKET/OBJECT/OBJECT GROUP is empty. + * + * @param string $name + * @param string $errMsg + * @throws OssException + * @return void + */ + public static function throwOssExceptionWithMessageIfEmpty($name, $errMsg) + { + if (empty($name)) { + if (is_string($name) && $name == '0') + return; + throw new OssException($errMsg); + } + } + + /** + * This is a method for test only. DO NOT USE. + * + * @param $filename + * @param $size + */ + public static function generateFile($filename, $size) + { + if (file_exists($filename) && $size == sprintf('%u',filesize($filename))) { + echo $filename . " already exists, no need to create again. "; + return; + } + $part_size = 1 * 1024 * 1024; + $fp = fopen($filename, "w"); + $characters = << 0) { + if ($size < $part_size) { + $write_size = $size; + } else { + $write_size = $part_size; + } + $size -= $write_size; + $a = $characters[rand(0, $charactersLength - 1)]; + $content = str_repeat($a, $write_size); + $flag = fwrite($fp, $content); + if (!$flag) { + echo "write to " . $filename . " failed.
"; + break; + } + } + } else { + echo "open " . $filename . " failed.
"; + } + fclose($fp); + } + + /** + * Get MD5 of the file. + * + * @param $filename + * @param $from_pos + * @param $to_pos + * @return string + */ + public static function getMd5SumForFile($filename, $from_pos, $to_pos) + { + $content_md5 = ""; + if (($to_pos - $from_pos) > self::OSS_MAX_PART_SIZE) { + return $content_md5; + } + $filesize = sprintf('%u',filesize($filename)); + if ($from_pos >= $filesize || $to_pos >= $filesize || $from_pos < 0 || $to_pos < 0) { + return $content_md5; + } + + $total_length = $to_pos - $from_pos + 1; + $buffer = 8192; + $left_length = $total_length; + if (!file_exists($filename)) { + return $content_md5; + } + + if (false === $fh = fopen($filename, 'rb')) { + return $content_md5; + } + + fseek($fh, $from_pos); + $data = ''; + while (!feof($fh)) { + if ($left_length >= $buffer) { + $read_length = $buffer; + } else { + $read_length = $left_length; + } + if ($read_length <= 0) { + break; + } else { + $data .= fread($fh, $read_length); + $left_length = $left_length - $read_length; + } + } + fclose($fh); + $content_md5 = base64_encode(md5($data, true)); + return $content_md5; + } + + /** + * Check if the OS is Windows. The default encoding in Windows is GBK. + * + * @return bool + */ + public static function isWin() + { + return strtoupper(substr(PHP_OS, 0, 3)) == "WIN"; + } + + /** + * Encodes the file path from GBK to UTF-8. + * The default encoding in Windows is GBK. + * And if the file path is in Chinese, the file would not be found without the transcoding to UTF-8. + * + * @param $file_path + * @return string + */ + public static function encodePath($file_path) + { + if (self::chkChinese($file_path) && self::isWin()) { + $file_path = iconv('utf-8', 'gbk', $file_path); + } + return $file_path; + } + + /** + * Check if the endpoint is in the IPv4 format, such as xxx.xxx.xxx.xxx:port or xxx.xxx.xxx.xxx. + * + * @param string $endpoint The endpoint to check. + * @return boolean + */ + public static function isIPFormat($endpoint) + { + $ip_array = explode(":", $endpoint); + $hostname = $ip_array[0]; + $ret = filter_var($hostname, FILTER_VALIDATE_IP); + if (!$ret) { + return false; + } else { + return true; + } + } + + /** + * Get the host:port from endpoint. + * + * @param string $endpoint the endpoint. + * @return string + * @throws OssException + */ + public static function getHostPortFromEndpoint($endpoint) + { + $str = $endpoint; + $pos = strpos($str, "://"); + if ($pos !== false) { + $str = substr($str, $pos+3); + } + + $pos = strpos($str, '#'); + if ($pos !== false) { + $str = substr($str, 0, $pos); + } + + $pos = strpos($str, '?'); + if ($pos !== false) { + $str = substr($str, 0, $pos); + } + + $pos = strpos($str, '/'); + if ($pos !== false) { + $str = substr($str, 0, $pos); + } + + $pos = strpos($str, '@'); + if ($pos !== false) { + $str = substr($str, $pos+1); + } + + if (!preg_match('/^[\w.-]+(:[0-9]+)?$/', $str)) { + throw new OssException("endpoint is invalid:" . $endpoint); + } + + return $str; + } + + /** + * Generate the xml message of DeleteMultiObjects. + * + * @param string[] $objects + * @param bool $quiet + * @return string + */ + public static function createDeleteObjectsXmlBody($objects, $quiet) + { + $xml = new \SimpleXMLElement(''); + $xml->addChild('Quiet', $quiet); + foreach ($objects as $object) { + $sub_object = $xml->addChild('Object'); + $object = OssUtil::sReplace($object); + $sub_object->addChild('Key', $object); + } + return $xml->asXML(); + } + + /** + * Generate the xml message of DeleteMultiObjects. + * + * @param DeleteObjectInfo[] $objects + * @param bool $quiet + * @return string + */ + public static function createDeleteObjectVersionsXmlBody($objects, $quiet) + { + $xml = new \SimpleXMLElement(''); + $xml->addChild('Quiet', $quiet); + foreach ($objects as $object) { + $sub_object = $xml->addChild('Object'); + $key = OssUtil::sReplace($object->getKey()); + $sub_object->addChild('Key', $key); + $versionId = $object->getVersionId(); + if (!empty($versionId)) { + $sub_object->addChild('VersionId', $object->getVersionId()); + } + } + return $xml->asXML(); + } + + /** + * Generate the xml message of CompleteMultipartUpload. + * + * @param array[] $listParts + * @return string + */ + public static function createCompleteMultipartUploadXmlBody($listParts) + { + $xml = new \SimpleXMLElement(''); + foreach ($listParts as $node) { + $part = $xml->addChild('Part'); + $part->addChild('PartNumber', $node['PartNumber']); + $part->addChild('ETag', $node['ETag']); + } + return $xml->asXML(); + } + + /** + * Read the directory, return a associative array in which the MD5 is the named key and the is the value. + * + * @param string $dir + * @param string $exclude + * @param bool $recursive + * @return string[] + */ + public static function readDir($dir, $exclude = ".|..|.svn|.git", $recursive = false) + { + $file_list_array = array(); + $base_path = $dir; + $exclude_array = explode("|", $exclude); + $exclude_array = array_unique(array_merge($exclude_array, array('.', '..'))); + + if ($recursive) { + foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir)) as $new_file) { + if ($new_file->isDir()) continue; + $object = str_replace($base_path, '', $new_file); + if (!in_array(strtolower($object), $exclude_array)) { + $object = ltrim($object, '/'); + if (is_file($new_file)) { + $key = md5($new_file . $object, false); + $file_list_array[$key] = array('path' => $new_file, 'file' => $object,); + } + } + } + } else if ($handle = opendir($dir)) { + while (false !== ($file = readdir($handle))) { + if (!in_array(strtolower($file), $exclude_array)) { + $new_file = $dir . '/' . $file; + $object = $file; + $object = ltrim($object, '/'); + if (is_file($new_file)) { + $key = md5($new_file . $object, false); + $file_list_array[$key] = array('path' => $new_file, 'file' => $object,); + } + } + } + closedir($handle); + } + return $file_list_array; + } + + /** + * Decode key based on the encoding type + * + * @param string $key + * @param string $encoding + * @return string + */ + public static function decodeKey($key, $encoding) + { + if ($encoding == "") { + return $key; + } + + if ($encoding == "url") { + return rawurldecode($key); + } else { + throw new OssException("Unrecognized encoding type: " . $encoding); + } + } + + public static function unparseUrl($parsed_url) { + $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; + $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; + $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; + $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; + $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; + return "$scheme$host$port$path$query"; + } +} diff --git a/addons/alioss/library/OSS/Credentials/Credentials.php b/addons/alioss/library/OSS/Credentials/Credentials.php new file mode 100644 index 0000000..2a8ffb5 --- /dev/null +++ b/addons/alioss/library/OSS/Credentials/Credentials.php @@ -0,0 +1,63 @@ +key = trim($key); + $this->secret = trim($secret); + $this->token = $token; + } + + + /** + * @return string + */ + public function getAccessKeyId() + { + return $this->key; + } + + /** + * @return string + */ + public function getAccessKeySecret() + { + return $this->secret; + } + + /** + * @return string|null + */ + public function getSecurityToken() + { + return $this->token; + } +} diff --git a/addons/alioss/library/OSS/Credentials/CredentialsProvider.php b/addons/alioss/library/OSS/Credentials/CredentialsProvider.php new file mode 100644 index 0000000..b2fde83 --- /dev/null +++ b/addons/alioss/library/OSS/Credentials/CredentialsProvider.php @@ -0,0 +1,11 @@ +credentials = new Credentials($key, $secret, $token); + } + + /** + * @return Credentials + */ + public function getCredentials() + { + return $this->credentials; + } +} diff --git a/addons/alioss/library/OSS/Http/LICENSE b/addons/alioss/library/OSS/Http/LICENSE new file mode 100644 index 0000000..49b38bd --- /dev/null +++ b/addons/alioss/library/OSS/Http/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2006-2010 Ryan Parman, Foleeo Inc., and contributors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are +permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other materials + provided with the distribution. + + * Neither the name of Ryan Parman, Foleeo Inc. nor the names of its contributors may be used to + endorse or promote products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS +AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/addons/alioss/library/OSS/Http/RequestCore.php b/addons/alioss/library/OSS/Http/RequestCore.php new file mode 100644 index 0000000..58bb215 --- /dev/null +++ b/addons/alioss/library/OSS/Http/RequestCore.php @@ -0,0 +1,898 @@ +). + */ + public $request_class = 'OSS\Http\RequestCore'; + + /** + * The default class to use for HTTP Responses (defaults to ). + */ + public $response_class = 'OSS\Http\ResponseCore'; + + /** + * Default useragent string to use. + */ + public $useragent = 'RequestCore/1.4.3'; + + /** + * File to read from while streaming up. + */ + public $read_file = null; + + /** + * The resource to read from while streaming up. + */ + public $read_stream = null; + + /** + * The size of the stream to read from. + */ + public $read_stream_size = null; + + /** + * The length already read from the stream. + */ + public $read_stream_read = 0; + + /** + * File to write to while streaming down. + */ + public $write_file = null; + + /** + * The resource to write to while streaming down. + */ + public $write_stream = null; + + /** + * Stores the intended starting seek position. + */ + public $seek_position = null; + + /** + * The location of the cacert.pem file to use. + */ + public $cacert_location = false; + + /** + * The state of SSL certificate verification. + */ + public $ssl_verification = true; + + /** + * The user-defined callback function to call when a stream is read from. + */ + public $registered_streaming_read_callback = null; + + /** + * The user-defined callback function to call when a stream is written to. + */ + public $registered_streaming_write_callback = null; + + /** + * The request timeout time, which is 5,184,000 seconds,that is, 60 days by default + * + * @var int + */ + public $timeout = 5184000; + + /** + * The connection timeout time, which is 10 seconds by default + * + * @var int + */ + public $connect_timeout = 10; + + /*%******************************************************************************************%*/ + // CONSTANTS + + /** + * GET HTTP Method + */ + const HTTP_GET = 'GET'; + + /** + * POST HTTP Method + */ + const HTTP_POST = 'POST'; + + /** + * PUT HTTP Method + */ + const HTTP_PUT = 'PUT'; + + /** + * DELETE HTTP Method + */ + const HTTP_DELETE = 'DELETE'; + + /** + * HEAD HTTP Method + */ + const HTTP_HEAD = 'HEAD'; + + + /*%******************************************************************************************%*/ + // CONSTRUCTOR/DESTRUCTOR + + /** + * Construct a new instance of this class. + * + * @param string $url (Optional) The URL to request or service endpoint to query. + * @param string $proxy (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port` + * @param array $helpers (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class. + * @return $this A reference to the current instance. + */ + public function __construct($url = null, $proxy = null, $helpers = null) + { + // Set some default values. + $this->request_url = $url; + $this->method = self::HTTP_GET; + $this->request_headers = array(); + $this->request_body = ''; + + // Set a new Request class if one was set. + if (isset($helpers['request']) && !empty($helpers['request'])) { + $this->request_class = $helpers['request']; + } + + // Set a new Request class if one was set. + if (isset($helpers['response']) && !empty($helpers['response'])) { + $this->response_class = $helpers['response']; + } + + if ($proxy) { + $this->set_proxy($proxy); + } + + return $this; + } + + /** + * Destruct the instance. Closes opened file handles. + * + * @return $this A reference to the current instance. + */ + public function __destruct() + { + if (isset($this->read_file) && isset($this->read_stream)) { + fclose($this->read_stream); + } + + if (isset($this->write_file) && isset($this->write_stream)) { + fclose($this->write_stream); + } + + return $this; + } + + + /*%******************************************************************************************%*/ + // REQUEST METHODS + + /** + * Set the credentials to use for authentication. + * + * @param string $user (Required) The username to authenticate with. + * @param string $pass (Required) The password to authenticate with. + * @return $this A reference to the current instance. + */ + public function set_credentials($user, $pass) + { + $this->username = $user; + $this->password = $pass; + return $this; + } + + /** + * Add a custom HTTP header to the cURL request. + * + * @param string $key (Required) The custom HTTP header to set. + * @param mixed $value (Required) The value to assign to the custom HTTP header. + * @return $this A reference to the current instance. + */ + public function add_header($key, $value) + { + $this->request_headers[$key] = $value; + return $this; + } + + /** + * Remove an HTTP header from the cURL request. + * + * @param string $key (Required) The custom HTTP header to set. + * @return $this A reference to the current instance. + */ + public function remove_header($key) + { + if (isset($this->request_headers[$key])) { + unset($this->request_headers[$key]); + } + return $this; + } + + /** + * Set the method type for the request. + * + * @param string $method (Required) One of the following constants: , , , , . + * @return $this A reference to the current instance. + */ + public function set_method($method) + { + $this->method = strtoupper($method); + return $this; + } + + /** + * Set a custom useragent string for the class. + * + * @param string $ua (Required) The useragent string to use. + * @return $this A reference to the current instance. + */ + public function set_useragent($ua) + { + $this->useragent = $ua; + return $this; + } + + /** + * Set the body to send in the request. + * + * @param string $body (Required) The textual content to send along in the body of the request. + * @return $this A reference to the current instance. + */ + public function set_body($body) + { + $this->request_body = $body; + return $this; + } + + /** + * Set the URL to make the request to. + * + * @param string $url (Required) The URL to make the request to. + * @return $this A reference to the current instance. + */ + public function set_request_url($url) + { + $this->request_url = $url; + return $this; + } + + /** + * Set additional CURLOPT settings. These will merge with the default settings, and override if + * there is a duplicate. + * + * @param array $curlopts (Optional) A set of key-value pairs that set `CURLOPT` options. These will merge with the existing CURLOPTs, and ones passed here will override the defaults. Keys should be the `CURLOPT_*` constants, not strings. + * @return $this A reference to the current instance. + */ + public function set_curlopts($curlopts) + { + $this->curlopts = $curlopts; + return $this; + } + + /** + * Set the length in bytes to read from the stream while streaming up. + * + * @param integer $size (Required) The length in bytes to read from the stream. + * @return $this A reference to the current instance. + */ + public function set_read_stream_size($size) + { + $this->read_stream_size = $size; + + return $this; + } + + /** + * Set the resource to read from while streaming up. Reads the stream from its current position until + * EOF or `$size` bytes have been read. If `$size` is not given it will be determined by and + * . + * + * @param resource $resource (Required) The readable resource to read from. + * @param integer $size (Optional) The size of the stream to read. + * @return $this A reference to the current instance. + */ + public function set_read_stream($resource, $size = null) + { + if (!isset($size) || $size < 0) { + $stats = fstat($resource); + + if ($stats && $stats['size'] >= 0) { + $position = ftell($resource); + + if ($position !== false && $position >= 0) { + $size = $stats['size'] - $position; + } + } + } + + $this->read_stream = $resource; + + return $this->set_read_stream_size($size); + } + + /** + * Set the file to read from while streaming up. + * + * @param string $location (Required) The readable location to read from. + * @return $this A reference to the current instance. + */ + public function set_read_file($location) + { + $this->read_file = $location; + $read_file_handle = fopen($location, 'r'); + + return $this->set_read_stream($read_file_handle); + } + + /** + * Set the resource to write to while streaming down. + * + * @param resource $resource (Required) The writeable resource to write to. + * @return $this A reference to the current instance. + */ + public function set_write_stream($resource) + { + $this->write_stream = $resource; + + return $this; + } + + /** + * Set the file to write to while streaming down. + * + * @param string $location (Required) The writeable location to write to. + * @return $this A reference to the current instance. + */ + public function set_write_file($location) + { + $this->write_file = $location; + } + + /** + * Set the proxy to use for making requests. + * + * @param string $proxy (Required) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port` + * @return $this A reference to the current instance. + */ + public function set_proxy($proxy) + { + $proxy = parse_url($proxy); + $proxy['user'] = isset($proxy['user']) ? $proxy['user'] : null; + $proxy['pass'] = isset($proxy['pass']) ? $proxy['pass'] : null; + $proxy['port'] = isset($proxy['port']) ? $proxy['port'] : null; + $this->proxy = $proxy; + return $this; + } + + /** + * Set the intended starting seek position. + * + * @param integer $position (Required) The byte-position of the stream to begin reading from. + * @return $this A reference to the current instance. + */ + public function set_seek_position($position) + { + $this->seek_position = isset($position) ? (integer)$position : null; + + return $this; + } + + /** + * A callback function that is invoked by cURL for streaming up. + * + * @param resource $curl_handle (Required) The cURL handle for the request. + * @param resource $header_content (Required) The header callback result. + * @return headers from a stream. + */ + public function streaming_header_callback($curl_handle, $header_content) + { + $code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE); + + if (isset($this->write_file) && intval($code) / 100 == 2 && !isset($this->write_file_handle)) + { + $this->write_file_handle = fopen($this->write_file, 'w'); + $this->set_write_stream($this->write_file_handle); + } + + $this->response_raw_headers .= $header_content; + return strlen($header_content); + } + + + /** + * Register a callback function to execute whenever a data stream is read from using + * . + * + * The user-defined callback function should accept three arguments: + * + *
    + *
  • $curl_handle - resource - Required - The cURL handle resource that represents the in-progress transfer.
  • + *
  • $file_handle - resource - Required - The file handle resource that represents the file on the local file system.
  • + *
  • $length - integer - Required - The length in kilobytes of the data chunk that was transferred.
  • + *
+ * + * @param string|array|function $callback (Required) The callback function is called by , so you can pass the following values:
    + *
  • The name of a global function to execute, passed as a string.
  • + *
  • A method to execute, passed as array('ClassName', 'MethodName').
  • + *
  • An anonymous function (PHP 5.3+).
+ * @return $this A reference to the current instance. + */ + public function register_streaming_read_callback($callback) + { + $this->registered_streaming_read_callback = $callback; + + return $this; + } + + /** + * Register a callback function to execute whenever a data stream is written to using + * . + * + * The user-defined callback function should accept two arguments: + * + *
    + *
  • $curl_handle - resource - Required - The cURL handle resource that represents the in-progress transfer.
  • + *
  • $length - integer - Required - The length in kilobytes of the data chunk that was transferred.
  • + *
+ * + * @param string|array|function $callback (Required) The callback function is called by , so you can pass the following values:
    + *
  • The name of a global function to execute, passed as a string.
  • + *
  • A method to execute, passed as array('ClassName', 'MethodName').
  • + *
  • An anonymous function (PHP 5.3+).
+ * @return $this A reference to the current instance. + */ + public function register_streaming_write_callback($callback) + { + $this->registered_streaming_write_callback = $callback; + + return $this; + } + + + /*%******************************************************************************************%*/ + // PREPARE, SEND, AND PROCESS REQUEST + + /** + * A callback function that is invoked by cURL for streaming up. + * + * @param resource $curl_handle (Required) The cURL handle for the request. + * @param resource $file_handle (Required) The open file handle resource. + * @param integer $length (Required) The maximum number of bytes to read. + * @return binary Binary data from a stream. + */ + public function streaming_read_callback($curl_handle, $file_handle, $length) + { + // Once we've sent as much as we're supposed to send... + if ($this->read_stream_read >= $this->read_stream_size) { + // Send EOF + return ''; + } + + // If we're at the beginning of an upload and need to seek... + if ($this->read_stream_read == 0 && isset($this->seek_position) && $this->seek_position !== ftell($this->read_stream)) { + if (fseek($this->read_stream, $this->seek_position) !== 0) { + throw new RequestCore_Exception('The stream does not support seeking and is either not at the requested position or the position is unknown.'); + } + } + + $read = fread($this->read_stream, min($this->read_stream_size - $this->read_stream_read, $length)); // Remaining upload data or cURL's requested chunk size + $this->read_stream_read += strlen($read); + + $out = $read === false ? '' : $read; + + // Execute callback function + if ($this->registered_streaming_read_callback) { + call_user_func($this->registered_streaming_read_callback, $curl_handle, $file_handle, $out); + } + + return $out; + } + + /** + * A callback function that is invoked by cURL for streaming down. + * + * @param resource $curl_handle (Required) The cURL handle for the request. + * @param binary $data (Required) The data to write. + * @return integer The number of bytes written. + */ + public function streaming_write_callback($curl_handle, $data) + { + $code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE); + + if (intval($code) / 100 != 2) + { + $this->response_error_body .= $data; + return strlen($data); + } + + $length = strlen($data); + $written_total = 0; + $written_last = 0; + + while ($written_total < $length) { + $written_last = fwrite($this->write_stream, substr($data, $written_total)); + + if ($written_last === false) { + return $written_total; + } + + $written_total += $written_last; + } + + // Execute callback function + if ($this->registered_streaming_write_callback) { + call_user_func($this->registered_streaming_write_callback, $curl_handle, $written_total); + } + + return $written_total; + } + + /** + * Prepare and adds the details of the cURL request. This can be passed along to a + * function. + * + * @return resource The handle for the cURL object. + * + */ + public function prep_request() + { + $curl_handle = curl_init(); + + // Set default options. + curl_setopt($curl_handle, CURLOPT_URL, $this->request_url); + curl_setopt($curl_handle, CURLOPT_FILETIME, true); + curl_setopt($curl_handle, CURLOPT_FRESH_CONNECT, false); +// curl_setopt($curl_handle, CURLOPT_CLOSEPOLICY, CURLCLOSEPOLICY_LEAST_RECENTLY_USED); + curl_setopt($curl_handle, CURLOPT_MAXREDIRS, 5); + curl_setopt($curl_handle, CURLOPT_HEADER, true); + curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl_handle, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout); + curl_setopt($curl_handle, CURLOPT_NOSIGNAL, true); + curl_setopt($curl_handle, CURLOPT_REFERER, $this->request_url); + curl_setopt($curl_handle, CURLOPT_USERAGENT, $this->useragent); + curl_setopt($curl_handle, CURLOPT_HEADERFUNCTION, array($this, 'streaming_header_callback')); + curl_setopt($curl_handle, CURLOPT_READFUNCTION, array($this, 'streaming_read_callback')); + + // Verification of the SSL cert + if ($this->ssl_verification) { + curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 2); + } else { + curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false); + } + + // chmod the file as 0755 + if ($this->cacert_location === true) { + curl_setopt($curl_handle, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem'); + } elseif (is_string($this->cacert_location)) { + curl_setopt($curl_handle, CURLOPT_CAINFO, $this->cacert_location); + } + + // Debug mode + if ($this->debug_mode) { + curl_setopt($curl_handle, CURLOPT_VERBOSE, true); + } + + // Handle open_basedir & safe mode + if (!ini_get('safe_mode') && !ini_get('open_basedir')) { + curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true); + } + + // Enable a proxy connection if requested. + if ($this->proxy) { + $host = $this->proxy['host']; + $host .= ($this->proxy['port']) ? ':' . $this->proxy['port'] : ''; + curl_setopt($curl_handle, CURLOPT_PROXY, $host); + + if (isset($this->proxy['user']) && isset($this->proxy['pass'])) { + curl_setopt($curl_handle, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']); + } + } + + // Set credentials for HTTP Basic/Digest Authentication. + if ($this->username && $this->password) { + curl_setopt($curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + curl_setopt($curl_handle, CURLOPT_USERPWD, $this->username . ':' . $this->password); + } + + // Handle the encoding if we can. + if (extension_loaded('zlib')) { + curl_setopt($curl_handle, CURLOPT_ENCODING, ''); + } + + // Process custom headers + if (isset($this->request_headers) && count($this->request_headers)) { + $temp_headers = array(); + + foreach ($this->request_headers as $k => $v) { + $temp_headers[] = $k . ': ' . $v; + } + + // fix "Expect: 100-continue" + $temp_headers[] = 'Expect:'; + curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $temp_headers); + } + + switch ($this->method) { + case self::HTTP_PUT: + //unset($this->read_stream); + curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT'); + if (isset($this->read_stream)) { + if (!isset($this->read_stream_size) || $this->read_stream_size < 0) { + throw new RequestCore_Exception('The stream size for the streaming upload cannot be determined.'); + } + curl_setopt($curl_handle, CURLOPT_INFILESIZE, $this->read_stream_size); + curl_setopt($curl_handle, CURLOPT_UPLOAD, true); + } else { + curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body); + } + break; + + case self::HTTP_POST: + curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST'); + if (isset($this->read_stream)) { + if (!isset($this->read_stream_size) || $this->read_stream_size < 0) { + throw new RequestCore_Exception('The stream size for the streaming upload cannot be determined.'); + } + curl_setopt($curl_handle, CURLOPT_INFILESIZE, $this->read_stream_size); + curl_setopt($curl_handle, CURLOPT_UPLOAD, true); + } else { + curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body); + } + break; + + case self::HTTP_HEAD: + curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, self::HTTP_HEAD); + curl_setopt($curl_handle, CURLOPT_NOBODY, 1); + break; + + default: // Assumed GET + curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, $this->method); + if (isset($this->write_stream) || isset($this->write_file)) { + curl_setopt($curl_handle, CURLOPT_WRITEFUNCTION, array($this, 'streaming_write_callback')); + curl_setopt($curl_handle, CURLOPT_HEADER, false); + } else { + curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body); + } + break; + } + + // Merge in the CURLOPTs + if (isset($this->curlopts) && sizeof($this->curlopts) > 0) { + foreach ($this->curlopts as $k => $v) { + curl_setopt($curl_handle, $k, $v); + } + } + + return $curl_handle; + } + + /** + * Take the post-processed cURL data and break it down into useful header/body/info chunks. Uses the + * data stored in the `curl_handle` and `response` properties unless replacement data is passed in via + * parameters. + * + * @param resource|\CurlHandle|null|false $curl_handle (Optional) The reference to the already executed cURL request. Receive CurlHandle instance from PHP8.0 + * @param string $response (Optional) The actual response content itself that needs to be parsed. + * @return ResponseCore A object containing a parsed HTTP response. + */ + public function process_response($curl_handle = null, $response = null) + { + // Accept a custom one if it's passed. + if ($curl_handle && $response) { + $this->response = $response; + } + + // As long as this came back as a valid resource or CurlHandle instance... + if (is_resource($curl_handle) || (is_object($curl_handle) && in_array(get_class($curl_handle),array('CurlHandle','Swoole\Curl\Handler', 'Swoole\Coroutine\Curl\Handle'),true))) { + // Determine what's what. + $header_size = curl_getinfo($curl_handle, CURLINFO_HEADER_SIZE); + $this->response_headers = substr($this->response, 0, $header_size); + $this->response_body = substr($this->response, $header_size); + $this->response_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE); + $this->response_info = curl_getinfo($curl_handle); + + if (intval($this->response_code) / 100 != 2 && isset($this->write_file)) + { + $this->response_headers = $this->response_raw_headers; + $this->response_body = $this->response_error_body; + } + + // Parse out the headers + $this->response_headers = explode("\r\n\r\n", trim($this->response_headers)); + $this->response_headers = array_pop($this->response_headers); + $this->response_headers = explode("\r\n", $this->response_headers); + array_shift($this->response_headers); + + // Loop through and split up the headers. + $header_assoc = array(); + foreach ($this->response_headers as $header) { + $kv = explode(': ', $header); + $header_assoc[strtolower($kv[0])] = isset($kv[1]) ? $kv[1] : ''; + } + + // Reset the headers to the appropriate property. + $this->response_headers = $header_assoc; + $this->response_headers['info'] = $this->response_info; + $this->response_headers['info']['method'] = $this->method; + + if ($curl_handle && $response) { + return new ResponseCore($this->response_headers, $this->response_body, $this->response_code); + } + } + + // Return false + return false; + } + + /** + * Send the request, calling necessary utility functions to update built-in properties. + * + * @param boolean $parse (Optional) Whether to parse the response with ResponseCore or not. + * @return string The resulting unparsed data from the request. + */ + public function send_request($parse = false) + { + set_time_limit(0); + + $curl_handle = $this->prep_request(); + $this->response = curl_exec($curl_handle); + + if ($this->response === false) { + throw new RequestCore_Exception('cURL error: ' . curl_error($curl_handle) . ' (' . curl_errno($curl_handle) . ')'); + } + + $parsed_response = $this->process_response($curl_handle, $this->response); + + curl_close($curl_handle); + unset($curl_handle); + + if ($parse) { + return $parsed_response; + } + + return $this->response; + } + + /*%******************************************************************************************%*/ + // RESPONSE METHODS + + /** + * Get the HTTP response headers from the request. + * + * @param string $header (Optional) A specific header value to return. Defaults to all headers. + * @return string|array All or selected header values. + */ + public function get_response_header($header = null) + { + if ($header) { + return $this->response_headers[strtolower($header)]; + } + return $this->response_headers; + } + + /** + * Get the HTTP response body from the request. + * + * @return string The response body. + */ + public function get_response_body() + { + return $this->response_body; + } + + /** + * Get the HTTP response code from the request. + * + * @return string The HTTP response code. + */ + public function get_response_code() + { + return $this->response_code; + } +} diff --git a/addons/alioss/library/OSS/Http/RequestCore_Exception.php b/addons/alioss/library/OSS/Http/RequestCore_Exception.php new file mode 100644 index 0000000..cb4e83c --- /dev/null +++ b/addons/alioss/library/OSS/Http/RequestCore_Exception.php @@ -0,0 +1,8 @@ +). + * @param string $body (Required) XML-formatted response from OSS. + * @param integer $status (Optional) HTTP response status code from the request. + * @return Mixed Contains an `header` property (HTTP headers as an associative array), a or `body` property, and an `status` code. + */ + public function __construct($header, $body, $status = null) + { + $this->header = $header; + $this->body = $body; + $this->status = $status; + + return $this; + } + + /** + * Did we receive the status code we expected? + * + * @param integer|array $codes (Optional) The status code(s) to expect. Pass an for a single acceptable value, or an of integers for multiple acceptable values. + * @return boolean Whether we received the expected status code or not. + */ + public function isOK($codes = array(200, 201, 204, 206)) + { + if (is_array($codes)) { + return in_array($this->status, $codes); + } + + return $this->status === $codes; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/BucketInfo.php b/addons/alioss/library/OSS/Model/BucketInfo.php new file mode 100644 index 0000000..e211eed --- /dev/null +++ b/addons/alioss/library/OSS/Model/BucketInfo.php @@ -0,0 +1,181 @@ +location = $location; + $this->createDate = $createDate; + $this->name = $name; + } + + /** + * Get bucket location + * + * @return string + */ + public function getLocation() + { + return $this->location; + } + + /** + * Get bucket name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Get bucket creation time. + * + * @return string + */ + public function getCreateDate() + { + return $this->createDate; + } + + /** + * Get bucket storage class. + * + * @return string + */ + public function getStorageClass() + { + return $this->storageClass; + } + + /** + * Get bucket extranet endpoint. + * + * @return string + */ + public function getExtranetEndpoint() + { + return $this->extranetEndpoint; + } + + /** + * Get bucket intranet endpoint. + * + * @return string + */ + public function getIntranetEndpoint() + { + return $this->intranetEndpoint; + } + + /** + * Get bucket intranet endpoint. + * + * @return string + */ + public function getRegion() + { + return $this->region; + } + + + /** + * Parse bucket information from node. + * + * @param xml $xml + * @throws OssException + * @return null + */ + public function parseFromXmlNode($xml) + { + if (isset($xml->Location)) { + $this->location = strval($xml->Location); + } + if (isset($xml->Name)) { + $this->name = strval($xml->Name); + } + if (isset($xml->CreationDate)) { + $this->createDate = strval($xml->CreationDate); + } + if (isset($xml->StorageClass)) { + $this->storageClass = strval($xml->StorageClass); + } + if (isset($xml->ExtranetEndpoint)) { + $this->extranetEndpoint = strval($xml->ExtranetEndpoint); + } + if (isset($xml->IntranetEndpoint)) { + $this->intranetEndpoint = strval($xml->IntranetEndpoint); + } + if (isset($xml->IntranetEndpoint)) { + $this->intranetEndpoint = strval($xml->IntranetEndpoint); + } + if (isset($xml->Region)) { + $this->region = strval($xml->Region); + } + } + + /** + * bucket region + * + * @var string + */ + private $location; + /** + * bucket name + * + * @var string + */ + private $name; + + /** + * bucket creation time + * + * @var string + */ + private $createDate; + + /** + * bucket storage class + * + * @var string + */ + private $storageClass; + + /** + * bucket extranet endpoint + * + * @var string + */ + private $extranetEndpoint; + + /** + * bucket intranet endpoint + * + * @var string + */ + private $intranetEndpoint; + + /** + * bucket region + * + * @var string + */ + private $region; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/BucketListInfo.php b/addons/alioss/library/OSS/Model/BucketListInfo.php new file mode 100644 index 0000000..ce03a0d --- /dev/null +++ b/addons/alioss/library/OSS/Model/BucketListInfo.php @@ -0,0 +1,39 @@ +bucketList = $bucketList; + } + + /** + * Get the BucketInfo list + * + * @return BucketInfo[] + */ + public function getBucketList() + { + return $this->bucketList; + } + + /** + * BucketInfo list + * + * @var array + */ + private $bucketList = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/BucketStat.php b/addons/alioss/library/OSS/Model/BucketStat.php new file mode 100644 index 0000000..60c7e55 --- /dev/null +++ b/addons/alioss/library/OSS/Model/BucketStat.php @@ -0,0 +1,331 @@ +storage; + } + + /** + * Get object count + * + * @return int + */ + public function getObjectCount() + { + return $this->objectCount; + } + + /** + * Get multipart upload count. + * + * @return int + */ + public function getMultipartUploadCount() + { + return $this->multipartUploadCount; + } + + /** + * Get live channel count + * + * @return int + */ + public function getLiveChannelCount() + { + return $this->liveChannelCount; + } + + /** + * Get last modified time + * + * @return int + */ + public function getLastModifiedTime() + { + return $this->lastModifiedTime; + } + + /** + * Get standard storage + * + * @return int + */ + public function getStandardStorage() + { + return $this->standardStorage; + } + + /** + * Get standard object count + * + * @return int + */ + public function getStandardObjectCount() + { + return $this->standardObjectCount; + } + + /** + * Get infrequent access storage + * + * @return int + */ + public function getInfrequentAccessStorage() + { + return $this->infrequentAccessStorage; + } + + /** + * Get infrequent access real storage + * + * @return int + */ + public function getInfrequentAccessRealStorage() + { + return $this->infrequentAccessRealStorage; + } + + /** + * Get infrequent access object count + * + * @return int + */ + public function getInfrequentAccessObjectCount() + { + return $this->infrequentAccessObjectCount; + } + + /** + * Get archive storage + * + * @return int + */ + public function getArchiveStorage() + { + return $this->archiveStorage; + } + + /** + * Get archive real storage + * + * @return int + */ + public function getArchiveRealStorage() + { + return $this->archiveRealStorage; + } + /** + * Get archive object count + * + * @return int + */ + public function getArchiveObjectCount() + { + return $this->archiveObjectCount; + } + + /** + * Get cold archive storage + * + * @return int + */ + public function getColdArchiveStorage() + { + return $this->coldArchiveStorage; + } + + /** + * Get cold archive real storage + * + * @return int + */ + public function getColdArchiveRealStorage() + { + return $this->coldArchiveRealStorage; + } + + /** + * Get cold archive object count + * + * @return int + */ + public function getColdArchiveObjectCount() + { + return $this->coldArchiveObjectCount; + } + + /** + * Parse stat from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (isset($xml->Storage) ) { + $this->storage = intval($xml->Storage); + } + if (isset($xml->ObjectCount) ) { + $this->objectCount = intval($xml->ObjectCount); + } + if (isset($xml->MultipartUploadCount) ) { + $this->multipartUploadCount = intval($xml->MultipartUploadCount); + } + if (isset($xml->LiveChannelCount) ) { + $this->liveChannelCount = intval($xml->LiveChannelCount); + } + if (isset($xml->LastModifiedTime) ) { + $this->lastModifiedTime = intval($xml->LastModifiedTime); + } + if (isset($xml->StandardStorage) ) { + $this->standardStorage = intval($xml->StandardStorage); + } + if (isset($xml->StandardObjectCount) ) { + $this->standardObjectCount = intval($xml->StandardObjectCount); + } + if (isset($xml->InfrequentAccessStorage) ) { + $this->infrequentAccessStorage = intval($xml->InfrequentAccessStorage); + } + if (isset($xml->InfrequentAccessRealStorage) ) { + $this->infrequentAccessRealStorage = intval($xml->InfrequentAccessRealStorage); + } + if (isset($xml->InfrequentAccessObjectCount) ) { + $this->infrequentAccessObjectCount = intval($xml->InfrequentAccessObjectCount); + } + if (isset($xml->ArchiveStorage) ) { + $this->archiveStorage = intval($xml->ArchiveStorage); + } + if (isset($xml->ArchiveRealStorage) ) { + $this->archiveRealStorage = intval($xml->ArchiveRealStorage); + } + if (isset($xml->ArchiveObjectCount) ) { + $this->archiveObjectCount = intval($xml->ArchiveObjectCount); + } + if (isset($xml->ColdArchiveStorage) ) { + $this->coldArchiveStorage = intval($xml->ColdArchiveStorage); + } + if (isset($xml->ColdArchiveRealStorage) ) { + $this->coldArchiveRealStorage = intval($xml->ColdArchiveRealStorage); + } + if (isset($xml->ColdArchiveObjectCount) ) { + $this->coldArchiveObjectCount = intval($xml->ColdArchiveObjectCount); + } + } + + /** + * current storage + * + * @var int + */ + private $storage; + /** + * object count + * + * @var int + */ + private $objectCount; + + /** + * multipart upload count + * + * @var int + */ + private $multipartUploadCount; + + /** + * live channel count + * @var int + */ + private $liveChannelCount; + + /** + * last modified time + * @var int + */ + private $lastModifiedTime; + + /** + * standard storage + * @var int + */ + private $standardStorage; + + /** + * standard object count + * @var int + */ + private $standardObjectCount; + + /** + * infrequent access storage + * @var int + */ + private $infrequentAccessStorage; + + /** + * infrequent access real storage + * @var int + */ + private $infrequentAccessRealStorage; + + /** + * infrequent access object Count + * @var int + */ + private $infrequentAccessObjectCount; + + /** + * archive storage + * @var int + */ + private $archiveStorage; + + /** + * archive real storage + * @var int + */ + private $archiveRealStorage; + + /** + * archive object count + * @var int + */ + private $archiveObjectCount; + + /** + * cold archive storage + * @var int + */ + private $coldArchiveStorage; + + /** + * cold archive real storage + * @var int + */ + private $coldArchiveRealStorage; + + /** + * cold archive object count + * @var int + */ + private $coldArchiveObjectCount; + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/CnameConfig.php b/addons/alioss/library/OSS/Model/CnameConfig.php new file mode 100644 index 0000000..f3597d2 --- /dev/null +++ b/addons/alioss/library/OSS/Model/CnameConfig.php @@ -0,0 +1,99 @@ +cnameList = array(); + } + + /** + * @return array + * @example + * array(2) { + * [0]=> + * array(3) { + * ["Domain"]=> + * string(11) "www.foo.com" + * ["Status"]=> + * string(7) "enabled" + * ["LastModified"]=> + * string(8) "20150101" + * } + * [1]=> + * array(3) { + * ["Domain"]=> + * string(7) "bar.com" + * ["Status"]=> + * string(8) "disabled" + * ["LastModified"]=> + * string(8) "20160101" + * } + * } + */ + public function getCnames() + { + return $this->cnameList; + } + + + public function addCname($cname) + { + if (count($this->cnameList) >= self::OSS_MAX_RULES) { + throw new OssException( + "num of cname in the config exceeds self::OSS_MAX_RULES: " . strval(self::OSS_MAX_RULES)); + } + $this->cnameList[] = array('Domain' => $cname); + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (!isset($xml->Cname)) return; + foreach ($xml->Cname as $entry) { + $cname = array(); + foreach ($entry as $key => $value) { + $cname[strval($key)] = strval($value); + } + $this->cnameList[] = $cname; + } + } + + public function serializeToXml() + { + $strXml = << + + +EOF; + $xml = new \SimpleXMLElement($strXml); + foreach ($this->cnameList as $cname) { + $node = $xml->addChild('Cname'); + foreach ($cname as $key => $value) { + $node->addChild($key, $value); + } + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + const OSS_MAX_RULES = 10; + + private $cnameList = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/CnameTokenInfo.php b/addons/alioss/library/OSS/Model/CnameTokenInfo.php new file mode 100644 index 0000000..295cfbd --- /dev/null +++ b/addons/alioss/library/OSS/Model/CnameTokenInfo.php @@ -0,0 +1,105 @@ +bucket; + } + + /** + * Get cname + * + * @return string + */ + public function getCname() + { + return $this->cname; + } + + /** + * Get token. + * + * @return string + */ + public function getToken() + { + return $this->token; + } + + /** + * Get expireTime. + * + * @return string + */ + public function getExpireTime() + { + return $this->expireTime; + } + + /** + * Parse cname token from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (isset($xml->Bucket) ) { + $this->bucket = strval($xml->Bucket); + } + if (isset($xml->Cname) ) { + $this->cname = strval($xml->Cname); + } + if (isset($xml->Token) ) { + $this->token = strval($xml->Token); + } + if (isset($xml->ExpireTime) ) { + $this->expireTime = strval($xml->ExpireTime); + } + } + + /** + * bucket name + * + * @var string + */ + private $bucket; + /** + * cname + * + * @var string + */ + private $cname; + + /** + * token + * + * @var string + */ + private $token; + + /** + * expire time + * + * @var string + */ + private $expireTime; + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/CorsConfig.php b/addons/alioss/library/OSS/Model/CorsConfig.php new file mode 100644 index 0000000..e0f1892 --- /dev/null +++ b/addons/alioss/library/OSS/Model/CorsConfig.php @@ -0,0 +1,140 @@ +rules = array(); + } + + /** + * Get CorsRule list + * + * @return CorsRule[] + */ + public function getRules() + { + return $this->rules; + } + + + /** + * Add a new CorsRule + * + * @param CorsRule $rule + * @throws OssException + */ + public function addRule($rule) + { + if (count($this->rules) >= self::OSS_MAX_RULES) { + throw new OssException("num of rules in the config exceeds self::OSS_MAX_RULES: " . strval(self::OSS_MAX_RULES)); + } + $this->rules[] = $rule; + } + /** + * @param boolean $value + */ + public function setResponseVary($value) + { + $this->responseVary = $value; + } + + /** + * @return boolean + */ + public function getResponseVary(){ + if (isset($this->responseVary)) { + return $this->responseVary; + } + return false; + } + + /** + * Parse CorsConfig from the xml. + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if(isset($xml->ResponseVary)){ + $this->responseVary = + (strval($xml->ResponseVary) === 'TRUE' || strval($xml->ResponseVary) === 'true') ? true : false; + } + if (!isset($xml->CORSRule)) return; + foreach ($xml->CORSRule as $rule) { + $corsRule = new CorsRule(); + foreach ($rule as $key => $value) { + if ($key === self::OSS_CORS_ALLOWED_HEADER) { + $corsRule->addAllowedHeader(strval($value)); + } elseif ($key === self::OSS_CORS_ALLOWED_METHOD) { + $corsRule->addAllowedMethod(strval($value)); + } elseif ($key === self::OSS_CORS_ALLOWED_ORIGIN) { + $corsRule->addAllowedOrigin(strval($value)); + } elseif ($key === self::OSS_CORS_EXPOSE_HEADER) { + $corsRule->addExposeHeader(strval($value)); + } elseif ($key === self::OSS_CORS_MAX_AGE_SECONDS) { + $corsRule->setMaxAgeSeconds(strval($value)); + } + } + $this->addRule($corsRule); + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + foreach ($this->rules as $rule) { + $xmlRule = $xml->addChild('CORSRule'); + $rule->appendToXml($xmlRule); + } + if(isset($this->responseVary)){ + if ($this->responseVary) { + $xml->addChild('ResponseVary', 'true'); + } else { + $xml->addChild('ResponseVary', 'false'); + } + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + const OSS_CORS_ALLOWED_ORIGIN = 'AllowedOrigin'; + const OSS_CORS_ALLOWED_METHOD = 'AllowedMethod'; + const OSS_CORS_ALLOWED_HEADER = 'AllowedHeader'; + const OSS_CORS_EXPOSE_HEADER = 'ExposeHeader'; + const OSS_CORS_MAX_AGE_SECONDS = 'MaxAgeSeconds'; + const OSS_MAX_RULES = 10; + + /** + * CorsRule list + * + * @var CorsRule[] + */ + private $rules = array(); + private $responseVary; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/CorsRule.php b/addons/alioss/library/OSS/Model/CorsRule.php new file mode 100644 index 0000000..08353a0 --- /dev/null +++ b/addons/alioss/library/OSS/Model/CorsRule.php @@ -0,0 +1,150 @@ +allowedOrigins[] = $allowedOrigin; + } + } + + /** + * Add an allowedMethod rule + * + * @param string $allowedMethod + */ + public function addAllowedMethod($allowedMethod) + { + if (!empty($allowedMethod)) { + $this->allowedMethods[] = $allowedMethod; + } + } + + /** + * Add an allowedHeader rule + * + * @param string $allowedHeader + */ + public function addAllowedHeader($allowedHeader) + { + if (!empty($allowedHeader)) { + $this->allowedHeaders[] = $allowedHeader; + } + } + + /** + * Add an exposeHeader rule + * + * @param string $exposeHeader + */ + public function addExposeHeader($exposeHeader) + { + if (!empty($exposeHeader)) { + $this->exposeHeaders[] = $exposeHeader; + } + } + + /** + * @return int + */ + public function getMaxAgeSeconds() + { + return $this->maxAgeSeconds; + } + + /** + * @param int $maxAgeSeconds + */ + public function setMaxAgeSeconds($maxAgeSeconds) + { + $this->maxAgeSeconds = $maxAgeSeconds; + } + + /** + * Get the AllowedHeaders list + * + * @return string[] + */ + public function getAllowedHeaders() + { + return $this->allowedHeaders; + } + + /** + * Get the AllowedOrigins list + * + * @return string[] + */ + public function getAllowedOrigins() + { + return $this->allowedOrigins; + } + + /** + * Get the AllowedMethods list + * + * @return string[] + */ + public function getAllowedMethods() + { + return $this->allowedMethods; + } + + /** + * Get the ExposeHeaders list + * + * @return string[] + */ + public function getExposeHeaders() + { + return $this->exposeHeaders; + } + + /** + * Serialize all the rules into the xml represented by parameter $xmlRule + * + * @param \SimpleXMLElement $xmlRule + * @throws OssException + */ + public function appendToXml(&$xmlRule) + { + if (!isset($this->maxAgeSeconds)) { + throw new OssException("maxAgeSeconds is not set in the Rule"); + } + foreach ($this->allowedOrigins as $allowedOrigin) { + $xmlRule->addChild(CorsConfig::OSS_CORS_ALLOWED_ORIGIN, $allowedOrigin); + } + foreach ($this->allowedMethods as $allowedMethod) { + $xmlRule->addChild(CorsConfig::OSS_CORS_ALLOWED_METHOD, $allowedMethod); + } + foreach ($this->allowedHeaders as $allowedHeader) { + $xmlRule->addChild(CorsConfig::OSS_CORS_ALLOWED_HEADER, $allowedHeader); + } + foreach ($this->exposeHeaders as $exposeHeader) { + $xmlRule->addChild(CorsConfig::OSS_CORS_EXPOSE_HEADER, $exposeHeader); + } + $xmlRule->addChild(CorsConfig::OSS_CORS_MAX_AGE_SECONDS, strval($this->maxAgeSeconds)); + } + + private $allowedHeaders = array(); + private $allowedOrigins = array(); + private $allowedMethods = array(); + private $exposeHeaders = array(); + private $maxAgeSeconds = null; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/DeleteMarkerInfo.php b/addons/alioss/library/OSS/Model/DeleteMarkerInfo.php new file mode 100644 index 0000000..c129e99 --- /dev/null +++ b/addons/alioss/library/OSS/Model/DeleteMarkerInfo.php @@ -0,0 +1,65 @@ +key = $key; + $this->versionId = $versionId; + $this->lastModified = $lastModified; + $this->isLatest = $isLatest; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getVersionId() + { + return $this->versionId; + } + + /** + * @return string + */ + public function getLastModified() + { + return $this->lastModified; + } + + /** + * @return string + */ + public function getIsLatest() + { + return $this->isLatest; + } + + private $key = ""; + private $versionId = ""; + private $lastModified = ""; + private $isLatest = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/DeleteObjectInfo.php b/addons/alioss/library/OSS/Model/DeleteObjectInfo.php new file mode 100644 index 0000000..806eafb --- /dev/null +++ b/addons/alioss/library/OSS/Model/DeleteObjectInfo.php @@ -0,0 +1,41 @@ +key = $key; + $this->versionId = $versionId; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getVersionId() + { + return $this->versionId; + } + + private $key = ""; + private $versionId = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/DeletedObjectInfo.php b/addons/alioss/library/OSS/Model/DeletedObjectInfo.php new file mode 100644 index 0000000..6bba39a --- /dev/null +++ b/addons/alioss/library/OSS/Model/DeletedObjectInfo.php @@ -0,0 +1,63 @@ +key = $key; + $this->versionId = $versionId; + $this->deleteMarker = $deleteMarker; + $this->deleteMarkerVersionId = $deleteMarkerVersionId; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getVersionId() + { + return $this->versionId; + } + + /** + * @return string + */ + public function getDeleteMarker() + { + return $this->deleteMarker; + } + + /** + * @return string + */ + public function getDeleteMarkerVersionId() + { + return $this->deleteMarkerVersionId; + } + + private $key = ""; + private $versionId = ""; + private $deleteMarker = ""; + private $deleteMarkerVersionId = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ExtendWormConfig.php b/addons/alioss/library/OSS/Model/ExtendWormConfig.php new file mode 100644 index 0000000..5e62287 --- /dev/null +++ b/addons/alioss/library/OSS/Model/ExtendWormConfig.php @@ -0,0 +1,64 @@ +day = $day; + } + + /** + * Parse ExtendWormConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + throw new OssException("Not implemented."); + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if (isset($this->day)) { + $xml->addChild('RetentionPeriodInDays', $this->day); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return int + */ + public function getDay() + { + return $this->day; + } + + private $day = 0; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/GetLiveChannelHistory.php b/addons/alioss/library/OSS/Model/GetLiveChannelHistory.php new file mode 100644 index 0000000..e6d518a --- /dev/null +++ b/addons/alioss/library/OSS/Model/GetLiveChannelHistory.php @@ -0,0 +1,37 @@ +liveRecordList; + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + + if (isset($xml->LiveRecord)) { + foreach ($xml->LiveRecord as $record) { + $liveRecord = new LiveChannelHistory(); + $liveRecord->parseFromXmlNode($record); + $this->liveRecordList[] = $liveRecord; + } + } + } + + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + private $liveRecordList = array(); +} diff --git a/addons/alioss/library/OSS/Model/GetLiveChannelInfo.php b/addons/alioss/library/OSS/Model/GetLiveChannelInfo.php new file mode 100644 index 0000000..0b5edfc --- /dev/null +++ b/addons/alioss/library/OSS/Model/GetLiveChannelInfo.php @@ -0,0 +1,68 @@ +description; + } + + public function getStatus() + { + return $this->status; + } + + public function getType() + { + return $this->type; + } + + public function getFragDuration() + { + return $this->fragDuration; + } + + public function getFragCount() + { + return $this->fragCount; + } + + public function getPlayListName() + { + return $this->playlistName; + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + + $this->description = strval($xml->Description); + $this->status = strval($xml->Status); + + if (isset($xml->Target)) { + foreach ($xml->Target as $target) { + $this->type = strval($target->Type); + $this->fragDuration = strval($target->FragDuration); + $this->fragCount = strval($target->FragCount); + $this->playlistName = strval($target->PlaylistName); + } + } + } + + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + private $description; + private $status; + private $type; + private $fragDuration; + private $fragCount; + private $playlistName; +} diff --git a/addons/alioss/library/OSS/Model/GetLiveChannelStatus.php b/addons/alioss/library/OSS/Model/GetLiveChannelStatus.php new file mode 100644 index 0000000..2ee7a68 --- /dev/null +++ b/addons/alioss/library/OSS/Model/GetLiveChannelStatus.php @@ -0,0 +1,107 @@ +status; + } + + public function getConnectedTime() + { + return $this->connectedTime; + } + + public function getRemoteAddr() + { + return $this->remoteAddr; + } + + public function getVideoWidth() + { + return $this->videoWidth; + } + public function getVideoHeight() + { + return $this->videoHeight; + } + public function getVideoFrameRate() + { + return $this->videoFrameRate; + } + public function getVideoBandwidth() + { + return $this->videoBandwidth; + } + public function getVideoCodec() + { + return $this->videoCodec; + } + + public function getAudioBandwidth() + { + return $this->audioBandwidth; + } + public function getAudioSampleRate() + { + return $this->audioSampleRate; + } + public function getAudioCodec() + { + return $this->audioCodec; + } + + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + $this->status = strval($xml->Status); + $this->connectedTime = strval($xml->ConnectedTime); + $this->remoteAddr = strval($xml->RemoteAddr); + + if (isset($xml->Video)) { + foreach ($xml->Video as $video) { + $this->videoWidth = intval($video->Width); + $this->videoHeight = intval($video->Height); + $this->videoFrameRate = intval($video->FrameRate); + $this->videoBandwidth = intval($video->Bandwidth); + $this->videoCodec = strval($video->Codec); + } + } + + if (isset($xml->Video)) { + foreach ($xml->Audio as $audio) { + $this->audioBandwidth = intval($audio->Bandwidth); + $this->audioSampleRate = intval($audio->SampleRate); + $this->audioCodec = strval($audio->Codec); + } + } + + } + + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + private $status; + private $connectedTime; + private $remoteAddr; + + private $videoWidth; + private $videoHeight; + private $videoFrameRate; + private $videoBandwidth; + private $videoCodec; + + private $audioBandwidth; + private $audioSampleRate; + private $audioCodec; + + +} diff --git a/addons/alioss/library/OSS/Model/InitiateWormConfig.php b/addons/alioss/library/OSS/Model/InitiateWormConfig.php new file mode 100644 index 0000000..572ceed --- /dev/null +++ b/addons/alioss/library/OSS/Model/InitiateWormConfig.php @@ -0,0 +1,64 @@ +day = $day; + } + + /** + * Parse InitiateWormConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + throw new OssException("Not implemented."); + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if (isset($this->day)) { + $xml->addChild('RetentionPeriodInDays', $this->day); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return int + */ + public function getDay() + { + return $this->day; + } + + private $day = 0; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/LifecycleAction.php b/addons/alioss/library/OSS/Model/LifecycleAction.php new file mode 100644 index 0000000..a0e2126 --- /dev/null +++ b/addons/alioss/library/OSS/Model/LifecycleAction.php @@ -0,0 +1,88 @@ +action = $action; + $this->timeSpec = $timeSpec; + $this->timeValue = $timeValue; + } + + /** + * @return LifecycleAction + */ + public function getAction() + { + return $this->action; + } + + /** + * @param string $action + */ + public function setAction($action) + { + $this->action = $action; + } + + /** + * @return string + */ + public function getTimeSpec() + { + return $this->timeSpec; + } + + /** + * @param string $timeSpec + */ + public function setTimeSpec($timeSpec) + { + $this->timeSpec = $timeSpec; + } + + /** + * @return string + */ + public function getTimeValue() + { + return $this->timeValue; + } + + /** + * @param string $timeValue + */ + public function setTimeValue($timeValue) + { + $this->timeValue = $timeValue; + } + + /** + * Use appendToXml to insert actions into xml. + * + * @param \SimpleXMLElement $xmlRule + */ + public function appendToXml(&$xmlRule) + { + $xmlAction = $xmlRule->addChild($this->action); + $xmlAction->addChild($this->timeSpec, $this->timeValue); + } + + private $action; + private $timeSpec; + private $timeValue; + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/LifecycleConfig.php b/addons/alioss/library/OSS/Model/LifecycleConfig.php new file mode 100644 index 0000000..f2d2dc3 --- /dev/null +++ b/addons/alioss/library/OSS/Model/LifecycleConfig.php @@ -0,0 +1,107 @@ +rules = array(); + $xml = simplexml_load_string($strXml); + if (!isset($xml->Rule)) return; + $this->rules = array(); + foreach ($xml->Rule as $rule) { + $id = strval($rule->ID); + $prefix = strval($rule->Prefix); + $status = strval($rule->Status); + $actions = array(); + foreach ($rule as $key => $value) { + if ($key === 'ID' || $key === 'Prefix' || $key === 'Status') continue; + $action = $key; + $timeSpec = null; + $timeValue = null; + foreach ($value as $timeSpecKey => $timeValueValue) { + $timeSpec = $timeSpecKey; + $timeValue = strval($timeValueValue); + } + $actions[] = new LifecycleAction($action, $timeSpec, $timeValue); + } + $this->rules[] = new LifecycleRule($id, $prefix, $status, $actions); + } + return; + } + + + /** + * Serialize the object to xml + * + * @return string + */ + public function serializeToXml() + { + + $xml = new \SimpleXMLElement(''); + foreach ($this->rules as $rule) { + $xmlRule = $xml->addChild('Rule'); + $rule->appendToXml($xmlRule); + } + return $xml->asXML(); + } + + /** + * + * Add a LifecycleRule + * + * @param LifecycleRule $lifecycleRule + * @throws OssException + */ + public function addRule($lifecycleRule) + { + if (!isset($lifecycleRule)) { + throw new OssException("lifecycleRule is null"); + } + $this->rules[] = $lifecycleRule; + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * Get all lifecycle rules. + * + * @return LifecycleRule[] + */ + public function getRules() + { + return $this->rules; + } + + /** + * @var LifecycleRule[] + */ + private $rules; +} + + diff --git a/addons/alioss/library/OSS/Model/LifecycleRule.php b/addons/alioss/library/OSS/Model/LifecycleRule.php new file mode 100644 index 0000000..73c6cc3 --- /dev/null +++ b/addons/alioss/library/OSS/Model/LifecycleRule.php @@ -0,0 +1,126 @@ +id; + } + + /** + * @param string $id Rule Id + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * Get a file prefix + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * Set a file prefix + * + * @param string $prefix The file prefix + */ + public function setPrefix($prefix) + { + $this->prefix = $prefix; + } + + /** + * Get Lifecycle status + * + * @return string + */ + public function getStatus() + { + return $this->status; + } + + /** + * Set Lifecycle status + * + * @param string $status + */ + public function setStatus($status) + { + $this->status = $status; + } + + /** + * + * @return LifecycleAction[] + */ + public function getActions() + { + return $this->actions; + } + + /** + * @param LifecycleAction[] $actions + */ + public function setActions($actions) + { + $this->actions = $actions; + } + + + /** + * LifecycleRule constructor. + * + * @param string $id rule Id + * @param string $prefix File prefix + * @param string $status Rule status, which has the following valid values: [self::LIFECYCLE_STATUS_ENABLED, self::LIFECYCLE_STATUS_DISABLED] + * @param LifecycleAction[] $actions + */ + public function __construct($id, $prefix, $status, $actions) + { + $this->id = $id; + $this->prefix = $prefix; + $this->status = $status; + $this->actions = $actions; + } + + /** + * @param \SimpleXMLElement $xmlRule + */ + public function appendToXml(&$xmlRule) + { + $xmlRule->addChild('ID', $this->id); + $xmlRule->addChild('Prefix', $this->prefix); + $xmlRule->addChild('Status', $this->status); + foreach ($this->actions as $action) { + $action->appendToXml($xmlRule); + } + } + + private $id; + private $prefix; + private $status; + private $actions = array(); + + const LIFECYCLE_STATUS_ENABLED = 'Enabled'; + const LIFECYCLE_STATUS_DISABLED = 'Disabled'; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ListMultipartUploadInfo.php b/addons/alioss/library/OSS/Model/ListMultipartUploadInfo.php new file mode 100644 index 0000000..105d005 --- /dev/null +++ b/addons/alioss/library/OSS/Model/ListMultipartUploadInfo.php @@ -0,0 +1,134 @@ +bucket = $bucket; + $this->keyMarker = $keyMarker; + $this->uploadIdMarker = $uploadIdMarker; + $this->nextKeyMarker = $nextKeyMarker; + $this->nextUploadIdMarker = $nextUploadIdMarker; + $this->delimiter = $delimiter; + $this->prefix = $prefix; + $this->maxUploads = $maxUploads; + $this->isTruncated = $isTruncated; + $this->uploads = $uploads; + } + + /** + * 得到bucket名称 + * + * @return string + */ + public function getBucket() + { + return $this->bucket; + } + + /** + * @return string + */ + public function getKeyMarker() + { + return $this->keyMarker; + } + + /** + * + * @return string + */ + public function getUploadIdMarker() + { + return $this->uploadIdMarker; + } + + /** + * @return string + */ + public function getNextKeyMarker() + { + return $this->nextKeyMarker; + } + + /** + * @return string + */ + public function getNextUploadIdMarker() + { + return $this->nextUploadIdMarker; + } + + /** + * @return string + */ + public function getDelimiter() + { + return $this->delimiter; + } + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * @return int + */ + public function getMaxUploads() + { + return $this->maxUploads; + } + + /** + * @return string + */ + public function getIsTruncated() + { + return $this->isTruncated; + } + + /** + * @return UploadInfo[] + */ + public function getUploads() + { + return $this->uploads; + } + + private $bucket = ""; + private $keyMarker = ""; + private $uploadIdMarker = ""; + private $nextKeyMarker = ""; + private $nextUploadIdMarker = ""; + private $delimiter = ""; + private $prefix = ""; + private $maxUploads = 0; + private $isTruncated = "false"; + private $uploads = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ListPartsInfo.php b/addons/alioss/library/OSS/Model/ListPartsInfo.php new file mode 100644 index 0000000..f1d10ee --- /dev/null +++ b/addons/alioss/library/OSS/Model/ListPartsInfo.php @@ -0,0 +1,97 @@ +bucket = $bucket; + $this->key = $key; + $this->uploadId = $uploadId; + $this->nextPartNumberMarker = $nextPartNumberMarker; + $this->maxParts = $maxParts; + $this->isTruncated = $isTruncated; + $this->listPart = $listPart; + } + + /** + * @return string + */ + public function getBucket() + { + return $this->bucket; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getUploadId() + { + return $this->uploadId; + } + + /** + * @return int + */ + public function getNextPartNumberMarker() + { + return $this->nextPartNumberMarker; + } + + /** + * @return int + */ + public function getMaxParts() + { + return $this->maxParts; + } + + /** + * @return string + */ + public function getIsTruncated() + { + return $this->isTruncated; + } + + /** + * @return array + */ + public function getListPart() + { + return $this->listPart; + } + + private $bucket = ""; + private $key = ""; + private $uploadId = ""; + private $nextPartNumberMarker = 0; + private $maxParts = 0; + private $isTruncated = ""; + private $listPart = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/LiveChannelConfig.php b/addons/alioss/library/OSS/Model/LiveChannelConfig.php new file mode 100644 index 0000000..dadedc9 --- /dev/null +++ b/addons/alioss/library/OSS/Model/LiveChannelConfig.php @@ -0,0 +1,121 @@ +description = $option['description']; + } + if (isset($option['status'])) { + $this->status = $option['status']; + } + if (isset($option['type'])) { + $this->type = $option['type']; + } + if (isset($option['fragDuration'])) { + $this->fragDuration = $option['fragDuration']; + } + if (isset($option['fragCount'])) { + $this->fragCount = $option['fragCount']; + } + if (isset($option['playListName'])) { + $this->playListName = $option['playListName']; + } + } + + public function getDescription() + { + return $this->description; + } + + public function getStatus() + { + return $this->status; + } + + public function getType() + { + return $this->type; + } + + public function getFragDuration() + { + return $this->fragDuration; + } + + public function getFragCount() + { + return $this->fragCount; + } + + public function getPlayListName() + { + return $this->playListName; + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + $this->description = strval($xml->Description); + $this->status = strval($xml->Status); + $target = $xml->Target; + $this->type = strval($target->Type); + $this->fragDuration = intval($target->FragDuration); + $this->fragCount = intval($target->FragCount); + $this->playListName = strval($target->PlayListName); + } + + public function serializeToXml() + { + $strXml = << + + +EOF; + $xml = new \SimpleXMLElement($strXml); + if (isset($this->description)) { + $xml->addChild('Description', $this->description); + } + + if (isset($this->status)) { + $xml->addChild('Status', $this->status); + } + + $node = $xml->addChild('Target'); + $node->addChild('Type', $this->type); + + if (isset($this->fragDuration)) { + $node->addChild('FragDuration', $this->fragDuration); + } + + if (isset($this->fragCount)) { + $node->addChild('FragCount', $this->fragCount); + } + + if (isset($this->playListName)) { + $node->addChild('PlayListName', $this->playListName); + } + + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + private $description; + private $status = "enabled"; + private $type; + private $fragDuration = 5; + private $fragCount = 3; + private $playListName = "playlist.m3u8"; +} diff --git a/addons/alioss/library/OSS/Model/LiveChannelHistory.php b/addons/alioss/library/OSS/Model/LiveChannelHistory.php new file mode 100644 index 0000000..1c1fd4d --- /dev/null +++ b/addons/alioss/library/OSS/Model/LiveChannelHistory.php @@ -0,0 +1,59 @@ +startTime; + } + + public function getEndTime() + { + return $this->endTime; + } + + public function getRemoteAddr() + { + return $this->remoteAddr; + } + + public function parseFromXmlNode($xml) + { + if (isset($xml->StartTime)) { + $this->startTime = strval($xml->StartTime); + } + + if (isset($xml->EndTime)) { + $this->endTime = strval($xml->EndTime); + } + + if (isset($xml->RemoteAddr)) { + $this->remoteAddr = strval($xml->RemoteAddr); + } + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + $this->parseFromXmlNode($xml); + } + + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + private $startTime; + private $endTime; + private $remoteAddr; +} diff --git a/addons/alioss/library/OSS/Model/LiveChannelInfo.php b/addons/alioss/library/OSS/Model/LiveChannelInfo.php new file mode 100644 index 0000000..c63ec54 --- /dev/null +++ b/addons/alioss/library/OSS/Model/LiveChannelInfo.php @@ -0,0 +1,107 @@ +name = $name; + $this->description = $description; + $this->publishUrls = array(); + $this->playUrls = array(); + } + + public function getName() + { + return $this->name; + } + + public function setName($name) + { + $this->name = $name; + } + + public function getPublishUrls() + { + return $this->publishUrls; + } + + public function getPlayUrls() + { + return $this->playUrls; + } + + public function getStatus() + { + return $this->status; + } + + public function getLastModified() + { + return $this->lastModified; + } + + public function getDescription() + { + return $this->description; + } + + public function setDescription($description) + { + $this->description = $description; + } + + public function parseFromXmlNode($xml) + { + if (isset($xml->Name)) { + $this->name = strval($xml->Name); + } + + if (isset($xml->Description)) { + $this->description = strval($xml->Description); + } + + if (isset($xml->Status)) { + $this->status = strval($xml->Status); + } + + if (isset($xml->LastModified)) { + $this->lastModified = strval($xml->LastModified); + } + + if (isset($xml->PublishUrls)) { + foreach ($xml->PublishUrls as $url) { + $this->publishUrls[] = strval($url->Url); + } + } + + if (isset($xml->PlayUrls)) { + foreach ($xml->PlayUrls as $url) { + $this->playUrls[] = strval($url->Url); + } + } + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + $this->parseFromXmlNode($xml); + } + + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + private $name; + private $description; + private $publishUrls; + private $playUrls; + private $status; + private $lastModified; +} diff --git a/addons/alioss/library/OSS/Model/LiveChannelListInfo.php b/addons/alioss/library/OSS/Model/LiveChannelListInfo.php new file mode 100644 index 0000000..f4ee02f --- /dev/null +++ b/addons/alioss/library/OSS/Model/LiveChannelListInfo.php @@ -0,0 +1,107 @@ +bucket; + } + + public function setBucketName($name) + { + $this->bucket = $name; + } + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * @return string + */ + public function getMarker() + { + return $this->marker; + } + + /** + * @return int + */ + public function getMaxKeys() + { + return $this->maxKeys; + } + + /** + * @return mixed + */ + public function getIsTruncated() + { + return $this->isTruncated; + } + + /** + * @return LiveChannelInfo[] + */ + public function getChannelList() + { + return $this->channelList; + } + + /** + * @return string + */ + public function getNextMarker() + { + return $this->nextMarker; + } + + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + + $this->prefix = strval($xml->Prefix); + $this->marker = strval($xml->Marker); + $this->maxKeys = intval($xml->MaxKeys); + $this->isTruncated = (strval($xml->IsTruncated) == 'true'); + $this->nextMarker = strval($xml->NextMarker); + + if (isset($xml->LiveChannel)) { + foreach ($xml->LiveChannel as $chan) { + $channel = new LiveChannelInfo(); + $channel->parseFromXmlNode($chan); + $this->channelList[] = $channel; + } + } + } + + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + private $bucket = ''; + private $prefix = ''; + private $marker = ''; + private $nextMarker = ''; + private $maxKeys = 100; + private $isTruncated = 'false'; + private $channelList = array(); +} diff --git a/addons/alioss/library/OSS/Model/LoggingConfig.php b/addons/alioss/library/OSS/Model/LoggingConfig.php new file mode 100644 index 0000000..ed9fb1d --- /dev/null +++ b/addons/alioss/library/OSS/Model/LoggingConfig.php @@ -0,0 +1,86 @@ +targetBucket = $targetBucket; + $this->targetPrefix = $targetPrefix; + } + + /** + * @param $strXml + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (!isset($xml->LoggingEnabled)) return; + foreach ($xml->LoggingEnabled as $status) { + foreach ($status as $key => $value) { + if ($key === 'TargetBucket') { + $this->targetBucket = strval($value); + } elseif ($key === 'TargetPrefix') { + $this->targetPrefix = strval($value); + } + } + break; + } + } + + /** + * Serialize to xml string + * + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if (isset($this->targetBucket) && isset($this->targetPrefix)) { + $loggingEnabled = $xml->addChild('LoggingEnabled'); + $loggingEnabled->addChild('TargetBucket', $this->targetBucket); + $loggingEnabled->addChild('TargetPrefix', $this->targetPrefix); + } + return $xml->asXML(); + } + + /** + * @return string + */ + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return string + */ + public function getTargetBucket() + { + return $this->targetBucket; + } + + /** + * @return string + */ + public function getTargetPrefix() + { + return $this->targetPrefix; + } + + private $targetBucket = ""; + private $targetPrefix = ""; + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ObjectInfo.php b/addons/alioss/library/OSS/Model/ObjectInfo.php new file mode 100644 index 0000000..9e538bf --- /dev/null +++ b/addons/alioss/library/OSS/Model/ObjectInfo.php @@ -0,0 +1,129 @@ +key = $key; + $this->lastModified = $lastModified; + $this->eTag = $eTag; + $this->type = $type; + $this->size = $size; + $this->storageClass = $storageClass; + $this->owner = $owner; + $this->restoreInfo = $restoreInfo; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getLastModified() + { + return $this->lastModified; + } + + /** + * @return string + */ + public function getETag() + { + return $this->eTag; + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * php7 && 64bit can use it + * @return int + */ + public function getSize() + { + return (int)$this->size; + } + + + /** + * php5.x or 32bit must use it + * @return string + */ + public function getSizeStr() + { + return $this->size; + } + + /** + * @return string + */ + public function getStorageClass() + { + return $this->storageClass; + } + + /** + * @return string + */ + public function getRestoreInfo() + { + return $this->restoreInfo; + } + + + /** + * @return Owner|null + */ + public function getOwner() + { + return $this->owner; + } + + private $key = ""; + private $lastModified = ""; + private $eTag = ""; + private $type = ""; + private $size = "0"; + private $storageClass = ""; + /** + * @var Owner + */ + private $owner; + private $restoreInfo; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ObjectListInfo.php b/addons/alioss/library/OSS/Model/ObjectListInfo.php new file mode 100644 index 0000000..81c5d27 --- /dev/null +++ b/addons/alioss/library/OSS/Model/ObjectListInfo.php @@ -0,0 +1,126 @@ +bucketName = $bucketName; + $this->prefix = $prefix; + $this->marker = $marker; + $this->nextMarker = $nextMarker; + $this->maxKeys = $maxKeys; + $this->delimiter = $delimiter; + $this->isTruncated = $isTruncated; + $this->objectList = $objectList; + $this->prefixList = $prefixList; + } + + /** + * @return string + */ + public function getBucketName() + { + return $this->bucketName; + } + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * @return string + */ + public function getMarker() + { + return $this->marker; + } + + /** + * @return int + */ + public function getMaxKeys() + { + return $this->maxKeys; + } + + /** + * @return string + */ + public function getDelimiter() + { + return $this->delimiter; + } + + /** + * @return mixed + */ + public function getIsTruncated() + { + return $this->isTruncated; + } + + /** + * Get the ObjectInfo list. + * + * @return ObjectInfo[] + */ + public function getObjectList() + { + return $this->objectList; + } + + /** + * Get the PrefixInfo list + * + * @return PrefixInfo[] + */ + public function getPrefixList() + { + return $this->prefixList; + } + + /** + * @return string + */ + public function getNextMarker() + { + return $this->nextMarker; + } + + private $bucketName = ""; + private $prefix = ""; + private $marker = ""; + private $nextMarker = ""; + private $maxKeys = 0; + private $delimiter = ""; + private $isTruncated = null; + private $objectList = array(); + private $prefixList = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ObjectListInfoV2.php b/addons/alioss/library/OSS/Model/ObjectListInfoV2.php new file mode 100644 index 0000000..c1fef22 --- /dev/null +++ b/addons/alioss/library/OSS/Model/ObjectListInfoV2.php @@ -0,0 +1,147 @@ +bucketName = $bucketName; + $this->prefix = $prefix; + $this->maxKeys = $maxKeys; + $this->delimiter = $delimiter; + $this->isTruncated = $isTruncated; + $this->objectList = $objectList; + $this->prefixList = $prefixList; + $this->continuationToken = $continuationToken; + $this->nextContinuationToken = $nextContinuationToken; + $this->startAfter = $startAfter; + $this->keyCount = $keyCount; + } + + /** + * @return string + */ + public function getBucketName() + { + return $this->bucketName; + } + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * @return int + */ + public function getMaxKeys() + { + return $this->maxKeys; + } + + /** + * @return string + */ + public function getDelimiter() + { + return $this->delimiter; + } + + /** + * @return mixed + */ + public function getIsTruncated() + { + return $this->isTruncated; + } + + /** + * Get the ObjectInfo list. + * + * @return ObjectInfo[] + */ + public function getObjectList() + { + return $this->objectList; + } + + /** + * Get the PrefixInfo list + * + * @return PrefixInfo[] + */ + public function getPrefixList() + { + return $this->prefixList; + } + + /** + * @return string + */ + public function getContinuationToken() + { + return $this->continuationToken; + } + + /** + * @return string + */ + public function getNextContinuationToken() + { + return $this->nextContinuationToken; + } + + /** + * @return string + */ + public function getStartAfter() + { + return $this->startAfter; + } + + /** + * @return int + */ + public function getKeyCount() + { + return $this->keyCount; + } + + private $bucketName = ""; + private $prefix = ""; + private $maxKeys = 0; + private $delimiter = ""; + private $isTruncated = null; + private $objectList = array(); + private $prefixList = array(); + private $nextContinuationToken = ""; + private $continuationToken = ""; + private $startAfter = ""; + private $keyCount = 0; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ObjectVersionInfo.php b/addons/alioss/library/OSS/Model/ObjectVersionInfo.php new file mode 100644 index 0000000..663bd0b --- /dev/null +++ b/addons/alioss/library/OSS/Model/ObjectVersionInfo.php @@ -0,0 +1,125 @@ +key = $key; + $this->versionId = $versionId; + $this->lastModified = $lastModified; + $this->eTag = $eTag; + $this->type = $type; + $this->size = $size; + $this->storageClass = $storageClass; + $this->isLatest = $isLatest; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getVersionId() + { + return $this->versionId; + } + + /** + * @return string + */ + public function getLastModified() + { + return $this->lastModified; + } + + /** + * @return string + */ + public function getETag() + { + return $this->eTag; + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * php7 && 64bit can use it + * @return int + */ + public function getSize() + { + return (int)$this->size; + } + + + /** + * php5.x or 32bit must use it + * @return string + */ + public function getSizeStr() + { + return $this->size; + } + + /** + * @return string + */ + public function getStorageClass() + { + return $this->storageClass; + } + + /** + * @return string + */ + public function getIsLatest() + { + return $this->isLatest; + } + + private $key = ""; + private $versionId = ""; + private $lastModified = ""; + private $eTag = ""; + private $type = ""; + private $size = "0"; + private $storageClass = ""; + private $isLatest = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ObjectVersionListInfo.php b/addons/alioss/library/OSS/Model/ObjectVersionListInfo.php new file mode 100644 index 0000000..f976b7e --- /dev/null +++ b/addons/alioss/library/OSS/Model/ObjectVersionListInfo.php @@ -0,0 +1,162 @@ +bucketName = $bucketName; + $this->prefix = $prefix; + $this->keyMarker = $keyMarker; + $this->nextKeyMarker = $nextKeyMarker; + $this->versionIdMarker = $versionIdMarker; + $this->nextVersionIdMarker = $nextVersionIdMarker; + $this->maxKeys = $maxKeys; + $this->delimiter = $delimiter; + $this->isTruncated = $isTruncated; + $this->objectVersionList = $objectversionList; + $this->deleteMarkerList = $deleteMarkerList; + $this->prefixList = $prefixList; + } + + /** + * @return string + */ + public function getBucketName() + { + return $this->bucketName; + } + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * @return string + */ + public function getKeyMarker() + { + return $this->keyMarker; + } + + /** + * @return string + */ + public function getNextKeyMarker() + { + return $this->nextKeyMarker; + } + + /** + * @return string + */ + public function getVersionIdMarker() + { + return $this->versionIdMarker; + } + + /** + * @return string + */ + public function getNextVersionIdMarker() + { + return $this->nextVersionIdMarker; + } + + /** + * @return int + */ + public function getMaxKeys() + { + return $this->maxKeys; + } + + /** + * @return string + */ + public function getDelimiter() + { + return $this->delimiter; + } + + /** + * @return mixed + */ + public function getIsTruncated() + { + return $this->isTruncated; + } + + /** + * Get the ObjectVersionInfo list. + * + * @return ObjectVersionInfo[] + */ + public function getObjectVersionList() + { + return $this->objectVersionList; + } + + /** + * Get the DeleteMarkerInfo list. + * + * @return DeleteMarkerInfo[] + */ + public function getDeleteMarkerList() + { + return $this->deleteMarkerList; + } + + /** + * Get the PrefixInfo list + * + * @return PrefixInfo[] + */ + public function getPrefixList() + { + return $this->prefixList; + } + + private $bucketName = ""; + private $prefix = ""; + private $keyMarker = ""; + private $nextKeyMarker = ""; + private $versionIdMarker = ""; + private $nextVersionIdMarker = ""; + private $maxKeys = 0; + private $delimiter = ""; + private $isTruncated = null; + private $objectVersionList = array(); + private $deleteMarkerList = array(); + private $prefixList = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/Owner.php b/addons/alioss/library/OSS/Model/Owner.php new file mode 100644 index 0000000..5de8bcf --- /dev/null +++ b/addons/alioss/library/OSS/Model/Owner.php @@ -0,0 +1,46 @@ +id = $id; + $this->displayName = $displayName; + } + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @return string + */ + public function getDisplayName() + { + return $this->displayName; + } + + private $id; + private $displayName; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/PartInfo.php b/addons/alioss/library/OSS/Model/PartInfo.php new file mode 100644 index 0000000..07df576 --- /dev/null +++ b/addons/alioss/library/OSS/Model/PartInfo.php @@ -0,0 +1,74 @@ +partNumber = $partNumber; + $this->lastModified = $lastModified; + $this->eTag = $eTag; + $this->size = $size; + } + + /** + * @return int + */ + public function getPartNumber() + { + return $this->partNumber; + } + + /** + * @return string + */ + public function getLastModified() + { + return $this->lastModified; + } + + /** + * @return string + */ + public function getETag() + { + return $this->eTag; + } + + /** + * php7 && 64bit can use it + * @return int + */ + public function getSize() + { + return (int)$this->size; + } + + + /** + * php5.x or 32bit must use it + * @return string + */ + public function getSizeStr() + { + return $this->size; + } + + private $partNumber = 0; + private $lastModified = ""; + private $eTag = ""; + private $size = "0"; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/PrefixInfo.php b/addons/alioss/library/OSS/Model/PrefixInfo.php new file mode 100644 index 0000000..27920b9 --- /dev/null +++ b/addons/alioss/library/OSS/Model/PrefixInfo.php @@ -0,0 +1,36 @@ +prefix = $prefix; + } + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + private $prefix; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/RefererConfig.php b/addons/alioss/library/OSS/Model/RefererConfig.php new file mode 100644 index 0000000..0830143 --- /dev/null +++ b/addons/alioss/library/OSS/Model/RefererConfig.php @@ -0,0 +1,93 @@ +AllowEmptyReferer)) return; + if (!isset($xml->RefererList)) return; + $this->allowEmptyReferer = + (strval($xml->AllowEmptyReferer) === 'TRUE' || strval($xml->AllowEmptyReferer) === 'true') ? true : false; + + foreach ($xml->RefererList->Referer as $key => $refer) { + $this->refererList[] = strval($refer); + } + } + + + /** + * serialize the RefererConfig object into xml string + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if ($this->allowEmptyReferer) { + $xml->addChild('AllowEmptyReferer', 'true'); + } else { + $xml->addChild('AllowEmptyReferer', 'false'); + } + $refererList = $xml->addChild('RefererList'); + foreach ($this->refererList as $referer) { + $refererList->addChild('Referer', $referer); + } + return $xml->asXML(); + } + + /** + * @return string + */ + function __toString() + { + return $this->serializeToXml(); + } + + /** + * @param boolean $allowEmptyReferer + */ + public function setAllowEmptyReferer($allowEmptyReferer) + { + $this->allowEmptyReferer = $allowEmptyReferer; + } + + /** + * @param string $referer + */ + public function addReferer($referer) + { + $this->refererList[] = $referer; + } + + /** + * @return boolean + */ + public function isAllowEmptyReferer() + { + return $this->allowEmptyReferer; + } + + /** + * @return array + */ + public function getRefererList() + { + return $this->refererList; + } + + private $allowEmptyReferer = true; + private $refererList = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/RequestPaymentConfig.php b/addons/alioss/library/OSS/Model/RequestPaymentConfig.php new file mode 100644 index 0000000..6b32060 --- /dev/null +++ b/addons/alioss/library/OSS/Model/RequestPaymentConfig.php @@ -0,0 +1,68 @@ +payer = $payer; + } + + /** + * Parse ServerSideEncryptionConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (isset($xml->Payer)) { + $this->payer = strval($xml->Payer); + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if (isset($this->payer)) { + $xml->addChild('Payer', $this->payer); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return string + */ + public function getPayer() + { + return $this->payer; + } + + private $payer = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/RestoreConfig.php b/addons/alioss/library/OSS/Model/RestoreConfig.php new file mode 100644 index 0000000..156852a --- /dev/null +++ b/addons/alioss/library/OSS/Model/RestoreConfig.php @@ -0,0 +1,77 @@ +day = $day; + $this->tier = $tier; + } + + /** + * Parse RestoreConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + throw new OssException("Not implemented."); + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + $xml->addChild('Days', strval($this->day)); + if (isset($this->tier)) { + $xml_param = $xml->addChild('JobParameters'); + $xml_param->addChild('Tier', $this->tier); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return int + */ + public function getDay() + { + return $this->day; + } + + /** + * @return string + */ + public function getTier() + { + return $this->tier; + } + + private $day = 1; + private $tier = 'Standard'; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/ServerSideEncryptionConfig.php b/addons/alioss/library/OSS/Model/ServerSideEncryptionConfig.php new file mode 100644 index 0000000..e3a190b --- /dev/null +++ b/addons/alioss/library/OSS/Model/ServerSideEncryptionConfig.php @@ -0,0 +1,91 @@ +sseAlgorithm = $sseAlgorithm; + $this->kmsMasterKeyID = $kmsMasterKeyID; + } + + /** + * Parse ServerSideEncryptionConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (!isset($xml->ApplyServerSideEncryptionByDefault)) return; + foreach ($xml->ApplyServerSideEncryptionByDefault as $default) { + foreach ($default as $key => $value) { + if ($key === 'SSEAlgorithm') { + $this->sseAlgorithm = strval($value); + } elseif ($key === 'KMSMasterKeyID') { + $this->kmsMasterKeyID = strval($value); + } + } + break; + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + $default = $xml->addChild('ApplyServerSideEncryptionByDefault'); + if (isset($this->sseAlgorithm)) { + $default->addChild('SSEAlgorithm', $this->sseAlgorithm); + } + if (isset($this->kmsMasterKeyID)) { + $default->addChild('KMSMasterKeyID', $this->kmsMasterKeyID); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return string + */ + public function getSSEAlgorithm() + { + return $this->sseAlgorithm; + } + + /** + * @return string + */ + public function getKMSMasterKeyID() + { + return $this->kmsMasterKeyID; + } + + private $sseAlgorithm = ""; + private $kmsMasterKeyID = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/StorageCapacityConfig.php b/addons/alioss/library/OSS/Model/StorageCapacityConfig.php new file mode 100644 index 0000000..39a9e72 --- /dev/null +++ b/addons/alioss/library/OSS/Model/StorageCapacityConfig.php @@ -0,0 +1,76 @@ +storageCapacity = $storageCapacity; + } + + /** + * Not implemented + */ + public function parseFromXml($strXml) + { + throw new OssException("Not implemented."); + } + + /** + * Serialize StorageCapacityConfig into xml + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + $xml->addChild('StorageCapacity', strval($this->storageCapacity)); + return $xml->asXML(); + } + + /** + * To string + * + * @return string + */ + function __toString() + { + return $this->serializeToXml(); + } + + /** + * Set storage capacity + * + * @param int $storageCapacity + */ + public function setStorageCapacity($storageCapacity) + { + $this->storageCapacity = $storageCapacity; + } + + /** + * Get storage capacity + * + * @return int + */ + public function getStorageCapacity() + { + return $this->storageCapacity; + } + + private $storageCapacity = 0; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/Tag.php b/addons/alioss/library/OSS/Model/Tag.php new file mode 100644 index 0000000..509bd6e --- /dev/null +++ b/addons/alioss/library/OSS/Model/Tag.php @@ -0,0 +1,41 @@ +key = $key; + $this->value = $value; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getValue() + { + return $this->value; + } + + private $key = ""; + private $value = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/TaggingConfig.php b/addons/alioss/library/OSS/Model/TaggingConfig.php new file mode 100644 index 0000000..09fa323 --- /dev/null +++ b/addons/alioss/library/OSS/Model/TaggingConfig.php @@ -0,0 +1,89 @@ +tags = array(); + } + + /** + * Get Tag list + * + * @return Tag[] + */ + public function getTags() + { + return $this->tags; + } + + + /** + * Add a new Tag + * + * @param Tag $tag + * @throws OssException + */ + public function addTag($tag) + { + $this->tags[] = $tag; + } + + /** + * Parse TaggingConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (!isset($xml->TagSet) || !isset($xml->TagSet->Tag)) return; + foreach ($xml->TagSet->Tag as $tag) { + $this->addTag(new Tag($tag->Key, $tag->Value)); + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + $xmlTagSet = $xml->addChild('TagSet'); + foreach ($this->tags as $tag) { + $xmlTag = $xmlTagSet->addChild('Tag'); + $xmlTag->addChild('Key', strval($tag->getKey())); + $xmlTag->addChild('Value', strval($tag->getValue())); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * Tag list + * + * @var Tag[] + */ + private $tags = array(); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/TransferAccelerationConfig.php b/addons/alioss/library/OSS/Model/TransferAccelerationConfig.php new file mode 100644 index 0000000..187fb24 --- /dev/null +++ b/addons/alioss/library/OSS/Model/TransferAccelerationConfig.php @@ -0,0 +1,73 @@ +Enabled)) { + $this->enabled = (strval($xml->Enabled) === 'TRUE' || strval($xml->Enabled) === 'true') ? true : false; + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if (isset($this->enabled)) { + if($this->enabled === true){ + $xml->addChild('Enabled','true'); + } else { + $xml->addChild('Enabled','false'); + } + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + + /** + * @return bool + */ + public function getEnabled() + { + return $this->enabled; + } + + /** + * @param boolean enabled + */ + public function setEnabled($enabled) + { + $this->enabled = $enabled; + } + + /** + * @var $enabled boolean + */ + private $enabled = false; +} + + diff --git a/addons/alioss/library/OSS/Model/UploadInfo.php b/addons/alioss/library/OSS/Model/UploadInfo.php new file mode 100644 index 0000000..49aa414 --- /dev/null +++ b/addons/alioss/library/OSS/Model/UploadInfo.php @@ -0,0 +1,55 @@ +key = $key; + $this->uploadId = $uploadId; + $this->initiated = $initiated; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @return string + */ + public function getUploadId() + { + return $this->uploadId; + } + + /** + * @return string + */ + public function getInitiated() + { + return $this->initiated; + } + + private $key = ""; + private $uploadId = ""; + private $initiated = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/VersioningConfig.php b/addons/alioss/library/OSS/Model/VersioningConfig.php new file mode 100644 index 0000000..992a80f --- /dev/null +++ b/addons/alioss/library/OSS/Model/VersioningConfig.php @@ -0,0 +1,67 @@ +status = $status; + } + + /** + * Parse VersioningConfig from the xml. + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (isset($xml->Status)) { + $this->status = strval($xml->Status); + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + if (isset($this->status)) { + $xml->addChild('Status', $this->status); + } + return $xml->asXML(); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return string + */ + public function getStatus() + { + return $this->status; + } + + private $status = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/WebsiteConfig.php b/addons/alioss/library/OSS/Model/WebsiteConfig.php new file mode 100644 index 0000000..e298eb4 --- /dev/null +++ b/addons/alioss/library/OSS/Model/WebsiteConfig.php @@ -0,0 +1,76 @@ +indexDocument = $indexDocument; + $this->errorDocument = $errorDocument; + } + + /** + * @param string $strXml + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + if (isset($xml->IndexDocument) && isset($xml->IndexDocument->Suffix)) { + $this->indexDocument = strval($xml->IndexDocument->Suffix); + } + if (isset($xml->ErrorDocument) && isset($xml->ErrorDocument->Key)) { + $this->errorDocument = strval($xml->ErrorDocument->Key); + } + } + + /** + * Serialize the WebsiteConfig object into xml string. + * + * @return string + * @throws OssException + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + $index_document_part = $xml->addChild('IndexDocument'); + $error_document_part = $xml->addChild('ErrorDocument'); + $index_document_part->addChild('Suffix', $this->indexDocument); + $error_document_part->addChild('Key', $this->errorDocument); + return $xml->asXML(); + } + + /** + * @return string + */ + public function getIndexDocument() + { + return $this->indexDocument; + } + + /** + * @return string + */ + public function getErrorDocument() + { + return $this->errorDocument; + } + + private $indexDocument = ""; + private $errorDocument = ""; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/WormConfig.php b/addons/alioss/library/OSS/Model/WormConfig.php new file mode 100644 index 0000000..6a48956 --- /dev/null +++ b/addons/alioss/library/OSS/Model/WormConfig.php @@ -0,0 +1,90 @@ +WormId)) { + $this->wormId = strval($xml->WormId); + } + if (isset($xml->State)) { + $this->state = strval($xml->State); + } + if (isset($xml->RetentionPeriodInDays)) { + $this->day = intval($xml->RetentionPeriodInDays); + } + if (isset($xml->CreationDate)) { + $this->creationDate = strval($xml->CreationDate); + } + } + + /** + * Serialize the object into xml string. + * + * @return string + */ + public function serializeToXml() + { + throw new OssException("Not implemented."); + } + + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * @return string + */ + public function getWormId() + { + return $this->wormId; + } + + /** + * @return string + */ + public function getState() + { + return $this->state; + } + + /** + * @return int + */ + public function getDay() + { + return $this->day; + } + + /** + * @return string + */ + public function getCreationDate() + { + return $this->creationDate; + } + + private $wormId = ''; + private $state = ''; + private $creationDate = ''; + private $day = 0; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Model/XmlConfig.php b/addons/alioss/library/OSS/Model/XmlConfig.php new file mode 100644 index 0000000..8c0a0db --- /dev/null +++ b/addons/alioss/library/OSS/Model/XmlConfig.php @@ -0,0 +1,27 @@ + $endpoint, + 'cname' => $isCName, + 'request_proxy' => $requestProxy, + 'provider' => $provider + ); + $this->__initNewClient($config); + } + + /** + * @param array $config + * @throws OssException + */ + private function __initNewClient($config = array()) + { + $isCName = isset($config['cname']) ? $config['cname'] : false; + $endpoint = isset($config['endpoint']) ? $config['endpoint'] : ''; + $requestProxy = isset($config['request_proxy']) ? $config['request_proxy'] : null; + $provider = isset($config['provider']) ? $config['provider'] : ''; + if (empty($endpoint)) { + throw new OssException("endpoint is empty"); + } + $this->hostname = $this->checkEndpoint($endpoint, $isCName); + if (isset($config['forcePathStyle'])) { + if ($config['forcePathStyle'] === true) { + $this->hostType = self::OSS_HOST_TYPE_PATH_STYLE; + } + } + $this->requestProxy = $requestProxy; + if (!$provider instanceof CredentialsProvider) { + throw new OssException("provider must be an instance of CredentialsProvider"); + } + $this->provider = $provider; + + $this->region = isset($config['region']) ? $config['region'] : ''; + $this->cloudBoxId = isset($config['cloudBoxId']) ? $config['cloudBoxId'] : ''; + + // $enableStrictObjName + $this->enableStrictObjName = true; + if (isset($config['strictObjectName'])) { + if ($config['strictObjectName'] === false) { + $this->enableStrictObjName = false; + } + } + + // sign version + $signatureVersion = self::OSS_SIGNATURE_VERSION_V1; + if (isset($config['signatureVersion']) && $config['signatureVersion'] === self::OSS_SIGNATURE_VERSION_V4) { + $signatureVersion = self::OSS_SIGNATURE_VERSION_V4; + } + if ($signatureVersion === self::OSS_SIGNATURE_VERSION_V4) { + $this->enableStrictObjName = false; + $this->signer = new SignerV4(); + } else { + $this->signer = new SignerV1(); + } + + //checkObjectEncoding + $this->checkObjectEncoding = false; + if (isset($config['checkObjectEncoding'])) { + if ($config['checkObjectEncoding'] === true) { + $this->checkObjectEncoding = true; + } + } + + //filePathCompatible + $this->filePathCompatible = false; + if (version_compare(phpversion(), '7.0.0', '<')) { + if (OssUtil::isWin()) { + $this->filePathCompatible = true; + } + } + if (isset($config['filePathCompatible'])) { + if ($config['filePathCompatible'] === true) { + $this->filePathCompatible = true; + } else if ($config['filePathCompatible'] === false) { + $this->filePathCompatible = false; + } + } + + self::checkEnv(); + } + + /** + * Lists the Bucket [GetService]. Not applicable if the endpoint is CName (because CName must be binded to a specific bucket). + * + * @param array $options + * @return BucketListInfo|null + * @throws OssException|RequestCore_Exception + */ + public function listBuckets($options = NULL) + { + if ($this->hostType === self::OSS_HOST_TYPE_CNAME) { + throw new OssException("operation is not permitted with CName host"); + } + $this->precheckOptions($options); + $options[self::OSS_BUCKET] = ''; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $response = $this->auth($options); + $result = new ListBucketsResult($response); + return $result->getData(); + } + + /** + * Creates bucket,The ACL of the bucket created by default is OssClient::OSS_ACL_TYPE_PRIVATE + * + * @param string $bucket + * @param string $acl + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function createBucket($bucket, $acl = self::OSS_ACL_TYPE_PRIVATE, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_HEADERS][self::OSS_ACL] = $acl; + if (isset($options[self::OSS_STORAGE])) { + $this->precheckStorage($options[self::OSS_STORAGE]); + $options[self::OSS_CONTENT] = OssUtil::createBucketXmlBody($options[self::OSS_STORAGE]); + unset($options[self::OSS_STORAGE]); + } + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Deletes bucket + * The deletion will not succeed if the bucket is not empty (either has objects or parts) + * To delete a bucket, all its objects and parts must be deleted first. + * + * @param string $bucket + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucket($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Checks if a bucket exists + * + * @param string $bucket + * @return bool|null + * @throws OssException|RequestCore_Exception + */ + public function doesBucketExist($bucket) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new ExistResult($response); + return $result->getData(); + } + + /** + * Get the data center location information for the bucket + * + * @param string $bucket + * @param array $options + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketLocation($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'location'; + $response = $this->auth($options); + $result = new GetLocationResult($response); + return $result->getData(); + } + + /** + * Get the Meta information for the Bucket + * + * @param string $bucket + * @param array $options Refer to the SDK documentation + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketMeta($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_HEAD; + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * Gets the bucket ACL + * + * @param string $bucket + * @param array $options + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketAcl($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new AclResult($response); + return $result->getData(); + } + + /** + * Sets the bucket ACL + * + * @param string $bucket bucket name + * @param string $acl access permissions, valid values are ['private', 'public-read', 'public-read-write'] + * @param array $options by default is empty + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putBucketAcl($bucket, $acl, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_HEADERS][self::OSS_ACL] = $acl; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets object ACL + * + * @param string $bucket + * @param string $object + * @param array $options + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getObjectAcl($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options, true); + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new AclResult($response); + return $result->getData(); + } + + /** + * Sets the object ACL + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $acl access permissions, valid values are ['default', 'private', 'public-read', 'public-read-write'] + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putObjectAcl($bucket, $object, $acl, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options, true); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_HEADERS][self::OSS_OBJECT_ACL] = $acl; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the bucket logging config + * + * @param string $bucket bucket name + * @param array $options by default is empty + * @return LoggingConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketLogging($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'logging'; + $response = $this->auth($options); + $result = new GetLoggingResult($response); + return $result->getData(); + } + + /** + * Sets the bycket logging config. Only owner can call this API. + * + * @param string $bucket bucket name + * @param string $targetBucket The logging file's bucket + * @param string $targetPrefix The logging file's prefix + * @param array $options By default is empty. + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putBucketLogging($bucket, $targetBucket, $targetPrefix, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $this->precheckBucket($targetBucket, 'targetbucket is not allowed empty'); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'logging'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + + $loggingConfig = new LoggingConfig($targetBucket, $targetPrefix); + $options[self::OSS_CONTENT] = $loggingConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Deletes the bucket logging config + * + * @param string $bucket bucket name + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketLogging($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'logging'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Sets the website config in bucket---that is could make the bucket as a static website once the CName is binded. + * + * @param string $bucket bucket name + * @param WebsiteConfig $websiteConfig + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putBucketWebsite($bucket, $websiteConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'website'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $websiteConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the website config in the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return WebsiteConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketWebsite($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'website'; + $response = $this->auth($options); + $result = new GetWebsiteResult($response); + return $result->getData(); + } + + /** + * Deletes the website config in the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketWebsite($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'website'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Sets the cross-origin-resource-sharing (CORS) rule. It would overwrite the originl one. + * + * @param string $bucket bucket name + * @param CorsConfig $corsConfig CORS config. Check out the details from OSS API document + * @param array $options array + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putBucketCors($bucket, $corsConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'cors'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $corsConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the bucket CORS config + * + * @param string $bucket bucket name + * @param array $options + * @return CorsConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketCors($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'cors'; + $response = $this->auth($options); + $result = new GetCorsResult($response); + return $result->getData(); + } + + /** + * Deletes the bucket's CORS config and disable the CORS on the bucket. + * + * @param string $bucket bucket name + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketCors($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'cors'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Bind a CName for the bucket + * + * @param string $bucket bucket name + * @param string $cname + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function addBucketCname($bucket, $cname, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $cnameConfig = new CnameConfig(); + $cnameConfig->addCname($cname); + $options[self::OSS_CONTENT] = $cnameConfig->serializeToXml(); + $options[self::OSS_COMP] = 'add'; + $options[self::OSS_CNAME] = ''; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the binded CName list of the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return CnameConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketCname($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_CNAME] = ''; + $response = $this->auth($options); + $result = new GetCnameResult($response); + return $result->getData(); + } + + /** + * Remove a CName binding from the bucket + * + * @param string $bucket bucket name + * @param CnameConfig $cname + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketCname($bucket, $cname, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $cnameConfig = new CnameConfig(); + $cnameConfig->addCname($cname); + $options[self::OSS_CONTENT] = $cnameConfig->serializeToXml(); + $options[self::OSS_COMP] = 'delete'; + $options[self::OSS_CNAME] = ''; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * create a cname token for a bucket + * + * @param string $bucket bucket name + * @param array $options + * @return CnameTokenInfo|null + * @throws OssException|RequestCore_Exception + */ + public function createBucketCnameToken($bucket, $cname, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $cnameConfig = new CnameConfig(); + $cnameConfig->addCname($cname); + $options[self::OSS_CONTENT] = $cnameConfig->serializeToXml(); + $options[self::OSS_COMP] = 'token'; + $options[self::OSS_CNAME] = ''; + $response = $this->auth($options); + $result = new CreateBucketCnameTokenResult($response); + return $result->getData(); + } + + /** + * get a cname token for a bucket + * + * @param string $bucket bucket name + * @param array $options + * @return CnameTokenInfo|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketCnameToken($bucket, $cname, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_COMP] = 'token'; + $options[self::OSS_CNAME] = $cname; + $response = $this->auth($options); + $result = new GetBucketCnameTokenResult($response); + return $result->getData(); + } + + /** + * Creates a Live Channel under a bucket + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param LiveChannelConfig $channelConfig + * @param array $options + * @return LiveChannelInfo|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketLiveChannel($bucket, $channelName, $channelConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $channelName; + $options[self::OSS_SUB_RESOURCE] = 'live'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $channelConfig->serializeToXml(); + + $response = $this->auth($options); + $result = new PutLiveChannelResult($response); + $info = $result->getData(); + $info->setName($channelName); + $info->setDescription($channelConfig->getDescription()); + + return $info; + } + + /** + * Sets the LiveChannel status + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param string channelStatus $channelStatus enabled or disabled + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putLiveChannelStatus($bucket, $channelName, $channelStatus, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $channelName; + $options[self::OSS_SUB_RESOURCE] = 'live'; + $options[self::OSS_LIVE_CHANNEL_STATUS] = $channelStatus; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the LiveChannel information by the channel name + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param array $options + * @return GetLiveChannelInfo|null + * @throws OssException|RequestCore_Exception + */ + public function getLiveChannelInfo($bucket, $channelName, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_OBJECT] = $channelName; + $options[self::OSS_SUB_RESOURCE] = 'live'; + + $response = $this->auth($options); + $result = new GetLiveChannelInfoResult($response); + return $result->getData(); + } + + /** + * Gets the status of LiveChannel + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param array $options + * @return GetLiveChannelStatus|null + * @throws OssException|RequestCore_Exception + */ + public function getLiveChannelStatus($bucket, $channelName, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_OBJECT] = $channelName; + $options[self::OSS_SUB_RESOURCE] = 'live'; + $options[self::OSS_COMP] = 'stat'; + + $response = $this->auth($options); + $result = new GetLiveChannelStatusResult($response); + return $result->getData(); + } + + /** + * Gets the LiveChannel pushing streaming record + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param array $options + * @return GetLiveChannelHistory|null + * @throws OssException|RequestCore_Exception + */ + public function getLiveChannelHistory($bucket, $channelName, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_OBJECT] = $channelName; + $options[self::OSS_SUB_RESOURCE] = 'live'; + $options[self::OSS_COMP] = 'history'; + + $response = $this->auth($options); + $result = new GetLiveChannelHistoryResult($response); + return $result->getData(); + } + + /** + *Gets the live channel list under a bucket. + * + * @param string $bucket bucket name + * @param array $options + * @return LiveChannelListInfo|null + * @throws OssException|RequestCore_Exception + */ + public function listBucketLiveChannels($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'live'; + $options[self::OSS_QUERY_STRING] = array( + 'prefix' => isset($options['prefix']) ? $options['prefix'] : '', + 'marker' => isset($options['marker']) ? $options['marker'] : '', + 'max-keys' => isset($options['max-keys']) ? $options['max-keys'] : '', + ); + $response = $this->auth($options); + $result = new ListLiveChannelResult($response); + $list = $result->getData(); + $list->setBucketName($bucket); + + return $list; + } + + /** + * Creates a play list file for the LiveChannel + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param string $playlistName The playlist name, must end with ".m3u8". + * @param array $setTime startTime and EndTime in unix time. No more than 1 day. + * @return null + * @throws OssException|RequestCore_Exception + */ + public function postVodPlaylist($bucket, $channelName, $playlistName, $setTime) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_OBJECT] = $channelName . '/' . $playlistName; + $options[self::OSS_SUB_RESOURCE] = 'vod'; + $options[self::OSS_LIVE_CHANNEL_END_TIME] = $setTime['EndTime']; + $options[self::OSS_LIVE_CHANNEL_START_TIME] = $setTime['StartTime']; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Deletes the Bucket LiveChannel + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketLiveChannel($bucket, $channelName, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_OBJECT] = $channelName; + $options[self::OSS_SUB_RESOURCE] = 'live'; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Generates the signed pushing streaming url + * + * @param string $bucket bucket name + * @param string channelName $channelName + * @param int timeout timeout value in seconds + * @param array $options + * @return string The signed pushing streaming url + * @throws OssException + */ + public function signRtmpUrl($bucket, $channelName, $timeout = 60, $options = NULL) + { + $this->precheckCommon($bucket, $channelName, $options, false); + $expires = time() + $timeout; + $proto = 'rtmp://'; + $hostname = $this->generateHostname($bucket); + $cano_params = ''; + $query_items = array(); + $params = isset($options['params']) ? $options['params'] : array(); + uksort($params, 'strnatcasecmp'); + foreach ($params as $key => $value) { + $cano_params = $cano_params . $key . ':' . $value . "\n"; + $query_items[] = rawurlencode($key) . '=' . rawurlencode($value); + } + $resource = '/' . $bucket . '/' . $channelName; + + $string_to_sign = $expires . "\n" . $cano_params . $resource; + $cred = $this->provider->getCredentials(); + $this->checkCredentials($cred); + + $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $cred->getAccessKeySecret(), true)); + + $query_items[] = 'OSSAccessKeyId=' . rawurlencode($cred->getAccessKeyId()); + $query_items[] = 'Expires=' . rawurlencode($expires); + $query_items[] = 'Signature=' . rawurlencode($signature); + + return $proto . $hostname . '/live/' . $channelName . '?' . implode('&', $query_items); + } + + /** + * Generates the signed pushing streaming url + * + * @param string $bucket bucket name + * @param string $channelName channel name + * @param int $expiration expiration time of the Url, unix epoch, since 1970.1.1 00.00.00 UTC + * @param array $options + * @return string The signed pushing streaming url + * @throws OssException + */ + public function generatePresignedRtmpUrl($bucket, $channelName, $expiration, $options = NULL) + { + $this->precheckCommon($bucket, $channelName, $options, false); + $proto = 'rtmp://'; + $hostname = $this->generateHostname($bucket); + $cano_params = ''; + $query_items = array(); + $params = isset($options['params']) ? $options['params'] : array(); + uksort($params, 'strnatcasecmp'); + foreach ($params as $key => $value) { + $cano_params = $cano_params . $key . ':' . $value . "\n"; + $query_items[] = rawurlencode($key) . '=' . rawurlencode($value); + } + $resource = '/' . $bucket . '/' . $channelName; + + $string_to_sign = $expiration . "\n" . $cano_params . $resource; + $cred = $this->provider->getCredentials(); + $this->checkCredentials($cred); + + $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $cred->getAccessKeySecret(), true)); + + $query_items[] = 'OSSAccessKeyId=' . rawurlencode($cred->getAccessKeyId()); + $query_items[] = 'Expires=' . rawurlencode($expiration); + $query_items[] = 'Signature=' . rawurlencode($signature); + + return $proto . $hostname . '/live/' . $channelName . '?' . implode('&', $query_items); + } + + /** + * Precheck the CORS request. Before sending a CORS request, a preflight request (OPTIONS) is sent with the specific origin. + * HTTP METHOD and headers information are sent to OSS as well for evaluating if the CORS request is allowed. + * + * Note: OSS could enable the CORS on the bucket by calling putBucketCors. Once CORS is enabled, the OSS could evaluate accordingto the preflight request. + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $origin the origin of the request + * @param string $request_method The actual HTTP method which will be used in CORS request + * @param string $request_headers The actual HTTP headers which will be used in CORS request + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function optionsObject($bucket, $object, $origin, $request_method, $request_headers, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_OPTIONS; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_HEADERS][self::OSS_OPTIONS_ORIGIN] = $origin; + $options[self::OSS_HEADERS][self::OSS_OPTIONS_REQUEST_HEADERS] = $request_headers; + $options[self::OSS_HEADERS][self::OSS_OPTIONS_REQUEST_METHOD] = $request_method; + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * Sets the bucket's lifecycle config + * + * @param string $bucket bucket name + * @param LifecycleConfig $lifecycleConfig LifecycleConfig instance + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketLifecycle($bucket, $lifecycleConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $lifecycleConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets bucket's lifecycle config + * + * @param string $bucket bucket name + * @param array $options + * @return LifecycleConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketLifecycle($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; + $response = $this->auth($options); + $result = new GetLifecycleResult($response); + return $result->getData(); + } + + /** + * Deletes the bucket's lifecycle config + * + * @param string $bucket bucket name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketLifecycle($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Sets a bucket's referer, which has a whitelist of referrer and specifies if empty referer is allowed. + * Checks out API document for more details about "Bucket Referer" + * + * @param string $bucket bucket name + * @param RefererConfig $refererConfig + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketReferer($bucket, $refererConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'referer'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $refererConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the bucket's Referer + * Checks out API document for more details about "Bucket Referer" + * + * @param string $bucket bucket name + * @param array $options + * @return RefererConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketReferer($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'referer'; + $response = $this->auth($options); + $result = new GetRefererResult($response); + return $result->getData(); + } + + /** + * Set the size of the bucket,the unit is GB + * When the capacity of the bucket is bigger than the set, it's forbidden to continue writing + * + * @param string $bucket bucket name + * @param int $storageCapacity + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketStorageCapacity($bucket, $storageCapacity, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'qos'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $storageCapacityConfig = new StorageCapacityConfig($storageCapacity); + $options[self::OSS_CONTENT] = $storageCapacityConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Get the capacity of the bucket, the unit is GB + * + * @param string $bucket bucket name + * @param array $options + * @return int|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketStorageCapacity($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'qos'; + $response = $this->auth($options); + $result = new GetStorageCapacityResult($response); + return $result->getData(); + } + + /** + * Get the information of the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return BucketInfo|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketInfo($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'bucketInfo'; + $response = $this->auth($options); + $result = new GetBucketInfoResult($response); + return $result->getData(); + } + + /** + * Get the stat of the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return BucketStat|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketStat($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'stat'; + $response = $this->auth($options); + $result = new GetBucketStatResult($response); + return $result->getData(); + } + + /** + * Sets the bucket's policy + * + * @param string $bucket bucket name + * @param string $policy policy json format content + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketPolicy($bucket, $policy, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'policy'; + $options[self::OSS_CONTENT_TYPE] = 'application/json'; + $options[self::OSS_CONTENT] = $policy; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets bucket's policy + * + * @param string $bucket bucket name + * @param array $options + * @return string|null policy json content + * @throws OssException|RequestCore_Exception + */ + public function getBucketPolicy($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'policy'; + $response = $this->auth($options); + $result = new BodyResult($response); + return $result->getData(); + } + + /** + * Deletes the bucket's policy + * + * @param string $bucket bucket name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketPolicy($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'policy'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Sets the bucket's encryption + * + * @param string $bucket bucket name + * @param ServerSideEncryptionConfig $sseConfig + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketEncryption($bucket, $sseConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'encryption'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $sseConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets bucket's encryption + * + * @param string $bucket bucket name + * @param array $options + * @return ServerSideEncryptionConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketEncryption($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'encryption'; + $response = $this->auth($options); + $result = new GetBucketEncryptionResult($response); + return $result->getData(); + } + + /** + * Deletes the bucket's encryption + * + * @param string $bucket bucket name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketEncryption($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'encryption'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Set the request playment of the bucket, Can be BucketOwner and Requester + * + * @param string $bucket bucket name + * @param string $payer + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketRequestPayment($bucket, $payer, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'requestPayment'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $config = new RequestPaymentConfig($payer); + $options[self::OSS_CONTENT] = $config->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Get the request playment of the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketRequestPayment($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'requestPayment'; + $response = $this->auth($options); + $result = new GetBucketRequestPaymentResult($response); + return $result->getData(); + } + + /** + * Sets the bucket's tags + * + * @param string $bucket bucket name + * @param TaggingConfig $taggingConfig + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function putBucketTags($bucket, $taggingConfig, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = self::OSS_TAGGING; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $taggingConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets bucket's tags + * + * @param string $bucket bucket name + * @param array $options + * @return TaggingConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketTags($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = self::OSS_TAGGING; + $response = $this->auth($options); + $result = new GetBucketTagsResult($response); + return $result->getData(); + } + + /** + * Deletes the bucket's tags + * If want to delete specified tags for a bucket, please set the $tags + * + * @param string $bucket bucket name + * @param tag[] $tags (optional) + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function deleteBucketTags($bucket, $tags = NULL, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + if (empty($tags)) { + $options[self::OSS_SUB_RESOURCE] = self::OSS_TAGGING; + } else { + $value = ''; + foreach ($tags as $tag) { + $value .= $tag->getKey() . ','; + } + $value = rtrim($value, ','); + $options[self::OSS_TAGGING] = $value; + } + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Set the versioning of the bucket, Can be BucketOwner and Requester + * + * @param string $bucket bucket name + * @param string $status + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putBucketVersioning($bucket, $status, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'versioning'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $config = new VersioningConfig($status); + $options[self::OSS_CONTENT] = $config->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Get the versioning of the bucket + * + * @param string $bucket bucket name + * @param array $options + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketVersioning($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'versioning'; + $response = $this->auth($options); + $result = new GetBucketVersioningResult($response); + return $result->getData(); + } + + /** + * Initialize a bucket's worm + * + * @param string $bucket bucket name + * @param int $day + * @param array $options + * @return string|null returns upload id + * @throws OssException|RequestCore_Exception + */ + public function initiateBucketWorm($bucket, $day, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_SUB_RESOURCE] = 'worm'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $config = new InitiateWormConfig($day); + $options[self::OSS_CONTENT] = $config->serializeToXml(); + $response = $this->auth($options); + $result = new InitiateBucketWormResult($response); + return $result->getData(); + } + + /** + * Aborts the bucket's worm + * + * @param string $bucket bucket name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function abortBucketWorm($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_SUB_RESOURCE] = 'worm'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Complete a bucket's worm + * + * @param string $bucket bucket name + * @param string $wormId + * @param array $options + * @return string|null returns upload id + * @throws OssException|RequestCore_Exception + */ + public function completeBucketWorm($bucket, $wormId, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_WORM_ID] = $wormId; + $options[self::OSS_CONTENT] = ''; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Extend a bucket's worm + * + * @param string $bucket bucket name + * @param string $wormId + * @param int $day + * @param array $options + * @return string|null returns upload id + * @throws OssException|RequestCore_Exception + */ + public function extendBucketWorm($bucket, $wormId, $day, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_WORM_ID] = $wormId; + $options[self::OSS_SUB_RESOURCE] = 'wormExtend'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $config = new ExtendWormConfig($day); + $options[self::OSS_CONTENT] = $config->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Get a bucket's worm + * + * @param string $bucket bucket name + * @param array $options + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketWorm($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'worm'; + $response = $this->auth($options); + $result = new GetBucketWormResult($response); + return $result->getData(); + } + + + /** + * Put Bucket TransferAcceleration + * @param $bucket + * @param $enabled boolean + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + + public function putBucketTransferAcceleration($bucket, $enabled, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_SUB_RESOURCE] = 'transferAcceleration'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $config = new TransferAccelerationConfig(); + $config->setEnabled($enabled); + $options[self::OSS_CONTENT] = $config->serializeToXml(); + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * Put Bucket TransferAcceleration + * @param $bucket + * @param array $options + * @return boolean|null + * @throws OssException|RequestCore_Exception + */ + public function getBucketTransferAcceleration($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'transferAcceleration'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $response = $this->auth($options); + $result = new GetBucketTransferAccelerationResult($response); + return $result->getData(); + } + + /** + * Lists the bucket's object list (in ObjectListInfo) + * + * @param string $bucket + * @param array $options are defined below: + * $options = array( + * 'max-keys' => specifies max object count to return. By default is 100 and max value could be 1000. + * 'prefix' => specifies the key prefix the returned objects must have. Note that the returned keys still contain the prefix. + * 'delimiter' => The delimiter of object name for grouping object. When it's specified, listObjects will differeniate the object and folder. And it will return subfolder's objects. + * 'marker' => The key of returned object must be greater than the 'marker'. + *) + * Prefix and marker are for filtering and paging. Their length must be less than 256 bytes + * @return ObjectListInfo|null + * @throws OssException|RequestCore_Exception + */ + public function listObjects($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $query = isset($options[self::OSS_QUERY_STRING]) ? $options[self::OSS_QUERY_STRING] : array(); + $options[self::OSS_QUERY_STRING] = array_merge( + $query, + array(self::OSS_ENCODING_TYPE => self::OSS_ENCODING_TYPE_URL, + self::OSS_DELIMITER => isset($options[self::OSS_DELIMITER]) ? $options[self::OSS_DELIMITER] : '/', + self::OSS_PREFIX => isset($options[self::OSS_PREFIX]) ? $options[self::OSS_PREFIX] : '', + self::OSS_MAX_KEYS => isset($options[self::OSS_MAX_KEYS]) ? $options[self::OSS_MAX_KEYS] : self::OSS_MAX_KEYS_VALUE, + self::OSS_MARKER => isset($options[self::OSS_MARKER]) ? $options[self::OSS_MARKER] : '') + ); + + $response = $this->auth($options); + $result = new ListObjectsResult($response); + return $result->getData(); + } + + + /** + * Lists the bucket's object list v2 (in ObjectListInfoV2) + * + * @param string $bucket + * @param array $options are defined below: + * $options = array( + * 'max-keys' => specifies max object count to return. By default is 100 and max value could be 1000. + * 'prefix' => specifies the key prefix the returned objects must have. Note that the returned keys still contain the prefix. + * 'delimiter' => The delimiter of object name for grouping object. When it's specified, listObjects will differeniate the object and folder. And it will return subfolder's objects. + * 'start-after' => The key of returned object must be greater than the 'start-after'. + * 'continuation-token' => The token from which the list operation must start. + *) + * Prefix, start-after and continuation-token are for filtering and paging. Their length must be less than 256 bytes + * @return ObjectListInfoV2|null + * @throws OssException|RequestCore_Exception + */ + public function listObjectsV2($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $query = isset($options[self::OSS_QUERY_STRING]) ? $options[self::OSS_QUERY_STRING] : array(); + $temp = array( + self::OSS_LIST_TYPE => 2, + self::OSS_ENCODING_TYPE => self::OSS_ENCODING_TYPE_URL, + self::OSS_DELIMITER => isset($options[self::OSS_DELIMITER]) ? $options[self::OSS_DELIMITER] : '/', + self::OSS_PREFIX => isset($options[self::OSS_PREFIX]) ? $options[self::OSS_PREFIX] : '', + self::OSS_MAX_KEYS => isset($options[self::OSS_MAX_KEYS]) ? $options[self::OSS_MAX_KEYS] : self::OSS_MAX_KEYS_VALUE, + self::OSS_START_AFTER => isset($options[self::OSS_START_AFTER]) ? $options[self::OSS_START_AFTER] : '', + ); + if (isset($options[self::OSS_CONTINUATION_TOKEN])) { + $temp[self::OSS_CONTINUATION_TOKEN] = $options[self::OSS_CONTINUATION_TOKEN]; + } + $options[self::OSS_QUERY_STRING] = array_merge( + $query, $temp + ); + $response = $this->auth($options); + $result = new ListObjectsV2Result($response); + return $result->getData(); + } + + /** + * Lists the bucket's object with version information (in ObjectListInfo) + * + * @param string $bucket + * @param array $options are defined below: + * $options = array( + * 'max-keys' => specifies max object count to return. By default is 100 and max value could be 1000. + * 'prefix' => specifies the key prefix the returned objects must have. Note that the returned keys still contain the prefix. + * 'delimiter' => The delimiter of object name for grouping object. When it's specified, listObjectVersions will differeniate the object and folder. And it will return subfolder's objects. + * 'key-marker' => The key of returned object must be greater than the 'key-marker'. + * 'version-id-marker' => The version id of returned object must be greater than the 'version-id-marker'. + *) + * Prefix and marker are for filtering and paging. Their length must be less than 256 bytes + * @return ObjectVersionListInfo|null + * @throws OssException|RequestCore_Exception + */ + public function listObjectVersions($bucket, $options = NULL) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_SUB_RESOURCE] = 'versions'; + $query = isset($options[self::OSS_QUERY_STRING]) ? $options[self::OSS_QUERY_STRING] : array(); + $options[self::OSS_QUERY_STRING] = array_merge( + $query, + array(self::OSS_ENCODING_TYPE => self::OSS_ENCODING_TYPE_URL, + self::OSS_DELIMITER => isset($options[self::OSS_DELIMITER]) ? $options[self::OSS_DELIMITER] : '/', + self::OSS_PREFIX => isset($options[self::OSS_PREFIX]) ? $options[self::OSS_PREFIX] : '', + self::OSS_MAX_KEYS => isset($options[self::OSS_MAX_KEYS]) ? $options[self::OSS_MAX_KEYS] : self::OSS_MAX_KEYS_VALUE, + self::OSS_KEY_MARKER => isset($options[self::OSS_KEY_MARKER]) ? $options[self::OSS_KEY_MARKER] : '', + self::OSS_VERSION_ID_MARKER => isset($options[self::OSS_VERSION_ID_MARKER]) ? $options[self::OSS_VERSION_ID_MARKER] : '') + ); + + $response = $this->auth($options); + $result = new ListObjectVersionsResult($response); + return $result->getData(); + } + + /** + * Creates a virtual 'folder' in OSS. The name should not end with '/' because the method will append the name with a '/' anyway. + * + * Internal use only. + * + * @param string $bucket bucket name + * @param string $object object name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function createObjectDir($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $object . '/'; + $options[self::OSS_CONTENT_LENGTH] = array(self::OSS_CONTENT_LENGTH => 0); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Uploads the $content object to OSS. + * + * @param string $bucket bucket name + * @param string $object objcet name + * @param string $content The content object + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putObject($bucket, $object, $content, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + + $options[self::OSS_CONTENT] = $content; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $object; + + if (!isset($options[self::OSS_LENGTH])) { + $options[self::OSS_CONTENT_LENGTH] = strlen($options[self::OSS_CONTENT]); + } else { + $options[self::OSS_CONTENT_LENGTH] = $options[self::OSS_LENGTH]; + } + + $is_check_md5 = $this->isCheckMD5($options); + if ($is_check_md5) { + $content_md5 = base64_encode(md5($content, true)); + $options[self::OSS_CONTENT_MD5] = $content_md5; + } + + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object); + } + $response = $this->auth($options); + + if (isset($options[self::OSS_CALLBACK]) && !empty($options[self::OSS_CALLBACK])) { + $result = new CallbackResult($response); + } else { + $result = new PutSetDeleteResult($response); + } + + return $result->getData(); + } + + + /** + * creates symlink + * @param string $bucket bucket name + * @param string $symlink symlink name + * @param string $targetObject targetObject name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putSymlink($bucket, $symlink, $targetObject, $options = NULL) + { + $this->precheckCommon($bucket, $symlink, $options); + + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $symlink; + $options[self::OSS_SUB_RESOURCE] = self::OSS_SYMLINK; + $options[self::OSS_HEADERS][self::OSS_SYMLINK_TARGET] = rawurlencode($targetObject); + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets symlink + * @param string $bucket bucket name + * @param string $symlink symlink name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function getSymlink($bucket, $symlink, $options = NULL) + { + $this->precheckCommon($bucket, $symlink, $options); + + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_OBJECT] = $symlink; + $options[self::OSS_SUB_RESOURCE] = self::OSS_SYMLINK; + + $response = $this->auth($options); + $result = new SymlinkResult($response); + return $result->getData(); + } + + /** + * Uploads a local file + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $file local file path + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function uploadFile($bucket, $object, $file, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + OssUtil::throwOssExceptionWithMessageIfEmpty($file, "file path is invalid"); + $file = $this->encodeFilePath($file); + if (!file_exists($file)) { + throw new OssException($file . " file does not exist"); + } + $options[self::OSS_FILE_UPLOAD] = $file; + $file_size = sprintf('%u', filesize($options[self::OSS_FILE_UPLOAD])); + $is_check_md5 = $this->isCheckMD5($options); + if ($is_check_md5) { + $content_md5 = base64_encode(md5_file($options[self::OSS_FILE_UPLOAD], true)); + $options[self::OSS_CONTENT_MD5] = $content_md5; + } + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object, $file); + } + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_CONTENT_LENGTH] = $file_size; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Uploads object from file handle + * + * @param string $bucket bucket name + * @param string $object object name + * @param resource $handle file handle + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function uploadStream($bucket, $object, $handle, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + if (!is_resource($handle)) { + throw new OssException("The handle must be an opened stream"); + } + $options[self::OSS_FILE_UPLOAD] = $handle; + if ($this->isCheckMD5($options)) { + rewind($handle); + $ctx = hash_init('md5'); + hash_update_stream($ctx, $handle); + $content_md5 = base64_encode(hash_final($ctx, true)); + rewind($handle); + $options[self::OSS_CONTENT_MD5] = $content_md5; + } + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object); + } + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + if (!isset($options[self::OSS_CONTENT_LENGTH])) { + $stat = fstat($handle); + $options[self::OSS_CONTENT_LENGTH] = $stat[self::OSS_SIZE]; + } + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Append the object with the content at the specified position. + * The specified position is typically the lengh of the current file. + * @param string $bucket bucket name + * @param string $object objcet name + * @param string $content content to append + * @param array $options + * @return int|null next append position + * @throws OssException|RequestCore_Exception + */ + public function appendObject($bucket, $object, $content, $position, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + + $options[self::OSS_CONTENT] = $content; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = 'append'; + $options[self::OSS_POSITION] = strval($position); + if (!isset($options[self::OSS_LENGTH])) { + $options[self::OSS_CONTENT_LENGTH] = strlen($options[self::OSS_CONTENT]); + } else { + $options[self::OSS_CONTENT_LENGTH] = $options[self::OSS_LENGTH]; + } + + $is_check_md5 = $this->isCheckMD5($options); + if ($is_check_md5) { + $content_md5 = base64_encode(md5($content, true)); + $options[self::OSS_CONTENT_MD5] = $content_md5; + } + + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object); + } + $response = $this->auth($options); + $result = new AppendResult($response); + return $result->getData(); + } + + /** + * Append the object with a local file + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $file The local file path to append with + * @param array $options + * @return int|null next append position + * @throws OssException|RequestCore_Exception + */ + public function appendFile($bucket, $object, $file, $position, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + + OssUtil::throwOssExceptionWithMessageIfEmpty($file, "file path is invalid"); + $file = $this->encodeFilePath($file); + if (!file_exists($file)) { + throw new OssException($file . " file does not exist"); + } + $options[self::OSS_FILE_UPLOAD] = $file; + $file_size = sprintf('%u', filesize($options[self::OSS_FILE_UPLOAD])); + $is_check_md5 = $this->isCheckMD5($options); + if ($is_check_md5) { + $content_md5 = base64_encode(md5_file($options[self::OSS_FILE_UPLOAD], true)); + $options[self::OSS_CONTENT_MD5] = $content_md5; + } + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object, $file); + } + + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_CONTENT_LENGTH] = $file_size; + $options[self::OSS_SUB_RESOURCE] = 'append'; + $options[self::OSS_POSITION] = strval($position); + + $response = $this->auth($options); + $result = new AppendResult($response); + return $result->getData(); + } + + /** + * Copy from an existing OSS object to another OSS object. If the target object exists already, it will be overwritten. + * + * @param string $fromBucket Source bucket name + * @param string $fromObject Source object name + * @param string $toBucket Target bucket name + * @param string $toObject Target object name + * @param array $options + * @return null + * @throws OssException|RequestCore_Exception + */ + public function copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options = NULL) + { + $this->precheckCommon($fromBucket, $fromObject, $options); + $this->precheckCommon($toBucket, $toObject, $options); + $options[self::OSS_BUCKET] = $toBucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $toObject; + $param = '/' . $fromBucket . '/' . rawurlencode($fromObject); + if (isset($options[self::OSS_VERSION_ID])) { + $param = $param . '?versionId=' . $options[self::OSS_VERSION_ID]; + unset($options[self::OSS_VERSION_ID]); + } + $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE] = $param; + $response = $this->auth($options); + $result = new CopyObjectResult($response); + return $result->getData(); + } + + /** + * Gets Object metadata + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $options Checks out the SDK document for the detail + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function getObjectMeta($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_HEAD; + $options[self::OSS_OBJECT] = $object; + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * Gets the simplified metadata of a object. + * Simplified metadata includes ETag, Size, LastModified. + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $options Checks out the SDK document for the detail + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function getSimplifiedObjectMeta($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_HEAD; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = 'objectMeta'; + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * Deletes a object + * + * @param string $bucket bucket name + * @param string $object object name + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function deleteObject($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_OBJECT] = $object; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Deletes multiple objects in a bucket + * + * @param string $bucket bucket name + * @param array $objects object list + * @param array $options + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function deleteObjects($bucket, $objects, $options = null) + { + $this->precheckCommon($bucket, NULL, $options, false); + if (!is_array($objects) || !$objects) { + throw new OssException('objects must be array'); + } + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_SUB_RESOURCE] = 'delete'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $quiet = 'false'; + if (isset($options['quiet'])) { + if (is_bool($options['quiet'])) { //Boolean + $quiet = $options['quiet'] ? 'true' : 'false'; + } elseif (is_string($options['quiet'])) { // string + $quiet = ($options['quiet'] === 'true') ? 'true' : 'false'; + } + } + $xmlBody = OssUtil::createDeleteObjectsXmlBody($objects, $quiet); + $options[self::OSS_CONTENT] = $xmlBody; + $response = $this->auth($options); + $result = new DeleteObjectsResult($response); + return $result->getData(); + } + + /** + * Deletes multiple objects with version id in a bucket + * + * @param string $bucket bucket name + * @param array $objects DeleteObjectInfo list + * @param array $options + * @return DeletedObjectInfo|null + * @throws OssException|RequestCore_Exception + */ + public function deleteObjectVersions($bucket, $objects, $options = null) + { + $this->precheckCommon($bucket, NULL, $options, false); + if (!is_array($objects) || !$objects) { + throw new OssException('objects must be array'); + } + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_SUB_RESOURCE] = 'delete'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $quiet = 'false'; + if (isset($options['quiet'])) { + if (is_bool($options['quiet'])) { //Boolean + $quiet = $options['quiet'] ? 'true' : 'false'; + } elseif (is_string($options['quiet'])) { // string + $quiet = ($options['quiet'] === 'true') ? 'true' : 'false'; + } + } + $xmlBody = OssUtil::createDeleteObjectVersionsXmlBody($objects, $quiet); + $options[self::OSS_CONTENT] = $xmlBody; + $response = $this->auth($options); + $result = new DeleteObjectVersionsResult($response); + return $result->getData(); + } + + /** + * Gets Object content + * + * @param string $bucket bucket name + * @param string $object object name + * @param array $options It must contain ALIOSS::OSS_FILE_DOWNLOAD. And ALIOSS::OSS_RANGE is optional and empty means to download the whole file. + * @return string|null + * @throws OssException|RequestCore_Exception + */ + public function getObject($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_OBJECT] = $object; + if (isset($options[self::OSS_LAST_MODIFIED])) { + $options[self::OSS_HEADERS][self::OSS_IF_MODIFIED_SINCE] = $options[self::OSS_LAST_MODIFIED]; + unset($options[self::OSS_LAST_MODIFIED]); + } + if (isset($options[self::OSS_ETAG])) { + $options[self::OSS_HEADERS][self::OSS_IF_NONE_MATCH] = $options[self::OSS_ETAG]; + unset($options[self::OSS_ETAG]); + } + if (isset($options[self::OSS_RANGE])) { + $range = $options[self::OSS_RANGE]; + $options[self::OSS_HEADERS][self::OSS_RANGE] = "bytes=$range"; + unset($options[self::OSS_RANGE]); + } + $response = $this->auth($options); + $result = new BodyResult($response); + return $result->getData(); + } + + /** + * Checks if the object exists + * It's implemented by getObjectMeta(). + * + * @param string $bucket bucket name + * @param string $object object name + * @param array $options + * @return bool|null True:object exists; False:object does not exist + * @throws OssException|RequestCore_Exception| + */ + public function doesObjectExist($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_HEAD; + $options[self::OSS_OBJECT] = $object; + $response = $this->auth($options); + $result = new ExistResult($response); + return $result->getData(); + } + + /** + * Object reading for Archive type + * Use Restore to enable the server to perform the thawing task + * + * @param string $bucket bucket name + * @param string $object object name + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function restoreObject($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = self::OSS_RESTORE; + if (isset($options[self::OSS_RESTORE_CONFIG])) { + $config = $options[self::OSS_RESTORE_CONFIG]; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $config->serializeToXml(); + } + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Sets the object tagging + * + * @param string $bucket bucket name + * @param string $object object name + * @param TaggingConfig $taggingConfig + * @return array|null + * @throws OssException|RequestCore_Exception + */ + public function putObjectTagging($bucket, $object, $taggingConfig, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options, true); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = self::OSS_TAGGING; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $options[self::OSS_CONTENT] = $taggingConfig->serializeToXml(); + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Gets the object tagging + * + * @param string $bucket + * @param string $object + * @return TaggingConfig|null + * @throws OssException|RequestCore_Exception + */ + public function getObjectTagging($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options, true); + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = self::OSS_TAGGING; + $response = $this->auth($options); + $result = new GetBucketTagsResult($response); + return $result->getData(); + } + + /** + * Deletes the object tagging + * + * @param string $bucket + * @param string $object + * @return null + * @throws OssException|RequestCore_Exception + */ + public function deleteObjectTagging($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options, true); + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = self::OSS_TAGGING; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Processes the object + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $process process script + * @return string|null process result, json format + * @throws OssException|RequestCore_Exception| + */ + public function processObject($bucket, $object, $process, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = 'x-oss-process'; + $options[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; + $options[self::OSS_CONTENT] = 'x-oss-process=' . $process; + $response = $this->auth($options); + $result = new BodyResult($response); + return $result->getData(); + } + + + /** + * Async Process the object + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $asyncProcess async process script + * @param null $options + * @return string|null process result, json format + * @throws OssException + * @throws RequestCore_Exception + */ + public function asyncProcessObject($bucket, $object, $asyncProcess, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = 'x-oss-async-process'; + $options[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; + $options[self::OSS_CONTENT] = 'x-oss-async-process=' . $asyncProcess; + $response = $this->auth($options); + $result = new BodyResult($response); + return $result->getData(); + } + + /** + * Gets the part size according to the preferred part size. + * If the specified part size is too small or too big, it will return a min part or max part size instead. + * Otherwise returns the specified part size. + * @param int $partSize + * @return int + */ + private function computePartSize($partSize) + { + $partSize = (integer)$partSize; + if ($partSize <= self::OSS_MIN_PART_SIZE) { + $partSize = self::OSS_MIN_PART_SIZE; + } elseif ($partSize > self::OSS_MAX_PART_SIZE) { + $partSize = self::OSS_MAX_PART_SIZE; + } + return $partSize; + } + + /** + * Computes the parts count, size and start position according to the file size and the part size. + * It must be only called by upload_Part(). + * + * @param integer $file_size File size + * @param integer $partSize part size. Default is 5MB + * @return array An array contains key-value pairs--the key is `seekTo`and value is `length`. + */ + public function generateMultiuploadParts($file_size, $partSize = 5242880) + { + $i = 0; + $size_count = $file_size; + $values = array(); + $partSize = $this->computePartSize($partSize); + while ($size_count > 0) { + $size_count -= $partSize; + $values[] = array( + self::OSS_SEEK_TO => ($partSize * $i), + self::OSS_LENGTH => (($size_count > 0) ? $partSize : ($size_count + $partSize)), + ); + $i++; + } + return $values; + } + + /** + * Initialize a multi-part upload + * + * @param string $bucket bucket name + * @param string $object object name + * @param array $options Key-Value array + * @return string|null returns upload id + * @throws OssException|RequestCore_Exception + */ + public function initiateMultipartUpload($bucket, $object, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_SUB_RESOURCE] = 'uploads'; + $options[self::OSS_CONTENT] = ''; + + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object); + } + if (!isset($options[self::OSS_HEADERS])) { + $options[self::OSS_HEADERS] = array(); + } + $response = $this->auth($options); + $result = new InitiateMultipartUploadResult($response); + return $result->getData(); + } + + /** + * Upload a part in a multiparts upload. + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $uploadId + * @param array $options Key-Value array + * @return string|null eTag + * @throws OssException|RequestCore_Exception + */ + public function uploadPart($bucket, $object, $uploadId, $options = null) + { + $this->precheckCommon($bucket, $object, $options); + $this->precheckParam($options, self::OSS_FILE_UPLOAD, __FUNCTION__); + $this->precheckParam($options, self::OSS_PART_NUM, __FUNCTION__); + + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_UPLOAD_ID] = $uploadId; + + if (isset($options[self::OSS_LENGTH])) { + $options[self::OSS_CONTENT_LENGTH] = $options[self::OSS_LENGTH]; + } + $response = $this->auth($options); + $result = new UploadPartResult($response); + return $result->getData(); + } + + /** + * Gets the uploaded parts. + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $uploadId uploadId + * @param array $options Key-Value array + * @return ListPartsInfo|null + * @throws OssException|RequestCore_Exception + */ + public function listParts($bucket, $object, $uploadId, $options = null) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_UPLOAD_ID] = $uploadId; + $options[self::OSS_QUERY_STRING] = array(); + foreach (array('max-parts', 'part-number-marker') as $param) { + if (isset($options[$param])) { + $options[self::OSS_QUERY_STRING][$param] = $options[$param]; + unset($options[$param]); + } + } + $response = $this->auth($options); + $result = new ListPartsResult($response); + return $result->getData(); + } + + /** + * Abort a multiparts upload + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $uploadId uploadId + * @param array $options Key-Value name + * @return null + * @throws OssException|RequestCore_Exception + */ + public function abortMultipartUpload($bucket, $object, $uploadId, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_UPLOAD_ID] = $uploadId; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * Completes a multiparts upload, after all parts are uploaded. + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $uploadId uploadId + * @param array $listParts array( array("PartNumber"=> int, "ETag"=>string)) + * @param array $options Key-Value array + * @return null + * @throws OssException|RequestCore_Exception + */ + public function completeMultipartUpload($bucket, $object, $uploadId, $listParts, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + $options[self::OSS_METHOD] = self::OSS_HTTP_POST; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_UPLOAD_ID] = $uploadId; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + if (is_array($listParts)) { + $options[self::OSS_CONTENT] = OssUtil::createCompleteMultipartUploadXmlBody($listParts); + } else { + $options[self::OSS_CONTENT] = ""; + } + + $response = $this->auth($options); + if (isset($options[self::OSS_CALLBACK]) && !empty($options[self::OSS_CALLBACK])) { + $result = new CallbackResult($response); + } else { + $result = new PutSetDeleteResult($response); + } + return $result->getData(); + } + + /** + * Lists all ongoing multipart upload events, which means all initialized but not completed or aborted multipart uploads. + * + * @param string $bucket bucket + * @param array $options key-value array--expected keys are 'delimiter', 'key-marker', 'max-uploads', 'prefix', 'upload-id-marker' + * @return ListMultipartUploadInfo|null + * @throws OssException|RequestCore_Exception + */ + public function listMultipartUploads($bucket, $options = null) + { + $this->precheckCommon($bucket, NULL, $options, false); + $options[self::OSS_METHOD] = self::OSS_HTTP_GET; + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_SUB_RESOURCE] = 'uploads'; + + foreach (array('delimiter', 'key-marker', 'max-uploads', 'prefix', 'upload-id-marker') as $param) { + if (isset($options[$param])) { + $options[self::OSS_QUERY_STRING][$param] = $options[$param]; + unset($options[$param]); + } + } + $query = isset($options[self::OSS_QUERY_STRING]) ? $options[self::OSS_QUERY_STRING] : array(); + $options[self::OSS_QUERY_STRING] = array_merge( + $query, + array(self::OSS_ENCODING_TYPE => self::OSS_ENCODING_TYPE_URL) + ); + + $response = $this->auth($options); + $result = new ListMultipartUploadResult($response); + return $result->getData(); + } + + /** + * Copy an existing file as a part + * + * @param string $fromBucket source bucket name + * @param string $fromObject source object name + * @param string $toBucket target bucket name + * @param string $toObject target object name + * @param int $partNumber Part number + * @param string $uploadId Upload Id + * @param array $options Key-Value array---it should have 'start' or 'end' key to specify the range of the source object to copy. If it's not specifed, the whole object is copied. + * @return null + * @throws OssException|RequestCore_Exception + */ + public function uploadPartCopy($fromBucket, $fromObject, $toBucket, $toObject, $partNumber, $uploadId, $options = NULL) + { + $this->precheckCommon($fromBucket, $fromObject, $options); + $this->precheckCommon($toBucket, $toObject, $options); + + //If $options['isFullCopy'] is not set, copy from the beginning + $start_range = "0"; + if (isset($options['start'])) { + $start_range = $options['start']; + } + $end_range = ""; + if (isset($options['end'])) { + $end_range = $options['end']; + } + $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; + $options[self::OSS_BUCKET] = $toBucket; + $options[self::OSS_OBJECT] = $toObject; + $options[self::OSS_PART_NUM] = $partNumber; + $options[self::OSS_UPLOAD_ID] = $uploadId; + + if (!isset($options[self::OSS_HEADERS])) { + $options[self::OSS_HEADERS] = array(); + } + + $param = '/' . $fromBucket . '/' . rawurlencode($fromObject); + if (isset($options[self::OSS_VERSION_ID])) { + $param = $param . '?versionId=' . $options[self::OSS_VERSION_ID]; + unset($options[self::OSS_VERSION_ID]); + } + + $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE] = $param; + $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE_RANGE] = "bytes=" . $start_range . "-" . $end_range; + $response = $this->auth($options); + $result = new UploadPartResult($response); + return $result->getData(); + } + + /** + * A higher level API for uploading a file with multipart upload. It consists of initialization, parts upload and completion. + * + * @param string $bucket bucket name + * @param string $object object name + * @param string $file The local file to upload + * @param array $options Key-Value array + * @return null + * @throws OssException|RequestCore_Exception + */ + public function multiuploadFile($bucket, $object, $file, $options = null) + { + $this->precheckCommon($bucket, $object, $options); + if (isset($options[self::OSS_LENGTH])) { + $options[self::OSS_CONTENT_LENGTH] = $options[self::OSS_LENGTH]; + unset($options[self::OSS_LENGTH]); + } + if (empty($file)) { + throw new OssException("parameter invalid, file is empty"); + } + $uploadFile = $this->encodeFilePath($file); + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object, $uploadFile); + } + + $upload_position = isset($options[self::OSS_SEEK_TO]) ? (integer)$options[self::OSS_SEEK_TO] : 0; + + if (isset($options[self::OSS_CONTENT_LENGTH])) { + $upload_file_size = (integer)$options[self::OSS_CONTENT_LENGTH]; + } else { + $upload_file_size = sprintf('%u', filesize($uploadFile)); + + if ($upload_file_size !== false) { + $upload_file_size -= $upload_position; + } + } + + if ($upload_position === false || !isset($upload_file_size) || $upload_file_size === false || $upload_file_size < 0) { + throw new OssException('The size of `fileUpload` cannot be determined in ' . __FUNCTION__ . '().'); + } + // Computes the part size and assign it to options. + if (isset($options[self::OSS_PART_SIZE])) { + $options[self::OSS_PART_SIZE] = $this->computePartSize($options[self::OSS_PART_SIZE]); + } else { + $options[self::OSS_PART_SIZE] = self::OSS_MID_PART_SIZE; + } + + $is_check_md5 = $this->isCheckMD5($options); + // if the file size is less than part size, use simple file upload. + if ($upload_file_size < $options[self::OSS_PART_SIZE] && !isset($options[self::OSS_UPLOAD_ID])) { + return $this->uploadFile($bucket, $object, $uploadFile, $options); + } + + // Using multipart upload, initialize if no OSS_UPLOAD_ID is specified in options. + if (isset($options[self::OSS_UPLOAD_ID])) { + $uploadId = $options[self::OSS_UPLOAD_ID]; + } else { + // initialize + $uploadId = $this->initiateMultipartUpload($bucket, $object, $options); + } + + // generates the parts information and upload them one by one + $pieces = $this->generateMultiuploadParts($upload_file_size, (integer)$options[self::OSS_PART_SIZE]); + $response_upload_part = array(); + foreach ($pieces as $i => $piece) { + $from_pos = $upload_position + (integer)$piece[self::OSS_SEEK_TO]; + $to_pos = (integer)$piece[self::OSS_LENGTH] + $from_pos - 1; + $up_options = array( + self::OSS_FILE_UPLOAD => $uploadFile, + self::OSS_PART_NUM => ($i + 1), + self::OSS_SEEK_TO => $from_pos, + self::OSS_LENGTH => $to_pos - $from_pos + 1, + self::OSS_CHECK_MD5 => $is_check_md5, + ); + if ($is_check_md5) { + $content_md5 = OssUtil::getMd5SumForFile($uploadFile, $from_pos, $to_pos); + $up_options[self::OSS_CONTENT_MD5] = $content_md5; + } + $response_upload_part[] = $this->uploadPart($bucket, $object, $uploadId, $up_options); + } + + $uploadParts = array(); + foreach ($response_upload_part as $i => $etag) { + $uploadParts[] = array( + 'PartNumber' => ($i + 1), + 'ETag' => $etag, + ); + } + + //build complete options + $cmp_options = null; + if (isset($options[self::OSS_HEADERS]) && isset($options[self::OSS_HEADERS][self::OSS_REQUEST_PAYER])) { + $cmp_options = array( + OssClient::OSS_HEADERS => array( + OssClient::OSS_REQUEST_PAYER => $options[self::OSS_HEADERS][self::OSS_REQUEST_PAYER], + )); + } + return $this->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts, $cmp_options); + } + + /** + * Uploads the local directory to the specified bucket into specified folder (prefix) + * + * @param string $bucket bucket name + * @param string $prefix The object key prefix. Typically it's folder name. The name should not end with '/' as the API appends it automatically. + * @param string $localDirectory The local directory to upload + * @param string $exclude To excluded directories + * @param bool $recursive Recursive flag. True: Recursively upload all datas under the local directory; False: only upload first layer's files. + * @param bool $checkMd5 + * @return array Returns two list: array("succeededList" => array("object"), "failedList" => array("object"=>"errorMessage")) + * @throws OssException + */ + public function uploadDir($bucket, $prefix, $localDirectory, $exclude = '.|..|.svn|.git', $recursive = false, $checkMd5 = true) + { + $retArray = array("succeededList" => array(), "failedList" => array()); + if (empty($bucket)) throw new OssException("parameter error, bucket is empty"); + if (!is_string($prefix)) throw new OssException("parameter error, prefix is not string"); + if (empty($localDirectory)) throw new OssException("parameter error, localDirectory is empty"); + $directory = $localDirectory; + $directory = $this->encodeFilePath($directory); + //If it's not the local directory, throw OSSException. + if (!is_dir($directory)) { + throw new OssException('parameter error: ' . $directory . ' is not a directory, please check it'); + } + //read directory + $file_list_array = OssUtil::readDir($directory, $exclude, $recursive); + if (!$file_list_array) { + throw new OssException($directory . ' is empty...'); + } + foreach ($file_list_array as $k => $item) { + if (is_dir($item['path'])) { + continue; + } + $options = array( + self::OSS_PART_SIZE => self::OSS_MIN_PART_SIZE, + self::OSS_CHECK_MD5 => $checkMd5, + ); + //mbstring to utf-8 + $fileName = $this->decodeFilePath($item['file']); + $realObject = (!empty($prefix) ? $prefix . '/' : '') . $fileName; + + try { + $this->multiuploadFile($bucket, $realObject, $item['path'], $options); + $retArray["succeededList"][] = $realObject; + } catch (OssException $e) { + $retArray["failedList"][$realObject] = $e->getMessage(); + } + } + return $retArray; + } + + /** + * Sign URL with specified expiration time in seconds (timeout) and HTTP method. + * The signed URL could be used to access the object directly. + * + * @param string $bucket + * @param string $object + * @param int $timeout expiration time in seconds. + * @param string $method + * @param array $options Key-Value array + * @return string + * @throws OssException + */ + public function signUrl($bucket, $object, $timeout = 60, $method = self::OSS_HTTP_GET, $options = NULL) + { + $expiration = time() + $timeout; + return $this->generatePresignedUrl($bucket, $object, $expiration, $method, $options); + } + + /** + * Sign URL with specified expiration time in seconds and HTTP method. + * The signed URL could be used to access the object directly. + * + * @param string $bucket + * @param string $object + * @param int $expiration expiration time of the Url, unix epoch, since 1970.1.1 00.00.00 UTC + * @param string $method + * @param array $options Key-Value array + * @return string + * @throws OssException + */ + public function generatePresignedUrl($bucket, $object, $expiration, $method = self::OSS_HTTP_GET, $options = NULL) + { + $this->precheckObjectExt($object, $this->enableStrictObjName); + $this->precheckCommon($bucket, $object, $options); + $cred = $this->provider->getCredentials(); + //method + if (self::OSS_HTTP_GET !== $method && self::OSS_HTTP_PUT !== $method) { + throw new OssException("method is invalid"); + } + // Should https or http be used? + $scheme = $this->useSSL ? 'https://' : 'http://'; + // gets the host name. If the host name is public domain or private domain, form a third level domain by prefixing the bucket name on the domain name. + $hostname = $this->generateHostname($bucket); + $path = $this->generatePath($bucket, $object); + $headers = $this->generateHeaders($options, ''); + $query_string = $this->generateQueryString($options); + $query_string = empty($query_string) ? '' : '?' . $query_string; + $requestUrl = $scheme . $hostname . $path . $query_string; + //Creates the request + $request = new RequestCore($requestUrl); + $request->set_method($method); + if (isset($options[self::OSS_CALLBACK])) { + $headers[self::OSS_CALLBACK] = base64_encode($options[self::OSS_CALLBACK]); + } + if (isset($options[self::OSS_CALLBACK_VAR])) { + $headers[self::OSS_CALLBACK_VAR] = base64_encode($options[self::OSS_CALLBACK_VAR]); + } + foreach ($headers as $header_key => $header_value) { + $header_value = trim($header_value); + if (empty($header_value)) { + continue; + } + $request->add_header($header_key, $header_value); + } + $signingOpt = array( + 'bucket' => $bucket, + 'key' => $object, + 'region' => $this->getRegion(), + 'product' => $this->getProduct(), + 'expiration' => $expiration, + ); + $this->signer->presign($request, $cred, $signingOpt); + return $request->request_url; + } + + /** + * validates options. Create a empty array if it's NULL. + * + * @param array $options + * @throws OssException + */ + private function precheckOptions(&$options) + { + OssUtil::validateOptions($options); + if (!$options) { + $options = array(); + } + } + + /** + * Validates bucket parameter + * + * @param string $bucket + * @param string $errMsg + * @throws OssException + */ + private function precheckBucket($bucket, $errMsg = 'bucket is not allowed empty') + { + OssUtil::throwOssExceptionWithMessageIfEmpty($bucket, $errMsg); + if (!OssUtil::validateBucket($bucket)) { + throw new OssException('"' . $bucket . '"' . 'bucket name is invalid'); + } + } + + /** + * validates object parameter + * + * @param string $object + * @throws OssException + */ + private function precheckObject($object) + { + OssUtil::throwOssExceptionWithMessageIfEmpty($object, "object name is empty"); + if (!OssUtil::validateObject($object)) { + throw new OssException('"' . $object . '"' . ' object name is invalid'); + } + } + + /** + * validates object name start with ? or not + * @param $object string + * @param $strict boolean + * @throws OssException + */ + private function precheckObjectExt($object, $strict) + { + $this->precheckObject($object); + if ($strict) { + if (is_string($object) && $object[0] === "?") { + throw new OssException('"' . $object . '"' . ' object name cannot start with `?`'); + } + } + } + + /** + * Check option restore + * + * @param $storage string + * @throws OssException + */ + private function precheckStorage($storage) + { + if (is_string($storage)) { + switch ($storage) { + case self::OSS_STORAGE_ARCHIVE: + return; + case self::OSS_STORAGE_IA: + return; + case self::OSS_STORAGE_STANDARD: + return; + case self::OSS_STORAGE_COLDARCHIVE: + return; + default: + break; + } + } + throw new OssException('storage name is invalid'); + } + + /** + * Validates bucket,options parameters and optionally validate object parameter. + * + * @param string $bucket + * @param string $object + * @param array $options + * @param bool $isCheckObject + */ + private function precheckCommon($bucket, $object, &$options, $isCheckObject = true) + { + if ($isCheckObject) { + $this->precheckObject($object); + } + $this->precheckOptions($options); + $this->precheckBucket($bucket); + } + + /** + * checks parameters + * + * @param array $options + * @param string $param + * @param string $funcName + * @throws OssException + */ + private function precheckParam($options, $param, $funcName) + { + if (!isset($options[$param])) { + throw new OssException('The `' . $param . '` options is required in ' . $funcName . '().'); + } + } + + /** + * Checks md5 + * + * @param array $options + * @return bool|null + */ + private function isCheckMD5($options) + { + return $this->getValue($options, self::OSS_CHECK_MD5, false, true, true); + } + + /** + * Gets value of the specified key from the options + * + * @param array $options + * @param string $key + * @param string $default + * @param bool $isCheckEmpty + * @param bool $isCheckBool + * @return bool|null + */ + private function getValue($options, $key, $default = NULL, $isCheckEmpty = false, $isCheckBool = false) + { + $value = $default; + if (isset($options[$key])) { + if ($isCheckEmpty) { + if (!empty($options[$key])) { + $value = $options[$key]; + } + } else { + $value = $options[$key]; + } + unset($options[$key]); + } + if ($isCheckBool) { + if ($value !== true && $value !== false) { + $value = false; + } + } + return $value; + } + + /** + * Gets mimetype + * + * @param string $object + * @return string + */ + private function getMimeType($object, $file = null) + { + if (!is_null($file)) { + $type = MimeTypes::getMimetype($file); + if (!is_null($type)) { + return $type; + } + } + + $type = MimeTypes::getMimetype($object); + if (!is_null($type)) { + return $type; + } + + return self::DEFAULT_CONTENT_TYPE; + } + + /** + * Validates and executes the request according to OSS API protocol. + * + * @param array $options + * @return ResponseCore|string + * @throws OssException + * @throws RequestCore_Exception + */ + private function auth($options) + { + OssUtil::validateOptions($options); + //Object Encoding + $this->authPrecheckObjectEncoding($options); + //Validates ACL + $this->authPrecheckAcl($options); + $cred = $this->provider->getCredentials(); + $this->checkCredentials($cred); + + $bucket = isset($options[self::OSS_BUCKET]) ? $options[self::OSS_BUCKET] : ''; + $object = isset($options[self::OSS_OBJECT]) ? $options[self::OSS_OBJECT] : ''; + + // Should https or http be used? + $scheme = $this->useSSL ? 'https://' : 'http://'; + // gets the host name. If the host name is public domain or private domain, form a third level domain by prefixing the bucket name on the domain name. + $hostname = $this->generateHostname($bucket); + $path = $this->generatePath($bucket, $object); + $headers = $this->generateHeaders($options, $hostname); + $query_string = $this->generateQueryString($options); + $query_string = empty($query_string) ? '' : '?' . $query_string; + $requestUrl = $scheme . $hostname . $path . $query_string; + + //Creates the request + $request = new RequestCore($requestUrl, $this->requestProxy); + $request->set_useragent($this->generateUserAgent()); + // Streaming uploads + if (isset($options[self::OSS_FILE_UPLOAD])) { + if (is_resource($options[self::OSS_FILE_UPLOAD])) { + $length = null; + + if (isset($options[self::OSS_CONTENT_LENGTH])) { + $length = $options[self::OSS_CONTENT_LENGTH]; + } elseif (isset($options[self::OSS_SEEK_TO])) { + $stats = fstat($options[self::OSS_FILE_UPLOAD]); + if ($stats && $stats[self::OSS_SIZE] >= 0) { + $length = $stats[self::OSS_SIZE] - (integer)$options[self::OSS_SEEK_TO]; + } + } + $request->set_read_stream($options[self::OSS_FILE_UPLOAD], $length); + } else { + $request->set_read_file($options[self::OSS_FILE_UPLOAD]); + $length = $request->read_stream_size; + if (isset($options[self::OSS_CONTENT_LENGTH])) { + $length = $options[self::OSS_CONTENT_LENGTH]; + } elseif (isset($options[self::OSS_SEEK_TO]) && isset($length)) { + $length -= (integer)$options[self::OSS_SEEK_TO]; + } + $request->set_read_stream_size($length); + } + } + if (isset($options[self::OSS_SEEK_TO])) { + $request->set_seek_position((integer)$options[self::OSS_SEEK_TO]); + } + if (isset($options[self::OSS_FILE_DOWNLOAD])) { + if (is_resource($options[self::OSS_FILE_DOWNLOAD])) { + $request->set_write_stream($options[self::OSS_FILE_DOWNLOAD]); + } else { + $request->set_write_file($options[self::OSS_FILE_DOWNLOAD]); + } + } + if (isset($options[self::OSS_METHOD])) { + $request->set_method($options[self::OSS_METHOD]); + } + if (isset($options[self::OSS_CONTENT])) { + $request->set_body($options[self::OSS_CONTENT]); + if (isset($headers[self::OSS_CONTENT_TYPE]) && $headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { + $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; + } + + $headers[self::OSS_CONTENT_LENGTH] = strlen($options[self::OSS_CONTENT]); + $headers[self::OSS_CONTENT_MD5] = base64_encode(md5($options[self::OSS_CONTENT], true)); + } + + if (isset($options[self::OSS_CALLBACK])) { + $headers[self::OSS_CALLBACK] = base64_encode($options[self::OSS_CALLBACK]); + } + if (isset($options[self::OSS_CALLBACK_VAR])) { + $headers[self::OSS_CALLBACK_VAR] = base64_encode($options[self::OSS_CALLBACK_VAR]); + } + + if (!isset($headers[self::OSS_ACCEPT_ENCODING])) { + $headers[self::OSS_ACCEPT_ENCODING] = ''; + } + + if (!isset($headers[self::OSS_CONTENT_TYPE])) { + $headers[self::OSS_CONTENT_TYPE] = self::DEFAULT_CONTENT_TYPE; + } + + foreach ($headers as $header_key => $header_value) { + $header_value = trim($header_value); + if (empty($header_value)) { + continue; + } + $request->add_header($header_key, $header_value); + } + + // sign request + $signingOpt = array( + 'bucket' => $bucket, + 'key' => $object, + 'region' => $this->getRegion(), + 'product' => $this->getProduct(), + ); + if (isset($options[self::OSS_ADDITIONAL_HEADERS])) { + $signingOpt['additionalHeaders'] = $options[self::OSS_ADDITIONAL_HEADERS]; + } + + $this->signer->sign($request, $cred, $signingOpt); + $string_to_sign = isset($signingOpt['string_to_sign']) ? $signingOpt['string_to_sign'] : ''; + + if ($this->timeout !== 0) { + $request->timeout = $this->timeout; + } + if ($this->connectTimeout !== 0) { + $request->connect_timeout = $this->connectTimeout; + } + + try { + $request->send_request(); + } catch (RequestCore_Exception $e) { + throw(new OssException('RequestCoreException: ' . $e->getMessage())); + } + $response_header = $request->get_response_header(); + $response_header['oss-request-url'] = $requestUrl; + $response_header['oss-redirects'] = $this->redirects; + $response_header['oss-stringtosign'] = $string_to_sign; + $response_header['oss-requestheaders'] = $request->request_headers; + + $data = new ResponseCore($response_header, $request->get_response_body(), $request->get_response_code()); + //retry if OSS Internal Error + if ((integer)$request->get_response_code() === 500) { + if ($this->redirects <= $this->maxRetries) { + //Sets the sleep time betwen each retry. + $delay = (integer)(pow(4, $this->redirects) * 100000); + usleep($delay); + $this->redirects++; + $data = $this->auth($options); + } + } + + $this->redirects = 0; + return $data; + } + + /** + * Sets the max retry count + * + * @param int $maxRetries + * @return void + */ + public function setMaxTries($maxRetries = 3) + { + $this->maxRetries = $maxRetries; + } + + /** + * Gets the max retry count + * + * @return int + */ + public function getMaxRetries() + { + return $this->maxRetries; + } + + /** + * Enaable/disable STS in the URL. This is to determine the $sts value passed from constructor take effect or not. + * + * @param boolean $enable + */ + public function setSignStsInUrl($enable) + { + } + + /** + * @return boolean + */ + public function isUseSSL() + { + return $this->useSSL; + } + + /** + * @param boolean $useSSL + */ + public function setUseSSL($useSSL) + { + $this->useSSL = $useSSL; + } + + /** + * Checks the object's encoding. Convert it to UTF8 if it's in GBK or GB2312 + * + * @param mixed $options parameter + */ + private function authPrecheckObjectEncoding(&$options) + { + if ($this->checkObjectEncoding !== true) { + return; + } + + if (!isset($options[self::OSS_OBJECT])) { + return; + } + + try { + $tmp_object = $options[self::OSS_OBJECT]; + $encoding = array('UTF-8', 'GB2312', 'GBK'); + $encode = mb_detect_encoding($tmp_object, $encoding); + if ($encode === 'UTF-8' || $encode === false) { + return; + } + $tmp_object = iconv($encode, "UTF-8", $tmp_object); + if ($tmp_object === false) { + return; + } + $options[self::OSS_OBJECT] = $tmp_object; + } catch (\Exception $e) { + //IGNORE + } + } + + /** + * Checks if the ACL is one of the 3 predefined one. Throw OSSException if not. + * + * @param $options + * @throws OssException + */ + private function authPrecheckAcl($options) + { + if (isset($options[self::OSS_HEADERS][self::OSS_ACL]) && !empty($options[self::OSS_HEADERS][self::OSS_ACL])) { + if (!in_array(strtolower($options[self::OSS_HEADERS][self::OSS_ACL]), self::$OSS_ACL_TYPES)) { + throw new OssException($options[self::OSS_HEADERS][self::OSS_ACL] . ':' . 'acl is invalid(private,public-read,public-read-write)'); + } + } + } + + /** + * Gets the host name for the current request. + * It could be either a third level domain (prefixed by bucket name) or second level domain if it's CName or IP + * + * @param $bucket + * @return string The host name without the protocol scheem (e.g. https://) + */ + private function generateHostname($bucket) + { + if ($this->hostType === self::OSS_HOST_TYPE_IP || $this->hostType === self::OSS_HOST_TYPE_PATH_STYLE) { + $hostname = $this->hostname; + } elseif ($this->hostType === self::OSS_HOST_TYPE_CNAME) { + $hostname = $this->hostname; + } else { + // Private domain or public domain + $hostname = ($bucket == '') ? $this->hostname : ($bucket . '.') . $this->hostname; + } + return $hostname; + } + + /** + * Gets the Uri path in the current request + * + * @param $bucket + * @param $object + * @return string return the resource uri. + */ + private function generatePath($bucket, $object) + { + $paths = array(); + // +bucket + if ('' !== $bucket) { + if ($this->hostType === self::OSS_HOST_TYPE_IP || $this->hostType === self::OSS_HOST_TYPE_PATH_STYLE) { + $paths[] = $bucket; + if ('' === $object) { + $paths[] = ''; + } + } + } + // + object + if ('' !== $object && '/' !== $object) { + $paths[] = str_replace(array('%2F'), array('/'), rawurlencode($object)); + } + return '/' . implode('/', $paths); + } + + /** + * generates query string + * + * @param mixed $options + * @return string + */ + private function generateQueryString($options) + { + //query parameters + $query = array(); + $queryList = array( + self::OSS_PART_NUM, + 'response-content-type', + 'response-content-language', + 'response-cache-control', + 'response-content-encoding', + 'response-expires', + 'response-content-disposition', + self::OSS_UPLOAD_ID, + self::OSS_COMP, + self::OSS_LIVE_CHANNEL_STATUS, + self::OSS_LIVE_CHANNEL_START_TIME, + self::OSS_LIVE_CHANNEL_END_TIME, + self::OSS_PROCESS, + self::OSS_POSITION, + self::OSS_SYMLINK, + self::OSS_RESTORE, + self::OSS_TAGGING, + self::OSS_WORM_ID, + self::OSS_TRAFFIC_LIMIT, + self::OSS_VERSION_ID, + self::OSS_CONTINUATION_TOKEN, + self::OSS_CNAME, + ); + foreach ($queryList as $item) { + if (isset($options[$item])) { + $query[$item] = $options[$item]; + } + } + if (isset($options[self::OSS_QUERY_STRING])) { + $query = array_merge($query, $options[self::OSS_QUERY_STRING]); + } + if (isset($options[self::OSS_SUB_RESOURCE])) { + $query[$options[self::OSS_SUB_RESOURCE]] = ''; + } + + return OssUtil::toQueryString($query); + } + + /** + * Initialize headers + * + * @param mixed $options + * @param string $hostname hostname + * @return array + */ + private function generateHeaders($options, $hostname) + { + $headers = array(); + + if (!empty($hostname)) { + $headers[self::OSS_HOST] = $hostname; + } + + if (isset($options[self::OSS_CONTENT_TYPE])) { + $headers[self::OSS_CONTENT_TYPE] = $options[self::OSS_CONTENT_TYPE]; + } + + if (isset($options[self::OSS_DATE])) { + $headers[self::OSS_DATE] = $options[self::OSS_DATE]; + } + + if (isset($options[self::OSS_CONTENT_MD5])) { + $headers[self::OSS_CONTENT_MD5] = $options[self::OSS_CONTENT_MD5]; + } + + //Merge HTTP headers + if (isset($options[self::OSS_HEADERS])) { + $headers = array_merge($headers, $options[self::OSS_HEADERS]); + } + return $headers; + } + + /** + * Generates UserAgent + * + * @return string + */ + private function generateUserAgent() + { + return self::OSS_NAME . "/" . self::OSS_VERSION . " (" . php_uname('s') . "/" . php_uname('r') . "/" . php_uname('m') . ";" . PHP_VERSION . ")"; + } + + /** + * Checks endpoint type and returns the endpoint without the protocol schema. + * Figures out the domain's type (ip, cname or private/public domain). + * + * @param string $endpoint + * @param boolean $isCName + * @return string The domain name without the protocol schema. + * @throws OssException + */ + private function checkEndpoint($endpoint, $isCName) + { + $ret_endpoint = null; + if (strpos($endpoint, 'http://') === 0) { + $ret_endpoint = substr($endpoint, strlen('http://')); + } elseif (strpos($endpoint, 'https://') === 0) { + $ret_endpoint = substr($endpoint, strlen('https://')); + $this->useSSL = true; + } else { + $ret_endpoint = $endpoint; + } + + $ret_endpoint = OssUtil::getHostPortFromEndpoint($ret_endpoint); + + if ($isCName) { + $this->hostType = self::OSS_HOST_TYPE_CNAME; + } elseif (OssUtil::isIPFormat($ret_endpoint)) { + $this->hostType = self::OSS_HOST_TYPE_IP; + } else { + $this->hostType = self::OSS_HOST_TYPE_NORMAL; + } + return $ret_endpoint; + } + + /** + * @param Credentials $credential + * @throws OssException + */ + private function checkCredentials($credential) + { + if (empty($credential)) { + throw new OssException("credentials is empty."); + } + if (strlen($credential->getAccessKeyId()) == 0) { + throw new OssException("access key id is empty"); + } + if (strlen($credential->getAccessKeySecret()) == 0) { + throw new OssException("access key secret is empty"); + } + } + + /** + * For get Sign Product + * @return string + */ + private function getProduct() + { + if (!empty($this->cloudBoxId)) { + return self::OSS_CLOUDBOX_PRODUCT; + } + return self::OSS_DEFAULT_PRODUCT; + } + + /** + * For get Sign Region + * @return mixed + */ + private function getRegion() + { + if (!empty($this->cloudBoxId)) { + return $this->cloudBoxId; + } + return $this->region; + } + + /** + * Encodes the file path from UTF-8 to GBK. + * + * @param $filepath + * @return string + */ + private function encodeFilePath($filepath) + { + if ($this->filePathCompatible !== true) { + return $filepath; + } + + if (empty($filepath)) { + return $filepath; + } + + try { + $encoding = array('UTF-8', 'GB2312', 'GBK'); + $encode = mb_detect_encoding($filepath, $encoding); + if ($encode !== 'UTF-8') { + return $filepath; + } + $tmp = iconv($encode, 'GBK', $filepath); + if ($tmp !== false) { + $filepath = $tmp; + } + } catch (\Exception $e) { + //IGNORE + } + return $filepath; + } + + /** + * Decodes the file path from GBK to UTF-8. + * + * @param $filepath + * @return string + */ + private function decodeFilePath($filepath) + { + if ($this->filePathCompatible !== true) { + return $filepath; + } + if (empty($filepath)) { + return $filepath; + } + + try { + $encoding = array('UTF-8', 'GB2312', 'GBK'); + $encode = mb_detect_encoding($filepath, $encoding); + if ($encode === 'UTF-8' || $encode === false) { + return $filepath; + } + $tmp = iconv($encode, 'UTF-8', $filepath); + if ($tmp !== false) { + $filepath = $tmp; + } + } catch (\Exception $e) { + //IGNORE + } + return $filepath; + } + + /** + * Check if all dependent extensions are installed correctly. + * For now only "curl" is needed. + * @throws OssException + */ + public static function checkEnv() + { + if (function_exists('get_loaded_extensions')) { + //Test curl extension + $enabled_extension = array("curl"); + $extensions = get_loaded_extensions(); + if ($extensions) { + foreach ($enabled_extension as $item) { + if (!in_array($item, $extensions)) { + throw new OssException("Extension {" . $item . "} is not installed or not enabled, please check your php env."); + } + } + } else { + throw new OssException("function get_loaded_extensions not found."); + } + } else { + throw new OssException('Function get_loaded_extensions has been disabled, please check php config.'); + } + } + + /** + * Sets the http's timeout (in seconds) + * + * @param int $timeout + */ + public function setTimeout($timeout) + { + $this->timeout = $timeout; + } + + /** + * Sets the http's connection timeout (in seconds) + * + * @param int $connectTimeout + */ + public function setConnectTimeout($connectTimeout) + { + $this->connectTimeout = $connectTimeout; + } + + // Constants for Life cycle + const OSS_LIFECYCLE_EXPIRATION = "Expiration"; + const OSS_LIFECYCLE_TIMING_DAYS = "Days"; + const OSS_LIFECYCLE_TIMING_DATE = "Date"; + //OSS Internal constants + const OSS_BUCKET = 'bucket'; + const OSS_OBJECT = 'object'; + const OSS_HEADERS = OssUtil::OSS_HEADERS; + const OSS_ADDITIONAL_HEADERS = 'additionalHeaders'; + const OSS_METHOD = 'method'; + const OSS_QUERY = 'query'; + const OSS_BASENAME = 'basename'; + const OSS_MAX_KEYS = 'max-keys'; + const OSS_UPLOAD_ID = 'uploadId'; + const OSS_PART_NUM = 'partNumber'; + const OSS_COMP = 'comp'; + const OSS_LIVE_CHANNEL_STATUS = 'status'; + const OSS_LIVE_CHANNEL_START_TIME = 'startTime'; + const OSS_LIVE_CHANNEL_END_TIME = 'endTime'; + const OSS_POSITION = 'position'; + const OSS_MAX_KEYS_VALUE = 100; + const OSS_MAX_OBJECT_GROUP_VALUE = OssUtil::OSS_MAX_OBJECT_GROUP_VALUE; + const OSS_MAX_PART_SIZE = OssUtil::OSS_MAX_PART_SIZE; + const OSS_MID_PART_SIZE = OssUtil::OSS_MID_PART_SIZE; + const OSS_MIN_PART_SIZE = OssUtil::OSS_MIN_PART_SIZE; + const OSS_FILE_SLICE_SIZE = 8192; + const OSS_PREFIX = 'prefix'; + const OSS_DELIMITER = 'delimiter'; + const OSS_MARKER = 'marker'; + const OSS_FETCH_OWNER = 'fetch-owner'; + const OSS_START_AFTER = 'start-after'; + const OSS_CONTINUATION_TOKEN = 'continuation-token'; + const OSS_ACCEPT_ENCODING = 'Accept-Encoding'; + const OSS_CONTENT_MD5 = 'Content-Md5'; + const OSS_SELF_CONTENT_MD5 = 'x-oss-meta-md5'; + const OSS_CONTENT_TYPE = 'Content-Type'; + const OSS_CONTENT_LENGTH = 'Content-Length'; + const OSS_IF_MODIFIED_SINCE = 'If-Modified-Since'; + const OSS_IF_UNMODIFIED_SINCE = 'If-Unmodified-Since'; + const OSS_IF_MATCH = 'If-Match'; + const OSS_IF_NONE_MATCH = 'If-None-Match'; + const OSS_CACHE_CONTROL = 'Cache-Control'; + const OSS_EXPIRES = 'Expires'; + + const OSS_CONTENT_COING = 'Content-Coding'; + const OSS_CONTENT_DISPOSTION = 'Content-Disposition'; + const OSS_RANGE = 'range'; + const OSS_ETAG = 'etag'; + const OSS_LAST_MODIFIED = 'lastmodified'; + const OS_CONTENT_RANGE = 'Content-Range'; + const OSS_CONTENT = OssUtil::OSS_CONTENT; + const OSS_BODY = 'body'; + const OSS_LENGTH = OssUtil::OSS_LENGTH; + const OSS_HOST = 'Host'; + const OSS_DATE = 'Date'; + const OSS_AUTHORIZATION = 'Authorization'; + const OSS_FILE_DOWNLOAD = 'fileDownload'; + const OSS_FILE_UPLOAD = 'fileUpload'; + const OSS_PART_SIZE = 'partSize'; + const OSS_SEEK_TO = 'seekTo'; + const OSS_SIZE = 'size'; + const OSS_QUERY_STRING = 'query_string'; + const OSS_SUB_RESOURCE = 'sub_resource'; + const OSS_DEFAULT_PREFIX = 'x-oss-'; + const OSS_CHECK_MD5 = 'checkmd5'; + const OSS_CHECK_OBJECT = 'checkobject'; + const DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + const OSS_SYMLINK_TARGET = 'x-oss-symlink-target'; + const OSS_SYMLINK = 'symlink'; + const OSS_HTTP_CODE = 'http_code'; + const OSS_REQUEST_ID = 'x-oss-request-id'; + const OSS_INFO = 'info'; + const OSS_STORAGE = 'storage'; + const OSS_RESTORE = 'restore'; + const OSS_STORAGE_STANDARD = 'Standard'; + const OSS_STORAGE_IA = 'IA'; + const OSS_STORAGE_ARCHIVE = 'Archive'; + const OSS_STORAGE_COLDARCHIVE = 'ColdArchive'; + const OSS_TAGGING = 'tagging'; + const OSS_WORM_ID = 'wormId'; + const OSS_RESTORE_CONFIG = 'restore-config'; + const OSS_KEY_MARKER = 'key-marker'; + const OSS_VERSION_ID_MARKER = 'version-id-marker'; + const OSS_VERSION_ID = 'versionId'; + const OSS_HEADER_VERSION_ID = 'x-oss-version-id'; + const OSS_CNAME = 'cname'; + + //private URLs + const OSS_URL_ACCESS_KEY_ID = 'OSSAccessKeyId'; + const OSS_URL_EXPIRES = 'Expires'; + const OSS_URL_SIGNATURE = 'Signature'; + //HTTP METHOD + const OSS_HTTP_GET = 'GET'; + const OSS_HTTP_PUT = 'PUT'; + const OSS_HTTP_HEAD = 'HEAD'; + const OSS_HTTP_POST = 'POST'; + const OSS_HTTP_DELETE = 'DELETE'; + const OSS_HTTP_OPTIONS = 'OPTIONS'; + //Others + const OSS_ACL = 'x-oss-acl'; + const OSS_OBJECT_ACL = 'x-oss-object-acl'; + const OSS_OBJECT_GROUP = 'x-oss-file-group'; + const OSS_MULTI_PART = 'uploads'; + const OSS_MULTI_DELETE = 'delete'; + const OSS_OBJECT_COPY_SOURCE = 'x-oss-copy-source'; + const OSS_OBJECT_COPY_SOURCE_RANGE = "x-oss-copy-source-range"; + const OSS_PROCESS = "x-oss-process"; + const OSS_CALLBACK = "x-oss-callback"; + const OSS_CALLBACK_VAR = "x-oss-callback-var"; + const OSS_REQUEST_PAYER = "x-oss-request-payer"; + const OSS_TRAFFIC_LIMIT = "x-oss-traffic-limit"; + //Constants for STS SecurityToken + const OSS_SECURITY_TOKEN = "x-oss-security-token"; + const OSS_ACL_TYPE_PRIVATE = 'private'; + const OSS_ACL_TYPE_PUBLIC_READ = 'public-read'; + const OSS_ACL_TYPE_PUBLIC_READ_WRITE = 'public-read-write'; + const OSS_ENCODING_TYPE = "encoding-type"; + const OSS_ENCODING_TYPE_URL = "url"; + + const OSS_LIST_TYPE = "list-type"; + + // Domain Types + const OSS_HOST_TYPE_NORMAL = "normal";//http://bucket.oss-cn-hangzhou.aliyuncs.com/object + const OSS_HOST_TYPE_IP = "ip"; //http://1.1.1.1/bucket/object + const OSS_HOST_TYPE_SPECIAL = 'special'; //http://bucket.guizhou.gov/object + const OSS_HOST_TYPE_CNAME = "cname"; //http://mydomain.com/object + const OSS_HOST_TYPE_PATH_STYLE = "path-style"; //http://oss-cn-hangzhou.aliyuncs.com/bucket/object + //OSS ACL array + static $OSS_ACL_TYPES = array( + self::OSS_ACL_TYPE_PRIVATE, + self::OSS_ACL_TYPE_PUBLIC_READ, + self::OSS_ACL_TYPE_PUBLIC_READ_WRITE + ); + // OssClient version information + const OSS_NAME = "aliyun-sdk-php"; + const OSS_VERSION = "2.7.2"; + const OSS_BUILD = "20241028"; + const OSS_AUTHOR = ""; + const OSS_OPTIONS_ORIGIN = 'Origin'; + const OSS_OPTIONS_REQUEST_METHOD = 'Access-Control-Request-Method'; + const OSS_OPTIONS_REQUEST_HEADERS = 'Access-Control-Request-Headers'; + + // signatrue version information + const OSS_SIGNATURE_VERSION_V1 = "v1"; + const OSS_SIGNATURE_VERSION_V4 = "v4"; + const OSS_DEFAULT_PRODUCT = "oss"; + const OSS_CLOUDBOX_PRODUCT = "oss-cloudbox"; + + //use ssl flag + private $useSSL = false; + private $maxRetries = 3; + private $redirects = 0; + + // user's domain type. It could be one of the four: OSS_HOST_TYPE_NORMAL, OSS_HOST_TYPE_IP, OSS_HOST_TYPE_SPECIAL, OSS_HOST_TYPE_CNAME + private $hostType = self::OSS_HOST_TYPE_NORMAL; + private $requestProxy = null; + /** + * @var CredentialsProvider + */ + private $provider; + private $hostname; + private $enableStrictObjName; + private $timeout = 0; + private $connectTimeout = 0; + private $cloudBoxId = null; + private $region = null; + /** + * @var SignerV1|SignerV4 + */ + private $signer; + + private $checkObjectEncoding = false; + + private $filePathCompatible; +} diff --git a/addons/alioss/library/OSS/Result/AclResult.php b/addons/alioss/library/OSS/Result/AclResult.php new file mode 100644 index 0000000..7061ff0 --- /dev/null +++ b/addons/alioss/library/OSS/Result/AclResult.php @@ -0,0 +1,31 @@ +rawResponse->body; + if (empty($content)) { + throw new OssException("body is null"); + } + $xml = simplexml_load_string($content); + if (isset($xml->AccessControlList->Grant)) { + return strval($xml->AccessControlList->Grant); + } else { + throw new OssException("xml format exception"); + } + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/AppendResult.php b/addons/alioss/library/OSS/Result/AppendResult.php new file mode 100644 index 0000000..d898d58 --- /dev/null +++ b/addons/alioss/library/OSS/Result/AppendResult.php @@ -0,0 +1,27 @@ +rawResponse->header; + if (isset($header["x-oss-next-append-position"])) { + return intval($header["x-oss-next-append-position"]); + } + throw new OssException("cannot get next-append-position"); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/BodyResult.php b/addons/alioss/library/OSS/Result/BodyResult.php new file mode 100644 index 0000000..44ba15e --- /dev/null +++ b/addons/alioss/library/OSS/Result/BodyResult.php @@ -0,0 +1,19 @@ +rawResponse->body) ? "" : $this->rawResponse->body; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/CallbackResult.php b/addons/alioss/library/OSS/Result/CallbackResult.php new file mode 100644 index 0000000..514e985 --- /dev/null +++ b/addons/alioss/library/OSS/Result/CallbackResult.php @@ -0,0 +1,21 @@ +rawResponse->status; + if ((int)(intval($status) / 100) == 2 && (int)(intval($status)) !== 203) { + return true; + } + return false; + } + +} diff --git a/addons/alioss/library/OSS/Result/CopyObjectResult.php b/addons/alioss/library/OSS/Result/CopyObjectResult.php new file mode 100644 index 0000000..6ed67c6 --- /dev/null +++ b/addons/alioss/library/OSS/Result/CopyObjectResult.php @@ -0,0 +1,30 @@ +rawResponse->body; + $xml = simplexml_load_string($body); + $result = array(); + + if (isset($xml->LastModified)) { + $result[] = $xml->LastModified; + } + if (isset($xml->ETag)) { + $result[] = $xml->ETag; + } + + return array_merge($result, $this->rawResponse->header); + } +} diff --git a/addons/alioss/library/OSS/Result/CreateBucketCnameTokenResult.php b/addons/alioss/library/OSS/Result/CreateBucketCnameTokenResult.php new file mode 100644 index 0000000..a38ca0d --- /dev/null +++ b/addons/alioss/library/OSS/Result/CreateBucketCnameTokenResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $info = new CnameTokenInfo(); + $info->parseFromXml($content); + return $info; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/DeleteObjectVersionsResult.php b/addons/alioss/library/OSS/Result/DeleteObjectVersionsResult.php new file mode 100644 index 0000000..69f52a7 --- /dev/null +++ b/addons/alioss/library/OSS/Result/DeleteObjectVersionsResult.php @@ -0,0 +1,39 @@ +rawResponse->body); + $encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : ""; + return $this->parseDeletedList($xml, $encodingType); + } + + private function parseDeletedList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->Deleted)) { + foreach ($xml->Deleted as $content) { + $key = isset($content->Key) ? strval($content->Key) : ""; + $key = OssUtil::decodeKey($key, $encodingType); + $versionId = isset($content->VersionId) ? strval($content->VersionId) : ""; + $deleteMarker = isset($content->DeleteMarker) ? strval($content->DeleteMarker) : ""; + $deleteMarkerVersionId = isset($content->DeleteMarkerVersionId) ? strval($content->DeleteMarkerVersionId) : ""; + $retList[] = new DeletedObjectInfo($key, $versionId, $deleteMarker, $deleteMarkerVersionId); + } + } + return $retList; + } +} diff --git a/addons/alioss/library/OSS/Result/DeleteObjectsResult.php b/addons/alioss/library/OSS/Result/DeleteObjectsResult.php new file mode 100644 index 0000000..dc373b8 --- /dev/null +++ b/addons/alioss/library/OSS/Result/DeleteObjectsResult.php @@ -0,0 +1,27 @@ +rawResponse->body; + $xml = simplexml_load_string($body); + $objects = array(); + + if (isset($xml->Deleted)) { + foreach($xml->Deleted as $deleteKey) + $objects[] = $deleteKey->Key; + } + return $objects; + } +} diff --git a/addons/alioss/library/OSS/Result/ExistResult.php b/addons/alioss/library/OSS/Result/ExistResult.php new file mode 100644 index 0000000..e9522d4 --- /dev/null +++ b/addons/alioss/library/OSS/Result/ExistResult.php @@ -0,0 +1,34 @@ +rawResponse->status) === 200 ? true : false; + } + + /** + * Check if the response status is OK according to the http status code. + * [200-299]: OK; [404]: Not found. It means the object or bucket is not found--it's a valid response too. + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) { + return true; + } + return false; + } + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetBucketCnameTokenResult.php b/addons/alioss/library/OSS/Result/GetBucketCnameTokenResult.php new file mode 100644 index 0000000..b524d3f --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketCnameTokenResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $info = new CnameTokenInfo(); + $info->parseFromXml($content); + return $info; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetBucketEncryptionResult.php b/addons/alioss/library/OSS/Result/GetBucketEncryptionResult.php new file mode 100644 index 0000000..3987cc9 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketEncryptionResult.php @@ -0,0 +1,26 @@ +rawResponse->body; + $config = new ServerSideEncryptionConfig(); + $config->parseFromXml($content); + return $config; + } +} diff --git a/addons/alioss/library/OSS/Result/GetBucketInfoResult.php b/addons/alioss/library/OSS/Result/GetBucketInfoResult.php new file mode 100644 index 0000000..d467851 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketInfoResult.php @@ -0,0 +1,37 @@ +rawResponse->body; + if (empty($content)) { + throw new OssException("body is null"); + } + $xml = simplexml_load_string($content); + if (isset($xml->Bucket)) { + $info = new BucketInfo(); + $info->parseFromXmlNode($xml->Bucket); + return $info; + } else { + throw new OssException("xml format exception"); + } + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetBucketRequestPaymentResult.php b/addons/alioss/library/OSS/Result/GetBucketRequestPaymentResult.php new file mode 100644 index 0000000..5107de3 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketRequestPaymentResult.php @@ -0,0 +1,26 @@ +rawResponse->body; + $config = new RequestPaymentConfig(); + $config->parseFromXml($content); + return $config->getPayer(); + } +} diff --git a/addons/alioss/library/OSS/Result/GetBucketStatResult.php b/addons/alioss/library/OSS/Result/GetBucketStatResult.php new file mode 100644 index 0000000..aa310cf --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketStatResult.php @@ -0,0 +1,26 @@ +rawResponse->body; + $stat = new BucketStat(); + $stat->parseFromXml($content); + return $stat; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetBucketTagsResult.php b/addons/alioss/library/OSS/Result/GetBucketTagsResult.php new file mode 100644 index 0000000..59b4dd7 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketTagsResult.php @@ -0,0 +1,26 @@ +rawResponse->body; + $config = new TaggingConfig(); + $config->parseFromXml($content); + return $config; + } +} diff --git a/addons/alioss/library/OSS/Result/GetBucketTransferAccelerationResult.php b/addons/alioss/library/OSS/Result/GetBucketTransferAccelerationResult.php new file mode 100644 index 0000000..a300d62 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketTransferAccelerationResult.php @@ -0,0 +1,22 @@ +rawResponse->body; + $config = new TransferAccelerationConfig(); + $config->parseFromXml($content); + return $config->getEnabled(); + } +} diff --git a/addons/alioss/library/OSS/Result/GetBucketVersioningResult.php b/addons/alioss/library/OSS/Result/GetBucketVersioningResult.php new file mode 100644 index 0000000..225190c --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketVersioningResult.php @@ -0,0 +1,26 @@ +rawResponse->body; + $config = new VersioningConfig(); + $config->parseFromXml($content); + return $config->getStatus(); + } +} diff --git a/addons/alioss/library/OSS/Result/GetBucketWormResult.php b/addons/alioss/library/OSS/Result/GetBucketWormResult.php new file mode 100644 index 0000000..9587204 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetBucketWormResult.php @@ -0,0 +1,26 @@ +rawResponse->body; + $config = new WormConfig(); + $config->parseFromXml($content); + return $config; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetCnameResult.php b/addons/alioss/library/OSS/Result/GetCnameResult.php new file mode 100644 index 0000000..eed01f9 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetCnameResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $config = new CnameConfig(); + $config->parseFromXml($content); + return $config; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetCorsResult.php b/addons/alioss/library/OSS/Result/GetCorsResult.php new file mode 100644 index 0000000..8fb10ea --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetCorsResult.php @@ -0,0 +1,34 @@ +rawResponse->body; + $config = new CorsConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * Check if the response is OK, according to the http status. [200-299]:OK, the Cors config could be got; [404]: not found--no Cors config. + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) { + return true; + } + return false; + } + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetLifecycleResult.php b/addons/alioss/library/OSS/Result/GetLifecycleResult.php new file mode 100644 index 0000000..e0a9595 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetLifecycleResult.php @@ -0,0 +1,41 @@ +rawResponse->body; + $config = new LifecycleConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * Check if the response is OK according to the http status. + * [200-299]: OK, and the LifecycleConfig could be got; [404] The Life cycle config is not found. + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) { + return true; + } + return false; + } +} diff --git a/addons/alioss/library/OSS/Result/GetLiveChannelHistoryResult.php b/addons/alioss/library/OSS/Result/GetLiveChannelHistoryResult.php new file mode 100644 index 0000000..5d5bc92 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetLiveChannelHistoryResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $channelList = new GetLiveChannelHistory(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/addons/alioss/library/OSS/Result/GetLiveChannelInfoResult.php b/addons/alioss/library/OSS/Result/GetLiveChannelInfoResult.php new file mode 100644 index 0000000..cefe460 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetLiveChannelInfoResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $channelList = new GetLiveChannelInfo(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/addons/alioss/library/OSS/Result/GetLiveChannelStatusResult.php b/addons/alioss/library/OSS/Result/GetLiveChannelStatusResult.php new file mode 100644 index 0000000..6b8a60f --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetLiveChannelStatusResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $channelList = new GetLiveChannelStatus(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/addons/alioss/library/OSS/Result/GetLocationResult.php b/addons/alioss/library/OSS/Result/GetLocationResult.php new file mode 100644 index 0000000..a0c5129 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetLocationResult.php @@ -0,0 +1,30 @@ +rawResponse->body; + if (empty($content)) { + throw new OssException("body is null"); + } + $xml = simplexml_load_string($content); + return $xml; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetLoggingResult.php b/addons/alioss/library/OSS/Result/GetLoggingResult.php new file mode 100644 index 0000000..eab8c64 --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetLoggingResult.php @@ -0,0 +1,41 @@ +rawResponse->body; + $config = new LoggingConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * Judged according to the return HTTP status code, [200-299] that is OK, get the bucket configuration interface, + * 404 is also considered a valid response + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetRefererResult.php b/addons/alioss/library/OSS/Result/GetRefererResult.php new file mode 100644 index 0000000..a8a649e --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetRefererResult.php @@ -0,0 +1,41 @@ +rawResponse->body; + $config = new RefererConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * Judged according to the return HTTP status code, [200-299] that is OK, get the bucket configuration interface, + * 404 is also considered a valid response + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetStorageCapacityResult.php b/addons/alioss/library/OSS/Result/GetStorageCapacityResult.php new file mode 100644 index 0000000..2f4127b --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetStorageCapacityResult.php @@ -0,0 +1,34 @@ +rawResponse->body; + if (empty($content)) { + throw new OssException("body is null"); + } + $xml = simplexml_load_string($content); + if (isset($xml->StorageCapacity)) { + return intval($xml->StorageCapacity); + } else { + throw new OssException("xml format exception"); + } + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/GetWebsiteResult.php b/addons/alioss/library/OSS/Result/GetWebsiteResult.php new file mode 100644 index 0000000..64d54fa --- /dev/null +++ b/addons/alioss/library/OSS/Result/GetWebsiteResult.php @@ -0,0 +1,40 @@ +rawResponse->body; + $config = new WebsiteConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * Judged according to the return HTTP status code, [200-299] that is OK, get the bucket configuration interface, + * 404 is also considered a valid response + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/HeaderResult.php b/addons/alioss/library/OSS/Result/HeaderResult.php new file mode 100644 index 0000000..1ca4d1a --- /dev/null +++ b/addons/alioss/library/OSS/Result/HeaderResult.php @@ -0,0 +1,23 @@ +rawResponse->header) ? array() : $this->rawResponse->header; + } + +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/InitiateBucketWormResult.php b/addons/alioss/library/OSS/Result/InitiateBucketWormResult.php new file mode 100644 index 0000000..1cd7a02 --- /dev/null +++ b/addons/alioss/library/OSS/Result/InitiateBucketWormResult.php @@ -0,0 +1,27 @@ +rawResponse->header; + if (isset($header["x-oss-worm-id"])) { + return strval($header["x-oss-worm-id"]); + } + throw new OssException("cannot get worm-id"); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/InitiateMultipartUploadResult.php b/addons/alioss/library/OSS/Result/InitiateMultipartUploadResult.php new file mode 100644 index 0000000..53a15da --- /dev/null +++ b/addons/alioss/library/OSS/Result/InitiateMultipartUploadResult.php @@ -0,0 +1,29 @@ +rawResponse->body; + $xml = simplexml_load_string($content); + if (isset($xml->UploadId)) { + return strval($xml->UploadId); + } + throw new OssException("cannot get UploadId"); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/ListBucketsResult.php b/addons/alioss/library/OSS/Result/ListBucketsResult.php new file mode 100644 index 0000000..1dd037b --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListBucketsResult.php @@ -0,0 +1,32 @@ +rawResponse->body; + $xml = new \SimpleXMLElement($content); + if (isset($xml->Buckets) && isset($xml->Buckets->Bucket)) { + foreach ($xml->Buckets->Bucket as $bucket) { + $bucketInfo = new BucketInfo(); + $bucketInfo->parseFromXmlNode($bucket); + $bucketList[] = $bucketInfo; + } + } + return new BucketListInfo($bucketList); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/ListLiveChannelResult.php b/addons/alioss/library/OSS/Result/ListLiveChannelResult.php new file mode 100644 index 0000000..1a6e2a4 --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListLiveChannelResult.php @@ -0,0 +1,16 @@ +rawResponse->body; + $channelList = new LiveChannelListInfo(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/addons/alioss/library/OSS/Result/ListMultipartUploadResult.php b/addons/alioss/library/OSS/Result/ListMultipartUploadResult.php new file mode 100644 index 0000000..3220c86 --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListMultipartUploadResult.php @@ -0,0 +1,55 @@ +rawResponse->body; + $xml = simplexml_load_string($content); + + $encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : ""; + $bucket = isset($xml->Bucket) ? strval($xml->Bucket) : ""; + $keyMarker = isset($xml->KeyMarker) ? strval($xml->KeyMarker) : ""; + $keyMarker = OssUtil::decodeKey($keyMarker, $encodingType); + $uploadIdMarker = isset($xml->UploadIdMarker) ? strval($xml->UploadIdMarker) : ""; + $nextKeyMarker = isset($xml->NextKeyMarker) ? strval($xml->NextKeyMarker) : ""; + $nextKeyMarker = OssUtil::decodeKey($nextKeyMarker, $encodingType); + $nextUploadIdMarker = isset($xml->NextUploadIdMarker) ? strval($xml->NextUploadIdMarker) : ""; + $delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : ""; + $delimiter = OssUtil::decodeKey($delimiter, $encodingType); + $prefix = isset($xml->Prefix) ? strval($xml->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $maxUploads = isset($xml->MaxUploads) ? intval($xml->MaxUploads) : 0; + $isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : ""; + $listUpload = array(); + + if (isset($xml->Upload)) { + foreach ($xml->Upload as $upload) { + $key = isset($upload->Key) ? strval($upload->Key) : ""; + $key = OssUtil::decodeKey($key, $encodingType); + $uploadId = isset($upload->UploadId) ? strval($upload->UploadId) : ""; + $initiated = isset($upload->Initiated) ? strval($upload->Initiated) : ""; + $listUpload[] = new UploadInfo($key, $uploadId, $initiated); + } + } + return new ListMultipartUploadInfo($bucket, $keyMarker, $uploadIdMarker, + $nextKeyMarker, $nextUploadIdMarker, + $delimiter, $prefix, $maxUploads, $isTruncated, $listUpload); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/ListObjectVersionsResult.php b/addons/alioss/library/OSS/Result/ListObjectVersionsResult.php new file mode 100644 index 0000000..4503c03 --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListObjectVersionsResult.php @@ -0,0 +1,98 @@ +rawResponse->body); + $encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : ""; + $objectVersionList = $this->parseObjecVersionList($xml, $encodingType); + $deleteMarkerList = $this->parseDeleteMarkerList($xml, $encodingType); + $prefixList = $this->parsePrefixList($xml, $encodingType); + $bucketName = isset($xml->Name) ? strval($xml->Name) : ""; + $prefix = isset($xml->Prefix) ? strval($xml->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $keyMarker = isset($xml->KeyMarker) ? strval($xml->KeyMarker) : ""; + $keyMarker = OssUtil::decodeKey($keyMarker, $encodingType); + $nextKeyMarker = isset($xml->NextKeyMarker) ? strval($xml->NextKeyMarker) : ""; + $nextKeyMarker = OssUtil::decodeKey($nextKeyMarker, $encodingType); + $versionIdMarker = isset($xml->VersionIdMarker) ? strval($xml->VersionIdMarker) : ""; + $nextVersionIdMarker = isset($xml->NextVersionIdMarker) ? strval($xml->NextVersionIdMarker) : ""; + $maxKeys = isset($xml->MaxKeys) ? intval($xml->MaxKeys) : 0; + $delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : ""; + $delimiter = OssUtil::decodeKey($delimiter, $encodingType); + $isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : ""; + + return new ObjectVersionListInfo($bucketName, $prefix, $keyMarker, $nextKeyMarker, + $versionIdMarker, $nextVersionIdMarker, $maxKeys, $delimiter, $isTruncated, + $objectVersionList, $deleteMarkerList, $prefixList); + } + + private function parseObjecVersionList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->Version)) { + foreach ($xml->Version as $content) { + $key = isset($content->Key) ? strval($content->Key) : ""; + $key = OssUtil::decodeKey($key, $encodingType); + $versionId = isset($content->VersionId) ? strval($content->VersionId) : ""; + $lastModified = isset($content->LastModified) ? strval($content->LastModified) : ""; + $eTag = isset($content->ETag) ? strval($content->ETag) : ""; + $type = isset($content->Type) ? strval($content->Type) : ""; + $size = isset($content->Size) ? strval($content->Size) : "0"; + $storageClass = isset($content->StorageClass) ? strval($content->StorageClass) : ""; + $isLatest = isset($content->IsLatest) ? strval($content->IsLatest) : ""; + $retList[] = new ObjectVersionInfo($key, $versionId, $lastModified, $eTag, $type, $size, $storageClass, $isLatest); + } + } + return $retList; + } + + private function parseDeleteMarkerList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->DeleteMarker)) { + foreach ($xml->DeleteMarker as $content) { + $key = isset($content->Key) ? strval($content->Key) : ""; + $key = OssUtil::decodeKey($key, $encodingType); + $versionId = isset($content->VersionId) ? strval($content->VersionId) : ""; + $lastModified = isset($content->LastModified) ? strval($content->LastModified) : ""; + $isLatest = isset($content->IsLatest) ? strval($content->IsLatest) : ""; + $retList[] = new DeleteMarkerInfo($key, $versionId, $lastModified, $isLatest); + } + } + return $retList; + } + + private function parsePrefixList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->CommonPrefixes)) { + foreach ($xml->CommonPrefixes as $commonPrefix) { + $prefix = isset($commonPrefix->Prefix) ? strval($commonPrefix->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $retList[] = new PrefixInfo($prefix); + } + } + return $retList; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/ListObjectsResult.php b/addons/alioss/library/OSS/Result/ListObjectsResult.php new file mode 100644 index 0000000..1246174 --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListObjectsResult.php @@ -0,0 +1,80 @@ +rawResponse->body); + $encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : ""; + $objectList = $this->parseObjectList($xml, $encodingType); + $prefixList = $this->parsePrefixList($xml, $encodingType); + $bucketName = isset($xml->Name) ? strval($xml->Name) : ""; + $prefix = isset($xml->Prefix) ? strval($xml->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $marker = isset($xml->Marker) ? strval($xml->Marker) : ""; + $marker = OssUtil::decodeKey($marker, $encodingType); + $maxKeys = isset($xml->MaxKeys) ? intval($xml->MaxKeys) : 0; + $delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : ""; + $delimiter = OssUtil::decodeKey($delimiter, $encodingType); + $isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : ""; + $nextMarker = isset($xml->NextMarker) ? strval($xml->NextMarker) : ""; + $nextMarker = OssUtil::decodeKey($nextMarker, $encodingType); + return new ObjectListInfo($bucketName, $prefix, $marker, $nextMarker, $maxKeys, $delimiter, $isTruncated, $objectList, $prefixList); + } + + private function parseObjectList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->Contents)) { + foreach ($xml->Contents as $content) { + $key = isset($content->Key) ? strval($content->Key) : ""; + $key = OssUtil::decodeKey($key, $encodingType); + $lastModified = isset($content->LastModified) ? strval($content->LastModified) : ""; + $eTag = isset($content->ETag) ? strval($content->ETag) : ""; + $type = isset($content->Type) ? strval($content->Type) : ""; + $size = isset($content->Size) ? strval($content->Size) : "0"; + $storageClass = isset($content->StorageClass) ? strval($content->StorageClass) : ""; + if(isset($content->Owner)){ + $owner = new Owner(strval($content->Owner->ID),strval($content->Owner->DisplayName)); + }else{ + $owner = null; + } + $restoreInfo= isset($content->RestoreInfo) ? strval($content->RestoreInfo) : null; + $retList[] = new ObjectInfo($key, $lastModified, $eTag, $type, $size, $storageClass,$owner,$restoreInfo); + } + } + return $retList; + } + + private function parsePrefixList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->CommonPrefixes)) { + foreach ($xml->CommonPrefixes as $commonPrefix) { + $prefix = isset($commonPrefix->Prefix) ? strval($commonPrefix->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $retList[] = new PrefixInfo($prefix); + } + } + return $retList; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/ListObjectsV2Result.php b/addons/alioss/library/OSS/Result/ListObjectsV2Result.php new file mode 100644 index 0000000..8293767 --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListObjectsV2Result.php @@ -0,0 +1,81 @@ +rawResponse->body); + $encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : ""; + $objectList = $this->parseObjectList($xml, $encodingType); + $prefixList = $this->parsePrefixList($xml, $encodingType); + $bucketName = isset($xml->Name) ? strval($xml->Name) : ""; + $prefix = isset($xml->Prefix) ? strval($xml->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $maxKeys = isset($xml->MaxKeys) ? intval($xml->MaxKeys) : 0; + $delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : ""; + $delimiter = OssUtil::decodeKey($delimiter, $encodingType); + $isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : ""; + $continuationToken = isset($xml->ContinuationToken) ? strval($xml->ContinuationToken) : ""; + $nextContinuationToken = isset($xml->NextContinuationToken) ? strval($xml->NextContinuationToken) : ""; + $startAfter = isset($xml->StartAfter) ? strval($xml->StartAfter) : ""; + $startAfter = OssUtil::decodeKey($startAfter, $encodingType); + $keyCount = isset($xml->KeyCount) ? intval($xml->KeyCount) : 0; + return new ObjectListInfoV2($bucketName, $prefix, $maxKeys, $delimiter, $isTruncated, $objectList, $prefixList, $continuationToken, $nextContinuationToken, $startAfter, $keyCount); + } + + private function parseObjectList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->Contents)) { + foreach ($xml->Contents as $content) { + $key = isset($content->Key) ? strval($content->Key) : ""; + $key = OssUtil::decodeKey($key, $encodingType); + $lastModified = isset($content->LastModified) ? strval($content->LastModified) : ""; + $eTag = isset($content->ETag) ? strval($content->ETag) : ""; + $type = isset($content->Type) ? strval($content->Type) : ""; + $size = isset($content->Size) ? strval($content->Size) : "0"; + $storageClass = isset($content->StorageClass) ? strval($content->StorageClass) : ""; + if(isset($content->Owner)){ + $owner = new Owner(strval($content->Owner->ID),strval($content->Owner->DisplayName)); + }else{ + $owner = null; + } + $restoreInfo= isset($content->RestoreInfo) ? strval($content->RestoreInfo) : null; + $retList[] = new ObjectInfo($key, $lastModified, $eTag, $type, $size, $storageClass,$owner,$restoreInfo); + } + } + return $retList; + } + + private function parsePrefixList($xml, $encodingType) + { + $retList = array(); + if (isset($xml->CommonPrefixes)) { + foreach ($xml->CommonPrefixes as $commonPrefix) { + $prefix = isset($commonPrefix->Prefix) ? strval($commonPrefix->Prefix) : ""; + $prefix = OssUtil::decodeKey($prefix, $encodingType); + $retList[] = new PrefixInfo($prefix); + } + } + return $retList; + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/ListPartsResult.php b/addons/alioss/library/OSS/Result/ListPartsResult.php new file mode 100644 index 0000000..6641b5b --- /dev/null +++ b/addons/alioss/library/OSS/Result/ListPartsResult.php @@ -0,0 +1,42 @@ +rawResponse->body; + $xml = simplexml_load_string($content); + $bucket = isset($xml->Bucket) ? strval($xml->Bucket) : ""; + $key = isset($xml->Key) ? strval($xml->Key) : ""; + $uploadId = isset($xml->UploadId) ? strval($xml->UploadId) : ""; + $nextPartNumberMarker = isset($xml->NextPartNumberMarker) ? intval($xml->NextPartNumberMarker) : ""; + $maxParts = isset($xml->MaxParts) ? intval($xml->MaxParts) : ""; + $isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : ""; + $partList = array(); + if (isset($xml->Part)) { + foreach ($xml->Part as $part) { + $partNumber = isset($part->PartNumber) ? intval($part->PartNumber) : ""; + $lastModified = isset($part->LastModified) ? strval($part->LastModified) : ""; + $eTag = isset($part->ETag) ? strval($part->ETag) : ""; + $size = isset($part->Size) ? strval($part->Size) : ""; + $partList[] = new PartInfo($partNumber, $lastModified, $eTag, $size); + } + } + return new ListPartsInfo($bucket, $key, $uploadId, $nextPartNumberMarker, $maxParts, $isTruncated, $partList); + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/PutLiveChannelResult.php b/addons/alioss/library/OSS/Result/PutLiveChannelResult.php new file mode 100644 index 0000000..dcac86b --- /dev/null +++ b/addons/alioss/library/OSS/Result/PutLiveChannelResult.php @@ -0,0 +1,16 @@ +rawResponse->body; + $channel = new LiveChannelInfo(); + $channel->parseFromXml($content); + return $channel; + } +} diff --git a/addons/alioss/library/OSS/Result/PutSetDeleteResult.php b/addons/alioss/library/OSS/Result/PutSetDeleteResult.php new file mode 100644 index 0000000..97af003 --- /dev/null +++ b/addons/alioss/library/OSS/Result/PutSetDeleteResult.php @@ -0,0 +1,20 @@ + $this->rawResponse->body); + return array_merge($this->rawResponse->header, $body); + } +} diff --git a/addons/alioss/library/OSS/Result/Result.php b/addons/alioss/library/OSS/Result/Result.php new file mode 100644 index 0000000..597ac5a --- /dev/null +++ b/addons/alioss/library/OSS/Result/Result.php @@ -0,0 +1,213 @@ +rawResponse = $response; + $this->parseResponse(); + } + + /** + * Get requestId + * + * @return string + */ + public function getRequestId() + { + if (isset($this->rawResponse) && + isset($this->rawResponse->header) && + isset($this->rawResponse->header['x-oss-request-id']) + ) { + return $this->rawResponse->header['x-oss-request-id']; + } else { + return ''; + } + } + + /** + * Get the returned data, different request returns the data format is different + * + * $return mixed + */ + public function getData() + { + return $this->parsedData; + } + + /** + * Subclass implementation, different requests return data has different analytical logic, implemented by subclasses + * + * @return mixed + */ + abstract protected function parseDataFromResponse(); + + /** + * Whether the operation is successful + * + * @return mixed + */ + public function isOK() + { + return $this->isOk; + } + + /** + * @throws OssException + */ + public function parseResponse() + { + $this->isOk = $this->isResponseOk(); + if ($this->isOk) { + $this->parsedData = $this->parseDataFromResponse(); + } else { + $httpStatus = strval($this->rawResponse->status); + $requestId = strval($this->getRequestId()); + $code = $this->retrieveErrorCode($this->rawResponse->body); + $message = $this->retrieveErrorMessage($this->rawResponse->body); + $body = $this->rawResponse->body; + + $details = array( + 'status' => $httpStatus, + 'request-id' => $requestId, + 'code' => $code, + 'message' => $message, + 'body' => $body + ); + throw new OssException($details); + } + } + + /** + * Try to get the error message from body + * + * @param $body + * @return string + */ + private function retrieveErrorMessage($body) + { + if (empty($body) || false === strpos($body, 'Message)) { + return strval($xml->Message); + } + $flag = true; + } catch (\Exception $e) { + $flag = true; + } + if ($flag === true) { + $start = strpos($body, ''); + if ($start === false) { + return ''; + } + $start += 9; + $end = strpos($body, '', $start); + if ($end === false) { + return ''; + } + return substr($body, $start, $end - $start); + } + + return ''; + } + + /** + * Try to get the error Code from body + * + * @param $body + * @return string + */ + private function retrieveErrorCode($body) + { + if (empty($body) || false === strpos($body, 'Code)) { + return strval($xml->Code); + } + $flag = true; + } catch (\Exception $e) { + $flag = true; + } + if ($flag === true) { + $start = strpos($body, ''); + if ($start === false) { + return ''; + } + $start += 6; + $end = strpos($body, '', $start); + if ($end === false) { + return ''; + } + return substr($body, $start, $end - $start); + } + + return ''; + } + + /** + * Judging from the return http status code, [200-299] that is OK + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2) { + return true; + } + return false; + } + + /** + * Return the original return data + * + * @return ResponseCore + */ + public function getRawResponse() + { + return $this->rawResponse; + } + + /** + * Indicate whether the request is successful + */ + protected $isOk = false; + /** + * Data parsed by subclasses + */ + protected $parsedData = null; + /** + * Store the original Response returned by the auth function + * + * @var ResponseCore + */ + protected $rawResponse; +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Result/SymlinkResult.php b/addons/alioss/library/OSS/Result/SymlinkResult.php new file mode 100644 index 0000000..9c6d861 --- /dev/null +++ b/addons/alioss/library/OSS/Result/SymlinkResult.php @@ -0,0 +1,24 @@ +rawResponse->header[OssClient::OSS_SYMLINK_TARGET] = rawurldecode($this->rawResponse->header[OssClient::OSS_SYMLINK_TARGET]); + return $this->rawResponse->header; + } +} + diff --git a/addons/alioss/library/OSS/Result/UploadPartResult.php b/addons/alioss/library/OSS/Result/UploadPartResult.php new file mode 100644 index 0000000..c6b66d4 --- /dev/null +++ b/addons/alioss/library/OSS/Result/UploadPartResult.php @@ -0,0 +1,28 @@ +rawResponse->header; + if (isset($header["etag"])) { + return $header["etag"]; + } + throw new OssException("cannot get ETag"); + + } +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Signer/SignerInterface.php b/addons/alioss/library/OSS/Signer/SignerInterface.php new file mode 100644 index 0000000..c592a4f --- /dev/null +++ b/addons/alioss/library/OSS/Signer/SignerInterface.php @@ -0,0 +1,12 @@ +request_headers['Date'])) { + $request->add_header('Date', gmdate('D, d M Y H:i:s \G\M\T')); + } + // Credentials information + if (!empty($credentials->getSecurityToken())) { + $request->add_header("x-oss-security-token", $credentials->getSecurityToken()); + } + $headers = $request->request_headers; + $method = strtoupper($request->method); + $date = $headers['Date']; + $resourcePath = $this->getResourcePath($options); + $queryString = parse_url($request->request_url, PHP_URL_QUERY); + $query = array(); + if ($queryString !== null) { + parse_str($queryString, $query); + } + $stringToSign = $this->calcStringToSign($method, $date, $headers, $resourcePath, $query); +// printf("sign str:%s" . PHP_EOL, $stringToSign); + $options['string_to_sign'] = $stringToSign; + $signature = base64_encode(hash_hmac('sha1', $stringToSign, $credentials->getAccessKeySecret(), true)); + $request->add_header('Authorization', 'OSS ' . $credentials->getAccessKeyId() . ':' . $signature); + } + + public function presign(RequestCore $request, Credentials $credentials, array &$options) + { + $headers = $request->request_headers; + // Date + $expiration = $options['expiration']; + if (!isset($request->request_headers['Date'])) { + $request->add_header('Date', gmdate('D, d M Y H:i:s \G\M\T')); + } + $parsed_url = parse_url($request->request_url); + $queryString = isset($parsed_url['query']) ? $parsed_url['query'] : ''; + $query = array(); + if ($queryString !== null) { + parse_str($queryString, $query); + } + // Credentials information + if (!empty($credentials->getSecurityToken())) { + $query["security-token"] = $credentials->getSecurityToken(); + } + $method = strtoupper($request->method); + $date = $expiration . ""; + $resourcePath = $this->getResourcePath($options); + $stringToSign = $this->calcStringToSign($method, $date, $headers, $resourcePath, $query); + $options['string_to_sign'] = $stringToSign; + $signature = base64_encode(hash_hmac('sha1', $stringToSign, $credentials->getAccessKeySecret(), true)); + $query['OSSAccessKeyId'] = $credentials->getAccessKeyId(); + $query['Expires'] = $date; + $query['Signature'] = $signature; + $queryString = OssUtil::toQueryString($query); + $parsed_url['query'] = $queryString; + $request->request_url = OssUtil::unparseUrl($parsed_url); + } + + private function getResourcePath(array $options) + { + $resourcePath = '/'; + if (strlen($options['bucket']) > 0) { + $resourcePath .= $options['bucket'] . '/'; + } + if (strlen($options['key']) > 0) { + $resourcePath .= $options['key']; + } + return $resourcePath; + } + + private function calcStringToSign($method, $date, array $headers, $resourcePath, array $query) + { + /* + SignToString = + VERB + "\n" + + Content-MD5 + "\n" + + Content-Type + "\n" + + Date + "\n" + + CanonicalizedOSSHeaders + + CanonicalizedResource + Signature = base64(hmac-sha1(AccessKeySecret, SignToString)) + */ + $contentMd5 = ''; + $contentType = ''; + // CanonicalizedOSSHeaders + $signheaders = array(); + foreach ($headers as $key => $value) { + $lowk = strtolower($key); + if (strncmp($lowk, "x-oss-", 6) == 0) { + $signheaders[$lowk] = $value; + } else if ($lowk === 'content-md5') { + $contentMd5 = $value; + } else if ($lowk === 'content-type') { + $contentType = $value; + } + } + ksort($signheaders); + $canonicalizedOSSHeaders = ''; + foreach ($signheaders as $key => $value) { + $canonicalizedOSSHeaders .= $key . ':' . $value . "\n"; + } + // CanonicalizedResource + $signquery = array(); + foreach ($query as $key => $value) { + if (in_array($key, $this->signKeyList)) { + $signquery[$key] = $value; + } + } + ksort($signquery); + $sortedQueryList = array(); + foreach ($signquery as $key => $value) { + if (strlen($value) > 0) { + $sortedQueryList[] = $key . '=' . $value; + } else { + $sortedQueryList[] = $key; + } + } + $queryStringSorted = implode('&', $sortedQueryList); + $canonicalizedResource = $resourcePath; + if (!empty($queryStringSorted)) { + $canonicalizedResource .= '?' . $queryStringSorted; + } + return $method . "\n" . $contentMd5 . "\n" . $contentType . "\n" . $date . "\n" . $canonicalizedOSSHeaders . $canonicalizedResource; + } + + private $signKeyList = array( + "acl", "uploads", "location", "cors", + "logging", "website", "referer", "lifecycle", + "delete", "append", "tagging", "objectMeta", + "uploadId", "partNumber", "security-token", "x-oss-security-token", + "position", "img", "style", "styleName", + "replication", "replicationProgress", + "replicationLocation", "cname", "bucketInfo", + "comp", "qos", "live", "status", "vod", + "startTime", "endTime", "symlink", + "x-oss-process", "response-content-type", "x-oss-traffic-limit", + "response-content-language", "response-expires", + "response-cache-control", "response-content-disposition", + "response-content-encoding", "udf", "udfName", "udfImage", + "udfId", "udfImageDesc", "udfApplication", + "udfApplicationLog", "restore", "callback", "callback-var", "qosInfo", + "policy", "stat", "encryption", "versions", "versioning", "versionId", "requestPayment", + "x-oss-request-payer", "sequential", + "inventory", "inventoryId", "continuation-token", "asyncFetch", + "worm", "wormId", "wormExtend", "withHashContext", + "x-oss-enable-md5", "x-oss-enable-sha1", "x-oss-enable-sha256", + "x-oss-hash-ctx", "x-oss-md5-ctx", "transferAcceleration", + "regionList", "cloudboxes", "x-oss-ac-source-ip", "x-oss-ac-subnet-mask", "x-oss-ac-vpc-id", "x-oss-ac-forward-allow", + "metaQuery", "resourceGroup", "rtc", "x-oss-async-process", "responseHeader" + ); +} \ No newline at end of file diff --git a/addons/alioss/library/OSS/Signer/SignerV4.php b/addons/alioss/library/OSS/Signer/SignerV4.php new file mode 100644 index 0000000..039b04a --- /dev/null +++ b/addons/alioss/library/OSS/Signer/SignerV4.php @@ -0,0 +1,244 @@ +request_headers['Date'])) { + $request->add_header('Date', gmdate('D, d M Y H:i:s \G\M\T')); + } + $timestamp = strtotime($request->request_headers['Date']); + if ($timestamp === false) { + $timestamp = time(); + } + $datetime = gmdate('Ymd\THis\Z', $timestamp); + $date = substr($datetime, 0, 8); + $request->add_header("x-oss-date", $datetime); + if (!isset($request->request_headers['x-oss-content-sha256'])) { + $request->add_header("x-oss-content-sha256", 'UNSIGNED-PAYLOAD'); + } + // Credentials information + if (!empty($credentials->getSecurityToken())) { + $request->add_header("x-oss-security-token", $credentials->getSecurityToken()); + } + $headers = $request->request_headers; + $method = strtoupper($request->method); + $region = $options['region']; + $product = $options['product']; + $scope = $this->buildScope($date, $region, $product); + $resourcePath = $this->getResourcePath($options); + $additionalHeaders = $this->getCommonAdditionalHeaders($request, $options); + $queryString = parse_url($request->request_url, PHP_URL_QUERY); + $query = array(); + if ($queryString !== null) { + parse_str($queryString, $query); + } + $canonicalRequest = $this->calcCanonicalRequest($method, $resourcePath, $query, $headers, $additionalHeaders); + $stringToSign = $this->calcStringToSign($datetime, $scope, $canonicalRequest); +// printf('canonical request:%s' . PHP_EOL, $canonicalRequest); +// printf('sign str:%s' . PHP_EOL, $stringToSign); + $options['string_to_sign'] = $stringToSign; + $signature = $this->calcSignature($credentials->getAccessKeySecret(), $date, $region, $product, $stringToSign); + $authorization = 'OSS4-HMAC-SHA256 Credential=' . $credentials->getAccessKeyId() . '/' . $scope; + $additionalHeadersString = implode(';', $additionalHeaders); + if ($additionalHeadersString !== '') { + $authorization .= ',AdditionalHeaders=' . $additionalHeadersString; + } + $authorization .= ',Signature=' . $signature; + $request->add_header('Authorization', $authorization); + } + + public function presign(RequestCore $request, Credentials $credentials, array &$options) + { + if (!isset($request->request_headers['Date'])) { + $request->add_header('Date', gmdate('D, d M Y H:i:s \G\M\T')); + } + $timestamp = strtotime($request->request_headers['Date']); + if ($timestamp === false) { + $timestamp = time(); + } + $datetime = gmdate('Ymd\THis\Z', $timestamp); + $expiration = $options['expiration']; + $date = substr($datetime, 0, 8); + $expires = $expiration - $timestamp; + $headers = $request->request_headers; + $method = strtoupper($request->method); + $region = $options['region']; + $product = $options['product']; + $scope = $this->buildScope($date, $region, $product); + $resourcePath = $this->getResourcePath($options); + $additionalHeaders = $this->getCommonAdditionalHeaders($request, $options); + $queryString = parse_url($request->request_url, PHP_URL_QUERY); + $query = array(); + if ($queryString !== null) { + parse_str($queryString, $query); + } + if (!empty($credentials->getSecurityToken())) { + $query["x-oss-security-token"] = $credentials->getSecurityToken(); + } + $query["x-oss-signature-version"] = 'OSS4-HMAC-SHA256'; + $query["x-oss-date"] = $datetime; + $query["x-oss-expires"] = $expires; + $query["x-oss-credential"] = $credentials->getAccessKeyId() . '/' . $scope; + if (count($additionalHeaders) > 0) { + $query["x-oss-additional-headers"] = implode(";", $additionalHeaders); + } + $canonicalRequest = $this->calcCanonicalRequest($method, $resourcePath, $query, $headers, $additionalHeaders); + $stringToSign = $this->calcStringToSign($datetime, $scope, $canonicalRequest); +// printf('canonical request:%s' . PHP_EOL, $canonicalRequest); +// printf('sign str:%s' . PHP_EOL, $stringToSign); + $options['string_to_sign'] = $stringToSign; + $signature = $this->calcSignature($credentials->getAccessKeySecret(), $date, $region, $product, $stringToSign); + $query["x-oss-signature"] = $signature; + $queryStr = OssUtil::toQueryString($query); + $explodeUrl = explode('?', $request->request_url); + $index = count($explodeUrl); + if ($index === 1) { + $request->request_url .= '?' . $queryStr; + } else { + $baseUrl = $explodeUrl[0]; + $request->request_url = $baseUrl . '?' . $queryStr; + } + } + + private function getResourcePath(array $options) + { + $resourcePath = '/'; + if (strlen($options['bucket']) > 0) { + $resourcePath .= $options['bucket'] . '/'; + } + if (strlen($options['key']) > 0) { + $resourcePath .= $options['key']; + } + return $resourcePath; + } + + private function getCommonAdditionalHeaders(RequestCore $request, array $options) + { + if (isset($options[OssClient::OSS_ADDITIONAL_HEADERS])) { + $addHeaders = array(); + foreach ($options[OssClient::OSS_ADDITIONAL_HEADERS] as $key) { + $lowk = strtolower($key); + if ($this->isDefaultSignedHeader($lowk)) { + continue; + } + $addHeaders[$lowk] = ''; + } + $headers = array(); + foreach ($request->request_headers as $key => $value) { + $lowk = strtolower($key); + if (isset($addHeaders[$lowk])) { + $headers[$lowk] = ''; + } + } + ksort($headers); + return array_keys($headers); + } + return array(); + } + + private function isDefaultSignedHeader($low) + { + if (strncmp($low, "x-oss-", 6) == 0 || + $low === "content-type" || + $low === "content-md5") { + return true; + } + return false; + } + + private function calcStringToSign($datetime, $scope, $canonicalRequest) + { + /* + StringToSign + "OSS4-HMAC-SHA256" + "\n" + + TimeStamp + "\n" + + Scope + "\n" + + Hex(SHA256Hash(Canonical Request)) + */ + $hashedRequest = hash('sha256', $canonicalRequest); + return "OSS4-HMAC-SHA256" . "\n" . $datetime . "\n" . $scope . "\n" . $hashedRequest; + } + + private function calcCanonicalRequest($method, $resourcePath, array $query, array $headers, array $additionalHeaders) + { + /* + Canonical Request + HTTP Verb + "\n" + + Canonical URI + "\n" + + Canonical Query String + "\n" + + Canonical Headers + "\n" + + Additional Headers + "\n" + + Hashed PayLoad + */ + + //Canonical Uri + $canonicalUri = str_replace(array('%2F'), array('/'), rawurlencode($resourcePath)); + //Canonical Query + $querySigned = array(); + foreach ($query as $key => $value) { + $querySigned[rawurlencode($key)] = rawurlencode($value); + } + ksort($querySigned); + $sortedQueryList = array(); + foreach ($querySigned as $key => $value) { + if (strlen($value) > 0) { + $sortedQueryList[] = $key . '=' . $value; + } else { + $sortedQueryList[] = $key; + } + } + $canonicalQuery = implode('&', $sortedQueryList); + //Canonical Headers + $headersSigned = array(); + foreach ($headers as $key => $value) { + $lowk = strtolower($key); + if (SignerV4::isDefaultSignedHeader($lowk) || + in_array($lowk, $additionalHeaders)) { + $headersSigned[$lowk] = trim($value); + } + } + ksort($headersSigned); + $canonicalizedHeaders = ''; + foreach ($headersSigned as $key => $value) { + $canonicalizedHeaders .= $key . ':' . $value . "\n"; + } + //Additional Headers + $canonicalAdditionalHeaders = implode(';', $additionalHeaders); + $hashPayload = "UNSIGNED-PAYLOAD"; + if (isset($headersSigned['x-oss-content-sha256'])) { + $hashPayload = $headersSigned['x-oss-content-sha256']; + } + + $stringToSign = $method . "\n" + . $canonicalUri . "\n" + . $canonicalQuery . "\n" + . $canonicalizedHeaders . "\n" + . $canonicalAdditionalHeaders . "\n" + . $hashPayload; + return $stringToSign; + } + + private function buildScope($date, $region, $product) + { + return $date . "/" . $region . "/" . $product . "/aliyun_v4_request"; + } + + private function calcSignature($secret, $date, $region, $product, $stringToSign) + { + $h1Key = hash_hmac("sha256", $date, "aliyun_v4" . $secret, true); + $h2Key = hash_hmac("sha256", $region, $h1Key, true); + $h3Key = hash_hmac("sha256", $product, $h2Key, true); + $h4Key = hash_hmac("sha256", "aliyun_v4_request", $h3Key, true); + return bin2hex(hash_hmac("sha256", $stringToSign, $h4Key, true)); + } +} diff --git a/application/admin/command/FcCategoryImages.php b/application/admin/command/FcCategoryImages.php new file mode 100644 index 0000000..377a622 --- /dev/null +++ b/application/admin/command/FcCategoryImages.php @@ -0,0 +1,205 @@ +setName('fc:category-images') + ->setDescription('批量入库分类 AI 配图(本地→OSS→附件表→分类表)'); + } + + protected function execute(Input $input, Output $output) + { + $downloadDir = ROOT_PATH . 'tmp_img' . DS . 'downloaded'; + if (!is_dir($downloadDir)) { + $output->error("找不到图片目录: $downloadDir"); + return 1; + } + + // 1. 初始化 OSS(手动注册 addons/alioss OSS 命名空间,console 不会触发 Addon::appInit) + Loader::addNamespace('OSS', ROOT_PATH . 'addons' . DS . 'alioss' . DS . 'library' . DS . 'OSS' . DS); + $aliossConfig = $this->getAliossConfig(); + if (!$aliossConfig) { + $output->error("alioss 插件未配置"); + return 1; + } + $oss = new OssClient([ + 'accessKeyId' => $aliossConfig['accessKeyId'], + 'endpoint' => $aliossConfig['endpoint'], + 'bucket' => $aliossConfig['bucket'], + 'region' => str_replace('-internal', '', substr(explode('.', $aliossConfig['endpoint'])[0], 4)), + 'provider' => new StaticCredentialsProvider($aliossConfig['accessKeyId'], $aliossConfig['accessKeySecret']), + 'signatureVersion' => OssClient::OSS_SIGNATURE_VERSION_V4, + ]); + $output->writeln("==> OSS 已初始化: bucket={$aliossConfig['bucket']}"); + + // 2. 建立分类 id → 数据库记录映射 + $categories = Db::name('fc_category') + ->where('enabled', 1) + ->column('id,pid,name,kind,image', 'id'); + $output->writeln("==> 分类表加载: " . count($categories) . " 条"); + + // 3. 扫描下载目录 + $files = glob($downloadDir . DS . '*.jpg'); + $output->writeln("==> 本地图片: " . count($files) . " 张"); + + $success = 0; $skip = 0; $fail = 0; + $today = date('Ymd'); + $uploadDir = '/uploads/' . $today . '/'; + $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir); + if (!is_dir($destDir)) { @mkdir($destDir, 0755, true); } + + foreach ($files as $localFile) { + $basename = basename($localFile); + $id = (int)pathinfo($basename, PATHINFO_FILENAME); + if (!$id) { continue; } + + if (!isset($categories[$id])) { + $output->writeln("SKIP id=$id 分类不存在"); + $skip++; continue; + } + + $cat = $categories[$id]; + try { + // 3a. 每次循环清空变量,防止上轮残留 + unset($md5, $saveName, $ossKey, $urlPath, $destFile); + $md5 = md5_file($localFile); + if (!$md5) { throw new \Exception("无法计算 md5: $localFile"); } + $suffix = 'jpg'; + $saveName = $md5 . '.' . $suffix; + $ossKey = ltrim($uploadDir . $saveName, '/'); + $urlPath = '/' . $ossKey; + $destFile = $destDir . DS . $saveName; + + // 3b. 用 copy + unlink(避免 move_uploaded_file 对非 HTTP 临时文件无效) + @copy($localFile, $destFile); + if (!file_exists($destFile)) { throw new \Exception("copy 到 uploads 失败: $destFile"); } + @unlink($localFile); + + // 3c. 图片信息 + $imgInfo = @getimagesize($destFile); + $filesize = filesize($destFile); + $width = $imgInfo ? (int)($imgInfo[0] ?? 0) : 0; + $height = $imgInfo ? (int)($imgInfo[1] ?? 0) : 0; + $sha1 = sha1_file($destFile); + $mimetype = 'image/jpeg'; + $now = time(); + + // 3d. 先推 OSS(用临时本地文件) + $oss->uploadFile($aliossConfig['bucket'], $ossKey, $destFile); + + // 3e. 写 attachment(storage=alioss,与 index::upload 的 serverbackup=0 模式一致) + $attachment = Attachment::create([ + 'admin_id' => 1, + 'user_id' => 0, + 'filename' => mb_substr($cat['name'] . '_分类图', 0, 100), + 'category' => '', + 'filesize' => $filesize, + 'imagewidth' => $width, + 'imageheight' => $height, + 'imagetype' => $suffix, + 'imageframes' => 0, + 'mimetype' => $mimetype, + 'url' => $urlPath, + 'uploadtime' => $now, + 'storage' => 'alioss', + 'sha1' => $sha1, + ], true); + + // 3f. 更新 fc_category + Db::name('fc_category') + ->where('id', $id) + ->update([ + 'image' => $urlPath, + 'icon_key' => '', + 'updatetime' => $now, + ]); + + // 3g. serverbackup=0 → 删除本地临时文件(OSS 已是权威) + @unlink($destFile); + + $success++; + if ($success % 50 === 0) { + $output->writeln(" ... 进度 $success 最后: {$cat['name']} #$id"); + } + } catch (\Exception $e) { + $fail++; + $output->writeln("FAIL id=$id name={$cat['name']} err=" . $e->getMessage()); + @unlink($localFile); + @unlink($destFile); + } + } + + $output->writeln("==> 完成: success=$success skip=$skip fail=$fail total=" . count($files)); + + // 4. 验证 attachment 记录数 + $attachmentCount = Db::name('attachment') + ->where('storage', 'alioss') + ->where('url', 'like', $uploadDir . '%') + ->count(); + $output->writeln("==> 校验: 今日 alioss attachment 记录 = $attachmentCount"); + + return 0; + } + + /** 获取 alioss 插件配置 */ + protected function getAliossConfig() + { + // 1. 尝试插件配置表(有的环境没有 fa_addon,避免崩溃) + try { + if (Db::query("SHOW TABLES LIKE 'fa_addon'")) { + $conf = Db::name('addon')->where('name', 'alioss')->find(); + if ($conf && !empty($conf['config'])) { + $arr = json_decode($conf['config'], true); + if (is_array($arr) && isset($arr['accessKeyId'])) { + return $arr; + } + } + } + } catch (\Exception $e) { /* ignore */ } + + // 2. 回退到插件默认 config.php + $ini = ROOT_PATH . 'addons' . DS . 'alioss' . DS . 'config.php'; + if (file_exists($ini)) { + $default = include ROOT_PATH . 'addons' . DS . 'alioss' . DS . 'config.php'; + $flat = []; + foreach ($default as $item) { + if (isset($item['name']) && isset($item['value'])) { + $flat[$item['name']] = $item['value']; + } + } + return $flat; + } + return null; + } +} diff --git a/application/admin/command/FcMenu.php b/application/admin/command/FcMenu.php index b99b5ca..3fa26e0 100644 --- a/application/admin/command/FcMenu.php +++ b/application/admin/command/FcMenu.php @@ -78,14 +78,16 @@ class FcMenu extends Command 'auth/adminlog' => ['fc/auth', '操作日志', 'fa fa-list-alt', 80], // 系统设置 'general/config' => ['fc/system', '系统配置', 'fa fa-cog', 99], - 'dashboard' => ['fc/system', '平台概况', 'fa fa-dashboard', 95], + 'fc/setting' => ['fc/system', '小程序设置', 'fa fa-wechat', 97], + 'fc/area' => ['fc/system', '服务区域', 'fa fa-map-marker', 95], + 'dashboard' => ['fc/system', '平台概况', 'fa fa-dashboard', 90], 'general/attachment' => ['fc/system', '附件管理', 'fa fa-file-image-o', 80], 'general/profile' => ['fc/system', '个人资料', 'fa fa-user', 70], 'addon' => ['fc/system', '插件管理', 'fa fa-rocket', 60], ]; - /** 已并入对应主菜单或默认全国无需手动配置、不再单独显示的历史菜单 */ - const RETIRED = ['fc/setting', 'fc/memberbenefit', 'fc/area']; + /** 已并入对应主菜单或已下线不再单独显示的历史菜单 */ + const RETIRED = ['fc/memberbenefit']; /** 已彻底废弃的菜单(控制器不存在),重建时直接从数据库删除 */ const REMOVED = ['fc/board']; @@ -105,6 +107,7 @@ class FcMenu extends Command 'fc/coupon/edit' => ['fc/coupon', '编辑'], 'fc/coupon/del' => ['fc/coupon', '删除'], 'fc/coupon/multi' => ['fc/coupon', '批量更新'], + 'fc/area/import' => ['fc/area', '恢复全国默认'], ]; /** 需要整体下线的 FastAdmin 内置菜单(公众号模块 / 框架会员模块) */ diff --git a/application/admin/controller/fc/Area.php b/application/admin/controller/fc/Area.php index 89fb35e..0627953 100644 --- a/application/admin/controller/fc/Area.php +++ b/application/admin/controller/fc/Area.php @@ -43,6 +43,11 @@ class Area extends Backend return parent::add(); } + public function afterAdd($row) + { + \app\common\library\NationalArea::invalidate(); + } + /** * 编辑:保存前校验 * @param string $ids @@ -56,6 +61,54 @@ class Area extends Backend return parent::edit($ids); } + public function afterEdit($row) + { + \app\common\library\NationalArea::invalidate(); + } + + public function afterDel($ids) + { + \app\common\library\NationalArea::invalidate(); + } + + public function afterMulti($params) + { + \app\common\library\NationalArea::invalidate(); + } + + /** + * 省份下拉选项(不重复、enabled=1 的省份列表) + * GET ajax → ['北京市', '天津市', '贵州省', ...] + */ + public function provinces() + { + $rows = Db::name('fc_area') + ->where('enabled', 1) + ->group('province') + ->order('province asc') + ->column('province'); + $this->success('', null, $rows ?: []); + } + + /** + * 恢复全国默认(导入覆盖层) + * 操作:清空 fa_fc_area 覆盖层,从 national_areas.json 导入全国 3600 个区县,全部 enabled=1。 + * POST ajax = 确认按钮触发。 + */ + public function import() + { + if ($this->request->isPost()) { + $this->checkToken(); + try { + $count = \app\common\library\NationalArea::importFromJson(); + $this->success("已恢复全国默认,导入 {$count} 条区域记录"); + } catch (\Throwable $e) { + $this->error('恢复失败:' . $e->getMessage()); + } + } + return $this->view->fetch(); + } + /** * 省 / 市 / 区县已添加记录,供表单级联下拉合并全国行政区划及已添加状态标记使用 */ diff --git a/application/admin/controller/fc/Category.php b/application/admin/controller/fc/Category.php index 25fa0fa..98b1fbb 100644 --- a/application/admin/controller/fc/Category.php +++ b/application/admin/controller/fc/Category.php @@ -82,6 +82,16 @@ class Category extends Backend if (empty($r['image']) && !empty($r['icon_key'])) { $r['image'] = $this->resolveImageFromKey($r['icon_key']); } + // 确保图片路径与域名完整性: + // 本地静态资源 (/static/...) 保持本地绝对路径;附件系统 (/uploads/...) 走 OSS CDN 域名并挂 160px 缩略 + $rawImg = isset($r['image']) ? (string)$r['image'] : ''; + if ($rawImg !== '' && preg_match('/^\/uploads\//i', $rawImg)) { + $r['image'] = cdnurl($rawImg, true); + if ((strpos($r['image'], 'aliyuncs.com') !== false || strpos($r['image'], 'oss-') !== false) && strpos($r['image'], 'x-oss-process') === false) { + $sep = strpos($r['image'], '?') !== false ? '&' : '?'; + $r['image'] .= $sep . 'x-oss-process=image/resize,m_fill,w_160,h_160/quality,q_85'; + } + } if ($pid === 0) { $tops[] = $r; } else { @@ -218,6 +228,19 @@ class Category extends Backend if (empty($row['image']) && !empty($row['icon_key'])) { $row['image'] = $this->resolveImageFromKey($row['icon_key']); } + $rawImage = isset($row['image']) ? (string)$row['image'] : ''; + $iconKey = isset($row['icon_key']) ? (string)$row['icon_key'] : ''; + $displayImage = $rawImage; + if (preg_match('/^\/uploads\//i', $rawImage)) { + $displayImage = cdnurl($rawImage, true); + if ((strpos($displayImage, 'aliyuncs.com') !== false || strpos($displayImage, 'oss-') !== false) && strpos($displayImage, 'x-oss-process') === false) { + $sep = strpos($displayImage, '?') !== false ? '&' : '?'; + $displayImage .= $sep . 'x-oss-process=image/resize,m_fill,w_160,h_160/quality,q_85'; + } + } elseif ($rawImage === '' && $iconKey === '') { + $displayImage = '/static/categories/cat-job.svg'; + } + $row['display_image'] = $displayImage; $this->view->assign("row", $row); return $this->view->fetch(); } @@ -278,16 +301,23 @@ class Category extends Backend { $iconKey = trim((string)$iconKey); if ($iconKey === '') { - return '/static/icons/cat-service.png'; + return '/static/categories/cat-job.svg'; } if (preg_match('/^(\/uploads\/|\/static\/|https?:\/\/)/i', $iconKey)) { return $iconKey; } + // 优先匹配高质感矢量 SVG 图标 + if (is_file(ROOT_PATH . 'public/static/categories/' . $iconKey . '.svg')) { + return '/static/categories/' . $iconKey . '.svg'; + } $file = strpos($iconKey, '.') !== false ? $iconKey : ($iconKey . '.png'); if (is_file(ROOT_PATH . 'public/static/categories/' . $file)) { return '/static/categories/' . $file; } - return '/static/icons/' . $file; + if (is_file(ROOT_PATH . 'public/static/icons/' . $file)) { + return '/static/icons/' . $file; + } + return '/static/categories/cat-job.svg'; } /** diff --git a/application/admin/view/fc/area/index.html b/application/admin/view/fc/area/index.html index 55e7d6e..1f87aef 100644 --- a/application/admin/view/fc/area/index.html +++ b/application/admin/view/fc/area/index.html @@ -10,6 +10,7 @@ 添加 {:__('Edit')} {:__('Delete')} + 恢复全国默认 diff --git a/application/admin/view/fc/category/add.html b/application/admin/view/fc/category/add.html index 3688201..72e68b1 100644 --- a/application/admin/view/fc/category/add.html +++ b/application/admin/view/fc/category/add.html @@ -1,14 +1,28 @@
+ +
+
+ 分类图标 +
+
+
未命名分类
+ 通用便民类目 +
+
修改名称 / 图标 / 主题色时
此预览实时同步更新
+
+
-
+
归属与类型 决定前台分类层级与发布表单
-
- -
+
+ +
{:build_select('row[pid]', $parentList, 0, ['class'=>'form-control selectpicker', 'id'=>'c-pid', 'data-rule'=>'required'])} 选「顶级分类」创建一级大类频道;选指定分类(如「招聘专区」「肉蛋家禽」)则创建下属二级品类。
-
- -
+
+ +