<?php include "SCS.php"; include "config.php"; if (count($argv) <= 1) { echo "ERROR\n"; exit; } $ttl = isset($argv[2]) ? $argv[2] : 3600; $scs = new SCS(AccessKey, SecretKey); $uploadFile = $argv[1]; $bucketName = BUCKETNAME; if (preg_match("/\\d+/", $uploadFile) > 0) { $m = k_run_time("files"); $uploadFile = $m[$uploadFile]["name"]; } $obj = SCS::getAuthenticatedURL($bucketName, $uploadFile, $ttl); echo "DOWNLOAD URL IS : \n"; echo $obj . "\n";
/** * Get the SCS response * * @return object | false */ public function getResponse() { $query = ''; if (sizeof($this->parameters) > 0) { $query = substr($this->uri, -1) !== '?' ? '?' : '&'; foreach ($this->parameters as $var => $value) { if ($value == null || $value == '') { $query .= $var . '&'; } else { $query .= $var . '=' . rawurlencode($value) . '&'; } } $query = substr($query, 0, -1); $this->uri .= $query; /* if (array_key_exists('acl', $this->parameters) || array_key_exists('location', $this->parameters) || array_key_exists('torrent', $this->parameters) || array_key_exists('website', $this->parameters) || array_key_exists('logging', $this->parameters)) { $this->resource .= $query; } */ $single_filter_list = array('acl', 'location', 'torrent', 'website', 'logging', 'relax', 'meta', 'uploads', 'part', 'copy', 'multipart'); $double_filter_list = array('uploadId', 'ip', 'partNumber'); foreach ($this->parameters as $var => $value) { if (in_array($var, $single_filter_list)) { $this->resource .= '?' . $var; break; } } $query_for_sign_list = array(); foreach ($this->parameters as $var => $value) { if (in_array($var, $double_filter_list)) { $query_for_sign_list[$var] = $value; } } if (count($query_for_sign_list) > 0) { ksort($query_for_sign_list); $query_for_sign = ''; foreach ($query_for_sign_list as $key => $value) { $query_for_sign .= $key . '=' . rawurlencode($value) . '&'; } $query_for_sign = substr($query_for_sign, 0, -1); if ($query_for_sign) { $this->resource .= (strpos($this->resource, '?') === false ? '?' : '&') . $query_for_sign; } } } $url = (SCS::$useSSL ? 'https://' : 'http://') . ($this->headers['Host'] !== '' ? $this->headers['Host'] : $this->endpoint) . $this->uri; /* @TODO delete */ //$url = (SCS::$useSSL ? 'https://' : 'http://') . '58.63.236.206' . $this->uri; //var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url); // Basic setup $curl = curl_init(); if (defined("DEBUG")) { curl_setopt($curl, CURLOPT_VERBOSE, 1); } curl_setopt($curl, CURLOPT_USERAGENT, 'SCS/console'); if (SCS::$useSSL) { // SSL Validation can now be optional for those with broken OpenSSL installations curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, SCS::$useSSLValidation ? 2 : 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, SCS::$useSSLValidation ? 1 : 0); if (SCS::$sslKey !== null) { curl_setopt($curl, CURLOPT_SSLKEY, SCS::$sslKey); } if (SCS::$sslCert !== null) { curl_setopt($curl, CURLOPT_SSLCERT, SCS::$sslCert); } if (SCS::$sslCACert !== null) { curl_setopt($curl, CURLOPT_CAINFO, SCS::$sslCACert); } } curl_setopt($curl, CURLOPT_URL, $url); if (SCS::$proxy != null && isset(SCS::$proxy['host'])) { curl_setopt($curl, CURLOPT_PROXY, SCS::$proxy['host']); curl_setopt($curl, CURLOPT_PROXYTYPE, SCS::$proxy['type']); if (isset(SCS::$proxy['user'], SCS::$proxy['pass']) && SCS::$proxy['user'] != null && SCS::$proxy['pass'] != null) { curl_setopt($curl, CURLOPT_PROXYUSERPWD, sprintf('%s:%s', SCS::$proxy['user'], SCS::$proxy['pass'])); } } // Headers $headers = array(); $amz = array(); foreach ($this->amzHeaders as $header => $value) { if (strlen($value) > 0) { $headers[] = $header . ': ' . $value; } } foreach ($this->headers as $header => $value) { if (strlen($value) > 0) { $headers[] = $header . ': ' . $value; } } // Collect AMZ headers for signature foreach ($this->amzHeaders as $header => $value) { if (strlen($value) > 0) { $amz[] = strtolower($header) . ':' . $value; } } // AMZ headers must be sorted if (sizeof($amz) > 0) { //sort($amz); usort($amz, array(&$this, '__sortMetaHeadersCmp')); $amz = "\n" . implode("\n", $amz); } else { $amz = ''; } if (SCS::hasAuth()) { // Authorization string (CloudFront stringToSign should only contain a date) if ($this->headers['Host'] == 'cloudfront.amazonaws.com') { $headers[] = 'Authorization: ' . SCS::__getSignature($this->headers['Date']); } else { if (isset($this->headers['s-sina-sha1'])) { $this->headers['Content-MD5'] = $this->headers['s-sina-sha1']; } $headers[] = 'Authorization: ' . SCS::__getSignature($this->verb . "\n" . $this->headers['Content-MD5'] . "\n" . $this->headers['Content-Type'] . "\n" . $this->headers['Date'] . $amz . "\n" . $this->resource); } } /* @todo delete */ //$headers[] = 'Host: ' . ($this->headers['Host'] !== '' ? $this->headers['Host'] : $this->endpoint); //print_r($headers); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, false); curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback')); curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback')); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); /* 必要时设置超时时间 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($curl, CURLOPT_TIMEOUT, 1200); */ // Request types switch ($this->verb) { case 'GET': break; case 'PUT': case 'POST': // POST only used for CloudFront if ($this->fp !== false) { curl_setopt($curl, CURLOPT_PUT, true); curl_setopt($curl, CURLOPT_INFILE, $this->fp); if ($this->size >= 0) { curl_setopt($curl, CURLOPT_INFILESIZE, $this->size); } } elseif ($this->data !== false) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb); curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); } else { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb); } break; case 'HEAD': curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD'); curl_setopt($curl, CURLOPT_NOBODY, true); break; case 'DELETE': curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; default: break; } // Execute, grab errors if (curl_exec($curl)) { $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE); } else { $this->response->error = array('code' => curl_errno($curl), 'message' => curl_error($curl), 'resource' => $this->resource); } //echo $this->response->body; @curl_close($curl); // Parse body into XML | JSON if ($this->response->error === false && isset($this->response->headers['type']) && ($this->response->headers['type'] == 'application/xml' || $this->response->headers['type'] == 'application/json') && isset($this->response->body)) { if ($this->response->headers['type'] == 'application/json') { $this->response->body = json_decode($this->response->body); } else { $this->response->body = simplexml_load_string($this->response->body); } // Grab SCS errors if (!in_array($this->response->code, array(200, 204, 206)) && isset($this->response->body->Code, $this->response->body->Message)) { $this->response->error = array('code' => (string) $this->response->body->Code, 'message' => (string) $this->response->body->Message); if (isset($this->response->body->Resource)) { $this->response->error['resource'] = (string) $this->response->body->Resource; } unset($this->response->body); } } // Clean up file resources if ($this->fp !== false && is_resource($this->fp)) { fclose($this->fp); } return $this->response; }
<?php include "SCS.php"; include "config.php"; if (count($argv) <= 1) { echo "ERROR\n"; exit; } $bucketName = BUCKETNAME; date_default_timezone_set('UTC'); $scs = new SCS(AccessKey, SecretKey); $m = $scs->deleteObject($bucketName, $argv[1]); if ($m) { echo "DELETE FINISHED \n"; } else { echo "DELETE FAILED\n"; }
/* 列出图片 */ case 'listimage': default: $allowFiles = $CONFIG['imageManagerAllowFiles']; $listSize = $CONFIG['imageManagerListSize']; $path = $CONFIG['imageManagerListPath']; } $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1); /* 获取参数 */ $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize; $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0; $end = $start + $size; /* 获取文件列表 */ $scs = new SCS($accessKey, $secretKey); //初始化新浪SCS $get_filelist = SCS::getBucket($bucket); //获取文件列表 foreach ($get_filelist as $value) { if ($_GET['action'] == 'listimage') { preg_match("/^upload\\/image\\/.*[{$allowFiles}]\$/", $value['name'], $urls); } else { if ($_GET['action'] == 'listfile') { preg_match("/^upload\\/file\\/.*[{$allowFiles}]\$/", $value['name'], $urls); } } if ($urls) { $files[] = array('url' => $bucket . "/" . $urls[0], 'mtime' => $value['time']); } } if (!count($files)) { return json_encode(array("state" => "no match file", "list" => array(), "start" => $start, "total" => count($files)));
// If you want to use PECL Fileinfo for MIME types: //if (!extension_loaded('fileinfo') && @dl('fileinfo.so')) $_ENV['MAGIC'] = '/usr/share/file/magic'; // Check if our upload file exists if (!file_exists($uploadFile) || !is_file($uploadFile)) { exit("\nERROR: No such file: {$uploadFile}\n\n"); } // Check for CURL if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll')) { exit("\nERROR: CURL extension not loaded\n\n"); } // Pointless without your keys! if (AccessKey == 'change-this' || SecretKey == 'change-this') { exit("\nERROR: access information required\n\nPlease edit the following lines in this file:\n\n" . "define('AccessKey', 'change-me');\ndefine('SecretKey', 'change-me');\n\n"); } // Instantiate the class $scs = new SCS(AccessKey, SecretKey); echo "SCS::getAuthenticatedURL(): " . SCS::getAuthenticatedURL('sdk', 'snapshot/snapshot.png', 86400000) . "\n"; // List your buckets: echo "SCS::listBuckets(): " . print_r($scs->listBuckets(), 1) . "\n"; // Create a bucket with public read access if ($scs->putBucket($bucketName, SCS::ACL_PUBLIC_READ)) { echo "Created bucket {$bucketName}" . PHP_EOL; // Put our file (also with public read access) if ($scs->putObjectFile($uploadFile, $bucketName, baseName($uploadFile), SCS::ACL_PUBLIC_READ)) { echo "SCS::putObjectFile(): File copied to {$bucketName}/" . baseName($uploadFile) . PHP_EOL; // Get the contents of our bucket $contents = $scs->getBucket($bucketName); echo "SCS::getBucket(): Files in bucket {$bucketName}: " . print_r($contents, 1); // Get object info $info = $scs->getObjectInfo($bucketName, baseName($uploadFile)); echo "SCS::getObjectInfo(): Info for {$bucketName}/" . baseName($uploadFile) . ': ' . print_r($info, 1);
} // Pointless without your BucketName! if (BucketName == 'change-this') { exit("\nERROR: BucketName required\n\nPlease edit the following lines in this file:\n\n" . "define('BucketName', 'change-me');\n\n"); } SCS::setAuth(AccessKey, SecretKey); $bucket = BucketName; $path = 'myfiles/'; // Can be empty '' $lifetime = 3600; // Period for which the parameters are valid $maxFileSize = 1024 * 1024 * 50; // 50 MB $metaHeaders = array('uid' => 123); $requestHeaders = array('Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename=${filename}'); $params = SCS::getHttpUploadPostParams($bucket, $path, SCS::ACL_PUBLIC_READ, $lifetime, $maxFileSize, 201, $metaHeaders, $requestHeaders, false); $uploadURL = 'http://' . $bucket . '.sinacloud.net/'; ?> <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>SCS Form Upload</title> </head> <body> <form method="post" action="<?php echo $uploadURL; ?> " enctype="multipart/form-data"> <?php foreach ($params as $p => $v) {
while (!feof($fp)) { //上传分片 $res = SCS::putObject(SCS::inputResourceMultipart($fp, 1024 * 512, $uploadId, $i), $bucket, $object); if (isset($res['hash'])) { echo 'Part: ' . $i . " OK! \n"; $part_info[] = array('PartNumber' => $i, 'ETag' => $res['hash']); } $i++; } //列分片 $parts = SCS::listParts($bucket, $object, $uploadId); //print_r($parts); //print_r($part_info); if (count($parts) > 0 && count($parts) == count($part_info)) { foreach ($parts as $part_number => $part) { //echo $part['etag'] . "\n"; //echo $part_info[$k]['ETag'] . "\n"; if ($part['etag'] != $part_info[$part_number - 1]['ETag']) { exit('分片不匹配'); break; } } //合并分片 echo "开始合并\n"; SCS::completeMultipartUpload($bucket, $object, $uploadId, $part_info); echo "上传完成\n"; fclose($fp); } } catch (SCSException $e) { echo $e->getMessage(); }
<?php include "SCS.php"; include "config.php"; $scs = new SCS(AccessKey, SecretKey); $bucketName = BUCKETNAME; $contents = $scs->getBucket($bucketName, PREFIX); $all_size = 0; $index = 0; foreach ($contents as $file) { $all_size += $file['size']; //var_dump($file); echo str_pad($index++ . ". " . $file['name'], 64, ".") . $file['size'] . "\n"; } echo "All file size: " . $all_size . "\n";
{ $acl = self::ACL_PRIVATE; if ($mode & 0x20 || $mode & 0x4) { $acl = self::ACL_PUBLIC_READ; } // You probably don't want to enable public write access if ($mode & 0x10 || $mode & 0x8 || $mode & 0x2 || $mode & 0x1) { $acl = self::ACL_PUBLIC_READ; } //$acl = self::ACL_PUBLIC_READ_WRITE; return $acl; } } stream_wrapper_register('scs', 'SCSWrapper'); ################################################################################ SCS::setAuth(AccessKey, SecretKey); $bucketName = uniqid('scs-test'); echo "Creating bucket: {$bucketName}\n"; var_dump(mkdir("scs://{$bucketName}")); echo "\nWriting file: {$bucketName}/test.txt\n"; var_dump(file_put_contents("scs://{$bucketName}/test.txt", "http://weibo.com/smcz !")); echo "\nReading file: {$bucketName}/test.txt\n"; var_dump(file_get_contents("scs://{$bucketName}/test.txt")); echo "\nContents for bucket: {$bucketName}\n"; foreach (new DirectoryIterator("scs://{$bucketName}") as $b) { echo "\t" . $b . "\n"; } echo "\nUnlinking: {$bucketName}/test.txt\n"; var_dump(unlink("scs://{$bucketName}/test.txt")); echo "\nRemoving bucket: {$bucketName}\n"; var_dump(rmdir("scs://{$bucketName}"));
<?php include "SCS.php"; include "config.php"; if (count($argv) <= 1) { echo "ERROR\n"; exit; } $uploadFile = $argv[1]; $uploadFile = realpath($uploadFile); echo "Upload " . $uploadFile . "\n"; if (!file_exists($uploadFile)) { echo "FILE NOT EXIST\n"; exit; } $scs = new SCS(AccessKey, SecretKey); $bucketName = BUCKETNAME; $m = $scs->putObjectFile($uploadFile, $bucketName, PREFIX . baseName($uploadFile), SCS::ACL_PUBLIC_READ); if ($m == true) { echo "UPLOAD OK ! \n"; } else { echo "UPLOAD FAILED ! \n"; }
/** * 删除附件 * * @static * @access public * @return boolean * @throws Typecho_Plugin_Exception */ public static function ScsDelete($filepath) { $option = self::getSCSconfig(); self::getSCSsdk(); $scs = new SCS($option->accesskey, $option->secretkey); if ($scs->deleteObject($option->bucket, $filepath)) { return true; } else { return false; } }