summaryrefslogtreecommitdiff
path: root/ext/phar/phar.phar
blob: 793e7189e81cdbcf75c6ecfbf78b56595db585de (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
#!/usr/bin/php
<?php if (!class_exists('PHP_Archive')) {
?><?php
/**
 * PHP_Archive Class (implements .phar)
 *
 * @package PHP_Archive
 * @category PHP
 */
/**
 * PHP_Archive Class (implements .phar)
 *
 * PHAR files a singular archive from which an entire application can run.
 * To use it, simply package it using {@see PHP_Archive_Creator} and use phar://
 * URIs to your includes. i.e. require_once 'phar://config.php' will include config.php
 * from the root of the PHAR file.
 *
 * Gz code borrowed from the excellent File_Archive package by Vincent Lascaux.
 *
 * @copyright Copyright David Shafik and Synaptic Media 2004. All rights reserved.
 * @author Davey Shafik <davey@synapticmedia.net>
 * @author Greg Beaver <cellog@php.net>
 * @link http://www.synapticmedia.net Synaptic Media
 * @version $Id: Archive.php,v 1.43 2007/05/28 18:20:40 helly Exp $
 * @package PHP_Archive
 * @category PHP
 */
 
class PHP_Archive
{
    const GZ = 0x00001000;
    const BZ2 = 0x00002000;
    const SIG = 0x00010000;
    const SHA1 = 0x0002;
    const MD5 = 0x0001;
    /**
     * Whether this archive is compressed with zlib
     *
     * @var bool
     */
    private $_compressed;
    /**
     * @var string Real path to the .phar archive
     */
    private $_archiveName = null;
    /**
     * Current file name in the phar
     * @var string
     */
    protected $currentFilename = null;
    /**
     * Length of current file in the phar
     * @var string
     */
    protected $internalFileLength = null;
    /**
     * Current file statistics (size, creation date, etc.)
     * @var string
     */
    protected $currentStat = null;
    /**
     * @var resource|null Pointer to open .phar
     */
    protected $fp = null;
    /**
     * @var int Current Position of the pointer
     */
    protected $position = 0;

    /**
     * Map actual realpath of phars to meta-data about the phar
     *
     * Data is indexed by the alias that is used by internal files.  In other
     * words, if a file is included via:
     * <code>
     * require_once 'phar://PEAR.phar/PEAR/Installer.php';
     * </code>
     * then the alias is "PEAR.phar"
     * 
     * Information stored is a boolean indicating whether this .phar is compressed
     * with zlib, another for bzip2, phar-specific meta-data, and
     * the precise offset of internal files
     * within the .phar, used with the {@link $_manifest} to load actual file contents
     * @var array
     */
    private static $_pharMapping = array();
    /**
     * Map real file paths to alias used
     *
     * @var array
     */
    private static $_pharFiles = array();
    /**
     * File listing for the .phar
     * 
     * The manifest is indexed per phar.
     * 
     * Files within the .phar are indexed by their relative path within the
     * .phar.  Each file has this information in its internal array
     *
     * - 0 = uncompressed file size
     * - 1 = timestamp of when file was added to phar
     * - 2 = offset of file within phar relative to internal file's start
     * - 3 = compressed file size (actual size in the phar)
     * @var array
     */
    private static $_manifest = array();
    /**
     * Absolute offset of internal files within the .phar, indexed by absolute
     * path to the .phar
     *
     * @var array
     */
    private static $_fileStart = array();
    /**
     * file name of the phar
     *
     * @var string
     */
    private $_basename;


    /**
     * Default MIME types used for the web front controller
     *
     * @var array
     */
    public static $defaultmimes = array(
            'aif' => 'audio/x-aiff',
            'aiff' => 'audio/x-aiff',
            'arc' => 'application/octet-stream',
            'arj' => 'application/octet-stream',
            'art' => 'image/x-jg',
            'asf' => 'video/x-ms-asf',
            'asx' => 'video/x-ms-asf',
            'avi' => 'video/avi',
            'bin' => 'application/octet-stream',
            'bm' => 'image/bmp',
            'bmp' => 'image/bmp',
            'bz2' => 'application/x-bzip2',
            'css' => 'text/css',
            'doc' => 'application/msword',
            'dot' => 'application/msword',
            'dv' => 'video/x-dv',
            'dvi' => 'application/x-dvi',
            'eps' => 'application/postscript',
            'exe' => 'application/octet-stream',
            'gif' => 'image/gif',
            'gz' => 'application/x-gzip',
            'gzip' => 'application/x-gzip',
            'htm' => 'text/html',
            'html' => 'text/html',
            'ico' => 'image/x-icon',
            'jpe' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'js' => 'application/x-javascript',
            'log' => 'text/plain',
            'mid' => 'audio/x-midi',
            'mov' => 'video/quicktime',
            'mp2' => 'audio/mpeg',
            'mp3' => 'audio/mpeg3',
            'mpg' => 'audio/mpeg',
            'pdf' => 'aplication/pdf',
            'png' => 'image/png',
            'rtf' => 'application/rtf',
            'tif' => 'image/tiff',
            'tiff' => 'image/tiff',
            'txt' => 'text/plain',
            'xml' => 'text/xml',
        );

    public static $defaultphp = array(
        'php' => true
        );

    public static $defaultphps = array(
        'phps' => true
        );

    public static $deny = array('/.+\.inc$/');

    public static function viewSource($archive, $file)
    {
        // security, idea borrowed from PHK
        if (!file_exists($archive . '.introspect')) {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        if (self::_fileExists($archive, $_GET['viewsource'])) {
            $source = highlight_file('phar://@ALIAS@/' .
                $_GET['viewsource'], true);
            header('Content-Type: text/html');
            header('Content-Length: ' . strlen($source));
            echo '<html><head><title>Source of ',
                htmlspecialchars($_GET['viewsource']), '</title></head>';
            echo '<body><h1>Source of ',
                htmlspecialchars($_GET['viewsource']), '</h1>';
            if (isset($_GET['introspect'])) {
                echo '<a href="', htmlspecialchars($_SERVER['PHP_SELF']),
                    '?introspect=', urlencode(htmlspecialchars($_GET['introspect'])),
                    '">Return to ', htmlspecialchars($_GET['introspect']), '</a><br />';
            }
            echo $source;
            exit;
        } else {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        
    }

    public static function introspect($archive, $dir)
    {
        // security, idea borrowed from PHK
        if (!file_exists($archive . '.introspect')) {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        if (!$dir) {
            $dir = '/';
        }
        $dir = self::processFile($dir);
        if ($dir[0] != '/') {
            $dir = '/' . $dir;
        }
        try {
            $self = htmlspecialchars($_SERVER['PHP_SELF']);
            $iterate = new DirectoryIterator('phar://@ALIAS@' . $dir);
            echo '<html><head><title>Introspect ', htmlspecialchars($dir),
                '</title></head><body><h1>Introspect ', htmlspecialchars($dir),
                '</h1><ul>';
            if ($dir != '/') {
                echo '<li><a href="', $self, '?introspect=',
                    htmlspecialchars(dirname($dir)), '">..</a></li>';
            }
            foreach ($iterate as $entry) {
                if ($entry->isDot()) continue;
                $name = self::processFile($entry->getPathname());
                $name = str_replace('phar://@ALIAS@/', '', $name);
                if ($entry->isDir()) {
                    echo '<li><a href="', $self, '?introspect=',
                        urlencode(htmlspecialchars($name)),
                        '">',
                        htmlspecialchars($entry->getFilename()), '/</a> [directory]</li>';
                } else {
                    echo '<li><a href="', $self, '?introspect=',
                        urlencode(htmlspecialchars($dir)), '&viewsource=',
                        urlencode(htmlspecialchars($name)),
                        '">',
                        htmlspecialchars($entry->getFilename()), '</a></li>';
                }
            }
            exit;
        } catch (Exception $e) {
            echo '<html><head><title>Directory not found: ',
                htmlspecialchars($dir), '</title></head>',
                '<body><h1>Directory not found: ', htmlspecialchars($dir), '</h1>',
                '<p>Try <a href="', htmlspecialchars($_SERVER['PHP_SELF']), '?introspect=/">',
                'This link</a></p></body></html>';
            exit;
        }
    }

    public static function webFrontController($initfile)
    {
        if (isset($_SERVER) && isset($_SERVER['REQUEST_URI'])) {
            $uri = parse_url($_SERVER['REQUEST_URI']);
            $archive = realpath($_SERVER['SCRIPT_FILENAME']);
            $subpath = str_replace('/' . basename($archive), '', $uri['path']);
            if (!$subpath || $subpath == '/') {
                if (isset($_GET['viewsource'])) {
                    self::viewSource($archive, $_GET['viewsource']);
                }
                if (isset($_GET['introspect'])) {
                    self::introspect($archive, $_GET['introspect']);
                }
                $subpath = '/' . $initfile;
            }
            if (!self::_fileExists($archive, substr($subpath, 1))) {
                header("HTTP/1.0 404 Not Found");
                exit;
            }
            foreach (self::$deny as $pattern) {
                if (preg_match($pattern, $subpath)) {
                    header("HTTP/1.0 404 Not Found");
                    exit;
                }
            }
            $inf = pathinfo(basename($subpath));
            if (!isset($inf['extension'])) {
                header('Content-Type: text/plain');
                header('Content-Length: ' .
                    self::_filesize($archive, substr($subpath, 1)));
                readfile('phar://@ALIAS@' . $subpath);
                exit;
            }
            if (isset(self::$defaultphp[$inf['extension']])) {
                include 'phar://@ALIAS@' . $subpath;
                exit;
            }
            if (isset(self::$defaultmimes[$inf['extension']])) {
                header('Content-Type: ' . self::$defaultmimes[$inf['extension']]);
                header('Content-Length: ' .
                    self::_filesize($archive, substr($subpath, 1)));
                readfile('phar://@ALIAS@' . $subpath);
                exit;
            }
            if (isset(self::$defaultphps[$inf['extension']])) {
                header('Content-Type: text/html');
                $c = highlight_file('phar://@ALIAS@' . $subpath, true);
                header('Content-Length: ' . strlen($c));
                echo $c;
                exit;
            }
            header('Content-Type: text/plain');
            header('Content-Length: ' .
                    self::_filesize($archive, substr($subpath, 1)));
            readfile('phar://@ALIAS@' . $subpath);
            exit;
        }
    }

    /**
     * Detect end of stub
     *
     * @param string $buffer stub past '__HALT_'.'COMPILER();'
     * @return end of stub, prior to length of manifest.
     */
    private static final function _endOfStubLength($buffer)
    {
        $pos = 0;
        if (($buffer[0] == ' ' || $buffer[0] == "\n") && substr($buffer, 1, 2) == '?>')
        {
            $pos += 3;
            if ($buffer[$pos] == "\r" && $buffer[$pos+1] == "\n") {
                $pos += 2;
            }
            else if ($buffer[$pos] == "\n") {
                $pos += 1;
            }
        }
        return $pos;
    }

    /**
     * Allows loading an external Phar archive without include()ing it
     *
     * @param string $file  phar package to load
     * @param string $alias alias to use
     * @throws Exception
     */
    public static final function loadPhar($file, $alias = NULL)
    {
        $file = realpath($file);
        if ($file) {
            $fp = fopen($file, 'rb');
            $buffer = '';
            while (!$found && !feof($fp)) {
                $buffer .= fread($fp, 8192);
                // don't break phars
                if ($pos = strpos($buffer, '__HALT_COMPI' . 'LER();')) {
                    $buffer .= fread($fp, 5);
                    fclose($fp);
                    $pos += 18;
                    $pos += self::_endOfStubLength(substr($buffer, $pos));
                    return self::_mapPhar($file, $pos, $alias);
                }
            }
            fclose($fp);
        }
    }

    /**
     * Map a full real file path to an alias used to refer to the .phar
     *
     * This function can only be called from the initialization of the .phar itself.
     * Any attempt to call from outside the .phar or to re-alias the .phar will fail
     * as a security measure.
     * @param string $alias
     * @param int $dataoffset the value of __COMPILER_HALT_OFFSET__
     */
    public static final function mapPhar($alias = NULL, $dataoffset = NULL)
    {
        try {
            $file = __FILE__;
            // this ensures that this is safe
            if (!in_array($file, get_included_files())) {
                die('SECURITY ERROR: PHP_Archive::mapPhar can only be called from within ' .
                    'the phar that initiates it');
            }
            if (!isset($dataoffset)) {
                $dataoffset = constant('__COMPILER_HALT_OFFSET'.'__');
            }
            $file = realpath($file);

            $fp = fopen($file, 'rb');
            fseek($fp, $dataoffset, SEEK_SET);
            $pos = $dataoffset + self::_endOfStubLength(fread($fp, 5));
            fclose($fp);
            self::_mapPhar($file, $pos);
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * Sub-function, allows recovery from errors
     *
     * @param unknown_type $file
     * @param unknown_type $dataoffset
     */
    private static function _mapPhar($file, $dataoffset, $alias = NULL)
    {
        $file = realpath($file);
        if (isset(self::$_manifest[$file])) {
            return;
        }
        if (!is_array(self::$_pharMapping)) {
            self::$_pharMapping = array();
        }
        $fp = fopen($file, 'rb');
        // seek to __HALT_COMPILER_OFFSET__
        fseek($fp, $dataoffset);
        $manifest_length = unpack('Vlen', fread($fp, 4));
        $manifest = '';
        $last = '1';
        while (strlen($last) && strlen($manifest) < $manifest_length['len']) {
            $read = 8192;
            if ($manifest_length['len'] - strlen($manifest) < 8192) {
                $read = $manifest_length['len'] - strlen($manifest);
            }
            $last = fread($fp, $read);
            $manifest .= $last;
        }
        if (strlen($manifest) < $manifest_length['len']) {
            throw new Exception('ERROR: manifest length read was "' . 
                strlen($manifest) .'" should be "' .
                $manifest_length['len'] . '"');
        }
        $info = self::_unserializeManifest($manifest);
        if ($info['alias']) {
            $alias = $info['alias'];
            $explicit = true;
        } else {
            if (!isset($alias)) {
                $alias = $file;
            }
            $explicit = false;
        }
        self::$_manifest[$file] = $info['manifest'];
        $compressed = $info['compressed'];
        self::$_fileStart[$file] = ftell($fp);
        fclose($fp);
        if ($compressed & 0x00001000) {
            if (!function_exists('gzinflate')) {
                throw new Exception('Error: zlib extension is not enabled - gzinflate() function needed' .
                    ' for compressed .phars');
            }
        }
        if ($compressed & 0x00002000) {
            if (!function_exists('bzdecompress')) {
                throw new Exception('Error: bzip2 extension is not enabled - bzdecompress() function needed' .
                    ' for compressed .phars');
            }
        }
        if (isset(self::$_pharMapping[$alias])) {
            throw new Exception('ERROR: PHP_Archive::mapPhar has already been called for alias "' .
                $alias . '" cannot re-alias to "' . $file . '"');
        }
        self::$_pharMapping[$alias] = array($file, $compressed, $dataoffset, $explicit,
            $info['metadata']);
        self::$_pharFiles[$file] = $alias;
    }

    /**
     * extract the manifest into an internal array
     *
     * @param string $manifest
     * @return false|array
     */
    private static function _unserializeManifest($manifest)
    {
        // retrieve the number of files in the manifest
        $info = unpack('V', substr($manifest, 0, 4));
        $apiver = substr($manifest, 4, 2);
        $apiver = bin2hex($apiver);
        $apiver_dots = hexdec($apiver[0]) . '.' . hexdec($apiver[1]) . '.' . hexdec($apiver[2]);
        $majorcompat = hexdec($apiver[0]);
        $calcapi = explode('.', self::APIVersion());
        if ($calcapi[0] != $majorcompat) {
            throw new Exception('Phar is incompatible API version ' . $apiver_dots . ', but ' .
                'PHP_Archive is API version '.self::APIVersion());
        }
        if ($calcapi[0] === '0') {
            if (self::APIVersion() != $apiver_dots) {
                throw new Exception('Phar is API version ' . $apiver_dots .
                    ', but PHP_Archive is API version '.self::APIVersion(), E_USER_ERROR);
            }
        }
        $flags = unpack('V', substr($manifest, 6, 4));
        $ret = array('compressed' => $flags & 0x00003000);
        // signature is not verified by default in PHP_Archive, phar is better
        $ret['hassignature'] = $flags & 0x00010000;
        $aliaslen = unpack('V', substr($manifest, 10, 4));
        if ($aliaslen) {
            $ret['alias'] = substr($manifest, 14, $aliaslen[1]);
        } else {
            $ret['alias'] = false;
        }
        $manifest = substr($manifest, 14 + $aliaslen[1]);
        $metadatalen = unpack('V', substr($manifest, 0, 4));
        if ($metadatalen[1]) {
            $ret['metadata'] = unserialize(substr($manifest, 4, $metadatalen[1]));
            $manifest = substr($manifest, 4 + $metadatalen[1]);
        } else {
            $ret['metadata'] = null;
            $manifest = substr($manifest, 4);
        }
        $offset = 0;
        $start = 0;
        for ($i = 0; $i < $info[1]; $i++) {
            // length of the file name
            $len = unpack('V', substr($manifest, $start, 4));
            $start += 4;
            // file name
            $savepath = substr($manifest, $start, $len[1]);
            $start += $len[1];
            // retrieve manifest data:
            // 0 = uncompressed file size
            // 1 = timestamp of when file was added to phar
            // 2 = compressed filesize
            // 3 = crc32
            // 4 = flags
            // 5 = metadata length
            $ret['manifest'][$savepath] = array_values(unpack('Va/Vb/Vc/Vd/Ve/Vf', substr($manifest, $start, 24)));
            $ret['manifest'][$savepath][3] = sprintf('%u', $ret['manifest'][$savepath][3]);
            if ($ret['manifest'][$savepath][5]) {
                $ret['manifest'][$savepath][6] = unserialize(substr($manifest, $start + 24,
                    $ret['manifest'][$savepath][5]));
            } else {
                $ret['manifest'][$savepath][6] = null;
            }
            $ret['manifest'][$savepath][7] = $offset;
            $offset += $ret['manifest'][$savepath][2];
            $start += 24 + $ret['manifest'][$savepath][5];
        }
        return $ret;
    }

    /**
     * @param string
     */
    private static function processFile($path)
    {
        if ($path == '.') {
            return '';
        }
        $std = str_replace("\\", "/", $path);
        while ($std != ($std = ereg_replace("[^\/:?]+/\.\./", "", $std))) ;
        $std = str_replace("/./", "", $std);
        if (strlen($std) > 1 && $std[0] == '/') {
            $std = substr($std, 1);
        }
        if (strncmp($std, "./", 2) == 0) {
            return substr($std, 2);
        } else {
            return $std;
        }
    }

    /**
     * Seek in the master archive to a matching file or directory
     * @param string
     */
    protected function selectFile($path, $allowdirs = true)
    {
        $std = self::processFile($path);
        if (isset(self::$_manifest[$this->_archiveName][$path])) {
            $this->_setCurrentFile($path);
            return true;
        }
        if (!$allowdirs) {
            return 'Error: "' . $path . '" is not a file in phar "' . $this->_basename . '"';
        }
        foreach (self::$_manifest[$this->_archiveName] as $file => $info) {
            if (empty($std) ||
                  //$std is a directory
                  strncmp($std.'/', $path, strlen($std)+1) == 0) {
                $this->currentFilename = $this->internalFileLength = $this->currentStat = null;
                return true;
            }
        }
        return 'Error: "' . $path . '" not found in phar "' . $this->_basename . '"';
    }

    private function _setCurrentFile($path)
    {
        $this->currentStat = array(
            2 => 0100444, // file mode, readable by all, writeable by none
            4 => 0, // uid
            5 => 0, // gid
            7 => self::$_manifest[$this->_archiveName][$path][0], // size
            9 => self::$_manifest[$this->_archiveName][$path][1], // creation time
            );
        $this->currentFilename = $path;
        $this->internalFileLength = self::$_manifest[$this->_archiveName][$path][2];
        // seek to offset of file header within the .phar
        if (is_resource(@$this->fp)) {
            fseek($this->fp, self::$_fileStart[$this->_archiveName] + self::$_manifest[$this->_archiveName][$path][7]);
        }
    }

    private static function _fileExists($archive, $path)
    {
        return isset(self::$_manifest[$archive]) &&
            isset(self::$_manifest[$archive][$path]);
    }

    private static function _filesize($archive, $path)
    {
        return self::$_manifest[$archive][$path][0];
    }

    /**
     * Seek to a file within the master archive, and extract its contents
     * @param string
     * @return array|string an array containing an error message string is returned
     *                      upon error, otherwise the file contents are returned
     */
    public function extractFile($path)
    {
        $this->fp = @fopen($this->_archiveName, "rb");
        if (!$this->fp) {
            return array('Error: cannot open phar "' . $this->_archiveName . '"');
        }
        if (($e = $this->selectFile($path, false)) === true) {
            $data = '';
            $count = $this->internalFileLength;
            while ($count) {
                if ($count < 8192) {
                    $data .= @fread($this->fp, $count);
                    $count = 0;
                } else {
                    $count -= 8192;
                    $data .= @fread($this->fp, 8192);
                }
            }
            @fclose($this->fp);
            if (self::$_manifest[$this->_archiveName][$path][4] & self::GZ) {
                $data = gzinflate($data);
            } elseif (self::$_manifest[$this->_archiveName][$path][4] & self::BZ2) {
                $data = bzdecompress($data);
            }
            if (!isset(self::$_manifest[$this->_archiveName][$path]['ok'])) {
                if (strlen($data) != $this->currentStat[7]) {
                    return array("Not valid internal .phar file (size error {$size} != " .
                        $this->currentStat[7] . ")");
                }
                if (self::$_manifest[$this->_archiveName][$path][3] != sprintf("%u", crc32($data))) {
                    return array("Not valid internal .phar file (checksum error)");
                }
                self::$_manifest[$this->_archiveName][$path]['ok'] = true;
            }
            return $data;
        } else {
            @fclose($this->fp);
            return array($e);
        }
    }

    /**
     * Parse urls like phar:///fullpath/to/my.phar/file.txt
     *
     * @param string $file
     * @return false|array
     */
    static protected function parseUrl($file)
    {
        if (substr($file, 0, 7) != 'phar://') {
            return false;
        }
        $file = substr($file, 7);
    
        $ret = array('scheme' => 'phar');
        $pos_p = strpos($file, '.phar.php');
        $pos_z = strpos($file, '.phar.gz');
        $pos_b = strpos($file, '.phar.bz2');
        if ($pos_p) {
            if ($pos_z) {
                return false;
            }
            $ret['host'] = substr($file, 0, $pos_p + strlen('.phar.php'));
            $ret['path'] = substr($file, strlen($ret['host']));
        } elseif ($pos_z) {
            $ret['host'] = substr($file, 0, $pos_z + strlen('.phar.gz'));
            $ret['path'] = substr($file, strlen($ret['host']));
        } elseif ($pos_b) {
            $ret['host'] = substr($file, 0, $pos_z + strlen('.phar.bz2'));
            $ret['path'] = substr($file, strlen($ret['host']));
        } elseif (($pos_p = strpos($file, ".phar")) !== false) {
            $ret['host'] = substr($file, 0, $pos_p + strlen('.phar'));
            $ret['path'] = substr($file, strlen($ret['host']));
        } else {
            return false;
        }
        if (!$ret['path']) {
            $ret['path'] = '/';
        }
        return $ret;
    }
    
    /**
     * Locate the .phar archive in the include_path and detect the file to open within
     * the archive.
     *
     * Possible parameters are phar://pharname.phar/filename_within_phar.ext
     * @param string a file within the archive
     * @return string the filename within the .phar to retrieve
     */
    public function initializeStream($file)
    {
        $file = self::processFile($file);
        $info = @parse_url($file);
        if (!$info) {
            $info = self::parseUrl($file);
        }
        if (!$info) {
            return false;
        }
        if (!isset($info['host'])) {
            // malformed internal file
            return false;
        }
        if (!isset(self::$_pharFiles[$info['host']]) &&
              !isset(self::$_pharMapping[$info['host']])) {
            try {
                self::loadPhar($info['host']);
                // use alias from here out
                $info['host'] = self::$_pharFiles[$info['host']];
            } catch (Exception $e) {
                return false;
            }
        }
        if (!isset($info['path'])) {
            return false;
        } elseif (strlen($info['path']) > 1) {
            $info['path'] = substr($info['path'], 1);
        }
        if (isset(self::$_pharMapping[$info['host']])) {
            $this->_basename = $info['host'];
            $this->_archiveName = self::$_pharMapping[$info['host']][0];
            $this->_compressed = self::$_pharMapping[$info['host']][1];
        } elseif (isset(self::$_pharFiles[$info['host']])) {
            $this->_archiveName = $info['host'];
            $this->_basename = self::$_pharFiles[$info['host']];
            $this->_compressed = self::$_pharMapping[$this->_basename][1];
        }
        $file = $info['path'];
        return $file;
    }

    /**
     * Open the requested file - PHP streams API
     *
     * @param string $file String provided by the Stream wrapper
     * @access private
     */
    public function stream_open($file)
    {
        return $this->_streamOpen($file);
    }

    /**
     * @param string filename to opne, or directory name
     * @param bool if true, a directory will be matched, otherwise only files
     *             will be matched
     * @uses trigger_error()
     * @return bool success of opening
     * @access private
     */
    private function _streamOpen($file, $searchForDir = false)
    {
        $path = $this->initializeStream($file);
        if (!$path) {
            trigger_error('Error: Unknown phar in "' . $file . '"', E_USER_ERROR);
        }
        if (is_array($this->file = $this->extractFile($path))) {
            trigger_error($this->file[0], E_USER_ERROR);
            return false;
        }
        if ($path != $this->currentFilename) {
            if (!$searchForDir) {
                trigger_error("Cannot open '$file', is a directory", E_USER_ERROR);
                return false;
            } else {
                $this->file = '';
                return true;
            }
        }

        if (!is_null($this->file) && $this->file !== false) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * Read the data - PHP streams API
     *
     * @param int
     * @access private
     */
    public function stream_read($count)
    {
        $ret = substr($this->file, $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }
    
    /**
     * Whether we've hit the end of the file - PHP streams API
     * @access private
     */
    function stream_eof()
    {
        return $this->position >= $this->currentStat[7];
    }
    
    /**
     * For seeking the stream - PHP streams API
     * @param int
     * @param SEEK_SET|SEEK_CUR|SEEK_END
     * @access private
     */
    public function stream_seek($pos, $whence)
    {
        switch ($whence) {
            case SEEK_SET:
                if ($pos < 0) {
                    return false;
                }
                $this->position = $pos;
                break;
            case SEEK_CUR:
                if ($pos + $this->currentStat[7] < 0) {
                    return false;
                }
                $this->position += $pos;
                break;
            case SEEK_END:
                if ($pos + $this->currentStat[7] < 0) {
                    return false;
                }
                $this->position = $pos + $this->currentStat[7];
            default:
                return false;
        }
        return true;
    }
    
    /**
     * The current position in the stream - PHP streams API
     * @access private
     */
    public function stream_tell()
    {
        return $this->position;
    }

    /**
     * The result of an fstat call, returns mod time from creation, and file size -
     * PHP streams API
     * @uses _stream_stat()
     * @access private
     */
    public function stream_stat()
    {
        return $this->_stream_stat();
    }

    /**
     * Retrieve statistics on a file or directory within the .phar
     * @param string file/directory to stat
     * @access private
     */
    public function _stream_stat($file = null)
    {
        $std = $file ? self::processFile($file) : $this->currentFilename;
        if ($file) {
            if (isset(self::$_manifest[$this->_archiveName][$file])) {
                $this->_setCurrentFile($file);
                $isdir = false;
            } else {
                do {
                    $isdir = false;
                    if ($file == '/') {
                        break;
                    }
                    foreach (self::$_manifest[$this->_archiveName] as $path => $info) {
                        if (strpos($path, $file) === 0) {
                            if (strlen($path) > strlen($file) &&
                                  $path[strlen($file)] == '/') {
                                break 2;
                            }
                        }
                    }
                    // no files exist and no directories match this string
                    return false;
                } while (false);
                $isdir = true;
            }
        } else {
            $isdir = false; // open streams must be files
        }
        $mode = $isdir ? 0040444 : 0100444;
        // 040000 = dir, 010000 = file
        // everything is readable, nothing is writeable
        return array(
           0, 0, $mode, 0, 0, 0, 0, 0, 0, 0, 0, 0, // non-associative indices
           'dev' => 0, 'ino' => 0,
           'mode' => $mode,
           'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'blksize' => 0, 'blocks' => 0,
           'size' => $this->currentStat[7],
           'atime' => $this->currentStat[9],
           'mtime' => $this->currentStat[9],
           'ctime' => $this->currentStat[9],
           );
    }

    /**
     * Stat a closed file or directory - PHP streams API
     * @param string
     * @param int
     * @access private
     */
    public function url_stat($url, $flags)
    {
        $path = $this->initializeStream($url);
        return $this->_stream_stat($path);
    }

    /**
     * Open a directory in the .phar for reading - PHP streams API
     * @param string directory name
     * @access private
     */
    public function dir_opendir($path)
    {
        $info = @parse_url($path);
        if (!$info) {
            $info = self::parseUrl($path);
            if (!$info) {
                trigger_error('Error: "' . $path . '" is a file, and cannot be opened with opendir',
                    E_USER_ERROR);
                return false;
            }
        }
        $path = !empty($info['path']) ?
            $info['host'] . $info['path'] : $info['host'] . '/';
        $path = $this->initializeStream('phar://' . $path);
        if (isset(self::$_manifest[$this->_archiveName][$path])) {
            trigger_error('Error: "' . $path . '" is a file, and cannot be opened with opendir',
                E_USER_ERROR);
            return false;
        }
        if ($path == false) {
            trigger_error('Error: Unknown phar in "' . $file . '"', E_USER_ERROR);
            return false;
        }
        $this->fp = @fopen($this->_archiveName, "rb");
        if (!$this->fp) {
            trigger_error('Error: cannot open phar "' . $this->_archiveName . '"');
            return false;
        }
        $this->_dirFiles = array();
        foreach (self::$_manifest[$this->_archiveName] as $file => $info) {
            if ($path == '/') {
                if (strpos($file, '/')) {
                    $a = explode('/', $file);
                    $this->_dirFiles[array_shift($a)] = true;
                } else {
                    $this->_dirFiles[$file] = true;
                }
            } elseif (strpos($file, $path) === 0) {
                $fname = substr($file, strlen($path) + 1);
                if (strpos($fname, '/')) {
                    // this is a directory
                    $a = explode('/', $fname);
                    $this->_dirFiles[array_shift($a)] = true;
                } elseif ($file[strlen($path)] == '/') {
                    // this is a file
                    $this->_dirFiles[$fname] = true;
                }
            }
        }
        @fclose($this->fp);
        if (!count($this->_dirFiles)) {
            return false;
        }
        @uksort($this->_dirFiles, 'strnatcmp');
        return true;
    }

    /**
     * Read the next directory entry - PHP streams API
     * @access private
     */
    public function dir_readdir()
    {
        $ret = key($this->_dirFiles);
        @next($this->_dirFiles);
        if (!$ret) {
            return false;
        }
        return $ret;
    }

    /**
     * Close a directory handle opened with opendir() - PHP streams API
     * @access private
     */
    public function dir_closedir()
    {
        $this->_dirFiles = array();
        reset($this->_dirFiles);
        return true;
    }

    /**
     * Rewind to the first directory entry - PHP streams API
     * @access private
     */
    public function dir_rewinddir()
    {
        reset($this->_dirFiles);
        return true;
    }

    /**
     * API version of this class
     * @return string
     */
    public final function APIVersion()
    {
        return '1.1.0';
    }

    /**
     * Retrieve Phar-specific metadata for a Phar archive
     *
     * @param string $phar full path to Phar archive, or alias
     * @return null|mixed The value that was serialized for the Phar
     *                    archive's metadata
     * @throws Exception
     */
    public static function getPharMetadata($phar)
    {
        if (isset(self::$_pharFiles[$phar])) {
            $phar = self::$_pharFiles[$phar];
        }
        if (!isset(self::$_pharMapping[$phar])) {
            throw new Exception('Unknown Phar archive: "' . $phar . '"');
        }
        return self::$_pharMapping[$phar][4];
    }

    /**
     * Retrieve File-specific metadata for a Phar archive file
     *
     * @param string $phar full path to Phar archive, or alias
     * @param string $file relative path to file within Phar archive
     * @return null|mixed The value that was serialized for the Phar
     *                    archive's metadata
     * @throws Exception
     */
    public static function getFileMetadata($phar, $file)
    {
        if (!isset(self::$_pharFiles[$phar])) {
            if (!isset(self::$_pharMapping[$phar])) {
                throw new Exception('Unknown Phar archive: "' . $phar . '"');
            }
            $phar = self::$_pharMapping[$phar][0];
        }
        if (!isset(self::$_manifest[$phar])) {
            throw new Exception('Unknown Phar: "' . $phar . '"');
        }
        $file = self::processFile($file);
        if (!isset(self::$_manifest[$phar][$file])) {
            throw new Exception('Unknown file "' . $file . '" within Phar "'. $phar . '"');
        }
        return self::$_manifest[$phar][$file][6];
    }

    /**
     * @return list of supported signature algorithmns.
     */
    public static function getsupportedsignatures()
    {
        $ret = array('MD5', 'SHA-1');
        if (extension_loaded('hash')) {
            $ret[] = 'SHA-256';
            $ret[] = 'SHA-512';
        }
        return $ret;
    }
}
?><?php
}
if (!in_array('phar', stream_get_wrappers())) {
	stream_wrapper_register('phar', 'PHP_Archive');
}
if (!class_exists('Phar',0)) {
	include 'phar://'.__FILE__.'/phar.inc';
}
?><?php

/** @file phar.php
 * @ingroup Phar
 * @brief class CLICommand
 * @author  Marcus Boerger
 * @date    2007 - 2007
 *
 * Phar Command
 */

if (!extension_loaded('phar'))
{
	if (!class_exists('PHP_Archive', 0))
	{
	    echo "Neither Extension Phar nor class PHP_Archive are available.\n";
    	exit(1);
    }
    if (!in_array('phar', stream_get_wrappers()))
    {
	    stream_wrapper_register('phar', 'PHP_Archive');
    }
    if (!class_exists('Phar',0)) {
	    require 'phar://'.__FILE__.'/phar.inc';
    }
}

foreach(array("SPL", "Reflection") as $ext)
{
    if (!extension_loaded($ext))
    {
        echo "$argv[0] requires PHP extension $ext.\n";
        exit(1);
    }
}

function command_include($file)
{
    $file = 'phar://' . __FILE__ . '/' . $file;
    if (file_exists($file)) {
        include($file);
    }
}

function command_autoload($classname)
{
    command_include(strtolower($classname) . '.inc');
}

Phar::mapPhar();

spl_autoload_register('command_autoload');

new PharCommand($argc, $argv);

__HALT_COMPILER(); ?>
ˆ