S3.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  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-2011 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. if($location) {
  146. $data = '<CreateBucketConfiguration><LocationConstraint>'.$location.'</LocationConstraint></CreateBucketConfiguration>';
  147. }
  148. else {
  149. $data = null;
  150. }
  151. $response = $this->_makeRequest('PUT', $bucket, null, array(), $data);
  152. return ($response->getStatus() == 200);
  153. }
  154. /**
  155. * Checks if a given bucket name is available
  156. *
  157. * @param string $bucket
  158. * @return boolean
  159. */
  160. public function isBucketAvailable($bucket)
  161. {
  162. $response = $this->_makeRequest('HEAD', $bucket, array('max-keys'=>0));
  163. return ($response->getStatus() != 404);
  164. }
  165. /**
  166. * Checks if a given object exists
  167. *
  168. * @param string $object
  169. * @return boolean
  170. */
  171. public function isObjectAvailable($object)
  172. {
  173. $object = $this->_fixupObjectName($object);
  174. $response = $this->_makeRequest('HEAD', $object);
  175. return ($response->getStatus() == 200);
  176. }
  177. /**
  178. * Remove a given bucket. All objects in the bucket must be removed prior
  179. * to removing the bucket.
  180. *
  181. * @param string $bucket
  182. * @return boolean
  183. */
  184. public function removeBucket($bucket)
  185. {
  186. $response = $this->_makeRequest('DELETE', $bucket);
  187. // Look for a 204 No Content response
  188. return ($response->getStatus() == 204);
  189. }
  190. /**
  191. * Get metadata information for a given object
  192. *
  193. * @param string $object
  194. * @return array|false
  195. */
  196. public function getInfo($object)
  197. {
  198. $info = array();
  199. $object = $this->_fixupObjectName($object);
  200. $response = $this->_makeRequest('HEAD', $object);
  201. if ($response->getStatus() == 200) {
  202. $info['type'] = $response->getHeader('Content-type');
  203. $info['size'] = $response->getHeader('Content-length');
  204. $info['mtime'] = strtotime($response->getHeader('Last-modified'));
  205. $info['etag'] = $response->getHeader('ETag');
  206. }
  207. else {
  208. return false;
  209. }
  210. return $info;
  211. }
  212. /**
  213. * List the S3 buckets
  214. *
  215. * @return array|false
  216. */
  217. public function getBuckets()
  218. {
  219. $response = $this->_makeRequest('GET');
  220. if ($response->getStatus() != 200) {
  221. return false;
  222. }
  223. $xml = new SimpleXMLElement($response->getBody());
  224. $buckets = array();
  225. foreach ($xml->Buckets->Bucket as $bucket) {
  226. $buckets[] = (string)$bucket->Name;
  227. }
  228. return $buckets;
  229. }
  230. /**
  231. * Remove all objects in the bucket.
  232. *
  233. * @param string $bucket
  234. * @return boolean
  235. */
  236. public function cleanBucket($bucket)
  237. {
  238. $objects = $this->getObjectsByBucket($bucket);
  239. if (!$objects) {
  240. return false;
  241. }
  242. while (!empty($objects)) {
  243. foreach ($objects as $object) {
  244. $this->removeObject("$bucket/$object");
  245. }
  246. $params= array (
  247. 'marker' => $objects[count($objects)-1]
  248. );
  249. $objects = $this->getObjectsByBucket($bucket,$params);
  250. }
  251. return true;
  252. }
  253. /**
  254. * List the objects in a bucket.
  255. *
  256. * Provides the list of object keys that are contained in the bucket. Valid params include the following.
  257. * 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.
  258. * 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.
  259. * 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.
  260. * 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.
  261. *
  262. * @param string $bucket
  263. * @param array $params S3 GET Bucket Paramater
  264. * @return array|false
  265. */
  266. public function getObjectsByBucket($bucket, $params = array())
  267. {
  268. $response = $this->_makeRequest('GET', $bucket, $params);
  269. if ($response->getStatus() != 200) {
  270. return false;
  271. }
  272. $xml = new SimpleXMLElement($response->getBody());
  273. $objects = array();
  274. if (isset($xml->Contents)) {
  275. foreach ($xml->Contents as $contents) {
  276. foreach ($contents->Key as $object) {
  277. $objects[] = (string)$object;
  278. }
  279. }
  280. }
  281. return $objects;
  282. }
  283. /**
  284. * Make sure the object name is valid
  285. *
  286. * @param string $object
  287. * @return string
  288. */
  289. protected function _fixupObjectName($object)
  290. {
  291. $nameparts = explode('/', $object);
  292. $this->_validBucketName($nameparts[0]);
  293. $firstpart = array_shift($nameparts);
  294. if (count($nameparts) == 0) {
  295. return $firstpart;
  296. }
  297. return $firstpart.'/'.join('/', array_map('rawurlencode', $nameparts));
  298. }
  299. /**
  300. * Get an object
  301. *
  302. * @param string $object
  303. * @param bool $paidobject This is "requestor pays" object
  304. * @return string|false
  305. */
  306. public function getObject($object, $paidobject=false)
  307. {
  308. $object = $this->_fixupObjectName($object);
  309. if ($paidobject) {
  310. $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
  311. }
  312. else {
  313. $response = $this->_makeRequest('GET', $object);
  314. }
  315. if ($response->getStatus() != 200) {
  316. return false;
  317. }
  318. return $response->getBody();
  319. }
  320. /**
  321. * Get an object using streaming
  322. *
  323. * Can use either provided filename for storage or create a temp file if none provided.
  324. *
  325. * @param string $object Object path
  326. * @param string $streamfile File to write the stream to
  327. * @param bool $paidobject This is "requestor pays" object
  328. * @return Zend_Http_Response_Stream|false
  329. */
  330. public function getObjectStream($object, $streamfile = null, $paidobject=false)
  331. {
  332. $object = $this->_fixupObjectName($object);
  333. self::getHttpClient()->setStream($streamfile?$streamfile:true);
  334. if ($paidobject) {
  335. $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
  336. }
  337. else {
  338. $response = $this->_makeRequest('GET', $object);
  339. }
  340. self::getHttpClient()->setStream(null);
  341. if ($response->getStatus() != 200 || !($response instanceof Zend_Http_Response_Stream)) {
  342. return false;
  343. }
  344. return $response;
  345. }
  346. /**
  347. * Upload an object by a PHP string
  348. *
  349. * @param string $object Object name
  350. * @param string|resource $data Object data (can be string or stream)
  351. * @param array $meta Metadata
  352. * @return boolean
  353. */
  354. public function putObject($object, $data, $meta=null)
  355. {
  356. $object = $this->_fixupObjectName($object);
  357. $headers = (is_array($meta)) ? $meta : array();
  358. if(!is_resource($data)) {
  359. $headers['Content-MD5'] = base64_encode(md5($data, true));
  360. }
  361. $headers['Expect'] = '100-continue';
  362. if (!isset($headers[self::S3_CONTENT_TYPE_HEADER])) {
  363. $headers[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($object);
  364. }
  365. $response = $this->_makeRequest('PUT', $object, null, $headers, $data);
  366. // Check the MD5 Etag returned by S3 against and MD5 of the buffer
  367. if ($response->getStatus() == 200) {
  368. // It is escaped by double quotes for some reason
  369. $etag = str_replace('"', '', $response->getHeader('Etag'));
  370. if (is_resource($data) || $etag == md5($data)) {
  371. return true;
  372. }
  373. }
  374. return false;
  375. }
  376. /**
  377. * Put file to S3 as object
  378. *
  379. * @param string $path File name
  380. * @param string $object Object name
  381. * @param array $meta Metadata
  382. * @return boolean
  383. */
  384. public function putFile($path, $object, $meta=null)
  385. {
  386. $data = @file_get_contents($path);
  387. if ($data === false) {
  388. /**
  389. * @see Zend_Service_Amazon_S3_Exception
  390. */
  391. require_once 'Zend/Service/Amazon/S3/Exception.php';
  392. throw new Zend_Service_Amazon_S3_Exception("Cannot read file $path");
  393. }
  394. if (!is_array($meta)) {
  395. $meta = array();
  396. }
  397. if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
  398. $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
  399. }
  400. return $this->putObject($object, $data, $meta);
  401. }
  402. /**
  403. * Put file to S3 as object, using streaming
  404. *
  405. * @param string $path File name
  406. * @param string $object Object name
  407. * @param array $meta Metadata
  408. * @return boolean
  409. */
  410. public function putFileStream($path, $object, $meta=null)
  411. {
  412. $data = @fopen($path, "rb");
  413. if ($data === false) {
  414. /**
  415. * @see Zend_Service_Amazon_S3_Exception
  416. */
  417. require_once 'Zend/Service/Amazon/S3/Exception.php';
  418. throw new Zend_Service_Amazon_S3_Exception("Cannot open file $path");
  419. }
  420. if (!is_array($meta)) {
  421. $meta = array();
  422. }
  423. if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
  424. $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
  425. }
  426. if(!isset($meta['Content-MD5'])) {
  427. $headers['Content-MD5'] = base64_encode(md5_file($path, true));
  428. }
  429. return $this->putObject($object, $data, $meta);
  430. }
  431. /**
  432. * Remove a given object
  433. *
  434. * @param string $object
  435. * @return boolean
  436. */
  437. public function removeObject($object)
  438. {
  439. $object = $this->_fixupObjectName($object);
  440. $response = $this->_makeRequest('DELETE', $object);
  441. // Look for a 204 No Content response
  442. return ($response->getStatus() == 204);
  443. }
  444. /**
  445. * Copy an object
  446. *
  447. * @param string $sourceObject Source object name
  448. * @param string $destObject Destination object name
  449. * @param array $meta (OPTIONAL) Metadata to apply to desination object.
  450. * Set to null to copy metadata from source object.
  451. * @return boolean
  452. */
  453. public function copyObject($sourceObject, $destObject, $meta = null)
  454. {
  455. $sourceObject = $this->_fixupObjectName($sourceObject);
  456. $destObject = $this->_fixupObjectName($destObject);
  457. $headers = (is_array($meta)) ? $meta : array();
  458. $headers['x-amz-copy-source'] = $sourceObject;
  459. $headers['x-amz-metadata-directive'] = $meta === null ? 'COPY' : 'REPLACE';
  460. $response = $this->_makeRequest('PUT', $destObject, null, $headers);
  461. if ($response->getStatus() == 200 && !stristr($response->getBody(), '<Error>')) {
  462. return true;
  463. }
  464. return false;
  465. }
  466. /**
  467. * Move an object
  468. *
  469. * Performs a copy to dest + verify + remove source
  470. *
  471. * @param string $sourceObject Source object name
  472. * @param string $destObject Destination object name
  473. * @param array $meta (OPTIONAL) Metadata to apply to destination object.
  474. * Set to null to retain existing metadata.
  475. */
  476. public function moveObject($sourceObject, $destObject, $meta = null)
  477. {
  478. $sourceInfo = $this->getInfo($sourceObject);
  479. $this->copyObject($sourceObject, $destObject, $meta);
  480. $destInfo = $this->getInfo($destObject);
  481. if ($sourceInfo['etag'] === $destInfo['etag']) {
  482. return $this->removeObject($sourceObject);
  483. } else {
  484. return false;
  485. }
  486. }
  487. /**
  488. * Make a request to Amazon S3
  489. *
  490. * @param string $method Request method
  491. * @param string $path Path to requested object
  492. * @param array $params Request parameters
  493. * @param array $headers HTTP headers
  494. * @param string|resource $data Request data
  495. * @return Zend_Http_Response
  496. */
  497. public function _makeRequest($method, $path='', $params=null, $headers=array(), $data=null)
  498. {
  499. $retry_count = 0;
  500. if (!is_array($headers)) {
  501. $headers = array($headers);
  502. }
  503. $headers['Date'] = gmdate(DATE_RFC1123, time());
  504. if(is_resource($data) && $method != 'PUT') {
  505. /**
  506. * @see Zend_Service_Amazon_S3_Exception
  507. */
  508. require_once 'Zend/Service/Amazon/S3/Exception.php';
  509. throw new Zend_Service_Amazon_S3_Exception("Only PUT request supports stream data");
  510. }
  511. // build the end point out
  512. $parts = explode('/', $path, 2);
  513. $endpoint = clone($this->_endpoint);
  514. if ($parts[0]) {
  515. // prepend bucket name to the hostname
  516. $endpoint->setHost($parts[0].'.'.$endpoint->getHost());
  517. }
  518. if (!empty($parts[1])) {
  519. $endpoint->setPath('/'.$parts[1]);
  520. }
  521. else {
  522. $endpoint->setPath('/');
  523. if ($parts[0]) {
  524. $path = $parts[0].'/';
  525. }
  526. }
  527. self::addSignature($method, $path, $headers);
  528. $client = self::getHttpClient();
  529. $client->resetParameters();
  530. $client->setUri($endpoint);
  531. $client->setAuth(false);
  532. // Work around buglet in HTTP client - it doesn't clean headers
  533. // Remove when ZHC is fixed
  534. $client->setHeaders(array('Content-MD5' => null,
  535. 'Content-Encoding' => null,
  536. 'Expect' => null,
  537. 'Range' => null,
  538. 'x-amz-acl' => null,
  539. 'x-amz-copy-source' => null,
  540. 'x-amz-metadata-directive' => null));
  541. $client->setHeaders($headers);
  542. if (is_array($params)) {
  543. foreach ($params as $name=>$value) {
  544. $client->setParameterGet($name, $value);
  545. }
  546. }
  547. if (($method == 'PUT') && ($data !== null)) {
  548. if (!isset($headers['Content-type'])) {
  549. $headers['Content-type'] = self::getMimeType($path);
  550. }
  551. $client->setRawData($data, $headers['Content-type']);
  552. }
  553. do {
  554. $retry = false;
  555. $response = $client->request($method);
  556. $response_code = $response->getStatus();
  557. // Some 5xx errors are expected, so retry automatically
  558. if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) {
  559. $retry = true;
  560. $retry_count++;
  561. sleep($retry_count / 4 * $retry_count);
  562. }
  563. else if ($response_code == 307) {
  564. // Need to redirect, new S3 endpoint given
  565. // This should never happen as Zend_Http_Client will redirect automatically
  566. }
  567. else if ($response_code == 100) {
  568. // echo 'OK to Continue';
  569. }
  570. } while ($retry);
  571. return $response;
  572. }
  573. /**
  574. * Add the S3 Authorization signature to the request headers
  575. *
  576. * @param string $method
  577. * @param string $path
  578. * @param array &$headers
  579. * @return string
  580. */
  581. protected function addSignature($method, $path, &$headers)
  582. {
  583. if (!is_array($headers)) {
  584. $headers = array($headers);
  585. }
  586. $type = $md5 = $date = '';
  587. // Search for the Content-type, Content-MD5 and Date headers
  588. foreach ($headers as $key=>$val) {
  589. if (strcasecmp($key, 'content-type') == 0) {
  590. $type = $val;
  591. }
  592. else if (strcasecmp($key, 'content-md5') == 0) {
  593. $md5 = $val;
  594. }
  595. else if (strcasecmp($key, 'date') == 0) {
  596. $date = $val;
  597. }
  598. }
  599. // If we have an x-amz-date header, use that instead of the normal Date
  600. if (isset($headers['x-amz-date']) && isset($date)) {
  601. $date = '';
  602. }
  603. $sig_str = "$method\n$md5\n$type\n$date\n";
  604. // For x-amz- headers, combine like keys, lowercase them, sort them
  605. // alphabetically and remove excess spaces around values
  606. $amz_headers = array();
  607. foreach ($headers as $key=>$val) {
  608. $key = strtolower($key);
  609. if (substr($key, 0, 6) == 'x-amz-') {
  610. if (is_array($val)) {
  611. $amz_headers[$key] = $val;
  612. }
  613. else {
  614. $amz_headers[$key][] = preg_replace('/\s+/', ' ', $val);
  615. }
  616. }
  617. }
  618. if (!empty($amz_headers)) {
  619. ksort($amz_headers);
  620. foreach ($amz_headers as $key=>$val) {
  621. $sig_str .= $key.':'.implode(',', $val)."\n";
  622. }
  623. }
  624. $sig_str .= '/'.parse_url($path, PHP_URL_PATH);
  625. if (strpos($path, '?location') !== false) {
  626. $sig_str .= '?location';
  627. }
  628. else if (strpos($path, '?acl') !== false) {
  629. $sig_str .= '?acl';
  630. }
  631. else if (strpos($path, '?torrent') !== false) {
  632. $sig_str .= '?torrent';
  633. }
  634. $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY));
  635. $headers['Authorization'] = 'AWS '.$this->_getAccessKey().':'.$signature;
  636. return $sig_str;
  637. }
  638. /**
  639. * Attempt to get the content-type of a file based on the extension
  640. *
  641. * @param string $path
  642. * @return string
  643. */
  644. public static function getMimeType($path)
  645. {
  646. $ext = substr(strrchr($path, '.'), 1);
  647. if(!$ext) {
  648. // shortcut
  649. return 'binary/octet-stream';
  650. }
  651. switch (strtolower($ext)) {
  652. case 'xls':
  653. $content_type = 'application/excel';
  654. break;
  655. case 'hqx':
  656. $content_type = 'application/macbinhex40';
  657. break;
  658. case 'doc':
  659. case 'dot':
  660. case 'wrd':
  661. $content_type = 'application/msword';
  662. break;
  663. case 'pdf':
  664. $content_type = 'application/pdf';
  665. break;
  666. case 'pgp':
  667. $content_type = 'application/pgp';
  668. break;
  669. case 'ps':
  670. case 'eps':
  671. case 'ai':
  672. $content_type = 'application/postscript';
  673. break;
  674. case 'ppt':
  675. $content_type = 'application/powerpoint';
  676. break;
  677. case 'rtf':
  678. $content_type = 'application/rtf';
  679. break;
  680. case 'tgz':
  681. case 'gtar':
  682. $content_type = 'application/x-gtar';
  683. break;
  684. case 'gz':
  685. $content_type = 'application/x-gzip';
  686. break;
  687. case 'php':
  688. case 'php3':
  689. case 'php4':
  690. $content_type = 'application/x-httpd-php';
  691. break;
  692. case 'js':
  693. $content_type = 'application/x-javascript';
  694. break;
  695. case 'ppd':
  696. case 'psd':
  697. $content_type = 'application/x-photoshop';
  698. break;
  699. case 'swf':
  700. case 'swc':
  701. case 'rf':
  702. $content_type = 'application/x-shockwave-flash';
  703. break;
  704. case 'tar':
  705. $content_type = 'application/x-tar';
  706. break;
  707. case 'zip':
  708. $content_type = 'application/zip';
  709. break;
  710. case 'mid':
  711. case 'midi':
  712. case 'kar':
  713. $content_type = 'audio/midi';
  714. break;
  715. case 'mp2':
  716. case 'mp3':
  717. case 'mpga':
  718. $content_type = 'audio/mpeg';
  719. break;
  720. case 'ra':
  721. $content_type = 'audio/x-realaudio';
  722. break;
  723. case 'wav':
  724. $content_type = 'audio/wav';
  725. break;
  726. case 'bmp':
  727. $content_type = 'image/bitmap';
  728. break;
  729. case 'gif':
  730. $content_type = 'image/gif';
  731. break;
  732. case 'iff':
  733. $content_type = 'image/iff';
  734. break;
  735. case 'jb2':
  736. $content_type = 'image/jb2';
  737. break;
  738. case 'jpg':
  739. case 'jpe':
  740. case 'jpeg':
  741. $content_type = 'image/jpeg';
  742. break;
  743. case 'jpx':
  744. $content_type = 'image/jpx';
  745. break;
  746. case 'png':
  747. $content_type = 'image/png';
  748. break;
  749. case 'tif':
  750. case 'tiff':
  751. $content_type = 'image/tiff';
  752. break;
  753. case 'wbmp':
  754. $content_type = 'image/vnd.wap.wbmp';
  755. break;
  756. case 'xbm':
  757. $content_type = 'image/xbm';
  758. break;
  759. case 'css':
  760. $content_type = 'text/css';
  761. break;
  762. case 'txt':
  763. $content_type = 'text/plain';
  764. break;
  765. case 'htm':
  766. case 'html':
  767. $content_type = 'text/html';
  768. break;
  769. case 'xml':
  770. $content_type = 'text/xml';
  771. break;
  772. case 'xsl':
  773. $content_type = 'text/xsl';
  774. break;
  775. case 'mpg':
  776. case 'mpe':
  777. case 'mpeg':
  778. $content_type = 'video/mpeg';
  779. break;
  780. case 'qt':
  781. case 'mov':
  782. $content_type = 'video/quicktime';
  783. break;
  784. case 'avi':
  785. $content_type = 'video/x-ms-video';
  786. break;
  787. case 'eml':
  788. $content_type = 'message/rfc822';
  789. break;
  790. default:
  791. $content_type = 'binary/octet-stream';
  792. break;
  793. }
  794. return $content_type;
  795. }
  796. /**
  797. * Register this object as stream wrapper client
  798. *
  799. * @param string $name
  800. * @return Zend_Service_Amazon_S3
  801. */
  802. public function registerAsClient($name)
  803. {
  804. self::$_wrapperClients[$name] = $this;
  805. return $this;
  806. }
  807. /**
  808. * Unregister this object as stream wrapper client
  809. *
  810. * @param string $name
  811. * @return Zend_Service_Amazon_S3
  812. */
  813. public function unregisterAsClient($name)
  814. {
  815. unset(self::$_wrapperClients[$name]);
  816. return $this;
  817. }
  818. /**
  819. * Get wrapper client for stream type
  820. *
  821. * @param string $name
  822. * @return Zend_Service_Amazon_S3
  823. */
  824. public static function getWrapperClient($name)
  825. {
  826. return self::$_wrapperClients[$name];
  827. }
  828. /**
  829. * Register this object as stream wrapper
  830. *
  831. * @param string $name
  832. * @return Zend_Service_Amazon_S3
  833. */
  834. public function registerStreamWrapper($name='s3')
  835. {
  836. /**
  837. * @see Zend_Service_Amazon_S3_Stream
  838. */
  839. require_once 'Zend/Service/Amazon/S3/Stream.php';
  840. stream_register_wrapper($name, 'Zend_Service_Amazon_S3_Stream');
  841. $this->registerAsClient($name);
  842. }
  843. /**
  844. * Unregister this object as stream wrapper
  845. *
  846. * @param string $name
  847. * @return Zend_Service_Amazon_S3
  848. */
  849. public function unregisterStreamWrapper($name='s3')
  850. {
  851. stream_wrapper_unregister($name);
  852. $this->unregisterAsClient($name);
  853. }
  854. }