PageRenderTime 46ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/brunoMaurice/youfood
PHP | 824 lines | 488 code | 90 blank | 246 comment | 79 complexity | d109c40a5a0caf8e1c9b318ec5de7127 MD5 | raw file
  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-2009 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 16971 2009-07-22 18:05:45Z mikaelkael $
  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-2009 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.
  250. *
  251. * @param string $bucket
  252. * @return array|false
  253. */
  254. public function getObjectsByBucket($bucket)
  255. {
  256. $response = $this->_makeRequest('GET', $bucket);
  257. if ($response->getStatus() != 200) {
  258. return false;
  259. }
  260. $xml = new SimpleXMLElement($response->getBody());
  261. $objects = array();
  262. if (isset($xml->Contents)) {
  263. foreach ($xml->Contents as $contents) {
  264. foreach ($contents->Key as $object) {
  265. $objects[] = (string)$object;
  266. }
  267. }
  268. }
  269. return $objects;
  270. }
  271. /**
  272. * Make sure the object name is valid
  273. *
  274. * @param string $object
  275. * @return string
  276. */
  277. protected function _fixupObjectName($object)
  278. {
  279. $nameparts = explode('/', $object);
  280. $this->_validBucketName($nameparts[0]);
  281. $firstpart = array_shift($nameparts);
  282. if (count($nameparts) == 0) {
  283. return $firstpart;
  284. }
  285. return $firstpart.'/'.join('/', array_map('rawurlencode', $nameparts));
  286. }
  287. /**
  288. * Get an object
  289. *
  290. * @param string $object
  291. * @param bool $paidobject This is "requestor pays" object
  292. * @return string|false
  293. */
  294. public function getObject($object, $paidobject=false)
  295. {
  296. $object = $this->_fixupObjectName($object);
  297. if ($paidobject) {
  298. $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
  299. }
  300. else {
  301. $response = $this->_makeRequest('GET', $object);
  302. }
  303. if ($response->getStatus() != 200) {
  304. return false;
  305. }
  306. return $response->getBody();
  307. }
  308. /**
  309. * Upload an object by a PHP string
  310. *
  311. * @param string $object Object name
  312. * @param string $data Object data
  313. * @param array $meta Metadata
  314. * @return boolean
  315. */
  316. public function putObject($object, $data, $meta=null)
  317. {
  318. $object = $this->_fixupObjectName($object);
  319. $headers = (is_array($meta)) ? $meta : array();
  320. $headers['Content-MD5'] = base64_encode(md5($data, true));
  321. $headers['Expect'] = '100-continue';
  322. if (!isset($headers[self::S3_CONTENT_TYPE_HEADER])) {
  323. $headers[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($object);
  324. }
  325. $response = $this->_makeRequest('PUT', $object, null, $headers, $data);
  326. // Check the MD5 Etag returned by S3 against and MD5 of the buffer
  327. if ($response->getStatus() == 200) {
  328. // It is escaped by double quotes for some reason
  329. $etag = str_replace('"', '', $response->getHeader('Etag'));
  330. if ($etag == md5($data)) {
  331. return true;
  332. }
  333. }
  334. return false;
  335. }
  336. /**
  337. * Put file to S3 as object
  338. *
  339. * @param string $path File name
  340. * @param string $object Object name
  341. * @param array $meta Metadata
  342. * @return boolean
  343. */
  344. public function putFile($path, $object, $meta=null)
  345. {
  346. $data = @file_get_contents($path);
  347. if ($data === false) {
  348. /**
  349. * @see Zend_Service_Amazon_S3_Exception
  350. */
  351. require_once 'Zend/Service/Amazon/S3/Exception.php';
  352. throw new Zend_Service_Amazon_S3_Exception("Cannot read file $path");
  353. }
  354. if (!is_array($meta)) {
  355. $meta = array();
  356. }
  357. if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
  358. $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
  359. }
  360. return $this->putObject($object, $data, $meta);
  361. }
  362. /**
  363. * Remove a given object
  364. *
  365. * @param string $object
  366. * @return boolean
  367. */
  368. public function removeObject($object)
  369. {
  370. $object = $this->_fixupObjectName($object);
  371. $response = $this->_makeRequest('DELETE', $object);
  372. // Look for a 204 No Content response
  373. return ($response->getStatus() == 204);
  374. }
  375. /**
  376. * Make a request to Amazon S3
  377. *
  378. * @param string $method
  379. * @param string $path
  380. * @param array $params
  381. * @param array $headers
  382. * @param string $data
  383. * @return Zend_Http_Response
  384. */
  385. public function _makeRequest($method, $path='', $params=null, $headers=array(), $data=null)
  386. {
  387. $retry_count = 0;
  388. if (!is_array($headers)) {
  389. $headers = array($headers);
  390. }
  391. $headers['Date'] = gmdate(DATE_RFC1123, time());
  392. // build the end point out
  393. $parts = explode('/', $path, 2);
  394. $endpoint = clone($this->_endpoint);
  395. if ($parts[0]) {
  396. // prepend bucket name to the hostname
  397. $endpoint->setHost($parts[0].'.'.$endpoint->getHost());
  398. }
  399. if (!empty($parts[1])) {
  400. $endpoint->setPath('/'.$parts[1]);
  401. }
  402. else {
  403. $endpoint->setPath('/');
  404. if ($parts[0]) {
  405. $path = $parts[0].'/';
  406. }
  407. }
  408. self::addSignature($method, $path, $headers);
  409. $client = self::getHttpClient();
  410. $client->resetParameters();
  411. $client->setAuth(false);
  412. // Work around buglet in HTTP client - it doesn't clean headers
  413. // Remove when ZHC is fixed
  414. $client->setHeaders(array('Content-MD5' => null,
  415. 'Expect' => null,
  416. 'Range' => null,
  417. 'x-amz-acl' => null));
  418. $client->setUri($endpoint);
  419. $client->setHeaders($headers);
  420. if (is_array($params)) {
  421. foreach ($params as $name=>$value) {
  422. $client->setParameterGet($name, $value);
  423. }
  424. }
  425. if (($method == 'PUT') && ($data !== null)) {
  426. if (!isset($headers['Content-type'])) {
  427. $headers['Content-type'] = self::getMimeType($path);
  428. }
  429. $client->setRawData($data, $headers['Content-type']);
  430. }
  431. do {
  432. $retry = false;
  433. $response = $client->request($method);
  434. $response_code = $response->getStatus();
  435. // Some 5xx errors are expected, so retry automatically
  436. if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) {
  437. $retry = true;
  438. $retry_count++;
  439. sleep($retry_count / 4 * $retry_count);
  440. }
  441. else if ($response_code == 307) {
  442. // Need to redirect, new S3 endpoint given
  443. // This should never happen as Zend_Http_Client will redirect automatically
  444. }
  445. else if ($response_code == 100) {
  446. // echo 'OK to Continue';
  447. }
  448. } while ($retry);
  449. return $response;
  450. }
  451. /**
  452. * Add the S3 Authorization signature to the request headers
  453. *
  454. * @param string $method
  455. * @param string $path
  456. * @param array &$headers
  457. * @return string
  458. */
  459. protected function addSignature($method, $path, &$headers)
  460. {
  461. if (!is_array($headers)) {
  462. $headers = array($headers);
  463. }
  464. $type = $md5 = $date = '';
  465. // Search for the Content-type, Content-MD5 and Date headers
  466. foreach ($headers as $key=>$val) {
  467. if (strcasecmp($key, 'content-type') == 0) {
  468. $type = $val;
  469. }
  470. else if (strcasecmp($key, 'content-md5') == 0) {
  471. $md5 = $val;
  472. }
  473. else if (strcasecmp($key, 'date') == 0) {
  474. $date = $val;
  475. }
  476. }
  477. // If we have an x-amz-date header, use that instead of the normal Date
  478. if (isset($headers['x-amz-date']) && isset($date)) {
  479. $date = '';
  480. }
  481. $sig_str = "$method\n$md5\n$type\n$date\n";
  482. // For x-amz- headers, combine like keys, lowercase them, sort them
  483. // alphabetically and remove excess spaces around values
  484. $amz_headers = array();
  485. foreach ($headers as $key=>$val) {
  486. $key = strtolower($key);
  487. if (substr($key, 0, 6) == 'x-amz-') {
  488. if (is_array($val)) {
  489. $amz_headers[$key] = $val;
  490. }
  491. else {
  492. $amz_headers[$key][] = preg_replace('/\s+/', ' ', $val);
  493. }
  494. }
  495. }
  496. if (!empty($amz_headers)) {
  497. ksort($amz_headers);
  498. foreach ($amz_headers as $key=>$val) {
  499. $sig_str .= $key.':'.implode(',', $val)."\n";
  500. }
  501. }
  502. $sig_str .= '/'.parse_url($path, PHP_URL_PATH);
  503. if (strpos($path, '?location') !== false) {
  504. $sig_str .= '?location';
  505. }
  506. else if (strpos($path, '?acl') !== false) {
  507. $sig_str .= '?acl';
  508. }
  509. else if (strpos($path, '?torrent') !== false) {
  510. $sig_str .= '?torrent';
  511. }
  512. $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY));
  513. $headers['Authorization'] = 'AWS '.$this->_getAccessKey().':'.$signature;
  514. return $sig_str;
  515. }
  516. /**
  517. * Attempt to get the content-type of a file based on the extension
  518. *
  519. * TODO: move this to Zend_Mime
  520. *
  521. * @param string $path
  522. * @return string
  523. */
  524. public static function getMimeType($path)
  525. {
  526. $ext = substr(strrchr($path, '.'), 1);
  527. if(!$ext) {
  528. // shortcut
  529. return 'binary/octet-stream';
  530. }
  531. switch ($ext) {
  532. case 'xls':
  533. $content_type = 'application/excel';
  534. break;
  535. case 'hqx':
  536. $content_type = 'application/macbinhex40';
  537. break;
  538. case 'doc':
  539. case 'dot':
  540. case 'wrd':
  541. $content_type = 'application/msword';
  542. break;
  543. case 'pdf':
  544. $content_type = 'application/pdf';
  545. break;
  546. case 'pgp':
  547. $content_type = 'application/pgp';
  548. break;
  549. case 'ps':
  550. case 'eps':
  551. case 'ai':
  552. $content_type = 'application/postscript';
  553. break;
  554. case 'ppt':
  555. $content_type = 'application/powerpoint';
  556. break;
  557. case 'rtf':
  558. $content_type = 'application/rtf';
  559. break;
  560. case 'tgz':
  561. case 'gtar':
  562. $content_type = 'application/x-gtar';
  563. break;
  564. case 'gz':
  565. $content_type = 'application/x-gzip';
  566. break;
  567. case 'php':
  568. case 'php3':
  569. case 'php4':
  570. $content_type = 'application/x-httpd-php';
  571. break;
  572. case 'js':
  573. $content_type = 'application/x-javascript';
  574. break;
  575. case 'ppd':
  576. case 'psd':
  577. $content_type = 'application/x-photoshop';
  578. break;
  579. case 'swf':
  580. case 'swc':
  581. case 'rf':
  582. $content_type = 'application/x-shockwave-flash';
  583. break;
  584. case 'tar':
  585. $content_type = 'application/x-tar';
  586. break;
  587. case 'zip':
  588. $content_type = 'application/zip';
  589. break;
  590. case 'mid':
  591. case 'midi':
  592. case 'kar':
  593. $content_type = 'audio/midi';
  594. break;
  595. case 'mp2':
  596. case 'mp3':
  597. case 'mpga':
  598. $content_type = 'audio/mpeg';
  599. break;
  600. case 'ra':
  601. $content_type = 'audio/x-realaudio';
  602. break;
  603. case 'wav':
  604. $content_type = 'audio/wav';
  605. break;
  606. case 'bmp':
  607. $content_type = 'image/bitmap';
  608. break;
  609. case 'gif':
  610. $content_type = 'image/gif';
  611. break;
  612. case 'iff':
  613. $content_type = 'image/iff';
  614. break;
  615. case 'jb2':
  616. $content_type = 'image/jb2';
  617. break;
  618. case 'jpg':
  619. case 'jpe':
  620. case 'jpeg':
  621. $content_type = 'image/jpeg';
  622. break;
  623. case 'jpx':
  624. $content_type = 'image/jpx';
  625. break;
  626. case 'png':
  627. $content_type = 'image/png';
  628. break;
  629. case 'tif':
  630. case 'tiff':
  631. $content_type = 'image/tiff';
  632. break;
  633. case 'wbmp':
  634. $content_type = 'image/vnd.wap.wbmp';
  635. break;
  636. case 'xbm':
  637. $content_type = 'image/xbm';
  638. break;
  639. case 'css':
  640. $content_type = 'text/css';
  641. break;
  642. case 'txt':
  643. $content_type = 'text/plain';
  644. break;
  645. case 'htm':
  646. case 'html':
  647. $content_type = 'text/html';
  648. break;
  649. case 'xml':
  650. $content_type = 'text/xml';
  651. break;
  652. case 'xsl':
  653. $content_type = 'text/xsl';
  654. break;
  655. case 'mpg':
  656. case 'mpe':
  657. case 'mpeg':
  658. $content_type = 'video/mpeg';
  659. break;
  660. case 'qt':
  661. case 'mov':
  662. $content_type = 'video/quicktime';
  663. break;
  664. case 'avi':
  665. $content_type = 'video/x-ms-video';
  666. break;
  667. case 'eml':
  668. $content_type = 'message/rfc822';
  669. break;
  670. default:
  671. $content_type = 'binary/octet-stream';
  672. break;
  673. }
  674. return $content_type;
  675. }
  676. /**
  677. * Register this object as stream wrapper client
  678. *
  679. * @param string $name
  680. * @return Zend_Service_Amazon_S3
  681. */
  682. public function registerAsClient($name)
  683. {
  684. self::$_wrapperClients[$name] = $this;
  685. return $this;
  686. }
  687. /**
  688. * Unregister this object as stream wrapper client
  689. *
  690. * @param string $name
  691. * @return Zend_Service_Amazon_S3
  692. */
  693. public function unregisterAsClient($name)
  694. {
  695. unset(self::$_wrapperClients[$name]);
  696. return $this;
  697. }
  698. /**
  699. * Get wrapper client for stream type
  700. *
  701. * @param string $name
  702. * @return Zend_Service_Amazon_S3
  703. */
  704. public static function getWrapperClient($name)
  705. {
  706. return self::$_wrapperClients[$name];
  707. }
  708. /**
  709. * Register this object as stream wrapper
  710. *
  711. * @param string $name
  712. * @return Zend_Service_Amazon_S3
  713. */
  714. public function registerStreamWrapper($name='s3')
  715. {
  716. /**
  717. * @see Zend_Service_Amazon_S3_Stream
  718. */
  719. require_once 'Zend/Service/Amazon/S3/Stream.php';
  720. stream_register_wrapper($name, 'Zend_Service_Amazon_S3_Stream');
  721. $this->registerAsClient($name);
  722. }
  723. /**
  724. * Unregister this object as stream wrapper
  725. *
  726. * @param string $name
  727. * @return Zend_Service_Amazon_S3
  728. */
  729. public function unregisterStreamWrapper($name='s3')
  730. {
  731. stream_wrapper_unregister($name);
  732. $this->unregisterAsClient($name);
  733. }
  734. }