Passed
Pull Request — master (#118)
by Daniel
02:31
created

FilesystemPublisher::purgeURL()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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