backward up forward refresh
home
login
about

:

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
<?php
//============TAR Class v0.9.02============\\
// Author: Emdek                           \\
// URL: http://emdek.cba.pl                \\
// Licence: LGPL                           \\
// Last modified: 2008-03-01 14:38:21 CET  \\
//                                         \\
// Inspired by TAR Manager (C) Josh Barger \\
//=========================================\\

class TAR {
/// Internal variables
private $FileName;
private $Handle;
private $Files;
private $Entries;
private $Modified = 0;

/// Saving (compression) modes
// No compression
const NONE = 1;
// Gzip, if available
const GZIP = 2;
// Bzip, if available
const BZIP = 4;
// LZF, if available
const LZF = 8;

/// Internal methods
public function __destruct () {
    if ($this->Modified) $this->save ();
    }
// Computes the checksum of an entry header
private function checksum ($ByteString) {
    $CheckSum = 0;
    for ($i = 0; $i < 512; $i++) {
        if ($i == 148) {
            $i += 7;
            continue;
            }
        $CheckSum += ord ($ByteString[$i]);
        }
    return ($CheckSum + 256);
    }
// Unpad a NULL padded string
private function str_unpad ($String) {
    return (substr ($String, 0, strpos ($String, "\0")));
    }
// Prepare path to file
private function file_path ($FileName) {
    if (!file_exists ($FileName)) return (0);
    $Extension = explode ('.', $FileName);
    $Extension = strtolower (end ($Extension));
    if ($Extension == 'bz2') {
        if (!function_exists ('bzopen')) return (0);
        $FileName = 'compress.bzip2://'.$FileName;
        }
    else if (in_array ($Extension, array ('gz', 'tgz'))) {
        if (!function_exists ('gzopen')) return (0);
        $FileName = 'compress.zlib://'.$FileName;
        }
    return ($FileName);
    }
// Parses TAR file
private function parse ($FileName, $Store = 0, $Validate = 0, $OverWrite = 0) {
    if (!$FileName = $this->file_path ($FileName)) return (0);
    $TAR = fopen ($FileName, 'rb');
    while (!feof ($TAR)) {
        $Header = fread ($TAR, 512);
        if (!$Header) {
            if ($Validate) return (substr_count ($Header, "\0") == 512);
            break;
            }
        $FileName = $this->str_unpad (substr ($Header, 0, 100));
        if (isset ($this->Entries[$FileName]) && !$OverWrite && !$Validate) continue;
        $TmpArray = array (
            'mode' => substr ($Header, 100, 8),
            'uid' => octdec (substr ($Header, 108, 8)),
            'gid' => octdec (substr ($Header, 116, 8)),
            'size' => octdec (substr ($Header, 124, 12)),
            'mtime' => octdec (substr ($Header, 136, 12)),
            'chksum' => octdec (substr ($Header, 148, 6)),
            'type' => substr ($Header, 156, 1),
            'linkname' => $this->str_unpad (substr ($Header, 157, 100)),
            'uname' => $this->str_unpad (substr ($Header, 265, 32)),
            'gname' => $this->str_unpad (substr ($Header, 297, 32)),
            );
        if ($this->checksum ($Header) == $TmpArray['chksum']) {
            if ($Validate) continue;
            $this->Entries[$FileName] = $TmpArray;
            $this->Entries[$FileName]['position'] = ftell ($TAR);
            }
        else if ($Validate) return (0);
        $BlockSize = (ceil ($TmpArray['size'] / 512) * 512);
        if ($BlockSize) {
            if ($Store) {
                $this->Files[$FileName] = '';
                $Blocks = floor ($TmpArray['size'] / 8192);
                for ($i = 0; $i < $Blocks; $i++) $this->Files[$FileName].= fread ($TAR, 8192);
                if ($TmpArray['size'] % 8192) $this->Files[$FileName].= fread ($TAR, ceil ($TmpArray['size'] % 8192));
                if ($BlockSize - $TmpArray['size']) fseek ($TAR, ($BlockSize - $TmpArray['size']), SEEK_CUR);
                }
            else fseek ($TAR, $BlockSize, SEEK_CUR);
            }
        }
    fclose ($TAR);
    return (!$Validate);
    }
// Generates a TAR entry
private function entry_generate ($Name, $Array) {
    $Keys = array ('mode', 'uid', 'gid', 'size', 'mtime');
    $String = str_pad ($Name, 100, "\0");
    for ($i = 0; $i < 5; $i++) $String.= str_pad (decoct ($Array[$Keys[$i]]), (($i < 3)?7:11), '0', STR_PAD_LEFT)."\0";
    $String.= '      '."\0".chr (32).$Array['type'].str_pad ($Array['linkname'], 100, "\0").'ustar'.chr (32).chr (32)."\0";
    $String.= str_pad ($Array['uname'], 32, "\0").str_pad ($Array['gname'], 32, "\0").str_repeat ("\0", 183);
    $String = substr ($String, 0, 148).str_pad (decoct ($this->checksum ($String)), 6, '0', STR_PAD_LEFT).substr ($String, 154);
    if (!$Array['type'] || $Array['type'] == 1) {
        if (!isset ($this->Files[$Name]) && !($File = implode ('', $this->entry_get ($Name))) && $Array['size']) return ('');
        $String.= str_pad ((isset ($this->Files[$Name])?$this->Files[$Name]:$File), (ceil ($Array['size'] / 512) * 512), "\0");
        }
    return ($String);
    }
/// Public methods
// Information about class version...
public function version () {
    return ('TAR class v0.9.02 (2008-03-01)');
    }
// Opens a TAR file
public function open ($FileName) {
    $this->FileName = $FileName;
    if (!is_file ($FileName)) {
        touch ($FileName);
        return (is_file ($FileName));
        }
    $OpenName = $this->file_path ($FileName);
    if ($OpenName != $this->FileName) {
        if (!$this->Handle = tmpfile ()) return (0);
        fwrite ($this->Handle, file_get_contents ($OpenName));
        }
    else $this->Handle = fopen ($FileName, 'rb');
    return ($this->parse ($FileName));
    }
// Returns array of entries (optional from specified path)
public function entries ($Path = NULL) {
    if ($Path === NULL) return ($this->Entries);
    if (!isset ($this->Entries[$Path]) && $Path) return (0);
    $Array = array ();
    $Length = strlen ($Path);
    foreach ($this->Entries as $Key => $Value) {
        if ($Path) {
            $Sub = substr ($Key, 0, $Length);
            if ($Sub != $Path || $Path == $Key) continue;
            $Sub = substr ($Key, $Length);
            }
        else $Sub = &$Key;
        $Tmp = substr_count ($Sub, '/');
        if ($Tmp > 1 || ($Tmp == 1 && substr ($Sub, -1) != '/')) continue;
        $Array[$Key] = &$Value;
        }
    return ($Array);
    }
// Appends a TAR file to the archive
public function append ($FileName, $OverWrite = 0) {
    $this->Modified = 1;
    return ($this->parse ($FileName, 1, 0, $OverWrite));
    }
// Check if entry exists
public function entry_exists ($Entry) {
    return (isset ($this->Entries[$Entry]));
    }
// Information about specified entry
public function entry_information ($Entry) {
    if (!isset ($this->Entries[$Entry])) return (0);
    return ($this->Entries[$Entry]);
    }
// Delete an entry from the archive
public function entry_delete ($Entry = '') {
    if (!$Entry) {
        unset ($this->Entries);
        return (1);
        }
    if (!isset ($this->Entries[$Entry])) return (0);
    if ($this->Entries[$Entry]['type'] == 5) {
        $Entries = array_keys ($this->Entries);
        $Length = strlen ($Entry);
        for ($i = 0, $c = count ($Entries); $i < $c; $i++) {
            if (substr ($Entries[$i], $Length) == $Entry) unset ($this->Entries[$Entries[$i]]);
            }
        }
    unset ($this->Entries[$Entry]);
    $this->Modified = 1;
    return (1);
    }
// Add an entry to the archive
public function entry_add ($FileName, $LocalName = '', $OverWrite = 0) {
    if (!file_exists ($FileName)) return (0);
    $Stat = stat ($FileName);
    if (($Stat['mode'] & 0xC000) == 0xC000) $Type = 8;
    else if (($Stat['mode'] & 0xA000) == 0xA000) $Type = 2;
    else if (($Stat['mode'] & 0x8000) == 0x8000) $Type = 0;
    else if (($Stat['mode'] & 0x6000) == 0x6000) $Type = 4;
    else if (($Stat['mode'] & 0x4000) == 0x4000) $Type = 5;
    else if (($Stat['mode'] & 0x2000) == 0x2000) $Type = 3;
    else if (($Stat['mode'] & 0x1000) == 0x1000) $Type = 6;
    else $Type = 9;
    if (($Type == 5) && substr ($FileName, -1) != '/') $FileName.= '/';
    $Name = $LocalName.((substr ($LocalName, -1) == '/' && $Type == 5)?'':basename ($FileName).(($Type == 5)?'/':''));
    if (isset ($this->Entries[$Name]) && !$OverWrite) return (0);
    if (function_exists ('posix_getgrgid')) {
        $Group = posix_getgrgid ($Stat['gid']);
        $Owner = posix_getpwuid ($Stat['uid']);
        }
    else $Owner['name'] = $Group['name'] = '';
    $this->Entries[$Name] = array (
        'chksum' => '',
        'gname' => $Group['name'],
        'gid' => $Stat['gid'],
        'linkname' => (($Type == 2)?readlink (($Type == 5)?substr ($FileName, 0, -1):$FileName):''),
        'mode' => $Stat['mode'],
        'mtime' => $Stat['mtime'],
        'size' => $Stat['size'],
        'type' => $Type,
        'uid' => $Stat['uid'],
        'uname' => $Owner['name'],
        );
    if ($Type == 5) {
        $Files = glob ($FileName.'*');
        for ($i = 0, $c = count ($Files); $i < $c; $i++) $this->entry_add ($Files[$i], $LocalName.(is_dir ($Files[$i])?basename ($Files[$i]).'/':''));
        }
    else $this->Files[$Name] = file_get_contents ($FileName);
    $this->Modified = 1;
    return (1);
    }
// Add an entry to the archive from string
public function entry_add_from_string ($LocalName, $Contents = '', $OverWrite = 1, $Dir = 0) {
    if (strstr ($LocalName, '/') && substr_count ($LocalName, '/') > 1) $this->entry_add_from_string (substr ($LocalName, 0, (strrpos (substr ($LocalName, 0, -1), '/') + 1)), '', 0, 1);
    if (isset ($this->Entries[$LocalName]) && !$OverWrite) return (0);
    $this->Entries[$LocalName] = array (
        'chksum' => '',
        'gname' => '',
        'gid' => 0,
        'linkname' => '',
        'mode' => ($Dir?0000775:0000644),
        'mtime' => time (),
        'size' => ($Dir?0:strlen ($Contents)),
        'type' => ($Dir?5:0),
        'uid' => 0,
        'uname' => '',
        );
    if (!$Dir) $this->Files[$LocalName] = $Contents;
    $this->Modified = 1;
    return (1);
    }
// Update an entry in the archive
public function entry_update ($LocalName, $Contents = NULL, $Array = NULL) {
    if (!isset ($this->Entries[$LocalName])) return (0);
    if ($Contents !== NULL) {
        $this->Files[$LocalName] = $Contents;
        $this->Entries[$LocalName]['size'] = strlen ($Contents);
        }
    if ($Array !== NULL) {
        $Keys = array ('gname', 'gid', 'linkname', 'mode', 'mtime', 'uid', 'uname');
        for ($i = 0; $i < 7; ++$i) {
            if (isset ($Array[$Keys[$i]])) $this->Entries[$LocalName][$Keys[$i]] = $Array[$Keys[$i]];
            }
        }
    $this->Modified = 1;
    return (1);
    }
// Rename an entry in the archive
public function entry_rename ($OldName, $NewName) {
    if (!isset ($this->Entries[$OldName])) return (0);
    $Length = strlen ($OldName);
    foreach ($this->Entries as $Key => $Value) {
        if (substr ($Key, 0, $Length) == $OldName) {
            $Path = $NewName.substr ($Key, $Length);
            $this->Entries[$Path] = &$this->Entries[$Key];
            unset ($this->Entries[$Key]);
            if (isset ($this->Files[$Key])) {
                $this->Files[$Path] = &$this->Files[$Key];
                unset ($this->Files[$Key]);
                }
            }
        }
    return (1);
    }
// Returns contents of entries from specified path
public function entry_get ($Path) {
    if ((!isset ($this->Entries[$Path]) && $Path) || !$this->Entries) return (0);
    $Length = strlen ($Path);
    $Files = array ();
    foreach ($this->Entries as $Key => $Value) {
        $Entry = $Key;
        if (!$Path || substr ($Key, 0, $Length) == $Path) {
            if (!$Path || substr ($Path, -1) == '/') {
                if ($Key == $Path) continue;
                $Key = substr ($Key, $Length);
                }
            else $Key = basename ($Path);
            if (isset ($this->Files[$Entry])) $Files[$Key] = $this->Files[$Entry];
            else $Files[$Key] = stream_get_contents ($this->Handle, $this->Entries[$Entry]['size'], $this->Entries[$Entry]['position']);
            }
        }
    return ($Files);
    }
// Extracts specified entries to specified destination
public function extract ($Destination = '', $Entry = '') {
    if (!$Entries = $this->entry_get ($Entry)) return (0);
    ksort ($Entries);
    if (!$Entry || !$this->Entries[$Entry]['type']) {
        $DirName = dirname ($Entry);
        $Entry = $DirName.($DirName?'/':'');
        }
    foreach ($Entries as $Key => $Value) {
        if (!isset ($this->Entries[$Entry.$Key]) || file_exists ($Destination.$Key)) continue;
        if ($this->Entries[$Entry.$Key]['type']) {
            if (!mkdir ($Destination.$Key, 0777)) return (0);
            chmod ($Destination.$Key, 0777);
            }
        else {
            if (!file_put_contents ($Destination.$Key, $Value) && $this->Entries[$Entry.$Key]['size']) return (0);
            }
        }
    return (1);
    }
// Saves archive (current or new) with optional compression
public function save ($FileName = '', $Mode = 1) {
    $TAR = '';
    if (!$this->Entries || !$this->Modified) return (0);
    ksort ($this->Entries);
    if (!$FileName) $FileName = $this->FileName;
    foreach ($this->Entries as $Key => $Value) $TAR.= $this->entry_generate ($Key, $Value);
    $Length = strlen ($TAR);
    $TAR.= str_repeat ("\0", 512);
    if (substr ($FileName, -4) != '.tar') $FileName.= '.tar';
    switch ($Mode) {
        case self::BZIP:
        if (!function_exists ('bzcompress')) break;
        $TAR = bzcompress ($TAR);
        $FileName.= '.bz2';
        break;
        case self::GZIP:
        if (!function_exists ('gzcompress')) break;
        $TAR = gzencode ($TAR);
        $FileName.= '.gz';
        break;
        case self::LZF:
        if (!function_exists ('lzf_compress')) break;
        $TAR = lzf_compress ($TAR);
        $FileName.= '.lzf';
        break;
        }
    $this->Modified = 0;
    return (file_put_contents ($FileName, $TAR));
    }
// Clears entries variables
public function clear () {
    unset ($this->Entries, $this->Files);
    }
// Closes the archive
public function close () {
    $this->clear ();
    unset ($this->FileName);
    if ($this->Handle) fclose ($this->Handle);
    }
}
?>

Source file (PHP), size: 12.75 KB