72 lines
2.3 KiB
PHP
72 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace DJMixHosting;
|
|
|
|
class CustomCDN
|
|
{
|
|
private $space;
|
|
private $region;
|
|
private $storageType;
|
|
private $accessKey;
|
|
private $secretKey;
|
|
private $public = false;
|
|
|
|
public function __construct($space, $region, $storageType, $accessKey, $secretKey)
|
|
{
|
|
$this->space = $space;
|
|
$this->region = $region;
|
|
$this->storageType = $storageType;
|
|
$this->accessKey = $accessKey;
|
|
$this->secretKey = $secretKey;
|
|
}
|
|
|
|
public function uploadFile($filePath, $spacePath)
|
|
{
|
|
$file = basename($filePath);
|
|
$date = gmdate('D, d M Y H:i:s T');
|
|
if ($this->public) {
|
|
$acl = "x-amz-acl:public-read";
|
|
} else {
|
|
$acl = "x-amz-acl:private";
|
|
}
|
|
$contentType = $this->getContentType($filePath);
|
|
$storageClass = "x-amz-storage-class:{$this->storageType}";
|
|
|
|
$stringToSign = "PUT\n\n{$contentType}\n{$date}\n{$acl}\n{$storageClass}\n/{$this->space}{$spacePath}{$file}";
|
|
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $this->secretKey, true));
|
|
|
|
$headers = ["Host: {$this->space}.{$this->region}.digitaloceanspaces.com", "Date: {$date}", "Content-Type: {$contentType}", "{$storageClass}", "{$acl}", "Authorization: AWS {$this->accessKey}:{$signature}"];
|
|
|
|
$ch = curl_init("https://{$this->space}.{$this->region}.digitaloceanspaces.com{$spacePath}{$file}");
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_PUT, true);
|
|
curl_setopt($ch, CURLOPT_INFILE, fopen($filePath, 'r'));
|
|
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filePath));
|
|
|
|
$response = curl_exec($ch);
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
return $error ? $error : $response;
|
|
}
|
|
|
|
private function getContentType($filePath)
|
|
{
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
$mimeType = finfo_file($finfo, $filePath);
|
|
finfo_close($finfo);
|
|
return $mimeType ?: 'application/octet-stream';
|
|
}
|
|
|
|
public function setPublic()
|
|
{
|
|
$this->public = true;
|
|
}
|
|
|
|
public function setPrivate()
|
|
{
|
|
$this->public = false;
|
|
}
|
|
}
|