diff --git a/AliOssSdk/alioss.class.php b/AliOssSdk/alioss.class.php deleted file mode 100644 index 9428f14..0000000 --- a/AliOssSdk/alioss.class.php +++ /dev/null @@ -1,3 +0,0 @@ -set_enable_domain_style(true); - - ` - -* 使用sts方式初始化ALIOSS - * 如果是移动端的开发者,需要使用sts服务,只需要在初始化的时候调用sts的api生成临时的accessId,accessKey,以及securityToken即可。 - - ` - $access_id = "调用sts接口得到的临时access_id"; - $access_key = "调用sts接口得到的临时access_key"; - $end_point = "操作集群的endpoint"; - $security_token = "调用sts接口得到的临时security_token"; - $client = ALIOSS($access_id,$access_key,$end_point,$security_token); - - ` - -## Bucket相关操作 -* 获取bucket列表 - * 示例代码 - - ` - $options = null; - $response = $client->list_bucket($options); - - ` - * 参数说明 - - ` - $options 可选参数,无需设置 - - ` - * 响应结果 - 、 - 将结果Response转换成array得到,下同 - Array( - [status] => 200 - [header] => Array( - [date] => Wed, 01 Jul 2015 09:21:15 GMT - [content-type] => application/xml - [content-length] => 6266 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5593B10B58DB3AB752154A62 - ) - [body] => Array( - [ListAllMyBucketsResult] => Array( - [Owner] => Array ( - [ID] => 128257 - [DisplayName] => 128257 - ) - [Buckets] => Array( - [Bucket] => Array( - [0] => Array( - [Location] => oss-cn-hangzhou - [Name] => 33331111 - [CreationDate] => 2014-08-27T03:04:20.000Z - ) - [1] => Array ( - [Location] => oss-cn-qingdao - [Name] => a-00000000000000000001 - [CreationDate] => 2015-05-22T05:30:40.000Z - ) - - ) - - ) - - ) - - ) - - ) - 、 -* 创建bucket - * 示例代码 - - ` - $bucket_name = "bucket name"; - $acl = ALIOSS::OSS_ACL_TYPE_PRIVATE; - $options = null; - $response = $client->create_bucket($bucket_name,$acl,$options); - - ` - * 参数说明 - - ` - - $bucket_name 必选参数,需要符合bucket命名规范 - $acl 必选参数,只能从private,public-read,public-read-write中任选一个,分别和以下常量映射 - ALIOSS::OSS_ACL_TYPE_PRIVATE, - ALIOSS::OSS_ACL_TYPE_PUBLIC_READ, - ALIOSS::OSS_ACL_TYPE_PUBLIC_READ_WRITE - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - Array( - [status] => 200 - [header] => Array( - [date] => Wed, 01 Jul 2015 09:55:18 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5593B906031C87E546154CC1 - ) - - [body] => - ) - - ` - -* 删除bucket - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->delete_bucket($bucket_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,需要符合bucket命名规范 - $options 可选参数,无需设置 - - ` - * 响应结果 - - ` - - 将结果Response转换成array得到,下同 - Array( - [status] => 204 - [header] => Array( - [date] => Wed, 01 Jul 2015 10:08:45 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5593BC2D58DB3AB752155156 - ) - - [body] => - ) - - ` -* 获取bucket Acl - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->get_bucket_acl($bucket_name,$options); - - - ` - * 参数说明 - - ` - $bucket_name 必选参数,需要符合bucket命名规范 - $options 可选参数,无需设置 - - ` - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Wed, 01 Jul 2015 10:17:41 GMT - [content-type] => application/xml - [content-length] => 239 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5593BE45031C87E54615500F - ) - - [body] => Array( - [AccessControlPolicy] => Array( - [Owner] => Array( - [ID] => 128257 - [DisplayName] => 128257 - ) - - [AccessControlList] => Array( - [Grant] => public-read - ) - ) - ) - ) - - ` - -* 设置bucket Acl - * 示例代码 - - ` - $bucket_name = "bucket name"; - $options = null; - $response = $client->set_bucket_acl($bucket_name,$options); - ` - - * 参数说明 - - ` - $bucket_name 必选参数,需要符合bucket命名规范 - $options 可选参数,无需设置 - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - Array( - [status] => 200 - [header] => Array( - [date] => Wed, 01 Jul 2015 11:08:31 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5593CA2F031C87E5461557B5 - ) - - [body] => - ) - ` - -## Object相关操作 -* 获取Object列表 - * 示例代码 - - ` - $bucket_name = 'bucket name'; - $options = array( - 'delimiter' => '/', - 'prefix' => '', - 'max-keys' => 5, - 'marker' => '', - ); - - $response = $client->list_object($$bucket_name,$options); - - ` - - - * 参数说明 - - - ` - - $bucket_name 必选参数,需要符合bucket命名规范 - $options 可选参数,其中的参数说明如下 - delimiter 是一个用于对Object名字进行分组的字符。所有名字包含指定的前缀且第一次出现delimiter - 字符之间的object作为一组元素——CommonPrefixes。 - prefix 限定返回的object key必须以prefix作为前缀。注意使用prefix查询时,返回的key中 - 仍会包含prefix - max-keys 限定此次返回object的最大数,如果不设定,默认为100,max-keys取值不能大于1000 - marker 设定结果从marker之后按字母排序的第一个开始返回 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 07:59:32 GMT - [content-type] => application/xml - [content-length] => 1466 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594EF64031C87E546160F24 - ) - - [body] => Array( - [ListBucketResult] => Array( - [Name] => common-bucket - [Prefix] => - [Marker] => - [MaxKeys] => 5 - [Delimiter] => / - [IsTruncated] => true - [NextMarker] => metro_driver.dll - [Contents] => Array( - [0] => Array( - [Key] => chrome_elf.dll - [LastModified] => 2015-07-01T03:44:58.000Z - [ETag] => "78CE940FD1CCDF6F743EE1A9AED8AAD8" - [Type] => Normal - [Size] => 133960 - [StorageClass] => Standard - [Owner] => Array( - [ID] => 128257 - [DisplayName] => 128257 - ) - ) - - [1] => Array( - [Key] => delegate_execute.exe - [LastModified] => 2015-06-29T09:18:41.000Z - [ETag] => "37C49C4E0EC4E0D96B6EBBA2190E8824" - [Type] => Normal - [Size] => 692040 - [StorageClass] => Standard - [Owner] => Array( - [ID] => 128257 - [DisplayName] => 128257 - ) - ) - } - - [CommonPrefixes] => Array( - [0] => Array( - [Prefix] => common-folder/ - ) - - [1] => Array( - [Prefix] => common-folder2/ - ) - ) - ) - ) - ) - - ` - - -* 创建虚拟文件夹 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $dir_name = 'directory name'; - $options = null; - $response = $client->create_object_dir($bucket_name,$dir_name,$options); - - ` - - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $dir_name 必选参数,必须符合object命名规范 - $options 可选参数,对于虚拟文件夹而言,无需设置一些header头 - - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 08:10:16 GMT - [content-length] => 0 - [connection] => close - [etag] => "D41D8CD98F00B204E9800998ECF8427E" - [server] => AliyunOSS - [x-oss-request-id] => 5594F1E8031C87E5461610B9 - ) - - [body] => - ) - - ` - - -* 上传文件(直接指定内容) - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $content = 'object content'; - $options = array( - 'content' => $content, - 'length' => strlen($content), - ALIOSS::OSS_HEADERS => array( - 'Expires' => 'Fri, 28 Feb 2012 05:38:42 GMT', - 'Cache-Control' => 'no-cache', - 'Content-Disposition' => 'attachment;filename=oss_download.log', - 'Content-Encoding' => 'utf-8', - 'Content-Language' => 'zh-CN', - 'x-oss-server-side-encryption' => 'AES256', - ), - ); - $response = $obj->upload_file_by_content($bucket_name,$object_name,$options); - - ` - - * 参数说明 - - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $options 必选参数,该参内指定上传所需要的各种信息,具体各参数说明如下 - content 上传object的内容 - length 上传object的大小 - ALIOSS::OSS_HEADERS 该参数可选,如果指定,则可以设置该object的一些meta信息,可以设置的头信息如下: - Expires 过期时间(milliseconds) - Cache-Control 指定该Object被下载时的网页的缓存行为 - Content-Disposition 指定该Object被下载时的名称 - Content-Encoding 指定该Object被下载时的内容编码格式 - Content-Language 指定object被下载时候的语言 - x-oss-server-side-encryption 指定oss创建object时的服务器端加密编码算法 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 08:24:11 GMT - [content-length] => 0 - [connection] => close - [etag] => "9BA9EF6DDFBE14916FA2D3337B427774" - [server] => AliyunOSS - [x-oss-request-id] => 5594F52B031C87E5461612D1 - ) - - [body] => - ) - - ` - -* 上传文件(指定上传路径) - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $file_path = "upload file path"; - $options = array( - ALIOSS::OSS_HEADERS => array( - 'Expires' => 'Fri, 28 Feb 2012 05:38:42 GMT', - 'Cache-Control' => 'no-cache', - 'Content-Disposition' => 'attachment;filename=oss_download.gz', - 'Content-Encoding' => 'utf-8', - 'Content-Language' => 'zh-CN', - 'x-oss-server-side-encryption' => 'AES256', - - ), - ); - $response = $obj->upload_file_by_file($bucket,$object,$file_path,$upload_file_options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $file_path 必选参数,文件所在的路径 - $options 必选参数,该参内指定上传所需要的各种信息,具体各参数说明如下 - content 上传object的内容 - length 上传object的大小 - ALIOSS::OSS_HEADERS 该参数可选,如果指定,则可以设置该object的一些meta信息,可以设置的头信息如下: - Expires 过期时间(milliseconds) - Cache-Control 指定该Object被下载时的网页的缓存行为 - Content-Disposition 指定该Object被下载时的名称 - Content-Encoding 指定该Object被下载时的内容编码格式 - Content-Language 指定object被下载时候的语言 - x-oss-server-side-encryption 指定oss创建object时的服务器端加密编码算法 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 08:41:10 GMT - [content-length] => 0 - [connection] => close - [etag] => "4B12FF064A3BBFE0AE5A1314E77FF0DF" - [server] => AliyunOSS - [x-oss-request-id] => 5594F91358DB3AB7521617CA - ) - - [body] => - ) - - ` - - -* 拷贝Object - * 示例代码 - - ` - - $from_bucket = 'copy from bucket'; - $from_object = 'copy from object'; - $to_bucket = 'copy to bucket'; - $to_object = 'copy to object'; - $options = array( - ALIOSS::OSS_HEADERS => array( - 'x-oss-copy-source-if-match' => 'E024E425254F1EEDB237F69F854CE883', - 'x-oss-copy-source-if-none-match' => 'Thu, 18 Jun 2015 08:50:31 GMT', - 'x-oss-copy-source-if-unmodified-since' => 'Thu, 18 Jun 2015 08:50:31 GMT', - 'x-oss-copy-source-if-modified-since' => 'Thu, 18 Jun 2015 09:50:31 GMT', - 'x-oss-metadata-directive' => 'COPY', - 'x-oss-server-side-encryption' => 'AES256' - ) - ); - - $response = $obj->copy_object($from_bucket,$from_object,$to_bucket,$to_object,$options); - - ` - - * 参数说明 - - ` - - $from_bucket 必选参数,源bucket,必须符合bucket命名规范 - $from_object 必选参数,源object,必须符合object命名规范 - $to_bucket 必选参数,目标bucket,必须符合bucket命名规范 - $to_object 必选参数,目标object,必须符合object命名规范 - $options 可选参数,如果需要设置,可以设置 ALIOSS::OSS_HEADERS 头参数,参数有如下的几个选项 - x-oss-copy-source-if-match 如果源Object的ETAG值和用户提供的ETAG相等,则执行拷贝操作; - 否则返回412 HTTP错误码(预处理失败) - x-oss-copy-source-if-none-match 如果源Object自从用户指定的时间以后就没有被修改过,则执行拷贝操作; - 否则返回412 HTTP错误码(预处理失败) - x-oss-copy-source-if-unmodified-since 如果传入参数中的时间等于或者晚于文件实际修改时间,则正常传输文件, - 并返回200 OK;否则返回412 precondition failed错误 - x-oss-copy-source-if-modified-since 如果源Object自从用户指定的时间以后被修改过,则执行拷贝操作; - 否则返回412 HTTP错误码(预处理失败) - x-oss-metadata-directive 有效值为COPY和REPLACE。如果该值设为COPY,则新的Object的meta都从源Object复制过来; - 如果设为REPLACE,则忽视所有源Object的meta值,而采用用户这次请求中指定的meta值;其他值则返回400 HTTP错误码。 - 注意该值为COPY时,源Object的x-oss-server-side-encryption的meta值不会进行拷贝;默认值为COPY - x-oss-server-side-encryption 指定oss创建目标object时的服务器端熵编码加密算法,目前仅支持AES256 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-type] => application/xml - [content-length] => 184 - [connection] => close - [date] => Thu, 02 Jul 2015 09:26:28 GMT - [etag] => "E024E425254F1EEDB237F69F854CE883" - [server] => AliyunOSS - [x-oss-request-id] => 559503C458DB3AB752161E83 - [x-oss-server-side-encryption] => AES256 - ) - - [body] => Array( - [CopyObjectResult] => Array( - [LastModified] => 2015-07-02T09:26:28.000Z - [ETag] => "E024E425254F1EEDB237F69F854CE883" - ) - ) - ) - - ` - - -* 获取Object MetaData - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $options = null; - $response = $client->get_object_meta($bucket_name,$object_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 09:03:40 GMT - [content-type] => plain/text - [content-length] => 10 - [connection] => close - [accept-ranges] => bytes - [cache-control] => no-cache - [content-disposition] => attachment;filename=oss_download.log - [content-encoding] => utf-8 - [content-language] => zh-CN - [etag] => "9BA9EF6DDFBE14916FA2D3337B427774" - [expires] => Fri, 28 Feb 2012 05:38:42 GMT - [last-modified] => Thu, 02 Jul 2015 08:38:10 GMT - [server] => AliyunOSS - [x-oss-object-type] => Normal - [x-oss-request-id] => 5594FE6C031C87E5461618B6 - [x-oss-server-side-encryption] => AES256 - ) - - [body] => - ) - - ` - -* 删除单个Object - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $options = null; - $response = $client->delete_object($bucket_name,$object_name,$options); - - ` - - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $options 可选参数,无需设置 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 204 - [header] => Array( - [content-length] => 0 - [connection] => close - [date] => Thu, 02 Jul 2015 10:01:00 GMT - [server] => AliyunOSS - [x-oss-request-id] => 55950BDC58DB3AB75216239D - ) - - [body] => - ) - - - ` - - -* 删除多个Object - * 示例代码 - - - ` - - $bucket_name = 'bucket name'; - $objects = array( - 'delete object 1', - 'delete object 2', - ... - ); - - $options = array( - 'quiet' => false, - ); - - $response = $client->delete_objects($bucket_name,$objects,$options); - - ` - - - * 参数说明 - - ` - $bucket_name 必选参数,必须符合bucket命名规范 - $objects 必选参数,其中的object必须符合object命名规范 - $options 可选参数,此处可以根据实际情况选择删除的两种模式,quite 参数可有true|false两种选择, - true OSS返回的消息体中只包含删除过程中出错的Object结果;如果所有删除都成功的话,则没有消息体。 - false OSS返回的消息体中会包含每一个删除Object的结果 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-type] => application/xml - [content-length] => 188 - [connection] => close - [date] => Thu, 02 Jul 2015 10:06:00 GMT - [server] => AliyunOSS - [x-oss-request-id] => 55950D0858DB3AB752162459 - ) - - [body] => Array( - [DeleteResult] => Array( - [Deleted] => Array( - [0] => Array( - [Key] => delegate_execute.exe - ) - - [1] => Array( - [Key] => metro_driver.dll - ) - ) - ) - ) - - - ` - - -* 下载Object - * 示例代码 - - ` - - $bucket_name = 'download bucket'; - $object_name = 'download object'; - - $options = array( - ALIOSS::OSS_FILE_DOWNLOAD => "download path", - ALIOSS::OSS_RANGE => '0-1', - ); - - $response = $client>get_object($bucket_name,$object_name,$options); - - ` - - * 参数说明 - - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $options 必选参数,该参数中必须设置ALIOSS::OSS_FILE_DOWNLOAD,ALIOSS::OSS_RANGE可选,可以根据实际情况设置; - 如果不设置,默认会下载全部内容 - - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 206 - [header] => Array( - ) - - [body] => - ) - - ` - - -## MultipartUpload相关操作 -* 初始化 multipartUpload - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $options = array( - ALIOSS::OSS_HEADERS => array( - 'Expires' => 'Fri, 28 Feb 2012 05:38:42 GMT', - 'Cache-Control' => 'no-cache', - 'Content-Disposition' => 'attachment;filename=oss_download.log', - 'Content-Encoding' => 'utf-8', - 'Content-Type' => 'plain/text', - 'Content-Language' => 'zh-CN', - 'x-oss-server-side-encryption' => 'AES256', - ), - ); - $response = $client->initiate_multipart_upload($bucket_name,$object_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $options 必选参数,该参内指定上传所需要的各种信息,具体各参数说明如下 - ALIOSS::OSS_HEADERS 该参数可选,如果指定,则可以设置该object的一些meta信息,可以设置的头信息如下: - Expires 过期时间(milliseconds) - Cache-Control 指定该Object被下载时的网页的缓存行为 - Content-Disposition 指定该Object被下载时的名称 - Content-Encoding 指定该Object被下载时的内容编码格式 - 'Content-Type' => 'plain/text'指定Object响应时的MIME类型 - Content-Language 指定object被下载时候的语言 - x-oss-server-side-encryption 指定oss创建object时的服务器端加密编码算法 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-type] => application/xml - [content-length] => 234 - [connection] => close - [date] => Thu, 02 Jul 2015 11:35:36 GMT - [server] => AliyunOSS - [x-oss-request-id] => 5595220858DB3AB7521631B1 - [x-oss-server-side-encryption] => AES256 - ) - - [body] => Array( - [InitiateMultipartUploadResult] => Array( - [Bucket] => common-bucket - [Key] => multipart-upload-1435836936 - [UploadId] => 154A34BD1FE24A90A025EB800AA392CC - ) - ) - ) - - ` - - -* 上传Part - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $upload_id = 'upload id'; - $options = array( - 'fileUpload' => 'upload path', - 'partNumber' => 1, - 'seekTo' => 1, - 'length' => 5242880, - ); - - $response = $client->upload_part($bucket_name,$object_name, $upload_id, $options); - - ` - - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $upload_id 必选参数,上传part对应的multipart uploads Id - $options 必选参数,该参内指定上传所需要的各种信息,具体各参数说明如下 - fileUpload 上传文件的路径 - partNumber 上传part的序号 - seekTo 读取上传文件的起始字节 - length 切片大小 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-length] => 0 - [connection] => close - [date] => Thu, 02 Jul 2015 11:35:36 GMT - [etag] => "3AE3AD480200A26738F10CBF2FFBE8B6" - [server] => AliyunOSS - [x-oss-request-id] => 5595220858DB3AB7521631B3 - [x-oss-server-side-encryption] => AES256 - ) - - [body] => - ) - - ` - - -* 拷贝Upload Part - * 示例代码 - - ` - - $from_bucket = 'copy from bucket'; - $from_object = 'copy from object'; - $to_bucket = 'copy to bucket'; - $to_object = 'copy to object'; - $part_number = 1; - $upload_id = 'copy to upload id'; - $options = array( - 'start' => 0, - 'end' => 25000032, - ); - - $response = $client->copy_upload_part($from_bucket,$from_object,$to_bucket,$to_object,$part_number,$upload_id,$options); - - - ` - - * 参数说明 - - ` - - $from_bucket 必选参数,源bucket,必须符合bucket命名规范 - $from_object 必选参数,源object,必须符合object命名规范 - $to_bucket 必选参数,目标bucket,必须符合bucket命名规范 - $to_object 必选参数,目标object,必须符合object命名规范 - $part_number 必选参数,范围是1~10,000 - $upload_id 必选参数,初始化multipartupload返回的uploadid - $options 可选参数,如果需要设置,可以设置isFullCopy,startRange,endRange和 - ALIOSS::OSS_HEADERS 等参数,其中ALIOSS::OSS_HEADERS中可以设置的参数如下: - x-oss-copy-source-if-match 如果源Object的ETAG值和用户提供的ETAG相等,则执行拷贝操作; - 否则返回412 HTTP错误码(预处理失败) - x-oss-copy-source-if-none-match 如果源Object自从用户指定的时间以后就没有被修改过,则执行拷贝操作; - 否则返回412 HTTP错误码(预处理失败) - x-oss-copy-source-if-unmodified-since 如果传入参数中的时间等于或者晚于文件实际修改时间,则正常传输文件, - 并返回200 OK;否则返回412 precondition failed错误 - x-oss-copy-source-if-modified-since 如果源Object自从用户指定的时间以后被修改过,则执行拷贝操作; - 否则返回412 HTTP错误码(预处理失败) - isFullCopy 是否启用全部拷贝,如果设置为true,则无需设置startRange和endRange - startRange 如果isFullCopy为false,该参数有效,指的是拷贝来源object的起始位置 - endRange 如果isFullCopy为false,该参数有效,指的是拷贝开源object的终止位置 - - ` - - * 响应结果 - ` - 将结果Response转换成array得到,下同 - - Array - ( - [success] => 1 - [status] => 200 - [header] => Array - ( - [date] => Thu, 06 Aug 2015 18:13:59 GMT - [content-type] => application/xml - [content-length] => 180 - [connection] => keep-alive - [content-range] => bytes 11304368-11534335/11534336 - [etag] => "E95C28888F15B92B9C49C9ECEC53C958" - [server] => AliyunOSS - [x-oss-bucket-version] => 1438864637 - [x-oss-request-id] => 55C3A3E79646C3C03F40EA5E - ) - - [body] => Array - ( - [CopyPartResult] => Array - ( - [LastModified] => 2015-08-06T18:13:59.000Z - [ETag] => "E95C28888F15B92B9C49C9ECEC53C958" - ) - - ) - - ) - ` -* 获取Part列表 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $upload_id = 'upload id'; - $options = null; - $response = $client->list_parts($bucket_name,$object_name, $upload_id,$options); - - ` - - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $upload_id 必选参数,上传part对应的multipart uploads Id - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-type] => application/xml - [content-length] => 584 - [connection] => close - [date] => Thu, 02 Jul 2015 11:35:40 GMT - [server] => AliyunOSS - [x-oss-request-id] => 5595220C031C87E546162F44 - ) - - [body] => Array( - [ListPartsResult] => Array( - [Bucket] => common-bucket - [Key] => multipart-upload-1435836813 - [UploadId] => B4D4B89F8B064A3D835D83D7805B49F3 - [StorageClass] => Standard - [PartNumberMarker] => 0 - [NextPartNumberMarker] => 1 - [MaxParts] => 1000 - [IsTruncated] => false - [Part] => Array( - [PartNumber] => 1 - [LastModified] => 2015-07-02T11:35:40.000Z - [ETag] => "3AE3AD480200A26738F10CBF2FFBE8B6" - [Size] => 5242880 - ) - ) - ) - ) - - ` - - -* 获取mulipartUpload列表 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $options = array( - 'delimiter' => '/', - 'max-uploads' => 2, - 'key-marker' => '', - 'prefix' => '', - 'upload-id-marker' => '' - ); - $response = $client->list_multipart_uploads($bucket_name,$options); - - - ` - - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $options 可选参数,如果需要设置,可以设置如下参数 - delimiter 是一个用于对Object名字进行分组的字符。所有名字包含指定的前缀且第一次出现delimiter字符之间的object作为一组元素—— - CommonPrefixes max-uploads 限定此次返回Multipart Uploads事件的最大数目,如果不设定,默认为1000,max-keys取值不能大于1000 - key-marker 与upload-id-marker参数一同使用来指定返回结果的起始位置。 l 如果upload-id-marker参数未设置,查询结果中包含: - 所有Object名字的字典序大于key-marker参数值的Multipart事件。 l 如果upload-id-marker参数被设置,查询结果中包含: - 所有Object名字的字典序大于key-marker参数值的Multipart事件和Object名字等于key-marker参数值,但是Upload ID比upload-id-marker - 参数值大的Multipart Uploads事件 - prefix 限定返回的object key必须以prefix作为前缀。注意使用prefix查询时,返回的key中仍会包含prefix - upload-id-marker 与key-marker参数一同使用来指定返回结果的起始位置。 l 如果key-marker参数未设置,则OSS忽略upload-id-marker参数。 - 如果key-marker参数被设置,查询结果中包含:所有Object名字的字典序大于key-marker参数值的Multipart事件和Object名字等于key-marker - 参数值,但是Upload ID比upload-id-marker参数值大的Multipart Uploads事件 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-type] => application/xml - [content-length] => 876 - [connection] => close - [date] => Thu, 02 Jul 2015 12:01:50 GMT - [server] => AliyunOSS - [x-oss-request-id] => 5595282E031C87E546163301 - ) - - [body] => Array( - [ListMultipartUploadsResult] => Array( - [Bucket] => common-bucket - [KeyMarker] => - [UploadIdMarker] => - [NextKeyMarker] => multipart-upload-1435835648 - [NextUploadIdMarker] => 5C79DDEC71DE478AA4AD9E9AA8BFE6DE - [Delimiter] => / - [Prefix] => - [MaxUploads] => 2 - [IsTruncated] => true - [Upload] => Array( - [0] => Array( - [Key] => multipart-upload-1435835395 - [UploadId] => 799C914C0EC3448BAC126849A1B1D6D0 - [StorageClass] => Standard - [Initiated] => 2015-07-02T11:09:55.000Z - ) - - [1] => Array( - [Key] => multipart-upload-1435835648 - [UploadId] => 5C79DDEC71DE478AA4AD9E9AA8BFE6DE - [StorageClass] => Standard - [Initiated] => 2015-07-02T11:14:08.000Z - ) - ) - ) - ) - ) - - ` - - -* 终止multipartUpload - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $upload_id = 'upload id'; - $options = null; - $response = $client->abort_multipart_upload($bucket_name,$object_name,$upload_id,$options); - - - ` - - - * 参数说明 - * - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $upload_id 必选参数,上传part对应的multipart uploads Id - $options 可选参数,无需设置 - - ` - - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 204 - [header] => Array( - [content-length] => 0 - [connection] => close - [date] => Thu, 02 Jul 2015 11:53:52 GMT - [server] => AliyunOSS - [x-oss-request-id] => 55952650031C87E5461631E7 - ) - - [body] => - ) - - ` - - -* 完成multipartUpload - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $upload_id = 'upload id'; - - $upload_parts = array(); - $upload_parts[] = array( - 'PartNumber' => 1, - 'ETag' => '3AE3AD480200A26738F10CBF2FFBE8B6' - ); - $options = null; - $response = $client->complete_multipart_upload($bucket_name,$object_name,$upload_id,$upload_parts,$options); - - ` - - * 参数说明 - - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $upload_id 必选参数,上传part对应的multipart uploads Id - $upload_parts 包含part的数组,其中必须包含PartNumber和Etag - $options 可选参数,无需设置 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [content-type] => application/xml - [content-length] => 331 - [connection] => close - [date] => Thu, 02 Jul 2015 11:35:40 GMT - [etag] => "003B6AEB546001A97D838E411025239A-1" - [server] => AliyunOSS - [x-oss-request-id] => 5595220C031C87E546162F45 - [x-oss-server-side-encryption] => AES256 - ) - - [body] => Array( - [CompleteMultipartUploadResult] => Array( - [Location] => http://common-bucket.oss-cn-shanghai.aliyuncs.com/multipart-upload-1435836813 - [Bucket] => common-bucket - [Key] => multipart-upload-1435836813 - [ETag] => "003B6AEB546001A97D838E411025239A-1" - ) - ) - ) - - ` -## 生命周期管理(LifeCycle) -* 创建Lifecycle规则 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $lifecycle = " - - - DaysRule - days/ - Enabled - - 1 - - - " ; - $options = null; - $response = $client->set_bucket_lifecycle($bucket_name,$lifecycle,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $lifecycle 必选参数,lifecycle规则,具体请xml元素说明请参阅oss api文档: - http://docs.aliyun.com/?spm=5176.383663.9.2.1hkILe#/pub/oss/api-reference/bucket&PutBucketLifecycle - $options 可选参数,无需设置 - - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 06:32:57 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594DB19031C87E5461601D1 - ) - - [body] => - ) - - ` - -* 获取lifeCycle规则 - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->get_bucket_lifecycle($bucket_name,$options); - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 06:32:57 GMT - [content-type] => application/xml - [content-length] => 243 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594DB1958DB3AB75216045C - ) - - [body] => Array( - [LifecycleConfiguration] => Array( - [Rule] => Array( - [ID] => DaysRule - [Prefix] => days/ - [Status] => Enabled - [Expiration] => Array( - [Days] => 1 - ) - ) - ) - ) - ) - - ` - -* 删除lifeCycle规则 - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->delete_bucket_lifecycle($bucket_name,$options); - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 204 - [header] => Array( - [date] => Thu, 02 Jul 2015 06:32:58 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594DB1A58DB3AB75216045D - ) - - [body] => - ) - - ` - -## 跨域资源管理(CORS) -* 创建CORS规则 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - - $cors_rule = array(); - - $cors_rule[ALIOSS::OSS_CORS_ALLOWED_HEADER]=array("x-oss-test"); - $cors_rule[ALIOSS::OSS_CORS_ALLOWED_METHOD]=array("GET"); - $cors_rule[ALIOSS::OSS_CORS_ALLOWED_ORIGIN]=array("http://www.b.com"); - $cors_rule[ALIOSS::OSS_CORS_EXPOSE_HEADER]=array("x-oss-test1"); - $cors_rule[ALIOSS::OSS_CORS_MAX_AGE_SECONDS] = 10; - - $cors_rules=array($cors_rule); - - $options = null; - $response = $obj->set_bucket_cors($bucket_name, $cors_rules,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $cors_rules 定义一个cors规则数组,每条规则中需要包含以下元素 - ALIOSS::OSS_CORS_ALLOWED_ORIGIN 必选,指定允许的跨域请求的来源,每条规则最多能有一个"*"符号 - ALIOSS::OSS_CORS_ALLOWED_METHOD 必选,指定允许的跨域请求方法,仅能从GET,PUT,POST,DELETE,HEAD中选择一个或多个 - ALIOSS::OSS_CORS_ALLOWED_HEADER 可选,控制在OPTIONS预取指令中Access-Control-Request-Headers头中指定的header是否允许。 - 在Access-Control-Request-Headers中指定的每个header都必须在AllowedHeader中有一条对应的项。允许使用最多一个“*”通配符 - ALIOSS::OSS_CORS_EXPOSE_HEADER 可选,指定允许用户从应用程序中访问的响应头(例如一个Javascript的XMLHttpRequest对象。) - 不允许使用“*”通配符。 - ALIOSS::OSS_CORS_MAX_AGE_SECONDS 可选,指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒。 - 一个CORSRule里面最多允许出现一个。 - - $options 可选参数,无需设置 - - ` - - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 07:03:29 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594E241031C87E546160697 - ) - - [body] => - ) - - - ` - -* 获取CORS规则 - * 示例代码 - - ` - - $bucket = 'bucket name'; - $options = null; - $response = $client->get_bucket_cors($bucket_name,$options); - - ` - - - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 07:03:39 GMT - [content-type] => application/xml - [content-length] => 327 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594E24B58DB3AB752160920 - ) - - [body] => Array( - [CORSConfiguration] => Array( - [CORSRule] => Array( - [AllowedOrigin] => http://www.b.com - [AllowedMethod] => GET - [AllowedHeader] => x-oss-test - [ExposeHeader] => x-oss-test1 - [MaxAgeSeconds] => 10 - ) - ) - ) - ) - - ` - -* 评估是否允许跨域请求 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name ='object name'; - $origin = 'http://www.b.com'; - $request_method = ALIOSS::OSS_HTTP_GET; - $request_headers = 'x-oss-test'; - $options = null; - - $response = $obj->options_object($bucket_name, $object_name, $origin, $request_method, $request_headers,$options); - - - ` - - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范 - $object_name 必选参数,必须符合object命名规范 - $origin 必选参数,请求来源域,用来标示跨域请求 - $request_method 必选参数,表示在实际请求中将会用到的方法 - $request_headers 必选参数,表示在实际请求中会用到的除了简单头部之外的headers - $options 可选参数,无需设置 - - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 07:03:39 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594E24B031C87E5461606A1 - ) - - [body] => - ) - - ` - - -* 删除CORS规则 - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->delete_bucket_cors($bucket_name,$options); - - ` - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array - ( - [status] => 204 - [header] => Array( - [date] => Thu, 02 Jul 2015 07:03:39 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594E24B031C87E5461606A2 - ) - - [body] => - ) - - ` - -## 静态网站托管(WebSite) -* 设置WebSite - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $index_document = 'index.html'; - $error_document = 'error.html'; - $options = null; - $response = $client->set_bucket_website($bucket_name,$index_document,$error_document,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范 - $index_document 必选参数,开启website功能,必须设置index_document - $error_document 可选参数,自行决定在开启website功能时,是否设置error_document - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 02:39:23 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594A45B58DB3AB75215E239 - ) - - [body] => - ) - - ` - -* 获取WebSite设置 - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->get_bucket_website($bucket_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 02:39:24 GMT - [content-type] => application/xml - [content-length] => 218 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594A45C031C87E54615DF98 - ) - - [body] => Array( - [WebsiteConfiguration] => Array( - [IndexDocument] => Array( - [Suffix] => index.html - ) - - [ErrorDocument] => Array( - [Key] => error.html - ) - ) - ) - ) - - - ` - -* 删除WebSite - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->delete_bucket_website($bucket_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 204 - [header] => Array( - [date] => Thu, 02 Jul 2015 02:39:24 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594A45C031C87E54615DF99 - ) - [body] => - ) - - ` - -## 日志管理(Logging) -* 设置Logging - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $target_bucket_name = "logging target bucket"; - $target_prefix = "logging file prefix"; - $options = null; - $response = $client->set_bucket_logging($bucket_name,$target_bucket_name,$target_prefix,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必须参数,必须符合bucket命名规范;且必须是属于owner的存在的bucket - $target_bucket_name 必须参数,日志保存的目标bucket,且必须和要记录日志的bucket在同一集群 - $target_prefix 可选参数,如果设置,日志文件的名称为 $target_prefix + oss日志规范命名 - $options 可选参数,无需设置 - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 01:59:06 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 55949AEA031C87E54615D996 - ) - - [body] => - ) - - ` - -* 获取logging设置 - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->get_bucket_logging($bucket_name,$options); - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 02:14:09 GMT - [content-length] => 235 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 55949E7158DB3AB75215DE78 - ) - - [body] => Array( - [BucketLoggingStatus] => Array( - [LoggingEnabled] => Array( - [TargetBucket] => a-00000000000000000003 - [TargetPrefix] => common-bucket-logging- - ) - ) - ) - ) - - ` - -* 删除Logging - * 示例代码 - - ` - - $bucket_name = "bucket name"; - $options = null; - $response = $client->get_bucket_logging($bucket_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 204 - [header] => Array( - [date] => Thu, 02 Jul 2015 02:29:12 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594A1F858DB3AB75215E0C4 - ) - - [body] => - ) - - ` - - -## 防盗链(Referer) -* 设置Referer防盗链 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $is_allow_empty_referer = true; - $referer_list = array( - 'http://aliyun.com', - 'http://sina.com.cn' - ); - $options = null; - $response = $client->set_bucket_referer($bucket_name,$is_allow_empty_referer,$referer_list,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $is_allow_empty_referer 必选参数,是否允许空referer,默认为true - $referer_list 可选参数,允许的refer白名单列表,注意每条记录均需以http://开头 - $options 可选参数,无需设置 - - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 03:30:46 GMT - [content-length] => 0 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594B06658DB3AB75215E9EC - ) - - [body] => - ) - - ` - -* 获取Referer设置 - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $options = null; - $response = $client->get_bucket_referer($bucket_name,$options); - - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,必须符合bucket命名规范 - $options 可选参数,无需设置 - - ` - - * 响应结果 - - ` - 将结果Response转换成array得到,下同 - - Array( - [status] => 200 - [header] => Array( - [date] => Thu, 02 Jul 2015 03:30:46 GMT - [content-type] => application/xml - [content-length] => 248 - [connection] => close - [server] => AliyunOSS - [x-oss-request-id] => 5594B06658DB3AB75215E9F2 - ) - - [body] => Array( - [RefererConfiguration] => Array( - [AllowEmptyReferer] => true - [RefererList] => Array( - [Referer] => Array( - [0] => http://aliyun.com - [1] => http://sina.com.cn - ) - ) - ) - ) - ) - - ` - -## URL签名操作 -* 获取Get签名URL - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $timeout = 3600; - $options = null; - $signed_url = $client->get_sign_url($bucket_name,$object_name,$timeout,$options); - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,参数需要符合bucket命名规范 - $object_name 必选参数,参数需要符合object命名规范 - $timeout 必选参数,过期时间 - $options 可选参数,无需设置 - - ` - - - * 响应结果 - - ` - - http://common-bucket.oss-cn-shanghai.aliyuncs.com/my_get_file.log?OSSAccessKeyId=ACSb***&Expires=1435820652& - Signature=AW5z87zmaLulEmvMzf6ZOUrVboE%3D - - ` - -* 获取Get或Put签名URL - * 示例代码 - - ` - - $bucket_name = 'bucket name'; - $object_name = 'object name'; - $timeout = 3600; - $method = ALIOSS::OSS_HTTP_GET; - $options = null; - $signed_url = $client->get_sign_url($bucket_name,$object_name,$timeout,$method,$options); - ` - - * 参数说明 - - ` - - $bucket_name 必选参数,参数需要符合bucket命名规范 - $object_name 必选参数,参数需要符合object命名规范 - $timeout 必选参数,过期时间 - $method 必选参数,方法类型,目前支持GET、PUT - $options 可选参数,无需设置 - - ` - - - * 响应结果 - - ` - - http://common-bucket.oss-cn-shanghai.aliyuncs.com/my_get_file.log?OSSAccessKeyId=ACSb***&Expires=1435820652& - Signature=AW5z87zmaLulEmvMzf6ZOUrVboE%3D - - ` - diff --git a/AliOssSdk/lang/zh.inc.php b/AliOssSdk/lang/zh.inc.php deleted file mode 100644 index 368ea2a..0000000 --- a/AliOssSdk/lang/zh.inc.php +++ /dev/null @@ -1,99 +0,0 @@ -. You can get the code from . - -### License and Copyright - -This code is Copyright (c) 2008-2010, Ryan Parman. However, I'm licensing this code for others to use under the [Simplified BSD license](http://www.opensource.org/licenses/bsd-license.php). diff --git a/AliOssSdk/lib/requestcore/requestcore.class.php b/AliOssSdk/lib/requestcore/requestcore.class.php deleted file mode 100644 index f475859..0000000 --- a/AliOssSdk/lib/requestcore/requestcore.class.php +++ /dev/null @@ -1,1030 +0,0 @@ -). - */ - public $request_class = 'RequestCore'; - - /** - * The default class to use for HTTP Responses (defaults to ). - */ - public $response_class = '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; - - - /*%******************************************************************************************%*/ - // 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 - - /** - * Constructs 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; - } - - /** - * Destructs 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 - - /** - * Sets 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; - } - - /** - * Adds 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; - } - - /** - * Removes 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; - } - - /** - * Sets 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; - } - - /** - * Sets 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; - } - - /** - * Sets 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); - } - - /** - * Sets 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); - } - - /** - * Sets 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; - } - - /** - * Sets 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; - $write_file_handle = fopen($location, 'w'); - - return $this->set_write_stream($write_file_handle); - } - - /** - * 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; - } - - /** - * 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) - { - $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; - } - - /** - * Prepares 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, 5184000); - curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 120); - 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_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) - { - curl_setopt($curl_handle, CURLOPT_HTTPPROXYTUNNEL, true); - - $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; - } - - 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_POST, true); - 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)) - { - 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 $curl_handle (Optional) The reference to the already executed cURL request. - * @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->curl_handle = $curl_handle; - $this->response = $response; - } - - // As long as this came back as a valid resource... - if (is_resource($this->curl_handle)) - { - // Determine what's what. - $header_size = curl_getinfo($this->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($this->curl_handle, CURLINFO_HTTP_CODE); - $this->response_info = curl_getinfo($this->curl_handle); - - // 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 $this->response_class($this->response_headers, $this->response_body, $this->response_code, $this->curl_handle); - } - } - - // Return false - return false; - } - - /** - * Sends 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 resource: ' . (string) $curl_handle . '; cURL error: ' . curl_error($curl_handle) . ' (' . curl_errno($curl_handle) . ')'); - } - - $parsed_response = $this->process_response($curl_handle, $this->response); - - curl_close($curl_handle); - - if ($parse) - { - return $parsed_response; - } - - return $this->response; - } - - /** - * Sends the request using , enabling parallel requests. Uses the "rolling" method. - * - * @param array $handles (Required) An indexed array of cURL handles to process simultaneously. - * @param array $opt (Optional) An associative array of parameters that can have the following keys:
    - *
  • callback - string|array - Optional - The string name of a function to pass the response data to. If this is a method, pass an array where the [0] index is the class and the [1] index is the method name.
  • - *
  • limit - integer - Optional - The number of simultaneous requests to make. This can be useful for scaling around slow server responses. Defaults to trusting cURLs judgement as to how many to use.
- * @return array Post-processed cURL responses. - */ - public function send_multi_request($handles, $opt = null) - { - set_time_limit(0); - - // Skip everything if there are no handles to process. - if (count($handles) === 0) return array(); - - if (!$opt) $opt = array(); - - // Initialize any missing options - $limit = isset($opt['limit']) ? $opt['limit'] : -1; - - // Initialize - $handle_list = $handles; - $http = new $this->request_class(); - $multi_handle = curl_multi_init(); - $handles_post = array(); - $added = count($handles); - $last_handle = null; - $count = 0; - $i = 0; - - // Loop through the cURL handles and add as many as it set by the limit parameter. - while ($i < $added) - { - if ($limit > 0 && $i >= $limit) break; - curl_multi_add_handle($multi_handle, array_shift($handles)); - $i++; - } - - do - { - $active = false; - - // Start executing and wait for a response. - while (($status = curl_multi_exec($multi_handle, $active)) === CURLM_CALL_MULTI_PERFORM) - { - // Start looking for possible responses immediately when we have to add more handles - if (count($handles) > 0) break; - } - - // Figure out which requests finished. - $to_process = array(); - - while ($done = curl_multi_info_read($multi_handle)) - { - // Since curl_errno() isn't reliable for handles that were in multirequests, we check the 'result' of the info read, which contains the curl error number, (listed here http://curl.haxx.se/libcurl/c/libcurl-errors.html ) - if ($done['result'] > 0) - { - throw new RequestCore_Exception('cURL resource: ' . (string) $done['handle'] . '; cURL error: ' . curl_error($done['handle']) . ' (' . $done['result'] . ')'); - } - - // Because curl_multi_info_read() might return more than one message about a request, we check to see if this request is already in our array of completed requests - elseif (!isset($to_process[(int) $done['handle']])) - { - $to_process[(int) $done['handle']] = $done; - } - } - - // Actually deal with the request - foreach ($to_process as $pkey => $done) - { - $response = $http->process_response($done['handle'], curl_multi_getcontent($done['handle'])); - $key = array_search($done['handle'], $handle_list, true); - $handles_post[$key] = $response; - - if (count($handles) > 0) - { - curl_multi_add_handle($multi_handle, array_shift($handles)); - } - - curl_multi_remove_handle($multi_handle, $done['handle']); - curl_close($done['handle']); - } - } - while ($active || count($handles_post) < $added); - - curl_multi_close($multi_handle); - - ksort($handles_post, SORT_NUMERIC); - return $handles_post; - } - - - /*%******************************************************************************************%*/ - // 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; - } -} - - -/** - * Container for all response-related methods. - */ -class ResponseCore -{ - /** - * Stores the HTTP header information. - */ - public $header; - - /** - * Stores the SimpleXML response. - */ - public $body; - - /** - * Stores the HTTP response code. - */ - public $status; - - /** - * Constructs a new instance of this class. - * - * @param array $header (Required) Associative array of HTTP headers (typically returned by ). - * @param string $body (Required) XML-formatted response from AWS. - * @param integer $status (Optional) HTTP response status code from the request. - * @return object 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; - } -} - -/** - * Default RequestCore Exception. - */ -class RequestCore_Exception extends Exception {} diff --git a/AliOssSdk/sdk.class.php b/AliOssSdk/sdk.class.php deleted file mode 100644 index 1663638..0000000 --- a/AliOssSdk/sdk.class.php +++ /dev/null @@ -1,2104 +0,0 @@ -access_id = $access_id; - $this->access_key = $access_key; - }elseif (defined('OSS_ACCESS_ID') && defined('OSS_ACCESS_KEY')){ - $this->access_id = OSS_ACCESS_ID; - $this->access_key = OSS_ACCESS_KEY; - }else{ - throw new OSS_Exception(NOT_SET_OSS_ACCESS_ID_AND_ACCESS_KEY); - } - if(empty($this->access_id) || empty($this->access_key)){ - throw new OSS_Exception(OSS_ACCESS_ID_OR_ACCESS_KEY_EMPTY); - } - if ($hostname) { - $this->hostname = $hostname; - } - else if (!$hostname and defined('OSS_ENDPOINT')) { - $this->hostname = OSS_ENDPOINT; - }else{ - $this->hostname = self::DEFAULT_OSS_ENDPOINT; - } - - //支持sts的security token - $this->security_token = $security_token; - } - - - /*%******************************************************************************************************%*/ - //Service Operation - /** - * 获取bucket列表 - * @param array $options (Optional) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function list_bucket($options = NULL) { - $this->precheck_options($options); - $options[self::OSS_BUCKET] = ''; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $response = $this->auth($options); - return $response; - } - - /*%******************************************************************************************************%*/ - //Bucket Operation - /** - * 创建bucket - * @param string $bucket (Required) - * @param string $acl (Optional) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function create_bucket($bucket, $acl = self::OSS_ACL_TYPE_PRIVATE, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_HEADERS] = array(self::OSS_ACL => $acl); - $response = $this->auth($options); - return $response; - } - - /** - * 删除bucket - * @param string $bucket (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function delete_bucket($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; - $options[self::OSS_OBJECT] = '/'; - $response = $this->auth($options); - return $response; - } - - /** - * 获取bucket的acl - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function get_bucket_acl($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'acl'; - $response = $this->auth($options); - return $response; - } - - /** - * 设置bucket的acl - * @param string $bucket (Required) - * @param string $acl (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function set_bucket_acl($bucket, $acl, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_HEADERS] = array(self::OSS_ACL => $acl); - $response = $this->auth($options); - return $response; - } - - /** - * 获取bucket logging - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function get_bucket_logging($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'logging'; - $response = $this->auth($options); - return $response; - } - - /** - * 设置bucket Logging - * @param string $bucket (Required) - * @param string $target_bucket (Required) - * @param string $target_prefix (Optional) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function set_bucket_logging($bucket, $target_bucket, $target_prefix, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $this->precheck_bucket($target_bucket, OSS_TARGET_BUCKET_IS_NOT_ALLOWED_EMPTY); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'logging'; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - $xml = new SimpleXMLElement(''); - $logging_enabled_part=$xml->addChild('LoggingEnabled'); - $logging_enabled_part->addChild('TargetBucket', $target_bucket); - $logging_enabled_part->addChild('TargetPrefix', $target_prefix); - $options[self::OSS_CONTENT] = $xml->asXML(); - return $this->auth($options); - } - - /** - * 删除bucket logging - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function delete_bucket_logging($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'logging'; - $response = $this->auth($options); - return $response; - } - - /** - * 设置bucket website - * @param string $bucket (Required) - * @param string $index_document (Required) - * @param string $error_document (Optional) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function set_bucket_website($bucket, $index_document, $error_document, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - OSSUtil::is_empty($index_document, OSS_INDEX_DOCUMENT_IS_NOT_ALLOWED_EMPTY); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'website'; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - - $xml = new SimpleXMLElement(''); - $index_document_part=$xml->addChild('IndexDocument'); - $error_document_part=$xml->addChild('ErrorDocument'); - $index_document_part->addChild('Suffix', $index_document); - $error_document_part->addChild('Key', $error_document); - $options[self::OSS_CONTENT] = $xml->asXML(); - return $this->auth($options); - } - - /** - * 获取bucket website - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function get_bucket_website($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'website'; - $response = $this->auth($options); - return $response; - } - - /** - * 删除bucket website - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function delete_bucket_website($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'website'; - $response = $this->auth($options); - return $response; - } - - /** - * 设置bucket cors - * @param string $bucket (Required) - * @param array $cors_rules (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function set_bucket_cors($bucket, $cors_rules, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'cors'; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - $xml = new SimpleXMLElement(''); - foreach ($cors_rules as $cors_rule){ - $cors_rule_part = $xml->addChild('CORSRule'); - foreach ($cors_rule[self::OSS_CORS_ALLOWED_ORIGIN] as $value){ - $cors_rule_part->addChild(self::OSS_CORS_ALLOWED_ORIGIN, $value); - } - foreach ($cors_rule[self::OSS_CORS_ALLOWED_HEADER] as $value){ - $cors_rule_part->addChild(self::OSS_CORS_ALLOWED_HEADER, $value); - } - foreach ($cors_rule[self::OSS_CORS_ALLOWED_METHOD] as $value){ - $cors_rule_part->addChild(self::OSS_CORS_ALLOWED_METHOD, $value); - } - foreach ($cors_rule[self::OSS_CORS_EXPOSE_HEADER] as $value){ - $cors_rule_part->addChild(self::OSS_CORS_EXPOSE_HEADER, $value); - } - $cors_rule_part->addChild(self::OSS_CORS_MAX_AGE_SECONDS, $cors_rule[self::OSS_CORS_MAX_AGE_SECONDS]); - } - $options[self::OSS_CONTENT] = $xml->asXML(); - return $this->auth($options); - } - /** - * 获取bucket cors - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function get_bucket_cors($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'cors'; - $response = $this->auth($options); - return $response; - } - - /** - * 删除bucket cors - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @author lijie.ma@alibaba-inc.com - * @since 2014-05-04 - * @return ResponseCore - */ - public function delete_bucket_cors($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'cors'; - $response = $this->auth($options); - return $response; - } - - /** - * 检验跨域资源请求 - * @param string $bucket (Required) - * @param string $object (Required) - * @param string $origin (Required) - * @param string $request_method (Required) - * @param string $request_headers (Required) - * @param array $options (Optional) - * @return ResponseCore - * @throws OSS_Exception - */ - public function options_object($bucket, $object, $origin, $request_method, $request_headers, $options = NULL){ - $this->precheck_common($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] = array( - self::OSS_OPTIONS_ORIGIN => $origin, - self::OSS_OPTIONS_REQUEST_HEADERS => $request_headers, - self::OSS_OPTIONS_REQUEST_METHOD => $request_method - ); - $response = $this->auth($options); - return $response; - } - - /** - * 设置bucket lifecycle - * @param string $bucket (Required) - * @param string $lifecycle_xml (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @since 2015-03-11 - * @return ResponseCore - */ - public function set_bucket_lifecycle($bucket, $lifecycle_xml, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - $options[self::OSS_CONTENT] = $lifecycle_xml; - return $this->auth($options); - } - - /** - * 获取bucket lifecycle - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @since 2015-03-11 - * @return ResponseCore - */ - public function get_bucket_lifecycle($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; - return $this->auth($options); - } - - /** - * 删除bucket lifecycle - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @since 2015-03-11 - * @return ResponseCore - */ - public function delete_bucket_lifecycle($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; - return $this->auth($options); - } - - /** - * 设置bucket referer - * @param string $bucket (Required) - * @param bool $is_allow_empty_referer (Required) - * @param array $referer_list (Optional) - * @param array $options (Optional) - * @return ResponseCore - * @throws OSS_Exception - */ - public function set_bucket_referer($bucket, $is_allow_empty_referer = true, $referer_list = NULL, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'referer'; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - - $xml = new SimpleXMLElement(''); - $list = $xml->addChild('RefererList'); - if ($referer_list){ - foreach ($referer_list as $value){ - $list->addChild('Referer', $value); - } - } - else{ - $list->addChild('Referer', ''); - } - $value = "true"; - if (!$is_allow_empty_referer){ - $value = "false"; - } - $xml->addChild('AllowEmptyReferer', $value); - $options[self::OSS_CONTENT] = $xml->asXML(); - return $this->auth($options); - } - - /** - * 获取bucket referer - * @param string $bucket (Required) - * @param array $options (Optional) - * @throws OSS_Exception - * @since 2015-03-11 - * @return ResponseCore - */ - public function get_bucket_referer($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'referer'; - return $this->auth($options); - } - - /*%******************************************************************************************************%*/ - //Object Operation - - /** - * 获取bucket下的object列表 - * @param string $bucket (Required) - * @param array $options (Optional) - * 其中options中的参数如下 - * $options = array( - * 'max-keys' => max-keys用于限定此次返回object的最大数,如果不设定,默认为100,max-keys取值不能大于100。 - * 'prefix' => 限定返回的object key必须以prefix作为前缀。注意使用prefix查询时,返回的key中仍会包含prefix。 - * 'delimiter' => 是一个用于对Object名字进行分组的字符。所有名字包含指定的前缀且第一次出现delimiter字符之间的object作为一组元素 - * 'marker' => 用户设定结果从marker之后按字母排序的第一个开始返回。 - *) - * 其中 prefix,marker用来实现分页显示效果,参数的长度必须小于256字节。 - * @throws OSS_Exception - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function list_object($bucket, $options = NULL){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_HEADERS] = array( - 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]:'', - ); - return $this->auth($options); - } - - /** - * 创建目录(目录和文件的区别在于,目录最后增加'/') - * @param string $bucket (Required) - * @param string $object (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function create_object_dir($bucket, $object, $options = NULL){ - $this->precheck_common($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); - return $this->auth($options); - } - - /** - * 通过在http body中添加内容来上传文件,适合比较小的文件 - * 根据api约定,需要在http header中增加content-length字段 - * @param string $bucket (Required) - * @param string $object (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function upload_file_by_content($bucket, $object, $options = NULL){ - $this->precheck_common($bucket, $object, $options); - - //内容校验 - OSSUtil::validate_content($options); - $content_type = $this->get_mime_type($object); - $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]; - } - - if(!isset($options[self::OSS_CONTENT_TYPE]) && isset($content_type) && !empty($content_type)){ - $options[self::OSS_CONTENT_TYPE] = $content_type; - } - return $this->auth($options); - } - - /** - * 上传文件,适合比较大的文件 - * @throws OSS_Exception - * @param string $bucket (Required) - * @param string $object (Required) - * @param string $file (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2012-02-28 - * @return ResponseCore - */ - public function upload_file_by_file($bucket, $object, $file, $options = NULL){ - $this->precheck_common($bucket, $object, $options); - OSSUtil::is_empty($file, OSS_FILE_PATH_IS_NOT_ALLOWED_EMPTY); - //Windows系统下进行转码 - $file = OSSUtil::encoding_path($file); - $options[self::OSS_FILE_UPLOAD] = $file; - if(!file_exists($options[self::OSS_FILE_UPLOAD])){ - throw new OSS_Exception($options[self::OSS_FILE_UPLOAD].OSS_FILE_NOT_EXIST); - } - $file_size = filesize($options[self::OSS_FILE_UPLOAD]); - $is_check_md5 = $this->is_check_md5($options); - if ($is_check_md5){ - $content_md5 = base64_encode(md5_file($options[self::OSS_FILE_UPLOAD], true)); - $options[self::OSS_CONTENT_MD5] = $content_md5; - } - $content_type = $this->get_mime_type($file); - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_OBJECT] = $object; - $options[self::OSS_CONTENT_TYPE] = $content_type; - $options[self::OSS_CONTENT_LENGTH] = $file_size; - $response = $this->auth($options); - return $response; - } - - /** - * 拷贝object - * @param string $from_bucket (Required) - * @param string $from_object (Required) - * @param string $to_bucket (Required) - * @param string $to_object (Required) - * @param array $options (Optional) - * @return ResponseCore - * @throws OSS_Exception - */ - public function copy_object($from_bucket, $from_object, $to_bucket, $to_object, $options = NULL){ - $this->precheck_common($from_bucket, $from_object, $options); - $this->precheck_common($to_bucket, $to_object, $options); - $options[self::OSS_BUCKET] = $to_bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_PUT; - $options[self::OSS_OBJECT] = $to_object; - if(isset($options[self::OSS_HEADERS])){ - $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE] = '/'.$from_bucket.'/'.$from_object; - } - else { - $options[self::OSS_HEADERS] = array(self::OSS_OBJECT_COPY_SOURCE => '/'.$from_bucket.'/'.$from_object); - } - - return $this->auth($options); - } - - /** - * 获得object的meta信息 - * @param string $bucket (Required) - * @param string $object (Required) - * @param string $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function get_object_meta($bucket, $object, $options = NULL){ - $this->precheck_common($bucket, $object, $options); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_HEAD; - $options[self::OSS_OBJECT] = $object; - return $this->auth($options); - } - - /** - * 删除object - * @param string $bucket(Required) - * @param string $object (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function delete_object($bucket, $object, $options = NULL){ - $this->precheck_common($bucket, $object, $options); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_DELETE; - $options[self::OSS_OBJECT] = $object; - return $this->auth($options); - } - - /** - * 批量删除objects - * @throws OSS_Exception - * @param string $bucket(Required) - * @param array $objects (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2012-03-09 - * @return ResponseCore - */ - public function delete_objects($bucket, $objects, $options = null){ - $this->precheck_common($bucket, NULL, $options, false); - //objects - if(!is_array($objects) || !$objects){ - throw new OSS_Exception('The ' . __FUNCTION__ . ' method requires the "objects" option to be set as an array.'); - } - - $options[self::OSS_METHOD] = self::OSS_HTTP_POST; - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_OBJECT] = '/'; - $options[self::OSS_SUB_RESOURCE] = 'delete'; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - $xml = new SimpleXMLElement(''); - // Quiet mode - if (isset($options['quiet'])){ - $quiet = 'false'; - if (is_bool($options['quiet'])) { //Boolean - $quiet = $options['quiet'] ? 'true' : 'false'; - }elseif (is_string($options['quiet'])){ // String - $quiet = ($options['quiet'] === 'true') ? 'true' : 'false'; - } - $xml->addChild('Quiet', $quiet); - } - // Add the objects - foreach ($objects as $object){ - $sub_object = $xml->addChild('Object'); - $object = OSSUtil::s_replace($object); - $sub_object->addChild('Key', $object); - } - $options[self::OSS_CONTENT] = $xml->asXML(); - return $this->auth($options); - } - - /** - * 获得Object内容 - * @param string $bucket(Required) - * @param string $object (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function get_object($bucket, $object, $options = NULL){ - $this->precheck_common($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]); - } - - return $this->auth($options); - } - - /** - * 检测Object是否存在 - * @param string $bucket(Required) - * @param string $object (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function is_object_exist($bucket, $object, $options = NULL){ - return $this->get_object_meta($bucket, $object, $options); - } - - /** - * 获取分片大小 - * @param int $part_size (Required) - * @return int - */ - private function get_part_size($part_size){ - $part_size = (integer)$part_size; - if($part_size <= self::OSS_MIN_PART_SIZE){ - $part_size = self::OSS_MIN_PART_SIZE; - }elseif ($part_size > self::OSS_MAX_PART_SIZE){ - $part_size = self::OSS_MAX_PART_SIZE; - }else{ - $part_size = self::OSS_MID_PART_SIZE; - } - return $part_size; - } - - /*%******************************************************************************************************%*/ - //Multi Part相关操作 - /** - * 计算文件可以分成多少个part,以及每个part的长度以及起始位置 - * 方法必须在 中调用 - * - * @param integer $file_size (Required) 文件大小 - * @param integer $part_size (Required) part大小,默认5M - * @return array An array 包含 key-value 键值对. Key 为 `seekTo` 和 `length`. - */ - public function get_multipart_counts($file_size, $part_size = 5242880){ - $i = 0; - $size_count = $file_size; - $values = array(); - $part_size = $this->get_part_size($part_size); - while ($size_count > 0) - { - $size_count -= $part_size; - $values[] = array( - self::OSS_SEEK_TO => ($part_size * $i), - self::OSS_LENGTH => (($size_count > 0) ? $part_size : ($size_count + $part_size)), - ); - $i++; - } - return $values; - } - - /** - * 初始化multi-part upload - * @param string $bucket (Required) Bucket名称 - * @param string $object (Required) Object名称 - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - */ - public function initiate_multipart_upload($bucket, $object, $options = NULL){ - $this->precheck_common($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] = ''; - $content_type = $this->get_mime_type($object); - if(!isset($options[self::OSS_HEADERS])){ - $options[self::OSS_HEADERS] = array(); - } - $options[self::OSS_HEADERS][self::OSS_CONTENT_TYPE] = $content_type; - - return $this->auth($options); - } - - /** - * 初始化multi-part upload,并且返回uploadId - * @param string $bucket (Required) Bucket名称 - * @param string $object (Required) Object名称 - * @param array $options (Optional) Key-Value数组 - * @return string uploadId - * @throws OSS_Exception - */ - public function init_multipart_upload($bucket, $object, $options = NULL){ - $res = $this->initiate_multipart_upload($bucket, $object, $options); - if (!$res->isOK()){ - throw new OSS_Exception('Init multi-part upload failed...'); - } - $xml = new SimpleXmlIterator($res->body); - $uploadId = (string)$xml->UploadId; - return $uploadId; - } - - /** - * 上传part - * @param string $bucket (Required) Bucket名称 - * @param string $object (Required) Object名称 - * @param string $upload_id (Required) uploadId - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - */ - public function upload_part($bucket, $object, $upload_id, $options = null){ - $this->precheck_common($bucket, $object, $options); - $this->precheck_param($options, self::OSS_FILE_UPLOAD, __FUNCTION__); - $this->precheck_param($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] = $upload_id; - - if(isset($options[self::OSS_LENGTH])){ - $options[self::OSS_CONTENT_LENGTH] = $options[self::OSS_LENGTH]; - } - return $this->auth($options); - } - - /** - * 获取已成功上传的part - * @param string $bucket (Required) Bucket名称 - * @param string $object (Required) Object名称 - * @param string $upload_id (Required) uploadId - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - */ - public function list_parts($bucket, $object, $upload_id, $options = null){ - $this->precheck_common($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] = $upload_id; - $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]); - } - } - return $this->auth($options); - } - - /** - * 中止上传mulit-part upload - * @param string $bucket (Required) Bucket名称 - * @param string $object (Required) Object名称 - * @param string $upload_id (Required) uploadId - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - */ - public function abort_multipart_upload($bucket, $object, $upload_id, $options = NULL){ - $this->precheck_common($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] = $upload_id; - return $this->auth($options); - } - - /** - * 完成multi-part上传 - * @param string $bucket (Required) Bucket名称 - * @param string $object (Required) Object名称 - * @param string $upload_id (Required) uploadId - * @param array | xml $parts 可以是一个上传成功part的数组,或者是一个ReponseCore对象 - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - */ - public function complete_multipart_upload($bucket, $object, $upload_id, $parts, $options = NULL){ - $this->precheck_common($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] = $upload_id; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; - - if(is_string($parts)){ - $options[self::OSS_CONTENT] = $parts; - }else if($parts instanceof SimpleXMLElement){ - $options[self::OSS_CONTENT] = $parts->asXML(); - }else if((is_array($parts) || $parts instanceof ResponseCore)){ - $xml = new SimpleXMLElement(''); - - if (is_array($parts)){ - foreach ($parts as $node){ - $part = $xml->addChild('Part'); - $part->addChild('PartNumber', $node['PartNumber']); - $part->addChild('ETag', $node['ETag']); - } - }elseif ($parts instanceof ResponseCore){ - foreach ($parts->body->Part as $node){ - $part = $xml->addChild('Part'); - $part->addChild('PartNumber', (string) $node->PartNumber); - $part->addChild('ETag', (string) $node->ETag); - } - } - $options[self::OSS_CONTENT] = $xml->asXML(); - } - return $this->auth($options); - } - - /** - * 列出multipart上传 - * @param string $bucket (Requeired) bucket - * @param array $options (Optional) 关联数组 - * @author xiaobing - * @since 2012-03-05 - * @return ResponseCore - */ - public function list_multipart_uploads($bucket, $options = null){ - $this->precheck_common($bucket, NULL, $options, false); - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_OBJECT] = '/'; - $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]); - } - } - return $this->auth($options); - } - - /** - * 从已存在的object拷贝part - * @param string $from_bucket (Required) - * @param string $from_object (Required) - * @param string $to_bucket (Required) - * @param string $to_object (Required) - * @param int $part_number (Required) - * @param string $upload_id (Required) - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - * @throws OSS_Exception - */ - public function copy_upload_part($from_bucket, $from_object, $to_bucket, $to_object, $part_number, $upload_id, $options = NULL){ - $this->precheck_common($from_bucket, $from_object, $options); - $this->precheck_common($to_bucket, $to_object, $options); - - //如果没有设置$options['isFullCopy'],则需要强制判断copy的起止位置 - $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] = $to_bucket; - $options[self::OSS_OBJECT] = $to_object; - $options[self::OSS_PART_NUM] = $part_number; - $options[self::OSS_UPLOAD_ID] = $upload_id; - - if(!isset($options[self::OSS_HEADERS])){ - $options[self::OSS_HEADERS] = array(); - } - - $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE] = '/' . $from_bucket . '/' . $from_object; - $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE_RANGE] = "bytes=" . $start_range . "-" . $end_range; - return $this->auth($options); - } - - /** - * multipart上传统一封装,从初始化到完成multipart,以及出错后中止动作 - * @param string $bucket (Required) - * @param string $object (Required) - * @param array $options (Optional) Key-Value数组 - * @return ResponseCore - * @throws OSS_Exception - */ - public function create_mpu_object($bucket, $object, $options = null){ - $this->precheck_common($bucket, $object, $options); - if(isset($options[self::OSS_LENGTH])){ - $options[self::OSS_CONTENT_LENGTH] = $options[self::OSS_LENGTH]; - unset($options[self::OSS_LENGTH]); - } - - if(isset($options[self::OSS_FILE_UPLOAD])){ - //Windows系统下进行转码 - $options[self::OSS_FILE_UPLOAD] = OSSUtil::encoding_path($options[self::OSS_FILE_UPLOAD]); - } - - $this->precheck_param($options, self::OSS_FILE_UPLOAD, __FUNCTION__); - $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 { - $filename = $options[self::OSS_FILE_UPLOAD]; - $upload_file_size = filesize($filename); - 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 OSS_Exception('The size of `fileUpload` cannot be determined in ' . __FUNCTION__ . '().'); - } - // 处理partSize - if (isset($options[self::OSS_PART_SIZE])){ - $options[self::OSS_PART_SIZE] = $this->get_part_size($options[self::OSS_PART_SIZE]); - } - else{ - $options[self::OSS_PART_SIZE] = self::OSS_MID_PART_SIZE; - } - - $is_check_md5 = $this->is_check_md5($options); - // 如果上传的文件小于partSize,则直接使用普通方式上传 - if ($upload_file_size < $options[self::OSS_PART_SIZE] && !isset($options[self::OSS_UPLOAD_ID])){ - $local_file = $options[self::OSS_FILE_UPLOAD]; - $options = array( - self::OSS_CHECK_MD5 => $is_check_md5, - ); - return $this->upload_file_by_file($bucket, $object, $local_file, $options); - } - - // 初始化multipart - if (isset($options[self::OSS_UPLOAD_ID])){ - $upload_id = $options[self::OSS_UPLOAD_ID]; - }else{ - //初始化 - $init_options = array(); - $upload_id = $this->init_multipart_upload($bucket, $object, $init_options); - } - - // 获取的分片 - $pieces = $this->get_multipart_counts($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 => $options[self::OSS_FILE_UPLOAD], - 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::get_content_md5_of_file($options[self::OSS_FILE_UPLOAD], $from_pos, $to_pos); - $up_options[self::OSS_CONTENT_MD5] = $content_md5; - } - $response_upload_part[] = $this->upload_part($bucket, $object, $upload_id, $up_options); - } - - $upload_parts = array(); - $upload_part_result = true; - foreach ($response_upload_part as $i => $response){ - $upload_part_result = $upload_part_result && $response->isOk(); - if(!$upload_part_result){ - throw new OSS_Exception('any part upload failed, please try again'); - } - $upload_parts[] = array( - 'PartNumber' => ($i + 1), - 'ETag' => (string) $response->header['etag'] - ); - } - return $this->complete_multipart_upload($bucket, $object, $upload_id, $upload_parts); - } - - /** - * 通过Multi-Part方式上传整个目录,其中的object默认为文件名 - * @param string $bucket (Required) - * @param string $dir (Required) - * @param bool $recursive 是否递归,如果为true,则递归读取所有目录,默认为不递归读取 - * @param string $exclude - * @param array $options (Optional) Key-Value数组,其中可以包括以下的key - * @return bool - * @throws OSS_Exception - */ - public function create_mtu_object_by_dir($bucket, $dir, $recursive = false, $exclude = ".|..|.svn", $options = null){ - $this->precheck_common($bucket, NULL, $options, false); - //Windows系统下进行转码 - $dir = OSSUtil::encoding_path($dir); - //判断是否目录 - if(!is_dir($dir)){ - throw new OSS_Exception($dir.' is not a directory, please check it'); - } - - $file_list_array = $this->read_dir($dir, $exclude, $recursive); - - - if(empty($file_list_array)){ - throw new OSS_Exception($dir.' is empty...'); - } - - $is_upload_ok = true; - $index = 1; - - foreach ($file_list_array as $k=>$item){ - echo $index++.". "; - echo "Multiupload file ".$item['path']." "; - if (is_dir($item['path'])) { - echo " skipped, because it is directory...\n"; - } - else { - $options = array( - self::OSS_FILE_UPLOAD => $item['path'], - self::OSS_PART_SIZE => self::OSS_MIN_PART_SIZE, - ); - - $response = $this->create_mpu_object($bucket, $item['file'], $options); - if($response->isOK()){ - echo " successful..\n"; - } - else { - echo " failed..\n"; - $is_upload_ok = false; - continue; - } - } - } - return $is_upload_ok; - } - - /** - * 上传目录 - * @param array $options - * $options = array( - * 'bucket' => (Required) string - * 'object' => (Optional) string - * 'directory' => (Required) string - * 'exclude' => (Optional) string - * 'recursive' => (Optional) string - * 'checkmd5' => (Optional) boolean - * ) - * @return bool - * @throws OSS_Exception - */ - public function batch_upload_file($options = NULL){ - if((NULL == $options) || !isset($options['bucket']) || empty($options['bucket']) || !isset($options['directory']) ||empty($options['directory'])){ - throw new OSS_Exception('Bad Request', 400); - } - - $is_batch_upload_ok = true; - $bucket = $this->get_value($options, 'bucket'); - $directory = $this->get_value($options, 'directory'); - //Windows系统下进行转码 - $directory = OSSUtil::encoding_path($directory); - - //判断是否目录 - if(!is_dir($directory)){ - throw new OSS_Exception($directory . ' is not a directory, please check it'); - } - - $object = $this->get_value($options, 'object', ''); - $exclude = $this->get_value($options, 'exclude', '.|..|.svn', true); - $recursive = $this->get_value($options, 'recursive', false, true, true); - - //read directory - $file_list_array = $this->read_dir($directory, $exclude, $recursive); - - if(!$file_list_array){ - throw new OSS_Exception($directory.' is empty...'); - } - - $index = 1; - $is_check_md5 = $this->is_check_md5($options); - - foreach ($file_list_array as $k=>$item){ - echo $index++.". "; - echo "Upload file ".$item['path']." "; - if (is_dir($item['path'])) { - echo " skipped, because it is directory...\n"; - } - else { - $options = array( - self::OSS_FILE_UPLOAD => $item['path'], - self::OSS_PART_SIZE => self::OSS_MIN_PART_SIZE, - self::OSS_CHECK_MD5 => $is_check_md5, - ); - $real_object = (!empty($object)?$object.'/':'').$item['file']; - $response = $this->create_mpu_object($bucket, $real_object, $options); - if($response->isOK()){ - echo " successful..\n"; - }else{ - echo " failed..\n"; - $is_batch_upload_ok = false; - continue; - } - } - } - return $is_batch_upload_ok; - } - - /*%******************************************************************************************************%*/ - //Object Group相关操作, 不建议再使用,官方API文档中已经无相关介绍 - /** - * 转化object数组为固定个xml格式 - * @param string $bucket (Required) - * @param array $object_array (Required) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-12-27 - * @return string - */ - public function make_object_group_xml($bucket, $object_array){ - $xml = ''; - $xml .= ''; - - if($object_array){ - if(count($object_array) > self::OSS_MAX_OBJECT_GROUP_VALUE){ - throw new OSS_Exception(OSS_OBJECT_GROUP_TOO_MANY_OBJECT, '-401'); - } - $index = 1; - foreach ($object_array as $key => $value){ - $object_meta = (array)$this->get_object_meta($bucket, $value); - if(isset($object_meta) && isset($object_meta['status']) && isset($object_meta['header']) && isset($object_meta['header']['etag']) && $object_meta['status'] == 200){ - $xml .= ''; - $xml .= ''.intval($index).''; - $xml .= ''.$value.''; - $xml .= ''.$object_meta['header']['etag'].''; - $xml .= ''; - - $index++; - } - } - }else{ - throw new OSS_Exception(OSS_OBJECT_ARRAY_IS_EMPTY, '-400'); - } - $xml .= ''; - return $xml; - } - /** - * 创建Object Group, 不建议再使用,官方API文档中已经无相关介绍 - * @param string $object_group (Required) Object Group名称 - * @param string $bucket (Required) Bucket名称 - * @param array $object_arry (Required) object数组,所有的object必须在同一个bucket下 - * 其中$object_arrya 格式如下: - * $object = array( - * $object1, - * $object2, - * ... - * ) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function create_object_group($bucket, $object_group, $object_arry, $options = NULL){ - $this->precheck_common($bucket, $object_group, $options); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_POST; - $options[self::OSS_OBJECT] = $object_group; - $options[self::OSS_CONTENT_TYPE] = $this->get_mime_type($object_group); //重设Content-Type - $options[self::OSS_SUB_RESOURCE] = 'group'; //设置?group - $options[self::OSS_CONTENT] = $this->make_object_group_xml($bucket, $object_arry); //格式化xml - return $this->auth($options ); - } - - /** - * 获取Object Group, 不建议再使用,官方API文档中已经无相关介绍 - * @param string $object_group (Required) - * @param string $bucket (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function get_object_group($bucket, $object_group, $options = NULL){ - $this->precheck_common($bucket, $object_group, $options); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = $object_group; - $options[self::OSS_HEADERS] = array(self::OSS_OBJECT_GROUP => self::OSS_OBJECT_GROUP); //header中的x-oss-file-group不能为空,否则返回值错误 - return $this->auth($options); - } - - /** - * 获取Object Group 的Object List信息, 不建议再使用,官方API文档中已经无相关介绍 - * @param string $object_group (Required) - * @param string $bucket (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function get_object_group_index($bucket, $object_group, $options = NULL){ - $this->precheck_common($bucket, $object_group, $options); - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_METHOD] = self::OSS_HTTP_GET; - $options[self::OSS_OBJECT] = $object_group; - $options[self::OSS_CONTENT_TYPE] = 'application/xml'; //重设Content-Type - $options[self::OSS_HEADERS] = array(self::OSS_OBJECT_GROUP => self::OSS_OBJECT_GROUP); - return $this->auth($options); - } - - /** - * 获得object group的meta信息, 不建议再使用,官方API文档中已经无相关介绍 - * @param string $bucket (Required) - * @param string $object_group (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function get_object_group_meta($bucket, $object_group, $options = NULL){ - return $this->get_object_meta($bucket, $object_group, $options); - } - - /** - * 删除Object Group, 不建议再使用,官方API文档中已经无相关介绍 - * @param string $bucket(Required) - * @param string $object_group (Required) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-11-14 - * @return ResponseCore - */ - public function delete_object_group($bucket, $object_group, $options = NULL){ - return $this->delete_object($bucket, $object_group, $options); - } - - /*%******************************************************************************************************%*/ - //带签名的url相关 - - /** - * 获取GET签名的url - * @param string $bucket (Required) - * @param string $object (Required) - * @param int $timeout (Optional) - * @param array $options (Optional) - * @author xiaobing - * @since 2011-12-21 - * @return string - */ - public function get_sign_url($bucket, $object, $timeout = 60, $options = NULL){ - return $this->presign_url($bucket, $object, $timeout, self::OSS_HTTP_GET, $options); - } - - /** - * 获取签名url,支持生成get和put签名 - * @param string $bucket - * @param string $object - * @param int $timeout - * @param array $options (Optional) Key-Value数组 - * @param string $method - * @return ResponseCore - * @throws OSS_Exception - */ - public function presign_url($bucket, $object, $timeout = 60, $method = self::OSS_HTTP_GET, $options = NULL){ - $this->precheck_common($bucket, $object, $options); - //method - if (self::OSS_HTTP_GET !== $method && self::OSS_HTTP_PUT !== $method) { - throw new OSS_Exception(OSS_INVALID_METHOD); - } - $options[self::OSS_BUCKET] = $bucket; - $options[self::OSS_OBJECT] = $object; - $options[self::OSS_METHOD] = $method; - if (!isset($options[self::OSS_CONTENT_TYPE])) { - $options[self::OSS_CONTENT_TYPE] = ''; - } - $timeout = time() + $timeout; - $options[self::OSS_PREAUTH] = $timeout; - $options[self::OSS_DATE] = $timeout; - $this->set_sign_sts_in_url(true); - return $this->auth($options); - } - - /** - * 检测options参数 - * @param array $options - * @throws OSS_Exception - */ - private function precheck_options(&$options) { - OSSUtil::validate_options($options); - if (!$options) { - $options = array(); - } - } - - /** - * 校验bucket参数 - * @param string $bucket - * @param string $err_msg - * @throws OSS_Exception - */ - private function precheck_bucket($bucket, $err_msg = OSS_BUCKET_IS_NOT_ALLOWED_EMPTY) { - OSSUtil::is_empty($bucket, $err_msg); - } - - /** - * 校验object参数 - * @param string $object - * @throws OSS_Exception - */ - private function precheck_object($object) { - OSSUtil::is_empty($object, OSS_OBJECT_IS_NOT_ALLOWED_EMPTY); - } - - /** - * 校验bucket,options参数 - * @param string $bucket - * @param string $object - * @param array $options - * @param bool $is_check_object - */ - private function precheck_common($bucket, $object, &$options, $is_check_object = true) { - if ($is_check_object){ - $this->precheck_object($object); - } - $this->precheck_options($options); - $this->precheck_bucket($bucket); - } - - /** - * 参数校验 - * @param array $options - * @param string $param - * @param string $func_name - * @throws OSS_Exception - */ - private function precheck_param($options, $param, $func_name){ - if (!isset($options[$param])){ - throw new OSS_Exception('The `' . $param . '` options is required in ' . $func_name . '().'); - } - } - - /** - * 检测md5 - * @param array $options - * @return bool|null - */ - private function is_check_md5($options){ - return $this->get_value($options, self::OSS_CHECK_MD5, false, true, true); - } - - /** - * 获取value - * @param array $options - * @param string $key - * @param string $default - * @param bool $is_check_empty - * @param bool $is_check_bool - * @return bool|null - */ - private function get_value($options, $key, $default = NULL, $is_check_empty = false, $is_check_bool = false) { - $value = $default; - if (isset($options[$key])){ - if ($is_check_empty){ - if (!empty($options[$key])){ - $value= $options[$key]; - } - } - else{ - $value= $options[$key]; - } - unset($options[$key]); - } - if ($is_check_bool){ - if ($value !== true && $value !== false){ - $value = false; - } - } - return $value; - } - - /** - * 获取mimetype类型 - * @param string $object - * @return string - */ - private function get_mime_type($object) { - $extension = explode('.', $object); - $extension = array_pop($extension); - $mime_type = MimeTypes::get_mimetype(strtolower($extension)); - return $mime_type; - } - - /** - * 读取目录 - * @param $dir - * @param string $exclude - * @param bool $recursive - * @return array - */ - private function read_dir($dir, $exclude = ".|..|.svn", $recursive = false){ - $file_list_array = array(); - $base_path=$dir; - $exclude_array = explode("|", $exclude); - // filter out "." and ".." - $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; - echo "$new_file\n"; - $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; - } - - - /*%******************************************************************************************************%*/ - //请求 - - /** - * auth接口 - * @param array $options - * @return ResponseCore - * @throws OSS_Exception - * @throws RequestCore_Exception - */ - public function auth($options){ - OSSUtil::validate_options($options); - - //验证Bucket,list_bucket时不需要验证 - if(!( ('/' == $options[self::OSS_OBJECT]) && ('' == $options[self::OSS_BUCKET]) && ('GET' == $options[self::OSS_METHOD])) && !OSSUtil::validate_bucket($options[self::OSS_BUCKET])){ - throw new OSS_Exception('"'.$options[self::OSS_BUCKET].'"'.OSS_BUCKET_NAME_INVALID); - } - //验证Object - if(isset($options[self::OSS_OBJECT]) && !OSSUtil::validate_object($options[self::OSS_OBJECT])){ - throw new OSS_Exception($options[self::OSS_OBJECT].OSS_OBJECT_NAME_INVALID); - } - //Object编码为UTF-8 - $tmp_object = $options[self::OSS_OBJECT]; - try { - if(OSSUtil::is_gb2312($options[self::OSS_OBJECT])){ - $options[self::OSS_OBJECT] = iconv('GB2312', "UTF-8//IGNORE",$options[self::OSS_OBJECT]); - }elseif(OSSUtil::check_char($options[self::OSS_OBJECT],true)){ - $options[self::OSS_OBJECT] = iconv('GBK', "UTF-8//IGNORE",$options[self::OSS_OBJECT]); - } - } catch (Exception $e) { - try{ - $tmp_object = iconv(mb_detect_encoding($tmp_object), "UTF-8", $tmp_object); - } - catch(Exception $e) { - } - } - $options[self::OSS_OBJECT] = $tmp_object; - - //验证ACL - 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 OSS_Exception($options[self::OSS_HEADERS][self::OSS_ACL].':'.OSS_ACL_INVALID); - } - } - - //定义scheme - $scheme = $this->use_ssl ? 'https://' : 'http://'; - if($this->enable_domain_style){ - $hostname = $this->vhost ? $this->vhost : (($options[self::OSS_BUCKET] == '') ? $this->hostname : ($options[self::OSS_BUCKET].'.').$this->hostname); - }else{ - $hostname = (isset($options[self::OSS_BUCKET]) && '' !== $options[self::OSS_BUCKET]) ? $this->hostname.'/'.$options[self::OSS_BUCKET] : $this->hostname; - } - - //请求参数 - $signable_resource = ''; - $query_string_params = array(); - $signable_query_string_params = array(); - $string_to_sign = ''; - - $oss_host = $this->hostname; - if ($this->enable_domain_style){ - $oss_host = $hostname; - } - $headers = array ( - self::OSS_CONTENT_MD5 => '', - self::OSS_CONTENT_TYPE => isset($options[self::OSS_CONTENT_TYPE]) ? $options[self::OSS_CONTENT_TYPE] : 'application/x-www-form-urlencoded', - self::OSS_DATE => isset($options[self::OSS_DATE]) ? $options[self::OSS_DATE] : gmdate('D, d M Y H:i:s \G\M\T'), - self::OSS_HOST => $oss_host, - ); - - if (isset($options[self::OSS_CONTENT_MD5])){ - $headers[self::OSS_CONTENT_MD5] = $options[self::OSS_CONTENT_MD5]; - } - - //增加stsSecurityToken - if((!is_null($this->security_token)) && (!$this->enable_sts_in_url)){ - $headers[self::OSS_SECURITY_TOKEN] = $this->security_token; - } - - if (isset($options[self::OSS_OBJECT]) && '/' !== $options[self::OSS_OBJECT]){ - $signable_resource = '/'.str_replace(array('%2F', '%25'), array('/', '%'), rawurlencode($options[self::OSS_OBJECT])); - } - - if(isset($options[self::OSS_QUERY_STRING])){ - $query_string_params = array_merge($query_string_params, $options[self::OSS_QUERY_STRING]); - } - $query_string = OSSUtil::to_query_string($query_string_params); - - $signable_list = 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, - ); - - foreach ($signable_list as $item){ - if(isset($options[$item])){ - $signable_query_string_params[$item] = $options[$item]; - } - } - - if ($this->enable_sts_in_url && (!is_null($this->security_token))) { - $signable_query_string_params["security-token"] = $this->security_token; - } - $signable_query_string = OSSUtil::to_query_string($signable_query_string_params); - - //合并 HTTP headers - if (isset($options[self::OSS_HEADERS])) { - $headers = array_merge($headers, $options[self::OSS_HEADERS]); - } - - //生成请求URL - $conjunction = '?'; - - $non_signable_resource = ''; - - if (isset($options[self::OSS_SUB_RESOURCE])){ - $signable_resource .= $conjunction . $options[self::OSS_SUB_RESOURCE]; - $conjunction = '&'; - } - - if($signable_query_string !== ''){ - $signable_query_string = $conjunction . $signable_query_string; - $conjunction = '&'; - } - - if($query_string !== ''){ - $non_signable_resource .= $conjunction . $query_string; - $conjunction = '&'; - } - - $this->request_url = $scheme . $hostname . $signable_resource . $signable_query_string . $non_signable_resource; - - //创建请求 - $request = new RequestCore($this->request_url); - $user_agent = OSS_NAME."/".OSS_VERSION." (".php_uname('s')."/".php_uname('r')."/".php_uname('m').";".PHP_VERSION.")"; - $request->set_useragent($user_agent); - - // 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); - - if ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded'){ - $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; - } - }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($headers[self::OSS_CONTENT_TYPE]) && ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded')){ - $mime_type = self::get_mime_type($options[self::OSS_FILE_UPLOAD]); - $headers[self::OSS_CONTENT_TYPE] = $mime_type; - } - } - } - - 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]); - $string_to_sign .= $options[self::OSS_METHOD] . "\n"; - } - - if (isset($options[self::OSS_CONTENT])) { - $request->set_body($options[self::OSS_CONTENT]); - if ($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)); - } - - uksort($headers, 'strnatcasecmp'); - - foreach($headers as $header_key => $header_value){ - $header_value = str_replace(array ("\r", "\n"), '', $header_value); - if ($header_value !== '') { - $request->add_header($header_key, $header_value); - } - - if ( - strtolower($header_key) === 'content-md5' || - strtolower($header_key) === 'content-type' || - strtolower($header_key) === 'date' || - (isset($options['self::OSS_PREAUTH']) && (integer) $options['self::OSS_PREAUTH'] > 0) - ){ - $string_to_sign .= $header_value . "\n"; - }elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX){ - $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n"; - } - } - - $string_to_sign .= '/' . $options[self::OSS_BUCKET]; - $string_to_sign .= $this->enable_domain_style ? ($options[self::OSS_BUCKET] != '' ? ($options[self::OSS_OBJECT]=='/'?'/':'') :''): ''; - $string_to_sign .= rawurldecode($signable_resource) . urldecode($signable_query_string); - - $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->access_key, true)); - $request->add_header('Authorization', 'OSS ' . $this->access_id . ':' . $signature); - - if (isset($options[self::OSS_PREAUTH]) && (integer) $options[self::OSS_PREAUTH] > 0){ - $signed_url = $this->request_url . $conjunction . self::OSS_URL_ACCESS_KEY_ID.'=' . rawurlencode($this->access_id) . '&'.self::OSS_URL_EXPIRES.'=' . $options[self::OSS_PREAUTH] . '&'.self::OSS_URL_SIGNATURE.'=' . rawurlencode($signature); - return $signed_url; - }elseif (isset($options[self::OSS_PREAUTH])){ - return $this->request_url; - } - - if ($this->debug_mode){ - $request->debug_mode = $this->debug_mode; - } - - $request->send_request(); - - $response_header = $request->get_response_header(); - $response_header['oss-request-url'] = $this->request_url; - $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->max_retries){ - //设置休眠 - $delay = (integer) (pow(4, $this->redirects) * 100000); - usleep($delay); - $this->redirects++; - $data = $this->auth($options); - } - } - - $this->redirects = 0; - return $data; - } - - /*%******************************************************************************************************%*/ - //属性 - - /** - * 设置debug模式 - * @param boolean $debug_mode (Optional) - * @author xiaobing - * @since 2012-05-29 - * @return void - */ - public function set_debug_mode($debug_mode = false){ - $this->debug_mode = $debug_mode; - } - public function get_debug_mode(){ - return $this->debug_mode; - } - - /** - * 设置最大尝试次数 - * @param int $max_retries - * @author xiaobing - * @since 2012-05-29 - * @return void - */ - public function set_max_retries($max_retries = 3){ - $this->max_retries = $max_retries; - } - - /** - * 获取最大尝试次数 - * @author xiaobing - * @since 2012-05-29 - * @return int - */ - public function get_max_retries(){ - return $this->max_retries; - } - - /** - * 设置host地址 - * @author xiaobing - * @param string $hostname host name - * @param int $port int - * @since 2012-06-11 - * @return void - */ - public function set_host_name($hostname, $port = null){ - $this->hostname = $hostname; - - if($port){ - $this->port = $port; - $this->hostname .= ':'.$port; - } - } - - public function get_host(){ - return $this->hostname; - } - - public function get_port(){ - return $this->port; - } - - public function get_id(){ - return $this->access_id; - } - - /** - * 设置vhost地址 - * @author xiaobing - * @param string $vhost vhost - * @since 2012-06-11 - * @return void - */ - public function set_vhost($vhost){ - $this->vhost = $vhost; - } - - public function get_vhost(){ - return $this->vhost; - } - /** - * 设置路径形式,如果为true,则启用三级域名,如bucket.oss.aliyuncs.com - * @author xiaobing - * @param boolean $enable_domain_style - * @since 2012-06-11 - * @return void - */ - public function set_enable_domain_style($enable_domain_style = true){ - $this->enable_domain_style = $enable_domain_style; - } - - public function get_enable_domain_style(){ - return $this->enable_domain_style; - } - - public function set_sign_sts_in_url($enable){ - if ($enable) { - $this->enable_sts_in_url = true; - } else { - $this->enable_sts_in_url = false; - } - } - - /*%******************************************************************************************************%*/ - const DEFAULT_OSS_HOST = 'oss.aliyuncs.com'; - const DEFAULT_OSS_ENDPOINT = 'oss.aliyuncs.com'; - const NAME = OSS_NAME; - const BUILD = OSS_BUILD; - const VERSION = OSS_VERSION; - const AUTHOR = OSS_AUTHOR; - //OSS 内部常量 - const OSS_BUCKET = 'bucket'; - const OSS_OBJECT = 'object'; - const OSS_HEADERS = OSSUtil::OSS_HEADERS; - 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_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_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_PREAUTH = 'preauth'; - 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'; - /*%******************************************************************************************%*/ - //私有URL变量 - const OSS_URL_ACCESS_KEY_ID = 'OSSAccessKeyId'; - const OSS_URL_EXPIRES = 'Expires'; - const OSS_URL_SIGNATURE = 'Signature'; - /*%******************************************************************************************%*/ - //HTTP方法 - 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'; - /*%******************************************************************************************%*/ - //其他常量 - const OSS_ACL = 'x-oss-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"; - //支持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'; - //OSS ACL数组 - static $OSS_ACL_TYPES = array( - self::OSS_ACL_TYPE_PRIVATE, - self::OSS_ACL_TYPE_PUBLIC_READ, - self::OSS_ACL_TYPE_PUBLIC_READ_WRITE - ); - - //CORS 相关 - 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_OPTIONS_ORIGIN = 'Origin'; - const OSS_OPTIONS_REQUEST_METHOD = 'Access-Control-Request-Method'; - const OSS_OPTIONS_REQUEST_HEADERS = 'Access-Control-Request-Headers'; - - - /*%******************************************************************************************%*/ - //是否使用SSL - public $version = OSS_VERSION; - protected $use_ssl = false; - //是否使用debug模式 - private $debug_mode = false; - private $max_retries = 3; - private $redirects = 0; - private $vhost; - //路径表现方式 - private $enable_domain_style = false; - private $request_url; - private $access_id; - private $access_key; - private $hostname; - private $port; - private $security_token; - private $enable_sts_in_url = false; -} diff --git a/AliOssSdk/thirdparty/xml2array.class.php b/AliOssSdk/thirdparty/xml2array.class.php deleted file mode 100644 index 1e9f773..0000000 --- a/AliOssSdk/thirdparty/xml2array.class.php +++ /dev/null @@ -1,139 +0,0 @@ -formatOutput = $format_output; - self::$encoding = $encoding; - } - - /** - * @param $input_xml - * @return mixed - * @throws Exception - */ - public static function &createArray($input_xml) { - $xml = self::getXMLRoot(); - if(is_string($input_xml)) { - $parsed = $xml->loadXML($input_xml); - if(!$parsed) { - throw new Exception('[XML2Array] Error parsing the XML string.'); - } - } else { - if(get_class($input_xml) != 'DOMDocument') { - throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.'); - } - $xml = self::$xml = $input_xml; - } - $array[$xml->documentElement->tagName] = self::convert($xml->documentElement); - self::$xml = null; // clear the xml node in the class for 2nd time use. - return $array; - } - - /** - * Convert an Array to XML - * @param mixed $node - XML as a string or as an object of DOMDocument - * @return mixed - */ - private static function &convert($node) { - $output = array(); - - switch ($node->nodeType) { - case XML_CDATA_SECTION_NODE: - $output['@cdata'] = trim($node->textContent); - break; - - case XML_TEXT_NODE: - $output = trim($node->textContent); - break; - - case XML_ELEMENT_NODE: - - // for each child node, call the covert function recursively - for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) { - $child = $node->childNodes->item($i); - $v = self::convert($child); - if(isset($child->tagName)) { - $t = $child->tagName; - - // assume more nodes of same kind are coming - if(!isset($output[$t])) { - $output[$t] = array(); - } - $output[$t][] = $v; - } else { - //check if it is not an empty text node - if($v !== '') { - $output = $v; - } - } - } - - if(is_array($output)) { - // if only one node of its kind, assign it directly instead if array($value); - foreach ($output as $t => $v) { - if(is_array($v) && count($v)==1) { - $output[$t] = $v[0]; - } - } - if(empty($output)) { - //for empty nodes - $output = ''; - } - } - - // loop through the attributes and collect them - if($node->attributes->length) { - $a = array(); - foreach($node->attributes as $attrName => $attrNode) { - $a[$attrName] = (string) $attrNode->value; - } - // if its an leaf node, store the value in @value instead of directly storing it. - if(!is_array($output)) { - $output = array('@value' => $output); - } - $output['@attributes'] = $a; - } - break; - } - return $output; - } - - /* - * Get the root XML node, if there isn't one, create it. - */ - private static function getXMLRoot(){ - if(empty(self::$xml)) { - self::init(); - } - return self::$xml; - } -} diff --git a/AliOssSdk/util/oss_util.class.php b/AliOssSdk/util/oss_util.class.php deleted file mode 100644 index a6b9d82..0000000 --- a/AliOssSdk/util/oss_util.class.php +++ /dev/null @@ -1,434 +0,0 @@ -IsTruncated; - $object_list = array(); - $marker = $xml->NextMarker; - foreach ( $xml->Contents as $content) { - array_push($object_list, $content->Key); - } - return $object_list; - } - - public static function print_res($response, $msg = "", $is_simple_print = true){ - if ($is_simple_print){ - if ((int)($response->status / 100) == 2){ - echo $msg." OK\n"; - } - else{ - echo "ret:".$response->status."\n"; - echo $msg." FAIL\n"; - } - } - else { - echo '|-----------------------Start---------------------------------------------------------------------------------------------------'."\n"; - echo '|-Status:' . $response->status . "\n"; - echo '|-Body:' ."\n"; - $body = $response->body . "\n"; - echo $body . "\n"; - echo "|-Header:\n"; - print_r ($response->header); - echo '-----------------------End-----------------------------------------------------------------------------------------------------'."\n\n"; - } - } - - /*%******************************************************************************************************%*/ - //工具类相关 - - /** - * 生成query params - * @param array $array 关联数组 - * @return string 返回诸如 key1=value1&key2=value2 - */ - public static function to_query_string($options = array()){ - $temp = array(); - uksort($options, 'strnatcasecmp'); - foreach ($options as $key => $value){ - if (is_string($key) && !is_array($value)){ - $temp[] = rawurlencode($key) . '=' . rawurlencode($value); - } - } - return implode('&', $temp); - } - - /** - * @param $str - * @return string - */ - public static function hex_to_base64($str){ - $result = ''; - for ($i = 0; $i < strlen($str); $i += 2){ - $result .= chr(hexdec(substr($str, $i, 2))); - } - return base64_encode($result); - } - - public static function s_replace($subject){ - $search = array('<', '>', '&', '\'', '"'); - $replace = array('<', '>', '&', ''', '"'); - return str_replace($search, $replace, $subject); - } - - /** - * @param $subject - * @return mixed - */ - public static function replace_invalid_xml_char($subject){ - $search = array( - '', '', '', '', '', '', '', '', ' ', ' ', ' ', ' ', ' ', - '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '' - ); - $replace = array( - '%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08', '%09', '%0A', '%0B', '%0C', '%0D', - '%0E', '%0F', '%10', '%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18', '%19', '%1A', - '%1B', '%1C', '%1D', '%1E', '%1F', '%7F' - ); - - return str_replace($search, $replace, $subject); - } - - /** - * @param $str - * @return int - */ - public static function chk_chinese($str){ - return preg_match('/[\x80-\xff]./', $str); - } - - /** - * 检测是否GB2312编码 - * @param string $str - * @author xiaobing - * @since 2012-03-20 - * @return boolean false UTF-8编码 TRUE GB2312编码 - */ - public static function is_gb2312($str) { - for($i=0; $i 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; //UTF-8编码 - else - return true; //GB编码 - } - } - } - } - - /** - * 检测是否GBK编码 - * @param string $str - * @param boolean $gbk - * @author xiaobing - * @since 2012-06-04 - * @return boolean - */ - public static function check_char($str, $gbk = true){ - for($i=0; $i 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; - } - - - /** - * 检验bucket名称是否合法 - * bucket的命名规范: - * 1. 只能包括小写字母,数字 - * 2. 必须以小写字母或者数字开头 - * 3. 长度必须在3-63字节之间 - * @param string $bucket (Required) - * @author xiaobing - * @since 2011-12-27 - * @return boolean - */ - public static function validate_bucket($bucket){ - $pattern = '/^[a-z0-9][a-z0-9-]{2,62}$/'; - if (!preg_match($pattern, $bucket)) { - return false; - } - return true; - } - - /** - * 检验object名称是否合法 - * object命名规范: - * 1. 规则长度必须在1-1023字节之间 - * 2. 使用UTF-8编码 - * @param string $object (Required) - * @author xiaobing - * @since 2011-12-27 - * @return boolean - */ - public static function validate_object($object){ - $pattern = '/^.{1,1023}$/'; - if (empty($object) || !preg_match($pattern, $object)) { - return false; - } - return true; - } - - /** - * 检验$options - * @param array $options (Optional) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-12-27 - * @return boolean - */ - public static function validate_options($options){ - //$options - if ($options != NULL && !is_array($options)) { - throw new OSS_Exception ($options.':'.OSS_OPTIONS_MUST_BE_ARRAY); - } - } - - /** - * 检测上传文件的内容 - * @param array $options (Optional) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-12-27 - * @return string - */ - public static function validate_content($options){ - if(isset($options[self::OSS_CONTENT])){ - if($options[self::OSS_CONTENT] == '' || !is_string($options[self::OSS_CONTENT])){ - throw new OSS_Exception(OSS_INVALID_HTTP_BODY_CONTENT,'-600'); - } - }else{ - throw new OSS_Exception(OSS_NOT_SET_HTTP_CONTENT, '-601'); - } - } - - /** - * @param $options - * @throws OSS_Exception - */ - public static function validate_content_length($options){ - if(isset($options[self::OSS_LENGTH]) && is_numeric($options[self::OSS_LENGTH])){ - if( !$options[self::OSS_LENGTH] > 0){ - throw new OSS_Exception(OSS_CONTENT_LENGTH_MUST_MORE_THAN_ZERO, '-602'); - } - }else{ - throw new OSS_Exception(OSS_INVALID_CONTENT_LENGTH, '-602'); - } - } - - /** - * 校验BUCKET/OBJECT/OBJECT GROUP是否为空 - * @param string $name (Required) - * @param string $errMsg (Required) - * @throws OSS_Exception - * @author xiaobing - * @since 2011-12-27 - * @return void - */ - public static function is_empty($name,$errMsg){ - if(empty($name)){ - throw new OSS_Exception($errMsg); - } - } - - /** - * 设置http header - * @param string $key (Required) - * @param string $value (Required) - * @param array $options (Required) - * @throws OSS_Exception - * @author xiaobing - * @return void - */ - public static function set_options_header($key, $value, &$options) { - if (isset($options[self::OSS_HEADERS])) { - if (!is_array($options[self::OSS_HEADERS])) { - throw new OSS_Exception(OSS_INVALID_OPTION_HEADERS, '-600'); - } - } else { - $options[self::OSS_HEADERS] = array (); - } - $options[self::OSS_HEADERS][$key] = $value; - } - - /** - * 仅供测试使用的接口,请勿使用 - */ - public static function generate_file($filename, $size) { - if (file_exists($filename) && $size == filesize($filename)) { - echo $filename." already exists, no need to create again. "; - return; - } - $part_size = 1*1024*1024; - $write_size = 0; - $fp = fopen($filename, "w"); - $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $charactersLength = strlen($characters); - if($fp) - { - while ($size > 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); - } - - public static function get_content_md5_of_file($filename, $from_pos, $to_pos) { - $content_md5 = ""; - if (($to_pos - $from_pos) > self::OSS_MAX_PART_SIZE) { - return $content_md5; - } - $filesize = 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; - } - - /** - * 检测是否windows系统,因为windows系统默认编码为GBK - * @return bool - */ - public static function is_win(){ - return strtoupper(substr(PHP_OS,0,3)) == "WIN"; - } - - /** - * 主要是由于windows系统编码是gbk,遇到中文时候,如果不进行转换处理会出现找不到文件的问题 - * @param $file_path - * @return string - */ - public static function encoding_path($file_path){ - if(self::chk_chinese($file_path) && self::is_win()){ - $file_path = iconv('utf-8', 'gbk',$file_path); - } - return $file_path; - } - - /** - * 转换响应 - * @param $response - * @return array - * @throws Exception - */ - public static function parse_response($response, $format="array"){ - //如果启用响应结果转换,则进行转换,否则原样返回 - $body = $response->body; - $headers = $response->header; - - switch (strtolower($format)) { - case 'array': - $body = empty($body) ? $body : XML2Array::createArray($body); - break; - case "json": - $body = empty($body) ? $body : json_encode(XML2Array::createArray($body)); - break; - default: - break; - } - - return array( - 'success' => $response->isOk(), - 'status' => $response->status, - 'header' => $headers, - 'body' => $body - ); - return $response; - } -} diff --git a/Plugin.php b/Plugin.php index d4e42bc..ceadafd 100644 --- a/Plugin.php +++ b/Plugin.php @@ -1,6 +1,9 @@ deleteHandle = array('AliOssForTypecho_Plugin', 'deleteHandle'); Typecho_Plugin::factory('Widget_Upload')->attachmentHandle = array('AliOssForTypecho_Plugin', 'attachmentHandle'); Typecho_Plugin::factory('Widget_Upload')->attachmentDataHandle = array('AliOssForTypecho_Plugin', 'attachmentDataHandle'); - + return _t('启用成功,请进行相应设置!'); + } /** @@ -51,55 +55,76 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface * @return void */ public static function config(Typecho_Widget_Helper_Form $form) - { $des = new Typecho_Widget_Helper_Form_Element_Text('des', NULL, '', _t('插件使用说明;'), - _t('
    -
  1. 插件基于阿里云oss_php_sdk_20150819开发包开发,若以后SDK开发包更新导致插件不可用,请到 我的博客 ^ - ^获取新版本插件,如果我还用typecho还用阿里云就会更新。

  2. -
  3. 阿里云OSS支持自定义域名到OSS获取文件,如果你的站点运行在阿里云ECS或ACE并十分清楚阿里云服务的内网互通规则,配置连接Bucket与获取文件使用不同的链接可以节省流量。如果你不清楚这些,那么就选择Bucket所在节点的外网地址。

  4. -
  5. 运行在云应用引擎上的站点可以使用本插件,插件不会保存文件到服务器,“在服务器保留备份”选项无效。

  6. -
  7. 若开启“在服务器保留备份”功能:
    插件尽在上传到OSS失败或者遇到其他错误时会返回错误信息,成功保存到OSS但是没有成功保存到服务器的情况下,插件不会抛出异常,上传过程会继续进行,但是会在' . __TYPECHO_ROOT_DIR__ . self::log_path . '目录下生成错误日志"error.log",请定期查阅并清理。

  8. -
  9. 未作容错性检测,配置错误会导致上传失败。

  10. -
  11. Typecho原因无法上传大写扩展名文件,本插件不做修补,等待Typecho更新。

  12. -
  13. 如有问题请到 我的博客 留言
  14. -
')); + { + + $upload_dir = $localPath = Typecho_Common::url(defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR, + defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__); + + $des = new Typecho_Widget_Helper_Form_Element_Text('des', NULL, '', _t('插件使用说明'), + '
    +
  1. 插件更新于2018-06-05
  2. +
  3. 插件基于aliyun-oss-php-sdk Release 2.3.0开发, +若以后SDK开发包更新导致插件不可用,请到 我的博客 ^ - ^获取新版本插件, +如果我还用typecho还用阿里云就会更新。
  4. +
  5. 请赋予目录

    '.$upload_dir.'

    '. __TYPECHO_ROOT_DIR__ .'/'. self::log_path . '

    写权限,否则可能导致上传失败。
  6. +
  7. 若开启“在服务器保留备份”功能:
    +成功保存文件到OSS但没有成功保存到服务器的情况下插件不会报错, +这将导致当前文件在服务器上没有备份,但是会在' . __TYPECHO_ROOT_DIR__ .'/'. self::log_path . '目录下生成错误日志"error.log",请定期查阅并清理。
  8. +
  9. 运行在云应用引擎上的站点“在服务器保留备份”选项无效。
  10. +
  11. 旧版本Typecho存在无法上传大写扩展名文件的bug,请更新Typecho程序。
  12. +
  13. 如有问题或建议请到 我的博客 留言
  14. +
'); $form->addInput($des); - $buketName = new Typecho_Widget_Helper_Form_Element_Text('bucketName', NULL, 'yourself bucketName', + $buketName = new Typecho_Widget_Helper_Form_Element_Text('bucketName', NULL, null, _t('Bucket名称'), _t('请填写Buket名称')); $form->addInput($buketName->addRule('required', _t('必须填写Bucket名称'))); - $accessId = new Typecho_Widget_Helper_Form_Element_Text('accessId', NULL, 'yourself AccessId', - _t('ACCESS_ID'), _t('请填写ACCESS_ID')); - $form->addInput($accessId->addRule('required', _t('必须填写ACCESS_ID'))); + $accessKeyId = new Typecho_Widget_Helper_Form_Element_Text('accessKeyId', NULL, null, + _t('ACCESS KEY ID'), _t('请填写ACCESS KEY ID')); + $form->addInput($accessKeyId->addRule('required', _t('必须填写ACCESS KEY ID'))); - $accessKey = new Typecho_Widget_Helper_Form_Element_Text('accessKey', NULL, 'yourself AccessKey', - _t('ACCESS_KEY'), _t('请填写请填写ACCESS_KEY')); - $form->addInput($accessKey->addRule('required', _t('必须填写ACCESS_KEY'))); + $accessKeySecret = new Typecho_Widget_Helper_Form_Element_Text('accessKeySecret', NULL, null, + _t('ACCESS KEY SECRET'), _t('请填写请填写ACCESS KEY SECRET')); + $form->addInput($accessKeySecret->addRule('required', _t('必须填写ACCESS_KEY'))); $endPoint = new Typecho_Widget_Helper_Form_Element_Select('endPoint', array( - "oss-cn-qingdao.aliyuncs.com" => '青岛节点外网地址: oss-cn-qingdao.aliyuncs.com', - "oss-cn-qingdao-internal.aliyuncs.com" => '青岛节点内网地址: oss-cn-qingdao-internal.aliyuncs.com', - "oss-cn-beijing.aliyuncs.com" => '北京节点外网地址: oss-cn-beijing.aliyuncs.com', - "oss-cn-beijing-internal.aliyuncs.com" => '北京节点内网地址: oss-cn-beijing-internal.aliyuncs.com', - "oss-cn-hangzhou.aliyuncs.com" => '杭州节点外网地址: oss-cn-hangzhou.aliyuncs.com', - "oss-cn-hangzhou-internal.aliyuncs.com" => '杭州节点内网地址: oss-cn-hangzhou-internal.aliyuncs.com', - "oss-cn-hongkong.aliyuncs.com" => '香港节点外网地址: oss-cn-hongkong.aliyuncs.com', - "oss-cn-hongkong-internal.aliyuncs.com" => '香港节点内网地址: oss-cn-hongkong-internal.aliyuncs.com', - "oss-cn-shenzhen.aliyuncs.com" => '深圳节点外网地址: oss-cn-shenzhen.aliyuncs.com', - "oss-cn-shenzhen-internal.aliyuncs.com" => '深圳节点内网地址: oss-cn-shenzhen-internal.aliyuncs.com', - "oss-cn-shanghai.aliyuncs.com" => '上海节点外网地址: oss-cn-shanghai.aliyuncs.com', - "oss-cn-shanghai-internal.aliyuncs.com" => '上海节点内网地址: oss-cn-shanghai-internal.aliyuncs.com', - "oss-us-west-1.aliyuncs.com" => '美国硅谷节点外网地址: oss-us-west-1.aliyuncs.com', - "oss-us-west-1-internal.aliyuncs.com" => '美国硅谷节点内网地址: oss-us-west-1-internal.aliyuncs.com', - "oss-ap-southeast-1.aliyuncs.com" => '亚太(新加坡)节点外网地址: oss-ap-southeast-1.aliyuncs.com', - "oss-ap-southeast-1-internal.aliyuncs.com" => '亚太(新加坡)节点内网地址: oss-ap-southeast-1-internal.aliyuncs.com', - "other" => '其他' - ), - 'oss-cn-qingdao.aliyuncs.com', _t('连接Bucket结点所用地址'), _t('参见使用说明第二条')); + "oss-cn-hangzhou" => '华东 1 oss-cn-hangzhou', + "oss-cn-shanghai" => '华东 2 oss-cn-shanghai', + "oss-cn-qingdao" => '华北 1 oss-cn-qingdao', + "oss-cn-beijing" => '华北 2 oss-cn-beijing', + "oss-cn-zhangjiakou" => '华北 3 oss-cn-zhangjiakou', + "oss-cn-huhehaote" => '华北 5 oss-cn-huhehaote', + "oss-cn-shenzhen" => '华南 1 oss-cn-shenzhen', + "oss-cn-hongkong" => '香港 oss-cn-hongkong', + "oss-us-west-1" => '美国西部 1(硅谷)oss-us-west-1', + "oss-us-east-1" => '美国东部 1(弗吉尼亚)oss-us-east-1', + "oss-ap-southeast-1" => '亚太东南 1(新加坡)oss-ap-southeast-1', + "oss-ap-southeast-2" => '亚太东南 2(悉尼)oss-ap-southeast-2', + "oss-ap-southeast-3" => '亚太东南 3(吉隆坡) oss-ap-southeast-3', + "oss-ap-southeast-5" => '亚太东南 5 (雅加达) oss-ap-southeast-5', + "oss-ap-northeast-1" => '亚太东北 1(日本)oss-ap-northeast-1', + "oss-ap-south-1" => '亚太南部 1(孟买)oss-ap-south-1', + "oss-eu-central-1" => '欧洲中部 1(法兰克福)oss-eu-central-1', + "oss-me-east-1" => '中东东部 1(迪拜)oss-me-east-1', + "other" => '自定义' + ), + 'oss-cn-qingdao', + _t('区域选择,金融云需自定义'), ''); $form->addInput($endPoint); + + $endPointType = new Typecho_Widget_Helper_Form_Element_Select('endPointType', + array( + ".aliyuncs.com" => '外网', + "-internal.aliyuncs.com" => '内网', + ), + '.aliyuncs.com', '', + '在你了解两种连接方式的不同作用的情况下修改此选项'); + $form->addInput($endPointType); - $otherEndPoint = new Typecho_Widget_Helper_Form_Element_Text('otherEndPoint', NULL, '填写其他节点', - '', _t('不包含http://,结尾不包含"/"')); + $otherEndPoint = new Typecho_Widget_Helper_Form_Element_Text('otherEndPoint', NULL, '自定义EndPoint,例如"oss-cn-qingdao.aliyuncs.com"', + '', '填写全部Endpoint,通常以\'.aliyuncs.com\'或\'-internal.aliyuncs.com\'结尾,开头不包含http://,结尾不包含"/"'); $form->addInput($otherEndPoint); $userDir = new Typecho_Widget_Helper_Form_Element_Text('userDir', NULL, 'typecho/', @@ -107,7 +132,7 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface $form->addInput($userDir); $cdnUrl = new Typecho_Widget_Helper_Form_Element_Text('cdnUrl', NULL, '', - _t('自定义域名'), _t('请填写自定义域名,留空则访问OSS源,不包含http://,结尾不包含"/"')); + _t('自定义(CDN)域名'), '请填写自定义域名,留空则使用外网Endpoint访问,以http://或https://开头,以"/"结尾'); $form->addInput($cdnUrl); $ifLoaclSave = new Typecho_Widget_Helper_Form_Element_Radio('ifLoaclSave', array( "1" => '保留', "0" => '不保留' ), "1", @@ -115,26 +140,41 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface $form->addInput($ifLoaclSave); echo ''; } @@ -156,107 +196,76 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface */ public static function uploadHandle($file) { - if (empty($file['name'])) - { + if (empty($file['name'])) { return FALSE; } - - $ext = self::getSafeName($file['name']); - if (!self::checkFileType($ext)) - { + $options = Typecho_Widget::widget('Widget_Options'); + $userDir = $options->plugin('AliOssForTypecho')->userDir; + $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; + $end_point = 'http://' . (($options->plugin('AliOssForTypecho')->endPoint === "other") ? + $options->plugin('AliOssForTypecho')->otherEndPoint : + $options->plugin('AliOssForTypecho')->endPoint . $options->plugin('AliOssForTypecho')->endPointType); + $access_id = $options->plugin('AliOssForTypecho')->accessKeyId; + $access_key = $options->plugin('AliOssForTypecho')->accessKeySecret; + + $ext = self::getExtentionName($file['name']); + + if (!self::checkFileType($ext)) { return FALSE; } date_default_timezone_set('PRC'); - $testDate = date('Y/m/d/'); - $options = Typecho_Widget::widget('Widget_Options'); - $path = $testDate; - //error_log(date('h:m:sa'), 3, self::log_path . 'error.log'); - - //获取文件名 - $fileName = substr(time(), 5) . sprintf('%u', crc32(uniqid())) . '.' . $ext; - - $userDir = $options->plugin('AliOssForTypecho')->userDir; - $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; - $end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ? - $options->plugin('AliOssForTypecho')->otherEndPoint : - $options->plugin('AliOssForTypecho')->endPoint; - $access_id = $options->plugin('AliOssForTypecho')->accessId; - $access_key = $options->plugin('AliOssForTypecho')->accessKey; - - $localFile = $path . $fileName; - $object_name = $userDir . $localFile; - - if (isset($file['tmp_name'])) - { + + $file_origin_name = self::getSafeName($file['name']); + $file_id = substr(time(), 5) . sprintf('%u', crc32(uniqid())); + + $relative_path = date('Y/m/d/') . $file_id . '/' . $file_origin_name; + $object_name = $userDir . $relative_path; + + if (isset($file['tmp_name'])) { $content = file_get_contents($file['tmp_name']); - } else if (isset($file['bytes'])) - { + } else if (isset($file['bytes'])) { $content = $file['bytes']; - } else - { + } else { return FALSE; } - - $fileSize = strlen($content); - $ali_options = array( - 'content' => $content, - 'length' => $fileSize, - ALIOSS::OSS_HEADERS => array( - 'Content-Encoding' => 'utf-8', - 'Content-Language' => 'zh-CN', - ), - ); - - $client = new ALIOSS($access_id, $access_key, $end_point); - $client->set_enable_domain_style(TRUE); + try { + $client = new OssClient($access_id, $access_key, $end_point); + } catch (Exception $e) { + throw new Exception( $e->getMessage()); + } - $ali_response = $client->upload_file_by_content($bucket_name, $object_name, $ali_options); - - if (200 != $ali_response->status) - { + $ali_response = $client->putObject($bucket_name, $object_name, $content); + + if (200 != $ali_response['info']['http_code']) { return FALSE; - } else - { - $object_url = $ali_response->header["_info"]["url"]; + } else { + $object_url = $ali_response['info']["url"]; $ifLoaclSave = $options->plugin('AliOssForTypecho')->ifLoaclSave; - if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine()) - { + if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine()) { $localPath = Typecho_Common::url(defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR, defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__) - . '/' . $path; + . date('Y/m/d/') . $file_id . '/'; $mkdirSuccess = TRUE; - //创建上传目录 - if (!is_dir($localPath)) - { - if (!self::makeUploadDir($localPath)) - { + if (!is_dir($localPath)) { + if (!self::makeUploadDir($localPath)) { $mkdirSuccess = FALSE; } } - - $saveOnServerSuccess = FALSE; - - //保存文件到服务器 $error_log_path = self::log_path; - if ($mkdirSuccess) - { - if (file_put_contents($localPath.$fileName, $content)) - { - $saveOnServerSuccess = TRUE; - } else - { + if ($mkdirSuccess) { + if (file_put_contents($localPath.$file_origin_name, $content)) { + } else { $error = '错误:保存文件失败' . "\r\n" . '远程文件:' . $object_url . "\r\n" . '时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n"; error_log($error, 3, $error_log_path . "error.log"); } - } else - { + } else { $error = '错误:创建目录失败' . "\r\n" . '创建路径:' . $localPath . "\r\n" . '远程文件:' . $object_url . "\r\n" . @@ -264,17 +273,15 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface error_log($error, 3, $error_log_path . "error.log"); } } + + return array( + 'name' => $file_origin_name, + 'path' => $relative_path, + 'size' => intval($ali_response['oss-requestheaders']['Content-Length']), + 'type' => $ext, + 'mime' => $ali_response['oss-requestheaders']['Content-Type'] + ); } - - $name = $file['name']; - //返回相对存储路径 - return array( - 'name' => $name, - 'path' => $localFile, - 'size' => $fileSize, - 'type' => $ext, - 'mime' => Typecho_Common::mimeContentType($localPath . $fileName) - ); } /** @@ -287,15 +294,29 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface */ public static function modifyHandle($content, $file) { + if (empty($file['name'])) { return false; } - $ext = self::getSafeName($file['name']); + $options = Typecho_Widget::widget('Widget_Options'); + $userDir = $options->plugin('AliOssForTypecho')->userDir; + $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; + $end_point = 'http://' . (($options->plugin('AliOssForTypecho')->endPoint === "other") ? + $options->plugin('AliOssForTypecho')->otherEndPoint : + $options->plugin('AliOssForTypecho')->endPoint . $options->plugin('AliOssForTypecho')->endPointType); + $access_id = $options->plugin('AliOssForTypecho')->accessKeyId; + $access_key = $options->plugin('AliOssForTypecho')->accessKeySecret; + + $ext = self::getExtentionName($file['name']); if ($content['attachment']->type != $ext) { return false; } + + $path = $content['attachment']->path; + + $object_name = $userDir . $path; if (isset($file['tmp_name'])) { $newContent = file_get_contents($file['tmp_name']); @@ -305,70 +326,39 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface return false; } - $options = Typecho_Widget::widget('Widget_Options'); - $date = new Typecho_Date($options->gmtTime); - - $path = $content['attachment']->path; - - $userDir = $options->plugin('AliOssForTypecho')->userDir; - $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; - $end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ? - $options->plugin('AliOssForTypecho')->otherEndPoint : - $options->plugin('AliOssForTypecho')->endPoint; - $access_id = $options->plugin('AliOssForTypecho')->accessId; - $access_key = $options->plugin('AliOssForTypecho')->accessKey; - - $object_name = $userDir . $path; - - $fileSize = strlen($newContent); - $ali_options = array( - 'content' => $newContent, - 'length' => $fileSize, - ALIOSS::OSS_HEADERS => array( - 'Content-Encoding' => 'utf-8', - 'Content-Language' => 'zh-CN', - ), - ); - - $client = new ALIOSS($access_id, $access_key, $end_point); - $client->set_enable_domain_style(TRUE); + try { + $client = new OssClient($access_id, $access_key, $end_point); + } catch (Exception $e) { + throw new Exception( $e->getMessage()); + } - $ali_response = $client->upload_file_by_content($bucket_name, $object_name, $ali_options); + $ali_response = $client->putObject($bucket_name, $object_name, $newContent); - if (200 != $ali_response->status) - { + if (200 != $ali_response['info']['http_code']) { return FALSE; - } else - { - $object_url = $ali_response->header["_info"]["url"]; + } else { + $object_url = $ali_response["info"]["url"]; $ifLoaclSave = $options->plugin('AliOssForTypecho')->ifLoaclSave; - if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine()) + if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine()) { $localFile = Typecho_Common::url(self::UPLOAD_DIR . $path, defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__); $localPath = dirname($localFile); $mkdirSuccess = TRUE; - //创建上传目录 - if (!is_dir($localPath)) - { - if (!self::makeUploadDir($localPath)) - { + if (!is_dir($localPath)) { + if (!self::makeUploadDir($localPath)) { $mkdirSuccess = FALSE; } } - $saveOnServerSuccess = FALSE; - - //保存文件到服务器 $error_log_path = self::log_path; - if ($mkdirSuccess) + if ($mkdirSuccess) { - $deleteLacalFileSuccess = unlink($localFile); - if (!$deleteLacalFileSuccess) + if (!$deleteLacalFileSuccess) { $error_log_path = self::log_path; if (!is_dir($error_log_path)) @@ -381,9 +371,7 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface '时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n"; error_log($error, 3, $error_log_path . "error.log"); } else { - if (file_put_contents($localFile, $newContent)) - { - $saveOnServerSuccess = TRUE; + if (file_put_contents($localFile, $newContent)) { } else { $error = '错误:保存文件失败' . "\r\n" . @@ -402,14 +390,13 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface } } } - - //返回相对存储路径 + return array( 'name' => $content['attachment']->name, 'path' => $path, - 'size' => $fileSize, - 'type' => $content['attachment']->type, - 'mime' => $content['attachment']->mime + 'size' => intval($ali_response['oss-requestheaders']['Content-Length']), + 'type' => $ext, + 'mime' => $ali_response['oss-requestheaders']['Content-Type'] ); } @@ -423,25 +410,26 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface public static function deleteHandle(array $content) { $options = Typecho_Widget::widget('Widget_Options'); - $userDir = $options->plugin('AliOssForTypecho')->userDir; - $access_id = $options->plugin('AliOssForTypecho')->accessId; - $access_key = $options->plugin('AliOssForTypecho')->accessKey; $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; - $end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ? - $options->plugin('AliOssForTypecho')->otherEndPoint : - $options->plugin('AliOssForTypecho')->endPoint; - $ali_options = null; - - $client = new ALIOSS($access_id, $access_key, $end_point); + $end_point = 'http://' . (($options->plugin('AliOssForTypecho')->endPoint === "other") ? + $options->plugin('AliOssForTypecho')->otherEndPoint : + $options->plugin('AliOssForTypecho')->endPoint . $options->plugin('AliOssForTypecho')->endPointType); + $access_id = $options->plugin('AliOssForTypecho')->accessKeyId; + $access_key = $options->plugin('AliOssForTypecho')->accessKeySecret; + + try { + $client = new OssClient($access_id, $access_key, $end_point); + } catch (Exception $e) { + throw new Exception( $e->getMessage()); + } $path = $content['attachment']->path; $object_name = $userDir . $path; - $ali_response = $client->delete_object($bucket_name, $object_name, $ali_options); + $ali_response = $client->deleteObject($bucket_name, $object_name); $ifLoaclSave = $options->plugin('AliOssForTypecho')->ifLoaclSave; - if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine()) - { + if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine()) { $localPath = Typecho_Common::url(defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR, defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__) . $path; @@ -461,7 +449,7 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface error_log($error, 3, $error_log_path . "error.log"); } } - return ($ali_response->status == 200); + return ($ali_response['info']['http_code'] === 204); } /** @@ -471,22 +459,19 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface * @param array $content 文件相关信息 * @return string */ - public static function attachmentHandle(array $content) - { + public static function attachmentHandle(array $content) { $options = Typecho_Widget::widget('Widget_Options'); $cdnUrl = $options->plugin('AliOssForTypecho')->cdnUrl; $userDir = $options->plugin('AliOssForTypecho')->userDir; - if ($cdnUrl == '') - { + if ($cdnUrl == '') { $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; $end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ? $options->plugin('AliOssForTypecho')->otherEndPoint : $options->plugin('AliOssForTypecho')->endPoint; - return 'http://' . $bucket_name . '.' . $end_point . '/' . $userDir . $content['attachment']->path; - } else - { - return 'http://' . $cdnUrl . '/' . $userDir . $content['attachment']->path; + return 'https://' . $bucket_name . '.' . $end_point . '.aliyuncs.com/' . $userDir . $content['attachment']->path; + } else { + return $cdnUrl . $userDir . $content['attachment']->path; } } @@ -499,23 +484,7 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface */ public static function attachmentDataHandle(array $content) { - $options = Typecho_Widget::widget('Widget_Options'); - - $cdnUrl = $options->plugin('AliOssForTypecho')->cdnUrl; - $userDir = $options->plugin('AliOssForTypecho')->userDir; - if ($cdnUrl == '') - { - $bucket_name = $options->plugin('AliOssForTypecho')->bucketName; - $end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ? - $options->plugin('AliOssForTypecho')->otherEndPoint : - $options->plugin('AliOssForTypecho')->endPoint; - $filePath = 'http://' . $bucket_name . '.' . $end_point . $userDir . $content['attachment']->path; - } else - { - $filePath = 'http://' . $cdnUrl . $userDir . $content['attachment']->path; - } - - return file_get_contents($filePath); + return file_get_contents(self::attachmentHandle($content)); } /** @@ -582,8 +551,12 @@ class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface $name = false === strpos($name, '/') ? ('a' . $name) : str_replace('/', '/a', $name); $info = pathinfo($name); $name = substr($info['basename'], 1); - - //return isset($info['extension']) ? $info['extension'] : ''; + return $name; + } + + private static function getExtentionName(&$name) + { + $info = pathinfo($name); return isset($info['extension']) ? strtolower($info['extension']) : ''; } } diff --git a/aliyun-oss-php-sdk-2.3.0/CHANGELOG.md b/aliyun-oss-php-sdk-2.3.0/CHANGELOG.md new file mode 100755 index 0000000..042a72a --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/CHANGELOG.md @@ -0,0 +1,92 @@ +# ChangeLog - Aliyun OSS SDK for PHP + +## v2.3.0 / 2018-01-05 + +* 修复:putObject支持创建空文件 +* 修复:createBucket支持IA/Archive +* 增加:支持restoreObject +* 增加:支持Symlink功能 +* 增加:支持getBucketLocation +* 增加:支持getBucketMeta +* 增加:支持代理服务器Proxy + +## v2.2.4 / 2017-04-25 + +* fix getObject to local file bug + +## v2.2.3 / 2017-04-14 + +* fix md5 check + +## v2.2.2 / 2017-01-18 + +* 解决在php7上运行连接数和内存bug + +## v2.2.1 / 2016-12-01 + +* 禁止http curl自动填充Accept-Encoding + +## v2.2.0 / 2016-11-22 + +* 修复PutObject/CompleteMultipartUpload的返回值问题(#26) + +## v2.1.0 / 2016-11-12 + +* 增加[RTMP](https://help.aliyun.com/document_detail/44297.html)接口 +* 增加支持[图片服务](https://help.aliyun.com/document_detail/44686.html) + +## v2.0.7 / 2016-06-17 + +* Support append object + +## v2.0.6 + +* Trim access key id/secret and endpoint +* Refine tests and setup travis CI + +## v2.0.5 + +* 增加Add/Delete/Get BucketCname接口 + +## v2.0.4 + +* 增加Put/Get Object Acl接口 + +## v2.0.3 + +* 修复Util中的常量定义在低于5.6的PHP版本中报错的问题 + +## v2.0.2 + +* 修复multipart上传时无法指定Content-Type的问题 + +## v2.0.1 + +* 增加对ListObjects/ListMultipartUploads时特殊字符的处理 +* 提供接口获取OssException中的详细信息 + + +## 2015.11.25 + +* **大版本升级,不再兼容以前接口,新版本对易用性做了很大的改进,建议用户迁移到新版本。** + +## 修改内容 + +* 不再支持PHP 5.2版本 + +### 新增内容 + +* 引入命名空间 +* 接口命名修正,采用驼峰式命名 +* 接口入参修改,把常用参数从Options参数中提出来 +* 接口返回结果修改,对返回结果进行处理,用户可以直接得到容易处理的数据结构  +* OssClient的构造函数变更 +* 支持CNAME和IP格式的Endpoint地址 +* 重新整理sample文件组织结构,使用function组织功能点 +* 增加设置连接超时,请求超时的接口 +* 去掉Object Group相关的已经过时的接口 +* OssException中的message改为英文 + +### 问题修复 + +* object名称校验不完备 diff --git a/aliyun-oss-php-sdk-2.3.0/LICENSE.md b/aliyun-oss-php-sdk-2.3.0/LICENSE.md new file mode 100755 index 0000000..3183de8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/LICENSE.md @@ -0,0 +1,21 @@ +#The MIT License (MIT) + +Copyright (c) ali-sdk and other contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/README-CN.md b/aliyun-oss-php-sdk-2.3.0/README-CN.md new file mode 100755 index 0000000..8c0cf84 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/README-CN.md @@ -0,0 +1,149 @@ +# Aliyun OSS SDK for PHP + +[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php) +[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk) +[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master) + +## [README of English](https://github.com/aliyun/aliyun-oss-php-sdk/blob/master/README.md) + +## 概述 + +阿里云对象存储(Object Storage Service,简称OSS),是阿里云对外提供的海量、安全、低成本、高可靠的云存储服务。用户可以通过调用API,在任何应用、任何时间、任何地点上传和下载数据,也可以通过用户Web控制台对数据进行简单的管理。OSS适合存放任意文件类型,适合各种网站、开发企业及开发者使用。 + + +## 运行环境 +- PHP 5.3+ +- cURL extension + +提示: + +- Ubuntu下可以使用apt-get包管理器安装php的cURL扩展 `sudo apt-get install php5-curl` + +## 安装方法 + +1. 如果您通过composer管理您的项目依赖,可以在你的项目根目录运行: + + $ composer require aliyuncs/oss-sdk-php + + 或者在你的`composer.json`中声明对Aliyun OSS SDK for PHP的依赖: + + "require": { + "aliyuncs/oss-sdk-php": "~2.0" + } + + 然后通过`composer install`安装依赖。composer安装完成后,在您的PHP代码中引入依赖即可: + + require_once __DIR__ . '/vendor/autoload.php'; + +2. 您也可以直接下载已经打包好的[phar文件][releases-page],然后在你 + 的代码中引入这个文件即可: + + require_once '/path/to/oss-sdk-php.phar'; + +3. 下载SDK源码,在您的代码中引入SDK目录下的`autoload.php`文件: + + require_once '/path/to/oss-sdk/autoload.php'; + +## 快速使用 + +### 常用类 + +| 类名 | 解释 | +|:------------------|:------------------------------------| +|OSS\OssClient | OSS客户端类,用户通过OssClient的实例调用接口 | +|OSS\Core\OssException | OSS异常类,用户在使用的过程中,只需要注意这个异常| + +### OssClient初始化 + +SDK的OSS操作通过OssClient类完成的,下面代码创建一个OssClient对象: + +```php +"; ; +$accessKeySecret = "<您从OSS获得的AccessKeySecret>"; +$endpoint = "<您选定的OSS数据中心访问域名,例如oss-cn-hangzhou.aliyuncs.com>"; +try { + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); +} catch (OssException $e) { + print $e->getMessage(); +} +``` + +### 文件操作 + +文件(又称对象,Object)是OSS中最基本的数据单元,您可以把它简单地理解为文件,用下面代码可以实现一个Object的上传: + +```php +"; +$object = "<您使用的Object名字,注意命名规范>"; +$content = "Hello, OSS!"; // 上传的文件内容 +try { + $ossClient->putObject($bucket, $object, $content); +} catch (OssException $e) { + print $e->getMessage(); +} +``` + +### 存储空间操作 + +存储空间(又称Bucket)是一个用户用来管理所存储Object的存储空间,对于用户来说是一个管理Object的单元,所有的Object都必须隶属于某个Bucket。您可以按照下面的代码新建一个Bucket: + +```php +"; +try { + $ossClient->createBucket($bucket); +} catch (OssException $e) { + print $e->getMessage(); +} +``` + +### 返回结果处理 + +OssClient提供的接口返回返回数据分为两种: + +* Put,Delete类接口,接口返回null,如果没有OssException,即可认为操作成功 +* Get,List类接口,接口返回对应的数据,如果没有OssException,即可认为操作成功,举个例子: + +```php +listBuckets(); +$bucketList = $bucketListInfo->getBucketList(); +foreach($bucketList as $bucket) { + print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n"); +} +``` +上面代码中的$bucketListInfo的数据类型是 `OSS\Model\BucketListInfo` + + +### 运行Sample程序 + +1. 修改 `samples/Config.php`, 补充配置信息 +2. 执行 `cd samples/ && php RunAll.php` + +### 运行单元测试 + +1. 执行`composer install`下载依赖的库 +2. 设置环境变量 + + export OSS_ACCESS_KEY_ID=access-key-id + export OSS_ACCESS_KEY_SECRET=access-key-secret + export OSS_ENDPOINT=endpoint + export OSS_BUCKET=bucket-name + +3. 执行 `php vendor/bin/phpunit` + +## License + +- MIT + +## 联系我们 + +- [阿里云OSS官方网站](http://oss.aliyun.com) +- [阿里云OSS官方论坛](http://bbs.aliyun.com) +- [阿里云OSS官方文档中心](http://www.aliyun.com/product/oss#Docs) +- 阿里云官方技术支持:[提交工单](https://workorder.console.aliyun.com/#/ticket/createIndex) + +[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases +[phar-composer]: https://github.com/clue/phar-composer diff --git a/aliyun-oss-php-sdk-2.3.0/README.md b/aliyun-oss-php-sdk-2.3.0/README.md new file mode 100755 index 0000000..3c1da26 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/README.md @@ -0,0 +1,150 @@ +# Alibaba Cloud OSS SDK for PHP + +[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php) +[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk) +[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master) + +## [README of Chinese](https://github.com/aliyun/aliyun-oss-php-sdk/blob/master/README-CN.md) + +## Overview + +Alibaba Cloud Object Storage Service (OSS) is a cloud storage service provided by Alibaba Cloud, featuring a massive capacity, security, a low cost, and high reliability. You can upload and download data on any application anytime and anywhere by calling APIs, and perform simple management of data through the web console. The OSS can store any type of files and therefore applies to various websites, development enterprises and developers. + + +## Run environment +- PHP 5.3+. +- cURL extension. + +Tips: + +- In Ubuntu, you can use the ***apt-get*** package manager to install the *PHP cURL extension*: `sudo apt-get install php5-curl`. + +## Install OSS PHP SDK + +- If you use the ***composer*** to manage project dependencies, run the following command in your project's root directory: + + composer require aliyuncs/oss-sdk-php + + You can also declare the dependency on Alibaba Cloud OSS SDK for PHP in the `composer.json` file. + + "require": { + "aliyuncs/oss-sdk-php": "~2.0" + } + + Then run `composer install` to install the dependency. After the Composer Dependency Manager is installed, import the dependency in your PHP code: + + require_once __DIR__ . '/vendor/autoload.php'; + +- You can also directly download the packaged [PHAR File][releases-page], and + introduce the file to your code: + + require_once '/path/to/oss-sdk-php.phar'; + +- Download the SDK source code, and introduce the `autoload.php` file under the SDK directory to your code: + + require_once '/path/to/oss-sdk/autoload.php'; + +## Quick use + +### Common classes + +| Class | Explanation | +|:------------------|:------------------------------------| +|OSS\OSSClient | OSS client class. An OSSClient instance can be used to call the interface. | +|OSS\Core\OSSException |OSS Exception class . You only need to pay attention to this exception when you use the OSSClient. | + +### Initialize an OSSClient + +The SDK's operations for the OSS are performed through the OSSClient class. The code below creates an OSSClient object: + +```php +"; +$accessKeySecret = ""; +$endpoint = ""; +try { + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); +} catch (OssException $e) { + print $e->getMessage(); +} +``` + +### Operations on objects + +Objects are the most basic data units on the OSS. You can simply consider objects as files. The following code uploads an object: + +```php +"; +$object = ""; +$content = "Hello, OSS!"; // Content of the uploaded file +try { + $ossClient->putObject($bucket, $object, $content); +} catch (OssException $e) { + print $e->getMessage(); +} +``` + +### Operations on buckets + +Buckets are the space that you use to manage the stored objects. It is an object management unit for users. Each object must belong to a bucket. You can create a bucket with the following code: + +```php +"; +try { + $ossClient->createBucket($bucket); +} catch (OssException $e) { + print $e->getMessage(); +} +``` + +### Handle returned results + +The OSSClient provides the following two types of returned data from interfaces: + +- Put and Delete interfaces: The *PUT* and *DELETE* operations are deemed successful if *null* is returned by the interfaces without *OSSException*. +- Get and List interfaces: The *GET* and *LIST* operations are deemed successful if the desired data is returned by the interfaces without *OSSException*. For example, + + ```php + listBuckets(); + $bucketList = $bucketListInfo->getBucketList(); + foreach($bucketList as $bucket) { + print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n"); + } + ``` +In the above code, $bucketListInfo falls into the 'OSS\Model\BucketListInfo' data type. + + +### Run a sample project + +- Modify `samples/Config.php` to complete the configuration information. +- Run `cd samples/ && php RunAll.php`. + +### Run a unit test + +- Run `composer install` to download the dependent libraries. +- Set the environment variable. + + export OSS_ACCESS_KEY_ID=access-key-id + export OSS_ACCESS_KEY_SECRET=access-key-secret + export OSS_ENDPOINT=endpoint + export OSS_BUCKET=bucket-name + +- Run `php vendor/bin/phpunit` + +## License + +- MIT + +## Contact us + +- [Alibaba Cloud OSS official website](http://oss.aliyun.com). +- [Alibaba Cloud OSS official forum](http://bbs.aliyun.com). +- [Alibaba Cloud OSS official documentation center](http://www.aliyun.com/product/oss#Docs). +- Alibaba Cloud official technical support: [Submit a ticket](https://workorder.console.aliyun.com/#/ticket/createIndex). + +[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases +[phar-composer]: https://github.com/clue/phar-composer + diff --git a/aliyun-oss-php-sdk-2.3.0/autoload.php b/aliyun-oss-php-sdk-2.3.0/autoload.php new file mode 100755 index 0000000..e9a16bf --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/autoload.php @@ -0,0 +1,12 @@ +=5.3" + }, + "require-dev" : { + "phpunit/phpunit": "~4.0", + "satooshi/php-coveralls": "~1.0" + }, + "minimum-stability": "stable", + "autoload": { + "psr-4": {"OSS\\": "src/OSS"} + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/example.jpg b/aliyun-oss-php-sdk-2.3.0/example.jpg new file mode 100755 index 0000000..ffd46a2 Binary files /dev/null and b/aliyun-oss-php-sdk-2.3.0/example.jpg differ diff --git a/aliyun-oss-php-sdk-2.3.0/index.php b/aliyun-oss-php-sdk-2.3.0/index.php new file mode 100755 index 0000000..cdc28bc --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/index.php @@ -0,0 +1,3 @@ + + + + + + + ./src + + + + + + + + ./tests + ./tests/OSS/Tests/BucketCnameTest.php + + + diff --git a/aliyun-oss-php-sdk-2.3.0/samples/Bucket.php b/aliyun-oss-php-sdk-2.3.0/samples/Bucket.php new file mode 100755 index 0000000..bd16e65 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/Bucket.php @@ -0,0 +1,167 @@ +createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE); +Common::println("bucket $bucket created"); + +// 判断Bucket是否存在 +$doesExist = $ossClient->doesBucketExist($bucket); +Common::println("bucket $bucket exist? " . ($doesExist ? "yes" : "no")); + +// 获取Bucket列表 +$bucketListInfo = $ossClient->listBuckets(); + +// 设置bucket的ACL +$ossClient->putBucketAcl($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE); +Common::println("bucket $bucket acl put"); +// 获取bucket的ACL +$acl = $ossClient->getBucketAcl($bucket); +Common::println("bucket $bucket acl get: " . $acl); + + +//******************************* 完整用法参考下面函数 **************************************************** + +createBucket($ossClient, $bucket); +doesBucketExist($ossClient, $bucket); +deleteBucket($ossClient, $bucket); +putBucketAcl($ossClient, $bucket); +getBucketAcl($ossClient, $bucket); +listBuckets($ossClient); + +/** + * 创建一个存储空间 + * acl 指的是bucket的访问控制权限,有三种,私有读写,公共读私有写,公共读写。 + * 私有读写就是只有bucket的拥有者或授权用户才有权限操作 + * 三种权限分别对应 (OssClient::OSS_ACL_TYPE_PRIVATE,OssClient::OSS_ACL_TYPE_PUBLIC_READ, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE) + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 要创建的存储空间名称 + * @return null + */ +function createBucket($ossClient, $bucket) +{ + try { + $ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 判断Bucket是否存在 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + */ +function doesBucketExist($ossClient, $bucket) +{ + try { + $res = $ossClient->doesBucketExist($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + if ($res === true) { + print(__FUNCTION__ . ": OK" . "\n"); + } else { + print(__FUNCTION__ . ": FAILED" . "\n"); + } +} + +/** + * 删除bucket,如果bucket不为空则bucket无法删除成功, 不为空表示bucket既没有object,也没有未完成的multipart上传时的parts + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 待删除的存储空间名称 + * @return null + */ +function deleteBucket($ossClient, $bucket) +{ + try { + $ossClient->deleteBucket($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 设置bucket的acl配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putBucketAcl($ossClient, $bucket) +{ + $acl = OssClient::OSS_ACL_TYPE_PRIVATE; + try { + $ossClient->putBucketAcl($bucket, $acl); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + + +/** + * 获取bucket的acl配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getBucketAcl($ossClient, $bucket) +{ + try { + $res = $ossClient->getBucketAcl($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + print('acl: ' . $res); +} + + +/** + * 列出用户所有的Bucket + * + * @param OssClient $ossClient OssClient实例 + * @return null + */ +function listBuckets($ossClient) +{ + $bucketList = null; + try { + $bucketListInfo = $ossClient->listBuckets(); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + $bucketList = $bucketListInfo->getBucketList(); + foreach ($bucketList as $bucket) { + print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n"); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/samples/BucketCors.php b/aliyun-oss-php-sdk-2.3.0/samples/BucketCors.php new file mode 100755 index 0000000..cc5c0b9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/BucketCors.php @@ -0,0 +1,108 @@ +addAllowedHeader("x-oss-header"); +$rule->addAllowedOrigin("http://www.b.com"); +$rule->addAllowedMethod("POST"); +$rule->setMaxAgeSeconds(10); +$corsConfig->addRule($rule); +$ossClient->putBucketCors($bucket, $corsConfig); +Common::println("bucket $bucket corsConfig created:" . $corsConfig->serializeToXml()); + +// 获取cors配置 +$corsConfig = $ossClient->getBucketCors($bucket); +Common::println("bucket $bucket corsConfig fetched:" . $corsConfig->serializeToXml()); + +// 删除cors配置 +$ossClient->deleteBucketCors($bucket); +Common::println("bucket $bucket corsConfig deleted"); + +//******************************* 完整用法参考下面函数 ***************************************************** + +putBucketCors($ossClient, $bucket); +getBucketCors($ossClient, $bucket); +deleteBucketCors($ossClient, $bucket); +getBucketCors($ossClient, $bucket); + +/** + * 设置bucket的cors配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putBucketCors($ossClient, $bucket) +{ + $corsConfig = new CorsConfig(); + $rule = new CorsRule(); + $rule->addAllowedHeader("x-oss-header"); + $rule->addAllowedOrigin("http://www.b.com"); + $rule->addAllowedMethod("POST"); + $rule->setMaxAgeSeconds(10); + $corsConfig->addRule($rule); + + try { + $ossClient->putBucketCors($bucket, $corsConfig); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 获取并打印bucket的cors配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getBucketCors($ossClient, $bucket) +{ + $corsConfig = null; + try { + $corsConfig = $ossClient->getBucketCors($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + print($corsConfig->serializeToXml() . "\n"); +} + +/** + * 删除bucket的所有的cors配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteBucketCors($ossClient, $bucket) +{ + try { + $ossClient->deleteBucketCors($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + diff --git a/aliyun-oss-php-sdk-2.3.0/samples/BucketLifecycle.php b/aliyun-oss-php-sdk-2.3.0/samples/BucketLifecycle.php new file mode 100755 index 0000000..ec0c37f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/BucketLifecycle.php @@ -0,0 +1,109 @@ +addRule($lifecycleRule); +$ossClient->putBucketLifecycle($bucket, $lifecycleConfig); +Common::println("bucket $bucket lifecycleConfig created:" . $lifecycleConfig->serializeToXml()); + +//获取lifecycle规则 +$lifecycleConfig = $ossClient->getBucketLifecycle($bucket); +Common::println("bucket $bucket lifecycleConfig fetched:" . $lifecycleConfig->serializeToXml()); + +//删除bucket的lifecycle配置 +$ossClient->deleteBucketLifecycle($bucket); +Common::println("bucket $bucket lifecycleConfig deleted"); + + +//***************************** 完整用法参考下面函数 *********************************************** + +putBucketLifecycle($ossClient, $bucket); +getBucketLifecycle($ossClient, $bucket); +deleteBucketLifecycle($ossClient, $bucket); +getBucketLifecycle($ossClient, $bucket); + +/** + * 设置bucket的生命周期配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putBucketLifecycle($ossClient, $bucket) +{ + $lifecycleConfig = new LifecycleConfig(); + $actions = array(); + $actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DAYS, 3); + $lifecycleRule = new LifecycleRule("delete obsoleted files", "obsoleted/", "Enabled", $actions); + $lifecycleConfig->addRule($lifecycleRule); + $actions = array(); + $actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DATE, '2022-10-12T00:00:00.000Z'); + $lifecycleRule = new LifecycleRule("delete temporary files", "temporary/", "Enabled", $actions); + $lifecycleConfig->addRule($lifecycleRule); + try { + $ossClient->putBucketLifecycle($bucket, $lifecycleConfig); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 获取bucket的生命周期配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getBucketLifecycle($ossClient, $bucket) +{ + $lifecycleConfig = null; + try { + $lifecycleConfig = $ossClient->getBucketLifecycle($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + print($lifecycleConfig->serializeToXml() . "\n"); +} + +/** + * 删除bucket的生命周期配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteBucketLifecycle($ossClient, $bucket) +{ + try { + $ossClient->deleteBucketLifecycle($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + + diff --git a/aliyun-oss-php-sdk-2.3.0/samples/BucketLogging.php b/aliyun-oss-php-sdk-2.3.0/samples/BucketLogging.php new file mode 100755 index 0000000..406e1d4 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/BucketLogging.php @@ -0,0 +1,95 @@ +putBucketLogging($bucket, $bucket, "access.log", array()); +Common::println("bucket $bucket lifecycleConfig created"); + +// 获取Bucket访问日志记录规则 +$loggingConfig = $ossClient->getBucketLogging($bucket, array()); +Common::println("bucket $bucket lifecycleConfig fetched:" . $loggingConfig->serializeToXml()); + +// 删除Bucket访问日志记录规则 +$loggingConfig = $ossClient->getBucketLogging($bucket, array()); +Common::println("bucket $bucket lifecycleConfig deleted"); + +//******************************* 完整用法参考下面函数 **************************************************** + +putBucketLogging($ossClient, $bucket); +getBucketLogging($ossClient, $bucket); +deleteBucketLogging($ossClient, $bucket); +getBucketLogging($ossClient, $bucket); + +/** + * 设置bucket的Logging配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putBucketLogging($ossClient, $bucket) +{ + $option = array(); + //访问日志存放在本bucket下 + $targetBucket = $bucket; + $targetPrefix = "access.log"; + + try { + $ossClient->putBucketLogging($bucket, $targetBucket, $targetPrefix, $option); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 获取bucket的Logging配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getBucketLogging($ossClient, $bucket) +{ + $loggingConfig = null; + $options = array(); + try { + $loggingConfig = $ossClient->getBucketLogging($bucket, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + print($loggingConfig->serializeToXml() . "\n"); +} + +/** + * 删除bucket的Logging配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteBucketLogging($ossClient, $bucket) +{ + try { + $ossClient->deleteBucketLogging($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} diff --git a/aliyun-oss-php-sdk-2.3.0/samples/BucketReferer.php b/aliyun-oss-php-sdk-2.3.0/samples/BucketReferer.php new file mode 100755 index 0000000..3828df6 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/BucketReferer.php @@ -0,0 +1,101 @@ +setAllowEmptyReferer(true); +$refererConfig->addReferer("www.aliiyun.com"); +$refererConfig->addReferer("www.aliiyuncs.com"); +$ossClient->putBucketReferer($bucket, $refererConfig); +Common::println("bucket $bucket refererConfig created:" . $refererConfig->serializeToXml()); +//获取Referer白名单 +$refererConfig = $ossClient->getBucketReferer($bucket); +Common::println("bucket $bucket refererConfig fetched:" . $refererConfig->serializeToXml()); + +//删除referer白名单 +$refererConfig = new RefererConfig(); +$ossClient->putBucketReferer($bucket, $refererConfig); +Common::println("bucket $bucket refererConfig deleted"); + + +//******************************* 完整用法参考下面函数 **************************************************** + +putBucketReferer($ossClient, $bucket); +getBucketReferer($ossClient, $bucket); +deleteBucketReferer($ossClient, $bucket); +getBucketReferer($ossClient, $bucket); + +/** + * 设置bucket的防盗链配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putBucketReferer($ossClient, $bucket) +{ + $refererConfig = new RefererConfig(); + $refererConfig->setAllowEmptyReferer(true); + $refererConfig->addReferer("www.aliiyun.com"); + $refererConfig->addReferer("www.aliiyuncs.com"); + try { + $ossClient->putBucketReferer($bucket, $refererConfig); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 获取bucket的防盗链配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getBucketReferer($ossClient, $bucket) +{ + $refererConfig = null; + try { + $refererConfig = $ossClient->getBucketReferer($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + print($refererConfig->serializeToXml() . "\n"); +} + +/** + * 删除bucket的防盗链配置 + * Referer白名单不能直接清空,只能通过重新设置来覆盖之前的规则。 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteBucketReferer($ossClient, $bucket) +{ + $refererConfig = new RefererConfig(); + try { + $ossClient->putBucketReferer($bucket, $refererConfig); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} diff --git a/aliyun-oss-php-sdk-2.3.0/samples/BucketWebsite.php b/aliyun-oss-php-sdk-2.3.0/samples/BucketWebsite.php new file mode 100755 index 0000000..54706f8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/BucketWebsite.php @@ -0,0 +1,92 @@ +putBucketWebsite($bucket, $websiteConfig); +Common::println("bucket $bucket websiteConfig created:" . $websiteConfig->serializeToXml()); + +// 查看Bucket的静态网站托管状态 +$websiteConfig = $ossClient->getBucketWebsite($bucket); +Common::println("bucket $bucket websiteConfig fetched:" . $websiteConfig->serializeToXml()); + +// 删除Bucket的静态网站托管模式 +$ossClient->deleteBucketWebsite($bucket); +Common::println("bucket $bucket websiteConfig deleted"); + +//******************************* 完整用法参考下面函数 **************************************************** + +putBucketWebsite($ossClient, $bucket); +getBucketWebsite($ossClient, $bucket); +deleteBucketWebsite($ossClient, $bucket); +getBucketWebsite($ossClient, $bucket); + +/** + * 设置bucket的静态网站托管模式配置 + * + * @param $ossClient OssClient + * @param $bucket string 存储空间名称 + * @return null + */ +function putBucketWebsite($ossClient, $bucket) +{ + $websiteConfig = new WebsiteConfig("index.html", "error.html"); + try { + $ossClient->putBucketWebsite($bucket, $websiteConfig); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 获取bucket的静态网站托管状态 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getBucketWebsite($ossClient, $bucket) +{ + $websiteConfig = null; + try { + $websiteConfig = $ossClient->getBucketWebsite($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + print($websiteConfig->serializeToXml() . "\n"); +} + +/** + * 删除bucket的静态网站托管模式配置 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteBucketWebsite($ossClient, $bucket) +{ + try { + $ossClient->deleteBucketWebsite($bucket); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} diff --git a/aliyun-oss-php-sdk-2.3.0/samples/Callback.php b/aliyun-oss-php-sdk-2.3.0/samples/Callback.php new file mode 100755 index 0000000..8612a1c --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/Callback.php @@ -0,0 +1,83 @@ + $url, + OssClient::OSS_CALLBACK_VAR => $var + ); +$result = $ossClient->putObject($bucket, "b.file", "random content", $options); +Common::println($result['body']); +Common::println($result['info']['http_code']); + +/** + * completeMultipartUpload 使用callback上传内容到oss文件 + * callbackurl参数指定请求回调的服务器url + * callbackbodytype参数可为application/json或application/x-www-form-urlencoded, 可选参数,默认为application/x-www-form-urlencoded + * OSS_CALLBACK_VAR参数可以不设置 + */ +$object = "multipart-callback-test.txt"; +$copiedObject = "multipart-callback-test.txt.copied"; +$ossClient->putObject($bucket, $copiedObject, file_get_contents(__FILE__)); + +/** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ +$upload_id = $ossClient->initiateMultipartUpload($bucket, $object); + +/** + * step 2. uploadPartCopy + */ +$copyId = 1; +$eTag = $ossClient->uploadPartCopy($bucket, $copiedObject, $bucket, $object, $copyId, $upload_id); +$upload_parts[] = array( + 'PartNumber' => $copyId, + 'ETag' => $eTag, + ); +$listPartsInfo = $ossClient->listParts($bucket, $object, $upload_id); + +/** + * step 3. + */ +$json = + '{ + "callbackUrl":"callback.oss-demo.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}", + "callbackBodyType":"application/json" + }'; +$var = + '{ + "x:var1":"value1", + "x:var2":"值2" + }'; +$options = array(OssClient::OSS_CALLBACK => $json, + OssClient::OSS_CALLBACK_VAR => $var); + +$result = $ossClient->completeMultipartUpload($bucket, $object, $upload_id, $upload_parts, $options); +Common::println($result['body']); +Common::println($result['info']['http_code']); diff --git a/aliyun-oss-php-sdk-2.3.0/samples/Common.php b/aliyun-oss-php-sdk-2.3.0/samples/Common.php new file mode 100755 index 0000000..f419d17 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/Common.php @@ -0,0 +1,84 @@ +getMessage() . "\n"); + return null; + } + return $ossClient; + } + + public static function getBucketName() + { + return self::bucket; + } + + /** + * 工具方法,创建一个存储空间,如果发生异常直接exit + */ + public static function createBucket() + { + $ossClient = self::getOssClient(); + if (is_null($ossClient)) exit(1); + $bucket = self::getBucketName(); + $acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ; + try { + $ossClient->createBucket($bucket, $acl); + } catch (OssException $e) { + + $message = $e->getMessage(); + if (\OSS\Core\OssUtil::startsWith($message, 'http status: 403')) { + echo "Please Check your AccessKeyId and AccessKeySecret" . "\n"; + exit(0); + } elseif (strpos($message, "BucketAlreadyExists") !== false) { + echo "Bucket already exists. Please check whether the bucket belongs to you, or it was visited with correct endpoint. " . "\n"; + exit(0); + } + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + } + + public static function println($message) + { + if (!empty($message)) { + echo strval($message) . "\n"; + } + } +} + +Common::createBucket(); diff --git a/aliyun-oss-php-sdk-2.3.0/samples/Config.php b/aliyun-oss-php-sdk-2.3.0/samples/Config.php new file mode 100755 index 0000000..35c0dc7 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/Config.php @@ -0,0 +1,15 @@ +uploadFile($bucketName, $object, "example.jpg"); + +// 图片缩放 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("imageResize",$download_file); + +// 图片裁剪 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/crop,w_100,h_100,x_100,y_100,r_1", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("iamgeCrop", $download_file); + +// 图片旋转 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/rotate,90", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("imageRotate", $download_file); + +// 图片锐化 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/sharpen,100", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("imageSharpen", $download_file); + +// 图片水印 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("imageWatermark", $download_file); + +// 图片格式转换 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/format,png", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("imageFormat", $download_file); + +// 获取图片信息 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => $download_file, + OssClient::OSS_PROCESS => "image/info", ); +$ossClient->getObject($bucketName, $object, $options); +printImage("imageInfo", $download_file); + + +/** + * 生成一个带签名的可用于浏览器直接打开的url, URL的有效期是3600秒 + */ + $timeout = 3600; +$options = array( + OssClient::OSS_PROCESS => "image/resize,m_lfit,h_100,w_100", + ); +$signedUrl = $ossClient->signUrl($bucketName, $object, $timeout, "GET", $options); +Common::println("rtmp url: \n" . $signedUrl); + +//最后删除上传的$object +$ossClient->deleteObject($bucketName, $object); + +function printImage($func, $imageFile) +{ + $array = getimagesize($imageFile); + Common::println("$func, image width: " . $array[0]); + Common::println("$func, image height: " . $array[1]); + Common::println("$func, image type: " . ($array[2] === 2 ? 'jpg' : 'png')); + Common::println("$func, image size: " . ceil(filesize($imageFile))); +} diff --git a/aliyun-oss-php-sdk-2.3.0/samples/LiveChannel.php b/aliyun-oss-php-sdk-2.3.0/samples/LiveChannel.php new file mode 100755 index 0000000..2f7d3a8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/LiveChannel.php @@ -0,0 +1,125 @@ + 'live channel test', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); +$info = $ossClient->putBucketLiveChannel($bucket, 'test_rtmp_live', $config); +Common::println("bucket $bucket liveChannel created:\n" . +"live channel name: ". $info->getName() . "\n" . +"live channel description: ". $info->getDescription() . "\n" . +"publishurls: ". $info->getPublishUrls()[0] . "\n" . +"playurls: ". $info->getPlayUrls()[0] . "\n"); + +/** + 对创建好的频道,可以使用listBucketLiveChannels来进行列举已达到管理的目的。 + prefix可以按照前缀过滤list出来的频道。 + max_keys表示迭代器内部一次list出来的频道的最大数量,这个值最大不能超过1000,不填写的话默认为100。 + */ +$list = $ossClient->listBucketLiveChannels($bucket); +Common::println("bucket $bucket listLiveChannel:\n" . +"list live channel prefix: ". $list->getPrefix() . "\n" . +"list live channel marker: ". $list->getMarker() . "\n" . +"list live channel maxkey: ". $list->getMaxKeys() . "\n" . +"list live channel IsTruncated: ". $list->getIsTruncated() . "\n" . +"list live channel getNextMarker: ". $list->getNextMarker() . "\n"); + +foreach($list->getChannelList() as $list) +{ + Common::println("bucket $bucket listLiveChannel:\n" . + "list live channel IsTruncated: ". $list->getName() . "\n" . + "list live channel Description: ". $list->getDescription() . "\n" . + "list live channel Status: ". $list->getStatus() . "\n" . + "list live channel getNextMarker: ". $list->getLastModified() . "\n"); +} +/** + 创建直播频道之后拿到推流用的play_url(rtmp推流的url,如果Bucket不是公共读写权限那么还需要带上签名,见下文示例)和推流用的publish_url(推流产生的m3u8文件的url) + */ +$play_url = $ossClient->signRtmpUrl($bucket, "test_rtmp_live", 3600, array('params' => array('playlistName' => 'playlist.m3u8'))); +Common::println("bucket $bucket rtmp url: \n" . $play_url); +$play_url = $ossClient->signRtmpUrl($bucket, "test_rtmp_live", 3600); +Common::println("bucket $bucket rtmp url: \n" . $play_url); + +/** + 创建好直播频道,如果想把这个频道禁用掉(断掉正在推的流或者不再允许向一个地址推流),应该使用putLiveChannelStatus接口,将频道的status改成“Disabled”,如果要将一个禁用状态的频道启用,那么也是调用这个接口,将status改成“Enabled” + */ +$resp = $ossClient->putLiveChannelStatus($bucket, "test_rtmp_live", "enabled"); + +/** + 创建好直播频道之后调用getLiveChannelInfo可以得到频道相关的信息 + */ +$info = $ossClient->getLiveChannelInfo($bucket, 'test_rtmp_live'); +Common::println("bucket $bucket LiveChannelInfo:\n" . +"live channel info description: ". $info->getDescription() . "\n" . +"live channel info status: ". $info->getStatus() . "\n" . +"live channel info type: ". $info->getType() . "\n" . +"live channel info fragDuration: ". $info->getFragDuration() . "\n" . +"live channel info fragCount: ". $info->getFragCount() . "\n" . +"live channel info playListName: ". $info->getPlayListName() . "\n"); + +/** + 如果想查看一个频道历史推流记录,可以调用getLiveChannelHistory。目前最多可以看到10次推流的记录 + */ +$history = $ossClient->getLiveChannelHistory($bucket, "test_rtmp_live"); +if (count($history->getLiveRecordList()) != 0) +{ + foreach($history->getLiveRecordList() as $recordList) + { + Common::println("bucket $bucket liveChannelHistory:\n" . + "live channel history startTime: ". $recordList->getStartTime() . "\n" . + "live channel history endTime: ". $recordList->getEndTime() . "\n" . + "live channel history remoteAddr: ". $recordList->getRemoteAddr() . "\n"); + } +} + +/** + 对于正在推流的频道调用get_live_channel_stat可以获得流的状态信息。 + 如果频道正在推流,那么stat_result中的所有字段都有意义。 + 如果频道闲置或者处于“Disabled”状态,那么status为“Idle”或“Disabled”,其他字段无意义。 + */ +$status = $ossClient->getLiveChannelStatus($bucket, "test_rtmp_live"); +Common::println("bucket $bucket listLiveChannel:\n" . +"live channel status status: ". $status->getStatus() . "\n" . +"live channel status ConnectedTime: ". $status->getConnectedTime() . "\n" . +"live channel status VideoWidth: ". $status->getVideoWidth() . "\n" . +"live channel status VideoHeight: ". $status->getVideoHeight() . "\n" . +"live channel status VideoFrameRate: ". $status->getVideoFrameRate() . "\n" . +"live channel status VideoBandwidth: ". $status->getVideoBandwidth() . "\n" . +"live channel status VideoCodec: ". $status->getVideoCodec() . "\n" . +"live channel status AudioBandwidth: ". $status->getAudioBandwidth() . "\n" . +"live channel status AudioSampleRate: ". $status->getAudioSampleRate() . "\n" . +"live channel status AdioCodec: ". $status->getAudioCodec() . "\n"); + +/** + * 如果希望利用直播推流产生的ts文件生成一个点播列表,可以使用postVodPlaylist方法。 + * 指定起始时间为当前时间减去60秒,结束时间为当前时间,这意味着将生成一个长度为60秒的点播视频。 + * 播放列表指定为“vod_playlist.m3u8”,也就是说这个接口调用成功之后会在OSS上生成一个名叫“vod_playlist.m3u8”的播放列表文件。 + */ +$current_time = time(); +$ossClient->postVodPlaylist($bucket, + "test_rtmp_live", "vod_playlist.m3u8", + array('StartTime' => $current_time - 60, + 'EndTime' => $current_time) +); + +/** + * 如果一个直播频道已经不打算再使用了,那么可以调用delete_live_channel来删除频道。 + */ +$ossClient->deleteBucketLiveChannel($bucket, "test_rtmp_live"); diff --git a/aliyun-oss-php-sdk-2.3.0/samples/MultipartUpload.php b/aliyun-oss-php-sdk-2.3.0/samples/MultipartUpload.php new file mode 100755 index 0000000..e8d69a3 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/MultipartUpload.php @@ -0,0 +1,182 @@ +multiuploadFile($bucket, "file.php", __FILE__, array()); +Common::println("local file " . __FILE__ . " is uploaded to the bucket $bucket, file.php"); + + +// 上传本地目录到bucket内的targetdir子目录中 +$ossClient->uploadDir($bucket, "targetdir", __DIR__); +Common::println("local dir " . __DIR__ . " is uploaded to the bucket $bucket, targetdir/"); + + +// 列出当前未完成的分片上传 +$listMultipartUploadInfo = $ossClient->listMultipartUploads($bucket, array()); + + +//******************************* 完整用法参考下面函数 **************************************************** + +multiuploadFile($ossClient, $bucket); +putObjectByRawApis($ossClient, $bucket); +uploadDir($ossClient, $bucket); +listMultipartUploads($ossClient, $bucket); + +/** + * 通过multipart上传文件 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function multiuploadFile($ossClient, $bucket) +{ + $object = "test/multipart-test.txt"; + $file = __FILE__; + $options = array(); + + try { + $ossClient->multiuploadFile($bucket, $object, $file, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 使用基本的api分阶段进行分片上传 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @throws OssException + */ +function putObjectByRawApis($ossClient, $bucket) +{ + $object = "test/multipart-test.txt"; + /** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ + try { + $uploadId = $ossClient->initiateMultipartUpload($bucket, $object); + } catch (OssException $e) { + printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n"); + /* + * step 2. 上传分片 + */ + $partSize = 10 * 1024 * 1024; + $uploadFile = __FILE__; + $uploadFileSize = filesize($uploadFile); + $pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize); + $responseUploadPart = array(); + $uploadPosition = 0; + $isCheckMd5 = true; + foreach ($pieces as $i => $piece) { + $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO]; + $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1; + $upOptions = array( + $ossClient::OSS_FILE_UPLOAD => $uploadFile, + $ossClient::OSS_PART_NUM => ($i + 1), + $ossClient::OSS_SEEK_TO => $fromPos, + $ossClient::OSS_LENGTH => $toPos - $fromPos + 1, + $ossClient::OSS_CHECK_MD5 => $isCheckMd5, + ); + if ($isCheckMd5) { + $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos); + $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5; + } + //2. 将每一分片上传到OSS + try { + $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions); + } catch (OssException $e) { + printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n"); + } + $uploadParts = array(); + foreach ($responseUploadPart as $i => $eTag) { + $uploadParts[] = array( + 'PartNumber' => ($i + 1), + 'ETag' => $eTag, + ); + } + /** + * step 3. 完成上传 + */ + try { + $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts); + } catch (OssException $e) { + printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + printf(__FUNCTION__ . ": completeMultipartUpload OK\n"); +} + +/** + * 按照目录上传文件 + * + * @param OssClient $ossClient OssClient + * @param string $bucket 存储空间名称 + * + */ +function uploadDir($ossClient, $bucket) +{ + $localDirectory = "."; + $prefix = "samples/codes"; + try { + $ossClient->uploadDir($bucket, $prefix, $localDirectory); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + printf(__FUNCTION__ . ": completeMultipartUpload OK\n"); +} + +/** + * 获取当前未完成的分片上传列表 + * + * @param $ossClient OssClient + * @param $bucket string + */ +function listMultipartUploads($ossClient, $bucket) +{ + $options = array( + 'max-uploads' => 100, + 'key-marker' => '', + 'prefix' => '', + 'upload-id-marker' => '' + ); + try { + $listMultipartUploadInfo = $ossClient->listMultipartUploads($bucket, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": listMultipartUploads FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + printf(__FUNCTION__ . ": listMultipartUploads OK\n"); + $listUploadInfo = $listMultipartUploadInfo->getUploads(); + var_dump($listUploadInfo); +} diff --git a/aliyun-oss-php-sdk-2.3.0/samples/Object.php b/aliyun-oss-php-sdk-2.3.0/samples/Object.php new file mode 100755 index 0000000..3bf024b --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/Object.php @@ -0,0 +1,517 @@ +putObject($bucket, "b.file", "hi, oss"); +Common::println("b.file is created"); +Common::println($result['x-oss-request-id']); +Common::println($result['etag']); +Common::println($result['content-md5']); +Common::println($result['body']); + +// 上传本地文件 +$result = $ossClient->uploadFile($bucket, "c.file", __FILE__); +Common::println("c.file is created"); +Common::println("b.file is created"); +Common::println($result['x-oss-request-id']); +Common::println($result['etag']); +Common::println($result['content-md5']); +Common::println($result['body']); + +// 下载object到本地变量 +$content = $ossClient->getObject($bucket, "b.file"); +Common::println("b.file is fetched, the content is: " . $content); + +// 给object添加symlink +$content = $ossClient->putSymlink($bucket, "test-symlink", "b.file"); +Common::println("test-symlink is created"); +Common::println($result['x-oss-request-id']); +Common::println($result['etag']); + +// 获取symlink +$content = $ossClient->getSymlink($bucket, "test-symlink"); +Common::println("test-symlink refer to : " . $content[OssClient::OSS_SYMLINK_TARGET]); + +// 下载object到本地文件 +$options = array( + OssClient::OSS_FILE_DOWNLOAD => "./c.file.localcopy", +); +$ossClient->getObject($bucket, "c.file", $options); +Common::println("b.file is fetched to the local file: c.file.localcopy"); +Common::println("b.file is created"); + +// 拷贝object +$result = $ossClient->copyObject($bucket, "c.file", $bucket, "c.file.copy"); +Common::println("lastModifiedTime: " . $result[0]); +Common::println("ETag: " . $result[1]); + +// 判断object是否存在 +$doesExist = $ossClient->doesObjectExist($bucket, "c.file.copy"); +Common::println("file c.file.copy exist? " . ($doesExist ? "yes" : "no")); + +// 删除object +$result = $ossClient->deleteObject($bucket, "c.file.copy"); +Common::println("c.file.copy is deleted"); +Common::println("b.file is created"); +Common::println($result['x-oss-request-id']); + +// 判断object是否存在 +$doesExist = $ossClient->doesObjectExist($bucket, "c.file.copy"); +Common::println("file c.file.copy exist? " . ($doesExist ? "yes" : "no")); + +// 批量删除object +$result = $ossClient->deleteObjects($bucket, array("b.file", "c.file")); +foreach($result as $object) + Common::println($object); + +sleep(2); +unlink("c.file.localcopy"); + +//******************************* 完整用法参考下面函数 **************************************************** + +listObjects($ossClient, $bucket); +listAllObjects($ossClient, $bucket); +createObjectDir($ossClient, $bucket); +putObject($ossClient, $bucket); +uploadFile($ossClient, $bucket); +getObject($ossClient, $bucket); +getObjectToLocalFile($ossClient, $bucket); +copyObject($ossClient, $bucket); +modifyMetaForObject($ossClient, $bucket); +getObjectMeta($ossClient, $bucket); +deleteObject($ossClient, $bucket); +deleteObjects($ossClient, $bucket); +doesObjectExist($ossClient, $bucket); +getSymlink($ossClient, $bucket); +putSymlink($ossClient, $bucket); +/** + * 创建虚拟目录 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function createObjectDir($ossClient, $bucket) +{ + try { + $ossClient->createObjectDir($bucket, "dir"); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 把本地变量的内容到文件 + * + * 简单上传,上传指定变量的内存值作为object的内容 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putObject($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $content = file_get_contents(__FILE__); + $options = array(); + try { + $ossClient->putObject($bucket, $object, $content, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + + +/** + * 上传指定的本地文件内容 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function uploadFile($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $filePath = __FILE__; + $options = array(); + + try { + $ossClient->uploadFile($bucket, $object, $filePath, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 列出Bucket内所有目录和文件, 注意如果符合条件的文件数目超过设置的max-keys, 用户需要使用返回的nextMarker作为入参,通过 + * 循环调用ListObjects得到所有的文件,具体操作见下面的 listAllObjects 示例 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function listObjects($ossClient, $bucket) +{ + $prefix = 'oss-php-sdk-test/'; + $delimiter = '/'; + $nextMarker = ''; + $maxkeys = 1000; + $options = array( + 'delimiter' => $delimiter, + 'prefix' => $prefix, + 'max-keys' => $maxkeys, + 'marker' => $nextMarker, + ); + try { + $listObjectInfo = $ossClient->listObjects($bucket, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + $objectList = $listObjectInfo->getObjectList(); // 文件列表 + $prefixList = $listObjectInfo->getPrefixList(); // 目录列表 + if (!empty($objectList)) { + print("objectList:\n"); + foreach ($objectList as $objectInfo) { + print($objectInfo->getKey() . "\n"); + } + } + if (!empty($prefixList)) { + print("prefixList: \n"); + foreach ($prefixList as $prefixInfo) { + print($prefixInfo->getPrefix() . "\n"); + } + } +} + +/** + * 列出Bucket内所有目录和文件, 根据返回的nextMarker循环得到所有Objects + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function listAllObjects($ossClient, $bucket) +{ + //构造dir下的文件和虚拟目录 + for ($i = 0; $i < 100; $i += 1) { + $ossClient->putObject($bucket, "dir/obj" . strval($i), "hi"); + $ossClient->createObjectDir($bucket, "dir/obj" . strval($i)); + } + + $prefix = 'dir/'; + $delimiter = '/'; + $nextMarker = ''; + $maxkeys = 30; + + while (true) { + $options = array( + 'delimiter' => $delimiter, + 'prefix' => $prefix, + 'max-keys' => $maxkeys, + 'marker' => $nextMarker, + ); + var_dump($options); + try { + $listObjectInfo = $ossClient->listObjects($bucket, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + // 得到nextMarker,从上一次listObjects读到的最后一个文件的下一个文件开始继续获取文件列表 + $nextMarker = $listObjectInfo->getNextMarker(); + $listObject = $listObjectInfo->getObjectList(); + $listPrefix = $listObjectInfo->getPrefixList(); + var_dump(count($listObject)); + var_dump(count($listPrefix)); + if ($nextMarker === '') { + break; + } + } +} + +/** + * 获取object的内容 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getObject($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $options = array(); + try { + $content = $ossClient->getObject($bucket, $object, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + if (file_get_contents(__FILE__) === $content) { + print(__FUNCTION__ . ": FileContent checked OK" . "\n"); + } else { + print(__FUNCTION__ . ": FileContent checked FAILED" . "\n"); + } +} + +/** + * put symlink + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function putSymlink($ossClient, $bucket) +{ + $symlink = "test-samples-symlink"; + $object = "test-samples-object"; + try { + $ossClient->putObject($bucket, $object, 'test-content'); + $ossClient->putSymlink($bucket, $symlink, $object); + $content = $ossClient->getObject($bucket, $symlink); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + if ($content == 'test-content') { + print(__FUNCTION__ . ": putSymlink checked OK" . "\n"); + } else { + print(__FUNCTION__ . ": putSymlink checked FAILED" . "\n"); + } +} + +/** + * 获取symlink + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getSymlink($ossClient, $bucket) +{ + $symlink = "test-samples-symlink"; + $object = "test-samples-object"; + try { + $ossClient->putObject($bucket, $object, 'test-content'); + $ossClient->putSymlink($bucket, $symlink, $object); + $content = $ossClient->getSymlink($bucket, $symlink); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + if ($content[OssClient::OSS_SYMLINK_TARGET]) { + print(__FUNCTION__ . ": getSymlink checked OK" . "\n"); + } else { + print(__FUNCTION__ . ": getSymlink checked FAILED" . "\n"); + } +} + +/** + * get_object_to_local_file + * + * 获取object + * 将object下载到指定的文件 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getObjectToLocalFile($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $localfile = "upload-test-object-name.txt"; + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $localfile, + ); + + try { + $ossClient->getObject($bucket, $object, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK, please check localfile: 'upload-test-object-name.txt'" . "\n"); + if (file_get_contents($localfile) === file_get_contents(__FILE__)) { + print(__FUNCTION__ . ": FileContent checked OK" . "\n"); + } else { + print(__FUNCTION__ . ": FileContent checked FAILED" . "\n"); + } + if (file_exists($localfile)) { + unlink($localfile); + } +} + +/** + * 拷贝object + * 当目的object和源object完全相同时,表示修改object的meta信息 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function copyObject($ossClient, $bucket) +{ + $fromBucket = $bucket; + $fromObject = "oss-php-sdk-test/upload-test-object-name.txt"; + $toBucket = $bucket; + $toObject = $fromObject . '.copy'; + $options = array(); + + try { + $ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 修改Object Meta + * 利用copyObject接口的特性:当目的object和源object完全相同时,表示修改object的meta信息 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function modifyMetaForObject($ossClient, $bucket) +{ + $fromBucket = $bucket; + $fromObject = "oss-php-sdk-test/upload-test-object-name.txt"; + $toBucket = $bucket; + $toObject = $fromObject; + $copyOptions = array( + OssClient::OSS_HEADERS => array( + 'Cache-Control' => 'max-age=60', + 'Content-Disposition' => 'attachment; filename="xxxxxx"', + ), + ); + try { + $ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $copyOptions); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 获取object meta, 也就是getObjectMeta接口 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function getObjectMeta($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + try { + $objectMeta = $ossClient->getObjectMeta($bucket, $object); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + if (isset($objectMeta[strtolower('Content-Disposition')]) && + 'attachment; filename="xxxxxx"' === $objectMeta[strtolower('Content-Disposition')] + ) { + print(__FUNCTION__ . ": ObjectMeta checked OK" . "\n"); + } else { + print(__FUNCTION__ . ": ObjectMeta checked FAILED" . "\n"); + } +} + +/** + * 删除object + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteObject($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + try { + $ossClient->deleteObject($bucket, $object); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + + +/** + * 批量删除object + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function deleteObjects($ossClient, $bucket) +{ + $objects = array(); + $objects[] = "oss-php-sdk-test/upload-test-object-name.txt"; + $objects[] = "oss-php-sdk-test/upload-test-object-name.txt.copy"; + try { + $ossClient->deleteObjects($bucket, $objects); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); +} + +/** + * 判断object是否存在 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + */ +function doesObjectExist($ossClient, $bucket) +{ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + try { + $exist = $ossClient->doesObjectExist($bucket, $object); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + var_dump($exist); +} + diff --git a/aliyun-oss-php-sdk-2.3.0/samples/RunAll.php b/aliyun-oss-php-sdk-2.3.0/samples/RunAll.php new file mode 100755 index 0000000..a4d6d9b --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/samples/RunAll.php @@ -0,0 +1,13 @@ +uploadFile($bucket, "a.file", __FILE__); + +// 生成GetObject的签名url,用户可以使用这个url直接在浏览器下载 +$signedUrl = $ossClient->signUrl($bucket, "a.file", 3600); +Common::println($signedUrl); + +// 生成用于putObject的签名URL,用户可以直接用put方法使用这个url上传文件到 "a.file" +$signedUrl = $ossClient->signUrl($bucket, "a.file", "3600", "PUT"); +Common::println($signedUrl); + +// 生成从本地文件上传PutObject的签名url, 用户可以直接使用这个url把本地文件上传到 "a.file" +$signedUrl = $ossClient->signUrl($bucket, "a.file", 3600, "PUT", array('Content-Type' => 'txt')); +Common::println($signedUrl); + +//******************************* 完整用法参考下面函数 **************************************************** + +getSignedUrlForPuttingObject($ossClient, $bucket); +getSignedUrlForPuttingObjectFromFile($ossClient, $bucket); +getSignedUrlForGettingObject($ossClient, $bucket); + +/** + * 生成GetObject的签名url,主要用于私有权限下的读访问控制 + * + * @param $ossClient OssClient OssClient实例 + * @param $bucket string 存储空间名称 + * @return null + */ +function getSignedUrlForGettingObject($ossClient, $bucket) +{ + $object = "test/test-signature-test-upload-and-download.txt"; + $timeout = 3600; + try { + $signedUrl = $ossClient->signUrl($bucket, $object, $timeout); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n"); + /** + * 可以类似的代码来访问签名的URL,也可以输入到浏览器中去访问 + */ + $request = new RequestCore($signedUrl); + $request->set_method('GET'); + $request->add_header('Content-Type', ''); + $request->send_request(); + $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code()); + if ($res->isOK()) { + print(__FUNCTION__ . ": OK" . "\n"); + } else { + print(__FUNCTION__ . ": FAILED" . "\n"); + }; +} + +/** + * 生成PutObject的签名url,主要用于私有权限下的写访问控制 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @return null + * @throws OssException + */ +function getSignedUrlForPuttingObject($ossClient, $bucket) +{ + $object = "test/test-signature-test-upload-and-download.txt"; + $timeout = 3600; + $options = NULL; + try { + $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT"); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n"); + $content = file_get_contents(__FILE__); + + $request = new RequestCore($signedUrl); + $request->set_method('PUT'); + $request->add_header('Content-Type', ''); + $request->add_header('Content-Length', strlen($content)); + $request->set_body($content); + $request->send_request(); + $res = new ResponseCore($request->get_response_header(), + $request->get_response_body(), $request->get_response_code()); + if ($res->isOK()) { + print(__FUNCTION__ . ": OK" . "\n"); + } else { + print(__FUNCTION__ . ": FAILED" . "\n"); + }; +} + +/** + * 生成PutObject的签名url,主要用于私有权限下的写访问控制, 用户可以利用生成的signedUrl + * 从文件上传文件 + * + * @param OssClient $ossClient OssClient实例 + * @param string $bucket 存储空间名称 + * @throws OssException + */ +function getSignedUrlForPuttingObjectFromFile($ossClient, $bucket) +{ + $file = __FILE__; + $object = "test/test-signature-test-upload-and-download.txt"; + $timeout = 3600; + $options = array('Content-Type' => 'txt'); + try { + $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n"); + + $request = new RequestCore($signedUrl); + $request->set_method('PUT'); + $request->add_header('Content-Type', 'txt'); + $request->set_read_file($file); + $request->set_read_stream_size(filesize($file)); + $request->send_request(); + $res = new ResponseCore($request->get_response_header(), + $request->get_response_body(), $request->get_response_code()); + if ($res->isOK()) { + print(__FUNCTION__ . ": OK" . "\n"); + } else { + print(__FUNCTION__ . ": FAILED" . "\n"); + }; +} \ No newline at end of file diff --git a/AliOssSdk/util/mimetypes.class.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/MimeTypes.php old mode 100644 new mode 100755 similarity index 91% rename from AliOssSdk/util/mimetypes.class.php rename to aliyun-oss-php-sdk-2.3.0/src/OSS/Core/MimeTypes.php index f90a6e2..e9b88ff --- a/AliOssSdk/util/mimetypes.class.php +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/MimeTypes.php @@ -1,11 +1,36 @@ 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', @@ -17,11 +42,10 @@ class MimeTypes { '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' => 'application/ogg', + 'ogg' => 'audio/ogg', 'pdf' => 'application/pdf', 'rtf' => 'text/rtf', 'mif' => 'application/vnd.mif', @@ -66,9 +90,10 @@ class MimeTypes { 'spl' => 'application/x-futuresplash', 'gtar' => 'application/x-gtar', 'hdf' => 'application/x-hdf', - 'jar' => 'application/x-java-archive', + 'jar' => 'application/java-archive', 'jnlp' => 'application/x-java-jnlp-file', - 'js' => 'application/x-javascript', + 'js' => 'application/javascript', + 'json' => 'application/json', 'ksp' => 'application/x-kspread', 'chrt' => 'application/x-kchart', 'kil' => 'application/x-killustrator', @@ -225,6 +250,7 @@ class MimeTypes { 'vrml' => 'model/vrml', 'vxml' => 'application/voicexml+xml', 'webm' => 'video/webm', + 'webp' => 'image/webp', 'wrl' => 'model/vrml', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', @@ -233,8 +259,4 @@ class MimeTypes { 'xslt' => 'application/xslt+xml', 'xul' => 'application/vnd.mozilla.xul+xml', ); - - public static function get_mimetype($ext) { - return (isset ( self::$mime_types [$ext] ) ? self::$mime_types [$ext] : 'application/octet-stream'); - } -} +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/OssException.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/OssException.php new file mode 100755 index 0000000..b0e9e8b --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/OssUtil.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/OssUtil.php new file mode 100755 index 0000000..6e5d413 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Core/OssUtil.php @@ -0,0 +1,461 @@ + $value) { + if (is_string($key) && !is_array($value)) { + $temp[] = rawurlencode($key) . '=' . rawurlencode($value); + } + } + return implode('&', $temp); + } + + /** + * 转义字符替换 + * + * @param string $subject + * @return string + */ + public static function sReplace($subject) + { + $search = array('<', '>', '&', '\'', '"'); + $replace = array('<', '>', '&', ''', '"'); + return str_replace($search, $replace, $subject); + } + + /** + * 检查是否是中文编码 + * + * @param $str + * @return int + */ + public static function chkChinese($str) + { + return preg_match('/[\x80-\xff]./', $str); + } + + /** + * 检测是否GB2312编码 + * + * @param string $str + * @return boolean false UTF-8编码 TRUE GB2312编码 + */ + 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; + } + + /** + * 检测是否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; + } + + /** + * 检验bucket名称是否合法 + * bucket的命名规范: + * 1. 只能包括小写字母,数字 + * 2. 必须以小写字母或者数字开头 + * 3. 长度必须在3-63字节之间 + * + * @param string $bucket Bucket名称 + * @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; + } + + /** + * 检验object名称是否合法 + * object命名规范: + * 1. 规则长度必须在1-1023字节之间 + * 2. 使用UTF-8编码 + * 3. 不能以 "/" "\\"开头 + * + * @param string $object Object名称 + * @return boolean + */ + public static function validateObject($object) + { + $pattern = '/^.{1,1023}$/'; + if (empty($object) || !preg_match($pattern, $object) || + self::startsWith($object, '/') || self::startsWith($object, '\\') + ) { + return false; + } + return true; + } + + + /** + * 判断字符串$str是不是以$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; + } + } + + /** + * 生成createBucketXmlBody接口的xml消息 + * + * @param string $storageClass + * @return string + */ + public static function createBucketXmlBody($storageClass) + { + $xml = new \SimpleXMLElement(''); + $xml->addChild('StorageClass', $storageClass); + return $xml->asXML(); + } + + /** + * 检验$options + * + * @param array $options + * @throws OssException + * @return boolean + */ + public static function validateOptions($options) + { + //$options + if ($options != NULL && !is_array($options)) { + throw new OssException ($options . ':' . 'option must be array'); + } + } + + /** + * 检查上传文件的内容是否合法 + * + * @param $content string + * @throws OssException + */ + public static function validateContent($content) + { + if (empty($content)) { + throw new OssException("http body content is invalid"); + } + } + + /** + * 校验BUCKET/OBJECT/OBJECT GROUP是否为空 + * + * @param string $name + * @param string $errMsg + * @throws OssException + * @return void + */ + public static function throwOssExceptionWithMessageIfEmpty($name, $errMsg) + { + if (empty($name)) { + throw new OssException($errMsg); + } + } + + /** + * 仅供测试使用的接口,请勿使用 + * + * @param $filename + * @param $size + */ + public static function generateFile($filename, $size) + { + if (file_exists($filename) && $size == 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); + } + + /** + * 得到文件的md5编码 + * + * @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 = 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; + } + + /** + * 检测是否windows系统,因为windows系统默认编码为GBK + * + * @return bool + */ + public static function isWin() + { + return strtoupper(substr(PHP_OS, 0, 3)) == "WIN"; + } + + /** + * 主要是由于windows系统编码是gbk,遇到中文时候,如果不进行转换处理会出现找不到文件的问题 + * + * @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; + } + + /** + * 判断用户输入的endpoint是否是 xxx.xxx.xxx.xxx:port 或者 xxx.xxx.xxx.xxx的ip格式 + * + * @param string $endpoint 需要做判断的endpoint + * @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; + } + } + + /** + * 生成DeleteMultiObjects接口的xml消息 + * + * @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(); + } + + /** + * 生成CompleteMultipartUpload接口的xml消息 + * + * @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(); + } + + /** + * 读取目录 + * + * @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); + } + } +} diff --git a/AliOssSdk/lib/requestcore/LICENSE b/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/LICENSE old mode 100644 new mode 100755 similarity index 100% rename from AliOssSdk/lib/requestcore/LICENSE rename to aliyun-oss-php-sdk-2.3.0/src/OSS/Http/LICENSE diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/RequestCore.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/RequestCore.php new file mode 100755 index 0000000..06d0f87 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/RequestCore.php @@ -0,0 +1,896 @@ +). + */ + 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; + + /** + * 请求超时时间, 默认是5184000秒,6天 + * + * @var int + */ + public $timeout = 5184000; + + /** + * 连接超时时间,默认是10秒 + * + * @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 + + /** + * Constructs 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; + } + + /** + * Destructs 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 + + /** + * Sets 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; + } + + /** + * Adds 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; + } + + /** + * Removes 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; + } + + /** + * Sets 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; + } + + /** + * Sets 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; + } + + /** + * Sets 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); + } + + /** + * Sets 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); + } + + /** + * Sets 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; + } + + /** + * Sets 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; + } + + /** + * Prepares 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; + } + + 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 $curl_handle (Optional) The reference to the already executed cURL request. + * @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... + if (is_resource($curl_handle)) { + // 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; + } + + /** + * Sends 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 resource: ' . (string)$curl_handle . '; cURL error: ' . curl_error($curl_handle) . ' (' . curl_errno($curl_handle) . ')'); + } + + $parsed_response = $this->process_response($curl_handle, $this->response); + + curl_close($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/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/RequestCore_Exception.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/RequestCore_Exception.php new file mode 100755 index 0000000..cb4e83c --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Http/RequestCore_Exception.php @@ -0,0 +1,8 @@ +). + * @param string $body (Required) XML-formatted response from AWS. + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/BucketInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/BucketInfo.php new file mode 100755 index 0000000..9b89674 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/BucketInfo.php @@ -0,0 +1,78 @@ +location = $location; + $this->name = $name; + $this->createDate = $createDate; + } + + /** + * 得到bucket所在的region + * + * @return string + */ + public function getLocation() + { + return $this->location; + } + + /** + * 得到bucket的名称 + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * 得到bucket的创建时间 + * + * @return string + */ + public function getCreateDate() + { + return $this->createDate; + } + + /** + * bucket所在的region + * + * @var string + */ + private $location; + /** + * bucket的名称 + * + * @var string + */ + private $name; + + /** + * bucket的创建事件 + * + * @var string + */ + private $createDate; + +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/BucketListInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/BucketListInfo.php new file mode 100755 index 0000000..910717f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/BucketListInfo.php @@ -0,0 +1,39 @@ +bucketList = $bucketList; + } + + /** + * 得到BucketInfo列表 + * + * @return BucketInfo[] + */ + public function getBucketList() + { + return $this->bucketList; + } + + /** + * BucketInfo信息列表 + * + * @var array + */ + private $bucketList = array(); +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CnameConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CnameConfig.php new file mode 100755 index 0000000..f3597d2 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CorsConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CorsConfig.php new file mode 100755 index 0000000..c44c10a --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CorsConfig.php @@ -0,0 +1,113 @@ +rules = array(); + } + + /** + * 得到CorsRule列表 + * + * @return CorsRule[] + */ + public function getRules() + { + return $this->rules; + } + + + /** + * 添加一条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; + } + + /** + * 从xml数据中解析出CorsConfig + * + * @param string $strXml + * @throws OssException + * @return null + */ + public function parseFromXml($strXml) + { + $xml = simplexml_load_string($strXml); + 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); + } + return; + } + + /** + * 生成xml字符串 + * + * @return string + */ + public function serializeToXml() + { + $xml = new \SimpleXMLElement(''); + foreach ($this->rules as $rule) { + $xmlRule = $xml->addChild('CORSRule'); + $rule->appendToXml($xmlRule); + } + 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; + + /** + * orsRule列表 + * + * @var CorsRule[] + */ + private $rules = array(); +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CorsRule.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CorsRule.php new file mode 100755 index 0000000..2cbe1c1 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/CorsRule.php @@ -0,0 +1,150 @@ +allowedOrigins[] = $allowedOrigin; + } + } + + /** + * Rule中增加一条allowedMethod + * + * @param string $allowedMethod + */ + public function addAllowedMethod($allowedMethod) + { + if (!empty($allowedMethod)) { + $this->allowedMethods[] = $allowedMethod; + } + } + + /** + * Rule中增加一条allowedHeader + * + * @param string $allowedHeader + */ + public function addAllowedHeader($allowedHeader) + { + if (!empty($allowedHeader)) { + $this->allowedHeaders[] = $allowedHeader; + } + } + + /** + * Rule中增加一条exposeHeader + * + * @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; + } + + /** + * 得到AllowedHeaders列表 + * + * @return string[] + */ + public function getAllowedHeaders() + { + return $this->allowedHeaders; + } + + /** + * 得到AllowedOrigins列表 + * + * @return string[] + */ + public function getAllowedOrigins() + { + return $this->allowedOrigins; + } + + /** + * 得到AllowedMethods列表 + * + * @return string[] + */ + public function getAllowedMethods() + { + return $this->allowedMethods; + } + + /** + * 得到ExposeHeaders列表 + * + * @return string[] + */ + public function getExposeHeaders() + { + return $this->exposeHeaders; + } + + /** + * 根据提供的xmlRule, 把this按照一定的规则插入到$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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelHistory.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelHistory.php new file mode 100755 index 0000000..6643444 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelHistory.php @@ -0,0 +1,34 @@ +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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelInfo.php new file mode 100755 index 0000000..0b5edfc --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelStatus.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/GetLiveChannelStatus.php new file mode 100755 index 0000000..2ee7a68 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleAction.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleAction.php new file mode 100755 index 0000000..5abd825 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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; + } + + /** + * appendToXml 把actions插入到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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleConfig.php new file mode 100755 index 0000000..fc4f575 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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; + } + + + /** + * 生成xml字符串 + * + * @return string + */ + public function serializeToXml() + { + + $xml = new \SimpleXMLElement(''); + foreach ($this->rules as $rule) { + $xmlRule = $xml->addChild('Rule'); + $rule->appendToXml($xmlRule); + } + return $xml->asXML(); + } + + /** + * + * 添加LifecycleRule + * + * @param LifecycleRule $lifecycleRule + * @throws OssException + */ + public function addRule($lifecycleRule) + { + if (!isset($lifecycleRule)) { + throw new OssException("lifecycleRule is null"); + } + $this->rules[] = $lifecycleRule; + } + + /** + * 将配置转换成字符串,便于用户查看 + * + * @return string + */ + public function __toString() + { + return $this->serializeToXml(); + } + + /** + * 得到所有的生命周期规则 + * + * @return LifecycleRule[] + */ + public function getRules() + { + return $this->rules; + } + + /** + * @var LifecycleRule[] + */ + private $rules; +} + + diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleRule.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleRule.php new file mode 100755 index 0000000..ec615b9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LifecycleRule.php @@ -0,0 +1,126 @@ +id; + } + + /** + * @param string $id 规则ID + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * 得到文件前缀 + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * 设置文件前缀 + * + * @param string $prefix 文件前缀 + */ + public function setPrefix($prefix) + { + $this->prefix = $prefix; + } + + /** + * Lifecycle规则的状态 + * + * @return string + */ + public function getStatus() + { + return $this->status; + } + + /** + * 设置Lifecycle规则状态 + * + * @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 规则ID + * @param string $prefix 文件前缀 + * @param string $status 规则状态,可选[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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ListMultipartUploadInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ListMultipartUploadInfo.php new file mode 100755 index 0000000..105d005 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ListPartsInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ListPartsInfo.php new file mode 100755 index 0000000..f1d10ee --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelConfig.php new file mode 100755 index 0000000..dadedc9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelHistory.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelHistory.php new file mode 100755 index 0000000..1c1fd4d --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelInfo.php new file mode 100755 index 0000000..c63ec54 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelListInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LiveChannelListInfo.php new file mode 100755 index 0000000..bb5093a --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LoggingConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/LoggingConfig.php new file mode 100755 index 0000000..978421a --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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; + } + } + + /** + * 序列化成xml字符串 + * + */ + 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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ObjectInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ObjectInfo.php new file mode 100755 index 0000000..2ae6c99 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ObjectInfo.php @@ -0,0 +1,93 @@ +key = $key; + $this->lastModified = $lastModified; + $this->eTag = $eTag; + $this->type = $type; + $this->size = $size; + $this->storageClass = $storageClass; + } + + /** + * @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; + } + + /** + * @return int + */ + public function getSize() + { + return $this->size; + } + + /** + * @return string + */ + public function getStorageClass() + { + return $this->storageClass; + } + + private $key = ""; + private $lastModified = ""; + private $eTag = ""; + private $type = ""; + private $size = 0; + private $storageClass = ""; +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ObjectListInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/ObjectListInfo.php new file mode 100755 index 0000000..dbe7c7a --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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; + } + + /** + * 返回ListObjects接口返回数据中的ObjectInfo列表 + * + * @return ObjectInfo[] + */ + public function getObjectList() + { + return $this->objectList; + } + + /** + * 返回ListObjects接口返回数据中的PrefixInfo列表 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/PartInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/PartInfo.php new file mode 100755 index 0000000..439a84d --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/PartInfo.php @@ -0,0 +1,63 @@ +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; + } + + /** + * @return int + */ + public function getSize() + { + return $this->size; + } + + private $partNumber = 0; + private $lastModified = ""; + private $eTag = ""; + private $size = 0; +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/PrefixInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/PrefixInfo.php new file mode 100755 index 0000000..e61eac4 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/RefererConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/RefererConfig.php new file mode 100755 index 0000000..1d7d975 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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); + } + } + + + /** + * 把RefererConfig序列化成xml + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/StorageCapacityConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/StorageCapacityConfig.php new file mode 100755 index 0000000..05e6332 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/StorageCapacityConfig.php @@ -0,0 +1,74 @@ +storageCapacity = $storageCapacity; + } + + /** + * Not implemented + */ + public function parseFromXml($strXml) + { + throw new OssException("Not implemented."); + } + + /** + * 把StorageCapacityConfig序列化成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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/UploadInfo.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/UploadInfo.php new file mode 100755 index 0000000..8eaa363 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/WebsiteConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/WebsiteConfig.php new file mode 100755 index 0000000..8ea08a0 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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); + } + } + + /** + * 把WebsiteConfig序列化成xml + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/XmlConfig.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/XmlConfig.php new file mode 100755 index 0000000..d353a22 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Model/XmlConfig.php @@ -0,0 +1,27 @@ +hostname = $this->checkEndpoint($endpoint, $isCName); + $this->accessKeyId = $accessKeyId; + $this->accessKeySecret = $accessKeySecret; + $this->securityToken = $securityToken; + $this->requestProxy = $requestProxy; + + self::checkEnv(); + } + + /** + * 列举用户所有的Bucket[GetService], Endpoint类型为cname不能进行此操作 + * + * @param array $options + * @throws OssException + * @return BucketListInfo + */ + 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; + $options[self::OSS_OBJECT] = '/'; + $response = $this->auth($options); + $result = new ListBucketsResult($response); + return $result->getData(); + } + + /** + * 创建bucket,默认创建的bucket的ACL是OssClient::OSS_ACL_TYPE_PRIVATE + * + * @param string $bucket + * @param string $acl + * @param array $options + * @param string $storageType + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_HEADERS] = array(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(); + } + + /** + * 删除bucket + * 如果Bucket不为空(Bucket中有Object,或者有分块上传的碎片),则Bucket无法删除, + * 必须删除Bucket中的所有Object以及碎片后,Bucket才能成功删除。 + * + * @param string $bucket + * @param array $options + * @return null + */ + 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; + $options[self::OSS_OBJECT] = '/'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 判断bucket是否存在 + * + * @param string $bucket + * @return bool + * @throws OssException + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new ExistResult($response); + return $result->getData(); + } + + /** + * 获取bucket所属的数据中心位置信息 + * + * @param string $bucket + * @param array $options + * @throws OssException + * @return string + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'location'; + $response = $this->auth($options); + $result = new GetLocationResult($response); + return $result->getData(); + } + + /** + * 获取Bucket的Meta信息 + * + * @param string $bucket + * @param array $options 具体参考SDK文档 + * @return array + */ + 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; + $options[self::OSS_OBJECT] = '/'; + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * 获取bucket的ACL配置情况 + * + * @param string $bucket + * @param array $options + * @throws OssException + * @return string + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new AclResult($response); + return $result->getData(); + } + + /** + * 设置bucket的ACL配置情况 + * + * @param string $bucket bucket名称 + * @param string $acl 读写权限,可选值 ['private', 'public-read', 'public-read-write'] + * @param array $options 可以为空 + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_HEADERS] = array(self::OSS_ACL => $acl); + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 获取object的ACL属性 + * + * @param string $bucket + * @param string $object + * @throws OssException + * @return string + */ + public function getObjectAcl($bucket, $object) + { + $options = array(); + $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(); + } + + /** + * 设置object的ACL属性 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param string $acl 读写权限,可选值 ['default', 'private', 'public-read', 'public-read-write'] + * @throws OssException + * @return null + */ + public function putObjectAcl($bucket, $object, $acl) + { + $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] = array(self::OSS_OBJECT_ACL => $acl); + $options[self::OSS_SUB_RESOURCE] = 'acl'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 获取Bucket的访问日志配置情况 + * + * @param string $bucket bucket名称 + * @param array $options 可以为空 + * @throws OssException + * @return LoggingConfig + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'logging'; + $response = $this->auth($options); + $result = new GetLoggingResult($response); + return $result->getData(); + } + + /** + * 开启Bucket访问日志记录功能,只有Bucket的所有者才能更改 + * + * @param string $bucket bucket名称 + * @param string $targetBucket 日志文件存放的bucket + * @param string $targetPrefix 日志的文件前缀 + * @param array $options 可以为空 + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 关闭bucket访问日志记录功能 + * + * @param string $bucket bucket名称 + * @param array $options 可以为空 + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'logging'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 将bucket设置成静态网站托管模式 + * + * @param string $bucket bucket名称 + * @param WebsiteConfig $websiteConfig + * @param array $options 可以为空 + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 获取bucket的静态网站托管状态 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return WebsiteConfig + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'website'; + $response = $this->auth($options); + $result = new GetWebsiteResult($response); + return $result->getData(); + } + + /** + * 关闭bucket的静态网站托管模式 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'website'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 在指定的bucket上设定一个跨域资源共享(CORS)的规则,如果原规则存在则覆盖原规则 + * + * @param string $bucket bucket名称 + * @param CorsConfig $corsConfig 跨域资源共享配置,具体规则参见SDK文档 + * @param array $options array + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 获取Bucket的CORS配置情况 + * + * @param string $bucket bucket名称 + * @param array $options 可以为空 + * @throws OssException + * @return CorsConfig + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'cors'; + $response = $this->auth($options); + $result = new GetCorsResult($response, __FUNCTION__); + return $result->getData(); + } + + /** + * 关闭指定Bucket对应的CORS功能并清空所有规则 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'cors'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 为指定Bucket增加CNAME绑定 + * + * @param string $bucket bucket名称 + * @param string $cname + * @param array $options + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'cname'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $cnameConfig = new CnameConfig(); + $cnameConfig->addCname($cname); + $options[self::OSS_CONTENT] = $cnameConfig->serializeToXml(); + $options[self::OSS_COMP] = 'add'; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 获取指定Bucket已绑定的CNAME列表 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return CnameConfig + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'cname'; + $response = $this->auth($options); + $result = new GetCnameResult($response); + return $result->getData(); + } + + /** + * 解除指定Bucket的CNAME绑定 + * + * @param string $bucket bucket名称 + * @param CnameConfig $cnameConfig + * @param array $options + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'cname'; + $options[self::OSS_CONTENT_TYPE] = 'application/xml'; + $cnameConfig = new CnameConfig(); + $cnameConfig->addCname($cname); + $options[self::OSS_CONTENT] = $cnameConfig->serializeToXml(); + $options[self::OSS_COMP] = 'delete'; + + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 为指定Bucket创建LiveChannel + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param LiveChannelConfig $channelConfig + * @param array $options + * @throws OssException + * @return LiveChannelInfo + */ + 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; + } + + /** + * 设置LiveChannel的status + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param string channelStatus $channelStatus 为enabled或disabled + * @param array $options + * @throws OssException + * @return null + */ + 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(); + } + + /** + * 获取LiveChannel信息 + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param array $options + * @throws OssException + * @return GetLiveChannelInfo + */ + 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(); + } + + /** + * 获取LiveChannel状态信息 + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param array $options + * @throws OssException + * @return GetLiveChannelStatus + */ + 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(); + } + + /** + *获取LiveChannel推流记录 + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param array $options + * @throws OssException + * @return GetLiveChannelHistory + */ + 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(); + } + + /** + *获取指定Bucket下的live channel列表 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return LiveChannelListInfo + */ + 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_OBJECT] = '/'; + $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; + } + + /** + * 为指定LiveChannel生成播放列表 + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param string $playlistName 指定生成的点播播放列表的名称,必须以“.m3u8”结尾 + * @param array $setTime startTime和EndTime以unix时间戳格式给定,跨度不能超过一天 + * @throws OssException + * @return null + */ + 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(); + } + + /** + * 删除指定Bucket的LiveChannel + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param array $options + * @throws OssException + * @return null + */ + 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(); + } + + /** + * 生成带签名的推流地址 + * + * @param string $bucket bucket名称 + * @param string channelName $channelName + * @param int timeout 设置超时时间,单位为秒 + * @param array $options + * @throws OssException + * @return 推流地址 + */ + 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; + $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->accessKeySecret, true)); + + $query_items[] = 'OSSAccessKeyId=' . rawurlencode($this->accessKeyId); + $query_items[] = 'Expires=' . rawurlencode($expires); + $query_items[] = 'Signature=' . rawurlencode($signature); + + return $proto . $hostname . '/live/' . $channelName . '?' . implode('&', $query_items); + } + + /** + * 检验跨域资源请求, 发送跨域请求之前会发送一个preflight请求(OPTIONS)并带上特定的来源域, + * HTTP方法和header信息等给OSS以决定是否发送真正的请求。 OSS可以通过putBucketCors接口 + * 来开启Bucket的CORS支持,开启CORS功能之后,OSS在收到浏览器preflight请求时会根据设定的 + * 规则评估是否允许本次请求 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param string $origin 请求来源域 + * @param string $request_method 表明实际请求中会使用的HTTP方法 + * @param string $request_headers 表明实际请求中会使用的除了简单头部之外的headers + * @param array $options + * @return array + * @throws OssException + * @link http://help.aliyun.com/document_detail/oss/api-reference/cors/OptionObject.html + */ + 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] = array( + self::OSS_OPTIONS_ORIGIN => $origin, + self::OSS_OPTIONS_REQUEST_HEADERS => $request_headers, + self::OSS_OPTIONS_REQUEST_METHOD => $request_method + ); + $response = $this->auth($options); + $result = new HeaderResult($response); + return $result->getData(); + } + + /** + * 设置Bucket的Lifecycle配置 + * + * @param string $bucket bucket名称 + * @param LifecycleConfig $lifecycleConfig Lifecycle配置类 + * @param array $options + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 获取Bucket的Lifecycle配置情况 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return LifecycleConfig + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; + $response = $this->auth($options); + $result = new GetLifecycleResult($response); + return $result->getData(); + } + + /** + * 删除指定Bucket的生命周期配置 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return null + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'lifecycle'; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 设置一个bucket的referer访问白名单和是否允许referer字段为空的请求访问 + * Bucket Referer防盗链具体见OSS防盗链 + * + * @param string $bucket bucket名称 + * @param RefererConfig $refererConfig + * @param array $options + * @return ResponseCore + * @throws null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 获取Bucket的Referer配置情况 + * Bucket Referer防盗链具体见OSS防盗链 + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return RefererConfig + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'referer'; + $response = $this->auth($options); + $result = new GetRefererResult($response); + return $result->getData(); + } + + /** + * 设置bucket的容量大小,单位GB + * 当bucket的容量大于设置的容量时,禁止继续写入 + * + * @param string $bucket bucket名称 + * @param int $storageCapacity + * @param array $options + * @return ResponseCore + * @throws null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 获取bucket的容量大小,单位GB + * + * @param string $bucket bucket名称 + * @param array $options + * @throws OssException + * @return int + */ + 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_OBJECT] = '/'; + $options[self::OSS_SUB_RESOURCE] = 'qos'; + $response = $this->auth($options); + $result = new GetStorageCapacityResult($response); + return $result->getData(); + } + + /** + * 获取bucket下的object列表 + * + * @param string $bucket + * @param array $options + * 其中options中的参数如下 + * $options = array( + * 'max-keys' => max-keys用于限定此次返回object的最大数,如果不设定,默认为100,max-keys取值不能大于1000。 + * 'prefix' => 限定返回的object key必须以prefix作为前缀。注意使用prefix查询时,返回的key中仍会包含prefix。 + * 'delimiter' => 是一个用于对Object名字进行分组的字符。所有名字包含指定的前缀且第一次出现delimiter字符之间的object作为一组元素 + * 'marker' => 用户设定结果从marker之后按字母排序的第一个开始返回。 + *) + * 其中 prefix,marker用来实现分页显示效果,参数的长度必须小于256字节。 + * @throws OssException + * @return ObjectListInfo + */ + 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; + $options[self::OSS_OBJECT] = '/'; + $options[self::OSS_HEADERS] = array( + 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] : '', + ); + $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 ListObjectsResult($response); + return $result->getData(); + } + + /** + * 创建虚拟目录 (本函数会在object名称后增加'/', 所以创建目录的object名称不需要'/'结尾,否则,目录名称会变成'//') + * + * 暂不开放此接口 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param array $options + * @return null + */ + 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(); + } + + /** + * 上传内存中的内容 + * + * @param string $bucket bucket名称 + * @param string $object objcet名称 + * @param string $content 上传的内容 + * @param array $options + * @return null + */ + 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(); + } + + /** + * 创建symlink + * @param string $bucket bucket名称 + * @param string $symlink symlink名称 + * @param string $targetObject 目标object名称 + * @param array $options + * @return null + */ + 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(); + } + + /** + * 获取symlink + *@param string $bucket bucket名称 + * @param string $symlink symlink名称 + * @return null + */ + public function getSymlink($bucket, $symlink) + { + $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(); + } + + /** + * 上传本地文件 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param string $file 本地文件路径 + * @param array $options + * @return null + * @throws OssException + */ + public function uploadFile($bucket, $object, $file, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + OssUtil::throwOssExceptionWithMessageIfEmpty($file, "file path is invalid"); + $file = OssUtil::encodePath($file); + if (!file_exists($file)) { + throw new OssException($file . " file does not exist"); + } + $options[self::OSS_FILE_UPLOAD] = $file; + $file_size = 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(); + } + + /** + * 追加上传内存中的内容 + * + * @param string $bucket bucket名称 + * @param string $object objcet名称 + * @param string $content 本次追加上传的内容 + * @param array $options + * @return int next append position + * @throws OssException + */ + 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(); + } + + /** + * 追加上传本地文件 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param string $file 追加上传的本地文件路径 + * @param array $options + * @return int next append position + * @throws OssException + */ + public function appendFile($bucket, $object, $file, $position, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + + OssUtil::throwOssExceptionWithMessageIfEmpty($file, "file path is invalid"); + $file = OssUtil::encodePath($file); + if (!file_exists($file)) { + throw new OssException($file . " file does not exist"); + } + $options[self::OSS_FILE_UPLOAD] = $file; + $file_size = 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(); + } + + /** + * 拷贝一个在OSS上已经存在的object成另外一个object + * + * @param string $fromBucket 源bucket名称 + * @param string $fromObject 源object名称 + * @param string $toBucket 目标bucket名称 + * @param string $toObject 目标object名称 + * @param array $options + * @return null + * @throws OssException + */ + 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; + if (isset($options[self::OSS_HEADERS])) { + $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE] = '/' . $fromBucket . '/' . $fromObject; + } else { + $options[self::OSS_HEADERS] = array(self::OSS_OBJECT_COPY_SOURCE => '/' . $fromBucket . '/' . $fromObject); + } + $response = $this->auth($options); + $result = new CopyObjectResult($response); + return $result->getData(); + } + + /** + * 获取Object的Meta信息 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param string $options 具体参考SDK文档 + * @return array + */ + 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(); + } + + /** + * 删除某个Object + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param array $options + * @return null + */ + 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(); + } + + /** + * 删除同一个Bucket中的多个Object + * + * @param string $bucket bucket名称 + * @param array $objects object列表 + * @param array $options + * @return ResponseCore + * @throws null + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 获得Object内容 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param array $options 该参数中必须设置ALIOSS::OSS_FILE_DOWNLOAD,ALIOSS::OSS_RANGE可选,可以根据实际情况设置;如果不设置,默认会下载全部内容 + * @return string + */ + 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(); + } + + /** + * 检测Object是否存在 + * 通过获取Object的Meta信息来判断Object是否存在, 用户需要自行解析ResponseCore判断object是否存在 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param array $options + * @return bool + */ + 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(); + } + + /** + * 针对Archive类型的Object读取 + * 需要使用Restore操作让服务端执行解冻任务 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @return null + * @throws OssException + */ + 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; + $response = $this->auth($options); + $result = new PutSetDeleteResult($response); + return $result->getData(); + } + + /** + * 获取分片大小,根据用户提供的part_size,重新计算一个更合理的partsize + * + * @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; + } + + /** + * 计算文件可以分成多少个part,以及每个part的长度以及起始位置 + * 方法必须在 中调用 + * + * @param integer $file_size 文件大小 + * @param integer $partSize part大小,默认5M + * @return array An array 包含 key-value 键值对. Key 为 `seekTo` 和 `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; + } + + /** + * 初始化multi-part upload + * + * @param string $bucket Bucket名称 + * @param string $object Object名称 + * @param array $options Key-Value数组 + * @throws OssException + * @return string 返回uploadid + */ + 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(); + } + + /** + * 分片上传的块上传接口 + * + * @param string $bucket Bucket名称 + * @param string $object Object名称 + * @param string $uploadId + * @param array $options Key-Value数组 + * @return string eTag + * @throws OssException + */ + 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(); + } + + /** + * 获取已成功上传的part + * + * @param string $bucket Bucket名称 + * @param string $object Object名称 + * @param string $uploadId uploadId + * @param array $options Key-Value数组 + * @return ListPartsInfo + * @throws OssException + */ + 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(); + } + + /** + * 中止进行一半的分片上传操作 + * + * @param string $bucket Bucket名称 + * @param string $object Object名称 + * @param string $uploadId uploadId + * @param array $options Key-Value数组 + * @return null + * @throws OssException + */ + 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(); + } + + /** + * 在将所有数据Part都上传完成后,调用此接口完成本次分块上传 + * + * @param string $bucket Bucket名称 + * @param string $object Object名称 + * @param string $uploadId uploadId + * @param array $listParts array( array("PartNumber"=> int, "ETag"=>string)) + * @param array $options Key-Value数组 + * @throws OssException + * @return null + */ + 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)) { + throw new OssException("listParts must be array type"); + } + $options[self::OSS_CONTENT] = OssUtil::createCompleteMultipartUploadXmlBody($listParts); + $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(); + } + + /** + * 罗列出所有执行中的Multipart Upload事件,即已经被初始化的Multipart Upload但是未被 + * Complete或者Abort的Multipart Upload事件 + * + * @param string $bucket bucket + * @param array $options 关联数组 + * @throws OssException + * @return ListMultipartUploadInfo + */ + 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_OBJECT] = '/'; + $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(); + } + + /** + * 从一个已存在的Object中拷贝数据来上传一个Part + * + * @param string $fromBucket 源bucket名称 + * @param string $fromObject 源object名称 + * @param string $toBucket 目标bucket名称 + * @param string $toObject 目标object名称 + * @param int $partNumber 分块上传的块id + * @param string $uploadId 初始化multipart upload返回的uploadid + * @param array $options Key-Value数组 + * @return null + * @throws OssException + */ + public function uploadPartCopy($fromBucket, $fromObject, $toBucket, $toObject, $partNumber, $uploadId, $options = NULL) + { + $this->precheckCommon($fromBucket, $fromObject, $options); + $this->precheckCommon($toBucket, $toObject, $options); + + //如果没有设置$options['isFullCopy'],则需要强制判断copy的起止位置 + $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(); + } + + $options[self::OSS_HEADERS][self::OSS_OBJECT_COPY_SOURCE] = '/' . $fromBucket . '/' . $fromObject; + $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(); + } + + /** + * multipart上传统一封装,从初始化到完成multipart,以及出错后中止动作 + * + * @param string $bucket bucket名称 + * @param string $object object名称 + * @param string $file 需要上传的本地文件的路径 + * @param array $options Key-Value数组 + * @return null + * @throws OssException + */ + 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 = OssUtil::encodePath($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 = 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__ . '().'); + } + // 处理partSize + 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); + // 如果上传的文件小于partSize,则直接使用普通方式上传 + if ($upload_file_size < $options[self::OSS_PART_SIZE] && !isset($options[self::OSS_UPLOAD_ID])) { + return $this->uploadFile($bucket, $object, $uploadFile, $options); + } + + // 初始化multipart + if (isset($options[self::OSS_UPLOAD_ID])) { + $uploadId = $options[self::OSS_UPLOAD_ID]; + } else { + // 初始化 + $uploadId = $this->initiateMultipartUpload($bucket, $object, $options); + } + + // 获取的分片 + $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, + ); + } + return $this->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts); + } + + /** + * 上传本地目录内的文件或者目录到指定bucket的指定prefix的object中 + * + * @param string $bucket bucket名称 + * @param string $prefix 需要上传到的object的key前缀,可以理解成bucket中的子目录,结尾不能是'/',接口中会补充'/' + * @param string $localDirectory 需要上传的本地目录 + * @param string $exclude 需要排除的目录 + * @param bool $recursive 是否递归的上传localDirectory下的子目录内容 + * @param bool $checkMd5 + * @return array 返回两个列表 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 = OssUtil::encodePath($directory); + //判断是否目录 + 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, + ); + $realObject = (!empty($prefix) ? $prefix . '/' : '') . $item['file']; + + try { + $this->multiuploadFile($bucket, $realObject, $item['path'], $options); + $retArray["succeededList"][] = $realObject; + } catch (OssException $e) { + $retArray["failedList"][$realObject] = $e->getMessage(); + } + } + return $retArray; + } + + /** + * 支持生成get和put签名, 用户可以生成一个具有一定有效期的 + * 签名过的url + * + * @param string $bucket + * @param string $object + * @param int $timeout + * @param string $method + * @param array $options Key-Value数组 + * @return string + * @throws OssException + */ + public function signUrl($bucket, $object, $timeout = 60, $method = self::OSS_HTTP_GET, $options = NULL) + { + $this->precheckCommon($bucket, $object, $options); + //method + if (self::OSS_HTTP_GET !== $method && self::OSS_HTTP_PUT !== $method) { + throw new OssException("method is invalid"); + } + $options[self::OSS_BUCKET] = $bucket; + $options[self::OSS_OBJECT] = $object; + $options[self::OSS_METHOD] = $method; + if (!isset($options[self::OSS_CONTENT_TYPE])) { + $options[self::OSS_CONTENT_TYPE] = ''; + } + $timeout = time() + $timeout; + $options[self::OSS_PREAUTH] = $timeout; + $options[self::OSS_DATE] = $timeout; + $this->setSignStsInUrl(true); + return $this->auth($options); + } + + /** + * 检测options参数 + * + * @param array $options + * @throws OssException + */ + private function precheckOptions(&$options) + { + OssUtil::validateOptions($options); + if (!$options) { + $options = array(); + } + } + + /** + * 校验bucket参数 + * + * @param string $bucket + * @param string $errMsg + * @throws OssException + */ + private function precheckBucket($bucket, $errMsg = 'bucket is not allowed empty') + { + OssUtil::throwOssExceptionWithMessageIfEmpty($bucket, $errMsg); + } + + /** + * 校验object参数 + * + * @param string $object + * @throws OssException + */ + private function precheckObject($object) + { + OssUtil::throwOssExceptionWithMessageIfEmpty($object, "object name is empty"); + } + + /** + * 校验option restore + * + * @param string $restore + * @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; + default: + break; + } + } + throw new OssException('storage name is invalid'); + } + + /** + * 校验bucket,options参数 + * + * @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); + } + + /** + * 参数校验 + * + * @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 . '().'); + } + } + + /** + * 检测md5 + * + * @param array $options + * @return bool|null + */ + private function isCheckMD5($options) + { + return $this->getValue($options, self::OSS_CHECK_MD5, false, true, true); + } + + /** + * 获取value + * + * @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; + } + + /** + * 获取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; + } + + /** + * 验证并且执行请求,按照OSS Api协议,执行操作 + * + * @param array $options + * @return ResponseCore + * @throws OssException + * @throws RequestCore_Exception + */ + private function auth($options) + { + OssUtil::validateOptions($options); + //验证bucket,list_bucket时不需要验证 + $this->authPrecheckBucket($options); + //验证object + $this->authPrecheckObject($options); + //Object名称的编码必须是utf8 + $this->authPrecheckObjectEncoding($options); + //验证ACL + $this->authPrecheckAcl($options); + // 获得当次请求使用的协议头,是https还是http + $scheme = $this->useSSL ? 'https://' : 'http://'; + // 获得当次请求使用的hostname,如果是公共域名或者专有域名,bucket拼在前面构成三级域名 + $hostname = $this->generateHostname($options[self::OSS_BUCKET]); + $string_to_sign = ''; + $headers = $this->generateHeaders($options, $hostname); + $signable_query_string_params = $this->generateSignableQueryStringParam($options); + $signable_query_string = OssUtil::toQueryString($signable_query_string_params); + $resource_uri = $this->generateResourceUri($options); + //生成请求URL + $conjunction = '?'; + $non_signable_resource = ''; + if (isset($options[self::OSS_SUB_RESOURCE])) { + $conjunction = '&'; + } + if ($signable_query_string !== '') { + $signable_query_string = $conjunction . $signable_query_string; + $conjunction = '&'; + } + $query_string = $this->generateQueryString($options); + if ($query_string !== '') { + $non_signable_resource .= $conjunction . $query_string; + $conjunction = '&'; + } + $this->requestUrl = $scheme . $hostname . $resource_uri . $signable_query_string . $non_signable_resource; + + //创建请求 + $request = new RequestCore($this->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]); + $string_to_sign .= $options[self::OSS_METHOD] . "\n"; + } + + if (isset($options[self::OSS_CONTENT])) { + $request->set_body($options[self::OSS_CONTENT]); + if ($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] = ''; + } + + uksort($headers, 'strnatcasecmp'); + + foreach ($headers as $header_key => $header_value) { + $header_value = str_replace(array("\r", "\n"), '', $header_value); + if ($header_value !== '' || $header_key === self::OSS_ACCEPT_ENCODING) { + $request->add_header($header_key, $header_value); + } + + if ( + strtolower($header_key) === 'content-md5' || + strtolower($header_key) === 'content-type' || + strtolower($header_key) === 'date' || + (isset($options['self::OSS_PREAUTH']) && (integer)$options['self::OSS_PREAUTH'] > 0) + ) { + $string_to_sign .= $header_value . "\n"; + } elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX) { + $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n"; + } + } + // 生成 signable_resource + $signable_resource = $this->generateSignableResource($options); + $string_to_sign .= rawurldecode($signable_resource) . urldecode($signable_query_string); + + //对?后面的要签名的string字母序排序 + $string_to_sign_ordered = $this->stringToSignSorted($string_to_sign); + + $signature = base64_encode(hash_hmac('sha1', $string_to_sign_ordered, $this->accessKeySecret, true)); + $request->add_header('Authorization', 'OSS ' . $this->accessKeyId . ':' . $signature); + + if (isset($options[self::OSS_PREAUTH]) && (integer)$options[self::OSS_PREAUTH] > 0) { + $signed_url = $this->requestUrl . $conjunction . self::OSS_URL_ACCESS_KEY_ID . '=' . rawurlencode($this->accessKeyId) . '&' . self::OSS_URL_EXPIRES . '=' . $options[self::OSS_PREAUTH] . '&' . self::OSS_URL_SIGNATURE . '=' . rawurlencode($signature); + return $signed_url; + } elseif (isset($options[self::OSS_PREAUTH])) { + return $this->requestUrl; + } + + 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'] = $this->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) { + //设置休眠 + $delay = (integer)(pow(4, $this->redirects) * 100000); + usleep($delay); + $this->redirects++; + $data = $this->auth($options); + } + } + + $this->redirects = 0; + return $data; + } + + /** + * 设置最大尝试次数 + * + * @param int $maxRetries + * @return void + */ + public function setMaxTries($maxRetries = 3) + { + $this->maxRetries = $maxRetries; + } + + /** + * 获取最大尝试次数 + * + * @return int + */ + public function getMaxRetries() + { + return $this->maxRetries; + } + + /** + * 打开sts enable标志,使用户构造函数中传入的$sts生效 + * + * @param boolean $enable + */ + public function setSignStsInUrl($enable) + { + $this->enableStsInUrl = $enable; + } + + /** + * @return boolean + */ + public function isUseSSL() + { + return $this->useSSL; + } + + /** + * @param boolean $useSSL + */ + public function setUseSSL($useSSL) + { + $this->useSSL = $useSSL; + } + + /** + * 检查bucket名称格式是否正确,如果非法抛出异常 + * + * @param $options + * @throws OssException + */ + private function authPrecheckBucket($options) + { + if (!(('/' == $options[self::OSS_OBJECT]) && ('' == $options[self::OSS_BUCKET]) && ('GET' == $options[self::OSS_METHOD])) && !OssUtil::validateBucket($options[self::OSS_BUCKET])) { + throw new OssException('"' . $options[self::OSS_BUCKET] . '"' . 'bucket name is invalid'); + } + } + + /** + * + * 检查object名称格式是否正确,如果非法抛出异常 + * + * @param $options + * @throws OssException + */ + private function authPrecheckObject($options) + { + if (isset($options[self::OSS_OBJECT]) && $options[self::OSS_OBJECT] === '/') { + return; + } + + if (isset($options[self::OSS_OBJECT]) && !OssUtil::validateObject($options[self::OSS_OBJECT])) { + throw new OssException('"' . $options[self::OSS_OBJECT] . '"' . ' object name is invalid'); + } + } + + /** + * 检查object的编码,如果是gbk或者gb2312则尝试将其转化为utf8编码 + * + * @param mixed $options 参数 + */ + private function authPrecheckObjectEncoding(&$options) + { + $tmp_object = $options[self::OSS_OBJECT]; + try { + if (OssUtil::isGb2312($options[self::OSS_OBJECT])) { + $options[self::OSS_OBJECT] = iconv('GB2312', "UTF-8//IGNORE", $options[self::OSS_OBJECT]); + } elseif (OssUtil::checkChar($options[self::OSS_OBJECT], true)) { + $options[self::OSS_OBJECT] = iconv('GBK', "UTF-8//IGNORE", $options[self::OSS_OBJECT]); + } + } catch (\Exception $e) { + try { + $tmp_object = iconv(mb_detect_encoding($tmp_object), "UTF-8", $tmp_object); + } catch (\Exception $e) { + } + } + $options[self::OSS_OBJECT] = $tmp_object; + } + + /** + * 检查ACL是否是预定义中三种之一,如果不是抛出异常 + * + * @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)'); + } + } + } + + /** + * 获得档次请求使用的域名 + * bucket在前的三级域名,或者二级域名,如果是cname或者ip的话,则是二级域名 + * + * @param $bucket + * @return string 剥掉协议头的域名 + */ + private function generateHostname($bucket) + { + if ($this->hostType === self::OSS_HOST_TYPE_IP) { + $hostname = $this->hostname; + } elseif ($this->hostType === self::OSS_HOST_TYPE_CNAME) { + $hostname = $this->hostname; + } else { + // 专有域或者官网endpoint + $hostname = ($bucket == '') ? $this->hostname : ($bucket . '.') . $this->hostname; + } + return $hostname; + } + + /** + * 获得当次请求的资源定位字段 + * + * @param $options + * @return string 资源定位字段 + */ + private function generateResourceUri($options) + { + $resource_uri = ""; + + // resource_uri + bucket + if (isset($options[self::OSS_BUCKET]) && '' !== $options[self::OSS_BUCKET]) { + if ($this->hostType === self::OSS_HOST_TYPE_IP) { + $resource_uri = '/' . $options[self::OSS_BUCKET]; + } + } + + // resource_uri + object + if (isset($options[self::OSS_OBJECT]) && '/' !== $options[self::OSS_OBJECT]) { + $resource_uri .= '/' . str_replace(array('%2F', '%25'), array('/', '%'), rawurlencode($options[self::OSS_OBJECT])); + } + + // resource_uri + sub_resource + $conjunction = '?'; + if (isset($options[self::OSS_SUB_RESOURCE])) { + $resource_uri .= $conjunction . $options[self::OSS_SUB_RESOURCE]; + } + return $resource_uri; + } + + /** + * 生成signalbe_query_string_param, array类型 + * + * @param array $options + * @return array + */ + private function generateSignableQueryStringParam($options) + { + $signableQueryStringParams = array(); + $signableList = 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, + ); + + foreach ($signableList as $item) { + if (isset($options[$item])) { + $signableQueryStringParams[$item] = $options[$item]; + } + } + + if ($this->enableStsInUrl && (!is_null($this->securityToken))) { + $signableQueryStringParams["security-token"] = $this->securityToken; + } + + return $signableQueryStringParams; + } + + /** + * 生成用于签名resource段 + * + * @param mixed $options + * @return string + */ + private function generateSignableResource($options) + { + $signableResource = ""; + $signableResource .= '/'; + if (isset($options[self::OSS_BUCKET]) && '' !== $options[self::OSS_BUCKET]) { + $signableResource .= $options[self::OSS_BUCKET]; + // 如果操作没有Object操作的话,这里最后是否有斜线有个trick,ip的域名下,不需要加'/', 否则需要加'/' + if ($options[self::OSS_OBJECT] == '/') { + if ($this->hostType !== self::OSS_HOST_TYPE_IP) { + $signableResource .= "/"; + } + } + } + //signable_resource + object + if (isset($options[self::OSS_OBJECT]) && '/' !== $options[self::OSS_OBJECT]) { + $signableResource .= '/' . str_replace(array('%2F', '%25'), array('/', '%'), rawurlencode($options[self::OSS_OBJECT])); + } + if (isset($options[self::OSS_SUB_RESOURCE])) { + $signableResource .= '?' . $options[self::OSS_SUB_RESOURCE]; + } + return $signableResource; + } + + /** + * 生成query_string + * + * @param mixed $options + * @return string + */ + private function generateQueryString($options) + { + //请求参数 + $queryStringParams = array(); + if (isset($options[self::OSS_QUERY_STRING])) { + $queryStringParams = array_merge($queryStringParams, $options[self::OSS_QUERY_STRING]); + } + return OssUtil::toQueryString($queryStringParams); + } + + private function stringToSignSorted($string_to_sign) + { + $queryStringSorted = ''; + $explodeResult = explode('?', $string_to_sign); + $index = count($explodeResult); + if ($index === 1) + return $string_to_sign; + + $queryStringParams = explode('&', $explodeResult[$index - 1]); + sort($queryStringParams); + + foreach($queryStringParams as $params) + { + $queryStringSorted .= $params . '&'; + } + + $queryStringSorted = substr($queryStringSorted, 0, -1); + + return $explodeResult[0] . '?' . $queryStringSorted; + } + + /** + * 初始化headers + * + * @param mixed $options + * @param string $hostname hostname + * @return array + */ + private function generateHeaders($options, $hostname) + { + $headers = array( + self::OSS_CONTENT_MD5 => '', + self::OSS_CONTENT_TYPE => isset($options[self::OSS_CONTENT_TYPE]) ? $options[self::OSS_CONTENT_TYPE] : self::DEFAULT_CONTENT_TYPE, + self::OSS_DATE => isset($options[self::OSS_DATE]) ? $options[self::OSS_DATE] : gmdate('D, d M Y H:i:s \G\M\T'), + self::OSS_HOST => $hostname, + ); + if (isset($options[self::OSS_CONTENT_MD5])) { + $headers[self::OSS_CONTENT_MD5] = $options[self::OSS_CONTENT_MD5]; + } + + //添加stsSecurityToken + if ((!is_null($this->securityToken)) && (!$this->enableStsInUrl)) { + $headers[self::OSS_SECURITY_TOKEN] = $this->securityToken; + } + //合并HTTP headers + if (isset($options[self::OSS_HEADERS])) { + $headers = array_merge($headers, $options[self::OSS_HEADERS]); + } + return $headers; + } + + /** + * 生成请求用的UserAgent + * + * @return string + */ + private function generateUserAgent() + { + return self::OSS_NAME . "/" . self::OSS_VERSION . " (" . php_uname('s') . "/" . php_uname('r') . "/" . php_uname('m') . ";" . PHP_VERSION . ")"; + } + + /** + * 检查endpoint的种类 + * 如有有协议头,剥去协议头 + * 并且根据参数 is_cname 和endpoint本身,判定域名类型,是ip,cname,还是专有域或者官网域名 + * + * @param string $endpoint + * @param boolean $isCName + * @return string 剥掉协议头的域名 + */ + 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; + } + + 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; + } + + /** + * 用来检查sdk所以来的扩展是否打开 + * + * @throws OssException + */ + public static function checkEnv() + { + if (function_exists('get_loaded_extensions')) { + //检测curl扩展 + $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.'); + } + } + + /** + //* 设置http库的请求超时时间,单位秒 + * + * @param int $timeout + */ + public function setTimeout($timeout) + { + $this->timeout = $timeout; + } + + /** + * 设置http库的连接超时时间,单位秒 + * + * @param int $connectTimeout + */ + public function setConnectTimeout($connectTimeout) + { + $this->connectTimeout = $connectTimeout; + } + + // 生命周期相关常量 + const OSS_LIFECYCLE_EXPIRATION = "Expiration"; + const OSS_LIFECYCLE_TIMING_DAYS = "Days"; + const OSS_LIFECYCLE_TIMING_DATE = "Date"; + //OSS 内部常量 + const OSS_BUCKET = 'bucket'; + const OSS_OBJECT = 'object'; + const OSS_HEADERS = OssUtil::OSS_HEADERS; + 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_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_PREAUTH = 'preauth'; + 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 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'; + + //私有URL变量 + const OSS_URL_ACCESS_KEY_ID = 'OSSAccessKeyId'; + const OSS_URL_EXPIRES = 'Expires'; + const OSS_URL_SIGNATURE = 'Signature'; + //HTTP方法 + 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'; + //其他常量 + 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"; + //支持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_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 + //OSS ACL数组 + static $OSS_ACL_TYPES = array( + self::OSS_ACL_TYPE_PRIVATE, + self::OSS_ACL_TYPE_PUBLIC_READ, + self::OSS_ACL_TYPE_PUBLIC_READ_WRITE + ); + // OssClient版本信息 + const OSS_NAME = "aliyun-sdk-php"; + const OSS_VERSION = "2.3.0"; + const OSS_BUILD = "20180105"; + 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'; + + //是否使用ssl + private $useSSL = false; + private $maxRetries = 3; + private $redirects = 0; + + // 用户提供的域名类型,有四种 OSS_HOST_TYPE_NORMAL, OSS_HOST_TYPE_IP, OSS_HOST_TYPE_SPECIAL, OSS_HOST_TYPE_CNAME + private $hostType = self::OSS_HOST_TYPE_NORMAL; + private $requestUrl; + private $accessKeyId; + private $accessKeySecret; + private $hostname; + private $securityToken; + private $requestProxy = null; + private $enableStsInUrl = false; + private $timeout = 0; + private $connectTimeout = 0; +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/AclResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/AclResult.php new file mode 100755 index 0000000..6da0860 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/AclResult.php @@ -0,0 +1,32 @@ +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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/AppendResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/AppendResult.php new file mode 100755 index 0000000..433c03e --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/BodyResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/BodyResult.php new file mode 100755 index 0000000..44ba15e --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/BodyResult.php @@ -0,0 +1,19 @@ +rawResponse->body) ? "" : $this->rawResponse->body; + } +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/CallbackResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/CallbackResult.php new file mode 100755 index 0000000..514e985 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/CopyObjectResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/CopyObjectResult.php new file mode 100755 index 0000000..498723e --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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 $result; + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/DeleteObjectsResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/DeleteObjectsResult.php new file mode 100755 index 0000000..dc373b8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ExistResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ExistResult.php new file mode 100755 index 0000000..f7aa287 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ExistResult.php @@ -0,0 +1,35 @@ +rawResponse->status) === 200 ? true : false; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK, 判断是否存在的接口,404也认为是一种 + * 有效响应 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetCnameResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetCnameResult.php new file mode 100755 index 0000000..eed01f9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetCorsResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetCorsResult.php new file mode 100755 index 0000000..a51afe2 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetCorsResult.php @@ -0,0 +1,35 @@ +rawResponse->body; + $config = new CorsConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种 + * 有效响应 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLifecycleResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLifecycleResult.php new file mode 100755 index 0000000..6b440c3 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLifecycleResult.php @@ -0,0 +1,41 @@ +rawResponse->body; + $config = new LifecycleConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种 + * 有效响应 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelHistoryResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelHistoryResult.php new file mode 100755 index 0000000..202a668 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelHistoryResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $channelList = new GetLiveChannelHistory(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelInfoResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelInfoResult.php new file mode 100755 index 0000000..d5a9005 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelInfoResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $channelList = new GetLiveChannelInfo(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelStatusResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelStatusResult.php new file mode 100755 index 0000000..6b8a60f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLiveChannelStatusResult.php @@ -0,0 +1,19 @@ +rawResponse->body; + $channelList = new GetLiveChannelStatus(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLocationResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLocationResult.php new file mode 100755 index 0000000..71c4c96 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLoggingResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLoggingResult.php new file mode 100755 index 0000000..72fc3ae --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetLoggingResult.php @@ -0,0 +1,41 @@ +rawResponse->body; + $config = new LoggingConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种 + * 有效响应 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetRefererResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetRefererResult.php new file mode 100755 index 0000000..aee50d3 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetRefererResult.php @@ -0,0 +1,41 @@ +rawResponse->body; + $config = new RefererConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种 + * 有效响应 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetStorageCapacityResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetStorageCapacityResult.php new file mode 100755 index 0000000..84e4916 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetWebsiteResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetWebsiteResult.php new file mode 100755 index 0000000..3099172 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/GetWebsiteResult.php @@ -0,0 +1,40 @@ +rawResponse->body; + $config = new WebsiteConfig(); + $config->parseFromXml($content); + return $config; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种 + * 有效响应 + * + * @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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/HeaderResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/HeaderResult.php new file mode 100755 index 0000000..c9aae56 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/HeaderResult.php @@ -0,0 +1,23 @@ +rawResponse->header) ? array() : $this->rawResponse->header; + } + +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/InitiateMultipartUploadResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/InitiateMultipartUploadResult.php new file mode 100755 index 0000000..af985f2 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListBucketsResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListBucketsResult.php new file mode 100755 index 0000000..a58fb2d --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListBucketsResult.php @@ -0,0 +1,33 @@ +rawResponse->body; + $xml = new \SimpleXMLElement($content); + if (isset($xml->Buckets) && isset($xml->Buckets->Bucket)) { + foreach ($xml->Buckets->Bucket as $bucket) { + $bucketInfo = new BucketInfo(strval($bucket->Location), + strval($bucket->Name), + strval($bucket->CreationDate)); + $bucketList[] = $bucketInfo; + } + } + return new BucketListInfo($bucketList); + } +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListLiveChannelResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListLiveChannelResult.php new file mode 100755 index 0000000..1a6e2a4 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListLiveChannelResult.php @@ -0,0 +1,16 @@ +rawResponse->body; + $channelList = new LiveChannelListInfo(); + $channelList->parseFromXml($content); + return $channelList; + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListMultipartUploadResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListMultipartUploadResult.php new file mode 100755 index 0000000..bcb20bf --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListObjectsResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListObjectsResult.php new file mode 100755 index 0000000..fcf493d --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListObjectsResult.php @@ -0,0 +1,71 @@ +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) ? intval($content->Size) : 0; + $storageClass = isset($content->StorageClass) ? strval($content->StorageClass) : ""; + $retList[] = new ObjectInfo($key, $lastModified, $eTag, $type, $size, $storageClass); + } + } + 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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListPartsResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/ListPartsResult.php new file mode 100755 index 0000000..fd8a1b8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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) ? intval($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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/PutLiveChannelResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/PutLiveChannelResult.php new file mode 100755 index 0000000..dcac86b --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/PutLiveChannelResult.php @@ -0,0 +1,16 @@ +rawResponse->body; + $channel = new LiveChannelInfo(); + $channel->parseFromXml($content); + return $channel; + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/PutSetDeleteResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/PutSetDeleteResult.php new file mode 100755 index 0000000..97af003 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/PutSetDeleteResult.php @@ -0,0 +1,20 @@ + $this->rawResponse->body); + return array_merge($this->rawResponse->header, $body); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/Result.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/Result.php new file mode 100755 index 0000000..491256f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/Result.php @@ -0,0 +1,175 @@ +rawResponse = $response; + $this->parseResponse(); + } + + /** + * 获取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 ''; + } + } + + /** + * 得到返回数据,不同的请求返回数据格式不同 + * + * $return mixed + */ + public function getData() + { + return $this->parsedData; + } + + /** + * 由子类实现,不同的请求返回数据有不同的解析逻辑,由子类实现 + * + * @return mixed + */ + abstract protected function parseDataFromResponse(); + + /** + * 操作是否成功 + * + * @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); + } + } + + /** + * 尝试从body中获取错误Message + * + * @param $body + * @return string + */ + private function retrieveErrorMessage($body) + { + if (empty($body) || false === strpos($body, 'Message)) { + return strval($xml->Message); + } + return ''; + } + + /** + * 尝试从body中获取错误Code + * + * @param $body + * @return string + */ + private function retrieveErrorCode($body) + { + if (empty($body) || false === strpos($body, 'Code)) { + return strval($xml->Code); + } + return ''; + } + + /** + * 根据返回http状态码判断,[200-299]即认为是OK + * + * @return bool + */ + protected function isResponseOk() + { + $status = $this->rawResponse->status; + if ((int)(intval($status) / 100) == 2) { + return true; + } + return false; + } + + /** + * 返回原始的返回数据 + * + * @return ResponseCore + */ + public function getRawResponse() + { + return $this->rawResponse; + } + + /** + * 标示请求是否成功 + */ + protected $isOk = false; + /** + * 由子类解析过的数据 + */ + protected $parsedData = null; + /** + * 存放auth函数返回的原始Response + * + * @var ResponseCore + */ + protected $rawResponse; +} \ No newline at end of file diff --git a/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/SymlinkResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/SymlinkResult.php new file mode 100755 index 0000000..9c6d861 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/UploadPartResult.php b/aliyun-oss-php-sdk-2.3.0/src/OSS/Result/UploadPartResult.php new file mode 100755 index 0000000..c6b66d4 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/src/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/aliyun-oss-php-sdk-2.3.0/test.php b/aliyun-oss-php-sdk-2.3.0/test.php new file mode 100644 index 0000000..fd2dbc9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/test.php @@ -0,0 +1,9 @@ + + + + 00220120222 + user_example + + + public-read + + +BBBB; + + private $invalidXml = << + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new AclResult($response); + $this->assertEquals("public-read", $result->getData()); + } + + public function testParseNullXml() + { + $response = new ResponseCore(array(), "", 200); + try { + new AclResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('body is null', $e->getMessage()); + } + } + + public function testParseInvalidXml() + { + $response = new ResponseCore(array(), $this->invalidXml, 200); + try { + new AclResult($response); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals("xml format exception", $e->getMessage()); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BodyResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BodyResultTest.php new file mode 100755 index 0000000..af13d4d --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BodyResultTest.php @@ -0,0 +1,26 @@ +assertTrue($result->isOK()); + $this->assertEquals($result->getData(), "hi"); + } + + public function testParseInvalid404() + { + $response = new ResponseCore(array(), null, 200); + $result = new BodyResult($response); + $this->assertTrue($result->isOK()); + $this->assertEquals($result->getData(), ""); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketCnameTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketCnameTest.php new file mode 100755 index 0000000..87c9e54 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketCnameTest.php @@ -0,0 +1,77 @@ +client = Common::getOssClient(); + $this->bucketName = 'php-sdk-test-bucket-' . strval(rand(0, 10000)); + $this->client->createBucket($this->bucketName); + } + + public function tearDown() + { + $this->client->deleteBucket($this->bucketName); + } + + public function testBucketWithoutCname() + { + $cnameConfig = $this->client->getBucketCname($this->bucketName); + $this->assertEquals(0, count($cnameConfig->getCnames())); + } + + public function testAddCname() + { + $this->client->addBucketCname($this->bucketName, 'www.baidu.com'); + $this->client->addBucketCname($this->bucketName, 'www.qq.com'); + + $ret = $this->client->getBucketCname($this->bucketName); + $this->assertEquals(2, count($ret->getCnames())); + + // add another 2 cnames + $this->client->addBucketCname($this->bucketName, 'www.sina.com.cn'); + $this->client->addBucketCname($this->bucketName, 'www.iqiyi.com'); + + $ret = $this->client->getBucketCname($this->bucketName); + $cnames = $ret->getCnames(); + $cnameList = array(); + + foreach ($cnames as $c) { + $cnameList[] = $c['Domain']; + } + $should = array( + 'www.baidu.com', + 'www.qq.com', + 'www.sina.com.cn', + 'www.iqiyi.com' + ); + $this->assertEquals(4, count($cnames)); + $this->assertEquals(sort($should), sort($cnameList)); + } + + public function testDeleteCname() + { + $this->client->addBucketCname($this->bucketName, 'www.baidu.com'); + $this->client->addBucketCname($this->bucketName, 'www.qq.com'); + + $ret = $this->client->getBucketCname($this->bucketName); + $this->assertEquals(2, count($ret->getCnames())); + + // delete one cname + $this->client->deleteBucketCname($this->bucketName, 'www.baidu.com'); + + $ret = $this->client->getBucketCname($this->bucketName); + $this->assertEquals(1, count($ret->getCnames())); + $cnames = $ret->getCnames(); + $this->assertEquals('www.qq.com', $cnames[0]['Domain']); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketInfoTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketInfoTest.php new file mode 100755 index 0000000..80fa25c --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketInfoTest.php @@ -0,0 +1,21 @@ +assertNotNull($bucketInfo); + $this->assertEquals('cn-beijing', $bucketInfo->getLocation()); + $this->assertEquals('name', $bucketInfo->getName()); + $this->assertEquals('today', $bucketInfo->getCreateDate()); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketLiveChannelTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketLiveChannelTest.php new file mode 100755 index 0000000..bed68b0 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/BucketLiveChannelTest.php @@ -0,0 +1,283 @@ +client = Common::getOssClient(); + $this->bucketName = 'php-sdk-test-rtmp-bucket-name-' . strval(rand(0, 10000)); + $this->client->createBucket($this->bucketName); + Common::waitMetaSync(); + } + + public function tearDown() + { + ////to delete created bucket + //1. delele live channel + $list = $this->client->listBucketLiveChannels($this->bucketName); + if (count($list->getChannelList()) != 0) + { + foreach($list->getChannelList() as $list) + { + $this->client->deleteBucketLiveChannel($this->bucketName, $list->getName()); + } + } + //2. delete exsited object + $prefix = 'live-test/'; + $delimiter = '/'; + $nextMarker = ''; + $maxkeys = 1000; + $options = array( + 'delimiter' => $delimiter, + 'prefix' => $prefix, + 'max-keys' => $maxkeys, + 'marker' => $nextMarker, + ); + + try { + $listObjectInfo = $this->client->listObjects($this->bucketName, $options); + } catch (OssException $e) { + printf($e->getMessage() . "\n"); + return; + } + + $objectList = $listObjectInfo->getObjectList(); // 文件列表 + if (!empty($objectList)) + { + foreach($objectList as $objectInfo) + $this->client->deleteObject($this->bucketName, $objectInfo->getKey()); + } + //3. delete the bucket + $this->client->deleteBucket($this->bucketName); + } + + public function testPutLiveChannel() + { + $config = new LiveChannelConfig(array( + 'description' => 'live channel 1', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $info = $this->client->putBucketLiveChannel($this->bucketName, 'live-1', $config); + $this->client->deleteBucketLiveChannel($this->bucketName, 'live-1'); + + $this->assertEquals('live-1', $info->getName()); + $this->assertEquals('live channel 1', $info->getDescription()); + $this->assertEquals(1, count($info->getPublishUrls())); + $this->assertEquals(1, count($info->getPlayUrls())); + } + + public function testPutLiveChannelWithDefaultParams() + { + $config = new LiveChannelConfig(array( + 'description' => 'live channel 1', + 'type' => 'HLS', + )); + $info = $this->client->putBucketLiveChannel($this->bucketName, 'live-1', $config); + $this->client->deleteBucketLiveChannel($this->bucketName, 'live-1'); + + $this->assertEquals('live-1', $info->getName()); + $this->assertEquals('live channel 1', $info->getDescription()); + $this->assertEquals(1, count($info->getPublishUrls())); + $this->assertEquals(1, count($info->getPlayUrls())); + } + + public function testListLiveChannels() + { + $config = new LiveChannelConfig(array( + 'description' => 'live channel 1', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $this->client->putBucketLiveChannel($this->bucketName, 'live-1', $config); + + $config = new LiveChannelConfig(array( + 'description' => 'live channel 2', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $this->client->putBucketLiveChannel($this->bucketName, 'live-2', $config); + + $list = $this->client->listBucketLiveChannels($this->bucketName); + + $this->assertEquals($this->bucketName, $list->getBucketName()); + $this->assertEquals(false, $list->getIsTruncated()); + $channels = $list->getChannelList(); + $this->assertEquals(2, count($channels)); + + $chan1 = $channels[0]; + $this->assertEquals('live-1', $chan1->getName()); + $this->assertEquals('live channel 1', $chan1->getDescription()); + $this->assertEquals(1, count($chan1->getPublishUrls())); + $this->assertEquals(1, count($chan1->getPlayUrls())); + + $chan2 = $channels[1]; + $this->assertEquals('live-2', $chan2->getName()); + $this->assertEquals('live channel 2', $chan2->getDescription()); + $this->assertEquals(1, count($chan2->getPublishUrls())); + $this->assertEquals(1, count($chan2->getPlayUrls())); + + $list = $this->client->listBucketLiveChannels($this->bucketName, array( + 'prefix' => 'live-', + 'marker' => 'live-1', + 'max-keys' => 10 + )); + $channels = $list->getChannelList(); + $this->assertEquals(1, count($channels)); + $chan2 = $channels[0]; + $this->assertEquals('live-2', $chan2->getName()); + $this->assertEquals('live channel 2', $chan2->getDescription()); + $this->assertEquals(1, count($chan2->getPublishUrls())); + $this->assertEquals(1, count($chan2->getPlayUrls())); + + $this->client->deleteBucketLiveChannel($this->bucketName, 'live-1'); + $this->client->deleteBucketLiveChannel($this->bucketName, 'live-2'); + $list = $this->client->listBucketLiveChannels($this->bucketName, array( + 'prefix' => 'live-' + )); + $this->assertEquals(0, count($list->getChannelList())); + } + + public function testDeleteLiveChannel() + { + $channelName = 'live-to-delete'; + $config = new LiveChannelConfig(array( + 'description' => 'live channel to delete', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $this->client->putBucketLiveChannel($this->bucketName, $channelName, $config); + + $this->client->deleteBucketLiveChannel($this->bucketName, $channelName); + $list = $this->client->listBucketLiveChannels($this->bucketName, array( + 'prefix' => $channelName + )); + + $this->assertEquals(0, count($list->getChannelList())); + } + + public function testSignRtmpUrl() + { + $channelName = '90475'; + $bucket = 'douyu'; + $now = time(); + $url = $this->client->signRtmpUrl($bucket, $channelName, 900, array( + 'params' => array( + 'playlistName' => 'playlist.m3u8' + ) + )); + + $ret = parse_url($url); + $this->assertEquals('rtmp', $ret['scheme']); + parse_str($ret['query'], $query); + + $this->assertTrue(isset($query['OSSAccessKeyId'])); + $this->assertTrue(isset($query['Signature'])); + $this->assertTrue(intval($query['Expires']) - ($now + 900) < 3); + $this->assertEquals('playlist.m3u8', $query['playlistName']); + } + + public function testLiveChannelInfo() + { + $channelName = 'live-to-put-status'; + $config = new LiveChannelConfig(array( + 'description' => 'test live channel info', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $this->client->putBucketLiveChannel($this->bucketName, $channelName, $config); + + $info = $this->client->getLiveChannelInfo($this->bucketName, $channelName); + $this->assertEquals('test live channel info', $info->getDescription()); + $this->assertEquals('enabled', $info->getStatus()); + $this->assertEquals('HLS', $info->getType()); + $this->assertEquals(10, $info->getFragDuration()); + $this->assertEquals(5, $info->getFragCount()); + $this->assertEquals('playlist.m3u8', $info->getPlayListName()); + + $this->client->deleteBucketLiveChannel($this->bucketName, $channelName); + $list = $this->client->listBucketLiveChannels($this->bucketName, array( + 'prefix' => $channelName + )); + $this->assertEquals(0, count($list->getChannelList())); + } + + public function testPutLiveChannelStatus() + { + $channelName = 'live-to-put-status'; + $config = new LiveChannelConfig(array( + 'description' => 'test live channel info', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $this->client->putBucketLiveChannel($this->bucketName, $channelName, $config); + + $info = $this->client->getLiveChannelInfo($this->bucketName, $channelName); + $this->assertEquals('test live channel info', $info->getDescription()); + $this->assertEquals('enabled', $info->getStatus()); + $this->assertEquals('HLS', $info->getType()); + $this->assertEquals(10, $info->getFragDuration()); + $this->assertEquals(5, $info->getFragCount()); + $this->assertEquals('playlist.m3u8', $info->getPlayListName()); + $status = $this->client->getLiveChannelStatus($this->bucketName, $channelName); + $this->assertEquals('Idle', $status->getStatus()); + + + $resp = $this->client->putLiveChannelStatus($this->bucketName, $channelName, "disabled"); + $info = $this->client->getLiveChannelInfo($this->bucketName, $channelName); + $this->assertEquals('test live channel info', $info->getDescription()); + $this->assertEquals('disabled', $info->getStatus()); + $this->assertEquals('HLS', $info->getType()); + $this->assertEquals(10, $info->getFragDuration()); + $this->assertEquals(5, $info->getFragCount()); + $this->assertEquals('playlist.m3u8', $info->getPlayListName()); + + $status = $this->client->getLiveChannelStatus($this->bucketName, $channelName); + //getLiveChannelInfo + $this->assertEquals('Disabled', $status->getStatus()); + + $this->client->deleteBucketLiveChannel($this->bucketName, $channelName); + $list = $this->client->listBucketLiveChannels($this->bucketName, array( + 'prefix' => $channelName + )); + $this->assertEquals(0, count($list->getChannelList())); + + } + public function testLiveChannelHistory() + { + $channelName = 'live-test-history'; + $config = new LiveChannelConfig(array( + 'description' => 'test live channel info', + 'type' => 'HLS', + 'fragDuration' => 10, + 'fragCount' => 5, + 'playListName' => 'hello.m3u8' + )); + $this->client->putBucketLiveChannel($this->bucketName, $channelName, $config); + + $history = $this->client->getLiveChannelHistory($this->bucketName, $channelName); + $this->assertEquals(0, count($history->getLiveRecordList())); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CallbackTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CallbackTest.php new file mode 100755 index 0000000..a0db003 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CallbackTest.php @@ -0,0 +1,297 @@ +ossClient->putObject($this->bucket, $copiedObject, file_get_contents(__FILE__)); + + /** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ + try { + $upload_id = $this->ossClient->initiateMultipartUpload($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + /* + * step 2. uploadPartCopy + */ + $copyId = 1; + $eTag = $this->ossClient->uploadPartCopy($this->bucket, $copiedObject, $this->bucket, $object, $copyId, $upload_id); + $upload_parts[] = array( + 'PartNumber' => $copyId, + 'ETag' => $eTag, + ); + + try { + $listPartsInfo = $this->ossClient->listParts($this->bucket, $object, $upload_id); + $this->assertNotNull($listPartsInfo); + } catch (OssException $e) { + $this->assertTrue(false); + } + + /** + * step 3. + */ + + $json = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}", + "callbackBodyType":"application/json" + }'; + + $var = + '{ + "x:var1":"value1", + "x:var2":"值2" + }'; + $options = array(OssClient::OSS_CALLBACK => $json, + OssClient::OSS_CALLBACK_VAR => $var + ); + + try { + $result = $this->ossClient->completeMultipartUpload($this->bucket, $object, $upload_id, $upload_parts, $options); + $this->assertEquals("200", $result['info']['http_code']); + $this->assertEquals("{\"Status\":\"OK\"}", $result['body']); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + public function testMultipartUploadCallbackFailed() + { + $object = "multipart-callback-test.txt"; + $copiedObject = "multipart-callback-test.txt.copied"; + $this->ossClient->putObject($this->bucket, $copiedObject, file_get_contents(__FILE__)); + + /** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ + try { + $upload_id = $this->ossClient->initiateMultipartUpload($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + /* + * step 2. uploadPartCopy + */ + $copyId = 1; + $eTag = $this->ossClient->uploadPartCopy($this->bucket, $copiedObject, $this->bucket, $object, $copyId, $upload_id); + $upload_parts[] = array( + 'PartNumber' => $copyId, + 'ETag' => $eTag, + ); + + try { + $listPartsInfo = $this->ossClient->listParts($this->bucket, $object, $upload_id); + $this->assertNotNull($listPartsInfo); + } catch (OssException $e) { + $this->assertTrue(false); + } + + /** + * step 3. + */ + + $json = + '{ + "callbackUrl":"www.baidu.com", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}", + "callbackBodyType":"application/json" + }'; + + $var = + '{ + "x:var1":"value1", + "x:var2":"值2" + }'; + $options = array(OssClient::OSS_CALLBACK => $json, + OssClient::OSS_CALLBACK_VAR => $var + ); + + try { + $result = $this->ossClient->completeMultipartUpload($this->bucket, $object, $upload_id, $upload_parts, $options); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertTrue(true); + $this->assertEquals("203", $e->getHTTPStatus()); + } + + } + + public function testPutObjectCallbackNormal() + { + //json + { + $json = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size}}", + "callbackBodyType":"application/json" + }'; + $options = array(OssClient::OSS_CALLBACK => $json); + $this->putObjectCallbackOk($options, "200"); + } + //url + { + $url = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}", + "callbackBodyType":"application/x-www-form-urlencoded" + }'; + $options = array(OssClient::OSS_CALLBACK => $url); + $this->putObjectCallbackOk($options, "200"); + } + // Unspecified typre + { + $url = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}" + }'; + $options = array(OssClient::OSS_CALLBACK => $url); + $this->putObjectCallbackOk($options, "200"); + } + //json and body is chinese + { + $json = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\" 春水碧于天,画船听雨眠。\":\"垆边人似月,皓腕凝霜雪。\"}", + "callbackBodyType":"application/json" + }'; + $options = array(OssClient::OSS_CALLBACK => $json); + $this->putObjectCallbackOk($options, "200"); + } + //url and body is chinese + { + $url = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"春水碧于天,画船听雨眠。垆边人似月,皓腕凝霜雪", + "callbackBodyType":"application/x-www-form-urlencoded" + }'; + $options = array(OssClient::OSS_CALLBACK => $url); + $this->putObjectCallbackOk($options, "200"); + } + //json and add callback_var + { + $json = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}", + "callbackBodyType":"application/json" + }'; + + $var = + '{ + "x:var1":"value1", + "x:var2":"aliyun.com" + }'; + $options = array(OssClient::OSS_CALLBACK => $json, + OssClient::OSS_CALLBACK_VAR => $var + ); + $this->putObjectCallbackOk($options, "200"); + } + //url and add callback_var + { + $url = + '{ + "callbackUrl":"oss-demo.aliyuncs.com:23450", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}", + "callbackBodyType":"application/x-www-form-urlencoded" + }'; + $var = + '{ + "x:var1":"value1凌波不过横塘路,但目送,芳", + "x:var2":"值2" + }'; + $options = array(OssClient::OSS_CALLBACK => $url, + OssClient::OSS_CALLBACK_VAR => $var + ); + $this->putObjectCallbackOk($options, "200"); + } + + } + + public function testPutCallbackWithCallbackFailed() + { + { + $json = + '{ + "callbackUrl":"http://www.baidu.com", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size}}", + "callbackBodyType":"application/json" + }'; + $options = array(OssClient::OSS_CALLBACK => $json); + $this->putObjectCallbackFailed($options, "203"); + } + + { + $url = + '{ + "callbackUrl":"http://www.baidu.com", + "callbackHost":"oss-cn-hangzhou.aliyuncs.com", + "callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}", + "callbackBodyType":"application/x-www-form-urlencoded" + }'; + $options = array(OssClient::OSS_CALLBACK => $url); + $this->putObjectCallbackFailed($options, "203"); + } + + } + + private function putObjectCallbackOk($options, $status) + { + $object = "oss-php-sdk-callback-test.txt"; + $content = file_get_contents(__FILE__); + try { + $result = $this->ossClient->putObject($this->bucket, $object, $content, $options); + $this->assertEquals($status, $result['info']['http_code']); + $this->assertEquals("{\"Status\":\"OK\"}", $result['body']); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + private function putObjectCallbackFailed($options, $status) + { + $object = "oss-php-sdk-callback-test.txt"; + $content = file_get_contents(__FILE__); + try { + $result = $this->ossClient->putObject($this->bucket, $object, $content, $options); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals($status, $e->getHTTPStatus()); + $this->assertTrue(true); + } + } + + public function setUp() + { + parent::setUp(); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CnameConfigTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CnameConfigTest.php new file mode 100755 index 0000000..e3c1ce9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CnameConfigTest.php @@ -0,0 +1,77 @@ + + + + www.foo.com + enabled + 20150101 + + + bar.com + disabled + 20160101 + + +BBBB; + + public function testFromXml() + { + $cnameConfig = new CnameConfig(); + $cnameConfig->parseFromXml($this->xml1); + + $cnames = $cnameConfig->getCnames(); + $this->assertEquals(2, count($cnames)); + $this->assertEquals('www.foo.com', $cnames[0]['Domain']); + $this->assertEquals('enabled', $cnames[0]['Status']); + $this->assertEquals('20150101', $cnames[0]['LastModified']); + + $this->assertEquals('bar.com', $cnames[1]['Domain']); + $this->assertEquals('disabled', $cnames[1]['Status']); + $this->assertEquals('20160101', $cnames[1]['LastModified']); + } + + public function testToXml() + { + $cnameConfig = new CnameConfig(); + $cnameConfig->addCname('www.foo.com'); + $cnameConfig->addCname('bar.com'); + + $xml = $cnameConfig->serializeToXml(); + $comp = new CnameConfig(); + $comp->parseFromXml($xml); + + $cnames1 = $cnameConfig->getCnames(); + $cnames2 = $comp->getCnames(); + + $this->assertEquals(count($cnames1), count($cnames2)); + $this->assertEquals(count($cnames1[0]), count($cnames2[0])); + $this->assertEquals(1, count($cnames1[0])); + $this->assertEquals($cnames1[0]['Domain'], $cnames2[0]['Domain']); + } + + public function testCnameNumberLimit() + { + $cnameConfig = new CnameConfig(); + for ($i = 0; $i < CnameConfig::OSS_MAX_RULES; $i += 1) { + $cnameConfig->addCname(strval($i) . '.foo.com'); + } + try { + $cnameConfig->addCname('www.foo.com'); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals( + $e->getMessage(), + "num of cname in the config exceeds self::OSS_MAX_RULES: " . strval(CnameConfig::OSS_MAX_RULES)); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/Common.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/Common.php new file mode 100755 index 0000000..9d7190c --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/Common.php @@ -0,0 +1,70 @@ +getMessage() . "\n"); + return null; + } + return $ossClient; + } + + public static function getBucketName() + { + return getenv('OSS_BUCKET'); + } + + /** + * 工具方法,创建一个bucket + */ + public static function createBucket() + { + $ossClient = self::getOssClient(); + if (is_null($ossClient)) exit(1); + $bucket = self::getBucketName(); + $acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ; + try { + $ossClient->createBucket($bucket, $acl); + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return; + } + print(__FUNCTION__ . ": OK" . "\n"); + } + + /** + * Wait for bucket meta sync + */ + public static function waitMetaSync() + { + if (getenv('TRAVIS')) { + sleep(10); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ContentTypeTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ContentTypeTest.php new file mode 100755 index 0000000..606c810 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ContentTypeTest.php @@ -0,0 +1,133 @@ +/dev/null', $output, $status); + + $this->assertEquals(0, $status); + } + + private function getContentType($bucket, $object) + { + $client = Common::getOssClient(); + $headers = $client->getObjectMeta($bucket, $object); + return $headers['content-type']; + } + + public function testByFileName() + { + $client = Common::getOssClient(); + $bucket = Common::getBucketName(); + + $file = '/tmp/x.html'; + $object = 'test/x'; + $this->runCmd('touch ' . $file); + + $client->uploadFile($bucket, $object, $file); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('text/html', $type); + + $file = '/tmp/x.json'; + $object = 'test/y'; + $this->runCmd('dd if=/dev/urandom of=' . $file . ' bs=1024 count=100'); + + $client->multiuploadFile($bucket, $object, $file, array('partSize' => 100)); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('application/json', $type); + } + + public function testByObjectKey() + { + $client = Common::getOssClient(); + $bucket = Common::getBucketName(); + + $object = "test/x.txt"; + $client->putObject($bucket, $object, "hello world"); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('text/plain', $type); + + $file = '/tmp/x.html'; + $object = 'test/x.txt'; + $this->runCmd('touch ' . $file); + + $client->uploadFile($bucket, $object, $file); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('text/html', $type); + + $file = '/tmp/x.none'; + $object = 'test/x.txt'; + $this->runCmd('touch ' . $file); + + $client->uploadFile($bucket, $object, $file); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('text/plain', $type); + + $file = '/tmp/x.mp3'; + $object = 'test/y.json'; + $this->runCmd('dd if=/dev/urandom of=' . $file . ' bs=1024 count=100'); + + $client->multiuploadFile($bucket, $object, $file, array('partSize' => 100)); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('audio/mpeg', $type); + + $file = '/tmp/x.none'; + $object = 'test/y.json'; + $this->runCmd('dd if=/dev/urandom of=' . $file . ' bs=1024 count=100'); + + $client->multiuploadFile($bucket, $object, $file, array('partSize' => 100)); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('application/json', $type); + } + + public function testByUser() + { + $client = Common::getOssClient(); + $bucket = Common::getBucketName(); + + $object = "test/x.txt"; + $client->putObject($bucket, $object, "hello world", array( + 'Content-Type' => 'text/html' + )); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('text/html', $type); + + $file = '/tmp/x.html'; + $object = 'test/x'; + $this->runCmd('touch ' . $file); + + $client->uploadFile($bucket, $object, $file, array( + 'Content-Type' => 'application/json' + )); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('application/json', $type); + + $file = '/tmp/x.json'; + $object = 'test/y'; + $this->runCmd('dd if=/dev/urandom of=' . $file . ' bs=1024 count=100'); + + $client->multiuploadFile($bucket, $object, $file, array( + 'partSize' => 100, + 'Content-Type' => 'audio/mpeg' + )); + $type = $this->getContentType($bucket, $object); + + $this->assertEquals('audio/mpeg', $type); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CopyObjectResult.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CopyObjectResult.php new file mode 100755 index 0000000..171d4c8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CopyObjectResult.php @@ -0,0 +1,52 @@ + + + Fri, 24 Feb 2012 07:18:48 GMT + "5B3C1A2E053D763E1B002CC607C5A0FE" + +BBBB; + + public function testNullResponse() + { + $response = null; + try { + new CopyObjectResult($response); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('raw response is null', $e->getMessage()); + } + } + + public function testOkResponse() + { + $header= array(); + $response = new ResponseCore($header, $this->body, 200); + $result = new CopyObjectResult($response); + $data = $result->getData(); + $this->assertTrue($result->isOK()); + $this->assertEquals("Fri, 24 Feb 2012 07:18:48 GMT", $data[0]); + $this->assertEquals("\"5B3C1A2E053D763E1B002CC607C5A0FE\"", $data[1]); + } + + public function testFailResponse() + { + $response = new ResponseCore(array(), "", 404); + try { + new CopyObjectResult($response); + $this->assertFalse(true); + } catch (OssException $e) { + + } + } + +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CorsConfigTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CorsConfigTest.php new file mode 100755 index 0000000..ddc4d3a --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/CorsConfigTest.php @@ -0,0 +1,140 @@ + + + +http://www.b.com +http://www.a.com +http://www.a.com +GET +PUT +POST +x-oss-test +x-oss-test2 +x-oss-test2 +x-oss-test3 +x-oss-test1 +x-oss-test1 +x-oss-test2 +10 + + +http://www.b.com +GET +x-oss-test +x-oss-test1 +110 + + +BBBB; + + private $validXml2 = << + + +http://www.b.com +http://www.a.com +http://www.a.com +GET +PUT +POST +x-oss-test +x-oss-test2 +x-oss-test2 +x-oss-test3 +x-oss-test1 +x-oss-test1 +x-oss-test2 +10 + + +BBBB; + + public function testParseValidXml() + { + $corsConfig = new CorsConfig(); + $corsConfig->parseFromXml($this->validXml); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($corsConfig->serializeToXml())); + $this->assertNotNull($corsConfig->getRules()); + $rules = $corsConfig->getRules(); + $this->assertNotNull($rules[0]->getAllowedHeaders()); + $this->assertNotNull($rules[0]->getAllowedMethods()); + $this->assertNotNull($rules[0]->getAllowedOrigins()); + $this->assertNotNull($rules[0]->getExposeHeaders()); + $this->assertNotNull($rules[0]->getMaxAgeSeconds()); + } + + public function testParseValidXml2() + { + $corsConfig = new CorsConfig(); + $corsConfig->parseFromXml($this->validXml2); + $this->assertEquals($this->cleanXml($this->validXml2), $this->cleanXml($corsConfig->serializeToXml())); + } + + public function testCreateCorsConfigFromMoreThan10Rules() + { + $corsConfig = new CorsConfig(); + $rule = new CorsRule(); + for ($i = 0; $i < CorsConfig::OSS_MAX_RULES; $i += 1) { + $corsConfig->addRule($rule); + } + try { + $corsConfig->addRule($rule); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals($e->getMessage(), "num of rules in the config exceeds self::OSS_MAX_RULES: " . strval(CorsConfig::OSS_MAX_RULES)); + } + } + + public function testCreateCorsConfigParamAbsent() + { + $corsConfig = new CorsConfig(); + $rule = new CorsRule(); + $corsConfig->addRule($rule); + + try { + $xml = $corsConfig->serializeToXml(); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals($e->getMessage(), "maxAgeSeconds is not set in the Rule"); + } + } + + public function testCreateCorsConfigFromScratch() + { + $corsConfig = new CorsConfig(); + $rule = new CorsRule(); + $rule->addAllowedHeader("x-oss-test"); + $rule->addAllowedHeader("x-oss-test2"); + $rule->addAllowedHeader("x-oss-test2"); + $rule->addAllowedHeader("x-oss-test3"); + $rule->addAllowedOrigin("http://www.b.com"); + $rule->addAllowedOrigin("http://www.a.com"); + $rule->addAllowedOrigin("http://www.a.com"); + $rule->addAllowedMethod("GET"); + $rule->addAllowedMethod("PUT"); + $rule->addAllowedMethod("POST"); + $rule->addExposeHeader("x-oss-test1"); + $rule->addExposeHeader("x-oss-test1"); + $rule->addExposeHeader("x-oss-test2"); + $rule->setMaxAgeSeconds(10); + $corsConfig->addRule($rule); + $this->assertEquals($this->cleanXml($this->validXml2), $this->cleanXml($corsConfig->serializeToXml())); + $this->assertEquals($this->cleanXml($this->validXml2), $this->cleanXml(strval($corsConfig))); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ExistResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ExistResultTest.php new file mode 100755 index 0000000..e1b4e81 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ExistResultTest.php @@ -0,0 +1,38 @@ +assertTrue($result->isOK()); + $this->assertEquals($result->getData(), true); + } + + public function testParseInvalid404() + { + $response = new ResponseCore(array(), "", 404); + $result = new ExistResult($response); + $this->assertTrue($result->isOK()); + $this->assertEquals($result->getData(), false); + } + + public function testInvalidResponse() + { + $response = new ResponseCore(array(), "", 300); + try { + new ExistResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetCorsResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetCorsResultTest.php new file mode 100755 index 0000000..a3281c8 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetCorsResultTest.php @@ -0,0 +1,67 @@ + + + +http://www.b.com +http://www.a.com +http://www.a.com +GET +PUT +POST +x-oss-test +x-oss-test2 +x-oss-test2 +x-oss-test3 +x-oss-test1 +x-oss-test1 +x-oss-test2 +10 + + +http://www.b.com +GET +x-oss-test +x-oss-test1 +110 + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new GetCorsResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $corsConfig = $result->getData(); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($corsConfig->serializeToXml())); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } + + public function testInvalidResponse() + { + $response = new ResponseCore(array(), $this->validXml, 300); + try { + new GetCorsResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetLifecycleResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetLifecycleResultTest.php new file mode 100755 index 0000000..92ae208 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetLifecycleResultTest.php @@ -0,0 +1,59 @@ + + + +delete obsoleted files +obsoleted/ +Enabled +3 + + +delete temporary files +temporary/ +Enabled +2022-10-12T00:00:00.000Z +2022-10-12T00:00:00.000Z + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new GetLifecycleResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $lifecycleConfig = $result->getData(); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($lifecycleConfig->serializeToXml())); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } + + public function testInvalidResponse() + { + $response = new ResponseCore(array(), $this->validXml, 300); + try { + new GetLifecycleResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } + +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetLoggingResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetLoggingResultTest.php new file mode 100755 index 0000000..6195014 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetLoggingResultTest.php @@ -0,0 +1,51 @@ + + + +TargetBucket +TargetPrefix + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new GetLoggingResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $loggingConfig = $result->getData(); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($loggingConfig->serializeToXml())); + $this->assertEquals("TargetBucket", $loggingConfig->getTargetBucket()); + $this->assertEquals("TargetPrefix", $loggingConfig->getTargetPrefix()); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } + + public function testInvalidResponse() + { + $response = new ResponseCore(array(), $this->validXml, 300); + try { + new GetLoggingResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetRefererResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetRefererResultTest.php new file mode 100755 index 0000000..072aa43 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetRefererResultTest.php @@ -0,0 +1,51 @@ + + +true + +http://www.aliyun.com +https://www.aliyun.com +http://www.*.com +https://www.?.aliyuncs.com + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new GetRefererResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $refererConfig = $result->getData(); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($refererConfig->serializeToXml())); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } + + public function testInvalidResponse() + { + $response = new ResponseCore(array(), $this->validXml, 300); + try { + new GetRefererResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetWebsiteResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetWebsiteResultTest.php new file mode 100755 index 0000000..70e1559 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/GetWebsiteResultTest.php @@ -0,0 +1,50 @@ + + + +index.html + + +errorDocument.html + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new GetWebsiteResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $websiteConfig = $result->getData(); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($websiteConfig->serializeToXml())); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } + + public function testInvalidResponse() + { + $response = new ResponseCore(array(), $this->validXml, 300); + try { + new GetWebsiteResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/HeaderResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/HeaderResultTest.php new file mode 100755 index 0000000..dae4975 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/HeaderResultTest.php @@ -0,0 +1,23 @@ + 'value'), "", 200); + $result = new HeaderResult($response); + $this->assertTrue($result->isOK()); + $this->assertTrue(is_array($result->getData())); + $data = $result->getData(); + $this->assertEquals($data['key'], 'value'); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/HttpTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/HttpTest.php new file mode 100755 index 0000000..a59dfcd --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/HttpTest.php @@ -0,0 +1,77 @@ +assertFalse($res->isOK()); + $this->assertTrue($res->isOK(500)); + } + + public function testGet() + { + $httpCore = new RequestCore("http://www.baidu.com"); + $httpResponse = $httpCore->send_request(); + $this->assertNotNull($httpResponse); + } + + public function testSetProxyAndTimeout() + { + $httpCore = new RequestCore("http://www.baidu.com"); + $httpCore->set_proxy("1.0.2.1:8888"); + $httpCore->connect_timeout = 1; + try { + $httpResponse = $httpCore->send_request(); + $this->assertTrue(false); + } catch (RequestCore_Exception $e) { + + } + } + + public function testGetParseTrue() + { + $httpCore = new RequestCore("http://www.baidu.com"); + $httpCore->curlopts = array(CURLOPT_HEADER => true); + $url = $httpCore->send_request(true); + foreach ($httpCore->get_response_header() as $key => $value) { + $this->assertEquals($httpCore->get_response_header($key), $value); + } + $this->assertNotNull($url); + } + + public function testParseResponse() + { + $httpCore = new RequestCore("http://www.baidu.com"); + $response = $httpCore->send_request(); + $parsed = $httpCore->process_response(null, $response); + $this->assertNotNull($parsed); + } + + public function testExceptionGet() + { + $httpCore = null; + $exception = false; + try { + $httpCore = new RequestCore("http://www.notexistsitexx.com"); + $httpCore->set_body(""); + $httpCore->set_method("GET"); + $httpCore->connect_timeout = 10; + $httpCore->timeout = 10; + $res = $httpCore->send_request(); + } catch (RequestCore_Exception $e) { + $exception = true; + } + $this->assertTrue($exception); + } +} + + diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/InitiateMultipartUploadResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/InitiateMultipartUploadResultTest.php new file mode 100755 index 0000000..9f6c7a5 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/InitiateMultipartUploadResultTest.php @@ -0,0 +1,47 @@ + + + multipart_upload + multipart.data + 0004B9894A22E5B1888A1E29F8236E2D + +BBBB; + + private $invalidXml = << + + multipart_upload + multipart.data + +BBBB; + + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new InitiateMultipartUploadResult($response); + $this->assertEquals("0004B9894A22E5B1888A1E29F8236E2D", $result->getData()); + } + + public function testParseInvalidXml() + { + $response = new ResponseCore(array(), $this->invalidXml, 200); + try { + $result = new InitiateMultipartUploadResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LifecycleConfigTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LifecycleConfigTest.php new file mode 100755 index 0000000..7bd0331 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LifecycleConfigTest.php @@ -0,0 +1,130 @@ + + + +delete obsoleted files +obsoleted/ +Enabled +3 + + +delete temporary files +temporary/ +Enabled +2022-10-12T00:00:00.000Z +2022-10-12T00:00:00.000Z + + +BBBB; + + private $validLifecycle2 = << + +delete temporary files +temporary/ +Enabled +2022-10-12T00:00:00.000Z +2022-10-12T00:00:00.000Z + + +BBBB; + + private $nullLifecycle = << + +BBBB; + + public function testConstructValidConfig() + { + $lifecycleConfig = new LifecycleConfig(); + $actions = array(); + $actions[] = new LifecycleAction("Expiration", "Days", 3); + $lifecycleRule = new LifecycleRule("delete obsoleted files", "obsoleted/", "Enabled", $actions); + $lifecycleConfig->addRule($lifecycleRule); + $actions = array(); + $actions[] = new LifecycleAction("Expiration", "Date", '2022-10-12T00:00:00.000Z'); + $actions[] = new LifecycleAction("Expiration2", "Date", '2022-10-12T00:00:00.000Z'); + $lifecycleRule = new LifecycleRule("delete temporary files", "temporary/", "Enabled", $actions); + $lifecycleConfig->addRule($lifecycleRule); + try { + $lifecycleConfig->addRule(null); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('lifecycleRule is null', $e->getMessage()); + } + $this->assertEquals($this->cleanXml(strval($lifecycleConfig)), $this->cleanXml($this->validLifecycle)); + } + + public function testParseValidXml() + { + $lifecycleConfig = new LifecycleConfig(); + $lifecycleConfig->parseFromXml($this->validLifecycle); + $this->assertEquals($this->cleanXml($lifecycleConfig->serializeToXml()), $this->cleanXml($this->validLifecycle)); + $this->assertEquals(2, count($lifecycleConfig->getRules())); + $rules = $lifecycleConfig->getRules(); + $this->assertEquals('delete temporary files', $rules[1]->getId()); + } + + public function testParseValidXml2() + { + $lifecycleConfig = new LifecycleConfig(); + $lifecycleConfig->parseFromXml($this->validLifecycle2); + $this->assertEquals($this->cleanXml($lifecycleConfig->serializeToXml()), $this->cleanXml($this->validLifecycle2)); + $this->assertEquals(1, count($lifecycleConfig->getRules())); + $rules = $lifecycleConfig->getRules(); + $this->assertEquals('delete temporary files', $rules[0]->getId()); + } + + public function testParseNullXml() + { + $lifecycleConfig = new LifecycleConfig(); + $lifecycleConfig->parseFromXml($this->nullLifecycle); + $this->assertEquals($this->cleanXml($lifecycleConfig->serializeToXml()), $this->cleanXml($this->nullLifecycle)); + $this->assertEquals(0, count($lifecycleConfig->getRules())); + } + + public function testLifecycleRule() + { + $lifecycleRule = new LifecycleRule("x", "x", "x", array('x')); + $lifecycleRule->setId("id"); + $lifecycleRule->setPrefix("prefix"); + $lifecycleRule->setStatus("Enabled"); + $lifecycleRule->setActions(array()); + + $this->assertEquals('id', $lifecycleRule->getId()); + $this->assertEquals('prefix', $lifecycleRule->getPrefix()); + $this->assertEquals('Enabled', $lifecycleRule->getStatus()); + $this->assertEmpty($lifecycleRule->getActions()); + } + + public function testLifecycleAction() + { + $action = new LifecycleAction('x', 'x', 'x'); + $this->assertEquals($action->getAction(), 'x'); + $this->assertEquals($action->getTimeSpec(), 'x'); + $this->assertEquals($action->getTimeValue(), 'x'); + $action->setAction('y'); + $action->setTimeSpec('y'); + $action->setTimeValue('y'); + $this->assertEquals($action->getAction(), 'y'); + $this->assertEquals($action->getTimeSpec(), 'y'); + $this->assertEquals($action->getTimeValue(), 'y'); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListBucketsResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListBucketsResultTest.php new file mode 100755 index 0000000..1abe1f5 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListBucketsResultTest.php @@ -0,0 +1,97 @@ + + + + ut_test_put_bucket + ut_test_put_bucket + + + + oss-cn-hangzhou-a + xz02tphky6fjfiuc0 + 2014-05-15T11:18:32.000Z + + + oss-cn-hangzhou-a + xz02tphky6fjfiuc1 + 2014-05-15T11:18:32.000Z + + + +BBBB; + + private $nullXml = << + + + ut_test_put_bucket + ut_test_put_bucket + + + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new ListBucketsResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $bucketListInfo = $result->getData(); + $this->assertEquals(2, count($bucketListInfo->getBucketList())); + } + + public function testParseNullXml() + { + $response = new ResponseCore(array(), $this->nullXml, 200); + $result = new ListBucketsResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $bucketListInfo = $result->getData(); + $this->assertEquals(0, count($bucketListInfo->getBucketList())); + } + + public function test403() + { + $errorHeader = array( + 'x-oss-request-id' => '1a2b-3c4d' + ); + + $errorBody = <<< BBBB + + + NoSuchBucket + The specified bucket does not exist. + 566B870D207FB3044302EB0A + hello.oss-test.aliyun-inc.com + hello + +BBBB; + $response = new ResponseCore($errorHeader, $errorBody, 403); + try { + new ListBucketsResult($response); + } catch (OssException $e) { + $this->assertEquals( + $e->getMessage(), + 'NoSuchBucket: The specified bucket does not exist. RequestId: 1a2b-3c4d'); + $this->assertEquals($e->getHTTPStatus(), '403'); + $this->assertEquals($e->getRequestId(), '1a2b-3c4d'); + $this->assertEquals($e->getErrorCode(), 'NoSuchBucket'); + $this->assertEquals($e->getErrorMessage(), 'The specified bucket does not exist.'); + $this->assertEquals($e->getDetails(), $errorBody); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListMultipartUploadResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListMultipartUploadResultTest.php new file mode 100755 index 0000000..5c757d3 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListMultipartUploadResultTest.php @@ -0,0 +1,114 @@ + + + oss-example + xx + 3 + oss.avi + 0004B99B8E707874FC2D692FA5D77D3F + x + xx + 1000 + false + + multipart.data + 0004B999EF518A1FE585B0C9360DC4C8 + 2012-02-23T04:18:23.000Z + + + multipart.data + 0004B999EF5A239BB9138C6227D69F95 + 2012-02-23T04:18:23.000Z + + + oss.avi + 0004B99B8E707874FC2D692FA5D77D3F + 2012-02-23T06:14:27.000Z + + +BBBB; + + private $validXmlWithEncodedKey = << + + oss-example + url + php%2Bkey-marker + 3 + php%2Bnext-key-marker + 0004B99B8E707874FC2D692FA5D77D3F + %2F + php%2Bprefix + 1000 + true + + php%2Bkey-1 + 0004B999EF518A1FE585B0C9360DC4C8 + 2012-02-23T04:18:23.000Z + + + php%2Bkey-2 + 0004B999EF5A239BB9138C6227D69F95 + 2012-02-23T04:18:23.000Z + + + php%2Bkey-3 + 0004B99B8E707874FC2D692FA5D77D3F + 2012-02-23T06:14:27.000Z + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new ListMultipartUploadResult($response); + $listMultipartUploadInfo = $result->getData(); + $this->assertEquals("oss-example", $listMultipartUploadInfo->getBucket()); + $this->assertEquals("xx", $listMultipartUploadInfo->getKeyMarker()); + $this->assertEquals(3, $listMultipartUploadInfo->getUploadIdMarker()); + $this->assertEquals("oss.avi", $listMultipartUploadInfo->getNextKeyMarker()); + $this->assertEquals("0004B99B8E707874FC2D692FA5D77D3F", $listMultipartUploadInfo->getNextUploadIdMarker()); + $this->assertEquals("x", $listMultipartUploadInfo->getDelimiter()); + $this->assertEquals("xx", $listMultipartUploadInfo->getPrefix()); + $this->assertEquals(1000, $listMultipartUploadInfo->getMaxUploads()); + $this->assertEquals("false", $listMultipartUploadInfo->getIsTruncated()); + $uploads = $listMultipartUploadInfo->getUploads(); + $this->assertEquals("multipart.data", $uploads[0]->getKey()); + $this->assertEquals("0004B999EF518A1FE585B0C9360DC4C8", $uploads[0]->getUploadId()); + $this->assertEquals("2012-02-23T04:18:23.000Z", $uploads[0]->getInitiated()); + } + + public function testParseValidXmlWithEncodedKey() + { + $response = new ResponseCore(array(), $this->validXmlWithEncodedKey, 200); + $result = new ListMultipartUploadResult($response); + $listMultipartUploadInfo = $result->getData(); + $this->assertEquals("oss-example", $listMultipartUploadInfo->getBucket()); + $this->assertEquals("php+key-marker", $listMultipartUploadInfo->getKeyMarker()); + $this->assertEquals("php+next-key-marker", $listMultipartUploadInfo->getNextKeyMarker()); + $this->assertEquals(3, $listMultipartUploadInfo->getUploadIdMarker()); + $this->assertEquals("0004B99B8E707874FC2D692FA5D77D3F", $listMultipartUploadInfo->getNextUploadIdMarker()); + $this->assertEquals("/", $listMultipartUploadInfo->getDelimiter()); + $this->assertEquals("php+prefix", $listMultipartUploadInfo->getPrefix()); + $this->assertEquals(1000, $listMultipartUploadInfo->getMaxUploads()); + $this->assertEquals("true", $listMultipartUploadInfo->getIsTruncated()); + $uploads = $listMultipartUploadInfo->getUploads(); + $this->assertEquals("php+key-1", $uploads[0]->getKey()); + $this->assertEquals("0004B999EF518A1FE585B0C9360DC4C8", $uploads[0]->getUploadId()); + $this->assertEquals("2012-02-23T04:18:23.000Z", $uploads[0]->getInitiated()); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListObjectsResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListObjectsResultTest.php new file mode 100755 index 0000000..85f262c --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListObjectsResultTest.php @@ -0,0 +1,151 @@ + + + testbucket-hf + + + 1000 + / + false + + oss-php-sdk-test/ + + + test/ + + +BBBB; + + private $validXml2 = << + + testbucket-hf + oss-php-sdk-test/ + xx + 1000 + / + false + + oss-php-sdk-test/upload-test-object-name.txt + 2015-11-18T03:36:00.000Z + "89B9E567E7EB8815F2F7D41851F9A2CD" + Normal + 13115 + Standard + + cname_user + cname_user + + + +BBBB; + + private $validXmlWithEncodedKey = << + + testbucket-hf + url + php%2Fprefix + php%2Fmarker + php%2Fnext-marker + 1000 + %2F + true + + php/a%2Bb + 2015-11-18T03:36:00.000Z + "89B9E567E7EB8815F2F7D41851F9A2CD" + Normal + 13115 + Standard + + cname_user + cname_user + + + +BBBB; + + public function testParseValidXml1() + { + $response = new ResponseCore(array(), $this->validXml1, 200); + $result = new ListObjectsResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $objectListInfo = $result->getData(); + $this->assertEquals(2, count($objectListInfo->getPrefixList())); + $this->assertEquals(0, count($objectListInfo->getObjectList())); + $this->assertEquals('testbucket-hf', $objectListInfo->getBucketName()); + $this->assertEquals('', $objectListInfo->getPrefix()); + $this->assertEquals('', $objectListInfo->getMarker()); + $this->assertEquals(1000, $objectListInfo->getMaxKeys()); + $this->assertEquals('/', $objectListInfo->getDelimiter()); + $this->assertEquals('false', $objectListInfo->getIsTruncated()); + $prefixes = $objectListInfo->getPrefixList(); + $this->assertEquals('oss-php-sdk-test/', $prefixes[0]->getPrefix()); + $this->assertEquals('test/', $prefixes[1]->getPrefix()); + } + + public function testParseValidXml2() + { + $response = new ResponseCore(array(), $this->validXml2, 200); + $result = new ListObjectsResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $objectListInfo = $result->getData(); + $this->assertEquals(0, count($objectListInfo->getPrefixList())); + $this->assertEquals(1, count($objectListInfo->getObjectList())); + $this->assertEquals('testbucket-hf', $objectListInfo->getBucketName()); + $this->assertEquals('oss-php-sdk-test/', $objectListInfo->getPrefix()); + $this->assertEquals('xx', $objectListInfo->getMarker()); + $this->assertEquals(1000, $objectListInfo->getMaxKeys()); + $this->assertEquals('/', $objectListInfo->getDelimiter()); + $this->assertEquals('false', $objectListInfo->getIsTruncated()); + $objects = $objectListInfo->getObjectList(); + $this->assertEquals('oss-php-sdk-test/upload-test-object-name.txt', $objects[0]->getKey()); + $this->assertEquals('2015-11-18T03:36:00.000Z', $objects[0]->getLastModified()); + $this->assertEquals('"89B9E567E7EB8815F2F7D41851F9A2CD"', $objects[0]->getETag()); + $this->assertEquals('Normal', $objects[0]->getType()); + $this->assertEquals(13115, $objects[0]->getSize()); + $this->assertEquals('Standard', $objects[0]->getStorageClass()); + } + + public function testParseValidXmlWithEncodedKey() + { + $response = new ResponseCore(array(), $this->validXmlWithEncodedKey, 200); + $result = new ListObjectsResult($response); + $this->assertTrue($result->isOK()); + $this->assertNotNull($result->getData()); + $this->assertNotNull($result->getRawResponse()); + $objectListInfo = $result->getData(); + $this->assertEquals(0, count($objectListInfo->getPrefixList())); + $this->assertEquals(1, count($objectListInfo->getObjectList())); + $this->assertEquals('testbucket-hf', $objectListInfo->getBucketName()); + $this->assertEquals('php/prefix', $objectListInfo->getPrefix()); + $this->assertEquals('php/marker', $objectListInfo->getMarker()); + $this->assertEquals('php/next-marker', $objectListInfo->getNextMarker()); + $this->assertEquals(1000, $objectListInfo->getMaxKeys()); + $this->assertEquals('/', $objectListInfo->getDelimiter()); + $this->assertEquals('true', $objectListInfo->getIsTruncated()); + $objects = $objectListInfo->getObjectList(); + $this->assertEquals('php/a+b', $objects[0]->getKey()); + $this->assertEquals('2015-11-18T03:36:00.000Z', $objects[0]->getLastModified()); + $this->assertEquals('"89B9E567E7EB8815F2F7D41851F9A2CD"', $objects[0]->getETag()); + $this->assertEquals('Normal', $objects[0]->getType()); + $this->assertEquals(13115, $objects[0]->getSize()); + $this->assertEquals('Standard', $objects[0]->getStorageClass()); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListPartsResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListPartsResultTest.php new file mode 100755 index 0000000..c446714 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ListPartsResultTest.php @@ -0,0 +1,62 @@ + + + multipart_upload + multipart.data + 0004B999EF5A239BB9138C6227D69F95 + 5 + 1000 + false + + 1 + 2012-02-23T07:01:34.000Z + "3349DC700140D7F86A078484278075A9" + 6291456 + + + 2 + 2012-02-23T07:01:12.000Z + "3349DC700140D7F86A078484278075A9" + 6291456 + + + 5 + 2012-02-23T07:02:03.000Z + "7265F4D211B56873A381D321F586E4A9" + 1024 + + +BBBB; + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new ListPartsResult($response); + $listPartsInfo = $result->getData(); + $this->assertEquals("multipart_upload", $listPartsInfo->getBucket()); + $this->assertEquals("multipart.data", $listPartsInfo->getKey()); + $this->assertEquals("0004B999EF5A239BB9138C6227D69F95", $listPartsInfo->getUploadId()); + $this->assertEquals(5, $listPartsInfo->getNextPartNumberMarker()); + $this->assertEquals(1000, $listPartsInfo->getMaxParts()); + $this->assertEquals("false", $listPartsInfo->getIsTruncated()); + $this->assertEquals(3, count($listPartsInfo->getListPart())); + $parts = $listPartsInfo->getListPart(); + $this->assertEquals(1, $parts[0]->getPartNumber()); + $this->assertEquals('2012-02-23T07:01:34.000Z', $parts[0]->getLastModified()); + $this->assertEquals('"3349DC700140D7F86A078484278075A9"', $parts[0]->getETag()); + $this->assertEquals(6291456, $parts[0]->getSize()); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LiveChannelXmlTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LiveChannelXmlTest.php new file mode 100755 index 0000000..cc3e219 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LiveChannelXmlTest.php @@ -0,0 +1,249 @@ + + + xxx + enabled + + hls + 1000 + 5 + hello.m3u8 + + +BBBB; + + private $info = << + + live-1 + xxx + + rtmp://bucket.oss-cn-hangzhou.aliyuncs.com/live/213443245345 + + + http://bucket.oss-cn-hangzhou.aliyuncs.com/213443245345/播放列表.m3u8 + + enabled + 2015-11-24T14:25:31.000Z + +BBBB; + + private $list = << + +xxx + yyy + 100 + false + 121312132 + + 12123214323431 + xxx + + rtmp://bucket.oss-cn-hangzhou.aliyuncs.com/live/1 + + + http://bucket.oss-cn-hangzhou.aliyuncs.com/1/播放列表.m3u8 + + enabled + 2015-11-24T14:25:31.000Z + + + 432423432423 + yyy + + rtmp://bucket.oss-cn-hangzhou.aliyuncs.com/live/2 + + + http://bucket.oss-cn-hangzhou.aliyuncs.com/2/播放列表.m3u8 + + enabled + 2016-11-24T14:25:31.000Z + + +BBBB; + + private $status = << + + Live + 2016-10-20T14:25:31.000Z + 10.1.2.4:47745 + + + +BBBB; + + private $history = << + + + 2013-11-24T14:25:31.000Z + 2013-11-24T15:25:31.000Z + 10.101.194.148:56861 + + + 2014-11-24T14:25:31.000Z + 2014-11-24T15:25:31.000Z + 10.101.194.148:56862 + + + 2015-11-24T14:25:31.000Z + 2015-11-24T15:25:31.000Z + 10.101.194.148:56863 + + +BBBB; + + public function testLiveChannelStatus() + { + $stat = new GetLiveChannelStatus(); + $stat->parseFromXml($this->status); + + $this->assertEquals('Live', $stat->getStatus()); + $this->assertEquals('2016-10-20T14:25:31.000Z', $stat->getConnectedTime()); + $this->assertEquals('10.1.2.4:47745', $stat->getRemoteAddr()); + + $this->assertEquals(1280, $stat->getVideoWidth()); + $this->assertEquals(536, $stat->getVideoHeight()); + $this->assertEquals(24, $stat->getVideoFrameRate()); + $this->assertEquals(72513, $stat->getVideoBandwidth()); + $this->assertEquals('H264', $stat->getVideoCodec()); + $this->assertEquals(6519, $stat->getAudioBandwidth()); + $this->assertEquals(44100, $stat->getAudioSampleRate()); + $this->assertEquals('AAC', $stat->getAudioCodec()); + + } + + public function testLiveChannelHistory() + { + $history = new GetLiveChannelHistory(); + $history->parseFromXml($this->history); + + $recordList = $history->getLiveRecordList(); + $this->assertEquals(3, count($recordList)); + + $list0 = $recordList[0]; + $this->assertEquals('2013-11-24T14:25:31.000Z', $list0->getStartTime()); + $this->assertEquals('2013-11-24T15:25:31.000Z', $list0->getEndTime()); + $this->assertEquals('10.101.194.148:56861', $list0->getRemoteAddr()); + + $list1 = $recordList[1]; + $this->assertEquals('2014-11-24T14:25:31.000Z', $list1->getStartTime()); + $this->assertEquals('2014-11-24T15:25:31.000Z', $list1->getEndTime()); + $this->assertEquals('10.101.194.148:56862', $list1->getRemoteAddr()); + + $list2 = $recordList[2]; + $this->assertEquals('2015-11-24T14:25:31.000Z', $list2->getStartTime()); + $this->assertEquals('2015-11-24T15:25:31.000Z', $list2->getEndTime()); + $this->assertEquals('10.101.194.148:56863', $list2->getRemoteAddr()); + + } + + public function testLiveChannelConfig() + { + $config = new LiveChannelConfig(array('name' => 'live-1')); + $config->parseFromXml($this->config); + + $this->assertEquals('xxx', $config->getDescription()); + $this->assertEquals('enabled', $config->getStatus()); + $this->assertEquals('hls', $config->getType()); + $this->assertEquals(1000, $config->getFragDuration()); + $this->assertEquals(5, $config->getFragCount()); + $this->assertEquals('hello.m3u8', $config->getPlayListName()); + + $xml = $config->serializeToXml(); + $config2 = new LiveChannelConfig(array('name' => 'live-2')); + $config2->parseFromXml($xml); + $this->assertEquals('xxx', $config2->getDescription()); + $this->assertEquals('enabled', $config2->getStatus()); + $this->assertEquals('hls', $config2->getType()); + $this->assertEquals(1000, $config2->getFragDuration()); + $this->assertEquals(5, $config2->getFragCount()); + $this->assertEquals('hello.m3u8', $config2->getPlayListName()); + } + + public function testLiveChannelInfo() + { + $info = new LiveChannelInfo(array('name' => 'live-1')); + $info->parseFromXml($this->info); + + $this->assertEquals('live-1', $info->getName()); + $this->assertEquals('xxx', $info->getDescription()); + $this->assertEquals('enabled', $info->getStatus()); + $this->assertEquals('2015-11-24T14:25:31.000Z', $info->getLastModified()); + $pubs = $info->getPublishUrls(); + $this->assertEquals(1, count($pubs)); + $this->assertEquals('rtmp://bucket.oss-cn-hangzhou.aliyuncs.com/live/213443245345', $pubs[0]); + + $plays = $info->getPlayUrls(); + $this->assertEquals(1, count($plays)); + $this->assertEquals('http://bucket.oss-cn-hangzhou.aliyuncs.com/213443245345/播放列表.m3u8', $plays[0]); + } + + public function testLiveChannelList() + { + $list = new LiveChannelListInfo(); + $list->parseFromXml($this->list); + + $this->assertEquals('xxx', $list->getPrefix()); + $this->assertEquals('yyy', $list->getMarker()); + $this->assertEquals(100, $list->getMaxKeys()); + $this->assertEquals(false, $list->getIsTruncated()); + $this->assertEquals('121312132', $list->getNextMarker()); + + $channels = $list->getChannelList(); + $this->assertEquals(2, count($channels)); + + $chan1 = $channels[0]; + $this->assertEquals('12123214323431', $chan1->getName()); + $this->assertEquals('xxx', $chan1->getDescription()); + $this->assertEquals('enabled', $chan1->getStatus()); + $this->assertEquals('2015-11-24T14:25:31.000Z', $chan1->getLastModified()); + $pubs = $chan1->getPublishUrls(); + $this->assertEquals(1, count($pubs)); + $this->assertEquals('rtmp://bucket.oss-cn-hangzhou.aliyuncs.com/live/1', $pubs[0]); + + $plays = $chan1->getPlayUrls(); + $this->assertEquals(1, count($plays)); + $this->assertEquals('http://bucket.oss-cn-hangzhou.aliyuncs.com/1/播放列表.m3u8', $plays[0]); + + $chan2 = $channels[1]; + $this->assertEquals('432423432423', $chan2->getName()); + $this->assertEquals('yyy', $chan2->getDescription()); + $this->assertEquals('enabled', $chan2->getStatus()); + $this->assertEquals('2016-11-24T14:25:31.000Z', $chan2->getLastModified()); + $pubs = $chan2->getPublishUrls(); + $this->assertEquals(1, count($pubs)); + $this->assertEquals('rtmp://bucket.oss-cn-hangzhou.aliyuncs.com/live/2', $pubs[0]); + + $plays = $chan2->getPlayUrls(); + $this->assertEquals(1, count($plays)); + $this->assertEquals('http://bucket.oss-cn-hangzhou.aliyuncs.com/2/播放列表.m3u8', $plays[0]); + } + +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LoggingConfigTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LoggingConfigTest.php new file mode 100755 index 0000000..01496bb --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/LoggingConfigTest.php @@ -0,0 +1,47 @@ + + + +TargetBucket +TargetPrefix + + +BBBB; + + private $nullXml = << + +BBBB; + + public function testParseValidXml() + { + $loggingConfig = new LoggingConfig(); + $loggingConfig->parseFromXml($this->validXml); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml(strval($loggingConfig))); + } + + public function testConstruct() + { + $loggingConfig = new LoggingConfig('TargetBucket', 'TargetPrefix'); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($loggingConfig->serializeToXml())); + } + + public function testFailedConstruct() + { + $loggingConfig = new LoggingConfig('TargetBucket', null); + $this->assertEquals($this->cleanXml($this->nullXml), $this->cleanXml($loggingConfig->serializeToXml())); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/MimeTypesTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/MimeTypesTest.php new file mode 100755 index 0000000..0697409 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/MimeTypesTest.php @@ -0,0 +1,13 @@ +assertEquals('application/xml', MimeTypes::getMimetype('file.xml')); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ObjectAclTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ObjectAclTest.php new file mode 100755 index 0000000..d397288 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/ObjectAclTest.php @@ -0,0 +1,28 @@ +deleteObject($bucket, $object); + $client->putObject($bucket, $object, "hello world"); + + $acl = $client->getObjectAcl($bucket, $object); + $this->assertEquals('default', $acl); + + $client->putObjectAcl($bucket, $object, 'public-read'); + $acl = $client->getObjectAcl($bucket, $object); + $this->assertEquals('public-read', $acl); + + $content = $client->getObject($bucket, $object); + $this->assertEquals('hello world', $content); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketCorsTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketCorsTest.php new file mode 100755 index 0000000..a32154b --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketCorsTest.php @@ -0,0 +1,84 @@ +addAllowedHeader("x-oss-test"); + $rule->addAllowedHeader("x-oss-test2"); + $rule->addAllowedHeader("x-oss-test2"); + $rule->addAllowedHeader("x-oss-test3"); + $rule->addAllowedOrigin("http://www.b.com"); + $rule->addAllowedOrigin("http://www.a.com"); + $rule->addAllowedOrigin("http://www.a.com"); + $rule->addAllowedMethod("GET"); + $rule->addAllowedMethod("PUT"); + $rule->addAllowedMethod("POST"); + $rule->addExposeHeader("x-oss-test1"); + $rule->addExposeHeader("x-oss-test1"); + $rule->addExposeHeader("x-oss-test2"); + $rule->setMaxAgeSeconds(10); + $corsConfig->addRule($rule); + $rule = new CorsRule(); + $rule->addAllowedHeader("x-oss-test"); + $rule->addAllowedMethod("GET"); + $rule->addAllowedOrigin("http://www.b.com"); + $rule->addExposeHeader("x-oss-test1"); + $rule->setMaxAgeSeconds(110); + $corsConfig->addRule($rule); + + try { + $this->ossClient->putBucketCors($this->bucket, $corsConfig); + } catch (OssException $e) { + $this->assertFalse(True); + } + + try { + Common::waitMetaSync(); + $object = "cors/test.txt"; + $this->ossClient->putObject($this->bucket, $object, file_get_contents(__FILE__)); + $headers = $this->ossClient->optionsObject($this->bucket, $object, "http://www.a.com", "GET", "", null); + $this->assertNotEmpty($headers); + } catch (OssException $e) { + var_dump($e->getMessage()); + } + + try { + Common::waitMetaSync(); + $corsConfig2 = $this->ossClient->getBucketCors($this->bucket); + $this->assertNotNull($corsConfig2); + $this->assertEquals($corsConfig->serializeToXml(), $corsConfig2->serializeToXml()); + } catch (OssException $e) { + $this->assertFalse(True); + } + + try { + Common::waitMetaSync(); + $this->ossClient->deleteBucketCors($this->bucket); + } catch (OssException $e) { + $this->assertFalse(True); + } + + try { + Common::waitMetaSync(); + $corsConfig3 = $this->ossClient->getBucketCors($this->bucket); + $this->assertNotNull($corsConfig3); + $this->assertNotEquals($corsConfig->serializeToXml(), $corsConfig3->serializeToXml()); + } catch (OssException $e) { + $this->assertFalse(True); + } + + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketLifecycleTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketLifecycleTest.php new file mode 100755 index 0000000..46da1f0 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketLifecycleTest.php @@ -0,0 +1,57 @@ +addRule($lifecycleRule); + $actions = array(); + $actions[] = new LifecycleAction("Expiration", "Date", '2022-10-12T00:00:00.000Z'); + $lifecycleRule = new LifecycleRule("delete temporary files", "temporary/", "Enabled", $actions); + $lifecycleConfig->addRule($lifecycleRule); + + try { + $this->ossClient->putBucketLifecycle($this->bucket, $lifecycleConfig); + } catch (OssException $e) { + $this->assertTrue(false); + } + + try { + Common::waitMetaSync(); + $lifecycleConfig2 = $this->ossClient->getBucketLifecycle($this->bucket); + $this->assertEquals($lifecycleConfig->serializeToXml(), $lifecycleConfig2->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + + try { + Common::waitMetaSync(); + $this->ossClient->deleteBucketLifecycle($this->bucket); + } catch (OssException $e) { + $this->assertTrue(false); + } + + try { + Common::waitMetaSync(); + $lifecycleConfig3 = $this->ossClient->getBucketLifecycle($this->bucket); + $this->assertNotEquals($lifecycleConfig->serializeToXml(), $lifecycleConfig3->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketLoggingTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketLoggingTest.php new file mode 100755 index 0000000..16a10eb --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketLoggingTest.php @@ -0,0 +1,43 @@ +bucket, 'prefix'); + try { + $this->ossClient->putBucketLogging($this->bucket, $this->bucket, 'prefix'); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $loggingConfig2 = $this->ossClient->getBucketLogging($this->bucket); + $this->assertEquals($loggingConfig->serializeToXml(), $loggingConfig2->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $this->ossClient->deleteBucketLogging($this->bucket); + } catch (OssException $e) { + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $loggingConfig3 = $this->ossClient->getBucketLogging($this->bucket); + $this->assertNotEquals($loggingConfig->serializeToXml(), $loggingConfig3->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketRefererTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketRefererTest.php new file mode 100755 index 0000000..ba7d14f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketRefererTest.php @@ -0,0 +1,48 @@ +addReferer('http://www.aliyun.com'); + + try { + $this->ossClient->putBucketReferer($this->bucket, $refererConfig); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $refererConfig2 = $this->ossClient->getBucketReferer($this->bucket); + $this->assertEquals($refererConfig->serializeToXml(), $refererConfig2->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $nullRefererConfig = new RefererConfig(); + $nullRefererConfig->setAllowEmptyReferer(false); + $this->ossClient->putBucketReferer($this->bucket, $nullRefererConfig); + } catch (OssException $e) { + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $refererConfig3 = $this->ossClient->getBucketLogging($this->bucket); + $this->assertNotEquals($refererConfig->serializeToXml(), $refererConfig3->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketStorageCapacityTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketStorageCapacityTest.php new file mode 100755 index 0000000..87548f9 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketStorageCapacityTest.php @@ -0,0 +1,56 @@ +ossClient->getBucketStorageCapacity($this->bucket); + $this->assertEquals($storageCapacity, -1); + } catch (OssException $e) { + $this->assertTrue(false); + } + + try { + $this->ossClient->putBucketStorageCapacity($this->bucket, 1000); + } catch (OssException $e) { + $this->assertTrue(false); + } + + try { + Common::waitMetaSync(); + $storageCapacity = $this->ossClient->getBucketStorageCapacity($this->bucket); + $this->assertEquals($storageCapacity, 1000); + } catch (OssException $e) { + $this->assertTrue(false); + } + + try { + $this->ossClient->putBucketStorageCapacity($this->bucket, 0); + + Common::waitMetaSync(); + + $storageCapacity = $this->ossClient->getBucketStorageCapacity($this->bucket); + $this->assertEquals($storageCapacity, 0); + + $this->ossClient->putObject($this->bucket, 'test-storage-capacity','test-content'); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('Bucket storage exceed max storage capacity.',$e->getErrorMessage()); + } + + try { + $this->ossClient->putBucketStorageCapacity($this->bucket, -2); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals(400, $e->getHTTPStatus()); + $this->assertEquals('InvalidArgument', $e->getErrorCode()); + } + } + +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketTest.php new file mode 100755 index 0000000..f207ca1 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketTest.php @@ -0,0 +1,113 @@ +ossClient->createBucket("s"); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('"s"bucket name is invalid', $e->getMessage()); + } + } + + public function testBucketWithInvalidACL() + { + try { + $this->ossClient->createBucket($this->bucket, "invalid"); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('invalid:acl is invalid(private,public-read,public-read-write)', $e->getMessage()); + } + } + + public function testBucket() + { + $this->ossClient->createBucket($this->bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE); + + $bucketListInfo = $this->ossClient->listBuckets(); + $this->assertNotNull($bucketListInfo); + + $bucketList = $bucketListInfo->getBucketList(); + $this->assertTrue(is_array($bucketList)); + $this->assertGreaterThan(0, count($bucketList)); + + $this->ossClient->putBucketAcl($this->bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE); + Common::waitMetaSync(); + $this->assertEquals($this->ossClient->getBucketAcl($this->bucket), OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE); + + $this->assertTrue($this->ossClient->doesBucketExist($this->bucket)); + $this->assertFalse($this->ossClient->doesBucketExist($this->bucket . '-notexist')); + + $this->assertEquals($this->ossClient->getBucketLocation($this->bucket), 'oss-us-west-1'); + + $res = $this->ossClient->getBucketMeta($this->bucket); + $this->assertEquals('200', $res['info']['http_code']); + $this->assertEquals('oss-us-west-1', $res['x-oss-bucket-region']); + } + + public function testCreateBucketWithStorageType() + { + $object = 'storage-object'; + + $this->ossClient->putObject($this->archiveBucket, $object,'testcontent'); + try { + $this->ossClient->getObject($this->archiveBucket, $object); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('403', $e->getHTTPStatus()); + $this->assertEquals('InvalidObjectState', $e->getErrorCode()); + } + + $this->ossClient->putObject($this->iaBucket, $object,'testcontent'); + $result = $this->ossClient->getObject($this->iaBucket, $object); + $this->assertEquals($result, 'testcontent'); + + $this->ossClient->putObject($this->bucket, $object,'testcontent'); + $result = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($result, 'testcontent'); + } + + public function setUp() + { + parent::setUp(); + + $this->iaBucket = 'ia-' . $this->bucket; + $this->archiveBucket = 'archive-' . $this->bucket; + $options = array( + OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA + ); + + $this->ossClient->createBucket($this->iaBucket, OssClient::OSS_ACL_TYPE_PRIVATE, $options); + + $options = array( + OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_ARCHIVE + ); + + $this->ossClient->createBucket($this->archiveBucket, OssClient::OSS_ACL_TYPE_PRIVATE, $options); + } + + public function tearDown() + { + parent::tearDown(); + + $object = 'storage-object'; + + $this->ossClient->deleteObject($this->iaBucket, $object); + $this->ossClient->deleteObject($this->archiveBucket, $object); + $this->ossClient->deleteBucket($this->iaBucket); + $this->ossClient->deleteBucket($this->archiveBucket); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketWebsiteTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketWebsiteTest.php new file mode 100755 index 0000000..dfa9cc1 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientBucketWebsiteTest.php @@ -0,0 +1,46 @@ +ossClient->putBucketWebsite($this->bucket, $websiteConfig); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertTrue(false); + } + + try { + Common::waitMetaSync(); + $websiteConfig2 = $this->ossClient->getBucketWebsite($this->bucket); + $this->assertEquals($websiteConfig->serializeToXml(), $websiteConfig2->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $this->ossClient->deleteBucketWebsite($this->bucket); + } catch (OssException $e) { + $this->assertTrue(false); + } + try { + Common::waitMetaSync(); + $websiteConfig3 = $this->ossClient->getBucketLogging($this->bucket); + $this->assertNotEquals($websiteConfig->serializeToXml(), $websiteConfig3->serializeToXml()); + } catch (OssException $e) { + $this->assertTrue(false); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientImageTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientImageTest.php new file mode 100755 index 0000000..df8bd6c --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientImageTest.php @@ -0,0 +1,100 @@ +client = Common::getOssClient(); + $this->bucketName = 'php-sdk-test-bucket-image-' . strval(rand(0, 10000)); + $this->client->createBucket($this->bucketName); + Common::waitMetaSync(); + $this->local_file = "example.jpg"; + $this->object = "oss-example.jpg"; + $this->download_file = "image.jpg"; + + $this->client->uploadFile($this->bucketName, $this->object, $this->local_file); + } + + public function tearDown() + { + $this->client->deleteObject($this->bucketName, $this->object); + $this->client->deleteBucket($this->bucketName); + } + + public function testImageResize() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100", ); + $this->check($options, 100, 100, 3267, 'jpg'); + } + + public function testImageCrop() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/crop,w_100,h_100,x_100,y_100,r_1", ); + $this->check($options, 100, 100, 1969, 'jpg'); + } + + public function testImageRotate() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/rotate,90", ); + $this->check($options, 267, 400, 20998, 'jpg'); + } + + public function testImageSharpen() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/sharpen,100", ); + $this->check($options, 400, 267, 23015, 'jpg'); + } + + public function testImageWatermark() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ", ); + $this->check($options, 400, 267, 26369, 'jpg'); + } + + public function testImageFormat() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/format,png", ); + $this->check($options, 400, 267, 160733, 'png'); + } + + public function testImageTofile() + { + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $this->download_file, + OssClient::OSS_PROCESS => "image/resize,m_fixed,w_100,h_100", ); + $this->check($options, 100, 100, 3267, 'jpg'); + } + + private function check($options, $width, $height, $size, $type) + { + $this->client->getObject($this->bucketName, $this->object, $options); + $array = getimagesize($this->download_file); + $this->assertEquals($width, $array[0]); + $this->assertEquals($height, $array[1]); + $this->assertEquals($type === 'jpg' ? 2 : 3, $array[2]);//2 <=> jpg + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientMultipartUploadTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientMultipartUploadTest.php new file mode 100755 index 0000000..a95f412 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientMultipartUploadTest.php @@ -0,0 +1,313 @@ +ossClient->uploadDir($this->bucket, "", "abc/ds/s/s/notexitst"); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals("parameter error: abc/ds/s/s/notexitst is not a directory, please check it", $e->getMessage()); + } + + } + + public function testMultipartUploadBigFile() + { + $bigFileName = __DIR__ . DIRECTORY_SEPARATOR . "/bigfile.tmp"; + $localFilename = __DIR__ . DIRECTORY_SEPARATOR . "/localfile.tmp"; + OssUtil::generateFile($bigFileName, 6 * 1024 * 1024); + $object = 'mpu/multipart-bigfile-test.tmp'; + try { + $this->ossClient->multiuploadFile($this->bucket, $object, $bigFileName, array(OssClient::OSS_PART_SIZE => 1)); + $options = array(OssClient::OSS_FILE_DOWNLOAD => $localFilename); + $this->ossClient->getObject($this->bucket, $object, $options); + $this->assertEquals(md5_file($bigFileName), md5_file($localFilename)); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertFalse(true); + } + unlink($bigFileName); + unlink($localFilename); + } + + public function testMultipartUploadBigFileWithMD5Check() + { + $bigFileName = __DIR__ . DIRECTORY_SEPARATOR . "/bigfile.tmp"; + $localFilename = __DIR__ . DIRECTORY_SEPARATOR . "/localfile.tmp"; + OssUtil::generateFile($bigFileName, 6 * 1024 * 1024); + $object = 'mpu/multipart-bigfile-test.tmp'; + $options = array( + OssClient::OSS_CHECK_MD5 => true, + OssClient::OSS_PART_SIZE => 1, + ); + try { + $this->ossClient->multiuploadFile($this->bucket, $object, $bigFileName, $options); + $options = array(OssClient::OSS_FILE_DOWNLOAD => $localFilename); + $this->ossClient->getObject($this->bucket, $object, $options); + $this->assertEquals(md5_file($bigFileName), md5_file($localFilename)); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertFalse(true); + } + unlink($bigFileName); + unlink($localFilename); + } + + public function testCopyPart() + { + $object = "mpu/multipart-test.txt"; + $copiedObject = "mpu/multipart-test.txt.copied"; + $this->ossClient->putObject($this->bucket, $copiedObject, file_get_contents(__FILE__)); + /** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ + try { + $upload_id = $this->ossClient->initiateMultipartUpload($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + /* + * step 2. uploadPartCopy + */ + $copyId = 1; + $eTag = $this->ossClient->uploadPartCopy($this->bucket, $copiedObject, $this->bucket, $object, $copyId, $upload_id); + $upload_parts[] = array( + 'PartNumber' => $copyId, + 'ETag' => $eTag, + ); + + try { + $listPartsInfo = $this->ossClient->listParts($this->bucket, $object, $upload_id); + $this->assertNotNull($listPartsInfo); + } catch (OssException $e) { + $this->assertTrue(false); + } + + /** + * step 3. + */ + try { + $this->ossClient->completeMultipartUpload($this->bucket, $object, $upload_id, $upload_parts); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertTrue(false); + } + + $this->assertEquals($this->ossClient->getObject($this->bucket, $object), file_get_contents(__FILE__)); + $this->assertEquals($this->ossClient->getObject($this->bucket, $copiedObject), file_get_contents(__FILE__)); + } + + public function testAbortMultipartUpload() + { + $object = "mpu/multipart-test.txt"; + /** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ + try { + $upload_id = $this->ossClient->initiateMultipartUpload($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + /* + * step 2. 上传分片 + */ + $part_size = 10 * 1024 * 1024; + $upload_file = __FILE__; + $upload_filesize = filesize($upload_file); + $pieces = $this->ossClient->generateMultiuploadParts($upload_filesize, $part_size); + $response_upload_part = array(); + $upload_position = 0; + $is_check_md5 = true; + foreach ($pieces as $i => $piece) { + $from_pos = $upload_position + (integer)$piece[OssClient::OSS_SEEK_TO]; + $to_pos = (integer)$piece[OssClient::OSS_LENGTH] + $from_pos - 1; + $up_options = array( + OssClient::OSS_FILE_UPLOAD => $upload_file, + OssClient::OSS_PART_NUM => ($i + 1), + OssClient::OSS_SEEK_TO => $from_pos, + OssClient::OSS_LENGTH => $to_pos - $from_pos + 1, + OssClient::OSS_CHECK_MD5 => $is_check_md5, + ); + if ($is_check_md5) { + $content_md5 = OssUtil::getMd5SumForFile($upload_file, $from_pos, $to_pos); + $up_options[OssClient::OSS_CONTENT_MD5] = $content_md5; + } + //2. 将每一分片上传到OSS + try { + $response_upload_part[] = $this->ossClient->uploadPart($this->bucket, $object, $upload_id, $up_options); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + $upload_parts = array(); + foreach ($response_upload_part as $i => $eTag) { + $upload_parts[] = array( + 'PartNumber' => ($i + 1), + 'ETag' => $eTag, + ); + } + + try { + $listPartsInfo = $this->ossClient->listParts($this->bucket, $object, $upload_id); + $this->assertNotNull($listPartsInfo); + } catch (OssException $e) { + $this->assertTrue(false); + } + $this->assertEquals(1, count($listPartsInfo->getListPart())); + + $numOfMultipartUpload1 = 0; + $options = null; + try { + $listMultipartUploadInfo = $listMultipartUploadInfo = $this->ossClient->listMultipartUploads($this->bucket, $options); + $this->assertNotNull($listMultipartUploadInfo); + $numOfMultipartUpload1 = count($listMultipartUploadInfo->getUploads()); + } catch (OssException $e) { + $this->assertFalse(true); + } + + try { + $this->ossClient->abortMultipartUpload($this->bucket, $object, $upload_id); + } catch (OssException $e) { + $this->assertTrue(false); + } + + $numOfMultipartUpload2 = 0; + try { + $listMultipartUploadInfo = $listMultipartUploadInfo = $this->ossClient->listMultipartUploads($this->bucket, $options); + $this->assertNotNull($listMultipartUploadInfo); + $numOfMultipartUpload2 = count($listMultipartUploadInfo->getUploads()); + } catch (OssException $e) { + $this->assertFalse(true); + } + $this->assertEquals($numOfMultipartUpload1 - 1, $numOfMultipartUpload2); + } + + public function testPutObjectByRawApis() + { + $object = "mpu/multipart-test.txt"; + /** + * step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id + */ + try { + $upload_id = $this->ossClient->initiateMultipartUpload($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + /* + * step 2. 上传分片 + */ + $part_size = 10 * 1024 * 1024; + $upload_file = __FILE__; + $upload_filesize = filesize($upload_file); + $pieces = $this->ossClient->generateMultiuploadParts($upload_filesize, $part_size); + $response_upload_part = array(); + $upload_position = 0; + $is_check_md5 = true; + foreach ($pieces as $i => $piece) { + $from_pos = $upload_position + (integer)$piece[OssClient::OSS_SEEK_TO]; + $to_pos = (integer)$piece[OssClient::OSS_LENGTH] + $from_pos - 1; + $up_options = array( + OssClient::OSS_FILE_UPLOAD => $upload_file, + OssClient::OSS_PART_NUM => ($i + 1), + OssClient::OSS_SEEK_TO => $from_pos, + OssClient::OSS_LENGTH => $to_pos - $from_pos + 1, + OssClient::OSS_CHECK_MD5 => $is_check_md5, + ); + if ($is_check_md5) { + $content_md5 = OssUtil::getMd5SumForFile($upload_file, $from_pos, $to_pos); + $up_options[OssClient::OSS_CONTENT_MD5] = $content_md5; + } + //2. 将每一分片上传到OSS + try { + $response_upload_part[] = $this->ossClient->uploadPart($this->bucket, $object, $upload_id, $up_options); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + $upload_parts = array(); + foreach ($response_upload_part as $i => $eTag) { + $upload_parts[] = array( + 'PartNumber' => ($i + 1), + 'ETag' => $eTag, + ); + } + + try { + $listPartsInfo = $this->ossClient->listParts($this->bucket, $object, $upload_id); + $this->assertNotNull($listPartsInfo); + } catch (OssException $e) { + $this->assertTrue(false); + } + + /** + * step 3. + */ + try { + $this->ossClient->completeMultipartUpload($this->bucket, $object, $upload_id, $upload_parts); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + function testPutObjectsByDir() + { + $localDirectory = dirname(__FILE__); + $prefix = "samples/codes"; + try { + $this->ossClient->uploadDir($this->bucket, $prefix, $localDirectory); + } catch (OssException $e) { + var_dump($e->getMessage()); + $this->assertFalse(true); + + } + $this->assertTrue($this->ossClient->doesObjectExist($this->bucket, 'samples/codes/' . "OssClientMultipartUploadTest.php")); + } + + public function testPutObjectByMultipartUpload() + { + $object = "mpu/multipart-test.txt"; + $file = __FILE__; + $options = array(); + + try { + $this->ossClient->multiuploadFile($this->bucket, $object, $file, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testPutObjectByMultipartUploadWithMD5Check() + { + $object = "mpu/multipart-test.txt"; + $file = __FILE__; + $options = array(OssClient::OSS_CHECK_MD5 => true); + + try { + $this->ossClient->multiuploadFile($this->bucket, $object, $file, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testListMultipartUploads() + { + $options = null; + try { + $listMultipartUploadInfo = $this->ossClient->listMultipartUploads($this->bucket, $options); + $this->assertNotNull($listMultipartUploadInfo); + } catch (OssException $e) { + $this->assertFalse(true); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientObjectTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientObjectTest.php new file mode 100755 index 0000000..34e3ded --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientObjectTest.php @@ -0,0 +1,588 @@ +ossClient->getObjectMeta($this->bucket, $object); + $this->assertEquals('200', $res['info']['http_code']); + $this->assertEquals('text/plain', $res['content-type']); + $this->assertEquals('Accept-Encoding', $res['vary']); + $this->assertTrue(isset($res['content-length'])); + $this->assertFalse(isset($res['content-encoding'])); + } catch (OssException $e) { + $this->assertTrue(false); + } + + $options = array(OssClient::OSS_HEADERS => array(OssClient::OSS_ACCEPT_ENCODING => 'deflate, gzip')); + + try { + $res = $this->ossClient->getObjectMeta($this->bucket, $object, $options); + $this->assertEquals('200', $res['info']['http_code']); + $this->assertEquals('text/plain', $res['content-type']); + $this->assertEquals('Accept-Encoding', $res['vary']); + $this->assertFalse(isset($res['content-length'])); + $this->assertEquals('gzip', $res['content-encoding']); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + public function testGetObjectWithAcceptEncoding() + { + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $options = array(OssClient::OSS_HEADERS => array(OssClient::OSS_ACCEPT_ENCODING => 'deflate, gzip')); + + try { + $res = $this->ossClient->getObject($this->bucket, $object, $options); + $this->assertEquals(file_get_contents(__FILE__), $res); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + public function testGetObjectWithHeader() + { + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + try { + $res = $this->ossClient->getObject($this->bucket, $object, array(OssClient::OSS_LAST_MODIFIED => "xx")); + $this->assertEquals(file_get_contents(__FILE__), $res); + } catch (OssException $e) { + $this->assertEquals('"/ilegal.txt" object name is invalid', $e->getMessage()); + } + } + + public function testGetObjectWithIleggalEtag() + { + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + try { + $res = $this->ossClient->getObject($this->bucket, $object, array(OssClient::OSS_ETAG => "xx")); + $this->assertEquals(file_get_contents(__FILE__), $res); + } catch (OssException $e) { + $this->assertEquals('"/ilegal.txt" object name is invalid', $e->getMessage()); + } + } + + public function testObject() + { + /** + * 上传本地变量到bucket + */ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $content = file_get_contents(__FILE__); + $options = array( + OssClient::OSS_LENGTH => strlen($content), + OssClient::OSS_HEADERS => array( + 'Expires' => 'Fri, 28 Feb 2020 05:38:42 GMT', + 'Cache-Control' => 'no-cache', + 'Content-Disposition' => 'attachment;filename=oss_download.log', + 'Content-Encoding' => 'utf-8', + 'Content-Language' => 'zh-CN', + 'x-oss-server-side-encryption' => 'AES256', + 'x-oss-meta-self-define-title' => 'user define meta info', + ), + ); + + try { + $this->ossClient->putObject($this->bucket, $object, $content, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + + try { + $this->ossClient->putObject($this->bucket, $object, $content, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + + try { + $result = $this->ossClient->deleteObjects($this->bucket, "stringtype", $options); + $this->assertEquals('stringtype', $result[0]); + } catch (OssException $e) { + $this->assertEquals('objects must be array', $e->getMessage()); + } + + try { + $result = $this->ossClient->deleteObjects($this->bucket, "stringtype", $options); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('objects must be array', $e->getMessage()); + } + + try { + $this->ossClient->uploadFile($this->bucket, $object, "notexist.txt", $options); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('notexist.txt file does not exist', $e->getMessage()); + } + + /** + * getObject到本地变量,检查是否match + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * getObject的前五个字节 + */ + try { + $options = array(OssClient::OSS_RANGE => '0-4'); + $content = $this->ossClient->getObject($this->bucket, $object, $options); + $this->assertEquals($content, 'assertFalse(true); + } + + + /** + * 上传本地文件到object + */ + try { + $this->ossClient->uploadFile($this->bucket, $object, __FILE__); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 下载文件到本地变量,检查是否match + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 下载文件到本地文件 + */ + $localfile = "upload-test-object-name.txt"; + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $localfile, + ); + + try { + $this->ossClient->getObject($this->bucket, $object, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + $this->assertTrue(file_get_contents($localfile) === file_get_contents(__FILE__)); + if (file_exists($localfile)) { + unlink($localfile); + } + + /** + * 下载文件到本地文件 no such key + */ + $localfile = "upload-test-object-name-no-such-key.txt"; + $options = array( + OssClient::OSS_FILE_DOWNLOAD => $localfile, + ); + + try { + $this->ossClient->getObject($this->bucket, $object . "no-such-key", $options); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertTrue(true); + $this->assertFalse(file_exists($localfile)); + if (strpos($e, "The specified key does not exist") == false) + { + $this->assertTrue(true); + } + } + + /** + * 下载文件到内容 no such key + */ + try { + $result = $this->ossClient->getObject($this->bucket, $object . "no-such-key"); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertTrue(true); + if (strpos($e, "The specified key does not exist") == false) + { + $this->assertTrue(true); + } + } + + /** + * 复制object + */ + $to_bucket = $this->bucket; + $to_object = $object . '.copy'; + $options = array(); + try { + $result = $this->ossClient->copyObject($this->bucket, $object, $to_bucket, $to_object, $options); + $this->assertFalse(empty($result)); + $this->assertEquals(strlen("2016-11-21T03:46:58.000Z"), strlen($result[0])); + $this->assertEquals(strlen("\"5B3C1A2E053D763E1B002CC607C5A0FE\""), strlen($result[1])); + } catch (OssException $e) { + $this->assertFalse(true); + var_dump($e->getMessage()); + + } + + /** + * 检查复制的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $to_object); + $this->assertEquals($content, file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 列出bucket内的文件列表 + */ + $prefix = ''; + $delimiter = '/'; + $next_marker = ''; + $maxkeys = 1000; + $options = array( + 'delimiter' => $delimiter, + 'prefix' => $prefix, + 'max-keys' => $maxkeys, + 'marker' => $next_marker, + ); + + try { + $listObjectInfo = $this->ossClient->listObjects($this->bucket, $options); + $objectList = $listObjectInfo->getObjectList(); + $prefixList = $listObjectInfo->getPrefixList(); + $this->assertNotNull($objectList); + $this->assertNotNull($prefixList); + $this->assertTrue(is_array($objectList)); + $this->assertTrue(is_array($prefixList)); + + } catch (OssException $e) { + $this->assertTrue(false); + } + + /** + * 设置文件的meta信息 + */ + $from_bucket = $this->bucket; + $from_object = "oss-php-sdk-test/upload-test-object-name.txt"; + $to_bucket = $from_bucket; + $to_object = $from_object; + $copy_options = array( + OssClient::OSS_HEADERS => array( + 'Expires' => '2012-10-01 08:00:00', + 'Content-Disposition' => 'attachment; filename="xxxxxx"', + ), + ); + try { + $this->ossClient->copyObject($from_bucket, $from_object, $to_bucket, $to_object, $copy_options); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 获取文件的meta信息 + */ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + try { + $objectMeta = $this->ossClient->getObjectMeta($this->bucket, $object); + $this->assertEquals('attachment; filename="xxxxxx"', $objectMeta[strtolower('Content-Disposition')]); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除单个文件 + */ + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + + try { + $this->assertTrue($this->ossClient->doesObjectExist($this->bucket, $object)); + $this->ossClient->deleteObject($this->bucket, $object); + $this->assertFalse($this->ossClient->doesObjectExist($this->bucket, $object)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除多个个文件 + */ + $object1 = "oss-php-sdk-test/upload-test-object-name.txt"; + $object2 = "oss-php-sdk-test/upload-test-object-name.txt.copy"; + $list = array($object1, $object2); + try { + $this->assertTrue($this->ossClient->doesObjectExist($this->bucket, $object2)); + + $result = $this->ossClient->deleteObjects($this->bucket, $list); + $this->assertEquals($list[1], $result[0]); + $this->assertEquals($list[0], $result[1]); + + $result = $this->ossClient->deleteObjects($this->bucket, $list, array('quiet' => 'true')); + $this->assertEquals(array(), $result); + $this->assertFalse($this->ossClient->doesObjectExist($this->bucket, $object2)); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testAppendObject() + { + $object = "oss-php-sdk-test/append-test-object-name.txt"; + $content_array = array('Hello OSS', 'Hi OSS', 'OSS OK'); + + /** + * 追加上传字符串 + */ + try { + $position = $this->ossClient->appendObject($this->bucket, $object, $content_array[0], 0); + $this->assertEquals($position, strlen($content_array[0])); + $position = $this->ossClient->appendObject($this->bucket, $object, $content_array[1], $position); + $this->assertEquals($position, strlen($content_array[0]) + strlen($content_array[1])); + $position = $this->ossClient->appendObject($this->bucket, $object, $content_array[2], $position); + $this->assertEquals($position, strlen($content_array[0]) + strlen($content_array[1]) + strlen($content_array[1])); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 检查内容的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, implode($content_array)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + + /** + * 删除测试object + */ + try { + $this->ossClient->deleteObject($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 追加上传本地文件 + */ + try { + $position = $this->ossClient->appendFile($this->bucket, $object, __FILE__, 0); + $this->assertEquals($position, filesize(__FILE__)); + $position = $this->ossClient->appendFile($this->bucket, $object, __FILE__, $position); + $this->assertEquals($position, filesize(__FILE__) * 2); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 检查复制的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, file_get_contents(__FILE__) . file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除测试object + */ + try { + $this->ossClient->deleteObject($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + + + $options = array( + OssClient::OSS_HEADERS => array( + 'Expires' => '2012-10-01 08:00:00', + 'Content-Disposition' => 'attachment; filename="xxxxxx"', + ), + ); + + /** + * 带option的追加上传 + */ + try { + $position = $this->ossClient->appendObject($this->bucket, $object, "Hello OSS, ", 0, $options); + $position = $this->ossClient->appendObject($this->bucket, $object, "Hi OSS.", $position); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 获取文件的meta信息 + */ + try { + $objectMeta = $this->ossClient->getObjectMeta($this->bucket, $object); + $this->assertEquals('attachment; filename="xxxxxx"', $objectMeta[strtolower('Content-Disposition')]); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除测试object + */ + try { + $this->ossClient->deleteObject($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testPutIllelObject() + { + $object = "/ilegal.txt"; + try { + $this->ossClient->putObject($this->bucket, $object, "hi", null); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('"/ilegal.txt" object name is invalid', $e->getMessage()); + } + } + + public function testCheckMD5() + { + $object = "oss-php-sdk-test/upload-test-object-name.txt"; + $content = file_get_contents(__FILE__); + $options = array(OssClient::OSS_CHECK_MD5 => true); + + /** + * 上传数据开启MD5 + */ + try { + $this->ossClient->putObject($this->bucket, $object, $content, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 检查复制的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 上传文件开启MD5 + */ + try { + $this->ossClient->uploadFile($this->bucket, $object, __FILE__, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 检查复制的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除测试object + */ + try { + $this->ossClient->deleteObject($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + + $object = "oss-php-sdk-test/append-test-object-name.txt"; + $content_array = array('Hello OSS', 'Hi OSS', 'OSS OK'); + $options = array(OssClient::OSS_CHECK_MD5 => true); + + /** + * 追加上传字符串 + */ + try { + $position = $this->ossClient->appendObject($this->bucket, $object, $content_array[0], 0, $options); + $this->assertEquals($position, strlen($content_array[0])); + $position = $this->ossClient->appendObject($this->bucket, $object, $content_array[1], $position, $options); + $this->assertEquals($position, strlen($content_array[0]) + strlen($content_array[1])); + $position = $this->ossClient->appendObject($this->bucket, $object, $content_array[2], $position, $options); + $this->assertEquals($position, strlen($content_array[0]) + strlen($content_array[1]) + strlen($content_array[1])); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 检查内容的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, implode($content_array)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除测试object + */ + try { + $this->ossClient->deleteObject($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 追加上传本地文件 + */ + try { + $position = $this->ossClient->appendFile($this->bucket, $object, __FILE__, 0, $options); + $this->assertEquals($position, filesize(__FILE__)); + $position = $this->ossClient->appendFile($this->bucket, $object, __FILE__, $position, $options); + $this->assertEquals($position, filesize(__FILE__) * 2); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 检查复制的是否相同 + */ + try { + $content = $this->ossClient->getObject($this->bucket, $object); + $this->assertEquals($content, file_get_contents(__FILE__) . file_get_contents(__FILE__)); + } catch (OssException $e) { + $this->assertFalse(true); + } + + /** + * 删除测试object + */ + try { + $this->ossClient->deleteObject($this->bucket, $object); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function setUp() + { + parent::setUp(); + $this->ossClient->putObject($this->bucket, 'oss-php-sdk-test/upload-test-object-name.txt', file_get_contents(__FILE__)); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientRestoreObjectTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientRestoreObjectTest.php new file mode 100755 index 0000000..cc1412f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientRestoreObjectTest.php @@ -0,0 +1,96 @@ +ossClient->putObject($this->iaBucket, $object,'testcontent'); + try{ + $this->ossClient->restoreObject($this->iaBucket, $object); + $this->assertTrue(false); + }catch (OssException $e){ + $this->assertEquals('400', $e->getHTTPStatus()); + $this->assertEquals('OperationNotSupported', $e->getErrorCode()); + } + } + + public function testNullObjectRestoreObject() + { + $object = 'null-object'; + + try{ + $this->ossClient->restoreObject($this->bucket, $object); + $this->assertTrue(false); + }catch (OssException $e){ + $this->assertEquals('404', $e->getHTTPStatus()); + } + } + + public function testArchiveRestoreObject() + { + $object = 'storage-object'; + + $this->ossClient->putObject($this->archiveBucket, $object,'testcontent'); + try{ + $this->ossClient->getObject($this->archiveBucket, $object); + $this->assertTrue(false); + }catch (OssException $e){ + $this->assertEquals('403', $e->getHTTPStatus()); + $this->assertEquals('InvalidObjectState', $e->getErrorCode()); + } + $result = $this->ossClient->restoreObject($this->archiveBucket, $object); + common::waitMetaSync(); + $this->assertEquals('202', $result['info']['http_code']); + + try{ + $this->ossClient->restoreObject($this->archiveBucket, $object); + }catch(OssException $e){ + $this->assertEquals('409', $e->getHTTPStatus()); + $this->assertEquals('RestoreAlreadyInProgress', $e->getErrorCode()); + } + } + + public function setUp() + { + parent::setUp(); + + $this->iaBucket = 'ia-' . $this->bucket; + $this->archiveBucket = 'archive-' . $this->bucket; + $options = array( + OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA + ); + + $this->ossClient->createBucket($this->iaBucket, OssClient::OSS_ACL_TYPE_PRIVATE, $options); + + $options = array( + OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_ARCHIVE + ); + + $this->ossClient->createBucket($this->archiveBucket, OssClient::OSS_ACL_TYPE_PRIVATE, $options); + } + + public function tearDown() + { + parent::tearDown(); + + $object = 'storage-object'; + + $this->ossClient->deleteObject($this->iaBucket, $object); + $this->ossClient->deleteObject($this->archiveBucket, $object); + $this->ossClient->deleteBucket($this->iaBucket); + $this->ossClient->deleteBucket($this->archiveBucket); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientSignatureTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientSignatureTest.php new file mode 100755 index 0000000..109121d --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientSignatureTest.php @@ -0,0 +1,111 @@ +ossClient->putObject($this->bucket, $object, file_get_contents(__FILE__)); + $timeout = 3600; + try { + $signedUrl = $this->ossClient->signUrl($this->bucket, $object, $timeout); + } catch (OssException $e) { + $this->assertFalse(true); + } + + $request = new RequestCore($signedUrl); + $request->set_method('GET'); + $request->add_header('Content-Type', ''); + $request->send_request(); + $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code()); + $this->assertEquals(file_get_contents(__FILE__), $res->body); + } + + public function testGetSignedUrlForPuttingObject() + { + $object = "a.file"; + $timeout = 3600; + try { + $signedUrl = $this->ossClient->signUrl($this->bucket, $object, $timeout, "PUT"); + $content = file_get_contents(__FILE__); + $request = new RequestCore($signedUrl); + $request->set_method('PUT'); + $request->add_header('Content-Type', ''); + $request->add_header('Content-Length', strlen($content)); + $request->set_body($content); + $request->send_request(); + $res = new ResponseCore($request->get_response_header(), + $request->get_response_body(), $request->get_response_code()); + $this->assertTrue($res->isOK()); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testGetSignedUrlForPuttingObjectFromFile() + { + $file = __FILE__; + $object = "a.file"; + $timeout = 3600; + $options = array('Content-Type' => 'txt'); + try { + $signedUrl = $this->ossClient->signUrl($this->bucket, $object, $timeout, "PUT", $options); + $request = new RequestCore($signedUrl); + $request->set_method('PUT'); + $request->add_header('Content-Type', 'txt'); + $request->set_read_file($file); + $request->set_read_stream_size(filesize($file)); + $request->send_request(); + $res = new ResponseCore($request->get_response_header(), + $request->get_response_body(), $request->get_response_code()); + $this->assertTrue($res->isOK()); + } catch (OssException $e) { + $this->assertFalse(true); + } + + } + + public function tearDown() + { + $this->ossClient->deleteObject($this->bucket, "a.file"); + parent::tearDown(); + } + + public function setUp() + { + parent::setUp(); + /** + * 上传本地变量到bucket + */ + $object = "a.file"; + $content = file_get_contents(__FILE__); + $options = array( + OssClient::OSS_LENGTH => strlen($content), + OssClient::OSS_HEADERS => array( + 'Expires' => 'Fri, 28 Feb 2020 05:38:42 GMT', + 'Cache-Control' => 'no-cache', + 'Content-Disposition' => 'attachment;filename=oss_download.log', + 'Content-Encoding' => 'utf-8', + 'Content-Language' => 'zh-CN', + 'x-oss-server-side-encryption' => 'AES256', + 'x-oss-meta-self-define-title' => 'user define meta info', + ), + ); + + try { + $this->ossClient->putObject($this->bucket, $object, $content, $options); + } catch (OssException $e) { + $this->assertFalse(true); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientTest.php new file mode 100755 index 0000000..f92b346 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssClientTest.php @@ -0,0 +1,216 @@ +assertFalse($ossClient->isUseSSL()); + $ossClient->setUseSSL(true); + $this->assertTrue($ossClient->isUseSSL()); + $this->assertTrue(true); + $this->assertEquals(3, $ossClient->getMaxRetries()); + $ossClient->setMaxTries(4); + $this->assertEquals(4, $ossClient->getMaxRetries()); + $ossClient->setTimeout(10); + $ossClient->setConnectTimeout(20); + } catch (OssException $e) { + assertFalse(true); + } + } + + public function testConstrunct2() + { + try { + $ossClient = new OssClient('id', "", 'http://oss-cn-hangzhou.aliyuncs.com'); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals("access key secret is empty", $e->getMessage()); + } + } + + public function testConstrunct3() + { + try { + $ossClient = new OssClient("", 'key', 'http://oss-cn-hangzhou.aliyuncs.com'); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals("access key id is empty", $e->getMessage()); + } + } + + public function testConstrunct4() + { + try { + $ossClient = new OssClient('id', 'key', ""); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('endpoint is empty', $e->getMessage()); + } + } + + public function testConstrunct5() + { + try { + $ossClient = new OssClient('id', 'key', "123.123.123.1"); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + public function testConstrunct6() + { + try { + $ossClient = new OssClient('id', 'key', "https://123.123.123.1"); + $this->assertTrue($ossClient->isUseSSL()); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + public function testConstrunct7() + { + try { + $ossClient = new OssClient('id', 'key', "http://123.123.123.1"); + $this->assertFalse($ossClient->isUseSSL()); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + public function testConstrunct8() + { + try { + $ossClient = new OssClient('id', 'key', "http://123.123.123.1", true); + $ossClient->listBuckets(); + $this->assertFalse(true); + } catch (OssException $e) { + + } + } + + public function testConstrunct9() + { + try { + $accessKeyId = ' ' . getenv('OSS_ACCESS_KEY_ID') . ' '; + $accessKeySecret = ' ' . getenv('OSS_ACCESS_KEY_SECRET') . ' '; + $endpoint = ' ' . getenv('OSS_ENDPOINT') . '/ '; + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false); + $ossClient->listBuckets(); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testSupportPutEmptyObject() + { + try { + $accessKeyId = ' ' . getenv('OSS_ACCESS_KEY_ID') . ' '; + $accessKeySecret = ' ' . getenv('OSS_ACCESS_KEY_SECRET') . ' '; + $endpoint = ' ' . getenv('OSS_ENDPOINT') . '/ '; + $bucket = getenv('OSS_BUCKET'); + $ossClient = new OssClient($accessKeyId, $accessKeySecret , $endpoint, false); + $ossClient->putObject($bucket,'test_emptybody',''); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testCreateObjectDir() + { + try { + $accessKeyId = ' ' . getenv('OSS_ACCESS_KEY_ID') . ' '; + $accessKeySecret = ' ' . getenv('OSS_ACCESS_KEY_SECRET') . ' '; + $endpoint = ' ' . getenv('OSS_ENDPOINT') . '/ '; + $bucket = getenv('OSS_BUCKET'); + $object='test-dir'; + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false); + $ossClient->createObjectDir($bucket,$object); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testGetBucketCors() + { + try { + $accessKeyId = ' ' . getenv('OSS_ACCESS_KEY_ID') . ' '; + $accessKeySecret = ' ' . getenv('OSS_ACCESS_KEY_SECRET') . ' '; + $endpoint = ' ' . getenv('OSS_ENDPOINT') . '/ '; + $bucket = getenv('OSS_BUCKET'); + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false); + $ossClient->getBucketCors($bucket); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testGetBucketCname() + { + try { + $accessKeyId = ' ' . getenv('OSS_ACCESS_KEY_ID') . ' '; + $accessKeySecret = ' ' . getenv('OSS_ACCESS_KEY_SECRET') . ' '; + $endpoint = ' ' . getenv('OSS_ENDPOINT') . '/ '; + $bucket = getenv('OSS_BUCKET'); + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false); + $ossClient->getBucketCname($bucket); + } catch (OssException $e) { + $this->assertFalse(true); + } + } + + public function testProxySupport() + { + $accessKeyId = ' ' . getenv('OSS_ACCESS_KEY_ID') . ' '; + $accessKeySecret = ' ' . getenv('OSS_ACCESS_KEY_SECRET') . ' '; + $endpoint = ' ' . getenv('OSS_ENDPOINT') . '/ '; + $bucket = getenv('OSS_BUCKET') . '-proxy'; + $requestProxy = getenv('OSS_PROXY'); + $key = 'test-proxy-srv-object'; + $content = 'test-content'; + $proxys = parse_url($requestProxy); + + $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, null, $requestProxy); + + $result = $ossClient->createBucket($bucket); + $this->checkProxy($result, $proxys); + + $result = $ossClient->putObject($bucket, $key, $content); + $this->checkProxy($result, $proxys); + $result = $ossClient->getObject($bucket, $key); + $this->assertEquals($content, $result); + + // list object + $objectListInfo = $ossClient->listObjects($bucket); + $objectList = $objectListInfo->getObjectList(); + $this->assertNotNull($objectList); + $this->assertTrue(is_array($objectList)); + $objects = array(); + foreach ($objectList as $value) { + $objects[] = $value->getKey(); + } + $this->assertEquals(1, count($objects)); + $this->assertTrue(in_array($key, $objects)); + + $result = $ossClient->deleteObject($bucket, $key); + $this->checkProxy($result,$proxys); + + $result = $ossClient->deleteBucket($bucket); + $this->checkProxy($result, $proxys); + } + + private function checkProxy($result, $proxys) + { + $this->assertEquals($result['info']['primary_ip'], $proxys['host']); + $this->assertEquals($result['info']['primary_port'], $proxys['port']); + $this->assertTrue(array_key_exists('via', $result)); + } + +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssExceptionTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssExceptionTest.php new file mode 100755 index 0000000..4a418d5 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssExceptionTest.php @@ -0,0 +1,19 @@ +assertTrue(false); + } catch (OssException $e) { + $this->assertNotNull($e); + $this->assertEquals($e->getMessage(), "ERR"); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssUtilTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssUtilTest.php new file mode 100755 index 0000000..adf6457 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/OssUtilTest.php @@ -0,0 +1,225 @@ +assertEquals(OssUtil::chkChinese("hello,world"), 0); + $str = '你好,这里是卖咖啡!'; + $strGBK = OssUtil::encodePath($str); + $this->assertEquals(OssUtil::chkChinese($str), 1); + $this->assertEquals(OssUtil::chkChinese($strGBK), 1); + } + + public function testIsGB2312() + { + $str = '你好,这里是卖咖啡!'; + $this->assertFalse(OssUtil::isGb2312($str)); + } + + public function testCheckChar() + { + $str = '你好,这里是卖咖啡!'; + $this->assertFalse(OssUtil::checkChar($str)); + $this->assertTrue(OssUtil::checkChar(iconv("UTF-8", "GB2312//IGNORE", $str))); + } + + public function testIsIpFormat() + { + $this->assertTrue(OssUtil::isIPFormat("10.101.160.147")); + $this->assertTrue(OssUtil::isIPFormat("12.12.12.34")); + $this->assertTrue(OssUtil::isIPFormat("12.12.12.12")); + $this->assertTrue(OssUtil::isIPFormat("255.255.255.255")); + $this->assertTrue(OssUtil::isIPFormat("0.1.1.1")); + $this->assertFalse(OssUtil::isIPFormat("0.1.1.x")); + $this->assertFalse(OssUtil::isIPFormat("0.1.1.256")); + $this->assertFalse(OssUtil::isIPFormat("256.1.1.1")); + $this->assertFalse(OssUtil::isIPFormat("0.1.1.0.1")); + $this->assertTrue(OssUtil::isIPFormat("10.10.10.10:123")); + } + + public function testToQueryString() + { + $option = array("a" => "b"); + $this->assertEquals('a=b', OssUtil::toQueryString($option)); + } + + public function testSReplace() + { + $str = "<>&'\""; + $this->assertEquals("&lt;&gt;&'"", OssUtil::sReplace($str)); + } + + public function testCheckChinese() + { + $str = '你好,这里是卖咖啡!'; + $this->assertEquals(OssUtil::chkChinese($str), 1); + if (OssUtil::isWin()) { + $strGB = OssUtil::encodePath($str); + $this->assertEquals($str, iconv("GB2312", "UTF-8", $strGB)); + } + } + + public function testValidateOption() + { + $option = 'string'; + + try { + OssUtil::validateOptions($option); + $this->assertFalse(true); + } catch (OssException $e) { + $this->assertEquals("string:option must be array", $e->getMessage()); + } + + $option = null; + + try { + OssUtil::validateOptions($option); + $this->assertTrue(true); + } catch (OssException $e) { + $this->assertFalse(true); + } + + } + + public function testCreateDeleteObjectsXmlBody() + { + $xml = <<trueobj1 +BBBB; + $a = array('obj1'); + $this->assertEquals($xml, $this->cleanXml(OssUtil::createDeleteObjectsXmlBody($a, 'true'))); + } + + public function testCreateCompleteMultipartUploadXmlBody() + { + $xml = <<2xx +BBBB; + $a = array(array("PartNumber" => 2, "ETag" => "xx")); + $this->assertEquals($this->cleanXml(OssUtil::createCompleteMultipartUploadXmlBody($a)), $xml); + } + + public function testCreateBucketXmlBody() + { + $xml = <<Standard +BBBB; + $storageClass ="Standard"; + $this->assertEquals($this->cleanXml(OssUtil::createBucketXmlBody($storageClass)), $xml); + } + + public function testValidateBucket() + { + $this->assertTrue(OssUtil::validateBucket("xxx")); + $this->assertFalse(OssUtil::validateBucket("XXXqwe123")); + $this->assertFalse(OssUtil::validateBucket("XX")); + $this->assertFalse(OssUtil::validateBucket("/X")); + $this->assertFalse(OssUtil::validateBucket("")); + } + + public function testValidateObject() + { + $this->assertTrue(OssUtil::validateObject("xxx")); + $this->assertTrue(OssUtil::validateObject("xxx23")); + $this->assertTrue(OssUtil::validateObject("12321-xxx")); + $this->assertTrue(OssUtil::validateObject("x")); + $this->assertFalse(OssUtil::validateObject("/aa")); + $this->assertFalse(OssUtil::validateObject("\\aa")); + $this->assertFalse(OssUtil::validateObject("")); + } + + public function testStartWith() + { + $this->assertTrue(OssUtil::startsWith("xxab", "xx"), true); + } + + public function testReadDir() + { + $list = OssUtil::readDir("./src", ".|..|.svn|.git", true); + $this->assertNotNull($list); + } + + public function testIsWin() + { + //$this->assertTrue(OssUtil::isWin()); + } + + public function testGetMd5SumForFile() + { + $this->assertEquals(OssUtil::getMd5SumForFile(__FILE__, 0, filesize(__FILE__) - 1), base64_encode(md5(file_get_contents(__FILE__), true))); + } + + public function testGenerateFile() + { + $path = __DIR__ . DIRECTORY_SEPARATOR . "generatedFile.txt"; + OssUtil::generateFile($path, 1024 * 1024); + $this->assertEquals(filesize($path), 1024 * 1024); + unlink($path); + } + + public function testThrowOssExceptionWithMessageIfEmpty() + { + $null = null; + try { + OssUtil::throwOssExceptionWithMessageIfEmpty($null, "xx"); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('xx', $e->getMessage()); + } + } + + public function testThrowOssExceptionWithMessageIfEmpty2() + { + $null = ""; + try { + OssUtil::throwOssExceptionWithMessageIfEmpty($null, "xx"); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('xx', $e->getMessage()); + } + } + + public function testValidContent() + { + $null = ""; + try { + OssUtil::validateContent($null); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('http body content is invalid', $e->getMessage()); + } + + $notnull = "x"; + try { + OssUtil::validateContent($notnull); + $this->assertTrue(true); + } catch (OssException $e) { + $this->assertEquals('http body content is invalid', $e->getMessage()); + } + } + + public function testThrowOssExceptionWithMessageIfEmpty3() + { + $null = "xx"; + try { + OssUtil::throwOssExceptionWithMessageIfEmpty($null, "xx"); + $this->assertTrue(True); + } catch (OssException $e) { + $this->assertTrue(false); + } + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } + +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/PutSetDeleteResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/PutSetDeleteResultTest.php new file mode 100755 index 0000000..b298e44 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/PutSetDeleteResultTest.php @@ -0,0 +1,66 @@ +assertFalse(true); + } catch (OssException $e) { + $this->assertEquals('raw response is null', $e->getMessage()); + } + } + + public function testOkResponse() + { + $header= array( + 'x-oss-request-id' => '582AA51E004C4550BD27E0E4', + 'etag' => '595FA1EA77945233921DF12427F9C7CE', + 'content-md5' => 'WV+h6neUUjOSHfEkJ/nHzg==', + 'info' => array( + 'http_code' => '200', + 'method' => 'PUT' + ), + ); + $response = new ResponseCore($header, "this is a mock body, just for test", 200); + $result = new PutSetDeleteResult($response); + $data = $result->getData(); + $this->assertTrue($result->isOK()); + $this->assertEquals("this is a mock body, just for test", $data['body']); + $this->assertEquals('582AA51E004C4550BD27E0E4', $data['x-oss-request-id']); + $this->assertEquals('595FA1EA77945233921DF12427F9C7CE', $data['etag']); + $this->assertEquals('WV+h6neUUjOSHfEkJ/nHzg==', $data['content-md5']); + $this->assertEquals('200', $data['info']['http_code']); + $this->assertEquals('PUT', $data['info']['method']); + } + + public function testFailResponse() + { + $response = new ResponseCore(array(), "", 301); + try { + new PutSetDeleteResult($response); + $this->assertFalse(true); + } catch (OssException $e) { + + } + } + + public function setUp() + { + + } + + public function tearDown() + { + + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/RefererConfigTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/RefererConfigTest.php new file mode 100755 index 0000000..8360a24 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/RefererConfigTest.php @@ -0,0 +1,54 @@ + + +true + +http://www.aliyun.com +https://www.aliyun.com +http://www.*.com +https://www.?.aliyuncs.com + + +BBBB; + + private $validXml2 = << + +true + +http://www.aliyun.com + + +BBBB; + + public function testParseValidXml() + { + $refererConfig = new RefererConfig(); + $refererConfig->parseFromXml($this->validXml); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($refererConfig->serializeToXml())); + } + + public function testParseValidXml2() + { + $refererConfig = new RefererConfig(); + $refererConfig->parseFromXml($this->validXml2); + $this->assertEquals(true, $refererConfig->isAllowEmptyReferer()); + $this->assertEquals(1, count($refererConfig->getRefererList())); + $this->assertEquals($this->cleanXml($this->validXml2), $this->cleanXml(strval($refererConfig))); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/StorageCapacityTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/StorageCapacityTest.php new file mode 100755 index 0000000..4562da7 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/StorageCapacityTest.php @@ -0,0 +1,59 @@ + + + 1 + +BBBB; + + private $validXml = << + + 1 + +BBBB; + + public function testParseInValidXml() + { + $response = new ResponseCore(array(), $this->inValidXml, 300); + try { + new GetStorageCapacityResult($response); + $this->assertTrue(false); + } catch (OssException $e) {} + } + + public function testParseEmptyXml() + { + $response = new ResponseCore(array(), "", 300); + try { + new GetStorageCapacityResult($response); + $this->assertTrue(false); + } catch (OssException $e) {} + } + + public function testParseValidXml() + { + $response = new ResponseCore(array(), $this->validXml, 200); + $result = new GetStorageCapacityResult($response); + $this->assertEquals($result->getData(), 1); + } + + public function testSerializeToXml() + { + $xml = "\n1\n"; + + $storageCapacityConfig = new StorageCapacityConfig(1); + $content = $storageCapacityConfig->serializeToXml(); + $this->assertEquals($content, $xml); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/SymlinkTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/SymlinkTest.php new file mode 100755 index 0000000..d257c94 --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/SymlinkTest.php @@ -0,0 +1,74 @@ +ossClient ->putObject($bucket, $object, 'test_content'); + $this->ossClient->putSymlink($bucket, $symlink, $object); + $result = $this->ossClient->getObject($bucket, $symlink); + $this->assertEquals('test_content', $result); + + $this->ossClient ->putObject($bucket, $special_object, 'test_content'); + $this->ossClient->putSymlink($bucket, $symlink, $special_object); + $result = $this->ossClient->getObject($bucket, $symlink); + $this->assertEquals('test_content', $result); + } + + public function testGetSymlink() + { + $bucket = getenv('OSS_BUCKET'); + $symlink = 'test-link'; + $object = 'exist_object^$#!~'; + + $result = $this->ossClient->getSymlink($bucket, $symlink); + $this->assertEquals($result[OssClient::OSS_SYMLINK_TARGET], $object); + $this->assertEquals('200', $result[OssClient::OSS_INFO][OssClient::OSS_HTTP_CODE]); + $this->assertTrue(isset($result[OssClient::OSS_ETAG])); + $this->assertTrue(isset($result[OssClient::OSS_REQUEST_ID])); + } + + public function testPutNullSymlink() + { + $bucket = getenv('OSS_BUCKET'); + $symlink = 'null-link'; + $object_not_exist = 'not_exist_object+$#!b不'; + $this->ossClient->putSymlink($bucket, $symlink, $object_not_exist); + + try{ + $this->ossClient->getObject($bucket, $symlink); + $this->assertTrue(false); + }catch (OssException $e){ + $this->assertEquals('The symlink target object does not exist', $e->getErrorMessage()); + } + } + + public function testGetNullSymlink() + { + $bucket = getenv('OSS_BUCKET'); + $symlink = 'null-link-new'; + + try{ + $result = $this->ossClient->getSymlink($bucket, $symlink); + $this->assertTrue(false); + }catch (OssException $e){ + $this->assertEquals('The specified key does not exist.', $e->getErrorMessage()); + } + } +} + + diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/TestOssClientBase.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/TestOssClientBase.php new file mode 100755 index 0000000..4abd31f --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/TestOssClientBase.php @@ -0,0 +1,51 @@ +bucket = Common::getBucketName() . rand(100000, 999999); + $this->ossClient = Common::getOssClient(); + $this->ossClient->createBucket($this->bucket); + Common::waitMetaSync(); + } + + public function tearDown() + { + if (!$this->ossClient->doesBucketExist($this->bucket)) { + return; + } + + $objects = $this->ossClient->listObjects( + $this->bucket, array('max-keys' => 1000, 'delimiter' => ''))->getObjectList(); + $keys = array(); + foreach ($objects as $obj) { + $keys[] = $obj->getKey(); + } + if (count($keys) > 0) { + $this->ossClient->deleteObjects($this->bucket, $keys); + } + $uploads = $this->ossClient->listMultipartUploads($this->bucket)->getUploads(); + foreach ($uploads as $up) { + $this->ossClient->abortMultipartUpload($this->bucket, $up->getKey(), $up->getUploadId()); + } + + $this->ossClient->deleteBucket($this->bucket); + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/UploadPartResultTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/UploadPartResultTest.php new file mode 100755 index 0000000..e4789ef --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/UploadPartResultTest.php @@ -0,0 +1,33 @@ + '7265F4D211B56873A381D321F586E4A9'); + private $invalidHeader = array(); + + public function testParseValidHeader() + { + $response = new ResponseCore($this->validHeader, "", 200); + $result = new UploadPartResult($response); + $eTag = $result->getData(); + $this->assertEquals('7265F4D211B56873A381D321F586E4A9', $eTag); + } + + public function testParseInvalidHeader() + { + $response = new ResponseCore($this->invalidHeader, "", 200); + try { + new UploadPartResult($response); + $this->assertTrue(false); + } catch (OssException $e) { + $this->assertEquals('cannot get ETag', $e->getMessage()); + } + } +} diff --git a/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/WebsiteConfigTest.php b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/WebsiteConfigTest.php new file mode 100755 index 0000000..2ec0fcb --- /dev/null +++ b/aliyun-oss-php-sdk-2.3.0/tests/OSS/Tests/WebsiteConfigTest.php @@ -0,0 +1,56 @@ + + + +index.html + + +errorDocument.html + + +BBBB; + + private $nullXml = << +BBBB; + private $nullXml2 = << +BBBB; + + public function testParseValidXml() + { + $websiteConfig = new WebsiteConfig("index"); + $websiteConfig->parseFromXml($this->validXml); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($websiteConfig->serializeToXml())); + } + + public function testParsenullXml() + { + $websiteConfig = new WebsiteConfig(); + $websiteConfig->parseFromXml($this->nullXml); + $this->assertTrue($this->cleanXml($this->nullXml) === $this->cleanXml($websiteConfig->serializeToXml()) || + $this->cleanXml($this->nullXml2) === $this->cleanXml($websiteConfig->serializeToXml())); + } + + public function testWebsiteConstruct() + { + $websiteConfig = new WebsiteConfig("index.html", "errorDocument.html"); + $this->assertEquals('index.html', $websiteConfig->getIndexDocument()); + $this->assertEquals('errorDocument.html', $websiteConfig->getErrorDocument()); + $this->assertEquals($this->cleanXml($this->validXml), $this->cleanXml($websiteConfig->serializeToXml())); + } + + private function cleanXml($xml) + { + return str_replace("\n", "", str_replace("\r", "", $xml)); + } +}