-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpackager.php
More file actions
1472 lines (1412 loc) · 48.8 KB
/
Copy pathpackager.php
File metadata and controls
1472 lines (1412 loc) · 48.8 KB
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
// Copyright (c) 2012 - 2014 Pulse Storm LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//in progress, use at your own risk
if (!defined('DS')) define('DS','/');
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
date_default_timezone_set('America/Los_Angeles');
class Mage_Archive_Helper_File
{
/**
* Full path to directory where file located
*
* @var string
*/
protected $_fileLocation;
/**
* File name
*
* @var string
*/
protected $_fileName;
/**
* Full path (directory + filename) to file
*
* @var string
*/
protected $_filePath;
/**
* File permissions that will be set if file opened in write mode
*
* @var int
*/
protected $_chmod;
/**
* File handler
*
* @var pointer
*/
protected $_fileHandler;
/**
* Set file path via constructor
*
* @param string $filePath
*/
public function __construct($filePath)
{
$pathInfo = pathinfo($filePath);
$this->_filePath = $filePath;
$this->_fileLocation = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : '';
$this->_fileName = isset($pathInfo['basename']) ? $pathInfo['basename'] : '';
}
/**
* Close file if it's not closed before object destruction
*/
public function __destruct()
{
if ($this->_fileHandler) {
$this->_close();
}
}
/**
* Open file
*
* @param string $mode
* @param int $chmod
* @throws Mage_Exception
*/
public function open($mode = 'w+', $chmod = 0666)
{
if ($this->_isWritableMode($mode)) {
if (!is_writable($this->_fileLocation)) {
throw new Mage_Exception('Permission denied to write to ' . $this->_fileLocation);
}
if (is_file($this->_filePath) && !is_writable($this->_filePath)) {
throw new Mage_Exception("Can't open file " . $this->_fileName . " for writing. Permission denied.");
}
}
if ($this->_isReadableMode($mode) && (!is_file($this->_filePath) || !is_readable($this->_filePath))) {
if (!is_file($this->_filePath)) {
throw new Mage_Exception('File ' . $this->_filePath . ' does not exist');
}
if (!is_readable($this->_filePath)) {
throw new Mage_Exception('Permission denied to read file ' . $this->_filePath);
}
}
$this->_open($mode);
$this->_chmod = $chmod;
}
/**
* Write data to file
*
* @param string $data
*/
public function write($data)
{
$this->_checkFileOpened();
$this->_write($data);
}
/**
* Read data from file
*
* @param int $length
* @return string|boolean
*/
public function read($length = 4096)
{
$data = false;
$this->_checkFileOpened();
if ($length > 0) {
$data = $this->_read($length);
}
return $data;
}
/**
* Check whether end of file reached
*
* @return boolean
*/
public function eof()
{
$this->_checkFileOpened();
return $this->_eof();
}
/**
* Close file
*/
public function close()
{
$this->_checkFileOpened();
$this->_close();
$this->_fileHandler = false;
@chmod($this->_filePath, $this->_chmod);
}
/**
* Implementation of file opening
*
* @param string $mode
* @throws Mage_Exception
*/
protected function _open($mode)
{
$this->_fileHandler = @fopen($this->_filePath, $mode);
if (false === $this->_fileHandler) {
throw new Mage_Exception('Failed to open file ' . $this->_filePath);
}
}
/**
* Implementation of writing data to file
*
* @param string $data
* @throws Mage_Exception
*/
protected function _write($data)
{
$result = @fwrite($this->_fileHandler, $data);
if (false === $result) {
throw new Mage_Exception('Failed to write data to ' . $this->_filePath);
}
}
/**
* Implementation of file reading
*
* @param int $length
* @throws Mage_Exception
*/
protected function _read($length)
{
$result = fread($this->_fileHandler, $length);
if (false === $result) {
throw new Mage_Exception('Failed to read data from ' . $this->_filePath);
}
return $result;
}
/**
* Implementation of EOF indicator
*
* @return boolean
*/
protected function _eof()
{
return feof($this->_fileHandler);
}
/**
* Implementation of file closing
*/
protected function _close()
{
fclose($this->_fileHandler);
}
/**
* Check whether requested mode is writable mode
*
* @param string $mode
*/
protected function _isWritableMode($mode)
{
return preg_match('/(^[waxc])|(\+$)/', $mode);
}
/**
* Check whether requested mode is readable mode
*
* @param string $mode
*/
protected function _isReadableMode($mode) {
return !$this->_isWritableMode($mode);
}
/**
* Check whether file is opened
*
* @throws Mage_Exception
*/
protected function _checkFileOpened()
{
if (!$this->_fileHandler) {
throw new Mage_Exception('File not opened');
}
}
}
interface Mage_Archive_Interface
{
/**
* Pack file or directory.
*
* @param string $source
* @param string $destination
* @return string
*/
public function pack($source, $destination);
/**
* Unpack file or directory.
*
* @param string $source
* @param string $destination
* @return string
*/
public function unpack($source, $destination);
}
class Mage_Archive_Abstract
{
/**
* Write data to file. If file can't be opened - throw exception
*
* @param string $destination
* @param string $data
* @return boolean
* @throws Mage_Exception
*/
protected function _writeFile($destination, $data)
{
$destination = trim($destination);
if(false === file_put_contents($destination, $data)) {
throw new Mage_Exception("Can't write to file: " . $destination);
}
return true;
}
/**
* Read data from file. If file can't be opened, throw to exception.
*
* @param string $source
* @return string
* @throws Mage_Exception
*/
protected function _readFile($source)
{
$data = '';
if (is_file($source) && is_readable($source)) {
$data = @file_get_contents($source);
if ($data === false) {
throw new Mage_Exception("Can't get contents from: " . $source);
}
}
return $data;
}
/**
* Get file name from source (URI) without last extension.
*
* @param string $source
* @param bool $withExtension
* @return mixed|string
*/
public function getFilename($source, $withExtension=false)
{
$file = str_replace(dirname($source) . DS, '', $source);
if (!$withExtension) {
$file = substr($file, 0, strrpos($file, '.'));
}
return $file;
}
}
class Mage_Archive_Tar extends Mage_Archive_Abstract implements Mage_Archive_Interface
{
/**
* Tar block size
*
* @const int
*/
const TAR_BLOCK_SIZE = 512;
/**
* Keep file or directory for packing.
*
* @var string
*/
protected $_currentFile;
/**
* Keep path to file or directory for packing.
*
* @var mixed
*/
protected $_currentPath;
/**
* Skip first level parent directory. Example:
* use test/fip.php instead test/test/fip.php;
*
* @var mixed
*/
protected $_skipRoot;
/**
* Tarball data writer
*
* @var Mage_Archive_Helper_File
*/
protected $_writer;
/**
* Tarball data reader
*
* @var Mage_Archive_Helper_File
*/
protected $_reader;
/**
* Path to file where tarball should be placed
*
* @var string
*/
protected $_destinationFilePath;
/**
* Initialize tarball writer
*
* @return Mage_Archive_Tar
*/
protected function _initWriter()
{
$this->_writer = new Mage_Archive_Helper_File($this->_destinationFilePath);
$this->_writer->open('w');
return $this;
}
/**
* Returns string that is used for tar's header parsing
*
* @return string
*/
protected static final function _getFormatParseHeader()
{
return 'a100name/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100symlink/a6magic/a2version/'
. 'a32uname/a32gname/a8devmajor/a8devminor/a155prefix/a12closer';
}
/**
* Destroy tarball writer
*
* @return Mage_Archive_Tar
*/
protected function _destroyWriter()
{
if ($this->_writer instanceof Mage_Archive_Helper_File) {
$this->_writer->close();
$this->_writer = null;
}
return $this;
}
/**
* Get tarball writer
*
* @return Mage_Archive_Helper_File
*/
protected function _getWriter()
{
if (!$this->_writer) {
$this->_initWriter();
}
return $this->_writer;
}
/**
* Initialize tarball reader
*
* @return Mage_Archive_Tar
*/
protected function _initReader()
{
$this->_reader = new Mage_Archive_Helper_File($this->_getCurrentFile());
$this->_reader->open('r');
return $this;
}
/**
* Destroy tarball reader
*
* @return Mage_Archive_Tar
*/
protected function _destroyReader()
{
if ($this->_reader instanceof Mage_Archive_Helper_File) {
$this->_reader->close();
$this->_reader = null;
}
return $this;
}
/**
* Get tarball reader
*
* @return Mage_Archive_Helper_File
*/
protected function _getReader()
{
if (!$this->_reader) {
$this->_initReader();
}
return $this->_reader;
}
/**
* Set option that define ability skip first catalog level.
*
* @param mixed $skipRoot
* @return Mage_Archive_Tar
*/
protected function _setSkipRoot($skipRoot)
{
$this->_skipRoot = $skipRoot;
return $this;
}
/**
* Set file which is packing.
*
* @param string $file
* @return Mage_Archive_Tar
*/
protected function _setCurrentFile($file)
{
$this->_currentFile = $file .((!is_link($file) && is_dir($file) && substr($file, -1) != DS) ? DS : '');
return $this;
}
/**
* Set path to file where tarball should be placed
*
* @param string $destinationFilePath
* @return Mage_Archive_Tar
*/
protected function _setDestinationFilePath($destinationFilePath)
{
$this->_destinationFilePath = $destinationFilePath;
return $this;
}
/**
* Retrieve file which is packing.
*
* @return string
*/
protected function _getCurrentFile()
{
return $this->_currentFile;
}
/**
* Set path to file which is packing.
*
* @param string $path
* @return Mage_Archive_Tar
*/
protected function _setCurrentPath($path)
{
if ($this->_skipRoot && is_dir($path)) {
$this->_currentPath = $path.(substr($path, -1)!=DS?DS:'');
} else {
$this->_currentPath = dirname($path) . DS;
}
return $this;
}
/**
* Retrieve path to file which is packing.
*
* @return string
*/
protected function _getCurrentPath()
{
return $this->_currentPath;
}
/**
* Walk through directory and add to tar file or directory.
* Result is packed string on TAR format.
*
* @deprecated after 1.7.0.0
* @param boolean $skipRoot
* @return string
*/
protected function _packToTar($skipRoot=false)
{
$file = $this->_getCurrentFile();
$header = '';
$data = '';
if (!$skipRoot) {
$header = $this->_composeHeader();
$data = $this->_readFile($file);
$data = str_pad($data, floor(((is_dir($file) ? 0 : filesize($file)) + 512 - 1) / 512) * 512, "\0");
}
$sub = '';
if (is_dir($file)) {
$treeDir = scandir($file);
if (empty($treeDir)) {
throw new Mage_Exception('Can\'t scan dir: ' . $file);
}
array_shift($treeDir); /* remove './'*/
array_shift($treeDir); /* remove '../'*/
foreach ($treeDir as $item) {
$sub .= $this->_setCurrentFile($file.$item)->_packToTar(false);
}
}
$tarData = $header . $data . $sub;
$tarData = str_pad($tarData, floor((strlen($tarData) - 1) / 1536) * 1536, "\0");
return $tarData;
}
/**
* Recursively walk through file tree and create tarball
*
* @param boolean $skipRoot
* @param boolean $finalize
* @throws Mage_Exception
*/
protected function _createTar($skipRoot = false, $finalize = false)
{
if (!$skipRoot) {
$this->_packAndWriteCurrentFile();
}
$file = $this->_getCurrentFile();
if (is_dir($file)) {
$dirFiles = scandir($file);
if (false === $dirFiles) {
throw new Mage_Exception('Can\'t scan dir: ' . $file);
}
array_shift($dirFiles); /* remove './'*/
array_shift($dirFiles); /* remove '../'*/
foreach ($dirFiles as $item) {
$this->_setCurrentFile($file . $item)->_createTar();
}
}
if ($finalize) {
$this->_getWriter()->write(str_repeat("\0", self::TAR_BLOCK_SIZE * 12));
}
}
/**
* Write current file to tarball
*/
protected function _packAndWriteCurrentFile()
{
$archiveWriter = $this->_getWriter();
$archiveWriter->write($this->_composeHeader());
$currentFile = $this->_getCurrentFile();
$fileSize = 0;
if (is_file($currentFile) && !is_link($currentFile)) {
$fileReader = new Mage_Archive_Helper_File($currentFile);
$fileReader->open('r');
while (!$fileReader->eof()) {
$archiveWriter->write($fileReader->read());
}
$fileReader->close();
$fileSize = filesize($currentFile);
}
$appendZerosCount = (self::TAR_BLOCK_SIZE - $fileSize % self::TAR_BLOCK_SIZE) % self::TAR_BLOCK_SIZE;
$archiveWriter->write(str_repeat("\0", $appendZerosCount));
}
/**
* Compose header for current file in TAR format.
* If length of file's name greater 100 characters,
* method breaks header into two pieces. First contains
* header and data with long name. Second contain only header.
*
* @param boolean $long
* @return string
*/
protected function _composeHeader($long = false)
{
$file = $this->_getCurrentFile();
$path = $this->_getCurrentPath();
$infoFile = stat($file);
$nameFile = str_replace($path, '', $file);
$nameFile = str_replace('\\', '/', $nameFile);
$packedHeader = '';
$longHeader = '';
if (!$long && strlen($nameFile)>100) {
$longHeader = $this->_composeHeader(true);
$longHeader .= str_pad($nameFile, floor((strlen($nameFile) + 512 - 1) / 512) * 512, "\0");
}
$header = array();
$header['100-name'] = $long?'././@LongLink':substr($nameFile, 0, 100);
$header['8-mode'] = $long ? ' '
: str_pad(substr(sprintf("%07o", $infoFile['mode']),-4), 6, '0', STR_PAD_LEFT);
$header['8-uid'] = $long || $infoFile['uid']==0?"\0\0\0\0\0\0\0":sprintf("%07o", $infoFile['uid']);
$header['8-gid'] = $long || $infoFile['gid']==0?"\0\0\0\0\0\0\0":sprintf("%07o", $infoFile['gid']);
$header['12-size'] = $long ? sprintf("%011o", strlen($nameFile)) : sprintf("%011o", is_dir($file)
? 0 : filesize($file));
$header['12-mtime'] = $long?'00000000000':sprintf("%011o", $infoFile['mtime']);
$header['8-check'] = sprintf('% 8s', '');
$header['1-type'] = $long ? 'L' : (is_link($file) ? 2 : (is_dir($file) ? 5 : 0));
$header['100-symlink'] = is_link($file) ? readlink($file) : '';
$header['6-magic'] = 'ustar ';
$header['2-version'] = ' ';
$a=function_exists('posix_getpwuid')?posix_getpwuid (fileowner($file)):array('name'=>'');
$header['32-uname'] = $a['name'];
$a=function_exists('posix_getgrgid')?posix_getgrgid (filegroup($file)):array('name'=>'');
$header['32-gname'] = $a['name'];
$header['8-devmajor'] = '';
$header['8-devminor'] = '';
$header['155-prefix'] = '';
$header['12-closer'] = '';
$packedHeader = '';
foreach ($header as $key=>$element) {
$length = explode('-', $key);
$packedHeader .= pack('a' . $length[0], $element);
}
$checksum = 0;
for ($i = 0; $i < 512; $i++) {
$checksum += ord(substr($packedHeader, $i, 1));
}
$packedHeader = substr_replace($packedHeader, sprintf("%07o", $checksum)."\0", 148, 8);
return $longHeader . $packedHeader;
}
/**
* Read TAR string from file, and unpacked it.
* Create files and directories information about discribed
* in the string.
*
* @param string $destination path to file is unpacked
* @return array list of files
* @throws Mage_Exception
*/
protected function _unpackCurrentTar($destination)
{
$archiveReader = $this->_getReader();
$list = array();
while (!$archiveReader->eof()) {
$header = $this->_extractFileHeader();
if (!$header) {
continue;
}
$currentFile = $destination . $header['name'];
$dirname = dirname($currentFile);
if (in_array($header['type'], array("0",chr(0), ''))) {
if(!file_exists($dirname)) {
$mkdirResult = @mkdir($dirname, 0777, true);
if (false === $mkdirResult) {
throw new Mage_Exception('Failed to create directory ' . $dirname);
}
}
$this->_extractAndWriteFile($header, $currentFile);
$list[] = $currentFile;
} elseif ($header['type'] == '5') {
if(!file_exists($dirname)) {
$mkdirResult = @mkdir($currentFile, $header['mode'], true);
if (false === $mkdirResult) {
throw new Mage_Exception('Failed to create directory ' . $currentFile);
}
}
$list[] = $currentFile . DS;
} elseif ($header['type'] == '2') {
$symlinkResult = @symlink($header['symlink'], $currentFile);
if (false === $symlinkResult) {
throw new Mage_Exception('Failed to create symlink ' . $currentFile . ' to ' . $header['symlink']);
}
}
}
return $list;
}
/**
* Get header from TAR string and unpacked it by format.
*
* @deprecated after 1.7.0.0
* @param resource $pointer
* @return string
*/
protected function _parseHeader(&$pointer)
{
$firstLine = fread($pointer, 512);
if (strlen($firstLine)<512){
return false;
}
$fmt = self::_getFormatParseHeader();
$header = unpack ($fmt, $firstLine);
$header['mode']=$header['mode']+0;
$header['uid']=octdec($header['uid']);
$header['gid']=octdec($header['gid']);
$header['size']=octdec($header['size']);
$header['mtime']=octdec($header['mtime']);
$header['checksum']=octdec($header['checksum']);
if ($header['type'] == "5") {
$header['size'] = 0;
}
$checksum = 0;
$firstLine = substr_replace($firstLine, ' ', 148, 8);
for ($i = 0; $i < 512; $i++) {
$checksum += ord(substr($firstLine, $i, 1));
}
$isUstar = 'ustar' == strtolower(substr($header['magic'], 0, 5));
$checksumOk = $header['checksum'] == $checksum;
if (isset($header['name']) && $checksumOk) {
if ($header['name'] == '././@LongLink' && $header['type'] == 'L') {
$realName = substr(fread($pointer, floor(($header['size'] + 512 - 1) / 512) * 512), 0, $header['size']);
$headerMain = $this->_parseHeader($pointer);
$headerMain['name'] = $realName;
return $headerMain;
} else {
if ($header['size']>0) {
$header['data'] = substr(fread($pointer, floor(($header['size'] + 512 - 1) / 512) * 512), 0, $header['size']);
} else {
$header['data'] = '';
}
return $header;
}
}
return false;
}
/**
* Read and decode file header information from tarball
*
* @return array|boolean
*/
protected function _extractFileHeader()
{
$archiveReader = $this->_getReader();
$headerBlock = $archiveReader->read(self::TAR_BLOCK_SIZE);
if (strlen($headerBlock) < self::TAR_BLOCK_SIZE) {
return false;
}
$header = unpack(self::_getFormatParseHeader(), $headerBlock);
$header['mode'] = octdec($header['mode']);
$header['uid'] = octdec($header['uid']);
$header['gid'] = octdec($header['gid']);
$header['size'] = octdec($header['size']);
$header['mtime'] = octdec($header['mtime']);
$header['checksum'] = octdec($header['checksum']);
if ($header['type'] == "5") {
$header['size'] = 0;
}
$checksum = 0;
$headerBlock = substr_replace($headerBlock, ' ', 148, 8);
for ($i = 0; $i < 512; $i++) {
$checksum += ord(substr($headerBlock, $i, 1));
}
$checksumOk = $header['checksum'] == $checksum;
if (isset($header['name']) && $checksumOk) {
if (!($header['name'] == '././@LongLink' && $header['type'] == 'L')) {
$header['name'] = trim($header['name']);
return $header;
}
$realNameBlockSize = floor(($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE)
* self::TAR_BLOCK_SIZE;
$realNameBlock = $archiveReader->read($realNameBlockSize);
$realName = substr($realNameBlock, 0, $header['size']);
$headerMain = $this->_extractFileHeader();
$headerMain['name'] = trim($realName);
return $headerMain;
}
return false;
}
/**
* Extract next file from tarball by its $header information and save it to $destination
*
* @param array $fileHeader
* @param string $destination
*/
protected function _extractAndWriteFile($fileHeader, $destination)
{
$fileWriter = new Mage_Archive_Helper_File($destination);
$fileWriter->open('w', $fileHeader['mode']);
$archiveReader = $this->_getReader();
$filesize = $fileHeader['size'];
$bytesExtracted = 0;
while ($filesize > $bytesExtracted && !$archiveReader->eof()) {
$block = $archiveReader->read(self::TAR_BLOCK_SIZE);
$nonExtractedBytesCount = $filesize - $bytesExtracted;
$data = substr($block, 0, $nonExtractedBytesCount);
$fileWriter->write($data);
$bytesExtracted += strlen($block);
}
}
/**
* Pack file to TAR (Tape Archiver).
*
* @param string $source
* @param string $destination
* @param boolean $skipRoot
* @return string
*/
public function pack($source, $destination, $skipRoot = false)
{
$this->_setSkipRoot($skipRoot);
$source = realpath($source);
$tarData = $this->_setCurrentPath($source)
->_setDestinationFilePath($destination)
->_setCurrentFile($source);
$this->_initWriter();
$this->_createTar($skipRoot, true);
$this->_destroyWriter();
return $destination;
}
/**
* Unpack file from TAR (Tape Archiver).
*
* @param string $source
* @param string $destination
* @return string
*/
public function unpack($source, $destination)
{
$this->_setCurrentFile($source)
->_setCurrentPath($source);
$this->_initReader();
$this->_unpackCurrentTar($destination);
$this->_destroyReader();
return $destination;
}
/**
* Extract one file from TAR (Tape Archiver).
*
* @param string $file
* @param string $source
* @param string $destination
* @return string
*/
public function extract($file, $source, $destination)
{
$this->_setCurrentFile($source);
$this->_initReader();
$archiveReader = $this->_getReader();
$extractedFile = '';
while (!$archiveReader->eof()) {
$header = $this->_extractFileHeader();
if ($header['name'] == $file) {
$extractedFile = $destination . basename($header['name']);
$this->_extractAndWriteFile($header, $extractedFile);
break;
}
if ($header['type'] != 5){
$skipBytes = floor(($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE)
* self::TAR_BLOCK_SIZE;
$archiveReader->read($skipBytes);
}
}
$this->_destroyReader();
return $extractedFile;
}
}
class Mage_Exception extends Exception
{}
/**
* Still a lot of Magento users stuck on systems with 5.2, no no namespaces
* @todo but we're using anonymous functions below, so this won't work with
* 5.2 -- do we want this as a class, or a single file namespaced module?
*/
class Pulsestorm_MagentoTarToConnect
{
static public $verbose=true;
//from http://php.net/glob
// Does not support flag GLOB_BRACE
static public function globRecursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$files = array_merge($files, self::globRecursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
static public function input($string)
{
self::output($string);
self::output('] ','');
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
fclose($handle);
return $line;
}
static public function output($string, $newline="\n")
{
if(!self::$verbose)
{
return;
}
echo $string,$newline;
}
static public function error($string)
{
self::output("ERROR: " . $string);
self::output("Execution halted at " . __FILE__ . '::' . __LINE__);
exit;
}
static public function createPackageXmlAddNode($xml, $full_dir, $base_dir=false)
{
$parts = explode("/",str_replace($base_dir.'/','',$full_dir));
$single_file = array_pop($parts);
$node = $xml;
foreach($parts as $part)
{
$nodes = $node->xpath("dir[@name='".$part."']");
if(count($nodes) > 0)
{
$node = array_pop($nodes);
}
else
{
$node = $node->addChild('dir');
$node->addAttribute('name', $part);
}
}
$node = $node->addChild('file');
$node->addAttribute('name',$single_file);
$node->addAttribute('hash',md5_file($full_dir));
}
static public function createPackageXml($files, $base_dir, $config)
{
$xml = simplexml_load_string('<package/>');
$xml->name = $config['extension_name'];
$xml->version = $config['extension_version'];
$xml->stability = $config['stability'];
$xml->license = $config['license'];
$xml->channel = $config['channel'];
$xml->extends = '';
$xml->summary = $config['summary'];
$xml->description = $config['description'];
$xml->notes = $config['notes'];
$authors = $xml->addChild('authors');
foreach (self::getAuthorData($config) as $oneAuthor) {
$author = $authors->addChild('author');
$author->name = $oneAuthor['author_name'];
$author->user = $oneAuthor['author_user'];
$author->email = $oneAuthor['author_email'];
}
$xml->date = date('Y-m-d');
$xml->time = date('G:i:s');
$xml->compatible = '';
$dependencies = $xml->addChild('dependencies');
$required = $dependencies->addChild('required');
$php = $required->addChild('php');
$php->min = $config['php_min']; //'5.2.0';
$php->max = $config['php_max']; //'6.0.0';
// add php extension dependencies
if (is_array($config['extensions'])) {
foreach ($config['extensions'] as $extinfo) {
$extension = $required->addChild('extension');
if (is_array($extinfo)) {
$extension->name = $extinfo['name'];
$extension->min = isset($extinfo['min']) ? $extinfo['min'] : "";
$extension->max = isset($extinfo['max']) ? $extinfo['max'] : "";
} else {
$extension->name = $extinfo;
$extension->min = "";
$extension->max = "";
}
}
}
$node = $xml->addChild('contents');
$node = $node->addChild('target');
$node->addAttribute('name', 'mage');
// $files = $this->recursiveGlob($temp_dir);
// $files = array_unique($files);
$temp_dir = false;
foreach($files as $file)
{
//$this->addFileNode($node,$temp_dir,$file);
self::createPackageXmlAddNode($node, $file, $base_dir);
}
//file_put_contents($temp_dir . '/package.xml', $xml->asXml());
return $xml->asXml();
}
static public function getTempDir()
{
$name = tempnam(sys_get_temp_dir(),'tmp');
unlink($name);
$name = $name;