moodle /lib/spout/src/Spout/Writer/Common/Helper/ZipHelper.php

Language PHP Lines 218
MD5 Hash 7f04d43854178880546d13aae828139f Estimated Cost $2,256 (why?)
Repository https://bitbucket.org/moodle/moodle.git View Raw File View Project SPDX
  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
<?php

namespace Box\Spout\Writer\Common\Helper;

/**
 * Class ZipHelper
 * This class provides helper functions to create zip files
 *
 * @package Box\Spout\Writer\Common\Helper
 */
class ZipHelper
{
    const ZIP_EXTENSION = '.zip';

    /** Controls what to do when trying to add an existing file */
    const EXISTING_FILES_SKIP = 'skip';
    const EXISTING_FILES_OVERWRITE = 'overwrite';

    /** @var string Path of the folder where the zip file will be created */
    protected $tmpFolderPath;

    /** @var \ZipArchive The ZipArchive instance */
    protected $zip;

    /**
     * @param string $tmpFolderPath Path of the temp folder where the zip file will be created
     */
    public function __construct($tmpFolderPath)
    {
        $this->tmpFolderPath = $tmpFolderPath;
    }

    /**
     * Returns the already created ZipArchive instance or
     * creates one if none exists.
     *
     * @return \ZipArchive
     */
    protected function createOrGetZip()
    {
        if (!isset($this->zip)) {
            $this->zip = new \ZipArchive();
            $zipFilePath = $this->getZipFilePath();

            $this->zip->open($zipFilePath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
        }

        return $this->zip;
    }

    /**
     * @return string Path where the zip file of the given folder will be created
     */
    public function getZipFilePath()
    {
        return $this->tmpFolderPath . self::ZIP_EXTENSION;
    }

    /**
     * Adds the given file, located under the given root folder to the archive.
     * The file will be compressed.
     *
     * Example of use:
     *   addFileToArchive('/tmp/xlsx/foo', 'bar/baz.xml');
     *   => will add the file located at '/tmp/xlsx/foo/bar/baz.xml' in the archive, but only as 'bar/baz.xml'
     *
     * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree.
     * @param string $localFilePath Path of the file to be added, under the root folder
     * @param string|void $existingFileMode Controls what to do when trying to add an existing file
     * @return void
     */
    public function addFileToArchive($rootFolderPath, $localFilePath, $existingFileMode = self::EXISTING_FILES_OVERWRITE)
    {
        $this->addFileToArchiveWithCompressionMethod(
            $rootFolderPath,
            $localFilePath,
            $existingFileMode,
            \ZipArchive::CM_DEFAULT
        );
    }

    /**
     * Adds the given file, located under the given root folder to the archive.
     * The file will NOT be compressed.
     *
     * Example of use:
     *   addUncompressedFileToArchive('/tmp/xlsx/foo', 'bar/baz.xml');
     *   => will add the file located at '/tmp/xlsx/foo/bar/baz.xml' in the archive, but only as 'bar/baz.xml'
     *
     * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree.
     * @param string $localFilePath Path of the file to be added, under the root folder
     * @param string|void $existingFileMode Controls what to do when trying to add an existing file
     * @return void
     */
    public function addUncompressedFileToArchive($rootFolderPath, $localFilePath, $existingFileMode = self::EXISTING_FILES_OVERWRITE)
    {
        $this->addFileToArchiveWithCompressionMethod(
            $rootFolderPath,
            $localFilePath,
            $existingFileMode,
            \ZipArchive::CM_STORE
        );
    }

    /**
     * Adds the given file, located under the given root folder to the archive.
     * The file will NOT be compressed.
     *
     * Example of use:
     *   addUncompressedFileToArchive('/tmp/xlsx/foo', 'bar/baz.xml');
     *   => will add the file located at '/tmp/xlsx/foo/bar/baz.xml' in the archive, but only as 'bar/baz.xml'
     *
     * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree.
     * @param string $localFilePath Path of the file to be added, under the root folder
     * @param string $existingFileMode Controls what to do when trying to add an existing file
     * @param int $compressionMethod The compression method
     * @return void
     */
    protected function addFileToArchiveWithCompressionMethod($rootFolderPath, $localFilePath, $existingFileMode, $compressionMethod)
    {
        $zip = $this->createOrGetZip();

        if (!$this->shouldSkipFile($zip, $localFilePath, $existingFileMode)) {
            $normalizedFullFilePath = $this->getNormalizedRealPath($rootFolderPath . '/' . $localFilePath);
            $zip->addFile($normalizedFullFilePath, $localFilePath);

            if (self::canChooseCompressionMethod()) {
                $zip->setCompressionName($localFilePath, $compressionMethod);
            }
        }
    }

    /**
     * @return bool Whether it is possible to choose the desired compression method to be used
     */
    public static function canChooseCompressionMethod()
    {
        // setCompressionName() is a PHP7+ method...
        return (method_exists(new \ZipArchive(), 'setCompressionName'));
    }

    /**
     * @param string $folderPath Path to the folder to be zipped
     * @param string|void $existingFileMode Controls what to do when trying to add an existing file
     * @return void
     */
    public function addFolderToArchive($folderPath, $existingFileMode = self::EXISTING_FILES_OVERWRITE)
    {
        $zip = $this->createOrGetZip();

        $folderRealPath = $this->getNormalizedRealPath($folderPath) . '/';
        $itemIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);

        foreach ($itemIterator as $itemInfo) {
            $itemRealPath = $this->getNormalizedRealPath($itemInfo->getPathname());
            $itemLocalPath = str_replace($folderRealPath, '', $itemRealPath);

            if ($itemInfo->isFile() && !$this->shouldSkipFile($zip, $itemLocalPath, $existingFileMode)) {
                $zip->addFile($itemRealPath, $itemLocalPath);
            }
        }
    }

    /**
     * @param \ZipArchive $zip
     * @param string $itemLocalPath
     * @param string $existingFileMode
     * @return bool Whether the file should be added to the archive or skipped
     */
    protected function shouldSkipFile($zip, $itemLocalPath, $existingFileMode)
    {
        // Skip files if:
        //   - EXISTING_FILES_SKIP mode chosen
        //   - File already exists in the archive
        return ($existingFileMode === self::EXISTING_FILES_SKIP && $zip->locateName($itemLocalPath) !== false);
    }

    /**
     * Returns canonicalized absolute pathname, containing only forward slashes.
     *
     * @param string $path Path to normalize
     * @return string Normalized and canonicalized path
     */
    protected function getNormalizedRealPath($path)
    {
        $realPath = realpath($path);
        return str_replace(DIRECTORY_SEPARATOR, '/', $realPath);
    }

    /**
     * Closes the archive and copies it into the given stream
     *
     * @param resource $streamPointer Pointer to the stream to copy the zip
     * @return void
     */
    public function closeArchiveAndCopyToStream($streamPointer)
    {
        $zip = $this->createOrGetZip();
        $zip->close();
        unset($this->zip);

        $this->copyZipToStream($streamPointer);
    }

    /**
     * Streams the contents of the zip file into the given stream
     *
     * @param resource $pointer Pointer to the stream to copy the zip
     * @return void
     */
    protected function copyZipToStream($pointer)
    {
        $zipFilePointer = fopen($this->getZipFilePath(), 'r');
        stream_copy_to_stream($zipFilePointer, $pointer);
        fclose($zipFilePointer);
    }
}
Back to Top