S3.php 28 KB

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