Passed
Pull Request — master (#118)
by Daniel
01:57
created

FilesystemPublisher::compressFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 10
1
<?php
2
3
namespace SilverStripe\StaticPublishQueue\Publisher;
4
5
use SilverStripe\Assets\Filesystem;
6
use SilverStripe\Control\HTTPResponse;
7
use function SilverStripe\StaticPublishQueue\PathToURL;
8
use SilverStripe\StaticPublishQueue\Publisher;
9
use SilverStripe\Core\Config\Config;
10
use SilverStripe\Security\SecurityToken;
11
use function SilverStripe\StaticPublishQueue\URLtoPath;
12
13
class FilesystemPublisher extends Publisher
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $destFolder = 'cache';
19
20
    /**
21
     * @var string
22
     */
23
    protected $fileExtension = 'php';
24
25
    /**
26
     * @return string
27
     */
28
    public function getDestPath()
29
    {
30
        $base = defined('PUBLIC_PATH') ? PUBLIC_PATH : BASE_PATH;
31
        return $base . DIRECTORY_SEPARATOR . $this->getDestFolder();
32
    }
33
34
    public function setDestFolder($destFolder)
35
    {
36
        $this->destFolder = $destFolder;
37
        return $this;
38
    }
39
40
    public function getDestFolder()
41
    {
42
        return $this->destFolder;
43
    }
44
45
    public function setFileExtension($fileExtension)
46
    {
47
        $fileExtension = strtolower($fileExtension);
48
        if (!in_array($fileExtension, ['html', 'php'], true)) {
49
            throw new \InvalidArgumentException(
50
                sprintf(
51
                    'Bad file extension "%s" passed to %s::%s',
52
                    $fileExtension,
53
                    static::class,
54
                    __FUNCTION__
55
                )
56
            );
57
        }
58
        $this->fileExtension = $fileExtension;
59
        return $this;
60
    }
61
62
    public function getFileExtension()
63
    {
64
        return $this->fileExtension;
65
    }
66
67
    public function purgeURL($url)
68
    {
69
        if (!$url) {
70
            user_error('Bad url:' . var_export($url, true), E_USER_WARNING);
71
            return;
72
        }
73
        if ($path = $this->URLtoPath($url)) {
74
            $success = $this->deleteFromPath($path . '.html') && $this->deleteFromPath($path . '.php');
75
            return [
76
                'success' => $success,
77
                'url' => $url,
78
                'path' => $this->getDestPath() . DIRECTORY_SEPARATOR . $path,
79
            ];
80
        }
81
        return [
82
            'success' => false,
83
            'url' => $url,
84
            'path' => false,
85
        ];
86
    }
87
88
    public function purgeAll()
89
    {
90
        Filesystem::removeFolder($this->getDestPath());
91
92
        return file_exists($this->getDestPath()) ? false : true;
93
    }
94
95
    /**
96
     * @param string $url
97
     * @param bool $forcePublish
98
     * @return array A result array
99
     */
100
    public function publishURL($url, $forcePublish = false)
101
    {
102
        if (!$url) {
103
            user_error('Bad url:' . var_export($url, true), E_USER_WARNING);
104
            return;
105
        }
106
        $success = false;
107
        $response = $this->generatePageResponse($url);
108
        $statusCode = $response->getStatusCode();
109
        $doPublish = ($forcePublish && $this->getFileExtension() === 'php') || $statusCode < 400;
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: $doPublish = ($forcePubl...' || $statusCode < 400), Probably Intended Meaning: $doPublish = $forcePubli...' || $statusCode < 400)
Loading history...
110
111
        if ($statusCode >= 300 && $statusCode < 400) {
112
            // publish redirect response
113
            $success = $this->publishRedirect($response, $url);
114
        } elseif ($doPublish) {
115
            $success = $this->publishPage($response, $url);
116
        }
117
        return [
118
            'published' => $doPublish,
119
            'success' => $success,
120
            'responsecode' => $statusCode,
121
            'url' => $url,
122
        ];
123
    }
124
125
    /**
126
     * @param HTTPResponse $response
127
     * @param string       $url
128
     * @return bool
129
     */
130
    protected function publishRedirect($response, $url)
131
    {
132
        $success = true;
133
        if ($path = $this->URLtoPath($url)) {
134
            $location = $response->getHeader('Location');
135
            if ($this->getFileExtension() === 'php') {
136
                $phpContent = $this->generatePHPCacheFile($response);
137
                $success = $this->saveToPath($phpContent, $path . '.php');
138
            }
139
            return $this->saveToPath($this->generateHTMLCacheRedirection($location), $path . '.html') && $success;
140
        }
141
        return false;
142
    }
143
144
    /**
145
     * @param HTTPResponse $response
146
     * @param string       $url
147
     * @return bool
148
     */
149
    protected function publishPage($response, $url)
150
    {
151
        $success = true;
152
        if ($path = $this->URLtoPath($url)) {
153
            if ($this->getFileExtension() === 'php') {
154
                $phpContent = $this->generatePHPCacheFile($response);
155
                $success = $this->saveToPath($phpContent, $path . '.php');
156
            }
157
            return $this->saveToPath($response->getBody(), $path . '.html') && $success;
158
        }
159
        return false;
160
    }
161
162
    /**
163
     * returns true on success and false on failure
164
     *
165
     * @param string $content
166
     * @param string $filePath
167
     * @return bool
168
     */
169
    protected function saveToPath($content, $filePath)
170
    {
171
        if (empty($content)) {
172
            return false;
173
        }
174
175
        // Write to a temporary file first
176
        $temporaryPath = tempnam(TEMP_PATH, 'filesystempublisher_');
177
        if (file_put_contents($temporaryPath, $content) === false) {
178
            return false;
179
        }
180
181
        // Move the temporary file to the desired location (prevents unlocked files from being read during write)
182
        $publishPath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
183
        Filesystem::makeFolder(dirname($publishPath));
184
185
        $successWithPublish = rename($temporaryPath, $publishPath);
186
        if ($successWithPublish) {
187
            if (FilesystemPublisher::config()->get('use_gzip_compression')) {
188
                $publishPath = $this->compressFile($publishPath);
189
            }
190
        }
191
        return file_exists($publishPath);
192
    }
193
194
    /**
195
     * Compress the html file and store it gzipped
196
     *
197
     * @param string $publishPath
198
     * @return string The path of the compressed file
199
     */
200
    protected function compressFile($publishPath)
201
    {
202
        $data = file_get_contents($publishPath);
203
        $gzData = gzencode($data, 9);
204
        $gzPublishPath = $publishPath . '.gz';
205
        unlink($gzPublishPath);
206
        file_put_contents($gzPublishPath, $gzData);
207
        return $gzPublishPath;
208
    }
209
210
    protected function deleteFromPath($filePath)
211
    {
212
        $deletePath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
213
        if (file_exists($deletePath)) {
214
            $success = unlink($deletePath);
215
        } else {
216
            $success = true;
217
        }
218
        if (file_exists($deletePath . '.gz')) {
219
            $success = unlink($deletePath . '.gz') && $success;
220
        }
221
222
        return $success;
223
    }
224
225
    protected function URLtoPath($url)
226
    {
227
        return URLtoPath($url, BASE_URL, FilesystemPublisher::config()->get('domain_based_caching'));
228
    }
229
230
    protected function pathToURL($path)
231
    {
232
        return PathToURL($path, $this->getDestPath(), FilesystemPublisher::config()->get('domain_based_caching'));
233
    }
234
235
    public function getPublishedURLs($dir = null, &$result = [])
236
    {
237
        if ($dir === null) {
238
            $dir = $this->getDestPath();
239
        }
240
241
        $root = scandir($dir);
242
        foreach ($root as $fileOrDir) {
243
            if (strpos($fileOrDir, '.') === 0) {
244
                continue;
245
            }
246
            $fullPath = $dir . DIRECTORY_SEPARATOR . $fileOrDir;
247
            // we know html will always be generated, this prevents double ups
248
            if (is_file($fullPath) && pathinfo($fullPath, PATHINFO_EXTENSION) === 'html') {
249
                $result[] = $this->pathToURL($fullPath);
250
                continue;
251
            }
252
253
            if (is_dir($fullPath)) {
254
                $this->getPublishedURLs($fullPath, $result);
255
            }
256
        }
257
        return $result;
258
    }
259
}
260