Archive.php 12.8 KB
Newer Older
1
<?php
2
3
namespace T3o\TerFe2\Utility;

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
/*******************************************************************
 *  Copyright notice
 *
 *  (c) 2011 Kai Vogel <kai.vogel@speedprogs.de>, Speedprogs.de
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2 of
 *  the License, or (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ******************************************************************/

/**
 * Utilities to manage zip and t3x files
 */
31
class Archive
32
33
34
35
36
37
38
39
40
41
42
43
44
{

    /**
     * Create a zip archive
     *
     * @param string $filename File name of the archive
     * @param array $files All files to insert
     * @param string $overwrite Overwrite file if exists
     * @return boolean TRUE if success
     */
    public static function createZipArchive($filename, array $files, $overwrite = FALSE)
    {
        if (!class_exists('ZipArchive')) {
45
            throw new \Exception('Please make sure that php zip extension is installed');
46
47
48
        }

        // Check if file already exists
49
        if (!$overwrite && \T3o\TerFe2\Utility\File::fileExists($filename)) {
50
51
52
53
54
55
56
            return TRUE;
        }

        // Create zip archive
        $createMode = ($overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE);
        $zipArchive = new ZipArchive();
        if (empty($zipArchive) || !$zipArchive->open($filename, $createMode)) {
57
            throw new \Exception('Could not open ZIP file to write');
58
59
60
61
62
63
64
65
        }

        // Add files
        foreach ($files as $path => $content) {
            if (empty($path)) {
                continue;
            }
            if (!$zipArchive->addFromString($path, (string)$content)) {
66
                throw new \Exception('Could not write file "' . $path . '" into ZIP file');
67
68
69
70
71
            }
        }

        // Save and close
        if (!$zipArchive->close()) {
72
            throw new \Exception('Could not close ZIP file');
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        }

        return TRUE;
    }


    /**
     * Writes a zip archive to filesystem
     *
     * @param string $filename File name
     * @param string $path Path to extract into
     * @param mixed $files Single filename or array of filenames to extract
     * @return boolean TRUE if success
     */
    public static function extractZipArchive($filename, $path, $files = NULL)
    {
        if (!class_exists('ZipArchive')) {
90
            throw new \Exception('Please make sure that php zip extension is installed');
91
92
93
        }

        // Check if file exists
94
        if (!\T3o\TerFe2\Utility\File::fileExists($filename)) {
95
            throw new \Exception('File "' . $filename . '" not found to extract');
96
97
98
        }

        // Check if path is writable
99
        $path = \T3o\TerFe2\Utility\File::getAbsoluteDirectory($path);
100
        if (!is_writable($path)) {
101
            throw new \Exception('Path "' . $path . '" is not writeable');
102
103
104
105
106
        }

        // Load zip archive
        $zipArchive = new ZipArchive();
        if (empty($zipArchive) || !$zipArchive->open($filename)) {
107
            throw new \Exception('Could not open zip file to read');
108
109
110
111
        }

        // Extract
        if (!$zipArchive->extractTo($path, $files)) {
112
            throw new \Exception('Could not extract file "' . $filename . '" to path "' . $path . '"');
113
114
115
116
        }

        // Save and close
        if (!$zipArchive->close()) {
117
            throw new \Exception('Could not close ZIP file');
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        }

        return TRUE;
    }


    /**
     * Returns the content of a zip archive
     *
     * @param string $filename File name
     * @return array File informations
     */
    public static function getZipArchiveContent($filename)
    {
        if (!class_exists('ZipArchive')) {
133
            throw new \Exception('Please make sure that php zip extension is installed');
134
135
136
        }

        // Check if file exists
137
        if (!\T3o\TerFe2\Utility\File::fileExists($filename)) {
138
            throw new \Exception('File "' . $filename . '" not found to extract');
139
140
141
142
143
        }

        // Load zip archive
        $zipArchive = new ZipArchive();
        if (empty($zipArchive) || !$zipArchive->open($filename)) {
144
            throw new \Exception('Could not open zip file to read');
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
        }

        // Get all files
        $files = array();
        for ($i = 0; $i < $zipArchive->numFiles; $i++) {
            $fileInfo = $zipArchive->statIndex($i);
            $filePointer = $zipArchive->getStream($fileInfo['name']);
            if (!$filePointer) {
                continue;
            }
            $content = '';
            while (!feof($filePointer)) {
                $content .= fread($filePointer, 1024);
            }
            fclose($filePointer);
            $files[$fileInfo['name']] = (object)array(
                'name' => $fileInfo['name'],
                'size' => $fileInfo['size'],
                'modificationTime' => $fileInfo['mtime'],
                'isExecutable' => (substr($fileInfo['name'], -3) === 'php'),
                'content' => base64_encode($content),
                'contentMD5' => md5($content),
            );
        }

        return $files;
    }


    /**
     * Creates a zip file from given extension T3X file
     *
     * @throws Exception
     * @param string $t3xFile Path to the t3x file
     * @param string $zipFile Path to the zip file
     * @return boolean TRUE if success
     */
    public static function convertT3xToZip($t3xFile, $zipFile)
    {
        if (empty($t3xFile)) {
185
            throw new \Exception('No valid t3x file given to convert to zip file');
186
187
        }
        if (empty($zipFile)) {
188
            throw new \Exception('No valid zip file given to convert t3x file into');
189
190
191
        }

        // Check if file was cached
192
        if (\T3o\TerFe2\Utility\File::fileExists($zipFile)) {
193
194
195
196
197
198
199
200
201
202
203
204
205
206
            return TRUE;
        }

        // Unpack extension files
        $files = array();
        $content = self::extractT3xArchive($t3xFile);
        if (!empty($content['FILES']) && is_array($content['FILES'])) {
            foreach ($content['FILES'] as $fileInfo) {
                $files[$fileInfo['name']] = $fileInfo['content'];
            }
        }

        // Create ext_emconf.php if it doesn't exist
        if (!isset($files['ext_emconf.php']) && !empty($content['extKey']) && !empty($content['EM_CONF']) && is_array($content['EM_CONF'])) {
207
            $files['ext_emconf.php'] = \T3o\TerFe2\Utility\File::createExtEmconfFile(
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
                $content['extKey'],
                $content['EM_CONF']
            );
        }

        // Create ZIP archive
        self::createZipArchive($zipFile, $files);

        return TRUE;
    }


    /**
     * Extract files from an extension t3x file
     *
     * @param string $filename Path to t3x file
     * @return array Unpacked extension files
     */
    public static function extractT3xArchive($filename)
    {
        if (empty($filename)) {
            return array();
        }

        // Get local file name if on same server
233
234
        if (\T3o\TerFe2\Utility\File::isLocalUrl($filename)) {
            $filename = \T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($filename);
235
236
237
        }

        // Get file content
238
        $content = \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($filename);
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
        if (empty($content)) {
            return array();
        }

        return self::decompressT3xStream($content);
    }


    /**
     * Decompress t3x file content stream
     *
     * @param string $content File content
     * @return array Files array
     */
    public static function decompressT3xStream($content)
    {
        if (empty($content)) {
            return array();
        }

        // Get content parts
        list($hash, $compression, $data) = explode(':', $content, 3);
        unset($content);

        // Get extension files
        $files = gzuncompress($data);
        if (empty($files) || $hash != md5($files)) {
            return array();
        }

        // Unserialize files array
        return unserialize($files);
    }


    /**
     * Load extension information from zip file
     *
     * @param string $filename Path to zip file
     * @param array $files Reference to files
     * @return stdClass Extension information
     * @see tx_em_Extensions_Details::uploadToTER
     */
    public static function getExtensionDetailsFromZipArchive($filename, array &$files = array())
    {
        $files = self::getZipArchiveContent($filename);
        if (empty($files) || empty($files['ext_emconf.php'])) {
            return NULL;
        }
        $extEmconf = base64_decode($files['ext_emconf.php']->content);
        $extEmconf = self::extractEmConf($extEmconf);
        if (empty($extEmconf) || !is_array($extEmconf)) {
            return NULL;
        }

        // Dependencies / conflicts
        $possibleConstraints = array(
            'depends',
            'conflicts',
            'suggests'
        );
        if (is_array($extEmconf['constraints'])) {
            foreach ($extEmconf['constraints'] as $kind => $data) {
                if (in_array($kind, $possibleConstraints)) {
                    foreach ($data as $extKey => $version) {
                        if (strlen($extKey)) {
                            $dependenciesArr[] = array(
                                'kind' => $kind,
                                'extensionKey' => $extKey,
                                'versionRange' => $version
                            );
                        }
                    }
                }
            }
        }
        $clearCacheOnLoad = (isset($extEmconf['clearCacheOnLoad']) ? $extEmconf['clearCacheOnLoad'] : $extEmconf['clearcacheonload']);
        // Build extension information
        return (object)array(
            'extensionKey' => '',
            'version' => $extEmconf['version'],
            'metaData' => (object)array(
                'title' => $extEmconf['title'],
                'description' => $extEmconf['description'],
                'category' => $extEmconf['category'],
                'state' => $extEmconf['state'],
                'authorName' => $extEmconf['author'],
                'authorEmail' => $extEmconf['author_email'],
                'authorCompany' => $extEmconf['author_company'],
            ),
            'technicalData' => (object)array(
                'dependencies' => $dependenciesArr,
                'loadOrder' => $extEmconf['loadOrder'],
                'uploadFolder' => (bool)$extEmconf['uploadfolder'],
                'createDirs' => $extEmconf['createDirs'],
                'shy' => (bool)$extEmconf['shy'],
                'modules' => $extEmconf['module'],
                'modifyTables' => $extEmconf['modify_tables'],
                'priority' => $extEmconf['priority'],
                'clearCacheOnLoad' => (bool)$clearCacheOnLoad,
                'lockType' => $extEmconf['lockType'],
                'doNotLoadInFEe' => $extEmconf['doNotLoadInFE'],
                'docPath' => $extEmconf['docPath'],
            ),
            'infoData' => (object)array(
                'codeLines' => 0,
                'codeBytes' => 0,
                'codingGuidelinesCompliance' => $extEmconf['CGLcompliance'],
                'codingGuidelinesComplianceNotes' => $extEmconf['CGLcompliance_note'],
                'uploadComment' => '',
                'techInfo' => '',
            ),
        );
    }


    /**
     * Extract the ext_emconf.php data array safely
     *
     * @param $extEmConfCode
     * @return null
     */
    public static function extractEmConf($extEmConfCode)
    {
        $EM_CONF = NULL;

365
        include_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('ter_fe2') . 'Resources/Private/Php/PHP-Parser/lib/bootstrap.php');
366
367
368
369
370
371
372
373
374
375
376
        $parser = new PhpParser\Parser(new PhpParser\Lexer);

        try {
            $statements = $parser->parse($extEmConfCode);

            $traverser = new PhpParser\NodeTraverser;
            $prettyPrinter = new PhpParser\PrettyPrinter\Standard;

            // We will need to resolved names
            $traverser->addVisitor(new PhpParser\NodeVisitor\NameResolver);
            // Our own node visitor
377
            $traverser->addVisitor(\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\T3o\TerFe2\Visitor\ArrayAssurer'));
378
379
380
381
382
383
384

            $statements = $traverser->traverse($statements);
            $code = $prettyPrinter->prettyPrint($statements);

            eval($code);

            return reset($EM_CONF);
385
        } catch (\Exception $e) {
386
387
388
389
390
            return NULL;
        }
    }

}