Guest User

AwsS3

a guest
Dec 29th, 2020
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.19 KB | None | 0 0
  1. <?php
  2.  
  3. namespace BackEnd\Services;
  4.  
  5. define('PROJECT_ROOT', realpath(__DIR__ . '/..'));
  6. require PROJECT_ROOT . '/../../vendor/autoload.php';
  7.  
  8. use Aws\S3\S3Client;
  9. use Aws\Exception\AwsException;
  10. use Aws\S3\Exception\S3Exception;
  11. use Aws\Sts\StsClient;
  12.  
  13. class AWSS3
  14. {
  15.  
  16. // ACL flags
  17. const ACL_PRIVATE = 'private';
  18. const ACL_PUBLIC_READ = 'public-read';
  19. const ACL_PUBLIC_READ_WRITE = 'public-read-write';
  20. const ACL_AUTHENTICATED_READ = 'authenticated-read';
  21.  
  22. const STORAGE_CLASS_STANDARD = 'STANDARD';
  23. const STORAGE_CLASS_RRS = 'REDUCED_REDUNDANCY';
  24. const STORAGE_CLASS_STANDARD_IA = 'STANDARD_IA';
  25.  
  26. const SSE_NONE = '';
  27. const SSE_AES256 = 'AES256';
  28.  
  29. /**
  30. * The AWS Access key
  31. *
  32. * @var string
  33. * @access private
  34. * @static
  35. */
  36. private static $__accessKey = null;
  37.  
  38. /**
  39. * AWS Secret Key
  40. *
  41. * @var string
  42. * @access private
  43. * @static
  44. */
  45. private static $__secretKey = null;
  46.  
  47. /**
  48. * SSL Client key
  49. *
  50. * @var string
  51. * @access private
  52. * @static
  53. */
  54. private static $__sslKey = null;
  55.  
  56. /**
  57. * Default delimiter to be used, for example while getBucket().
  58. * @var string
  59. * @access public
  60. * @static
  61. */
  62. public static $defDelimiter = null;
  63.  
  64. /**
  65. * AWS URI
  66. *
  67. * @var string
  68. * @acess public
  69. * @static
  70. */
  71. public static $endpoint = 's3.amazonaws.com';
  72.  
  73. /**
  74. * Proxy information
  75. *
  76. * @var null|array
  77. * @access public
  78. * @static
  79. */
  80. public static $proxy = null;
  81.  
  82. /**
  83. * Connect using SSL?
  84. *
  85. * @var bool
  86. * @access public
  87. * @static
  88. */
  89. public static $useSSL = false;
  90.  
  91. /**
  92. * Use SSL validation?
  93. *
  94. * @var bool
  95. * @access public
  96. * @static
  97. */
  98. public static $useSSLValidation = true;
  99.  
  100. /**
  101. * Use SSL version
  102. *
  103. * @var const
  104. * @access public
  105. * @static
  106. */
  107. public static $useSSLVersion = CURL_SSLVERSION_TLSv1;
  108.  
  109. /**
  110. * Use PHP exceptions?
  111. *
  112. * @var bool
  113. * @access public
  114. * @static
  115. */
  116. public static $useExceptions = false;
  117.  
  118. /**
  119. * Time offset applied to time()
  120. * @access private
  121. * @static
  122. */
  123. private static $__timeOffset = 0;
  124.  
  125. /**
  126. * SSL client key
  127. *
  128. * @var bool
  129. * @access public
  130. * @static
  131. */
  132. public static $sslKey = null;
  133.  
  134. /**
  135. * SSL client certfificate
  136. *
  137. * @var string
  138. * @acess public
  139. * @static
  140. */
  141. public static $sslCert = null;
  142.  
  143. /**
  144. * SSL CA cert (only required if you are having problems with your system CA cert)
  145. *
  146. * @var string
  147. * @access public
  148. * @static
  149. */
  150. public static $sslCACert = null;
  151.  
  152. /**
  153. * Bucketname
  154. *
  155. * @var string
  156. * @access public
  157. * @static
  158. */
  159. public static $bucketname = '';
  160.  
  161. /**
  162. * Basepath
  163. *
  164. * @var string
  165. * @access public
  166. * @static
  167. */
  168. public static $basepath = '';
  169.  
  170. /**
  171. * AWS Key Pair ID
  172. *
  173. * @var string
  174. * @access private
  175. * @static
  176. */
  177. private static $__signingKeyPairId = null;
  178.  
  179. /**
  180. * Key resource, freeSigningKey() must be called to clear it from memory
  181. *
  182. * @var bool
  183. * @access private
  184. * @static
  185. */
  186. private static $__signingKeyResource = false;
  187.  
  188. private static $__client = null;
  189. private static $__stsclient = null;
  190. private static $__sessionname = 'sessionname';
  191. private static $__profile = 'arn:aws:iam::ID:instance-profile/POD-ROLE';
  192.  
  193. public static $region = null;
  194. /**
  195. * Constructor - if you're not using the class statically
  196. *
  197. * @param string $accessKey Access key
  198. * @param string $secretKey Secret key
  199. * @param boolean $useSSL Enable SSL
  200. * @param string $endpoint Amazon URI
  201. * @return void
  202. */
  203. public function __construct($accessKey = null, $secretKey = null, $useSSL = false, $endpoint = null, $bucketname = null, $basepath = null, $region = 'eu-west-1')
  204. {
  205. if (($accessKey !== null && $accessKey !== "") && ($secretKey !== null && $secretKey !== "")) {
  206. self::setAuth($accessKey, $secretKey);
  207. self::$__accessKey = $accessKey;
  208. self::$__secretKey = $secretKey;
  209. }
  210.  
  211. self::$useSSL = $useSSL;
  212. self::$endpoint = $endpoint;
  213. if ($basepath !== null)
  214. self::setBasepath($basepath);
  215.  
  216. if ($bucketname !== null)
  217. self::setBucketname($bucketname);
  218.  
  219. if ($region !== null)
  220. self::setRegion($region);
  221.  
  222. $this->setClient();
  223. }
  224.  
  225. public function getRegion()
  226. {
  227. return self::$region;
  228. }
  229.  
  230. public function getBasepath()
  231. {
  232. return self::$basepath;
  233. }
  234.  
  235. public function getBucketname()
  236. {
  237. return self::$bucketname;
  238. }
  239.  
  240. public function getEndpoint()
  241. {
  242. return self::$endpoint;
  243. }
  244.  
  245. public static function setBucketname($name)
  246. {
  247. self::$bucketname = $name;
  248. }
  249.  
  250. public static function setBasepath($base)
  251. {
  252. self::$basepath = $base;
  253. }
  254.  
  255. public function setClient()
  256. {
  257. //Se sono in possesso delle credenziali mi autentico, altrimenti uso il ruolo associato all'utenza
  258. try {
  259. if (self::hasAuth()) {
  260. self::$__client = new S3Client([
  261. 'version' => 'latest',
  262. 'region' => $this->getRegion(),
  263. 'credentials' => [
  264. 'key' => self::$__accessKey,
  265. 'secret' => self::$__secretKey,
  266. ],
  267. ]);
  268. } else {
  269. self::$__stsclient = new StsClient(
  270. [
  271. 'profile' => self::$__profile,
  272. 'version' => 'latest',
  273. 'region' => $this->getRegion(),
  274. 'use_aws_shared_config_files' => false,
  275. 'debug' => true
  276. ]
  277. );
  278. // print_r(self::$__stsclient);
  279. $result = self::$__stsclient->AssumeRole([
  280. 'RoleArn' => 'arn:aws:iam::ID:role/POD-ROLE',
  281. 'RoleSessionName' => self::$__sessionname,
  282. ]);
  283. echo "RESULT START";
  284. print_r($result);
  285. echo "RESULT END";
  286. self::$__client = new S3Client([
  287. 'version' => 'latest',
  288. 'region' => $this->getRegion(),
  289. 'debug' => true,
  290. 'credentials' => [
  291. 'key' => $result['Credentials']['AccessKeyId'],
  292. 'secret' => $result['Credentials']['SecretAccessKey'],
  293. 'token' => $result['Credentials']['SessionToken']
  294. ]
  295. ]);
  296. echo "CLIENT START";
  297. print_r(self::$__client);
  298. echo "CLIENT END";
  299. }
  300. } catch (AwsException $e) {
  301. echo $e->getMessage();
  302. echo "\n";
  303. }
  304. }
  305.  
  306. public static function setRegion($region)
  307. {
  308. self::$region = $region;
  309. }
  310.  
  311. /**
  312. * Set the service endpoint
  313. *
  314. * @param string $host Hostname
  315. * @return void
  316. */
  317. public function setEndpoint($host)
  318. {
  319. self::$endpoint = $host;
  320. }
  321.  
  322.  
  323. /**
  324. * Set AWS access key and secret key
  325. *
  326. * @param string $accessKey Access key
  327. * @param string $secretKey Secret key
  328. * @return void
  329. */
  330. public static function setAuth($accessKey, $secretKey)
  331. {
  332. self::$__accessKey = $accessKey;
  333. self::$__secretKey = $secretKey;
  334. }
  335.  
  336.  
  337. /**
  338. * Check if AWS keys have been set
  339. *
  340. * @return boolean
  341. */
  342. public static function hasAuth()
  343. {
  344. return (self::$__accessKey !== null && self::$__secretKey !== null);
  345. }
  346.  
  347.  
  348. /**
  349. * Set SSL on or off
  350. *
  351. * @param boolean $enabled SSL enabled
  352. * @param boolean $validate SSL certificate validation
  353. * @return void
  354. */
  355. public static function setSSL($enabled, $validate = true)
  356. {
  357. self::$useSSL = $enabled;
  358. self::$useSSLValidation = $validate;
  359. }
  360.  
  361.  
  362. /**
  363. * Set SSL client certificates (experimental)
  364. *
  365. * @param string $sslCert SSL client certificate
  366. * @param string $sslKey SSL client key
  367. * @param string $sslCACert SSL CA cert (only required if you are having problems with your system CA cert)
  368. * @return void
  369. */
  370. public static function setSSLAuth($sslCert = null, $sslKey = null, $sslCACert = null)
  371. {
  372. self::$sslCert = $sslCert;
  373. self::$sslKey = $sslKey;
  374. self::$sslCACert = $sslCACert;
  375. }
  376.  
  377. /**
  378. * Set proxy information
  379. *
  380. * @param string $host Proxy hostname and port (localhost:1234)
  381. * @param string $user Proxy username
  382. * @param string $pass Proxy password
  383. * @param constant $type CURL proxy type
  384. * @return void
  385. */
  386. public static function setProxy($host, $user = null, $pass = null, $type = CURLPROXY_SOCKS5)
  387. {
  388. self::$proxy = array('host' => $host, 'type' => $type, 'user' => $user, 'pass' => $pass);
  389. }
  390.  
  391. public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE)
  392. {
  393. if (self::$__client == null) return false;
  394. try {
  395. $result = self::$__client->putObject(['Bucket' => $bucket, 'Key' => $uri, 'Body' => file_get_contents($file), 'ACL' => $acl]);
  396. return $result['ObjectURL'];
  397. } catch (S3Exception $e) {
  398. echo "There was an error uploading the file.\n";
  399. echo $e->getMessage() . "\n";
  400. echo $e->getTraceAsString();
  401. return false;
  402. }
  403. }
  404.  
  405. public static function deleteObject($bucketName, $bucketfile)
  406. {
  407. if (self::$__client == null) return false;
  408. try {
  409. self::$__client->deleteObject(['Bucket' => $bucketName, 'Key' => $bucketfile]);
  410. return true;
  411. } catch (S3Exception $e) {
  412. echo "There was an error deleting the file.\n";
  413. echo $e->getMessage() . "\n";
  414. echo $e->getTraceAsString();
  415. return false;
  416. }
  417. }
  418.  
  419. public static function getBucket($bucketname, $path)
  420. {
  421. $objects = self::$__client->getIterator('ListObjects', array(
  422. 'Bucket' => $bucketname,
  423. 'Prefix' => $path . (substr($path, -1) == '/' ? '' : '/')
  424. ));
  425. return $objects;
  426. }
  427.  
  428. public static function getListObjects($bucketName, $bucketfile)
  429. {
  430. if (self::$__client == null) return false;
  431. $objects = [];
  432. try {
  433. $results = self::$__client->getPaginator('ListObjects', ['Bucket' => $bucketName, 'Prefix' => $bucketfile]);
  434. foreach ($results as $result) {
  435. if ($result['Contents'] !== null) {
  436. foreach ($result['Contents'] as $object) {
  437. if ($object['Size'] > 0) {
  438. $object['url'] = strpos($bucketfile, 'public') ? self::getObjectUrl($bucketName, $object['Key']) : self::getSignedUrl($bucketName, $object['Key']);
  439. array_push($objects, $object);
  440. }
  441. }
  442. }
  443. }
  444. return $objects;
  445. } catch (S3Exception $e) {
  446. echo "There was an error getting list of files.\n";
  447. echo $e->getMessage() . "\n";
  448. echo $e->getTraceAsString();
  449. return false;
  450. }
  451. }
  452.  
  453. public static function getSignedUrl($bucketName, $bucketfile)
  454. {
  455. if (self::$__client == null) return false;
  456. try {
  457. $cmd = self::$__client->getCommand('GetObject', ['Bucket' => $bucketName, 'Key' => $bucketfile]);
  458. $request = self::$__client->createPresignedRequest($cmd, '+60minutes');
  459. $url = (string)$request->getUri();
  460. return $url;
  461. } catch (S3Exception $e) {
  462. echo "There was an error getting the signataure of files.\n";
  463. echo $e->getMessage() . "\n";
  464. echo $e->getTraceAsString();
  465. return false;
  466. }
  467. }
  468.  
  469. public static function getObjectUrl($bucketName, $bucketfile)
  470. {
  471. if (self::$__client == null) return false;
  472. try {
  473. $url = self::$__client->getObjectUrl($bucketName,$bucketfile);
  474. return $url;
  475. } catch (S3Exception $e) {
  476. echo "There was an error getting the object url of file.\n";
  477. echo $e->getMessage() . "\n";
  478. echo $e->getTraceAsString();
  479. return false;
  480. }
  481. }
  482.  
  483. public static function getSingleObject($bucketName, $bucketfile)
  484. {
  485. if (self::$__client == null) return false;
  486. $objects = [];
  487. try {
  488. $results = self::$__client->getPaginator('ListObjects', ['Bucket' => $bucketName, 'Prefix' => $bucketfile]);
  489. foreach ($results as $result) {
  490. if ($result['Contents'] !== null) {
  491. if ($result['Contents'] !== null) {
  492. if ($result['Contents'][0] !== null) {
  493. $object = $result['Contents'][0];
  494. $object['url'] = strpos($bucketfile, 'public') ? self::getObjectUrl($bucketName, $object['Key']) : self::getSignedUrl($bucketName, $object['Key']);
  495. return $object['url'];
  496. }
  497. }
  498. }
  499. }
  500. return $objects;
  501. } catch (S3Exception $e) {
  502. echo "There was an error getting list of files.\n";
  503. echo $e->getMessage() . "\n";
  504. echo $e->getTraceAsString();
  505. return false;
  506. }
  507. }
  508. }
  509.  
Advertisement
Add Comment
Please, Sign In to add comment