Passed
Pull Request — master (#121)
by Daniel
02:12
created

FilesystemPublisher::setFileExtension()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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