-
Notifications
You must be signed in to change notification settings - Fork 12
/
BlobClient.php
1859 lines (1613 loc) · 72.1 KB
/
BlobClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* WindowsAzure BlobStorage Client
*
* Copyright (c) 2009 - 2012, RealDolmen
* Copyright (c) 2012, Benjamin Eberlei
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to kontakt@beberlei.de so I can send you a copy immediately.
*/
namespace Beberlei\AzureBlobStorage;
use Assert\Assertion;
/**
* Client for Microsoft Windows Azure Blob Storage.
*
* Originally implemented in the PHP Azure SDK.
*
* @copyright Copyright (c) 2009 - 2012, RealDolmen (http://www.realdolmen.com)
* @license http://phpazure.codeplex.com/license
* @license New BSD
*/
class BlobClient
{
/**
* ACL - Private access
*/
const ACL_PRIVATE = null;
/**
* ACL - Public access (read all blobs)
*
* @deprecated Use ACL_PUBLIC_CONTAINER or ACL_PUBLIC_BLOB instead.
*/
const ACL_PUBLIC = 'container';
/**
* ACL - Blob Public access (read all blobs)
*/
const ACL_PUBLIC_BLOB = 'blob';
/**
* ACL - Container Public access (enumerate and read all blobs)
*/
const ACL_PUBLIC_CONTAINER = 'container';
/**
* Blob lease constants
*/
const LEASE_ACQUIRE = 'acquire';
const LEASE_RENEW = 'renew';
const LEASE_RELEASE = 'release';
const LEASE_BREAK = 'break';
/**
* Maximal blob size (in bytes)
*/
const MAX_BLOB_SIZE = 67108864;
/**
* Maximal blob transfer size (in bytes)
*/
const MAX_BLOB_TRANSFER_SIZE = 4194304;
/**
* Blob types
*/
const BLOBTYPE_BLOCK = 'BlockBlob';
const BLOBTYPE_PAGE = 'PageBlob';
/**
* Put page write options
*/
const PAGE_WRITE_UPDATE = 'update';
const PAGE_WRITE_CLEAR = 'clear';
const URL_DEV_BLOB = 'http://127.0.0.1:10000';
const URL_CLOUD_BLOB = 'ssl://blob.core.windows.net';
const DEVSTORE_ACCOUNT = "devstoreaccount1";
const DEVSTORE_KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";
const RESOURCE_CONTAINER = "c";
const RESOURCE_BLOB = "b";
const PERMISSION_READ = "r";
const PERMISSION_WRITE = "w";
const PERMISSION_DELETE = "d";
const PERMISSION_LIST = "l";
/**
* Stream wrapper clients
*
* @var array
*/
protected static $wrapperClients = array();
/**
* SharedAccessSignature credentials
*
* @var CredentialsAbstract
*/
protected $credentials = null;
/**
* @var string
*/
protected $host;
/**
* @var string
*/
protected $accountName;
/**
* @var string
*/
protected $accountKey;
/**
* @var string
*/
protected $apiVersion = '2009-09-19';
/**
* @var CredentialsAbstract
*/
protected $sharedAccessSignatureCredentials;
/**
* Creates a new BlobClient instance
*
* @param string $host Storage host name
* @param string $accountName Account name for Windows Azure
* @param string $accountKey Account key for Windows Azure
*/
public function __construct($host = self::URL_DEV_BLOB, $accountName = self::DEVSTORE_ACCOUNT, $accountKey = self::DEVSTORE_KEY)
{
$this->host = $host;
$this->accountName = $accountName;
$this->accountKey = $accountKey;
$this->credentials = new SharedKey($accountName, $accountKey, ($host === self::URL_DEV_BLOB));
$this->sharedAccessSignatureCredentials = new SharedAccessSignature($accountName, $accountKey, ($host === self::URL_DEV_BLOB));
$this->httpClient = new \Beberlei\AzureBlobStorage\Http\SocketClient;
}
/**
* Perform request using Microsoft_Http_Client channel
*
* @param string $path Path
* @param array $query Query parameters
* @param string $httpVerb HTTP verb the request will use
* @param array $headers x-ms headers to add
* @param boolean $forTableStorage Is the request for table storage?
* @param mixed $rawData Optional RAW HTTP data to be sent over the wire
* @param string $resourceType Resource type
* @param string $requiredPermission Required permission
* @return Microsoft_Http_Response
*/
protected function performRequest(
$path = '/',
$query = array(),
$httpVerb = 'GET',
$headers = array(),
$forTableStorage = false,
$rawData = null,
$resourceType = self::RESOURCE_UNKNOWN,
$requiredPermission = self::PERMISSION_READ
) {
// Clean path
if (strpos($path, '/') !== 0) {
$path = '/' . $path;
}
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = '';
}
if (!isset($headers['content-length']) && ($rawData !== null || $httpVerb == "PUT")) {
$headers['Content-Length'] = strlen((string)$rawData);
}
$headers['Expect'] = '';
// Add version header
$headers['x-ms-version'] = $this->apiVersion;
// Generate URL
$path = str_replace(' ', '%20', $path);
$requestUrl = $this->getBaseUrl() . $path;
if (count($query) > 0) {
$queryString = '';
foreach ($query as $key => $value) {
$queryString .= ($queryString ? '&' : '?') . rawurlencode($key) . '=' . rawurlencode($value);
}
$requestUrl .= $queryString;
}
$requestUrl = $this->credentials->signRequestUrl($requestUrl, $resourceType, $requiredPermission);
$headers = $this->credentials->signRequestHeaders(
$httpVerb,
$path,
$query,
$headers,
$forTableStorage,
$resourceType,
$requiredPermission,
$rawData
);
return $this->httpClient->request($httpVerb, $requestUrl, $rawData, $headers);
}
/**
* Check if a blob exists
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param string $snapshotId Snapshot identifier
* @return boolean
*/
public function blobExists($containerName = '', $blobName = '', $snapshotId = null)
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
try {
$this->getBlobInstance($containerName, $blobName, $snapshotId);
} catch (BlobException $e) {
return false;
}
return true;
}
/**
* Check if a container exists
*
* @param string $containerName Container name
* @return boolean
*/
public function containerExists($containerName = '')
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
// List containers
$containers = $this->listContainers($containerName, 1);
foreach ($containers as $container) {
if ($container->Name == $containerName) {
return true;
}
}
return false;
}
/**
* Create container
*
* @param string $containerName Container name
* @param array $metadata Key/value pairs of meta data
* @return object Container properties
* @throws BlobException
*/
public function createContainer($containerName = '', $metadata = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::isArray($metadata, 'Meta data should be an array of key and value pairs.');
$headers = $this->generateMetadataHeaders($metadata);
$response = $this->performRequest($containerName, array('restype' => 'container'), 'PUT', $headers, false, null, self::RESOURCE_CONTAINER, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
return new BlobContainer(
$containerName,
$response->getHeader('Etag'),
$response->getHeader('Last-modified'),
$metadata
);
}
/**
* Create container if it does not exist
*
* @param string $containerName Container name
* @param array $metadata Key/value pairs of meta data
* @throws BlobException
*/
public function createContainerIfNotExists($containerName = '', $metadata = array())
{
if ( ! $this->containerExists($containerName)) {
$this->createContainer($containerName, $metadata);
}
}
/**
* Get container ACL
*
* @param string $containerName Container name
* @param bool $signedIdentifiers Display only private/blob/container or display signed identifiers?
* @return string Acl, to be compared with Blob::ACL_*
* @throws BlobException
*/
public function getContainerAcl($containerName = '', $signedIdentifiers = false)
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
$response = $this->performRequest($containerName, array('restype' => 'container', 'comp' => 'acl'), 'GET', array(), false, null, self::RESOURCE_CONTAINER, self::PERMISSION_READ);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
if ($signedIdentifiers == false) {
// Only private/blob/container
$accessType = $response->getHeader(Storage::PREFIX_STORAGE_HEADER . 'blob-public-access');
if (strtolower($accessType) == 'true') {
$accessType = self::ACL_PUBLIC_CONTAINER;
}
return $accessType;
}
$result = $this->parseResponse($response);
if ( ! $result) {
return array();
}
$entries = null;
if ($result->SignedIdentifier) {
if (count($result->SignedIdentifier) > 1) {
$entries = $result->SignedIdentifier;
} else {
$entries = array($result->SignedIdentifier);
}
}
$returnValue = array();
foreach ($entries as $entry) {
$returnValue[] = new SignedIdentifier(
$entry->Id,
$entry->AccessPolicy ? $entry->AccessPolicy->Start ? $entry->AccessPolicy->Start : '' : '',
$entry->AccessPolicy ? $entry->AccessPolicy->Expiry ? $entry->AccessPolicy->Expiry : '' : '',
$entry->AccessPolicy ? $entry->AccessPolicy->Permission ? $entry->AccessPolicy->Permission : '' : ''
);
}
return $returnValue;
}
/**
* Set container ACL
*
* @param string $containerName Container name
* @param bool $acl Blob::ACL_*
* @param array $signedIdentifiers Signed identifiers
* @throws BlobException
*/
public function setContainerAcl($containerName = '', $acl = self::ACL_PRIVATE, $signedIdentifiers = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
$headers = array();
// Acl specified?
if ($acl != self::ACL_PRIVATE && !is_null($acl) && $acl != '') {
$headers[Storage::PREFIX_STORAGE_HEADER . 'blob-public-access'] = $acl;
}
$policies = null;
if (is_array($signedIdentifiers) && count($signedIdentifiers) > 0) {
$policies = '';
$policies .= '<?xml version="1.0" encoding="utf-8"?>' . "\r\n";
$policies .= '<SignedIdentifiers>' . "\r\n";
foreach ($signedIdentifiers as $signedIdentifier) {
$policies .= ' <SignedIdentifier>' . "\r\n";
$policies .= ' <Id>' . $signedIdentifier->Id . '</Id>' . "\r\n";
$policies .= ' <AccessPolicy>' . "\r\n";
if ($signedIdentifier->Start != '')
$policies .= ' <Start>' . $signedIdentifier->Start . '</Start>' . "\r\n";
if ($signedIdentifier->Expiry != '')
$policies .= ' <Expiry>' . $signedIdentifier->Expiry . '</Expiry>' . "\r\n";
if ($signedIdentifier->Permissions != '')
$policies .= ' <Permission>' . $signedIdentifier->Permissions . '</Permission>' . "\r\n";
$policies .= ' </AccessPolicy>' . "\r\n";
$policies .= ' </SignedIdentifier>' . "\r\n";
}
$policies .= '</SignedIdentifiers>' . "\r\n";
}
$response = $this->performRequest($containerName, array('restype' => 'container', 'comp' => 'acl'), 'PUT', $headers, false, $policies, self::RESOURCE_CONTAINER, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
}
/**
* Get container
*
* @param string $containerName Container name
* @return BlobContainer
* @throws BlobException
*/
public function getContainer($containerName = '')
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
$response = $this->performRequest($containerName, array('restype' => 'container'), 'GET', array(), false, null, self::RESOURCE_CONTAINER, self::PERMISSION_READ);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
$metadata = $this->parseMetadataHeaders($response->getHeaders());
return new BlobContainer(
$containerName,
$response->getHeader('Etag'),
$response->getHeader('Last-modified'),
$metadata
);
}
/**
* Get container metadata
*
* @param string $containerName Container name
* @return array Key/value pairs of meta data
* @throws BlobException
*/
public function getContainerMetadata($containerName = '')
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
return $this->getContainer($containerName)->Metadata;
}
/**
* Set container metadata
*
* Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container. It's not possible to modify an individual name/value pair.
*
* @param string $containerName Container name
* @param array $metadata Key/value pairs of meta data
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @throws BlobException
*/
public function setContainerMetadata($containerName = '', $metadata = array(), $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::isArray($metadata, 'Meta data should be an array of key and value pairs.');
if (count($metadata) == 0) {
return;
}
$headers = array();
$headers = array_merge($headers, $this->generateMetadataHeaders($metadata));
foreach ($additionalHeaders as $key => $value) {
$headers[$key] = $value;
}
$response = $this->performRequest($containerName, array('restype' => 'container', 'comp' => 'metadata'), 'PUT', $headers, false, null, self::RESOURCE_CONTAINER, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
}
/**
* Delete container
*
* @param string $containerName Container name
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @throws BlobException
*/
public function deleteContainer($containerName = '', $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
$headers = array();
foreach ($additionalHeaders as $key => $value) {
$headers[$key] = $value;
}
$response = $this->performRequest($containerName, array('restype' => 'container'), 'DELETE', $headers, false, null, self::RESOURCE_CONTAINER, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
}
/**
* List containers
*
* @param string $prefix Optional. Filters the results to return only containers whose name begins with the specified prefix.
* @param int $maxResults Optional. Specifies the maximum number of containers to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000)
* @param string $marker Optional string value that identifies the portion of the list to be returned with the next list operation.
* @param string $include Optional. Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
* @param int $currentResultCount Current result count (internal use)
* @return array
* @throws BlobException
*/
public function listContainers($prefix = null, $maxResults = null, $marker = null, $include = null, $currentResultCount = 0)
{
// Build query string
$query = array('comp' => 'list');
if (!is_null($prefix)) {
$query['prefix'] = $prefix;
}
if (!is_null($maxResults)) {
$query['maxresults'] = $maxResults;
}
if (!is_null($marker)) {
$query['marker'] = $marker;
}
if (!is_null($include)) {
$query['include'] = $include;
}
$response = $this->performRequest('', $query, 'GET', array(), false, null, self::RESOURCE_CONTAINER, self::PERMISSION_LIST);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
$xmlContainers = $this->parseResponse($response)->Containers->Container;
$xmlMarker = (string)$this->parseResponse($response)->NextMarker;
$containers = array();
if (!is_null($xmlContainers)) {
for ($i = 0; $i < count($xmlContainers); $i++) {
$containers[] = new BlobContainer(
(string)$xmlContainers[$i]->Name,
(string)$xmlContainers[$i]->Etag,
(string)$xmlContainers[$i]->LastModified,
$this->parseMetadataElement($xmlContainers[$i])
);
}
}
$currentResultCount = $currentResultCount + count($containers);
if (!is_null($maxResults) && $currentResultCount < $maxResults) {
if (!is_null($xmlMarker) && $xmlMarker != '') {
$containers = array_merge($containers, $this->listContainers($prefix, $maxResults, $xmlMarker, $include, $currentResultCount));
}
}
if (!is_null($maxResults) && count($containers) > $maxResults) {
$containers = array_slice($containers, 0, $maxResults);
}
return $containers;
}
/**
* Put blob
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param string $localFileName Local file name to be uploaded
* @param array $metadata Key/value pairs of meta data
* @param string $leaseId Lease identifier
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @return object Partial blob properties
* @throws BlobException
*/
public function putBlob($containerName = '', $blobName = '', $localFileName = '', $metadata = array(), $leaseId = null, $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
Assertion::notEmpty($localFileName, 'Local file name is not specified.');
Assertion::file($localFileName, 'Local file name is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
if (filesize($localFileName) >= self::MAX_BLOB_SIZE) {
return $this->putLargeBlob($containerName, $blobName, $localFileName, $metadata, $leaseId, $additionalHeaders);
}
return $this->putBlobData($containerName, $blobName, file_get_contents($localFileName), $metadata, $leaseId, $additionalHeaders);
}
/**
* Put blob data
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param mixed $data Data to store
* @param array $metadata Key/value pairs of meta data
* @param string $leaseId Lease identifier
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @return object Partial blob properties
* @throws BlobException
*/
public function putBlobData($containerName = '', $blobName = '', $data = '', $metadata = array(), $leaseId = null, $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}
$headers = array_merge($headers, $this->generateMetadataHeaders($metadata));
foreach ($additionalHeaders as $key => $value) {
$headers[$key] = $value;
}
$headers[Storage::PREFIX_STORAGE_HEADER . 'blob-type'] = self::BLOBTYPE_BLOCK;
$resourceName = self::createResourceName($containerName , $blobName);
$response = $this->performRequest($resourceName, array(), 'PUT', $headers, false, $data, self::RESOURCE_BLOB, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
return new BlobInstance(
$containerName,
$blobName,
null,
$response->getHeader('Etag'),
$response->getHeader('Last-modified'),
$this->getBaseUrl() . '/' . $containerName . '/' . $blobName,
strlen($data),
'',
'',
'',
false,
$metadata
);
}
/**
* Put large blob (> 64 MB)
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param string $localFileName Local file name to be uploaded
* @param array $metadata Key/value pairs of meta data
* @param string $leaseId Lease identifier
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @return object Partial blob properties
* @throws BlobException
*/
public function putLargeBlob($containerName = '', $blobName = '', $localFileName = '', $metadata = array(), $leaseId = null, $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
Assertion::notEmpty($localFileName, 'Local file name is not specified.');
Assertion::file($localFileName, 'Local file name is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
if (filesize($localFileName) < self::MAX_BLOB_SIZE) {
return $this->putBlob($containerName, $blobName, $localFileName, $metadata, $leaseId, $additionalHeaders);
}
$numberOfParts = ceil( filesize($localFileName) / self::MAX_BLOB_TRANSFER_SIZE );
$blockIdentifiers = array();
for ($i = 0; $i < $numberOfParts; $i++) {
$blockIdentifiers[] = $this->generateBlockId($i);
}
$fp = fopen($localFileName, 'r');
if ($fp === false) {
throw new BlobException('Could not open local file.');
}
for ($i = 0; $i < $numberOfParts; $i++) {
fseek($fp, $i * self::MAX_BLOB_TRANSFER_SIZE);
$fileContents = fread($fp, self::MAX_BLOB_TRANSFER_SIZE);
$this->putBlock($containerName, $blobName, $blockIdentifiers[$i], $fileContents, $leaseId);
$fileContents = null;
unset($fileContents);
}
fclose($fp);
$this->putBlockList($containerName, $blobName, $blockIdentifiers, $metadata, $leaseId, $additionalHeaders);
return $this->getBlobInstance($containerName, $blobName, null, $leaseId);
}
/**
* Put large blob block
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param string $identifier Block ID
* @param array $contents Contents of the block
* @param string $leaseId Lease identifier
* @throws BlobException
*/
public function putBlock($containerName = '', $blobName = '', $identifier = '', $contents = '', $leaseId = null)
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
Assertion::notEmpty($identifier, 'Block identifier is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
if (strlen($contents) > self::MAX_BLOB_TRANSFER_SIZE) {
throw new BlobException('Block size is too big.');
}
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}
$resourceName = self::createResourceName($containerName , $blobName);
$response = $this->performRequest($resourceName, array('comp' => 'block', 'blockid' => base64_encode($identifier)), 'PUT', $headers, false, $contents, self::RESOURCE_BLOB, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
}
/**
* Put block list
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param array $blockList Array of block identifiers
* @param array $metadata Key/value pairs of meta data
* @param string $leaseId Lease identifier
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @throws BlobException
*/
public function putBlockList($containerName = '', $blobName = '', $blockList = array(), $metadata = array(), $leaseId = null, $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
Assertion::notEmpty($blockList, 'Block list does not contain any elements.');
self::assertValidRootContainerBlobName($containerName, $blobName);
$blocks = '';
foreach ($blockList as $block) {
$blocks .= ' <Latest>' . base64_encode($block) . '</Latest>' . "\n";
}
$fileContents = utf8_encode(implode("\n", array(
'<?xml version="1.0" encoding="utf-8"?>',
'<BlockList>',
$blocks,
'</BlockList>'
)));
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}
$headers = array_merge($headers, $this->generateMetadataHeaders($metadata));
foreach ($additionalHeaders as $key => $value) {
$headers[$key] = $value;
}
$resourceName = self::createResourceName($containerName , $blobName);
$response = $this->performRequest($resourceName, array('comp' => 'blocklist'), 'PUT', $headers, false, $fileContents, self::RESOURCE_BLOB, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
}
/**
* Get block list
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param string $snapshotId Snapshot identifier
* @param string $leaseId Lease identifier
* @param integer $type Type of block list to retrieve. 0 = all, 1 = committed, 2 = uncommitted
* @return array
* @throws BlobException
*/
public function getBlockList($containerName = '', $blobName = '', $snapshotId = null, $leaseId = null, $type = 0)
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
if ($type < 0 || $type > 2) {
throw new BlobException('Invalid type of block list to retrieve.');
}
$blockListType = 'all';
if ($type == 1) {
$blockListType = 'committed';
}
if ($type == 2) {
$blockListType = 'uncommitted';
}
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}
$query = array('comp' => 'blocklist', 'blocklisttype' => $blockListType);
if (!is_null($snapshotId)) {
$query['snapshot'] = $snapshotId;
}
$resourceName = self::createResourceName($containerName , $blobName);
$response = $this->performRequest($resourceName, $query, 'GET', $headers, false, null, self::RESOURCE_BLOB, self::PERMISSION_READ);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
$blockList = $this->parseResponse($response);
$returnValue = array();
if ($blockList->CommittedBlocks) {
foreach ($blockList->CommittedBlocks->Block as $block) {
$returnValue['CommittedBlocks'][] = (object)array(
'Name' => (string)$block->Name,
'Size' => (string)$block->Size
);
}
}
if ($blockList->UncommittedBlocks) {
foreach ($blockList->UncommittedBlocks->Block as $block) {
$returnValue['UncommittedBlocks'][] = (object)array(
'Name' => (string)$block->Name,
'Size' => (string)$block->Size
);
}
}
return $returnValue;
}
/**
* Create page blob
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param int $size Size of the page blob in bytes
* @param array $metadata Key/value pairs of meta data
* @param string $leaseId Lease identifier
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @return object Partial blob properties
* @throws BlobException
*/
public function createPageBlob($containerName = '', $blobName = '', $size = 0, $metadata = array(), $leaseId = null, $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
if ($size <= 0) {
throw new BlobException('Page blob size must be specified.');
}
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}
$headers = array_merge($headers, $this->generateMetadataHeaders($metadata));
foreach ($additionalHeaders as $key => $value) {
$headers[$key] = $value;
}
$headers[Storage::PREFIX_STORAGE_HEADER . 'blob-type'] = self::BLOBTYPE_PAGE;
$headers[Storage::PREFIX_STORAGE_HEADER . 'blob-content-length'] = $size;
$headers['Content-Length'] = 0;
$resourceName = self::createResourceName($containerName , $blobName);
$response = $this->performRequest($resourceName, array(), 'PUT', $headers, false, '', self::RESOURCE_BLOB, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
return new BlobInstance(
$containerName,
$blobName,
null,
$response->getHeader('Etag'),
$response->getHeader('Last-modified'),
$this->getBaseUrl() . '/' . $containerName . '/' . $blobName,
$size,
'',
'',
'',
false,
$metadata
);
}
/**
* Put page in page blob
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param int $startByteOffset Start byte offset
* @param int $endByteOffset End byte offset
* @param mixed $contents Page contents
* @param string $writeMethod Write method (Blob::PAGE_WRITE_*)
* @param string $leaseId Lease identifier
* @param array $additionalHeaders Additional headers. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @throws BlobException
*/
public function putPage($containerName = '', $blobName = '', $startByteOffset = 0, $endByteOffset = 0, $contents = '', $writeMethod = self::PAGE_WRITE_UPDATE, $leaseId = null, $additionalHeaders = array())
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
if ($startByteOffset % 512 != 0) {
throw new BlobException('Start byte offset must be a modulus of 512.');
}
if (($endByteOffset + 1) % 512 != 0) {
throw new BlobException('End byte offset must be a modulus of 512 minus 1.');
}
$size = strlen($contents);
if ($size >= self::MAX_BLOB_TRANSFER_SIZE) {
throw new BlobException('Page blob size must not be larger than ' + self::MAX_BLOB_TRANSFER_SIZE . ' bytes.');
}
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}
foreach ($additionalHeaders as $key => $value) {
$headers[$key] = $value;
}
$headers['Range'] = 'bytes=' . $startByteOffset . '-' . $endByteOffset;
$headers[Storage::PREFIX_STORAGE_HEADER . 'page-write'] = $writeMethod;
$resourceName = self::createResourceName($containerName , $blobName);
$response = $this->performRequest($resourceName, array('comp' => 'page'), 'PUT', $headers, false, $contents, self::RESOURCE_BLOB, self::PERMISSION_WRITE);
if ( ! $response->isSuccessful()) {
throw new BlobException($this->getErrorMessage($response, 'Resource could not be accessed.'));
}
}
/**
* Put page in page blob
*
* @param string $containerName Container name
* @param string $blobName Blob name
* @param int $startByteOffset Start byte offset
* @param int $endByteOffset End byte offset
* @param string $leaseId Lease identifier
* @return array Array of page ranges
* @throws BlobException
*/
public function getPageRegions($containerName = '', $blobName = '', $startByteOffset = 0, $endByteOffset = 0, $leaseId = null)
{
Assertion::notEmpty($containerName, 'Container name is not specified');
self::assertValidContainerName($containerName);
Assertion::notEmpty($blobName, 'Blob name is not specified.');
self::assertValidRootContainerBlobName($containerName, $blobName);
if ($startByteOffset % 512 != 0) {
throw new BlobException('Start byte offset must be a modulus of 512.');
}
if ($endByteOffset > 0 && ($endByteOffset + 1) % 512 != 0) {
throw new BlobException('End byte offset must be a modulus of 512 minus 1.');
}
$headers = array();
if (!is_null($leaseId)) {
$headers['x-ms-lease-id'] = $leaseId;
}