S3.php 29 KB

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