PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Zend/Service/Amazon/S3.php

https://bitbucket.org/dbaltas/zend-framework-1.x-on-git
PHP | 1015 lines | 590 code | 109 blank | 316 comment | 105 complexity | 3fb11fbdc0e7df3cb60f100e617097eb MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, MIT
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Service
  17. * @subpackage Amazon_S3
  18. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: S3.php 24593 2012-01-05 20:35:02Z matthew $
  21. */
  22. /**
  23. * @see Zend_Service_Amazon_Abstract
  24. */
  25. require_once 'Zend/Service/Amazon/Abstract.php';
  26. /**
  27. * @see Zend_Crypt_Hmac
  28. */
  29. require_once 'Zend/Crypt/Hmac.php';
  30. /**
  31. * Amazon S3 PHP connection class
  32. *
  33. * @category Zend
  34. * @package Zend_Service
  35. * @subpackage Amazon_S3
  36. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. * @see http://docs.amazonwebservices.com/AmazonS3/2006-03-01/
  39. */
  40. class Zend_Service_Amazon_S3 extends Zend_Service_Amazon_Abstract
  41. {
  42. /**
  43. * Store for stream wrapper clients
  44. *
  45. * @var array
  46. */
  47. protected static $_wrapperClients = array();
  48. /**
  49. * Endpoint for the service
  50. *
  51. * @var Zend_Uri_Http
  52. */
  53. protected $_endpoint;
  54. const S3_ENDPOINT = 's3.amazonaws.com';
  55. const S3_ACL_PRIVATE = 'private';
  56. const S3_ACL_PUBLIC_READ = 'public-read';
  57. const S3_ACL_PUBLIC_WRITE = 'public-read-write';
  58. const S3_ACL_AUTH_READ = 'authenticated-read';
  59. const S3_REQUESTPAY_HEADER = 'x-amz-request-payer';
  60. const S3_ACL_HEADER = 'x-amz-acl';
  61. const S3_CONTENT_TYPE_HEADER = 'Content-Type';
  62. /**
  63. * Set S3 endpoint to use
  64. *
  65. * @param string|Zend_Uri_Http $endpoint
  66. * @return Zend_Service_Amazon_S3
  67. */
  68. public function setEndpoint($endpoint)
  69. {
  70. if (!($endpoint instanceof Zend_Uri_Http)) {
  71. $endpoint = Zend_Uri::factory($endpoint);
  72. }
  73. if (!$endpoint->valid()) {
  74. /**
  75. * @see Zend_Service_Amazon_S3_Exception
  76. */
  77. require_once 'Zend/Service/Amazon/S3/Exception.php';
  78. throw new Zend_Service_Amazon_S3_Exception('Invalid endpoint supplied');
  79. }
  80. $this->_endpoint = $endpoint;
  81. return $this;
  82. }
  83. /**
  84. * Get current S3 endpoint
  85. *
  86. * @return Zend_Uri_Http
  87. */
  88. public function getEndpoint()
  89. {
  90. return $this->_endpoint;
  91. }
  92. /**
  93. * Constructor
  94. *
  95. * @param string $accessKey
  96. * @param string $secretKey
  97. * @param string $region
  98. */
  99. public function __construct($accessKey=null, $secretKey=null, $region=null)
  100. {
  101. parent::__construct($accessKey, $secretKey, $region);
  102. $this->setEndpoint('http://'.self::S3_ENDPOINT);
  103. }
  104. /**
  105. * Verify if the bucket name is valid
  106. *
  107. * @param string $bucket
  108. * @return boolean
  109. */
  110. public function _validBucketName($bucket)
  111. {
  112. $len = strlen($bucket);
  113. if ($len < 3 || $len > 255) {
  114. /**
  115. * @see Zend_Service_Amazon_S3_Exception
  116. */
  117. require_once 'Zend/Service/Amazon/S3/Exception.php';
  118. throw new Zend_Service_Amazon_S3_Exception("Bucket name \"$bucket\" must be between 3 and 255 characters long");
  119. }
  120. if (preg_match('/[^a-z0-9\._-]/', $bucket)) {
  121. /**
  122. * @see Zend_Service_Amazon_S3_Exception
  123. */
  124. require_once 'Zend/Service/Amazon/S3/Exception.php';
  125. throw new Zend_Service_Amazon_S3_Exception("Bucket name \"$bucket\" contains invalid characters");
  126. }
  127. if (preg_match('/(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/', $bucket)) {
  128. /**
  129. * @see Zend_Service_Amazon_S3_Exception
  130. */
  131. require_once 'Zend/Service/Amazon/S3/Exception.php';
  132. throw new Zend_Service_Amazon_S3_Exception("Bucket name \"$bucket\" cannot be an IP address");
  133. }
  134. return true;
  135. }
  136. /**
  137. * Add a new bucket
  138. *
  139. * @param string $bucket
  140. * @return boolean
  141. */
  142. public function createBucket($bucket, $location = null)
  143. {
  144. $this->_validBucketName($bucket);
  145. $headers=array();
  146. if($location) {
  147. $data = '<CreateBucketConfiguration><LocationConstraint>'.$location.'</LocationConstraint></CreateBucketConfiguration>';
  148. $headers[self::S3_CONTENT_TYPE_HEADER]= 'text/plain';
  149. $headers['Content-size']= strlen($data);
  150. } else {
  151. $data = null;
  152. }
  153. $response = $this->_makeRequest('PUT', $bucket, null, $headers, $data);
  154. return ($response->getStatus() == 200);
  155. }
  156. /**
  157. * Checks if a given bucket name is available
  158. *
  159. * @param string $bucket
  160. * @return boolean
  161. */
  162. public function isBucketAvailable($bucket)
  163. {
  164. $response = $this->_makeRequest('HEAD', $bucket, array('max-keys'=>0));
  165. return ($response->getStatus() != 404);
  166. }
  167. /**
  168. * Checks if a given object exists
  169. *
  170. * @param string $object
  171. * @return boolean
  172. */
  173. public function isObjectAvailable($object)
  174. {
  175. $object = $this->_fixupObjectName($object);
  176. $response = $this->_makeRequest('HEAD', $object);
  177. return ($response->getStatus() == 200);
  178. }
  179. /**
  180. * Remove a given bucket. All objects in the bucket must be removed prior
  181. * to removing the bucket.
  182. *
  183. * @param string $bucket
  184. * @return boolean
  185. */
  186. public function removeBucket($bucket)
  187. {
  188. $response = $this->_makeRequest('DELETE', $bucket);
  189. // Look for a 204 No Content response
  190. return ($response->getStatus() == 204);
  191. }
  192. /**
  193. * Get metadata information for a given object
  194. *
  195. * @param string $object
  196. * @return array|false
  197. */
  198. public function getInfo($object)
  199. {
  200. $info = array();
  201. $object = $this->_fixupObjectName($object);
  202. $response = $this->_makeRequest('HEAD', $object);
  203. if ($response->getStatus() == 200) {
  204. $info['type'] = $response->getHeader('Content-type');
  205. $info['size'] = $response->getHeader('Content-length');
  206. $info['mtime'] = strtotime($response->getHeader('Last-modified'));
  207. $info['etag'] = $response->getHeader('ETag');
  208. }
  209. else {
  210. return false;
  211. }
  212. return $info;
  213. }
  214. /**
  215. * List the S3 buckets
  216. *
  217. * @return array|false
  218. */
  219. public function getBuckets()
  220. {
  221. $response = $this->_makeRequest('GET');
  222. if ($response->getStatus() != 200) {
  223. return false;
  224. }
  225. $xml = new SimpleXMLElement($response->getBody());
  226. $buckets = array();
  227. foreach ($xml->Buckets->Bucket as $bucket) {
  228. $buckets[] = (string)$bucket->Name;
  229. }
  230. return $buckets;
  231. }
  232. /**
  233. * Remove all objects in the bucket.
  234. *
  235. * @param string $bucket
  236. * @return boolean
  237. */
  238. public function cleanBucket($bucket)
  239. {
  240. $objects = $this->getObjectsByBucket($bucket);
  241. if (!$objects) {
  242. return false;
  243. }
  244. while (!empty($objects)) {
  245. foreach ($objects as $object) {
  246. $this->removeObject("$bucket/$object");
  247. }
  248. $params= array (
  249. 'marker' => $objects[count($objects)-1]
  250. );
  251. $objects = $this->getObjectsByBucket($bucket,$params);
  252. }
  253. return true;
  254. }
  255. /**
  256. * List the objects in a bucket.
  257. *
  258. * Provides the list of object keys that are contained in the bucket. Valid params include the following.
  259. * prefix - Limits the response to keys which begin with the indicated prefix. You can use prefixes to separate a bucket into different sets of keys in a way similar to how a file system uses folders.
  260. * marker - Indicates where in the bucket to begin listing. The list will only include keys that occur lexicographically after marker. This is convenient for pagination: To get the next page of results use the last key of the current page as the marker.
  261. * max-keys - The maximum number of keys you'd like to see in the response body. The server might return fewer than this many keys, but will not return more.
  262. * delimiter - Causes keys that contain the same string between the prefix and the first occurrence of the delimiter to be rolled up into a single result element in the CommonPrefixes collection. These rolled-up keys are not returned elsewhere in the response.
  263. *
  264. * @param string $bucket
  265. * @param array $params S3 GET Bucket Paramater
  266. * @return array|false
  267. */
  268. public function getObjectsByBucket($bucket, $params = array())
  269. {
  270. $response = $this->_makeRequest('GET', $bucket, $params);
  271. if ($response->getStatus() != 200) {
  272. return false;
  273. }
  274. $xml = new SimpleXMLElement($response->getBody());
  275. $objects = array();
  276. if (isset($xml->Contents)) {
  277. foreach ($xml->Contents as $contents) {
  278. foreach ($contents->Key as $object) {
  279. $objects[] = (string)$object;
  280. }
  281. }
  282. }
  283. return $objects;
  284. }
  285. /**
  286. * List the objects and common prefixes in a bucket.
  287. *
  288. * Provides the list of object keys and common prefixes that are contained in the bucket. Valid params include the following.
  289. * prefix - Limits the response to keys which begin with the indicated prefix. You can use prefixes to separate a bucket into different sets of keys in a way similar to how a file system uses folders.
  290. * marker - Indicates where in the bucket to begin listing. The list will only include keys that occur lexicographically after marker. This is convenient for pagination: To get the next page of results use the last key of the current page as the marker.
  291. * max-keys - The maximum number of keys you'd like to see in the response body. The server might return fewer than this many keys, but will not return more.
  292. * delimiter - Causes keys that contain the same string between the prefix and the first occurrence of the delimiter to be rolled up into a single result element in the CommonPrefixes collection. These rolled-up keys are not returned elsewhere in the response.
  293. *
  294. * @see ZF-11401
  295. * @param string $bucket
  296. * @param array $params S3 GET Bucket Paramater
  297. * @return array|false
  298. */
  299. public function getObjectsAndPrefixesByBucket($bucket, $params = array())
  300. {
  301. $response = $this->_makeRequest('GET', $bucket, $params);
  302. if ($response->getStatus() != 200) {
  303. return false;
  304. }
  305. $xml = new SimpleXMLElement($response->getBody());
  306. $objects = array();
  307. if (isset($xml->Contents)) {
  308. foreach ($xml->Contents as $contents) {
  309. foreach ($contents->Key as $object) {
  310. $objects[] = (string)$object;
  311. }
  312. }
  313. }
  314. $prefixes = array();
  315. if (isset($xml->CommonPrefixes)) {
  316. foreach ($xml->CommonPrefixes as $prefix) {
  317. foreach ($prefix->Prefix as $object) {
  318. $prefixes[] = (string)$object;
  319. }
  320. }
  321. }
  322. return array(
  323. 'objects' => $objects,
  324. 'prefixes' => $prefixes
  325. );
  326. }
  327. /**
  328. * Make sure the object name is valid
  329. *
  330. * @param string $object
  331. * @return string
  332. */
  333. protected function _fixupObjectName($object)
  334. {
  335. $nameparts = explode('/', $object);
  336. $this->_validBucketName($nameparts[0]);
  337. $firstpart = array_shift($nameparts);
  338. if (count($nameparts) == 0) {
  339. return $firstpart;
  340. }
  341. return $firstpart.'/'.join('/', array_map('rawurlencode', $nameparts));
  342. }
  343. /**
  344. * Get an object
  345. *
  346. * @param string $object
  347. * @param bool $paidobject This is "requestor pays" object
  348. * @return string|false
  349. */
  350. public function getObject($object, $paidobject=false)
  351. {
  352. $object = $this->_fixupObjectName($object);
  353. if ($paidobject) {
  354. $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
  355. }
  356. else {
  357. $response = $this->_makeRequest('GET', $object);
  358. }
  359. if ($response->getStatus() != 200) {
  360. return false;
  361. }
  362. return $response->getBody();
  363. }
  364. /**
  365. * Get an object using streaming
  366. *
  367. * Can use either provided filename for storage or create a temp file if none provided.
  368. *
  369. * @param string $object Object path
  370. * @param string $streamfile File to write the stream to
  371. * @param bool $paidobject This is "requestor pays" object
  372. * @return Zend_Http_Response_Stream|false
  373. */
  374. public function getObjectStream($object, $streamfile = null, $paidobject=false)
  375. {
  376. $object = $this->_fixupObjectName($object);
  377. self::getHttpClient()->setStream($streamfile?$streamfile:true);
  378. if ($paidobject) {
  379. $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
  380. }
  381. else {
  382. $response = $this->_makeRequest('GET', $object);
  383. }
  384. self::getHttpClient()->setStream(null);
  385. if ($response->getStatus() != 200 || !($response instanceof Zend_Http_Response_Stream)) {
  386. return false;
  387. }
  388. return $response;
  389. }
  390. /**
  391. * Upload an object by a PHP string
  392. *
  393. * @param string $object Object name
  394. * @param string|resource $data Object data (can be string or stream)
  395. * @param array $meta Metadata
  396. * @return boolean
  397. */
  398. public function putObject($object, $data, $meta=null)
  399. {
  400. $object = $this->_fixupObjectName($object);
  401. $headers = (is_array($meta)) ? $meta : array();
  402. if(!is_resource($data)) {
  403. $headers['Content-MD5'] = base64_encode(md5($data, true));
  404. }
  405. $headers['Expect'] = '100-continue';
  406. if (!isset($headers[self::S3_CONTENT_TYPE_HEADER])) {
  407. $headers[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($object);
  408. }
  409. $response = $this->_makeRequest('PUT', $object, null, $headers, $data);
  410. // Check the MD5 Etag returned by S3 against and MD5 of the buffer
  411. if ($response->getStatus() == 200) {
  412. // It is escaped by double quotes for some reason
  413. $etag = str_replace('"', '', $response->getHeader('Etag'));
  414. if (is_resource($data) || $etag == md5($data)) {
  415. return true;
  416. }
  417. }
  418. return false;
  419. }
  420. /**
  421. * Put file to S3 as object
  422. *
  423. * @param string $path File name
  424. * @param string $object Object name
  425. * @param array $meta Metadata
  426. * @return boolean
  427. */
  428. public function putFile($path, $object, $meta=null)
  429. {
  430. $data = @file_get_contents($path);
  431. if ($data === false) {
  432. /**
  433. * @see Zend_Service_Amazon_S3_Exception
  434. */
  435. require_once 'Zend/Service/Amazon/S3/Exception.php';
  436. throw new Zend_Service_Amazon_S3_Exception("Cannot read file $path");
  437. }
  438. if (!is_array($meta)) {
  439. $meta = array();
  440. }
  441. if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
  442. $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
  443. }
  444. return $this->putObject($object, $data, $meta);
  445. }
  446. /**
  447. * Put file to S3 as object, using streaming
  448. *
  449. * @param string $path File name
  450. * @param string $object Object name
  451. * @param array $meta Metadata
  452. * @return boolean
  453. */
  454. public function putFileStream($path, $object, $meta=null)
  455. {
  456. $data = @fopen($path, "rb");
  457. if ($data === false) {
  458. /**
  459. * @see Zend_Service_Amazon_S3_Exception
  460. */
  461. require_once 'Zend/Service/Amazon/S3/Exception.php';
  462. throw new Zend_Service_Amazon_S3_Exception("Cannot open file $path");
  463. }
  464. if (!is_array($meta)) {
  465. $meta = array();
  466. }
  467. if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
  468. $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
  469. }
  470. if(!isset($meta['Content-MD5'])) {
  471. $meta['Content-MD5'] = base64_encode(md5_file($path, true));
  472. }
  473. return $this->putObject($object, $data, $meta);
  474. }
  475. /**
  476. * Remove a given object
  477. *
  478. * @param string $object
  479. * @return boolean
  480. */
  481. public function removeObject($object)
  482. {
  483. $object = $this->_fixupObjectName($object);
  484. $response = $this->_makeRequest('DELETE', $object);
  485. // Look for a 204 No Content response
  486. return ($response->getStatus() == 204);
  487. }
  488. /**
  489. * Copy an object
  490. *
  491. * @param string $sourceObject Source object name
  492. * @param string $destObject Destination object name
  493. * @param array $meta (OPTIONAL) Metadata to apply to desination object.
  494. * Set to null to copy metadata from source object.
  495. * @return boolean
  496. */
  497. public function copyObject($sourceObject, $destObject, $meta = null)
  498. {
  499. $sourceObject = $this->_fixupObjectName($sourceObject);
  500. $destObject = $this->_fixupObjectName($destObject);
  501. $headers = (is_array($meta)) ? $meta : array();
  502. $headers['x-amz-copy-source'] = $sourceObject;
  503. $headers['x-amz-metadata-directive'] = $meta === null ? 'COPY' : 'REPLACE';
  504. $response = $this->_makeRequest('PUT', $destObject, null, $headers);
  505. if ($response->getStatus() == 200 && !stristr($response->getBody(), '<Error>')) {
  506. return true;
  507. }
  508. return false;
  509. }
  510. /**
  511. * Move an object
  512. *
  513. * Performs a copy to dest + verify + remove source
  514. *
  515. * @param string $sourceObject Source object name
  516. * @param string $destObject Destination object name
  517. * @param array $meta (OPTIONAL) Metadata to apply to destination object.
  518. * Set to null to retain existing metadata.
  519. */
  520. public function moveObject($sourceObject, $destObject, $meta = null)
  521. {
  522. $sourceInfo = $this->getInfo($sourceObject);
  523. $this->copyObject($sourceObject, $destObject, $meta);
  524. $destInfo = $this->getInfo($destObject);
  525. if ($sourceInfo['etag'] === $destInfo['etag']) {
  526. return $this->removeObject($sourceObject);
  527. } else {
  528. return false;
  529. }
  530. }
  531. /**
  532. * Make a request to Amazon S3
  533. *
  534. * @param string $method Request method
  535. * @param string $path Path to requested object
  536. * @param array $params Request parameters
  537. * @param array $headers HTTP headers
  538. * @param string|resource $data Request data
  539. * @return Zend_Http_Response
  540. */
  541. public function _makeRequest($method, $path='', $params=null, $headers=array(), $data=null)
  542. {
  543. $retry_count = 0;
  544. if (!is_array($headers)) {
  545. $headers = array($headers);
  546. }
  547. $headers['Date'] = gmdate(DATE_RFC1123, time());
  548. if(is_resource($data) && $method != 'PUT') {
  549. /**
  550. * @see Zend_Service_Amazon_S3_Exception
  551. */
  552. require_once 'Zend/Service/Amazon/S3/Exception.php';
  553. throw new Zend_Service_Amazon_S3_Exception("Only PUT request supports stream data");
  554. }
  555. // build the end point out
  556. $parts = explode('/', $path, 2);
  557. $endpoint = clone($this->_endpoint);
  558. if ($parts[0]) {
  559. // prepend bucket name to the hostname
  560. $endpoint->setHost($parts[0].'.'.$endpoint->getHost());
  561. }
  562. if (!empty($parts[1])) {
  563. // ZF-10218, ZF-10122
  564. $pathparts = explode('?',$parts[1]);
  565. $endpath = $pathparts[0];
  566. $endpoint->setPath('/'.$endpath);
  567. }
  568. else {
  569. $endpoint->setPath('/');
  570. if ($parts[0]) {
  571. $path = $parts[0].'/';
  572. }
  573. }
  574. self::addSignature($method, $path, $headers);
  575. $client = self::getHttpClient();
  576. $client->resetParameters(true);
  577. $client->setUri($endpoint);
  578. $client->setAuth(false);
  579. // Work around buglet in HTTP client - it doesn't clean headers
  580. // Remove when ZHC is fixed
  581. /*
  582. $client->setHeaders(array('Content-MD5' => null,
  583. 'Content-Encoding' => null,
  584. 'Expect' => null,
  585. 'Range' => null,
  586. 'x-amz-acl' => null,
  587. 'x-amz-copy-source' => null,
  588. 'x-amz-metadata-directive' => null));
  589. */
  590. $client->setHeaders($headers);
  591. if (is_array($params)) {
  592. foreach ($params as $name=>$value) {
  593. $client->setParameterGet($name, $value);
  594. }
  595. }
  596. if (($method == 'PUT') && ($data !== null)) {
  597. if (!isset($headers['Content-type'])) {
  598. $headers['Content-type'] = self::getMimeType($path);
  599. }
  600. $client->setRawData($data, $headers['Content-type']);
  601. }
  602. do {
  603. $retry = false;
  604. $response = $client->request($method);
  605. $response_code = $response->getStatus();
  606. // Some 5xx errors are expected, so retry automatically
  607. if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) {
  608. $retry = true;
  609. $retry_count++;
  610. sleep($retry_count / 4 * $retry_count);
  611. }
  612. else if ($response_code == 307) {
  613. // Need to redirect, new S3 endpoint given
  614. // This should never happen as Zend_Http_Client will redirect automatically
  615. }
  616. else if ($response_code == 100) {
  617. // echo 'OK to Continue';
  618. }
  619. } while ($retry);
  620. return $response;
  621. }
  622. /**
  623. * Add the S3 Authorization signature to the request headers
  624. *
  625. * @param string $method
  626. * @param string $path
  627. * @param array &$headers
  628. * @return string
  629. */
  630. protected function addSignature($method, $path, &$headers)
  631. {
  632. if (!is_array($headers)) {
  633. $headers = array($headers);
  634. }
  635. $type = $md5 = $date = '';
  636. // Search for the Content-type, Content-MD5 and Date headers
  637. foreach ($headers as $key=>$val) {
  638. if (strcasecmp($key, 'content-type') == 0) {
  639. $type = $val;
  640. }
  641. else if (strcasecmp($key, 'content-md5') == 0) {
  642. $md5 = $val;
  643. }
  644. else if (strcasecmp($key, 'date') == 0) {
  645. $date = $val;
  646. }
  647. }
  648. // If we have an x-amz-date header, use that instead of the normal Date
  649. if (isset($headers['x-amz-date']) && isset($date)) {
  650. $date = '';
  651. }
  652. $sig_str = "$method\n$md5\n$type\n$date\n";
  653. // For x-amz- headers, combine like keys, lowercase them, sort them
  654. // alphabetically and remove excess spaces around values
  655. $amz_headers = array();
  656. foreach ($headers as $key=>$val) {
  657. $key = strtolower($key);
  658. if (substr($key, 0, 6) == 'x-amz-') {
  659. if (is_array($val)) {
  660. $amz_headers[$key] = $val;
  661. }
  662. else {
  663. $amz_headers[$key][] = preg_replace('/\s+/', ' ', $val);
  664. }
  665. }
  666. }
  667. if (!empty($amz_headers)) {
  668. ksort($amz_headers);
  669. foreach ($amz_headers as $key=>$val) {
  670. $sig_str .= $key.':'.implode(',', $val)."\n";
  671. }
  672. }
  673. $sig_str .= '/'.parse_url($path, PHP_URL_PATH);
  674. if (strpos($path, '?location') !== false) {
  675. $sig_str .= '?location';
  676. }
  677. else if (strpos($path, '?acl') !== false) {
  678. $sig_str .= '?acl';
  679. }
  680. else if (strpos($path, '?torrent') !== false) {
  681. $sig_str .= '?torrent';
  682. }
  683. else if (strpos($path, '?versions') !== false) {
  684. $sig_str .= '?versions';
  685. }
  686. $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY));
  687. $headers['Authorization'] = 'AWS '.$this->_getAccessKey().':'.$signature;
  688. return $sig_str;
  689. }
  690. /**
  691. * Attempt to get the content-type of a file based on the extension
  692. *
  693. * @param string $path
  694. * @return string
  695. */
  696. public static function getMimeType($path)
  697. {
  698. $ext = substr(strrchr($path, '.'), 1);
  699. if(!$ext) {
  700. // shortcut
  701. return 'binary/octet-stream';
  702. }
  703. switch (strtolower($ext)) {
  704. case 'xls':
  705. $content_type = 'application/excel';
  706. break;
  707. case 'hqx':
  708. $content_type = 'application/macbinhex40';
  709. break;
  710. case 'doc':
  711. case 'dot':
  712. case 'wrd':
  713. $content_type = 'application/msword';
  714. break;
  715. case 'pdf':
  716. $content_type = 'application/pdf';
  717. break;
  718. case 'pgp':
  719. $content_type = 'application/pgp';
  720. break;
  721. case 'ps':
  722. case 'eps':
  723. case 'ai':
  724. $content_type = 'application/postscript';
  725. break;
  726. case 'ppt':
  727. $content_type = 'application/powerpoint';
  728. break;
  729. case 'rtf':
  730. $content_type = 'application/rtf';
  731. break;
  732. case 'tgz':
  733. case 'gtar':
  734. $content_type = 'application/x-gtar';
  735. break;
  736. case 'gz':
  737. $content_type = 'application/x-gzip';
  738. break;
  739. case 'php':
  740. case 'php3':
  741. case 'php4':
  742. $content_type = 'application/x-httpd-php';
  743. break;
  744. case 'js':
  745. $content_type = 'application/x-javascript';
  746. break;
  747. case 'ppd':
  748. case 'psd':
  749. $content_type = 'application/x-photoshop';
  750. break;
  751. case 'swf':
  752. case 'swc':
  753. case 'rf':
  754. $content_type = 'application/x-shockwave-flash';
  755. break;
  756. case 'tar':
  757. $content_type = 'application/x-tar';
  758. break;
  759. case 'zip':
  760. $content_type = 'application/zip';
  761. break;
  762. case 'mid':
  763. case 'midi':
  764. case 'kar':
  765. $content_type = 'audio/midi';
  766. break;
  767. case 'mp2':
  768. case 'mp3':
  769. case 'mpga':
  770. $content_type = 'audio/mpeg';
  771. break;
  772. case 'ra':
  773. $content_type = 'audio/x-realaudio';
  774. break;
  775. case 'wav':
  776. $content_type = 'audio/wav';
  777. break;
  778. case 'bmp':
  779. $content_type = 'image/bitmap';
  780. break;
  781. case 'gif':
  782. $content_type = 'image/gif';
  783. break;
  784. case 'iff':
  785. $content_type = 'image/iff';
  786. break;
  787. case 'jb2':
  788. $content_type = 'image/jb2';
  789. break;
  790. case 'jpg':
  791. case 'jpe':
  792. case 'jpeg':
  793. $content_type = 'image/jpeg';
  794. break;
  795. case 'jpx':
  796. $content_type = 'image/jpx';
  797. break;
  798. case 'png':
  799. $content_type = 'image/png';
  800. break;
  801. case 'tif':
  802. case 'tiff':
  803. $content_type = 'image/tiff';
  804. break;
  805. case 'wbmp':
  806. $content_type = 'image/vnd.wap.wbmp';
  807. break;
  808. case 'xbm':
  809. $content_type = 'image/xbm';
  810. break;
  811. case 'css':
  812. $content_type = 'text/css';
  813. break;
  814. case 'txt':
  815. $content_type = 'text/plain';
  816. break;
  817. case 'htm':
  818. case 'html':
  819. $content_type = 'text/html';
  820. break;
  821. case 'xml':
  822. $content_type = 'text/xml';
  823. break;
  824. case 'xsl':
  825. $content_type = 'text/xsl';
  826. break;
  827. case 'mpg':
  828. case 'mpe':
  829. case 'mpeg':
  830. $content_type = 'video/mpeg';
  831. break;
  832. case 'qt':
  833. case 'mov':
  834. $content_type = 'video/quicktime';
  835. break;
  836. case 'avi':
  837. $content_type = 'video/x-ms-video';
  838. break;
  839. case 'eml':
  840. $content_type = 'message/rfc822';
  841. break;
  842. default:
  843. $content_type = 'binary/octet-stream';
  844. break;
  845. }
  846. return $content_type;
  847. }
  848. /**
  849. * Register this object as stream wrapper client
  850. *
  851. * @param string $name
  852. * @return Zend_Service_Amazon_S3
  853. */
  854. public function registerAsClient($name)
  855. {
  856. self::$_wrapperClients[$name] = $this;
  857. return $this;
  858. }
  859. /**
  860. * Unregister this object as stream wrapper client
  861. *
  862. * @param string $name
  863. * @return Zend_Service_Amazon_S3
  864. */
  865. public function unregisterAsClient($name)
  866. {
  867. unset(self::$_wrapperClients[$name]);
  868. return $this;
  869. }
  870. /**
  871. * Get wrapper client for stream type
  872. *
  873. * @param string $name
  874. * @return Zend_Service_Amazon_S3
  875. */
  876. public static function getWrapperClient($name)
  877. {
  878. return self::$_wrapperClients[$name];
  879. }
  880. /**
  881. * Register this object as stream wrapper
  882. *
  883. * @param string $name
  884. * @return Zend_Service_Amazon_S3
  885. */
  886. public function registerStreamWrapper($name='s3')
  887. {
  888. /**
  889. * @see Zend_Service_Amazon_S3_Stream
  890. */
  891. require_once 'Zend/Service/Amazon/S3/Stream.php';
  892. stream_register_wrapper($name, 'Zend_Service_Amazon_S3_Stream');
  893. $this->registerAsClient($name);
  894. }
  895. /**
  896. * Unregister this object as stream wrapper
  897. *
  898. * @param string $name
  899. * @return Zend_Service_Amazon_S3
  900. */
  901. public function unregisterStreamWrapper($name='s3')
  902. {
  903. stream_wrapper_unregister($name);
  904. $this->unregisterAsClient($name);
  905. }
  906. }