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

/php/lib/S3.php

http://webgloo.googlecode.com/
PHP | 1285 lines | 769 code | 140 blank | 376 comment | 203 complexity | be6ebad202794388771e5d7a982b6332 MD5 | raw file
  1. <?php
  2. /**
  3. * $Id: S3.php 39 2008-11-27 01:22:33Z don.schonknecht $
  4. *
  5. * Copyright (c) 2008, Donovan Sch??nknecht. All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * - Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. * - Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  20. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  21. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  23. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  24. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  25. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26. * POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. * Amazon S3 is a trademark of Amazon.com, Inc. or its affiliates.
  29. */
  30. /**
  31. * Amazon S3 PHP class
  32. *
  33. * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
  34. * @version 0.3.7
  35. */
  36. class S3 {
  37. // ACL flags
  38. const ACL_PRIVATE = 'private';
  39. const ACL_PUBLIC_READ = 'public-read';
  40. const ACL_PUBLIC_READ_WRITE = 'public-read-write';
  41. public static $useSSL = true;
  42. private static $__accessKey; // AWS Access key
  43. private static $__secretKey; // AWS Secret key
  44. /**
  45. * Constructor - if you're not using the class statically
  46. *
  47. * @param string $accessKey Access key
  48. * @param string $secretKey Secret key
  49. * @param boolean $useSSL Enable SSL
  50. * @return void
  51. */
  52. public function __construct($accessKey = null, $secretKey = null, $useSSL = true) {
  53. if ($accessKey !== null && $secretKey !== null)
  54. self::setAuth($accessKey, $secretKey);
  55. self::$useSSL = $useSSL;
  56. }
  57. /**
  58. * Set AWS access key and secret key
  59. *
  60. * @param string $accessKey Access key
  61. * @param string $secretKey Secret key
  62. * @return void
  63. */
  64. public static function setAuth($accessKey, $secretKey) {
  65. self::$__accessKey = $accessKey;
  66. self::$__secretKey = $secretKey;
  67. }
  68. /**
  69. * Get a list of buckets
  70. *
  71. * @param boolean $detailed Returns detailed bucket list when true
  72. * @return array | false
  73. */
  74. public static function listBuckets($detailed = false) {
  75. $rest = new S3Request('GET', '', '');
  76. $rest = $rest->getResponse();
  77. if ($rest->error === false && $rest->code !== 200)
  78. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  79. if ($rest->error !== false) {
  80. trigger_error(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  81. return false;
  82. }
  83. $results = array(); //var_dump($rest->body);
  84. if (!isset($rest->body->Buckets)) return $results;
  85. if ($detailed) {
  86. if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
  87. $results['owner'] = array(
  88. 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID
  89. );
  90. $results['buckets'] = array();
  91. foreach ($rest->body->Buckets->Bucket as $b)
  92. $results['buckets'][] = array(
  93. 'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)
  94. );
  95. } else
  96. foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
  97. return $results;
  98. }
  99. /*
  100. * Get contents for a bucket
  101. *
  102. * If maxKeys is null this method will loop through truncated result sets
  103. *
  104. * @param string $bucket Bucket name
  105. * @param string $prefix Prefix
  106. * @param string $marker Marker (last file listed)
  107. * @param string $maxKeys Max keys (maximum number of keys to return)
  108. * @param string $delimiter Delimiter
  109. * @return array | false
  110. */
  111. public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null) {
  112. $rest = new S3Request('GET', $bucket, '');
  113. if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
  114. if ($marker !== null && $marker !== '') $rest->setParameter('marker', $marker);
  115. if ($maxKeys !== null && $maxKeys !== '') $rest->setParameter('max-keys', $maxKeys);
  116. if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
  117. $response = $rest->getResponse();
  118. if ($response->error === false && $response->code !== 200)
  119. $response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
  120. if ($response->error !== false) {
  121. trigger_error(sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING);
  122. return false;
  123. }
  124. $results = array();
  125. $lastMarker = null;
  126. if (isset($response->body, $response->body->Contents))
  127. foreach ($response->body->Contents as $c) {
  128. $results[(string)$c->Key] = array(
  129. 'name' => (string)$c->Key,
  130. 'time' => strtotime((string)$c->LastModified),
  131. 'size' => (int)$c->Size,
  132. 'hash' => substr((string)$c->ETag, 1, -1)
  133. );
  134. $lastMarker = (string)$c->Key;
  135. //$response->body->IsTruncated = 'true'; break;
  136. }
  137. if (isset($response->body->IsTruncated) &&
  138. (string)$response->body->IsTruncated == 'false') return $results;
  139. // Loop through truncated results if maxKeys isn't specified
  140. if ($maxKeys == null && $lastMarker !== null && (string)$response->body->IsTruncated == 'true')
  141. do {
  142. $rest = new S3Request('GET', $bucket, '');
  143. if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
  144. $rest->setParameter('marker', $lastMarker);
  145. if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
  146. if (($response = $rest->getResponse(true)) == false || $response->code !== 200) break;
  147. if (isset($response->body, $response->body->Contents))
  148. foreach ($response->body->Contents as $c) {
  149. $results[(string)$c->Key] = array(
  150. 'name' => (string)$c->Key,
  151. 'time' => strtotime((string)$c->LastModified),
  152. 'size' => (int)$c->Size,
  153. 'hash' => substr((string)$c->ETag, 1, -1)
  154. );
  155. $lastMarker = (string)$c->Key;
  156. }
  157. } while ($response !== false && (string)$response->body->IsTruncated == 'true');
  158. return $results;
  159. }
  160. /**
  161. * Put a bucket
  162. *
  163. * @param string $bucket Bucket name
  164. * @param constant $acl ACL flag
  165. * @param string $location Set as "EU" to create buckets hosted in Europe
  166. * @return boolean
  167. */
  168. public static function putBucket($bucket, $acl = self::ACL_PRIVATE, $location = false) {
  169. $rest = new S3Request('PUT', $bucket, '');
  170. $rest->setAmzHeader('x-amz-acl', $acl);
  171. if ($location !== false) {
  172. $dom = new DOMDocument;
  173. $createBucketConfiguration = $dom->createElement('CreateBucketConfiguration');
  174. $locationConstraint = $dom->createElement('LocationConstraint', strtoupper($location));
  175. $createBucketConfiguration->appendChild($locationConstraint);
  176. $dom->appendChild($createBucketConfiguration);
  177. $rest->data = $dom->saveXML();
  178. $rest->size = strlen($rest->data);
  179. $rest->setHeader('Content-Type', 'application/xml');
  180. }
  181. $rest = $rest->getResponse();
  182. if ($rest->error === false && $rest->code !== 200)
  183. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  184. if ($rest->error !== false) {
  185. trigger_error(sprintf("S3::putBucket({$bucket}, {$acl}, {$location}): [%s] %s",
  186. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  187. return false;
  188. }
  189. return true;
  190. }
  191. /**
  192. * Delete an empty bucket
  193. *
  194. * @param string $bucket Bucket name
  195. * @return boolean
  196. */
  197. public static function deleteBucket($bucket) {
  198. $rest = new S3Request('DELETE', $bucket);
  199. $rest = $rest->getResponse();
  200. if ($rest->error === false && $rest->code !== 204)
  201. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  202. if ($rest->error !== false) {
  203. trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
  204. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  205. return false;
  206. }
  207. return true;
  208. }
  209. /**
  210. * Create input info array for putObject()
  211. *
  212. * @param string $file Input file
  213. * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
  214. * @return array | false
  215. */
  216. public static function inputFile($file, $md5sum = true) {
  217. if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
  218. trigger_error('S3::inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
  219. return false;
  220. }
  221. return array('file' => $file, 'size' => filesize($file),
  222. 'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum :
  223. base64_encode(md5_file($file, true))) : '');
  224. }
  225. /**
  226. * Create input array info for putObject() with a resource
  227. *
  228. * @param string $resource Input resource to read from
  229. * @param integer $bufferSize Input byte size
  230. * @param string $md5sum MD5 hash to send (optional)
  231. * @return array | false
  232. */
  233. public static function inputResource(&$resource, $bufferSize, $md5sum = '') {
  234. if (!is_resource($resource) || $bufferSize <= 0) {
  235. trigger_error('S3::inputResource(): Invalid resource or buffer size', E_USER_WARNING);
  236. return false;
  237. }
  238. $input = array('size' => $bufferSize, 'md5sum' => $md5sum);
  239. $input['fp'] =& $resource;
  240. return $input;
  241. }
  242. /**
  243. * Put an object
  244. *
  245. * @param mixed $input Input data
  246. * @param string $bucket Bucket name
  247. * @param string $uri Object URI
  248. * @param constant $acl ACL constant
  249. * @param array $metaHeaders Array of x-amz-meta-* headers
  250. * @param array $requestHeaders Array of request headers or content type as a string
  251. * @return boolean
  252. */
  253. public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array()) {
  254. if ($input == false) return false;
  255. $rest = new S3Request('PUT', $bucket, $uri);
  256. if (is_string($input)) $input = array(
  257. 'data' => $input, 'size' => strlen($input),
  258. 'md5sum' => base64_encode(md5($input, true))
  259. );
  260. // Data
  261. if (isset($input['fp']))
  262. $rest->fp =& $input['fp'];
  263. elseif (isset($input['file']))
  264. $rest->fp = @fopen($input['file'], 'rb');
  265. elseif (isset($input['data']))
  266. $rest->data = $input['data'];
  267. // Content-Length (required)
  268. if (isset($input['size']) && $input['size'] > -1)
  269. $rest->size = $input['size'];
  270. else {
  271. if (isset($input['file']))
  272. $rest->size = filesize($input['file']);
  273. elseif (isset($input['data']))
  274. $rest->size = strlen($input['data']);
  275. }
  276. // Custom request headers (Content-Type, Content-Disposition, Content-Encoding)
  277. if (is_array($requestHeaders))
  278. foreach ($requestHeaders as $h => $v) $rest->setHeader($h, $v);
  279. elseif (is_string($requestHeaders)) // Support for legacy contentType parameter
  280. $input['type'] = $requestHeaders;
  281. // Content-Type
  282. if (!isset($input['type'])) {
  283. if (isset($requestHeaders['Content-Type']))
  284. $input['type'] =& $requestHeaders['Content-Type'];
  285. elseif (isset($input['file']))
  286. $input['type'] = self::__getMimeType($input['file']);
  287. else
  288. $input['type'] = 'application/octet-stream';
  289. }
  290. // We need to post with Content-Length and Content-Type, MD5 is optional
  291. if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) {
  292. $rest->setHeader('Content-Type', $input['type']);
  293. if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
  294. $rest->setAmzHeader('x-amz-acl', $acl);
  295. foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
  296. $rest->getResponse();
  297. } else
  298. $rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
  299. if ($rest->response->error === false && $rest->response->code !== 200)
  300. $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
  301. if ($rest->response->error !== false) {
  302. trigger_error(sprintf("S3::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
  303. return false;
  304. }
  305. return true;
  306. }
  307. /**
  308. * Put an object from a file (legacy function)
  309. *
  310. * @param string $file Input file path
  311. * @param string $bucket Bucket name
  312. * @param string $uri Object URI
  313. * @param constant $acl ACL constant
  314. * @param array $metaHeaders Array of x-amz-meta-* headers
  315. * @param string $contentType Content type
  316. * @return boolean
  317. */
  318. public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
  319. return self::putObject(self::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
  320. }
  321. /**
  322. * Put an object from a string (legacy function)
  323. *
  324. * @param string $string Input data
  325. * @param string $bucket Bucket name
  326. * @param string $uri Object URI
  327. * @param constant $acl ACL constant
  328. * @param array $metaHeaders Array of x-amz-meta-* headers
  329. * @param string $contentType Content type
  330. * @return boolean
  331. */
  332. public static function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
  333. return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
  334. }
  335. /**
  336. * Get an object
  337. *
  338. * @param string $bucket Bucket name
  339. * @param string $uri Object URI
  340. * @param mixed $saveTo Filename or resource to write to
  341. * @return mixed
  342. */
  343. public static function getObject($bucket, $uri, $saveTo = false) {
  344. $rest = new S3Request('GET', $bucket, $uri);
  345. if ($saveTo !== false) {
  346. if (is_resource($saveTo))
  347. $rest->fp =& $saveTo;
  348. else
  349. if (($rest->fp = @fopen($saveTo, 'wb')) !== false)
  350. $rest->file = realpath($saveTo);
  351. else
  352. $rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
  353. }
  354. if ($rest->response->error === false) $rest->getResponse();
  355. if ($rest->response->error === false && $rest->response->code !== 200)
  356. $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
  357. if ($rest->response->error !== false) {
  358. trigger_error(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
  359. $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
  360. return false;
  361. }
  362. return $rest->response;
  363. }
  364. /**
  365. * Get object information
  366. *
  367. * @param string $bucket Bucket name
  368. * @param string $uri Object URI
  369. * @param boolean $returnInfo Return response information
  370. * @return mixed | false
  371. */
  372. public static function getObjectInfo($bucket, $uri, $returnInfo = true) {
  373. $rest = new S3Request('HEAD', $bucket, $uri);
  374. $rest = $rest->getResponse();
  375. if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
  376. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  377. if ($rest->error !== false) {
  378. trigger_error(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
  379. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  380. return false;
  381. }
  382. return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
  383. }
  384. /**
  385. * Copy an object
  386. *
  387. * @param string $bucket Source bucket name
  388. * @param string $uri Source object URI
  389. * @param string $bucket Destination bucket name
  390. * @param string $uri Destination object URI
  391. * @param constant $acl ACL constant
  392. * @return mixed | false
  393. */
  394. public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PRIVATE) {
  395. $rest = new S3Request('PUT', $bucket, $uri);
  396. $rest->setAmzHeader('x-amz-acl', $acl);
  397. $rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, $srcUri));
  398. $rest = $rest->getResponse();
  399. if ($rest->error === false && $rest->code !== 200)
  400. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  401. if ($rest->error !== false) {
  402. trigger_error(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s",
  403. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  404. return false;
  405. }
  406. return isset($rest->body->LastModified, $rest->body->ETag) ? array(
  407. 'time' => strtotime((string)$rest->body->LastModified),
  408. 'hash' => substr((string)$rest->body->ETag, 1, -1)
  409. ) : false;
  410. }
  411. /**
  412. * Set logging for a bucket
  413. *
  414. * @param string $bucket Bucket name
  415. * @param string $targetBucket Target bucket (where logs are stored)
  416. * @param string $targetPrefix Log prefix (e,g; domain.com-)
  417. * @return boolean
  418. */
  419. public static function setBucketLogging($bucket, $targetBucket, $targetPrefix = null) {
  420. // The S3 log delivery group has to be added to the target bucket's ACP
  421. if ($targetBucket !== null && ($acp = self::getAccessControlPolicy($targetBucket, '')) !== false) {
  422. // Only add permissions to the target bucket when they do not exist
  423. $aclWriteSet = false;
  424. $aclReadSet = false;
  425. foreach ($acp['acl'] as $acl)
  426. if ($acl['type'] == 'Group' && $acl['uri'] == 'http://acs.amazonaws.com/groups/s3/LogDelivery') {
  427. if ($acl['permission'] == 'WRITE') $aclWriteSet = true;
  428. elseif ($acl['permission'] == 'READ_ACP') $aclReadSet = true;
  429. }
  430. if (!$aclWriteSet) $acp['acl'][] = array(
  431. 'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'WRITE'
  432. );
  433. if (!$aclReadSet) $acp['acl'][] = array(
  434. 'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'READ_ACP'
  435. );
  436. if (!$aclReadSet || !$aclWriteSet) self::setAccessControlPolicy($targetBucket, '', $acp);
  437. }
  438. $dom = new DOMDocument;
  439. $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
  440. $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
  441. if ($targetBucket !== null) {
  442. if ($targetPrefix == null) $targetPrefix = $bucket . '-';
  443. $loggingEnabled = $dom->createElement('LoggingEnabled');
  444. $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
  445. $loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
  446. // TODO: Add TargetGrants?
  447. $bucketLoggingStatus->appendChild($loggingEnabled);
  448. }
  449. $dom->appendChild($bucketLoggingStatus);
  450. $rest = new S3Request('PUT', $bucket, '');
  451. $rest->setParameter('logging', null);
  452. $rest->data = $dom->saveXML();
  453. $rest->size = strlen($rest->data);
  454. $rest->setHeader('Content-Type', 'application/xml');
  455. $rest = $rest->getResponse();
  456. if ($rest->error === false && $rest->code !== 200)
  457. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  458. if ($rest->error !== false) {
  459. trigger_error(sprintf("S3::setBucketLogging({$bucket}, {$uri}): [%s] %s",
  460. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  461. return false;
  462. }
  463. return true;
  464. }
  465. /**
  466. * Get logging status for a bucket
  467. *
  468. * This will return false if logging is not enabled.
  469. * Note: To enable logging, you also need to grant write access to the log group
  470. *
  471. * @param string $bucket Bucket name
  472. * @return array | false
  473. */
  474. public static function getBucketLogging($bucket) {
  475. $rest = new S3Request('GET', $bucket, '');
  476. $rest->setParameter('logging', null);
  477. $rest = $rest->getResponse();
  478. if ($rest->error === false && $rest->code !== 200)
  479. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  480. if ($rest->error !== false) {
  481. trigger_error(sprintf("S3::getBucketLogging({$bucket}): [%s] %s",
  482. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  483. return false;
  484. }
  485. if (!isset($rest->body->LoggingEnabled)) return false; // No logging
  486. return array(
  487. 'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
  488. 'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
  489. );
  490. }
  491. /**
  492. * Disable bucket logging
  493. *
  494. * @param string $bucket Bucket name
  495. * @return boolean
  496. */
  497. public static function disableBucketLogging($bucket) {
  498. return self::setBucketLogging($bucket, null);
  499. }
  500. /**
  501. * Get a bucket's location
  502. *
  503. * @param string $bucket Bucket name
  504. * @return string | false
  505. */
  506. public static function getBucketLocation($bucket) {
  507. $rest = new S3Request('GET', $bucket, '');
  508. $rest->setParameter('location', null);
  509. $rest = $rest->getResponse();
  510. if ($rest->error === false && $rest->code !== 200)
  511. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  512. if ($rest->error !== false) {
  513. trigger_error(sprintf("S3::getBucketLocation({$bucket}): [%s] %s",
  514. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  515. return false;
  516. }
  517. return (isset($rest->body[0]) && (string)$rest->body[0] !== '') ? (string)$rest->body[0] : 'US';
  518. }
  519. /**
  520. * Set object or bucket Access Control Policy
  521. *
  522. * @param string $bucket Bucket name
  523. * @param string $uri Object URI
  524. * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
  525. * @return boolean
  526. */
  527. public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
  528. $dom = new DOMDocument;
  529. $dom->formatOutput = true;
  530. $accessControlPolicy = $dom->createElement('AccessControlPolicy');
  531. $accessControlList = $dom->createElement('AccessControlList');
  532. // It seems the owner has to be passed along too
  533. $owner = $dom->createElement('Owner');
  534. $owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
  535. $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
  536. $accessControlPolicy->appendChild($owner);
  537. foreach ($acp['acl'] as $g) {
  538. $grant = $dom->createElement('Grant');
  539. $grantee = $dom->createElement('Grantee');
  540. $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  541. if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
  542. $grantee->setAttribute('xsi:type', 'CanonicalUser');
  543. $grantee->appendChild($dom->createElement('ID', $g['id']));
  544. } elseif (isset($g['email'])) { // AmazonCustomerByEmail
  545. $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
  546. $grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
  547. } elseif ($g['type'] == 'Group') { // Group
  548. $grantee->setAttribute('xsi:type', 'Group');
  549. $grantee->appendChild($dom->createElement('URI', $g['uri']));
  550. }
  551. $grant->appendChild($grantee);
  552. $grant->appendChild($dom->createElement('Permission', $g['permission']));
  553. $accessControlList->appendChild($grant);
  554. }
  555. $accessControlPolicy->appendChild($accessControlList);
  556. $dom->appendChild($accessControlPolicy);
  557. $rest = new S3Request('PUT', $bucket, $uri);
  558. $rest->setParameter('acl', null);
  559. $rest->data = $dom->saveXML();
  560. $rest->size = strlen($rest->data);
  561. $rest->setHeader('Content-Type', 'application/xml');
  562. $rest = $rest->getResponse();
  563. if ($rest->error === false && $rest->code !== 200)
  564. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  565. if ($rest->error !== false) {
  566. trigger_error(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
  567. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  568. return false;
  569. }
  570. return true;
  571. }
  572. /**
  573. * Get object or bucket Access Control Policy
  574. *
  575. * @param string $bucket Bucket name
  576. * @param string $uri Object URI
  577. * @return mixed | false
  578. */
  579. public static function getAccessControlPolicy($bucket, $uri = '') {
  580. $rest = new S3Request('GET', $bucket, $uri);
  581. $rest->setParameter('acl', null);
  582. $rest = $rest->getResponse();
  583. if ($rest->error === false && $rest->code !== 200)
  584. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  585. if ($rest->error !== false) {
  586. trigger_error(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
  587. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  588. return false;
  589. }
  590. $acp = array();
  591. if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) {
  592. $acp['owner'] = array(
  593. 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
  594. );
  595. }
  596. if (isset($rest->body->AccessControlList)) {
  597. $acp['acl'] = array();
  598. foreach ($rest->body->AccessControlList->Grant as $grant) {
  599. foreach ($grant->Grantee as $grantee) {
  600. if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
  601. $acp['acl'][] = array(
  602. 'type' => 'CanonicalUser',
  603. 'id' => (string)$grantee->ID,
  604. 'name' => (string)$grantee->DisplayName,
  605. 'permission' => (string)$grant->Permission
  606. );
  607. elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
  608. $acp['acl'][] = array(
  609. 'type' => 'AmazonCustomerByEmail',
  610. 'email' => (string)$grantee->EmailAddress,
  611. 'permission' => (string)$grant->Permission
  612. );
  613. elseif (isset($grantee->URI)) // Group
  614. $acp['acl'][] = array(
  615. 'type' => 'Group',
  616. 'uri' => (string)$grantee->URI,
  617. 'permission' => (string)$grant->Permission
  618. );
  619. else continue;
  620. }
  621. }
  622. }
  623. return $acp;
  624. }
  625. /**
  626. * Delete an object
  627. *
  628. * @param string $bucket Bucket name
  629. * @param string $uri Object URI
  630. * @return boolean
  631. */
  632. public static function deleteObject($bucket, $uri) {
  633. $rest = new S3Request('DELETE', $bucket, $uri);
  634. $rest = $rest->getResponse();
  635. if ($rest->error === false && $rest->code !== 204)
  636. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  637. if ($rest->error !== false) {
  638. trigger_error(sprintf("S3::deleteObject(): [%s] %s",
  639. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  640. return false;
  641. }
  642. return true;
  643. }
  644. /**
  645. * Get a query string authenticated URL
  646. *
  647. * @param string $bucket Bucket name
  648. * @param string $uri Object URI
  649. * @param integer $lifetime Lifetime in seconds
  650. * @param boolean $hostBucket Use the bucket name as the hostname
  651. * @return string
  652. */
  653. public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false) {
  654. $expires = time() + $lifetime;
  655. return sprintf("http://%s/%s?AWSAccessKeyId=%s&Expires=%u&Signature=%s", $hostBucket ? $bucket : $bucket.'.s3.amazonaws.com',
  656. $uri, self::$__accessKey, $expires, urlencode(self::__getHash("GET\n\n\n{$expires}\n/{$bucket}/{$uri}")));
  657. }
  658. /**
  659. * Create a CloudFront distribution
  660. *
  661. * @param string $bucket Bucket name
  662. * @param boolean $enabled Enabled (true/false)
  663. * @param array $cnames Array containing CNAME aliases
  664. * @param string $comment Use the bucket name as the hostname
  665. * @return array | false
  666. */
  667. public static function createDistribution($bucket, $enabled = true, $cnames = array(), $comment = '') {
  668. self::$useSSL = true; // CloudFront requires SSL
  669. $rest = new S3Request('POST', '', '2008-06-30/distribution', 'cloudfront.amazonaws.com');
  670. $rest->data = self::__getCloudFrontDistributionConfigXML($bucket.'.s3.amazonaws.com', $enabled, $comment, (string)microtime(true), $cnames);
  671. $rest->size = strlen($rest->data);
  672. $rest->setHeader('Content-Type', 'application/xml');
  673. $rest = self::__getCloudFrontResponse($rest);
  674. if ($rest->error === false && $rest->code !== 201)
  675. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  676. if ($rest->error !== false) {
  677. trigger_error(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", '$comment'): [%s] %s",
  678. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  679. return false;
  680. } elseif ($rest->body instanceof SimpleXMLElement)
  681. return self::__parseCloudFrontDistributionConfig($rest->body);
  682. return false;
  683. }
  684. /**
  685. * Get CloudFront distribution info
  686. *
  687. * @param string $distributionId Distribution ID from listDistributions()
  688. * @return array | false
  689. */
  690. public static function getDistribution($distributionId) {
  691. self::$useSSL = true; // CloudFront requires SSL
  692. $rest = new S3Request('GET', '', '2008-06-30/distribution/'.$distributionId, 'cloudfront.amazonaws.com');
  693. $rest = self::__getCloudFrontResponse($rest);
  694. if ($rest->error === false && $rest->code !== 200)
  695. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  696. if ($rest->error !== false) {
  697. trigger_error(sprintf("S3::getDistribution($distributionId): [%s] %s",
  698. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  699. return false;
  700. } elseif ($rest->body instanceof SimpleXMLElement) {
  701. $dist = self::__parseCloudFrontDistributionConfig($rest->body);
  702. $dist['hash'] = $rest->headers['hash'];
  703. return $dist;
  704. }
  705. return false;
  706. }
  707. /**
  708. * Update a CloudFront distribution
  709. *
  710. * @param array $dist Distribution array info identical to output of getDistribution()
  711. * @return array | false
  712. */
  713. public static function updateDistribution($dist) {
  714. self::$useSSL = true; // CloudFront requires SSL
  715. $rest = new S3Request('PUT', '', '2008-06-30/distribution/'.$dist['id'].'/config', 'cloudfront.amazonaws.com');
  716. $rest->data = self::__getCloudFrontDistributionConfigXML($dist['origin'], $dist['enabled'], $dist['comment'], $dist['callerReference'], $dist['cnames']);
  717. $rest->size = strlen($rest->data);
  718. $rest->setHeader('If-Match', $dist['hash']);
  719. $rest = self::__getCloudFrontResponse($rest);
  720. if ($rest->error === false && $rest->code !== 200)
  721. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  722. if ($rest->error !== false) {
  723. trigger_error(sprintf("S3::updateDistribution({$dist['id']}, ".(int)$enabled.", '$comment'): [%s] %s",
  724. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  725. return false;
  726. } else {
  727. $dist = self::__parseCloudFrontDistributionConfig($rest->body);
  728. $dist['hash'] = $rest->headers['hash'];
  729. return $dist;
  730. }
  731. return false;
  732. }
  733. /**
  734. * Delete a CloudFront distribution
  735. *
  736. * @param array $dist Distribution array info identical to output of getDistribution()
  737. * @return boolean
  738. */
  739. public static function deleteDistribution($dist) {
  740. self::$useSSL = true; // CloudFront requires SSL
  741. $rest = new S3Request('DELETE', '', '2008-06-30/distribution/'.$dist['id'], 'cloudfront.amazonaws.com');
  742. $rest->setHeader('If-Match', $dist['hash']);
  743. $rest = self::__getCloudFrontResponse($rest);
  744. if ($rest->error === false && $rest->code !== 204)
  745. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  746. if ($rest->error !== false) {
  747. trigger_error(sprintf("S3::deleteDistribution({$dist['id']}): [%s] %s",
  748. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  749. return false;
  750. }
  751. return true;
  752. }
  753. /**
  754. * Get a list of CloudFront distributions
  755. *
  756. * @return array
  757. */
  758. public static function listDistributions() {
  759. self::$useSSL = true; // CloudFront requires SSL
  760. $rest = new S3Request('GET', '', '2008-06-30/distribution', 'cloudfront.amazonaws.com');
  761. $rest = self::__getCloudFrontResponse($rest);
  762. if ($rest->error === false && $rest->code !== 200)
  763. $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
  764. if ($rest->error !== false) {
  765. trigger_error(sprintf("S3::listDistributions(): [%s] %s",
  766. $rest->error['code'], $rest->error['message']), E_USER_WARNING);
  767. return false;
  768. } elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->DistributionSummary)) {
  769. $list = array();
  770. if (isset($rest->body->Marker, $rest->body->MaxItems, $rest->body->IsTruncated)) {
  771. //$info['marker'] = (string)$rest->body->Marker;
  772. //$info['maxItems'] = (int)$rest->body->MaxItems;
  773. //$info['isTruncated'] = (string)$rest->body->IsTruncated == 'true' ? true : false;
  774. }
  775. foreach ($rest->body->DistributionSummary as $summary) {
  776. $list[(string)$summary->Id] = self::__parseCloudFrontDistributionConfig($summary);
  777. }
  778. return $list;
  779. }
  780. return array();
  781. }
  782. /**
  783. * Get a DistributionConfig DOMDocument
  784. *
  785. * @internal Used to create XML in createDistribution() and updateDistribution()
  786. * @param string $bucket Origin bucket
  787. * @param boolean $enabled Enabled (true/false)
  788. * @param string $comment Comment to append
  789. * @param string $callerReference Caller reference
  790. * @param array $cnames Array of CNAME aliases
  791. * @return string
  792. */
  793. private static function __getCloudFrontDistributionConfigXML($bucket, $enabled, $comment, $callerReference = '0', $cnames = array()) {
  794. $dom = new DOMDocument('1.0', 'UTF-8');
  795. $dom->formatOutput = true;
  796. $distributionConfig = $dom->createElement('DistributionConfig');
  797. $distributionConfig->setAttribute('xmlns', 'http://cloudfront.amazonaws.com/doc/2008-06-30/');
  798. $distributionConfig->appendChild($dom->createElement('Origin', $bucket));
  799. $distributionConfig->appendChild($dom->createElement('CallerReference', $callerReference));
  800. foreach ($cnames as $cname)
  801. $distributionConfig->appendChild($dom->createElement('CNAME', $cname));
  802. if ($comment !== '') $distributionConfig->appendChild($dom->createElement('Comment', $comment));
  803. $distributionConfig->appendChild($dom->createElement('Enabled', $enabled ? 'true' : 'false'));
  804. $dom->appendChild($distributionConfig);
  805. return $dom->saveXML();
  806. }
  807. /**
  808. * Parse a CloudFront distribution config
  809. *
  810. * @internal Used to parse the CloudFront DistributionConfig node to an array
  811. * @param object &$node DOMNode
  812. * @return array
  813. */
  814. private static function __parseCloudFrontDistributionConfig(&$node) {
  815. $dist = array();
  816. if (isset($node->Id, $node->Status, $node->LastModifiedTime, $node->DomainName)) {
  817. $dist['id'] = (string)$node->Id;
  818. $dist['status'] = (string)$node->Status;
  819. $dist['time'] = strtotime((string)$node->LastModifiedTime);
  820. $dist['domain'] = (string)$node->DomainName;
  821. }
  822. if (isset($node->CallerReference))
  823. $dist['callerReference'] = (string)$node->CallerReference;
  824. if (isset($node->Comment))
  825. $dist['comment'] = (string)$node->Comment;
  826. if (isset($node->Enabled, $node->Origin)) {
  827. $dist['origin'] = (string)$node->Origin;
  828. $dist['enabled'] = (string)$node->Enabled == 'true' ? true : false;
  829. } elseif (isset($node->DistributionConfig)) {
  830. $dist = array_merge($dist, self::__parseCloudFrontDistributionConfig($node->DistributionConfig));
  831. }
  832. if (isset($node->CNAME)) {
  833. $dist['cnames'] = array();
  834. foreach ($node->CNAME as $cname) $dist['cnames'][(string)$cname] = (string)$cname;
  835. }
  836. return $dist;
  837. }
  838. /**
  839. * Grab CloudFront response
  840. *
  841. * @internal Used to parse the CloudFront S3Request::getResponse() output
  842. * @param object &$rest S3Request instance
  843. * @return object
  844. */
  845. private static function __getCloudFrontResponse(&$rest) {
  846. $rest->getResponse();
  847. if ($rest->response->error === false && isset($rest->response->body) &&
  848. is_string($rest->response->body) && substr($rest->response->body, 0, 5) == '<?xml') {
  849. $rest->response->body = simplexml_load_string($rest->response->body);
  850. // Grab CloudFront errors
  851. if (isset($rest->response->body->Error, $rest->response->body->Error->Code,
  852. $rest->response->body->Error->Message)) {
  853. $rest->response->error = array(
  854. 'code' => (string)$rest->response->body->Error->Code,
  855. 'message' => (string)$rest->response->body->Error->Message
  856. );
  857. unset($rest->response->body);
  858. }
  859. }
  860. return $rest->response;
  861. }
  862. /**
  863. * Get MIME type for file
  864. *
  865. * @internal Used to get mime types
  866. * @param string &$file File path
  867. * @return string
  868. */
  869. public static function __getMimeType(&$file) {
  870. $type = false;
  871. // Fileinfo documentation says fileinfo_open() will use the
  872. // MAGIC env var for the magic file
  873. if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
  874. ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
  875. if (($type = finfo_file($finfo, $file)) !== false) {
  876. // Remove the charset and grab the last content-type
  877. $type = explode(' ', str_replace('; charset=', ';charset=', $type));
  878. $type = array_pop($type);
  879. $type = explode(';', $type);
  880. $type = trim(array_shift($type));
  881. }
  882. finfo_close($finfo);
  883. // If anyone is still using mime_content_type()
  884. } elseif (function_exists('mime_content_type'))
  885. $type = trim(mime_content_type($file));
  886. if ($type !== false && strlen($type) > 0) return $type;
  887. // Otherwise do it the old fashioned way
  888. static $exts = array(
  889. 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
  890. 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
  891. 'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
  892. 'zip' => 'application/zip', 'gz' => 'application/x-gzip',
  893. 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
  894. 'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
  895. 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
  896. 'css' => 'text/css', 'js' => 'text/javascript',
  897. 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
  898. 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
  899. 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
  900. 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
  901. );
  902. $ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
  903. return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
  904. }
  905. /**
  906. * Generate the auth string: "AWS AccessKey:Signature"
  907. *
  908. * @internal Used by S3Request::getResponse()
  909. * @param string $string String to sign
  910. * @return string
  911. */
  912. public static function __getSignature($string) {
  913. return 'AWS '.self::$__accessKey.':'.self::__getHash($string);
  914. }
  915. /**
  916. * Creates a HMAC-SHA1 hash
  917. *
  918. * This uses the hash extension if loaded
  919. *
  920. * @internal Used by __getSignature()
  921. * @param string $string String to sign
  922. * @return string
  923. */
  924. private static function __getHash($string) {
  925. return base64_encode(extension_loaded('hash') ?
  926. hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1(
  927. (str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
  928. pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^
  929. (str_repeat(chr(0x36), 64))) . $string)))));
  930. }
  931. }
  932. final class S3Request {
  933. private $verb, $bucket, $uri, $resource = '', $parameters = array(),
  934. $amzHeaders = array(), $headers = array(
  935. 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
  936. );
  937. public $fp = false, $size = 0, $data = false, $response;
  938. /**
  939. * Constructor
  940. *
  941. * @param string $verb Verb
  942. * @param string $bucket Bucket name
  943. * @param string $uri Object URI
  944. * @return mixed
  945. */
  946. function __construct($verb, $bucket = '', $uri = '', $defaultHost = 's3.amazonaws.com') {
  947. $this->verb = $verb;
  948. $this->bucket = strtolower($bucket);
  949. $this->uri = $uri !== '' ? '/'.$uri : '/';
  950. if ($this->bucket !== '') {
  951. $this->headers['Host'] = $this->bucket.'.'.$defaultHost;
  952. $this->resource = '/'.$this->bucket.$this->uri;
  953. } else {
  954. $this->headers['Host'] = $defaultHost;
  955. //$this->resource = strlen($this->uri) > 1 ? '/'.$this->bucket.$this->uri : $this->uri;
  956. $this->resource = $this->uri;
  957. }
  958. $this->headers['Date'] = gmdate('D, d M Y H:i:s T');
  959. $this->response = new STDClass;
  960. $this->response->error = false;
  961. }
  962. /**
  963. * Set request parameter
  964. *
  965. * @param string $key Key
  966. * @param string $value Value
  967. * @return void
  968. */
  969. public function setParameter($key, $value) {
  970. $this->parameters[$key] = $value;
  971. }
  972. /**
  973. * Set request header
  974. *
  975. * @param string $key Key
  976. * @param string $value Value
  977. * @return void
  978. */
  979. public function setHeader($key, $value) {
  980. $this->headers[$key] = $value;
  981. }
  982. /**
  983. * Set x-amz-meta-* header
  984. *
  985. * @param string $key Key
  986. * @param string $value Value
  987. * @return void
  988. */
  989. public function setAmzHeader($key, $value) {
  990. $this->amzHeaders[$key] = $value;
  991. }
  992. /**
  993. * Get the S3 response
  994. *
  995. * @return object | false
  996. */
  997. public function getResponse() {
  998. $query = '';
  999. if (sizeof($this->parameters) > 0) {
  1000. $query = substr($this->uri, -1) !== '?' ? '?' : '&';
  1001. foreach ($this->parameters as $var => $value)
  1002. if ($value == null || $value == '') $query .= $var.'&';
  1003. else $query .= $var.'='.$value.'&';
  1004. $query = substr($query, 0, -1);
  1005. $this->uri .= $query;
  1006. if (array_key_exists('acl', $this->parameters) ||
  1007. array_key_exists('location', $this->parameters) ||
  1008. array_key_exists('torrent', $this->parameters) ||
  1009. array_key_exists('logging', $this->parameters))
  1010. $this->resource .= $query;
  1011. }
  1012. $url = ((S3::$useSSL && extension_loaded('openssl')) ?
  1013. 'https://':'http://').$this->headers['Host'].$this->uri;
  1014. //var_dump($this->bucket, $this->uri, $this->resource, $url);
  1015. // Basic setup
  1016. $curl = curl_init();
  1017. curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
  1018. if (S3::$useSSL) {
  1019. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
  1020. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
  1021. }
  1022. curl_setopt($curl, CURLOPT_URL, $url);
  1023. // Headers
  1024. $headers = array(); $amz = array();
  1025. foreach ($this->amzHeaders as $header => $value)
  1026. if (strlen($value) > 0) $headers[] = $header.': '.$value;
  1027. foreach ($this->headers as $header => $value)
  1028. if (strlen($value) > 0) $headers[] = $header.': '.$value;
  1029. // Collect AMZ headers for signature
  1030. foreach ($this->amzHeaders as $header => $value)
  1031. if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value;
  1032. // AMZ headers must be sorted
  1033. if (sizeof($amz) > 0) {
  1034. sort($amz);
  1035. $amz = "\n".implode("\n", $amz);
  1036. } else $amz = '';
  1037. // Authorization string (CloudFront stringToSign should only contain a date)
  1038. $headers[] = 'Authorization: ' . S3::__getSignature(
  1039. $this->headers['Host'] == 'cloudfront.amazonaws.com' ? $this->headers['Date'] :
  1040. $this->verb."\n".$this->headers['Content-MD5']."\n".
  1041. $this->headers['Content-Type']."\n".$this->headers['Date'].$amz."\n".$this->resource
  1042. );
  1043. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  1044. curl_setopt($curl, CURLOPT_HEADER, false);
  1045. curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
  1046. curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
  1047. curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
  1048. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  1049. // Request types
  1050. switch ($this->verb) {
  1051. case 'GET': break;
  1052. case 'PUT': case 'POST': // POST only used for CloudFront
  1053. if ($this->fp !== false) {
  1054. curl_setopt($curl, CURLOPT_PUT, true);
  1055. curl_setopt($curl, CURLOPT_INFILE, $this->fp);
  1056. if ($this->size > 0)
  1057. curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
  1058. } elseif ($this->data !== false) {
  1059. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
  1060. curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
  1061. if ($this->size > 0)
  1062. curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size);
  1063. } else
  1064. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
  1065. break;
  1066. case 'HEAD':
  1067. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
  1068. curl_setopt($curl, CURLOPT_NOBODY, true);
  1069. break;
  1070. case 'DELETE':
  1071. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
  1072. break;
  1073. default: break;
  1074. }
  1075. // Execute, grab errors
  1076. if (curl_exec($curl))
  1077. $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  1078. else
  1079. $this->response->error = array(
  1080. 'code' => curl_errno($curl),
  1081. 'message' => curl_error($curl),
  1082. 'resource' => $this->resource
  1083. );
  1084. @curl_close($curl);
  1085. // Parse body into XML
  1086. if ($this->response->error === false && isset($this->response->headers['type']) &&
  1087. $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) {
  1088. $this->response->body = simplexml_load_string($this->response->body);
  1089. // Grab S3 errors
  1090. if (!in_array($this->response->code, array(200, 204)) &&
  1091. isset($this->response->body->Code, $this->response->body->Message)) {
  1092. $this->response->error = array(
  1093. 'code' => (string)$this->response->body->Code,
  1094. 'message' => (string)$this->response->body->Message
  1095. );
  1096. if (isset($this->response->body->Resource))
  1097. $this->response->error['resource'] = (string)$this->response->body->Resource;
  1098. unset($this->response->body);
  1099. }
  1100. }
  1101. // Clean up file resources
  1102. if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);
  1103. return $this->response;
  1104. }
  1105. /**
  1106. * CURL write callback
  1107. *
  1108. * @param resource &$curl CURL resource
  1109. * @param string &$data Data
  1110. * @return integer
  1111. */
  1112. private function __responseWriteCallback(&$curl, &$data) {
  1113. if ($this->response->code == 200 && $this->fp !== false)
  1114. return fwrite($this->fp, $data);
  1115. else
  1116. $this->response->body .= $data;
  1117. return strlen($data);
  1118. }
  1119. /**
  1120. * CURL header callback
  1121. *
  1122. * @param resource &$curl CURL resource
  1123. * @param string &$data Data
  1124. * @return integer
  1125. */
  1126. private function __responseHeaderCallback(&$curl, &$data) {
  1127. if (($strlen = strlen($data)) <= 2) return $strlen;
  1128. if (substr($data, 0, 4) == 'HTTP')
  1129. $this->response->code = (int)substr($data, 9, 3);
  1130. else {
  1131. list($header, $value) = explode(': ', trim($data), 2);
  1132. if ($header == 'Last-Modified')
  1133. $this->response->headers['time'] = strtotime($value);
  1134. elseif ($header == 'Content-Length')
  1135. $this->response->headers['size'] = (int)$value;
  1136. elseif ($header == 'Content-Type')
  1137. $this->response->headers['type'] = $value;
  1138. elseif ($header == 'ETag')
  1139. $this->response->headers['hash'] = $value{0} == '"' ? substr($value, 1, -1) : $value;
  1140. elseif (preg_match('/^x-amz-meta-.*$/', $header))
  1141. $this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;
  1142. }
  1143. return $strlen;
  1144. }
  1145. }